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/ini/trakem2/persistence/TMLHandler.java b/ini/trakem2/persistence/TMLHandler.java
index 86f59ce0..356187a3 100644
--- a/ini/trakem2/persistence/TMLHandler.java
+++ b/ini/trakem2/persistence/TMLHandler.java
@@ -1,984 +1,984 @@
/**
TrakEM2 plugin for ImageJ(C).
Copyright (C) 2005-2009 Albert Cardona and Rodney Douglas.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation (http://www.gnu.org/licenses/gpl.txt )
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
You may contact Albert Cardona at acardona at ini.phys.ethz.ch
Institute of Neuroinformatics, University of Zurich / ETH, Switzerland.
**/
package ini.trakem2.persistence;
import ij.IJ;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Set;
import java.util.HashSet;
import java.io.File;
import java.util.regex.Pattern;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import ini.trakem2.tree.*;
import ini.trakem2.display.*;
import ini.trakem2.utils.*;
import ini.trakem2.Project;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.InputSource;
import org.xml.sax.Attributes;
import mpicbg.models.TransformList;
import mpicbg.trakem2.transform.CoordinateTransform;
import mpicbg.trakem2.transform.CoordinateTransformList;
import mpicbg.trakem2.transform.InvertibleCoordinateTransform;
import mpicbg.trakem2.transform.InvertibleCoordinateTransformList;
/** Creates the project objects from an XML file (TrakEM2 Markup Language Handler). */
public class TMLHandler extends DefaultHandler {
private LayerThing root_lt = null;
private ProjectThing root_pt = null;
private TemplateThing root_tt = null;
private TemplateThing project_tt = null;
private TemplateThing template_layer_thing = null;
private TemplateThing template_layer_set_thing = null;
private Project project = null;
private LayerSet layer_set = null;
private final FSLoader loader;
private boolean skip = false;
private String base_dir;
private String xml_path;
/** Stores the object and its String with coma-separated links, to construct links when all objects exist. */
private HashMap ht_links = new HashMap();
private Thing current_thing = null;
private ArrayList al_open = new ArrayList();
private ArrayList<Layer> al_layers = new ArrayList<Layer>();
private ArrayList<LayerSet> al_layer_sets = new ArrayList<LayerSet>();
private ArrayList<HashMap> al_displays = new ArrayList<HashMap>(); // contains HashMap instances with display data.
/** To accumulate Displayable types for relinking and assigning their proper layer. */
private HashMap ht_displayables = new HashMap();
private HashMap ht_zdispl = new HashMap();
private HashMap ht_oid_pt = new HashMap();
private HashMap ht_pt_expanded = new HashMap();
private Ball last_ball = null;
private AreaList last_area_list = null;
private long last_area_list_layer_id = -1;
private Dissector last_dissector = null;
private Stack last_stack = null;
private Patch last_patch = null;
private Treeline last_treeline = null;
private AreaTree last_areatree = null;
private LinkedList<Taggable> taggables = new LinkedList<Taggable>();
private ReconstructArea reca = null;
private Node last_root_node = null;
private LinkedList<Node> nodes = new LinkedList<Node>();
private Map<Long,List<Node>> node_layer_table = new HashMap<Long,List<Node>>();
private Map<Tree,Node> tree_root_nodes = new HashMap<Tree,Node>();
private StringBuilder last_treeline_data = null;
private Displayable last_displayable = null;
private ArrayList< TransformList< Object > > ct_list_stack = new ArrayList< TransformList< Object > >();
private boolean open_displays = true;
/** @param path The XML file that contains the project data in XML format.
* @param loader The FSLoader for the project.
* Expects the path with '/' as folder separator char.
*/
public TMLHandler(final String path, FSLoader loader) {
this.loader = loader;
this.base_dir = path.substring(0, path.lastIndexOf('/') + 1); // not File.separatorChar: TrakEM2 uses '/' always
this.xml_path = path;
final TemplateThing[] tt = DTDParser.extractTemplate(path);
if (null == tt) {
Utils.log("TMLHandler: can't read DTD in file " + path);
loader = null;
return;
}
/*
// debug:
Utils.log2("ROOTS #####################");
for (int k=0; k < tt.length; k++) {
Utils.log2("tt root " + k + ": " + tt[k]);
}
*/
this.root_tt = tt[0];
// There should only be one root. There may be more than one
// when objects in the DTD are declared but do not exist in a
// TemplateThing hierarchy, such as ict_* and iict_*.
// Find the first proper root:
if (tt.length > 1) {
final Pattern icts = Pattern.compile("^i{1,2}ct_transform.*$");
this.root_tt = null;
for (int k=0; k<tt.length; k++) {
if (icts.matcher(tt[k].getType()).matches()) {
continue;
}
this.root_tt = tt[k];
break;
}
}
// TODO the above should be a better filtering rule in the DTDParser.
// create LayerThing templates
this.template_layer_thing = new TemplateThing("layer");
this.template_layer_set_thing = new TemplateThing("layer set");
this.template_layer_set_thing.addChild(this.template_layer_thing);
this.template_layer_thing.addChild(this.template_layer_set_thing);
// create Project template
this.project_tt = new TemplateThing("project");
project_tt.addChild(this.root_tt);
project_tt.addAttribute("title", "Project");
}
public boolean isUnreadable() {
return null == loader;
}
/** returns 4 objects packed in an array:
<pre>
[0] = root TemplateThing
[1] = root ProjectThing (contains Project instance)
[2] = root LayerThing (contains the top-level LayerSet)
[3] = expanded states of all ProjectThing objects
</pre>
* <br />
* Also, triggers the reconstruction of links and assignment of Displayable objects to their layer.
*/
public Object[] getProjectData(final boolean open_displays) {
if (null == project) return null;
this.open_displays = open_displays;
// 1 - Reconstruct links using ht_links
// Links exist between Displayable objects.
for (Iterator it = ht_displayables.values().iterator(); it.hasNext(); ) {
Displayable d = (Displayable)it.next();
Object olinks = ht_links.get(d);
if (null == olinks) continue; // not linked
String[] links = ((String)olinks).split(",");
Long lid = null;
for (int i=0; i<links.length; i++) {
try {
lid = new Long(links[i]);
} catch (NumberFormatException nfe) {
Utils.log2("Ignoring incorrectly formated link '" + links[i] + "' for ob " + d);
continue;
}
Displayable partner = (Displayable)ht_displayables.get(lid);
if (null != partner) d.link(partner, false);
else Utils.log("TMLHandler: can't find partner with id=" + links[i] + " for Displayable with id=" + d.getId());
}
}
// 1.2 - Reconstruct linked properties
for (final Map.Entry<Displayable,Map<Long,Map<String,String>>> lpe : all_linked_props.entrySet()) {
final Displayable origin = lpe.getKey();
for (final Map.Entry<Long,Map<String,String>> e : lpe.getValue().entrySet()) {
final Displayable target = (Displayable)ht_displayables.get(e.getKey());
if (null == target) {
Utils.log("Setting linked properties for origin " + origin.getId() + ":\n\t* Could not find target displayable #" + e.getKey());
continue;
}
origin.setLinkedProperties(target, e.getValue());
}
}
// 2 - Add Displayable objects to ProjectThing that can contain them
for (Iterator it = ht_oid_pt.entrySet().iterator(); it.hasNext(); ) {
Map.Entry entry = (Map.Entry)it.next();
Long lid = (Long)entry.getKey();
ProjectThing pt = (ProjectThing)entry.getValue();
Object od = ht_displayables.get(lid);
//Utils.log("==== processing: Displayable [" + od + "] vs. ProjectThing [" + pt + "]");
if (null != od) {
ht_displayables.remove(lid);
pt.setObject(od);
} else {
Utils.log("#### Failed to find a Displayable for ProjectThing " + pt + " #####");
}
}
// debug:
/*
for (Iterator it = al_layer_sets.iterator(); it.hasNext(); ) {
LayerSet ls = (LayerSet)it.next();
Utils.log2("ls #id " + ls.getId() + " size: " +ls.getLayers().size());
}
*/
// 3 - Assign a layer pointer to ZDisplayable objects
for (Iterator it = ht_zdispl.values().iterator(); it.hasNext(); ) {
ZDisplayable zd = (ZDisplayable)it.next();
//zd.setLayer((Layer)zd.getLayerSet().getLayers().get(0));
zd.setLayer(zd.getLayerSet().getLayer(0));
}
// 4 - Assign layers to Treeline nodes
for (final Layer la : al_layers) {
final List<Node> list = node_layer_table.remove(la.getId());
if (null == list) continue;
for (final Node nd : list) nd.setLayer(la);
}
if (!node_layer_table.isEmpty()) {
Utils.log("ERROR: node_layer_table is not empty!");
}
// 5 - Assign root nodes to Treelines, now that all nodes have a layer
for (final Map.Entry<Tree,Node> e : tree_root_nodes.entrySet()) {
if (null == e.getValue()) {
//Utils.log2("Ignoring, applies to new Treeline format only.");
continue;
}
e.getKey().setRoot(e.getValue()); // will generate node caches of each Treeline
}
tree_root_nodes.clear();
try {
// Create a table with all layer ids vs layer instances:
final HashMap<Long,Layer> ht_lids = new HashMap<Long,Layer>();
for (final Layer layer : al_layers) {
ht_lids.put(new Long(layer.getId()), layer);
}
// Spawn threads to recreate buckets, starting from the subset of displays to open
int n = Runtime.getRuntime().availableProcessors();
if (n > 1) {
if (n > 4) n -= 2;
else n = 3;
}
final ExecutorService exec = Executors.newFixedThreadPool(n);
final Set<Long> dlids = new HashSet();
final LayerSet layer_set = (LayerSet) root_lt.getObject();
final List<Future> fus = new ArrayList<Future>();
for (final HashMap ht_attributes : al_displays) {
Object ob = ht_attributes.get("layer_id");
if (null == ob) continue;
final Long lid = new Long((String)ob);
dlids.add(lid);
final Layer la = ht_lids.get(lid);
if (null == la) {
ht_lids.remove(lid);
continue;
}
// to open later:
new Display(project, Long.parseLong((String)ht_attributes.get("id")), la, ht_attributes);
fus.add(exec.submit(new Runnable() { public void run() {
la.recreateBuckets();
}}));
}
fus.add(exec.submit(new Runnable() { public void run() {
layer_set.recreateBuckets(false); // only for ZDisplayable
}}));
// Ensure launching:
if (dlids.isEmpty() && layer_set.size() > 0) {
dlids.add(layer_set.getLayer(0).getId());
}
final List<Layer> layers = layer_set.getLayers();
for (final Long lid : new HashSet<Long>(dlids)) {
fus.add(exec.submit(new Runnable() { public void run() {
int start = layers.indexOf(layer_set.getLayer(lid.longValue()));
int next = start + 1;
int prev = start -1;
while (next < layer_set.size() || prev > -1) {
if (prev > -1) {
final Layer lprev = layers.get(prev);
synchronized (dlids) {
if (dlids.add(lprev.getId())) { // returns true if not there already
fus.add(exec.submit(new Runnable() { public void run() {
lprev.recreateBuckets();
}}));
}
}
prev--;
}
if (next < layers.size()) {
final Layer lnext = layers.get(next);
synchronized (dlids) {
if (dlids.add(lnext.getId())) { // returns true if not there already
fus.add(exec.submit(new Runnable() { public void run() {
lnext.recreateBuckets();
}}));
}
}
next++;
}
}
}}));
}
exec.submit(new Runnable() { public void run() {
Utils.wait(fus);
exec.shutdownNow();
}});
} catch (Throwable t) {
IJError.print(t);
}
// debug:
//root_tt.debug("");
//root_pt.debug("");
//root_lt.debug("");
return new Object[]{root_tt, root_pt, root_lt, ht_pt_expanded};
}
private int counter = 0;
public void startElement(String namespace_URI, String local_name, String qualified_name, Attributes attributes) throws SAXException {
if (null == loader) return;
//Utils.log2("startElement: " + qualified_name);
this.counter++;
Utils.showStatus("Loading " + counter, false);
try {
// failsafe:
qualified_name = qualified_name.toLowerCase();
HashMap ht_attributes = new HashMap();
for (int i=attributes.getLength() -1; i>-1; i--) {
ht_attributes.put(attributes.getQName(i).toLowerCase(), attributes.getValue(i));
}
// get the id, which whenever possible it's the id of the encapsulating Thing object. The encapsulated object id is the oid
// The type is specified by the qualified_name
Thing thing = null;
if (0 == qualified_name.indexOf("t2_")) {
if (qualified_name.equals("t2_display")) {
if (open_displays) al_displays.add(ht_attributes); // store for later, until the layers exist
} else {
// a Layer, LayerSet or Displayable object
thing = makeLayerThing(qualified_name, ht_attributes);
if (null != thing) {
if (null == root_lt && thing.getObject() instanceof LayerSet) {
root_lt = (LayerThing)thing;
}
}
}
} else if (qualified_name.equals("project")) {
if (null != this.root_pt) {
Utils.log("WARNING: more than one project definitions.");
return;
}
// Create the project
this.project = new Project(Long.parseLong((String)ht_attributes.remove("id")), (String)ht_attributes.remove("title"));
this.project.setTempLoader(this.loader); // temp, but will be the same anyway
this.project.parseXMLOptions(ht_attributes);
this.project.addToDatabase(); // register id
// Add all unique TemplateThing types to the project
for (Iterator it = root_tt.getUniqueTypes(new HashMap()).values().iterator(); it.hasNext(); ) {
this.project.addUniqueType((TemplateThing)it.next());
}
this.project.addUniqueType(this.project_tt);
this.root_pt = new ProjectThing(this.project_tt, this.project, this.project);
this.root_pt.addAttribute("title", ht_attributes.get("title"));
// Add a project pointer to all template things
this.root_tt.addToDatabase(this.project);
thing = root_pt;
} else if (qualified_name.startsWith("ict_transform")||qualified_name.startsWith("iict_transform")) {
makeCoordinateTransform(qualified_name, ht_attributes);
} else if (!qualified_name.equals("trakem2")) {
// Any abstract object
thing = makeProjectThing(qualified_name, ht_attributes);
}
if (null != thing) {
// get the previously open thing and add this new_thing to it as a child
int size = al_open.size();
if (size > 0) {
Thing parent = (Thing)al_open.get(size -1);
parent.addChild(thing);
//Utils.log2("Adding child " + thing + " to parent " + parent);
}
// add the new thing as open
al_open.add(thing);
}
} catch (Exception e) {
IJError.print(e);
skip = true;
}
}
public void endElement(String namespace_URI, String local_name, String qualified_name) {
if (null == loader) return;
if (skip) {
skip = false; // reset
return;
}
String orig_qualified_name = qualified_name;
//Utils.log2("endElement: " + qualified_name);
// iterate over all open things and find the one that matches the qualified_name, and set it closed (pop it out of the list):
qualified_name = qualified_name.toLowerCase().trim();
if (0 == qualified_name.indexOf("t2_")) {
qualified_name = qualified_name.substring(3);
}
for (int i=al_open.size() -1; i>-1; i--) {
Thing thing = (Thing)al_open.get(i);
if (thing.getType().toLowerCase().equals(qualified_name)) {
al_open.remove(thing);
break;
}
}
// terminate non-single clause objects
if (orig_qualified_name.equals("t2_area_list")) {
last_area_list = null;
last_displayable = null;
} else if (orig_qualified_name.equals("t2_node")) {
// Remove one node from the stack
nodes.removeLast();
taggables.removeLast();
} else if (orig_qualified_name.equals("t2_area")) {
if (null != reca) {
if (null != last_area_list) {
last_area_list.addArea(last_area_list_layer_id, reca.getArea()); // it's local
} else {
((AreaTree.AreaNode)nodes.getLast()).setData(reca.getArea());
}
reca = null;
}
} else if (orig_qualified_name.equals("ict_transform_list")) {
ct_list_stack.remove( ct_list_stack.size() - 1 );
} else if (orig_qualified_name.equals("t2_patch")) {
last_patch = null;
last_displayable = null;
} else if (orig_qualified_name.equals("t2_ball")) {
last_ball = null;
last_displayable = null;
} else if (orig_qualified_name.equals("t2_dissector")) {
last_dissector = null;
last_displayable = null;
} else if (orig_qualified_name.equals( "t2_stack" )) {
last_stack = null;
last_displayable = null;
} else if (orig_qualified_name.equals("t2_treeline")) {
if (null != last_treeline) {
// old format:
if (null == last_root_node && null != last_treeline_data && last_treeline_data.length() > 0) {
last_root_node = parseBranch(Utils.trim(last_treeline_data));
last_treeline_data = null;
}
// new
tree_root_nodes.put(last_treeline, last_root_node);
last_root_node = null;
// always:
last_treeline = null;
nodes.clear();
}
last_displayable = null;
} else if (orig_qualified_name.equals("t2_areatree")) {
if (null != last_areatree) {
tree_root_nodes.put(last_areatree, last_root_node);
last_root_node = null;
last_areatree = null;
}
last_displayable = null;
} else if (in(orig_qualified_name, all_displayables)) {
last_displayable = null;
}
}
static private final String[] all_displayables = new String[]{"t2_area_list", "t2_patch", "t2_pipe", "t2_polyline", "t2_ball", "t2_label", "t2_dissector", "t2_profile", "t2_stack", "t2_treeline"};
private final boolean in(final String s, final String[] all) {
for (int i=all.length-1; i>-1; i--) {
if (s.equals(all[i])) return true;
}
return false;
}
public void characters(char[] c, int start, int length) {
if (null != last_treeline) {
// for old format:
last_treeline_data.append(c, start, length);
}
}
public void fatalError(SAXParseException e) {
Utils.log("Fatal error: column=" + e.getColumnNumber() + " line=" + e.getLineNumber());
}
public void skippedEntity(String name) {
Utils.log("SAX Parser has skipped: " + name);
}
public void notationDeclaration(String name, String publicId, String systemId) {
Utils.log("Notation declaration: " + name + ", " + publicId + ", " + systemId);
}
public void warning(SAXParseException e) {
Utils.log("SAXParseException : " + e);
}
private ProjectThing makeProjectThing(String type, HashMap ht_attributes) {
try {
type = type.toLowerCase();
// debug:
//Utils.log2("TMLHander.makeProjectThing for type=" + type);
long id = -1;
Object sid = ht_attributes.get("id");
if (null != sid) {
id = Long.parseLong((String)sid);
ht_attributes.remove("id");
}
long oid = -1;
Object soid = ht_attributes.get("oid");
if (null != soid) {
oid = Long.parseLong((String)soid);
ht_attributes.remove("oid");
}
Boolean expanded = new Boolean(false); // default: collapsed
Object eob = ht_attributes.get("expanded");
if (null != eob) {
expanded = new Boolean((String)eob);
ht_attributes.remove("expanded");
}
// abstract object, including profile_list
HashMap ht_attr = new HashMap();
for (Iterator it = ht_attributes.entrySet().iterator(); it.hasNext(); ) {
Map.Entry entry = (Map.Entry)it.next();
String key = (String)entry.getKey();
String data = (String)entry.getValue();
ht_attr.put(key, new ProjectAttribute(this.project, -1, key, data));
//Utils.log2("putting key=[" + key + "]=" + data);
}
TemplateThing tt = this.project.getTemplateThing(type);
if (null == tt) {
Utils.log("No template for type " + type);
return null;
}
ProjectThing pt = new ProjectThing(tt, this.project, id, type, null, ht_attr);
pt.addToDatabase();
ht_pt_expanded.put(pt, expanded);
// store the oid vs. pt relationship to fill in the object later.
if (-1 != oid) {
ht_oid_pt.put(new Long(oid), pt);
}
return pt;
} catch (Exception e) {
IJError.print(e);
}
// default:
return null;
}
private void addToLastOpenLayer(Displayable d) {
// find last open layer
for (int i = al_layers.size() -1; i>-1; i--) {
((Layer)al_layers.get(i)).addSilently(d);
break;
}
}
private void addToLastOpenLayerSet(ZDisplayable zd) {
// find last open layer set
for (int i = al_layer_sets.size() -1; i>-1; i--) {
((LayerSet)al_layer_sets.get(i)).addSilently(zd);
break;
}
}
final private Map<Displayable,Map<Long,Map<String,String>>> all_linked_props = new HashMap<Displayable,Map<Long,Map<String,String>>>();
private void putLinkedProperty(final Displayable origin, final HashMap ht_attributes) {
final String stid = (String)ht_attributes.get("target_id");
if (null == stid) {
Utils.log2("Can't setLinkedProperty to null target id for origin Displayable " + origin.getId());
return;
}
Long target_id;
try {
target_id = Long.parseLong(stid);
} catch (NumberFormatException e) {
Utils.log2("Unparseable target_id: " + stid + ", for origin " + origin.getId());
return;
}
String key = (String)ht_attributes.get("key");
String value = (String)ht_attributes.get("value");
if (null == key || null == value) {
Utils.log("Skipping linked property for Displayable " + origin.getId() + ": null key or value");
return;
}
key = key.trim();
value = value.trim();
if (0 == key.length() || 0 == value.length()) {
Utils.log("Skipping linked property for Displayable " + origin.getId() + ": empty key or value");
return;
}
Map<Long,Map<String,String>> linked_props = all_linked_props.get(origin);
if (null == linked_props) {
linked_props = new HashMap<Long,Map<String,String>>();
all_linked_props.put(origin, linked_props);
}
Map<String,String> p = linked_props.get(target_id);
if (null == p) {
p = new HashMap<String,String>();
linked_props.put(target_id, p);
}
p.put(key, value);
}
private LayerThing makeLayerThing(String type, HashMap ht_attributes) {
try {
type = type.toLowerCase();
if (0 == type.indexOf("t2_")) {
type = type.substring(3);
}
long id = -1;
Object sid = ht_attributes.get("id");
if (null != sid) id = Long.parseLong((String)sid);
long oid = -1;
Object soid = ht_attributes.get("oid");
if (null != soid) oid = Long.parseLong((String)soid);
if (type.equals("node")) {
Node node;
Tree last_tree = (null != last_treeline ? last_treeline
: (null != last_areatree ? last_areatree : null));
if (null == last_tree) {
throw new NullPointerException("Can't create a node for null last_treeline or null last_areatree!");
}
node = last_tree.newNode(ht_attributes);
taggables.add(node);
// Put node into the list of nodes with that layer id, to update to proper Layer pointer later
long ndlid = Long.parseLong((String)ht_attributes.get("lid"));
List<Node> list = node_layer_table.get(ndlid);
if (null == list) {
list = new ArrayList<Node>();
node_layer_table.put(ndlid, list);
}
list.add(node);
// Set node as root node or add as child to last node in the stack
if (null == last_root_node) {
last_root_node = node;
} else {
Node last = nodes.getLast();
last.add(node, Byte.parseByte((String)ht_attributes.get("c")));
}
// Put node into stack of nodes (to be removed on closing the tag)
nodes.add(node);
} else if (type.equals("profile")) {
Profile profile = new Profile(this.project, oid, ht_attributes, ht_links);
profile.addToDatabase();
ht_displayables.put(new Long(oid), profile);
addToLastOpenLayer(profile);
last_displayable = profile;
return null;
} else if (type.equals("pipe")) {
Pipe pipe = new Pipe(this.project, oid, ht_attributes, ht_links);
pipe.addToDatabase();
ht_displayables.put(new Long(oid), pipe);
ht_zdispl.put(new Long(oid), pipe);
last_displayable = pipe;
addToLastOpenLayerSet(pipe);
return null;
} else if (type.equals("polyline")) {
Polyline pline = new Polyline(this.project, oid, ht_attributes, ht_links);
pline.addToDatabase();
last_displayable = pline;
ht_displayables.put(new Long(oid), pline);
ht_zdispl.put(new Long(oid), pline);
addToLastOpenLayerSet(pline);
return null;
} else if (type.equals("connector")) {
Connector con = new Connector(this.project, oid, ht_attributes, ht_links);
con.addToDatabase();
last_displayable = con;
ht_displayables.put(new Long(oid), con);
ht_zdispl.put(new Long(oid), con);
addToLastOpenLayerSet(con);
return null;
} else if (type.equals("path")) {
if (null != reca) {
reca.add((String)ht_attributes.get("d"));
return null;
}
return null;
} else if (type.equals("area")) {
reca = new ReconstructArea();
if (null != last_area_list) {
last_area_list_layer_id = Long.parseLong((String)ht_attributes.get("layer_id"));
}
return null;
} else if (type.equals("area_list")) {
AreaList area = new AreaList(this.project, oid, ht_attributes, ht_links);
area.addToDatabase(); // why? This looks like an onion
last_area_list = area;
last_displayable = area;
ht_displayables.put(new Long(oid), area);
ht_zdispl.put(new Long(oid), area);
addToLastOpenLayerSet(area);
return null;
} else if (type.equals("tag")) {
Taggable t = taggables.getLast();
if (null != t) {
Object ob = ht_attributes.get("key");
int keyCode = KeyEvent.VK_T; // defaults to 't'
- if (null != ob) keyCode = (int)((String)ob).charAt(0);
+ if (null != ob) keyCode = (int)((String)ob).toUpperCase().charAt(0); // KeyEvent.VK_U is char U, not u
Tag tag = new Tag(ht_attributes.get("name"), keyCode);
al_layer_sets.get(al_layer_sets.size()-1).putTag(tag, keyCode);
t.addTag(tag);
}
} else if (type.equals("ball_ob")) {
// add a ball to the last open Ball
if (null != last_ball) {
last_ball.addBall(Double.parseDouble((String)ht_attributes.get("x")),
Double.parseDouble((String)ht_attributes.get("y")),
Double.parseDouble((String)ht_attributes.get("r")),
Long.parseLong((String)ht_attributes.get("layer_id")));
}
return null;
} else if (type.equals("ball")) {
Ball ball = new Ball(this.project, oid, ht_attributes, ht_links);
ball.addToDatabase();
last_ball = ball;
last_displayable = ball;
ht_displayables.put(new Long(oid), ball);
ht_zdispl.put(new Long(oid), ball);
addToLastOpenLayerSet(ball);
return null;
} else if (type.equals("stack")) {
Stack stack = new Stack(this.project, oid, ht_attributes, ht_links);
stack.addToDatabase();
last_stack = stack;
last_displayable = stack;
ht_displayables.put(new Long(oid), stack);
ht_zdispl.put( new Long(oid), stack );
addToLastOpenLayerSet( stack );
} else if (type.equals("treeline")) {
Treeline tline = new Treeline(this.project, oid, ht_attributes, ht_links);
tline.addToDatabase();
last_treeline = tline;
last_treeline_data = new StringBuilder();
last_displayable = tline;
ht_displayables.put(oid, tline);
ht_zdispl.put(oid, tline);
addToLastOpenLayerSet(tline);
} else if (type.equals("areatree")) {
AreaTree art = new AreaTree(this.project, oid, ht_attributes, ht_links);
art.addToDatabase();
last_areatree = art;
last_displayable = art;
ht_displayables.put(oid, art);
ht_zdispl.put(oid, art);
addToLastOpenLayerSet(art);
} else if (type.equals("dd_item")) {
if (null != last_dissector) {
last_dissector.addItem(Integer.parseInt((String)ht_attributes.get("tag")),
Integer.parseInt((String)ht_attributes.get("radius")),
(String)ht_attributes.get("points"));
}
} else if (type.equals("label")) {
DLabel label = new DLabel(project, oid, ht_attributes, ht_links);
label.addToDatabase();
ht_displayables.put(new Long(oid), label);
addToLastOpenLayer(label);
last_displayable = label;
return null;
} else if (type.equals("patch")) {
Patch patch = new Patch(project, oid, ht_attributes, ht_links);
patch.addToDatabase();
ht_displayables.put(new Long(oid), patch);
addToLastOpenLayer(patch);
last_patch = patch;
last_displayable = patch;
return null;
} else if (type.equals("dissector")) {
Dissector dissector = new Dissector(this.project, oid, ht_attributes, ht_links);
dissector.addToDatabase();
last_dissector = dissector;
last_displayable = dissector;
ht_displayables.put(new Long(oid), dissector);
ht_zdispl.put(new Long(oid), dissector);
addToLastOpenLayerSet(dissector);
} else if (type.equals("layer")) {
// find last open LayerSet, if any
for (int i = al_layer_sets.size() -1; i>-1; i--) {
LayerSet set = (LayerSet)al_layer_sets.get(i);
Layer layer = new Layer(project, oid, ht_attributes);
layer.addToDatabase();
set.addSilently(layer);
al_layers.add(layer);
Object ot = ht_attributes.get("title");
return new LayerThing(template_layer_thing, project, -1, (null == ot ? null : (String)ot), layer, null, null);
}
} else if (type.equals("layer_set")) {
LayerSet set = new LayerSet(project, oid, ht_attributes, ht_links);
last_displayable = set;
set.addToDatabase();
ht_displayables.put(new Long(oid), set);
al_layer_sets.add(set);
addToLastOpenLayer(set);
Object ot = ht_attributes.get("title");
return new LayerThing(template_layer_set_thing, project, -1, (null == ot ? null : (String)ot), set, null, null);
} else if (type.equals("calibration")) {
// find last open LayerSet if any
for (int i = al_layer_sets.size() -1; i>-1; i--) {
LayerSet set = (LayerSet)al_layer_sets.get(i);
set.restoreCalibration(ht_attributes);
return null;
}
} else if (type.equals("prop")) {
// Add property to last created Displayable
if (null != last_displayable) {
last_displayable.setProperty((String)ht_attributes.get("key"), (String)ht_attributes.get("value"));
}
} else if (type.equals("linked_prop")) {
// Add linked property to last created Displayable. Has to wait until the Displayable ids have been resolved to instances.
if (null != last_displayable) {
putLinkedProperty(last_displayable, ht_attributes);
}
} else {
Utils.log2("TMLHandler Unknown type: " + type);
}
} catch (Exception e) {
IJError.print(e);
}
// default:
return null;
}
final private void makeCoordinateTransform( String type, final HashMap ht_attributes )
{
try
{
type = type.toLowerCase();
if ( type.equals( "ict_transform" ) )
{
final CoordinateTransform ct = ( CoordinateTransform )Class.forName( ( String )ht_attributes.get( "class" ) ).newInstance();
ct.init( ( String )ht_attributes.get( "data" ) );
if ( ct_list_stack.isEmpty() )
{
if ( last_patch != null )
last_patch.setCoordinateTransformSilently( ct );
}
else
{
ct_list_stack.get( ct_list_stack.size() - 1 ).add( ct );
}
}
else if ( type.equals( "iict_transform" ) )
{
final InvertibleCoordinateTransform ict = ( InvertibleCoordinateTransform )Class.forName( ( String )ht_attributes.get( "class" ) ).newInstance();
ict.init( ( String )ht_attributes.get( "data" ) );
if ( ct_list_stack.isEmpty() )
{
if ( last_patch != null )
last_patch.setCoordinateTransformSilently( ict );
else if ( last_stack != null )
last_stack.setInvertibleCoordinateTransformSilently( ict );
}
else
{
ct_list_stack.get( ct_list_stack.size() - 1 ).add( ict );
}
}
else if ( type.equals( "ict_transform_list" ) )
{
final CoordinateTransformList< CoordinateTransform > ctl = new CoordinateTransformList< CoordinateTransform >();
if ( ct_list_stack.isEmpty() )
{
if ( last_patch != null )
last_patch.setCoordinateTransformSilently( ctl );
}
else
ct_list_stack.get( ct_list_stack.size() - 1 ).add( ctl );
ct_list_stack.add( ( TransformList )ctl );
}
else if ( type.equals( "iict_transform_list" ) )
{
final InvertibleCoordinateTransformList< InvertibleCoordinateTransform > ictl = new InvertibleCoordinateTransformList< InvertibleCoordinateTransform >();
if ( ct_list_stack.isEmpty() )
{
if ( last_patch != null )
last_patch.setCoordinateTransformSilently( ictl );
else if ( last_stack != null )
last_stack.setInvertibleCoordinateTransformSilently( ictl );
}
else
ct_list_stack.get( ct_list_stack.size() - 1 ).add( ictl );
ct_list_stack.add( ( TransformList )ictl );
}
}
catch ( Exception e ) { IJError.print(e); }
}
private final Node parseBranch(String s) {
// 1 - Parse the slab
final int first = s.indexOf('(');
final int last = s.indexOf(')', first+1);
final String[] coords = s.substring(first+1, last).split(" ");
Node prev = null;
final List<Node> nodes = new ArrayList<Node>();
for (int i=0; i<coords.length; i+=3) {
long lid = Long.parseLong(coords[i+2]);
Node nd = new Treeline.RadiusNode(Float.parseFloat(coords[i]), Float.parseFloat(coords[i+1]), null);
nd.setData(0f);
nodes.add(nd);
// Add to node_layer_table for later assignment of a Layer object to the node
List<Node> list = node_layer_table.get(lid);
if (null == list) {
list = new ArrayList<Node>();
node_layer_table.put(lid, list);
}
list.add(nd);
//
if (null == prev) prev = nd;
else {
prev.add(nd, Node.MAX_EDGE_CONFIDENCE);
prev = nd; // new parent
}
}
// 2 - Parse the branches
final int ibranches = s.indexOf(":branches", last+1);
if (-1 != ibranches) {
final int len = s.length();
int open = s.indexOf('{', ibranches + 9);
while (-1 != open) {
int end = open + 1; // don't read the first curly bracket
int level = 1;
for(; end < len; end++) {
switch (s.charAt(end)) {
case '{': level++; break;
case '}': level--; break;
}
if (0 == level) break;
}
// Add the root node of the new branch to the node at branch index
int openbranch = s.indexOf('{', open+1);
int branchindex = Integer.parseInt(s.substring(open+1, openbranch-1));
nodes.get(branchindex).add(parseBranch(s.substring(open, end)),
Node.MAX_EDGE_CONFIDENCE);
open = s.indexOf('{', end+1);
}
}
return nodes.get(0);
}
}
| true | true | private LayerThing makeLayerThing(String type, HashMap ht_attributes) {
try {
type = type.toLowerCase();
if (0 == type.indexOf("t2_")) {
type = type.substring(3);
}
long id = -1;
Object sid = ht_attributes.get("id");
if (null != sid) id = Long.parseLong((String)sid);
long oid = -1;
Object soid = ht_attributes.get("oid");
if (null != soid) oid = Long.parseLong((String)soid);
if (type.equals("node")) {
Node node;
Tree last_tree = (null != last_treeline ? last_treeline
: (null != last_areatree ? last_areatree : null));
if (null == last_tree) {
throw new NullPointerException("Can't create a node for null last_treeline or null last_areatree!");
}
node = last_tree.newNode(ht_attributes);
taggables.add(node);
// Put node into the list of nodes with that layer id, to update to proper Layer pointer later
long ndlid = Long.parseLong((String)ht_attributes.get("lid"));
List<Node> list = node_layer_table.get(ndlid);
if (null == list) {
list = new ArrayList<Node>();
node_layer_table.put(ndlid, list);
}
list.add(node);
// Set node as root node or add as child to last node in the stack
if (null == last_root_node) {
last_root_node = node;
} else {
Node last = nodes.getLast();
last.add(node, Byte.parseByte((String)ht_attributes.get("c")));
}
// Put node into stack of nodes (to be removed on closing the tag)
nodes.add(node);
} else if (type.equals("profile")) {
Profile profile = new Profile(this.project, oid, ht_attributes, ht_links);
profile.addToDatabase();
ht_displayables.put(new Long(oid), profile);
addToLastOpenLayer(profile);
last_displayable = profile;
return null;
} else if (type.equals("pipe")) {
Pipe pipe = new Pipe(this.project, oid, ht_attributes, ht_links);
pipe.addToDatabase();
ht_displayables.put(new Long(oid), pipe);
ht_zdispl.put(new Long(oid), pipe);
last_displayable = pipe;
addToLastOpenLayerSet(pipe);
return null;
} else if (type.equals("polyline")) {
Polyline pline = new Polyline(this.project, oid, ht_attributes, ht_links);
pline.addToDatabase();
last_displayable = pline;
ht_displayables.put(new Long(oid), pline);
ht_zdispl.put(new Long(oid), pline);
addToLastOpenLayerSet(pline);
return null;
} else if (type.equals("connector")) {
Connector con = new Connector(this.project, oid, ht_attributes, ht_links);
con.addToDatabase();
last_displayable = con;
ht_displayables.put(new Long(oid), con);
ht_zdispl.put(new Long(oid), con);
addToLastOpenLayerSet(con);
return null;
} else if (type.equals("path")) {
if (null != reca) {
reca.add((String)ht_attributes.get("d"));
return null;
}
return null;
} else if (type.equals("area")) {
reca = new ReconstructArea();
if (null != last_area_list) {
last_area_list_layer_id = Long.parseLong((String)ht_attributes.get("layer_id"));
}
return null;
} else if (type.equals("area_list")) {
AreaList area = new AreaList(this.project, oid, ht_attributes, ht_links);
area.addToDatabase(); // why? This looks like an onion
last_area_list = area;
last_displayable = area;
ht_displayables.put(new Long(oid), area);
ht_zdispl.put(new Long(oid), area);
addToLastOpenLayerSet(area);
return null;
} else if (type.equals("tag")) {
Taggable t = taggables.getLast();
if (null != t) {
Object ob = ht_attributes.get("key");
int keyCode = KeyEvent.VK_T; // defaults to 't'
if (null != ob) keyCode = (int)((String)ob).charAt(0);
Tag tag = new Tag(ht_attributes.get("name"), keyCode);
al_layer_sets.get(al_layer_sets.size()-1).putTag(tag, keyCode);
t.addTag(tag);
}
} else if (type.equals("ball_ob")) {
// add a ball to the last open Ball
if (null != last_ball) {
last_ball.addBall(Double.parseDouble((String)ht_attributes.get("x")),
Double.parseDouble((String)ht_attributes.get("y")),
Double.parseDouble((String)ht_attributes.get("r")),
Long.parseLong((String)ht_attributes.get("layer_id")));
}
return null;
} else if (type.equals("ball")) {
Ball ball = new Ball(this.project, oid, ht_attributes, ht_links);
ball.addToDatabase();
last_ball = ball;
last_displayable = ball;
ht_displayables.put(new Long(oid), ball);
ht_zdispl.put(new Long(oid), ball);
addToLastOpenLayerSet(ball);
return null;
} else if (type.equals("stack")) {
Stack stack = new Stack(this.project, oid, ht_attributes, ht_links);
stack.addToDatabase();
last_stack = stack;
last_displayable = stack;
ht_displayables.put(new Long(oid), stack);
ht_zdispl.put( new Long(oid), stack );
addToLastOpenLayerSet( stack );
} else if (type.equals("treeline")) {
Treeline tline = new Treeline(this.project, oid, ht_attributes, ht_links);
tline.addToDatabase();
last_treeline = tline;
last_treeline_data = new StringBuilder();
last_displayable = tline;
ht_displayables.put(oid, tline);
ht_zdispl.put(oid, tline);
addToLastOpenLayerSet(tline);
} else if (type.equals("areatree")) {
AreaTree art = new AreaTree(this.project, oid, ht_attributes, ht_links);
art.addToDatabase();
last_areatree = art;
last_displayable = art;
ht_displayables.put(oid, art);
ht_zdispl.put(oid, art);
addToLastOpenLayerSet(art);
} else if (type.equals("dd_item")) {
if (null != last_dissector) {
last_dissector.addItem(Integer.parseInt((String)ht_attributes.get("tag")),
Integer.parseInt((String)ht_attributes.get("radius")),
(String)ht_attributes.get("points"));
}
} else if (type.equals("label")) {
DLabel label = new DLabel(project, oid, ht_attributes, ht_links);
label.addToDatabase();
ht_displayables.put(new Long(oid), label);
addToLastOpenLayer(label);
last_displayable = label;
return null;
} else if (type.equals("patch")) {
Patch patch = new Patch(project, oid, ht_attributes, ht_links);
patch.addToDatabase();
ht_displayables.put(new Long(oid), patch);
addToLastOpenLayer(patch);
last_patch = patch;
last_displayable = patch;
return null;
} else if (type.equals("dissector")) {
Dissector dissector = new Dissector(this.project, oid, ht_attributes, ht_links);
dissector.addToDatabase();
last_dissector = dissector;
last_displayable = dissector;
ht_displayables.put(new Long(oid), dissector);
ht_zdispl.put(new Long(oid), dissector);
addToLastOpenLayerSet(dissector);
} else if (type.equals("layer")) {
// find last open LayerSet, if any
for (int i = al_layer_sets.size() -1; i>-1; i--) {
LayerSet set = (LayerSet)al_layer_sets.get(i);
Layer layer = new Layer(project, oid, ht_attributes);
layer.addToDatabase();
set.addSilently(layer);
al_layers.add(layer);
Object ot = ht_attributes.get("title");
return new LayerThing(template_layer_thing, project, -1, (null == ot ? null : (String)ot), layer, null, null);
}
} else if (type.equals("layer_set")) {
LayerSet set = new LayerSet(project, oid, ht_attributes, ht_links);
last_displayable = set;
set.addToDatabase();
ht_displayables.put(new Long(oid), set);
al_layer_sets.add(set);
addToLastOpenLayer(set);
Object ot = ht_attributes.get("title");
return new LayerThing(template_layer_set_thing, project, -1, (null == ot ? null : (String)ot), set, null, null);
} else if (type.equals("calibration")) {
// find last open LayerSet if any
for (int i = al_layer_sets.size() -1; i>-1; i--) {
LayerSet set = (LayerSet)al_layer_sets.get(i);
set.restoreCalibration(ht_attributes);
return null;
}
} else if (type.equals("prop")) {
// Add property to last created Displayable
if (null != last_displayable) {
last_displayable.setProperty((String)ht_attributes.get("key"), (String)ht_attributes.get("value"));
}
} else if (type.equals("linked_prop")) {
// Add linked property to last created Displayable. Has to wait until the Displayable ids have been resolved to instances.
if (null != last_displayable) {
putLinkedProperty(last_displayable, ht_attributes);
}
} else {
Utils.log2("TMLHandler Unknown type: " + type);
}
} catch (Exception e) {
IJError.print(e);
}
// default:
return null;
}
| private LayerThing makeLayerThing(String type, HashMap ht_attributes) {
try {
type = type.toLowerCase();
if (0 == type.indexOf("t2_")) {
type = type.substring(3);
}
long id = -1;
Object sid = ht_attributes.get("id");
if (null != sid) id = Long.parseLong((String)sid);
long oid = -1;
Object soid = ht_attributes.get("oid");
if (null != soid) oid = Long.parseLong((String)soid);
if (type.equals("node")) {
Node node;
Tree last_tree = (null != last_treeline ? last_treeline
: (null != last_areatree ? last_areatree : null));
if (null == last_tree) {
throw new NullPointerException("Can't create a node for null last_treeline or null last_areatree!");
}
node = last_tree.newNode(ht_attributes);
taggables.add(node);
// Put node into the list of nodes with that layer id, to update to proper Layer pointer later
long ndlid = Long.parseLong((String)ht_attributes.get("lid"));
List<Node> list = node_layer_table.get(ndlid);
if (null == list) {
list = new ArrayList<Node>();
node_layer_table.put(ndlid, list);
}
list.add(node);
// Set node as root node or add as child to last node in the stack
if (null == last_root_node) {
last_root_node = node;
} else {
Node last = nodes.getLast();
last.add(node, Byte.parseByte((String)ht_attributes.get("c")));
}
// Put node into stack of nodes (to be removed on closing the tag)
nodes.add(node);
} else if (type.equals("profile")) {
Profile profile = new Profile(this.project, oid, ht_attributes, ht_links);
profile.addToDatabase();
ht_displayables.put(new Long(oid), profile);
addToLastOpenLayer(profile);
last_displayable = profile;
return null;
} else if (type.equals("pipe")) {
Pipe pipe = new Pipe(this.project, oid, ht_attributes, ht_links);
pipe.addToDatabase();
ht_displayables.put(new Long(oid), pipe);
ht_zdispl.put(new Long(oid), pipe);
last_displayable = pipe;
addToLastOpenLayerSet(pipe);
return null;
} else if (type.equals("polyline")) {
Polyline pline = new Polyline(this.project, oid, ht_attributes, ht_links);
pline.addToDatabase();
last_displayable = pline;
ht_displayables.put(new Long(oid), pline);
ht_zdispl.put(new Long(oid), pline);
addToLastOpenLayerSet(pline);
return null;
} else if (type.equals("connector")) {
Connector con = new Connector(this.project, oid, ht_attributes, ht_links);
con.addToDatabase();
last_displayable = con;
ht_displayables.put(new Long(oid), con);
ht_zdispl.put(new Long(oid), con);
addToLastOpenLayerSet(con);
return null;
} else if (type.equals("path")) {
if (null != reca) {
reca.add((String)ht_attributes.get("d"));
return null;
}
return null;
} else if (type.equals("area")) {
reca = new ReconstructArea();
if (null != last_area_list) {
last_area_list_layer_id = Long.parseLong((String)ht_attributes.get("layer_id"));
}
return null;
} else if (type.equals("area_list")) {
AreaList area = new AreaList(this.project, oid, ht_attributes, ht_links);
area.addToDatabase(); // why? This looks like an onion
last_area_list = area;
last_displayable = area;
ht_displayables.put(new Long(oid), area);
ht_zdispl.put(new Long(oid), area);
addToLastOpenLayerSet(area);
return null;
} else if (type.equals("tag")) {
Taggable t = taggables.getLast();
if (null != t) {
Object ob = ht_attributes.get("key");
int keyCode = KeyEvent.VK_T; // defaults to 't'
if (null != ob) keyCode = (int)((String)ob).toUpperCase().charAt(0); // KeyEvent.VK_U is char U, not u
Tag tag = new Tag(ht_attributes.get("name"), keyCode);
al_layer_sets.get(al_layer_sets.size()-1).putTag(tag, keyCode);
t.addTag(tag);
}
} else if (type.equals("ball_ob")) {
// add a ball to the last open Ball
if (null != last_ball) {
last_ball.addBall(Double.parseDouble((String)ht_attributes.get("x")),
Double.parseDouble((String)ht_attributes.get("y")),
Double.parseDouble((String)ht_attributes.get("r")),
Long.parseLong((String)ht_attributes.get("layer_id")));
}
return null;
} else if (type.equals("ball")) {
Ball ball = new Ball(this.project, oid, ht_attributes, ht_links);
ball.addToDatabase();
last_ball = ball;
last_displayable = ball;
ht_displayables.put(new Long(oid), ball);
ht_zdispl.put(new Long(oid), ball);
addToLastOpenLayerSet(ball);
return null;
} else if (type.equals("stack")) {
Stack stack = new Stack(this.project, oid, ht_attributes, ht_links);
stack.addToDatabase();
last_stack = stack;
last_displayable = stack;
ht_displayables.put(new Long(oid), stack);
ht_zdispl.put( new Long(oid), stack );
addToLastOpenLayerSet( stack );
} else if (type.equals("treeline")) {
Treeline tline = new Treeline(this.project, oid, ht_attributes, ht_links);
tline.addToDatabase();
last_treeline = tline;
last_treeline_data = new StringBuilder();
last_displayable = tline;
ht_displayables.put(oid, tline);
ht_zdispl.put(oid, tline);
addToLastOpenLayerSet(tline);
} else if (type.equals("areatree")) {
AreaTree art = new AreaTree(this.project, oid, ht_attributes, ht_links);
art.addToDatabase();
last_areatree = art;
last_displayable = art;
ht_displayables.put(oid, art);
ht_zdispl.put(oid, art);
addToLastOpenLayerSet(art);
} else if (type.equals("dd_item")) {
if (null != last_dissector) {
last_dissector.addItem(Integer.parseInt((String)ht_attributes.get("tag")),
Integer.parseInt((String)ht_attributes.get("radius")),
(String)ht_attributes.get("points"));
}
} else if (type.equals("label")) {
DLabel label = new DLabel(project, oid, ht_attributes, ht_links);
label.addToDatabase();
ht_displayables.put(new Long(oid), label);
addToLastOpenLayer(label);
last_displayable = label;
return null;
} else if (type.equals("patch")) {
Patch patch = new Patch(project, oid, ht_attributes, ht_links);
patch.addToDatabase();
ht_displayables.put(new Long(oid), patch);
addToLastOpenLayer(patch);
last_patch = patch;
last_displayable = patch;
return null;
} else if (type.equals("dissector")) {
Dissector dissector = new Dissector(this.project, oid, ht_attributes, ht_links);
dissector.addToDatabase();
last_dissector = dissector;
last_displayable = dissector;
ht_displayables.put(new Long(oid), dissector);
ht_zdispl.put(new Long(oid), dissector);
addToLastOpenLayerSet(dissector);
} else if (type.equals("layer")) {
// find last open LayerSet, if any
for (int i = al_layer_sets.size() -1; i>-1; i--) {
LayerSet set = (LayerSet)al_layer_sets.get(i);
Layer layer = new Layer(project, oid, ht_attributes);
layer.addToDatabase();
set.addSilently(layer);
al_layers.add(layer);
Object ot = ht_attributes.get("title");
return new LayerThing(template_layer_thing, project, -1, (null == ot ? null : (String)ot), layer, null, null);
}
} else if (type.equals("layer_set")) {
LayerSet set = new LayerSet(project, oid, ht_attributes, ht_links);
last_displayable = set;
set.addToDatabase();
ht_displayables.put(new Long(oid), set);
al_layer_sets.add(set);
addToLastOpenLayer(set);
Object ot = ht_attributes.get("title");
return new LayerThing(template_layer_set_thing, project, -1, (null == ot ? null : (String)ot), set, null, null);
} else if (type.equals("calibration")) {
// find last open LayerSet if any
for (int i = al_layer_sets.size() -1; i>-1; i--) {
LayerSet set = (LayerSet)al_layer_sets.get(i);
set.restoreCalibration(ht_attributes);
return null;
}
} else if (type.equals("prop")) {
// Add property to last created Displayable
if (null != last_displayable) {
last_displayable.setProperty((String)ht_attributes.get("key"), (String)ht_attributes.get("value"));
}
} else if (type.equals("linked_prop")) {
// Add linked property to last created Displayable. Has to wait until the Displayable ids have been resolved to instances.
if (null != last_displayable) {
putLinkedProperty(last_displayable, ht_attributes);
}
} else {
Utils.log2("TMLHandler Unknown type: " + type);
}
} catch (Exception e) {
IJError.print(e);
}
// default:
return null;
}
|
diff --git a/platform/com.netifera.platform.ui/com.netifera.platform.ui.probe/src/com/netifera/platform/ui/probe/wizard/TCPListenChannelConfigPage.java b/platform/com.netifera.platform.ui/com.netifera.platform.ui.probe/src/com/netifera/platform/ui/probe/wizard/TCPListenChannelConfigPage.java
index b2d79e0f..d3cff2bc 100644
--- a/platform/com.netifera.platform.ui/com.netifera.platform.ui.probe/src/com/netifera/platform/ui/probe/wizard/TCPListenChannelConfigPage.java
+++ b/platform/com.netifera.platform.ui/com.netifera.platform.ui.probe/src/com/netifera/platform/ui/probe/wizard/TCPListenChannelConfigPage.java
@@ -1,118 +1,118 @@
package com.netifera.platform.ui.probe.wizard;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import com.netifera.platform.util.patternmatching.InternetAddressMatcher;
public class TCPListenChannelConfigPage extends WizardPage {
private Text addressText;
private Text portText;
public TCPListenChannelConfigPage() {
super("tcpListenConfig");
setTitle("TCP Listen Channel");
setDescription("Configure the connection information for the new Probe.");
setPageComplete(false);
}
public String getConfigString() {
return "tcplisten:" + addressText.getText() + ":"+ portText.getText();
}
public void createControl(Composite parent) {
Composite container = createComposite(parent);
ModifyListener listener = new ModifyListener() {
public void modifyText(ModifyEvent e) {
verifyFields();
}
};
addressText = createAddressField(container);
addressText.addModifyListener(listener);
portText = createPortField(container);
portText.addModifyListener(listener);
}
private void verifyFields() {
- if (addressText.getText().isEmpty()) {
+ if (addressText.getText().length() == 0) {
setErrorMessage("Enter an IP address.");
setPageComplete(false);
return;
}
if (!addressValid(addressText.getText())) {
setErrorMessage("Invalid IP address.");
setPageComplete(false);
return;
}
- if (portText.getText().isEmpty()) {
+ if (portText.getText().length() == 0) {
setErrorMessage("Enter a port number.");
setPageComplete(false);
return;
}
if (!portValid(portText.getText())) {
setErrorMessage("Invalid port.");
setPageComplete(false);
return;
}
setErrorMessage(null);
setPageComplete(true);
}
private boolean addressValid(String address) {
return InternetAddressMatcher.matches(address);
}
private boolean portValid(String portString) {
try {
final int port = Integer.parseInt(portString);
return port > 0 && port <= 65535;
} catch(NumberFormatException e) {
return false;
}
}
private Composite createComposite(Composite parent) {
final Composite c = new Composite(parent, SWT.NONE);
final GridLayout gridLayout = new GridLayout();
gridLayout.numColumns = 2;
c.setLayout(gridLayout);
setControl(c);
return c;
}
private Text createAddressField(Composite container) {
createLabel(container, "Probe IP Address:");
return createText(container, 16, "IP address for connecting to this probe TCP Listen channel.");
}
private Text createPortField(Composite container) {
createLabel(container, "Probe Listen Port:");
return createText(container,5, "Port where the Probe is listening");
}
private void createLabel(Composite container, String text) {
final Label label = new Label(container, SWT.NONE);
final GridData gd = new GridData(SWT.END, SWT.CENTER, false, false);
label.setLayoutData(gd);
label.setText(text);
}
private Text createText(Composite container, int limit, String tooltip) {
final Text text = new Text(container, SWT.BORDER);
final GridData gd = new GridData(SWT.FILL, SWT.CENTER, true, false);
gd.widthHint = 100;
text.setLayoutData(gd);
text.setTextLimit(limit);
text.setToolTipText(tooltip);
text.pack();
return text;
}
}
| false | true | private void verifyFields() {
if (addressText.getText().isEmpty()) {
setErrorMessage("Enter an IP address.");
setPageComplete(false);
return;
}
if (!addressValid(addressText.getText())) {
setErrorMessage("Invalid IP address.");
setPageComplete(false);
return;
}
if (portText.getText().isEmpty()) {
setErrorMessage("Enter a port number.");
setPageComplete(false);
return;
}
if (!portValid(portText.getText())) {
setErrorMessage("Invalid port.");
setPageComplete(false);
return;
}
setErrorMessage(null);
setPageComplete(true);
}
| private void verifyFields() {
if (addressText.getText().length() == 0) {
setErrorMessage("Enter an IP address.");
setPageComplete(false);
return;
}
if (!addressValid(addressText.getText())) {
setErrorMessage("Invalid IP address.");
setPageComplete(false);
return;
}
if (portText.getText().length() == 0) {
setErrorMessage("Enter a port number.");
setPageComplete(false);
return;
}
if (!portValid(portText.getText())) {
setErrorMessage("Invalid port.");
setPageComplete(false);
return;
}
setErrorMessage(null);
setPageComplete(true);
}
|
diff --git a/Homework1/src/de/uniluebeck/itm/kma/xuggler/FileAnalyzer.java b/Homework1/src/de/uniluebeck/itm/kma/xuggler/FileAnalyzer.java
index ee5b987..9f6c401 100644
--- a/Homework1/src/de/uniluebeck/itm/kma/xuggler/FileAnalyzer.java
+++ b/Homework1/src/de/uniluebeck/itm/kma/xuggler/FileAnalyzer.java
@@ -1,237 +1,237 @@
package de.uniluebeck.itm.kma.xuggler;
import com.xuggle.xuggler.Global;
import com.xuggle.xuggler.ICodec;
import javax.swing.JTextPane;
import com.xuggle.xuggler.IContainer;
import com.xuggle.xuggler.IPacket;
import com.xuggle.xuggler.IStream;
import com.xuggle.xuggler.IStreamCoder;
import de.uniluebeck.itm.kma.LoggingHelper;
/**
* Analyzer for multimedia files. Outputs information to
* a predefined JTextPane as plain text.
*
* @author seidel
*/
public class FileAnalyzer
{
/** JTextPane object for analyzer output */
private JTextPane logPane;
/**
* Constructor sets logPane member.
*
* @param logPane JTextPane object
*/
public FileAnalyzer(JTextPane logPane)
{
this.logPane = logPane;
this.log("Welcome to Media Converter. Please select input file.");
this.log("");
this.log("Your JVM is running on " + System.getProperty("sun.arch.data.model") + " bit.");
this.log("");
}
/**
* Setter for logPane member.
*
* @param logPane JTextPane object
*/
public void setLogPane(JTextPane logPane)
{
this.logPane = logPane;
}
/**
* Getter for logPane member.
*
* @return JTextPane object
*/
public JTextPane getLogPane()
{
return this.logPane;
}
/**
* Helper method for logging, provided for convenience.
*
* @param textToAppend Text to append to log pane
*/
private void log(String textToAppend)
{
LoggingHelper.appendAndScroll(this.logPane, textToAppend);
}
/**
* This method analyzes a multimedia file and outputs
* information about it on the log pane which was set
* in the constructor.
*
* @param fileName File name
*/
public void analyzeMediafile(String fileName)
{
this.log("============================================================");
this.log("");
this.log("Analyzing metadata from file: \t'" + fileName + "'");
this.log("");
// Create local variables for Xuggler
int numStreams = 0;
IContainer container = IContainer.make();
// Open container and read file
if (container.open(fileName, IContainer.Type.READ, null) < 0)
{
throw new IllegalArgumentException("Could not open file: '" + fileName + "'");
}
this.log("Container opened for analysis...");
this.log("");
// Analyze basic file information
numStreams = container.getNumStreams();
this.log("Number of streams: \t\t" + numStreams);
String duration = (container.getDuration() == Global.NO_PTS ? "unknown" : (container.getDuration() / 1000) + " ms");
this.log("Duration: \t\t\t" + duration);
this.log("File size: \t\t\t" + container.getFileSize() + " Bytes");
this.log("Bitrate: \t\t\t" + container.getBitRate() + " Bit/s");
this.log("");
// Analyze streams
this.log("Now analizing streams...");
this.log("");
// Analyze all IStreams within the IContainer
for (int i = 0; i < numStreams; i++)
{
// Get stream
IStream stream = container.getStream(i);
// Get stream coder
IStreamCoder coder = stream.getStreamCoder();
this.log("------------------------------------------------------------");
this.log("");
this.log("New stream found...");
this.log("");
this.log("Codec type: \t\t" + coder.getCodecType());
this.log("Codec ID: \t\t\t" + coder.getCodecID());
String streamDuration = (stream.getDuration() == Global.NO_PTS ? "unknown" : String.valueOf(stream.getDuration()));
this.log("Duration: \t\t\t" + streamDuration + " time units");
String startTime = (stream.getStartTime() == Global.NO_PTS ? "unknown" : String.valueOf(stream.getStartTime()));
this.log("Start time: \t\t\t" + startTime);
this.log("Language: \t\t\t" + (stream.getLanguage() == null ? "unknown" : stream.getLanguage()));
this.log("IStream time-base: \t\t" + stream.getTimeBase().getNumerator() + " (Numerator), "
+ stream.getTimeBase().getDenominator() + " (Denominator)");
this.log("IStreamCoder time-base: \t" + coder.getTimeBase().getNumerator() + " (Numerator), "
+ coder.getTimeBase().getDenominator() + " (Denominator)");
this.log("");
this.log("Checking stream specifics...");
this.log("");
// Analyze information, which depend on file type (audio vs. video)
if (coder.getCodecType().equals(ICodec.Type.CODEC_TYPE_AUDIO))
{
this.log("Media file type: \t\tAudio");
- this.log("Sample rate: \t\t" + coder.getSampleRate());
+ this.log("Sample rate: \t\t" + coder.getSampleRate() + " Hz");
this.log("Number of channels: \t\t" + coder.getChannels());
this.log("Sample format: \t\t" + coder.getSampleFormat());
}
else if (coder.getCodecType().equals(ICodec.Type.CODEC_TYPE_VIDEO))
{
this.log("Media file type: \t\tVideo");
this.log("Frame measurements: \t" + coder.getHeight() + " (height), " + coder.getWidth() + " (width)");
this.log("Format (pixel type): \t\t" + coder.getPixelType());
this.log("Frame rate: \t\t" + coder.getFrameRate().getDouble() + " fps");
}
this.log("");
}
// Close container and release resources
this.closeContainerSafely(container);
}
/**
* This method closes the IContainer object and releases
* all used resources.
*
* @param container IContainer object
*/
private void closeContainerSafely(IContainer container)
{
// Create local variables for Xuggler
int i;
int numStreams = container.getNumStreams();
// Do some fancy stuff...
if (container.getType() == IContainer.Type.WRITE)
{
for (i = 0; i < numStreams; i++)
{
IStreamCoder c = container.getStream(i).getStreamCoder();
if (c != null)
{
IPacket oPacket = IPacket.make();
if (c.getCodecType() == ICodec.Type.CODEC_TYPE_VIDEO)
{
c.encodeVideo(oPacket, null, 0);
}
if (oPacket.isComplete())
{
container.writePacket(oPacket, true);
}
}
}
}
if (container.getType() == IContainer.Type.WRITE)
{
int retval = container.writeTrailer();
if (retval < 0)
{
throw new RuntimeException("Could not write trailer to output file.");
}
}
// Release all IStreamCoder resources
for (i = 0; i < numStreams; i++)
{
IStreamCoder c = container.getStream(i).getStreamCoder();
if (c != null)
{
c.close();
}
}
// Close IContainer object and free memory
container.close();
container = null;
this.log("------------------------------------------------------------");
this.log("");
this.log("Container successfully closed.");
this.log("");
}
}
| true | true | public void analyzeMediafile(String fileName)
{
this.log("============================================================");
this.log("");
this.log("Analyzing metadata from file: \t'" + fileName + "'");
this.log("");
// Create local variables for Xuggler
int numStreams = 0;
IContainer container = IContainer.make();
// Open container and read file
if (container.open(fileName, IContainer.Type.READ, null) < 0)
{
throw new IllegalArgumentException("Could not open file: '" + fileName + "'");
}
this.log("Container opened for analysis...");
this.log("");
// Analyze basic file information
numStreams = container.getNumStreams();
this.log("Number of streams: \t\t" + numStreams);
String duration = (container.getDuration() == Global.NO_PTS ? "unknown" : (container.getDuration() / 1000) + " ms");
this.log("Duration: \t\t\t" + duration);
this.log("File size: \t\t\t" + container.getFileSize() + " Bytes");
this.log("Bitrate: \t\t\t" + container.getBitRate() + " Bit/s");
this.log("");
// Analyze streams
this.log("Now analizing streams...");
this.log("");
// Analyze all IStreams within the IContainer
for (int i = 0; i < numStreams; i++)
{
// Get stream
IStream stream = container.getStream(i);
// Get stream coder
IStreamCoder coder = stream.getStreamCoder();
this.log("------------------------------------------------------------");
this.log("");
this.log("New stream found...");
this.log("");
this.log("Codec type: \t\t" + coder.getCodecType());
this.log("Codec ID: \t\t\t" + coder.getCodecID());
String streamDuration = (stream.getDuration() == Global.NO_PTS ? "unknown" : String.valueOf(stream.getDuration()));
this.log("Duration: \t\t\t" + streamDuration + " time units");
String startTime = (stream.getStartTime() == Global.NO_PTS ? "unknown" : String.valueOf(stream.getStartTime()));
this.log("Start time: \t\t\t" + startTime);
this.log("Language: \t\t\t" + (stream.getLanguage() == null ? "unknown" : stream.getLanguage()));
this.log("IStream time-base: \t\t" + stream.getTimeBase().getNumerator() + " (Numerator), "
+ stream.getTimeBase().getDenominator() + " (Denominator)");
this.log("IStreamCoder time-base: \t" + coder.getTimeBase().getNumerator() + " (Numerator), "
+ coder.getTimeBase().getDenominator() + " (Denominator)");
this.log("");
this.log("Checking stream specifics...");
this.log("");
// Analyze information, which depend on file type (audio vs. video)
if (coder.getCodecType().equals(ICodec.Type.CODEC_TYPE_AUDIO))
{
this.log("Media file type: \t\tAudio");
this.log("Sample rate: \t\t" + coder.getSampleRate());
this.log("Number of channels: \t\t" + coder.getChannels());
this.log("Sample format: \t\t" + coder.getSampleFormat());
}
else if (coder.getCodecType().equals(ICodec.Type.CODEC_TYPE_VIDEO))
{
this.log("Media file type: \t\tVideo");
this.log("Frame measurements: \t" + coder.getHeight() + " (height), " + coder.getWidth() + " (width)");
this.log("Format (pixel type): \t\t" + coder.getPixelType());
this.log("Frame rate: \t\t" + coder.getFrameRate().getDouble() + " fps");
}
this.log("");
}
// Close container and release resources
this.closeContainerSafely(container);
}
| public void analyzeMediafile(String fileName)
{
this.log("============================================================");
this.log("");
this.log("Analyzing metadata from file: \t'" + fileName + "'");
this.log("");
// Create local variables for Xuggler
int numStreams = 0;
IContainer container = IContainer.make();
// Open container and read file
if (container.open(fileName, IContainer.Type.READ, null) < 0)
{
throw new IllegalArgumentException("Could not open file: '" + fileName + "'");
}
this.log("Container opened for analysis...");
this.log("");
// Analyze basic file information
numStreams = container.getNumStreams();
this.log("Number of streams: \t\t" + numStreams);
String duration = (container.getDuration() == Global.NO_PTS ? "unknown" : (container.getDuration() / 1000) + " ms");
this.log("Duration: \t\t\t" + duration);
this.log("File size: \t\t\t" + container.getFileSize() + " Bytes");
this.log("Bitrate: \t\t\t" + container.getBitRate() + " Bit/s");
this.log("");
// Analyze streams
this.log("Now analizing streams...");
this.log("");
// Analyze all IStreams within the IContainer
for (int i = 0; i < numStreams; i++)
{
// Get stream
IStream stream = container.getStream(i);
// Get stream coder
IStreamCoder coder = stream.getStreamCoder();
this.log("------------------------------------------------------------");
this.log("");
this.log("New stream found...");
this.log("");
this.log("Codec type: \t\t" + coder.getCodecType());
this.log("Codec ID: \t\t\t" + coder.getCodecID());
String streamDuration = (stream.getDuration() == Global.NO_PTS ? "unknown" : String.valueOf(stream.getDuration()));
this.log("Duration: \t\t\t" + streamDuration + " time units");
String startTime = (stream.getStartTime() == Global.NO_PTS ? "unknown" : String.valueOf(stream.getStartTime()));
this.log("Start time: \t\t\t" + startTime);
this.log("Language: \t\t\t" + (stream.getLanguage() == null ? "unknown" : stream.getLanguage()));
this.log("IStream time-base: \t\t" + stream.getTimeBase().getNumerator() + " (Numerator), "
+ stream.getTimeBase().getDenominator() + " (Denominator)");
this.log("IStreamCoder time-base: \t" + coder.getTimeBase().getNumerator() + " (Numerator), "
+ coder.getTimeBase().getDenominator() + " (Denominator)");
this.log("");
this.log("Checking stream specifics...");
this.log("");
// Analyze information, which depend on file type (audio vs. video)
if (coder.getCodecType().equals(ICodec.Type.CODEC_TYPE_AUDIO))
{
this.log("Media file type: \t\tAudio");
this.log("Sample rate: \t\t" + coder.getSampleRate() + " Hz");
this.log("Number of channels: \t\t" + coder.getChannels());
this.log("Sample format: \t\t" + coder.getSampleFormat());
}
else if (coder.getCodecType().equals(ICodec.Type.CODEC_TYPE_VIDEO))
{
this.log("Media file type: \t\tVideo");
this.log("Frame measurements: \t" + coder.getHeight() + " (height), " + coder.getWidth() + " (width)");
this.log("Format (pixel type): \t\t" + coder.getPixelType());
this.log("Frame rate: \t\t" + coder.getFrameRate().getDouble() + " fps");
}
this.log("");
}
// Close container and release resources
this.closeContainerSafely(container);
}
|
diff --git a/src/main/groovy/groovyx/gpars/actor/Actor.java b/src/main/groovy/groovyx/gpars/actor/Actor.java
index ca7a4b07..cbfbbe67 100644
--- a/src/main/groovy/groovyx/gpars/actor/Actor.java
+++ b/src/main/groovy/groovyx/gpars/actor/Actor.java
@@ -1,492 +1,492 @@
// GPars - Groovy Parallel Systems
//
// Copyright © 2008-10 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 groovyx.gpars.actor;
import groovy.lang.Closure;
import groovy.lang.MetaClass;
import groovy.lang.MetaMethod;
import groovy.time.BaseDuration;
import groovyx.gpars.actor.impl.MessageStream;
import groovyx.gpars.dataflow.DataCallback;
import groovyx.gpars.dataflow.DataFlowExpression;
import groovyx.gpars.dataflow.DataFlowVariable;
import groovyx.gpars.group.PGroup;
import groovyx.gpars.remote.RemoteConnection;
import groovyx.gpars.remote.RemoteHost;
import groovyx.gpars.serial.DefaultRemoteHandle;
import groovyx.gpars.serial.RemoteHandle;
import groovyx.gpars.serial.RemoteSerialized;
import groovyx.gpars.serial.SerialContext;
import groovyx.gpars.serial.SerialHandle;
import groovyx.gpars.serial.SerialMsg;
import groovyx.gpars.serial.WithSerialId;
import org.codehaus.groovy.runtime.InvokerHelper;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Timer;
import java.util.concurrent.TimeUnit;
/**
* Actors are active objects, which borrow a thread from a thread pool.
* The Actor interface provides means to send messages to the actor, start and stop the background thread as well as
* check its status.
*
* @author Vaclav Pech, Alex Tkachman
*/
public abstract class Actor extends MessageStream {
/**
* Maps each thread to the actor it currently processes.
* Used in the send() method to remember the sender of each message for potential replies
*/
private static final ThreadLocal<Actor> currentActorPerThread = new ThreadLocal<Actor>();
private static final long serialVersionUID = -3491276479442857422L;
private final DataFlowExpression<Object> joinLatch;
/**
* The parallel group to which the message stream belongs
*/
protected volatile PGroup parallelGroup;
protected static final ActorMessage START_MESSAGE = new ActorMessage("Start", null);
protected static final ActorMessage STOP_MESSAGE = new ActorMessage("STOP_MESSAGE", null);
protected static final ActorMessage TERMINATE_MESSAGE = new ActorMessage("TERMINATE_MESSAGE", null);
private static final String AFTER_START = "afterStart";
private static final String RESPONDS_TO = "respondsTo";
private static final String ON_DELIVERY_ERROR = "onDeliveryError";
private static final Object[] EMPTY_ARGUMENTS = new Object[0];
@SuppressWarnings({"ConstantDeclaredInAbstractClass"})
public static final String TIMEOUT = "TIMEOUT";
protected static final ActorMessage TIMEOUT_MESSAGE = new ActorMessage(TIMEOUT, null);
private volatile Closure onStop = null;
protected volatile Thread currentThread;
protected static final String ACTOR_HAS_ALREADY_BEEN_STARTED = "Actor has already been started.";
/**
* Timer holding timeouts for react methods
*/
protected static final Timer timer = new Timer("GPars Actor Timer", true);
protected Actor() {
this(new DataFlowVariable<Object>());
}
/**
* Constructor to be used by deserialization
*
* @param joinLatch The instance of DataFlowExpression to use for join operation
*/
protected Actor(final DataFlowExpression<Object> joinLatch) {
this(joinLatch, Actors.defaultActorPGroup);
}
protected Actor(final DataFlowExpression<Object> joinLatch, final PGroup parallelGroup) {
this.joinLatch = joinLatch;
this.parallelGroup = parallelGroup;
}
/**
* Retrieves the group to which the actor belongs
*
* @return The group
*/
public final PGroup getParallelGroup() {
return parallelGroup;
}
/**
* Sets the parallel group.
* It can only be invoked before the actor is started.
*
* @param group new group
*/
public void setParallelGroup(final PGroup group) {
if (group == null) {
throw new IllegalArgumentException("Cannot set actor's group to null.");
}
parallelGroup = group;
}
/**
* Sends a message and execute continuation when reply became available.
*
* @param message message to send
* @param closure closure to execute when reply became available
* @return The message that came in reply to the original send.
* @throws InterruptedException if interrupted while waiting
*/
@SuppressWarnings({"AssignmentToMethodParameter"})
public final <T> MessageStream sendAndContinue(final T message, Closure closure) throws InterruptedException {
closure = (Closure) closure.clone();
closure.setDelegate(this);
closure.setResolveStrategy(Closure.DELEGATE_FIRST);
return send(message, new DataCallback(closure, parallelGroup));
}
/**
* Starts the Actor without sending the START_MESSAGE message to speed the start-up.
* The potential custom afterStart handlers won't be run.
* No messages can be sent or received before an Actor is started.
*
* @return same actor
*/
public abstract Actor silentStart();
/**
* Starts the Actor and sends it the START_MESSAGE to run any afterStart handlers.
* No messages can be sent or received before an Actor is started.
*
* @return same actor
*/
public abstract Actor start();
/**
* Send message to stop to the Actor. The actor will finish processing the current message and all unprocessed messages will be passed to the afterStop method, if such exists.
* No new messages will be accepted since that point.
* Has no effect if the Actor is not started.
*
* @return same actor
*/
public abstract Actor stop();
/**
* Terminates the Actor. Unprocessed messages will be passed to the afterStop method, if exists.
* No new messages will be accepted since that point.
* Has no effect if the Actor is not started.
*
* @return same actor
*/
public abstract Actor terminate();
/**
* Checks the current status of the Actor.
*
* @return current status of the Actor.
*/
public abstract boolean isActive();
/**
* Joins the actor. Waits for its termination.
*
* @throws InterruptedException when interrupted while waiting
*/
public final void join() throws InterruptedException {
joinLatch.getVal();
}
/**
* Notify listener when finished
*
* @param listener listener to notify
* @throws InterruptedException if interrupted while waiting
*/
public final void join(final MessageStream listener) throws InterruptedException {
joinLatch.getValAsync(listener);
}
/**
* Joins the actor. Waits for its termination.
*
* @param timeout timeout
* @param unit units of timeout
* @throws InterruptedException if interrupted while waiting
*/
public final void join(final long timeout, final TimeUnit unit) throws InterruptedException {
if (timeout > 0L) {
joinLatch.getVal(timeout, unit);
} else {
joinLatch.getVal();
}
}
/**
* Joins the actor. Waits for its termination.
*
* @param duration timeout to wait
* @throws InterruptedException if interrupted while waiting
*/
public final void join(final BaseDuration duration) throws InterruptedException {
join(duration.toMilliseconds(), TimeUnit.MILLISECONDS);
}
/**
* Join-point for this actor
*
* @return The DataFlowExpression instance, which is used to join this actor
*/
public DataFlowExpression<Object> getJoinLatch() {
return joinLatch;
}
/**
* Registers the actor with the current thread
*
* @param currentActor The actor to register
*/
protected static void registerCurrentActorWithThread(final Actor currentActor) {
Actor.currentActorPerThread.set(currentActor);
}
/**
* Deregisters the actor registered from the thread
*/
protected static void deregisterCurrentActorWithThread() {
Actor.currentActorPerThread.set(null);
}
/**
* Retrieves the actor registered with the current thread
*
* @return The associated actor
*/
public static Actor threadBoundActor() {
return Actor.currentActorPerThread.get();
}
protected final ActorMessage createActorMessage(final Object message) {
if (hasBeenStopped()) {
//noinspection ObjectEquality
if (message != TERMINATE_MESSAGE && message != STOP_MESSAGE)
throw new IllegalStateException("The actor cannot accept messages at this point.");
}
final ActorMessage actorMessage;
if (message instanceof ActorMessage) {
actorMessage = (ActorMessage) message;
} else {
actorMessage = ActorMessage.build(message);
}
return actorMessage;
}
protected abstract boolean hasBeenStopped();
@Override
protected RemoteHandle createRemoteHandle(final SerialHandle handle, final SerialContext host) {
return new MyRemoteHandle(handle, host, joinLatch);
}
@SuppressWarnings("unchecked")
protected void handleStart() {
final Object list = InvokerHelper.invokeMethod(this, RESPONDS_TO, new Object[]{AFTER_START});
if (list != null && !((Collection<Object>) list).isEmpty()) {
InvokerHelper.invokeMethod(this, AFTER_START, EMPTY_ARGUMENTS);
}
}
protected void handleTermination() {
final List<?> queue = sweepQueue();
if (onStop != null)
onStop.call(queue);
callDynamic("afterStop", new Object[]{queue});
}
/**
* Set on stop handler for this actor
*
* @param onStop The code to invoke when stopping
*/
public final void onStop(final Closure onStop) {
if (onStop != null) {
this.onStop = (Closure) onStop.clone();
this.onStop.setDelegate(this);
this.onStop.setResolveStrategy(Closure.DELEGATE_FIRST);
}
}
@SuppressWarnings({"UseOfSystemOutOrSystemErr"})
protected void handleException(final Throwable exception) {
if (!callDynamic("onException", new Object[]{exception})) {
System.err.println("An exception occurred in the Actor thread " + Thread.currentThread().getName());
exception.printStackTrace(System.err);
}
}
@SuppressWarnings({"TypeMayBeWeakened", "UseOfSystemOutOrSystemErr"})
protected void handleInterrupt(final InterruptedException exception) {
Thread.interrupted();
if (!callDynamic("onInterrupt", new Object[]{exception})) {
if (!hasBeenStopped()) {
System.err.println("The actor processing thread has been interrupted " + Thread.currentThread().getName());
exception.printStackTrace(System.err);
}
}
}
protected void handleTimeout() {
callDynamic("onTimeout", EMPTY_ARGUMENTS);
}
private boolean callDynamic(final String method, final Object[] args) {
final MetaClass metaClass = InvokerHelper.getMetaClass(this);
final List<MetaMethod> list = metaClass.respondsTo(this, method);
if (list != null && !list.isEmpty()) {
InvokerHelper.invokeMethod(this, method, args);
return true;
}
return false;
}
/**
* Removes the head of the message queue
*
* @return The head message, or null, if the message queue is empty
*/
protected abstract ActorMessage sweepNextMessage();
/**
* Clears the message queue returning all the messages it held.
*
* @return The messages stored in the queue
*/
@SuppressWarnings("unchecked")
final List<ActorMessage> sweepQueue() {
final List<ActorMessage> messages = new ArrayList<ActorMessage>();
ActorMessage message = sweepNextMessage();
while (message != null && message != STOP_MESSAGE) {
- final Object payloadList = InvokerHelper.invokeMethod(message.getPayLoad(), RESPONDS_TO, new Object[]{ON_DELIVERY_ERROR});
- if (payloadList != null && !((Collection<Object>) payloadList).isEmpty()) {
- InvokerHelper.invokeMethod(message.getPayLoad(), ON_DELIVERY_ERROR, EMPTY_ARGUMENTS);
+ final Object senderMethodList = InvokerHelper.invokeMethod(message.getSender(), RESPONDS_TO, new Object[]{ON_DELIVERY_ERROR});
+ if (senderMethodList != null && !((Collection<Object>) senderMethodList).isEmpty()) {
+ InvokerHelper.invokeMethod(message.getSender(), ON_DELIVERY_ERROR, EMPTY_ARGUMENTS);
} else {
- final Object senderList = InvokerHelper.invokeMethod(message.getSender(), RESPONDS_TO, new Object[]{ON_DELIVERY_ERROR});
- if (senderList != null && !((Collection<Object>) senderList).isEmpty()) {
- InvokerHelper.invokeMethod(message.getSender(), ON_DELIVERY_ERROR, EMPTY_ARGUMENTS);
+ final Object payloadMethodList = InvokerHelper.invokeMethod(message.getPayLoad(), RESPONDS_TO, new Object[]{ON_DELIVERY_ERROR});
+ if (payloadMethodList != null && !((Collection<Object>) payloadMethodList).isEmpty()) {
+ InvokerHelper.invokeMethod(message.getPayLoad(), ON_DELIVERY_ERROR, EMPTY_ARGUMENTS);
}
}
messages.add(message);
message = sweepNextMessage();
}
return messages;
}
/**
* Checks whether the current thread is the actor's current thread.
*
* @return True if invoked from within an actor thread
*/
public final boolean isActorThread() {
return Thread.currentThread() == currentThread;
}
public static class MyRemoteHandle extends DefaultRemoteHandle {
private final DataFlowExpression<Object> joinLatch;
private static final long serialVersionUID = 3721849638877039035L;
public MyRemoteHandle(final SerialHandle handle, final SerialContext host, final DataFlowExpression<Object> joinLatch) {
super(handle.getSerialId(), host.getHostId(), RemoteActor.class);
this.joinLatch = joinLatch;
}
@Override
protected WithSerialId createObject(final SerialContext context) throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
return new RemoteActor(context, joinLatch);
}
}
public static class RemoteActor extends Actor implements RemoteSerialized {
private final RemoteHost remoteHost;
private static final long serialVersionUID = -1375776678860848278L;
public RemoteActor(final SerialContext host, final DataFlowExpression<Object> jointLatch) {
super(jointLatch);
remoteHost = (RemoteHost) host;
}
@Override
public Actor silentStart() {
return null;
}
@Override
public Actor start() {
throw new UnsupportedOperationException();
}
@Override
public Actor stop() {
remoteHost.write(new StopActorMsg(this));
return this;
}
@Override
public Actor terminate() {
remoteHost.write(new TerminateActorMsg(this));
return this;
}
@Override
public boolean isActive() {
throw new UnsupportedOperationException();
}
@Override
protected boolean hasBeenStopped() {
return false; //todo implement
}
@Override
protected ActorMessage sweepNextMessage() {
throw new UnsupportedOperationException();
}
@SuppressWarnings({"AssignmentToMethodParameter"})
@Override
public MessageStream send(Object message) {
if (!(message instanceof ActorMessage)) {
message = new ActorMessage(message, Actor.threadBoundActor());
}
remoteHost.write(new SendTo(this, (ActorMessage) message));
return this;
}
public static class StopActorMsg extends SerialMsg {
private final Actor actor;
private static final long serialVersionUID = -927785591952534581L;
public StopActorMsg(final RemoteActor remoteActor) {
actor = remoteActor;
}
@Override
public void execute(final RemoteConnection conn) {
actor.stop();
}
}
public static class TerminateActorMsg extends SerialMsg {
private final Actor actor;
private static final long serialVersionUID = -839334644951906974L;
public TerminateActorMsg(final RemoteActor remoteActor) {
actor = remoteActor;
}
@Override
public void execute(final RemoteConnection conn) {
actor.terminate();
}
}
}
}
| false | true | final List<ActorMessage> sweepQueue() {
final List<ActorMessage> messages = new ArrayList<ActorMessage>();
ActorMessage message = sweepNextMessage();
while (message != null && message != STOP_MESSAGE) {
final Object payloadList = InvokerHelper.invokeMethod(message.getPayLoad(), RESPONDS_TO, new Object[]{ON_DELIVERY_ERROR});
if (payloadList != null && !((Collection<Object>) payloadList).isEmpty()) {
InvokerHelper.invokeMethod(message.getPayLoad(), ON_DELIVERY_ERROR, EMPTY_ARGUMENTS);
} else {
final Object senderList = InvokerHelper.invokeMethod(message.getSender(), RESPONDS_TO, new Object[]{ON_DELIVERY_ERROR});
if (senderList != null && !((Collection<Object>) senderList).isEmpty()) {
InvokerHelper.invokeMethod(message.getSender(), ON_DELIVERY_ERROR, EMPTY_ARGUMENTS);
}
}
messages.add(message);
message = sweepNextMessage();
}
return messages;
}
| final List<ActorMessage> sweepQueue() {
final List<ActorMessage> messages = new ArrayList<ActorMessage>();
ActorMessage message = sweepNextMessage();
while (message != null && message != STOP_MESSAGE) {
final Object senderMethodList = InvokerHelper.invokeMethod(message.getSender(), RESPONDS_TO, new Object[]{ON_DELIVERY_ERROR});
if (senderMethodList != null && !((Collection<Object>) senderMethodList).isEmpty()) {
InvokerHelper.invokeMethod(message.getSender(), ON_DELIVERY_ERROR, EMPTY_ARGUMENTS);
} else {
final Object payloadMethodList = InvokerHelper.invokeMethod(message.getPayLoad(), RESPONDS_TO, new Object[]{ON_DELIVERY_ERROR});
if (payloadMethodList != null && !((Collection<Object>) payloadMethodList).isEmpty()) {
InvokerHelper.invokeMethod(message.getPayLoad(), ON_DELIVERY_ERROR, EMPTY_ARGUMENTS);
}
}
messages.add(message);
message = sweepNextMessage();
}
return messages;
}
|
diff --git a/src/edu/sc/seis/sod/subsetter/waveformArm/PhaseRequest.java b/src/edu/sc/seis/sod/subsetter/waveformArm/PhaseRequest.java
index 230cdf375..b7f8e077e 100644
--- a/src/edu/sc/seis/sod/subsetter/waveformArm/PhaseRequest.java
+++ b/src/edu/sc/seis/sod/subsetter/waveformArm/PhaseRequest.java
@@ -1,236 +1,242 @@
package edu.sc.seis.sod.subsetter.waveFormArm;
import edu.sc.seis.sod.*;
import edu.sc.seis.TauP.*;
import edu.iris.Fissures.IfEvent.*;
import edu.iris.Fissures.event.*;
import edu.iris.Fissures.IfNetwork.*;
import edu.iris.Fissures.network.*;
import edu.iris.Fissures.Location;
import edu.iris.Fissures.model.*;
import edu.iris.Fissures.IfSeismogramDC.*;
import java.util.*;
import org.w3c.dom.*;
/**
* sample xml file
*<pre>
* <phaseRequest>
* <beginPhase>ttp</beginPhase>
* <beginOffset>
* <unit>SECOND</unit>
* <value>-120</value>
* </beginOffset>
* <endPhase>tts</endPhase>
* <endOffset>
* <unit>SECOND</unit>
* <value>600</value>
* </endOffset>
* </phaseRequest>
*</pre>
*/
public class PhaseRequest implements RequestGenerator{
/**
* Creates a new <code>PhaseRequest</code> instance.
*
* @param config an <code>Element</code> value
*/
public PhaseRequest (Element config) throws ConfigurationException{
NodeList childNodes = config.getChildNodes();
Node node;
for(int counter = 0; counter < childNodes.getLength(); counter++) {
node = childNodes.item(counter);
if(node instanceof Element) {
Element element = (Element)node;
if(element.getTagName().equals("beginPhase")) {
beginPhase = SodUtil.getNestedText(element);
} else if(element.getTagName().equals("beginOffset")) {
SodElement sodElement =
(SodElement) SodUtil.load(element,
waveformArmPackage);
beginOffset = (BeginOffset)sodElement;
} else if(element.getTagName().equals("endPhase")) {
endPhase = SodUtil.getNestedText(element);
} else if(element.getTagName().equals("endOffset")) {
SodElement sodElement =
(SodElement) SodUtil.load(element,
waveformArmPackage);
endOffset = (EndOffset)sodElement;
}
}
}
}
/**
* Describe <code>generateRequest</code> method here.
*
* @param event an <code>EventAccessOperations</code> value
* @param network a <code>NetworkAccess</code> value
* @param channel a <code>Channel</code> value
* @param cookies a <code>CookieJar</code> value
* @return a <code>RequestFilter[]</code> value
*/
public RequestFilter[] generateRequest(EventAccessOperations event,
NetworkAccess network,
Channel channel,
CookieJar cookies) throws Exception{
Origin origin = null;
double arrivalStartTime = -100.0;
double arrivalEndTime = -100.0;
origin = event.get_preferred_origin();
if ( prevRequestFilter != null &&
origin.my_location.equals(prevOriginLoc) &&
channel.my_site.my_location.equals(prevSiteLoc) ) {
// don't need to do any work
- return prevRequestFilter;
+ RequestFilter[] out = new RequestFilter[prevRequestFilter.length];
+ for (int i = 0; i < out.length; i++) {
+ out[i] = new RequestFilter(channel.get_id(),
+ prevRequestFilter[i].start_time,
+ prevRequestFilter[i].end_time);
+ }
+ return out;
} else {
prevOriginLoc = origin.my_location;
prevSiteLoc = channel.my_site.my_location;
prevRequestFilter = null;
} // end of else
Properties props = Start.getProperties();
String tauPModel = new String();
tauPModel = props.getProperty("edu.sc.seis.sod.TaupModel");
if(tauPModel == null) tauPModel = "prem";
String phaseNames= "";
if ( ! beginPhase.equals(ORIGIN)) {
phaseNames += " "+beginPhase;
} // end of if (beginPhase.equals("origin"))
if ( ! endPhase.equals(ORIGIN)) {
phaseNames += " "+endPhase;
} // end of if (beginPhase.equals("origin"))
Arrival[] arrivals = calculateArrivals(tauPModel,
phaseNames,
origin.my_location,
channel.my_site.my_location);
for(int counter = 0; counter < arrivals.length; counter++) {
String arrivalName = arrivals[counter].getName();
if(beginPhase.startsWith("tt")) {
if(beginPhase.equals("tts")
&& arrivalName.toUpperCase().startsWith("S")) {
arrivalStartTime = arrivals[counter].getTime();
break;
} else if(beginPhase.equals("ttp")
&& arrivalName.toUpperCase().startsWith("P")) {
arrivalStartTime = arrivals[counter].getTime();
break;
}
} else if(beginPhase.equals(arrivalName)) {
arrivalStartTime = arrivals[counter].getTime();
break;
}
}
for(int counter = 0; counter < arrivals.length; counter++) {
String arrivalName = arrivals[counter].getName();
if(endPhase.startsWith("tt")) {
if(endPhase.equals("tts")
&& arrivalName.toUpperCase().startsWith("S")) {
arrivalEndTime = arrivals[counter].getTime();
break;
} else if(endPhase.equals("ttp")
&& arrivalName.toUpperCase().startsWith("P")) {
arrivalEndTime = arrivals[counter].getTime();
break;
}
} else if(endPhase.equals(arrivalName)) {
arrivalEndTime = arrivals[counter].getTime();
break;
}
}
if (beginPhase.equals(ORIGIN)) {
arrivalStartTime = 0;
}
if (endPhase.equals(ORIGIN)) {
arrivalEndTime = 0;
}
if(arrivalStartTime == -100.0 || arrivalEndTime == -100.0) {
// no arrivals found, return zero length request filters
prevRequestFilter = new RequestFilter[0];
return prevRequestFilter;
}
// round to milliseconds
arrivalStartTime = Math.rint(1000*arrivalStartTime)/1000;
arrivalEndTime = Math.rint(1000*arrivalEndTime)/1000;
edu.iris.Fissures.Time originTime = origin.origin_time;
MicroSecondDate originDate = new MicroSecondDate(originTime);
TimeInterval bInterval = beginOffset.getTimeInterval();
bInterval = bInterval.add(new TimeInterval(arrivalStartTime,
UnitImpl.SECOND));
TimeInterval eInterval = endOffset.getTimeInterval();
eInterval = eInterval.add(new TimeInterval(arrivalEndTime,
UnitImpl.SECOND));
MicroSecondDate bDate = originDate.add(bInterval);
MicroSecondDate eDate = originDate.add(eInterval);
RequestFilter[] filters;
filters = new RequestFilter[1];
filters[0] =
new RequestFilter(channel.get_id(),
bDate.getFissuresTime(),
eDate.getFissuresTime()
);
prevRequestFilter = filters;
return filters;
}
protected static TauP_Time tauPTime = new TauP_Time();
protected synchronized static Arrival[] calculateArrivals(
String tauPModelName,
String phases,
Location originLoc,
Location channelLoc)
throws java.io.IOException, TauModelException {
if (tauPTime.getTauModelName() != tauPModelName) {
tauPTime.loadTauModel(tauPModelName);
}
tauPTime.clearPhaseNames();
tauPTime.parsePhaseList(phases);
double originDepth =
((QuantityImpl)originLoc.depth).convertTo(UnitImpl.KILOMETER).value;
tauPTime.setSourceDepth(originDepth);
tauPTime.calculate(SphericalCoords.distance(originLoc.latitude,
originLoc.longitude,
channelLoc.latitude,
channelLoc.longitude));
return tauPTime.getArrivals();
}
private BeginOffset beginOffset;
private String beginPhase;
private EndOffset endOffset;
private String endPhase;
private RequestFilter[] prevRequestFilter = null;
private Location prevOriginLoc = null;
protected Location prevSiteLoc = null;
private static final String ORIGIN = "origin";
}// PhaseRequest
| true | true | public RequestFilter[] generateRequest(EventAccessOperations event,
NetworkAccess network,
Channel channel,
CookieJar cookies) throws Exception{
Origin origin = null;
double arrivalStartTime = -100.0;
double arrivalEndTime = -100.0;
origin = event.get_preferred_origin();
if ( prevRequestFilter != null &&
origin.my_location.equals(prevOriginLoc) &&
channel.my_site.my_location.equals(prevSiteLoc) ) {
// don't need to do any work
return prevRequestFilter;
} else {
prevOriginLoc = origin.my_location;
prevSiteLoc = channel.my_site.my_location;
prevRequestFilter = null;
} // end of else
Properties props = Start.getProperties();
String tauPModel = new String();
tauPModel = props.getProperty("edu.sc.seis.sod.TaupModel");
if(tauPModel == null) tauPModel = "prem";
String phaseNames= "";
if ( ! beginPhase.equals(ORIGIN)) {
phaseNames += " "+beginPhase;
} // end of if (beginPhase.equals("origin"))
if ( ! endPhase.equals(ORIGIN)) {
phaseNames += " "+endPhase;
} // end of if (beginPhase.equals("origin"))
Arrival[] arrivals = calculateArrivals(tauPModel,
phaseNames,
origin.my_location,
channel.my_site.my_location);
for(int counter = 0; counter < arrivals.length; counter++) {
String arrivalName = arrivals[counter].getName();
if(beginPhase.startsWith("tt")) {
if(beginPhase.equals("tts")
&& arrivalName.toUpperCase().startsWith("S")) {
arrivalStartTime = arrivals[counter].getTime();
break;
} else if(beginPhase.equals("ttp")
&& arrivalName.toUpperCase().startsWith("P")) {
arrivalStartTime = arrivals[counter].getTime();
break;
}
} else if(beginPhase.equals(arrivalName)) {
arrivalStartTime = arrivals[counter].getTime();
break;
}
}
for(int counter = 0; counter < arrivals.length; counter++) {
String arrivalName = arrivals[counter].getName();
if(endPhase.startsWith("tt")) {
if(endPhase.equals("tts")
&& arrivalName.toUpperCase().startsWith("S")) {
arrivalEndTime = arrivals[counter].getTime();
break;
} else if(endPhase.equals("ttp")
&& arrivalName.toUpperCase().startsWith("P")) {
arrivalEndTime = arrivals[counter].getTime();
break;
}
} else if(endPhase.equals(arrivalName)) {
arrivalEndTime = arrivals[counter].getTime();
break;
}
}
if (beginPhase.equals(ORIGIN)) {
arrivalStartTime = 0;
}
if (endPhase.equals(ORIGIN)) {
arrivalEndTime = 0;
}
if(arrivalStartTime == -100.0 || arrivalEndTime == -100.0) {
// no arrivals found, return zero length request filters
prevRequestFilter = new RequestFilter[0];
return prevRequestFilter;
}
// round to milliseconds
arrivalStartTime = Math.rint(1000*arrivalStartTime)/1000;
arrivalEndTime = Math.rint(1000*arrivalEndTime)/1000;
edu.iris.Fissures.Time originTime = origin.origin_time;
MicroSecondDate originDate = new MicroSecondDate(originTime);
TimeInterval bInterval = beginOffset.getTimeInterval();
bInterval = bInterval.add(new TimeInterval(arrivalStartTime,
UnitImpl.SECOND));
TimeInterval eInterval = endOffset.getTimeInterval();
eInterval = eInterval.add(new TimeInterval(arrivalEndTime,
UnitImpl.SECOND));
MicroSecondDate bDate = originDate.add(bInterval);
MicroSecondDate eDate = originDate.add(eInterval);
RequestFilter[] filters;
filters = new RequestFilter[1];
filters[0] =
new RequestFilter(channel.get_id(),
bDate.getFissuresTime(),
eDate.getFissuresTime()
);
prevRequestFilter = filters;
return filters;
}
| public RequestFilter[] generateRequest(EventAccessOperations event,
NetworkAccess network,
Channel channel,
CookieJar cookies) throws Exception{
Origin origin = null;
double arrivalStartTime = -100.0;
double arrivalEndTime = -100.0;
origin = event.get_preferred_origin();
if ( prevRequestFilter != null &&
origin.my_location.equals(prevOriginLoc) &&
channel.my_site.my_location.equals(prevSiteLoc) ) {
// don't need to do any work
RequestFilter[] out = new RequestFilter[prevRequestFilter.length];
for (int i = 0; i < out.length; i++) {
out[i] = new RequestFilter(channel.get_id(),
prevRequestFilter[i].start_time,
prevRequestFilter[i].end_time);
}
return out;
} else {
prevOriginLoc = origin.my_location;
prevSiteLoc = channel.my_site.my_location;
prevRequestFilter = null;
} // end of else
Properties props = Start.getProperties();
String tauPModel = new String();
tauPModel = props.getProperty("edu.sc.seis.sod.TaupModel");
if(tauPModel == null) tauPModel = "prem";
String phaseNames= "";
if ( ! beginPhase.equals(ORIGIN)) {
phaseNames += " "+beginPhase;
} // end of if (beginPhase.equals("origin"))
if ( ! endPhase.equals(ORIGIN)) {
phaseNames += " "+endPhase;
} // end of if (beginPhase.equals("origin"))
Arrival[] arrivals = calculateArrivals(tauPModel,
phaseNames,
origin.my_location,
channel.my_site.my_location);
for(int counter = 0; counter < arrivals.length; counter++) {
String arrivalName = arrivals[counter].getName();
if(beginPhase.startsWith("tt")) {
if(beginPhase.equals("tts")
&& arrivalName.toUpperCase().startsWith("S")) {
arrivalStartTime = arrivals[counter].getTime();
break;
} else if(beginPhase.equals("ttp")
&& arrivalName.toUpperCase().startsWith("P")) {
arrivalStartTime = arrivals[counter].getTime();
break;
}
} else if(beginPhase.equals(arrivalName)) {
arrivalStartTime = arrivals[counter].getTime();
break;
}
}
for(int counter = 0; counter < arrivals.length; counter++) {
String arrivalName = arrivals[counter].getName();
if(endPhase.startsWith("tt")) {
if(endPhase.equals("tts")
&& arrivalName.toUpperCase().startsWith("S")) {
arrivalEndTime = arrivals[counter].getTime();
break;
} else if(endPhase.equals("ttp")
&& arrivalName.toUpperCase().startsWith("P")) {
arrivalEndTime = arrivals[counter].getTime();
break;
}
} else if(endPhase.equals(arrivalName)) {
arrivalEndTime = arrivals[counter].getTime();
break;
}
}
if (beginPhase.equals(ORIGIN)) {
arrivalStartTime = 0;
}
if (endPhase.equals(ORIGIN)) {
arrivalEndTime = 0;
}
if(arrivalStartTime == -100.0 || arrivalEndTime == -100.0) {
// no arrivals found, return zero length request filters
prevRequestFilter = new RequestFilter[0];
return prevRequestFilter;
}
// round to milliseconds
arrivalStartTime = Math.rint(1000*arrivalStartTime)/1000;
arrivalEndTime = Math.rint(1000*arrivalEndTime)/1000;
edu.iris.Fissures.Time originTime = origin.origin_time;
MicroSecondDate originDate = new MicroSecondDate(originTime);
TimeInterval bInterval = beginOffset.getTimeInterval();
bInterval = bInterval.add(new TimeInterval(arrivalStartTime,
UnitImpl.SECOND));
TimeInterval eInterval = endOffset.getTimeInterval();
eInterval = eInterval.add(new TimeInterval(arrivalEndTime,
UnitImpl.SECOND));
MicroSecondDate bDate = originDate.add(bInterval);
MicroSecondDate eDate = originDate.add(eInterval);
RequestFilter[] filters;
filters = new RequestFilter[1];
filters[0] =
new RequestFilter(channel.get_id(),
bDate.getFissuresTime(),
eDate.getFissuresTime()
);
prevRequestFilter = filters;
return filters;
}
|
diff --git a/src/main/java/cz/mallat/uasparser/OnlineUpdateUASparser.java b/src/main/java/cz/mallat/uasparser/OnlineUpdateUASparser.java
index f4e168c..d6acb8f 100644
--- a/src/main/java/cz/mallat/uasparser/OnlineUpdateUASparser.java
+++ b/src/main/java/cz/mallat/uasparser/OnlineUpdateUASparser.java
@@ -1,79 +1,80 @@
package cz.mallat.uasparser;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.ConnectException;
import cz.mallat.uasparser.fileparser.PHPFileParser;
/**
* The parser will download the definition file from the internet
*
* @author oli
*/
@Deprecated
public class OnlineUpdateUASparser extends UASparser {
protected static final String DATA_RETRIVE_URL = "http://user-agent-string.info/rpc/get_data.php?key=free&format=ini";
protected static final String VERSION_CHECK_URL = "http://user-agent-string.info/rpc/get_data.php?key=free&format=ini&ver=y";
protected static final long UPDATE_INTERVAL = 1000 * 60 * 60 * 24; // 1 day
protected long lastUpdateCheck;
protected String currentVersion;
/**
* Since we've online access to the data file, we check every day for an update
*/
@Override
protected synchronized void checkDataMaps() throws IOException {
if (lastUpdateCheck == 0 || lastUpdateCheck < System.currentTimeMillis() - UPDATE_INTERVAL) {
String versionOnServer = getVersionFromServer();
if (currentVersion == null || versionOnServer.compareTo(currentVersion) > 0) {
loadDataFromInternet();
currentVersion = versionOnServer;
}
lastUpdateCheck = System.currentTimeMillis();
}
}
/**
* Loads the data file from user-agent-string.info
*
* @throws IOException
*/
private void loadDataFromInternet() throws IOException {
URL url = new URL(DATA_RETRIVE_URL);
InputStream is = url.openStream();
try {
PHPFileParser fp = new PHPFileParser(is);
createInternalDataStructre(fp.getSections());
} finally {
is.close();
}
}
/**
* Gets the current version from user-agent-string.info
*
* @return
* @throws IOException
*/
protected String getVersionFromServer() throws IOException {
URL url = new URL(VERSION_CHECK_URL);
+ InputStream is = null;
try{
- InputStream is = url.openStream();
+ is = url.openStream();
} catch (ConnectException e) {
- return '0';
+ return "0"; //not sure about this
}
try {
byte[] buff = new byte[4048];
int len = is.read(buff);
return new String(buff, 0, len);
} finally {
is.close();
}
}
}
| false | true | protected String getVersionFromServer() throws IOException {
URL url = new URL(VERSION_CHECK_URL);
try{
InputStream is = url.openStream();
} catch (ConnectException e) {
return '0';
}
try {
byte[] buff = new byte[4048];
int len = is.read(buff);
return new String(buff, 0, len);
} finally {
is.close();
}
}
| protected String getVersionFromServer() throws IOException {
URL url = new URL(VERSION_CHECK_URL);
InputStream is = null;
try{
is = url.openStream();
} catch (ConnectException e) {
return "0"; //not sure about this
}
try {
byte[] buff = new byte[4048];
int len = is.read(buff);
return new String(buff, 0, len);
} finally {
is.close();
}
}
|
diff --git a/core/src/test/java/org/zenoss/zep/dao/impl/ConfigDaoImplIT.java b/core/src/test/java/org/zenoss/zep/dao/impl/ConfigDaoImplIT.java
index 5d14fe9..05de1f5 100644
--- a/core/src/test/java/org/zenoss/zep/dao/impl/ConfigDaoImplIT.java
+++ b/core/src/test/java/org/zenoss/zep/dao/impl/ConfigDaoImplIT.java
@@ -1,60 +1,62 @@
/*****************************************************************************
*
* Copyright (C) Zenoss, Inc. 2010, all rights reserved.
*
* This content is made available according to terms specified in
* License.zenoss under the directory where your Zenoss product is installed.
*
****************************************************************************/
package org.zenoss.zep.dao.impl;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.zenoss.protobufs.zep.Zep.EventSeverity;
import org.zenoss.protobufs.zep.Zep.ZepConfig;
import org.zenoss.zep.ZepException;
import org.zenoss.zep.dao.ConfigDao;
import static org.junit.Assert.*;
@ContextConfiguration({"classpath:zep-config.xml"})
public class ConfigDaoImplIT extends AbstractTransactionalJUnit4SpringContextTests {
@Autowired
public ConfigDao configDao;
@Test
public void testConfig() throws ZepException {
ZepConfig.Builder builder = ZepConfig.newBuilder();
builder.setEventAgeDisableSeverity(EventSeverity.SEVERITY_CRITICAL);
builder.setEventAgeSeverityInclusive(true);
builder.setEventAgeIntervalMinutes(60);
builder.setEventArchiveIntervalMinutes(7*24*60);
builder.setEventArchivePurgeIntervalDays(30);
builder.setEventTimePurgeIntervalDays(2);
builder.setEventMaxSizeBytes(40000);
builder.setIndexSummaryIntervalMilliseconds(5000);
builder.setIndexArchiveIntervalMilliseconds(15000);
builder.setIndexLimit(500);
builder.setAgingLimit(600);
builder.setArchiveLimit(750);
builder.setAgingIntervalMilliseconds(30000);
builder.setArchiveIntervalMilliseconds(45000);
+ builder.setEnableEventFlappingDetection(false);
+ builder.setFlappingEventClass("/Status/Flapping");
ZepConfig cnf = builder.build();
configDao.setConfig(cnf);
assertEquals(cnf, configDao.getConfig());
cnf = ZepConfig.newBuilder(cnf).setEventAgeIntervalMinutes(90).build();
configDao.setConfigValue("event_age_interval_minutes", cnf);
assertEquals(cnf, configDao.getConfig());
assertEquals(1, configDao.removeConfigValue("event_age_interval_minutes"));
assertEquals(0, configDao.removeConfigValue("event_age_interval_minutes"));
assertEquals(ZepConfig.getDefaultInstance().getEventAgeIntervalMinutes(),
configDao.getConfig().getEventAgeIntervalMinutes());
}
}
| true | true | public void testConfig() throws ZepException {
ZepConfig.Builder builder = ZepConfig.newBuilder();
builder.setEventAgeDisableSeverity(EventSeverity.SEVERITY_CRITICAL);
builder.setEventAgeSeverityInclusive(true);
builder.setEventAgeIntervalMinutes(60);
builder.setEventArchiveIntervalMinutes(7*24*60);
builder.setEventArchivePurgeIntervalDays(30);
builder.setEventTimePurgeIntervalDays(2);
builder.setEventMaxSizeBytes(40000);
builder.setIndexSummaryIntervalMilliseconds(5000);
builder.setIndexArchiveIntervalMilliseconds(15000);
builder.setIndexLimit(500);
builder.setAgingLimit(600);
builder.setArchiveLimit(750);
builder.setAgingIntervalMilliseconds(30000);
builder.setArchiveIntervalMilliseconds(45000);
ZepConfig cnf = builder.build();
configDao.setConfig(cnf);
assertEquals(cnf, configDao.getConfig());
cnf = ZepConfig.newBuilder(cnf).setEventAgeIntervalMinutes(90).build();
configDao.setConfigValue("event_age_interval_minutes", cnf);
assertEquals(cnf, configDao.getConfig());
assertEquals(1, configDao.removeConfigValue("event_age_interval_minutes"));
assertEquals(0, configDao.removeConfigValue("event_age_interval_minutes"));
assertEquals(ZepConfig.getDefaultInstance().getEventAgeIntervalMinutes(),
configDao.getConfig().getEventAgeIntervalMinutes());
}
| public void testConfig() throws ZepException {
ZepConfig.Builder builder = ZepConfig.newBuilder();
builder.setEventAgeDisableSeverity(EventSeverity.SEVERITY_CRITICAL);
builder.setEventAgeSeverityInclusive(true);
builder.setEventAgeIntervalMinutes(60);
builder.setEventArchiveIntervalMinutes(7*24*60);
builder.setEventArchivePurgeIntervalDays(30);
builder.setEventTimePurgeIntervalDays(2);
builder.setEventMaxSizeBytes(40000);
builder.setIndexSummaryIntervalMilliseconds(5000);
builder.setIndexArchiveIntervalMilliseconds(15000);
builder.setIndexLimit(500);
builder.setAgingLimit(600);
builder.setArchiveLimit(750);
builder.setAgingIntervalMilliseconds(30000);
builder.setArchiveIntervalMilliseconds(45000);
builder.setEnableEventFlappingDetection(false);
builder.setFlappingEventClass("/Status/Flapping");
ZepConfig cnf = builder.build();
configDao.setConfig(cnf);
assertEquals(cnf, configDao.getConfig());
cnf = ZepConfig.newBuilder(cnf).setEventAgeIntervalMinutes(90).build();
configDao.setConfigValue("event_age_interval_minutes", cnf);
assertEquals(cnf, configDao.getConfig());
assertEquals(1, configDao.removeConfigValue("event_age_interval_minutes"));
assertEquals(0, configDao.removeConfigValue("event_age_interval_minutes"));
assertEquals(ZepConfig.getDefaultInstance().getEventAgeIntervalMinutes(),
configDao.getConfig().getEventAgeIntervalMinutes());
}
|
diff --git a/de.walware.statet.r.ui/srcDebug/de/walware/statet/r/internal/debug/ui/launcher/RScriptDirectLaunchShortcut.java b/de.walware.statet.r.ui/srcDebug/de/walware/statet/r/internal/debug/ui/launcher/RScriptDirectLaunchShortcut.java
index 6489701d..74d41983 100644
--- a/de.walware.statet.r.ui/srcDebug/de/walware/statet/r/internal/debug/ui/launcher/RScriptDirectLaunchShortcut.java
+++ b/de.walware.statet.r.ui/srcDebug/de/walware/statet/r/internal/debug/ui/launcher/RScriptDirectLaunchShortcut.java
@@ -1,92 +1,91 @@
/*******************************************************************************
* Copyright (c) 2005-2010 WalWare/StatET-Project (www.walware.de/goto/statet).
* 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:
* Stephan Wahlbrink - initial API and implementation
*******************************************************************************/
package de.walware.statet.r.internal.debug.ui.launcher;
import org.eclipse.core.resources.IFile;
import org.eclipse.debug.ui.ILaunchShortcut;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.texteditor.AbstractTextEditor;
import de.walware.ecommons.ltk.ui.util.LTKSelectionUtil;
import de.walware.statet.r.internal.debug.ui.RLaunchingMessages;
import de.walware.statet.r.launching.ICodeLaunchContentHandler;
import de.walware.statet.r.launching.RCodeLaunching;
/**
* Launch shortcut, which submits the whole script directly to R
* and does not change the focus.
*/
public class RScriptDirectLaunchShortcut implements ILaunchShortcut {
private boolean fGotoConsole;
public RScriptDirectLaunchShortcut() {
this(false);
}
protected RScriptDirectLaunchShortcut(final boolean gotoConsole) {
fGotoConsole = gotoConsole;
}
public void launch(final ISelection selection, final String mode) {
assert mode.equals("run"); //$NON-NLS-1$
try {
final IFile[] files = LTKSelectionUtil.getSelectedFiles(selection);
if (files != null) {
final int last = files.length-1;
for (int i = 0; i <= last; i++) {
final String[] lines = LaunchShortcutUtil.getCodeLines(files[i]);
- RCodeLaunching.runRCodeDirect(lines[i],
- (i < last) && fGotoConsole);
+ RCodeLaunching.runRCodeDirect(lines, (i == last) && fGotoConsole);
}
return;
}
LaunchShortcutUtil.handleUnsupportedExecution(null);
}
catch (final Exception e) {
LaunchShortcutUtil.handleRLaunchException(e,
RLaunchingMessages.RScriptLaunch_error_message, null);
}
}
public void launch(final IEditorPart editor, final String mode) {
assert mode.equals("run"); //$NON-NLS-1$
try {
if (editor instanceof AbstractTextEditor) {
final AbstractTextEditor redt = (AbstractTextEditor) editor;
final ICodeLaunchContentHandler handler = RCodeLaunching.getCodeLaunchContentHandler(
LaunchShortcutUtil.getContentTypeId(redt.getEditorInput()));
final IDocument document = redt.getDocumentProvider().getDocument(editor.getEditorInput() );
final String[] lines = handler.getCodeLines(document);
RCodeLaunching.runRCodeDirect(lines, fGotoConsole);
return;
}
LaunchShortcutUtil.handleUnsupportedExecution(null);
}
catch (final Exception e) {
LaunchShortcutUtil.handleRLaunchException(e,
RLaunchingMessages.RScriptLaunch_error_message, null);
}
}
}
| true | true | public void launch(final ISelection selection, final String mode) {
assert mode.equals("run"); //$NON-NLS-1$
try {
final IFile[] files = LTKSelectionUtil.getSelectedFiles(selection);
if (files != null) {
final int last = files.length-1;
for (int i = 0; i <= last; i++) {
final String[] lines = LaunchShortcutUtil.getCodeLines(files[i]);
RCodeLaunching.runRCodeDirect(lines[i],
(i < last) && fGotoConsole);
}
return;
}
LaunchShortcutUtil.handleUnsupportedExecution(null);
}
catch (final Exception e) {
LaunchShortcutUtil.handleRLaunchException(e,
RLaunchingMessages.RScriptLaunch_error_message, null);
}
}
| public void launch(final ISelection selection, final String mode) {
assert mode.equals("run"); //$NON-NLS-1$
try {
final IFile[] files = LTKSelectionUtil.getSelectedFiles(selection);
if (files != null) {
final int last = files.length-1;
for (int i = 0; i <= last; i++) {
final String[] lines = LaunchShortcutUtil.getCodeLines(files[i]);
RCodeLaunching.runRCodeDirect(lines, (i == last) && fGotoConsole);
}
return;
}
LaunchShortcutUtil.handleUnsupportedExecution(null);
}
catch (final Exception e) {
LaunchShortcutUtil.handleRLaunchException(e,
RLaunchingMessages.RScriptLaunch_error_message, null);
}
}
|
diff --git a/modules/world/palette/src/classes/org/jdesktop/wonderland/modules/palette/client/HUDCellPalette.java b/modules/world/palette/src/classes/org/jdesktop/wonderland/modules/palette/client/HUDCellPalette.java
index c2cabe8ad..c249b40db 100644
--- a/modules/world/palette/src/classes/org/jdesktop/wonderland/modules/palette/client/HUDCellPalette.java
+++ b/modules/world/palette/src/classes/org/jdesktop/wonderland/modules/palette/client/HUDCellPalette.java
@@ -1,329 +1,329 @@
/**
* Project Wonderland
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., All Rights Reserved
*
* Redistributions in source code form must reproduce the above
* copyright and this condition.
*
* The contents of this file are subject to the GNU General Public
* License, Version 2 (the "License"); you may not use this file
* except in compliance with the License. A copy of the License is
* available at http://www.opensource.org/licenses/gpl-license.php.
*
* Sun designates this particular file as subject to the "Classpath"
* exception as provided by Sun in the License file that accompanied
* this code.
*/
package org.jdesktop.wonderland.modules.palette.client;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.datatransfer.Transferable;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.SwingUtilities;
import javax.swing.TransferHandler;
import org.jdesktop.wonderland.client.cell.registry.CellRegistry;
import org.jdesktop.wonderland.client.cell.registry.CellRegistry.CellRegistryListener;
import org.jdesktop.wonderland.client.cell.registry.spi.CellFactorySPI;
import org.jdesktop.wonderland.modules.palette.client.dnd.CellServerStateTransferable;
/**
* A palette of cells to create in the world by drag and drop, as a HUD panel.
*
* @author Jordan Slott <[email protected]>
* @author nsimpson
*/
public class HUDCellPalette extends javax.swing.JPanel {
private Map<String, CellFactorySPI> cellFactoryMap = new HashMap();
private List<Image> imageList;
private DefaultListModel model;
private Image noPreviewAvailableImage = null;
private CellRegistryListener cellListener = null;
private static final int SIZE = 48;
public HUDCellPalette() {
initComponents();
imageList = new ArrayList();
model = new DefaultListModel();
componentList.setModel(model);
componentList.setCellRenderer(new ListImageRenderer());
componentList.setDragEnabled(true);
// Create a generic image for cells that don't have a preview image
URL url = CellPalette.class.getResource("resources/nopreview128x128.png");
noPreviewAvailableImage = Toolkit.getDefaultToolkit().createImage(url);
componentList.setTransferHandler(new ListTransferHandler());
// Create a listener for changes to the list of registered Cell
// factories, to be used in setVisible(). When the list changes we
// simply do a fresh update of all values.
cellListener = new CellRegistryListener() {
public void cellRegistryChanged() {
// Since this is not happening (necessarily) in the AWT Event
// Thread, we should put it in one
SwingUtilities.invokeLater(new Runnable() {
public void run() {
updatePanelIcons();
}
});
}
};
CellRegistry.getCellRegistry().addCellRegistryListener(cellListener);
updatePanelIcons();
}
public class ListTransferHandler extends TransferHandler {
/**
* {@inheritDoc}
*/
@Override
public boolean canImport(TransferHandler.TransferSupport info) {
// the cell palette doesn't support import
return false;
}
/**
* {@inheritDoc}
*/
@Override
protected Transferable createTransferable(JComponent c) {
CellFactorySPI factory = cellFactoryMap.get((String) componentList.getSelectedValue());
return new CellServerStateTransferable(factory);
}
/**
* {@inheritDoc}
*/
@Override
public int getSourceActions(JComponent c) {
// only support copying
return TransferHandler.COPY;
}
/**
* {@inheritDoc}
*/
@Override
public Icon getVisualRepresentation(Transferable t) {
Image image = imageList.get(componentList.getSelectedIndex());
ImageIcon icon = new ImageIcon(image);
return (Icon) image;
}
}
public class ListImageRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean hasFocus) {
JLabel label = (JLabel) super.getListCellRendererComponent(list,
value, index, isSelected, hasFocus);
Image icon = imageList.get(index);
label.setIcon(new ImageIcon(icon));
label.setText("");
label.setTransferHandler(new ListTransferHandler());
// // Set up the drag and drop support for the image
// DragSource ds = DragSource.getDefaultDragSource();
// PaletteDragGestureListener listener = new PaletteDragGestureListener();
// listener.previewImage = icon;
// listener.cellFactory = cellFactoryMap.get((String)value);
// ds.createDefaultDragGestureRecognizer(componentList,
// DnDConstants.ACTION_COPY, listener);
return (label);
}
}
/**
* Updates the list of values displayed from the CellRegistry.
*
* NOTE: This method assumes it is being called in the AWT Event Thread.
*/
public void updatePanelIcons() {
// We synchronized around the cellFactoryMap so that this action does not
// interfere with any changes in the map.
synchronized (cellFactoryMap) {
// First remove all of the entries in the map and the panel
cellFactoryMap.clear();
model.clear();
componentList.removeAll();
imageList.clear();
// Fetch the registry of cells and for each, get the palette info and
// populate the list.
CellRegistry registry = CellRegistry.getCellRegistry();
Set<CellFactorySPI> cellFactories = registry.getAllCellFactories();
for (CellFactorySPI cellFactory : cellFactories) {
try {
// We only add the entry if it has a non-null display name.
// Fetch the preview image (use the default if none exists
// and add to the panel
String name = cellFactory.getDisplayName();
Image preview = cellFactory.getPreviewImage();
if (name != null) {
model.addElement(name);
cellFactoryMap.put(name, cellFactory);
// Store the image for the list renderer
Image image = createScaledImage(preview, name, SIZE);
imageList.add(image);
}
} catch (java.lang.Exception excp) {
// Just ignore, but log a message
Logger logger = Logger.getLogger(CellPalette.class.getName());
logger.log(Level.WARNING, "No Display Name for Cell Factory " +
cellFactory, excp);
}
}
componentList.invalidate();
}
}
/**
* Creates a new label given the Image, the cell name, and the size to make
* it.
*/
private Image createScaledImage(Image image, String displayName, int size) {
ImageIcon srcImage;
boolean label = false;
if (image == null) {
// If the preview image is null, then use the default one
srcImage = new ImageIcon(noPreviewAvailableImage);
label = true;
} else {
srcImage = new ImageIcon(image);
}
// First resize the image. We use a trick to fetch the BufferedImage
// from the given Image, by creating the ImageIcon and calling the
// getImage() method. Then resize into a Buffered Image.
BufferedImage resizedImage = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = resizedImage.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(srcImage.getImage(), 0, 0, size, size, null);
g2.dispose();
if (label) {
labelImage(resizedImage, displayName);
}
return resizedImage;
}
private Image labelImage(BufferedImage image, String label) {
if (label != null) {
Graphics2D g2 = image.createGraphics();
String[] words = label.split(" ");
// find the longest word
String longest = "";
for (int i = 0; i < words.length; i++) {
if (words[i].length() > longest.length()) {
longest = words[i];
}
}
int rowGap = 3;
int x;
int y = rowGap;
int iw = image.getWidth();
int ih = image.getHeight();
int fontSize = 10;
Font font = new Font("SansSerif", Font.BOLD, fontSize);
FontMetrics metrics = g2.getFontMetrics(font);
// find the font required to fit the longest word in the width of
// the image
while (!(metrics.getStringBounds(longest, g2).getWidth() < iw - 2) &&
fontSize > 5) {
fontSize--;
font = new Font("SansSerif", Font.BOLD, fontSize);
metrics = g2.getFontMetrics(font);
}
g2.setFont(font);
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
- RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);
+ RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2.setColor(Color.DARK_GRAY);
Rectangle2D maxBounds = metrics.getMaxCharBounds(g2);
int wh = (int) maxBounds.getHeight();
// draw each word in order from top to bottom, centered in row
for (int i = 0; i < words.length; i++) {
Rectangle2D stringBounds = metrics.getStringBounds(words[i], g2);
x = (int) (iw / 2 - stringBounds.getWidth() / 2);
g2.drawString(words[i], x, y + wh);
y += wh + rowGap;
}
g2.dispose();
}
return image;
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
componentScrollPane = new javax.swing.JScrollPane();
componentList = new javax.swing.JList();
setPreferredSize(new java.awt.Dimension(530, 75));
setLayout(new javax.swing.BoxLayout(this, javax.swing.BoxLayout.LINE_AXIS));
componentScrollPane.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
componentList.setBackground(new java.awt.Color(0, 0, 0));
componentList.setDragEnabled(true);
componentList.setLayoutOrientation(javax.swing.JList.HORIZONTAL_WRAP);
componentList.setVisibleRowCount(1);
componentScrollPane.setViewportView(componentList);
add(componentScrollPane);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JList componentList;
private javax.swing.JScrollPane componentScrollPane;
// End of variables declaration//GEN-END:variables
}
| true | true | private Image labelImage(BufferedImage image, String label) {
if (label != null) {
Graphics2D g2 = image.createGraphics();
String[] words = label.split(" ");
// find the longest word
String longest = "";
for (int i = 0; i < words.length; i++) {
if (words[i].length() > longest.length()) {
longest = words[i];
}
}
int rowGap = 3;
int x;
int y = rowGap;
int iw = image.getWidth();
int ih = image.getHeight();
int fontSize = 10;
Font font = new Font("SansSerif", Font.BOLD, fontSize);
FontMetrics metrics = g2.getFontMetrics(font);
// find the font required to fit the longest word in the width of
// the image
while (!(metrics.getStringBounds(longest, g2).getWidth() < iw - 2) &&
fontSize > 5) {
fontSize--;
font = new Font("SansSerif", Font.BOLD, fontSize);
metrics = g2.getFontMetrics(font);
}
g2.setFont(font);
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);
g2.setColor(Color.DARK_GRAY);
Rectangle2D maxBounds = metrics.getMaxCharBounds(g2);
int wh = (int) maxBounds.getHeight();
// draw each word in order from top to bottom, centered in row
for (int i = 0; i < words.length; i++) {
Rectangle2D stringBounds = metrics.getStringBounds(words[i], g2);
x = (int) (iw / 2 - stringBounds.getWidth() / 2);
g2.drawString(words[i], x, y + wh);
y += wh + rowGap;
}
g2.dispose();
}
return image;
}
| private Image labelImage(BufferedImage image, String label) {
if (label != null) {
Graphics2D g2 = image.createGraphics();
String[] words = label.split(" ");
// find the longest word
String longest = "";
for (int i = 0; i < words.length; i++) {
if (words[i].length() > longest.length()) {
longest = words[i];
}
}
int rowGap = 3;
int x;
int y = rowGap;
int iw = image.getWidth();
int ih = image.getHeight();
int fontSize = 10;
Font font = new Font("SansSerif", Font.BOLD, fontSize);
FontMetrics metrics = g2.getFontMetrics(font);
// find the font required to fit the longest word in the width of
// the image
while (!(metrics.getStringBounds(longest, g2).getWidth() < iw - 2) &&
fontSize > 5) {
fontSize--;
font = new Font("SansSerif", Font.BOLD, fontSize);
metrics = g2.getFontMetrics(font);
}
g2.setFont(font);
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2.setColor(Color.DARK_GRAY);
Rectangle2D maxBounds = metrics.getMaxCharBounds(g2);
int wh = (int) maxBounds.getHeight();
// draw each word in order from top to bottom, centered in row
for (int i = 0; i < words.length; i++) {
Rectangle2D stringBounds = metrics.getStringBounds(words[i], g2);
x = (int) (iw / 2 - stringBounds.getWidth() / 2);
g2.drawString(words[i], x, y + wh);
y += wh + rowGap;
}
g2.dispose();
}
return image;
}
|
diff --git a/kundera-rest/src/test/java/com/impetus/kundera/rest/resources/CRUDResourceTest.java b/kundera-rest/src/test/java/com/impetus/kundera/rest/resources/CRUDResourceTest.java
index c0bf2481f..518d81e5e 100644
--- a/kundera-rest/src/test/java/com/impetus/kundera/rest/resources/CRUDResourceTest.java
+++ b/kundera-rest/src/test/java/com/impetus/kundera/rest/resources/CRUDResourceTest.java
@@ -1,211 +1,211 @@
/*******************************************************************************
* * Copyright 2012 Impetus Infotech.
* *
* * 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.impetus.kundera.rest.resources;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.core.MediaType;
import junit.framework.Assert;
import org.apache.cassandra.thrift.CfDef;
import org.apache.cassandra.thrift.InvalidRequestException;
import org.apache.cassandra.thrift.KsDef;
import org.apache.cassandra.thrift.NotFoundException;
import org.apache.cassandra.thrift.SchemaDisagreementException;
import org.apache.cassandra.thrift.TimedOutException;
import org.apache.cassandra.thrift.UnavailableException;
import org.apache.thrift.TException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.impetus.kundera.rest.common.CassandraCli;
import com.impetus.kundera.rest.dao.RESTClient;
import com.impetus.kundera.rest.dao.RESTClientImpl;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.test.framework.JerseyTest;
/**
* Test case for {@link CRUDResource}
* @author amresh
*
*/
public class CRUDResourceTest extends JerseyTest
{
String mediaType = MediaType.APPLICATION_XML;
RESTClient restClient;
String applicationToken = null;
String sessionToken = null;
String bookStr1;
String bookStr2;
String pk1;
String pk2;
public CRUDResourceTest() throws Exception
{
super("com.impetus.kundera.rest.resources");
}
@Before
public void setup() throws Exception
{
CassandraCli.cassandraSetUp();
CassandraCli.createKeySpace("KunderaExamples");
loadData();
}
@After
public void tearDown() throws Exception
{
super.tearDown();
CassandraCli.dropKeySpace("KunderaExamples");
}
@Test
public void testCRUD()
{
WebResource webResource = resource();
if (MediaType.APPLICATION_XML.equals(mediaType))
{
bookStr1 = "<book><isbn>1111111111111</isbn><author>Amresh</author><publication>Willey</publication></book>";
bookStr2 = "<book><isbn>2222222222222</isbn><author>Vivek</author><publication>OReilly</publication></book>";
pk1 = "1111111111111";
pk2 = "2222222222222";
}
else if (MediaType.APPLICATION_JSON.equals(mediaType))
{
bookStr1 = "{book:{\"isbn\":\"1111111111111\",\"author\":\"Amresh\", \"publication\":\"Willey\"}}";
bookStr2 = "{book:{\"isbn\":\"2222222222222\",\"author\":\"Vivek\", \"publication\":\"Oreilly\"}}";
pk1 = "1111111111111";
pk2 = "2222222222222";
}
else
{
Assert.fail("Incorrect Media Type:" + mediaType);
return;
}
RESTClient restClient = new RESTClientImpl();
// Initialize REST Client
restClient.initialize(webResource, mediaType);
// Get Application Token
applicationToken = restClient.getApplicationToken();
Assert.assertNotNull(applicationToken);
Assert.assertTrue(applicationToken.startsWith("AT_"));
// Get Session Token
sessionToken = restClient.getSessionToken(applicationToken);
Assert.assertNotNull(sessionToken);
- Assert.assertTrue(applicationToken.startsWith("ST_"));
+ Assert.assertTrue(sessionToken.startsWith("ST_"));
// Insert Record
restClient.insertBook(sessionToken, bookStr1);
restClient.insertBook(sessionToken, bookStr2);
// Find Record
String foundBook = restClient.findBook(sessionToken, pk1);
Assert.assertNotNull(foundBook);
if (MediaType.APPLICATION_JSON.equals(mediaType))
{
foundBook = "{book:" + foundBook + "}";
}
// Update Record
String updatedBook = restClient.updateBook(sessionToken, foundBook);
Assert.assertNotNull(updatedBook);
// Get All Books
// String allBooks = restClient.getAllBooks(sessionToken);
// Delete Records
restClient.deleteBook(sessionToken, updatedBook, pk1);
restClient.deleteBook(sessionToken, updatedBook, pk2);
// Close Session
restClient.closeSession(sessionToken);
// Close Application
restClient.closeApplication(applicationToken);
}
/**
* Load cassandra specific data.
*
* @throws TException
* the t exception
* @throws InvalidRequestException
* the invalid request exception
* @throws UnavailableException
* the unavailable exception
* @throws TimedOutException
* the timed out exception
* @throws SchemaDisagreementException
* the schema disagreement exception
*/
private void loadData() throws TException, InvalidRequestException, UnavailableException, TimedOutException,
SchemaDisagreementException
{
KsDef ksDef = null;
CfDef user_Def = new CfDef();
user_Def.name = "BOOK";
user_Def.keyspace = "KunderaExamples";
user_Def.setComparator_type("UTF8Type");
user_Def.setDefault_validation_class("UTF8Type");
List<CfDef> cfDefs = new ArrayList<CfDef>();
cfDefs.add(user_Def);
try
{
ksDef = CassandraCli.client.describe_keyspace("KunderaExamples");
CassandraCli.client.set_keyspace("KunderaExamples");
List<CfDef> cfDefn = ksDef.getCf_defs();
for (CfDef cfDef1 : cfDefn)
{
if (cfDef1.getName().equalsIgnoreCase("BOOK"))
{
CassandraCli.client.system_drop_column_family("BOOK");
}
}
CassandraCli.client.system_add_column_family(user_Def);
}
catch (NotFoundException e)
{
ksDef = new KsDef("KunderaExamples", "org.apache.cassandra.locator.SimpleStrategy", cfDefs);
ksDef.setReplication_factor(1);
CassandraCli.client.system_add_keyspace(ksDef);
}
CassandraCli.client.set_keyspace("KunderaExamples");
}
}
| true | true | public void testCRUD()
{
WebResource webResource = resource();
if (MediaType.APPLICATION_XML.equals(mediaType))
{
bookStr1 = "<book><isbn>1111111111111</isbn><author>Amresh</author><publication>Willey</publication></book>";
bookStr2 = "<book><isbn>2222222222222</isbn><author>Vivek</author><publication>OReilly</publication></book>";
pk1 = "1111111111111";
pk2 = "2222222222222";
}
else if (MediaType.APPLICATION_JSON.equals(mediaType))
{
bookStr1 = "{book:{\"isbn\":\"1111111111111\",\"author\":\"Amresh\", \"publication\":\"Willey\"}}";
bookStr2 = "{book:{\"isbn\":\"2222222222222\",\"author\":\"Vivek\", \"publication\":\"Oreilly\"}}";
pk1 = "1111111111111";
pk2 = "2222222222222";
}
else
{
Assert.fail("Incorrect Media Type:" + mediaType);
return;
}
RESTClient restClient = new RESTClientImpl();
// Initialize REST Client
restClient.initialize(webResource, mediaType);
// Get Application Token
applicationToken = restClient.getApplicationToken();
Assert.assertNotNull(applicationToken);
Assert.assertTrue(applicationToken.startsWith("AT_"));
// Get Session Token
sessionToken = restClient.getSessionToken(applicationToken);
Assert.assertNotNull(sessionToken);
Assert.assertTrue(applicationToken.startsWith("ST_"));
// Insert Record
restClient.insertBook(sessionToken, bookStr1);
restClient.insertBook(sessionToken, bookStr2);
// Find Record
String foundBook = restClient.findBook(sessionToken, pk1);
Assert.assertNotNull(foundBook);
if (MediaType.APPLICATION_JSON.equals(mediaType))
{
foundBook = "{book:" + foundBook + "}";
}
// Update Record
String updatedBook = restClient.updateBook(sessionToken, foundBook);
Assert.assertNotNull(updatedBook);
// Get All Books
// String allBooks = restClient.getAllBooks(sessionToken);
// Delete Records
restClient.deleteBook(sessionToken, updatedBook, pk1);
restClient.deleteBook(sessionToken, updatedBook, pk2);
// Close Session
restClient.closeSession(sessionToken);
// Close Application
restClient.closeApplication(applicationToken);
}
| public void testCRUD()
{
WebResource webResource = resource();
if (MediaType.APPLICATION_XML.equals(mediaType))
{
bookStr1 = "<book><isbn>1111111111111</isbn><author>Amresh</author><publication>Willey</publication></book>";
bookStr2 = "<book><isbn>2222222222222</isbn><author>Vivek</author><publication>OReilly</publication></book>";
pk1 = "1111111111111";
pk2 = "2222222222222";
}
else if (MediaType.APPLICATION_JSON.equals(mediaType))
{
bookStr1 = "{book:{\"isbn\":\"1111111111111\",\"author\":\"Amresh\", \"publication\":\"Willey\"}}";
bookStr2 = "{book:{\"isbn\":\"2222222222222\",\"author\":\"Vivek\", \"publication\":\"Oreilly\"}}";
pk1 = "1111111111111";
pk2 = "2222222222222";
}
else
{
Assert.fail("Incorrect Media Type:" + mediaType);
return;
}
RESTClient restClient = new RESTClientImpl();
// Initialize REST Client
restClient.initialize(webResource, mediaType);
// Get Application Token
applicationToken = restClient.getApplicationToken();
Assert.assertNotNull(applicationToken);
Assert.assertTrue(applicationToken.startsWith("AT_"));
// Get Session Token
sessionToken = restClient.getSessionToken(applicationToken);
Assert.assertNotNull(sessionToken);
Assert.assertTrue(sessionToken.startsWith("ST_"));
// Insert Record
restClient.insertBook(sessionToken, bookStr1);
restClient.insertBook(sessionToken, bookStr2);
// Find Record
String foundBook = restClient.findBook(sessionToken, pk1);
Assert.assertNotNull(foundBook);
if (MediaType.APPLICATION_JSON.equals(mediaType))
{
foundBook = "{book:" + foundBook + "}";
}
// Update Record
String updatedBook = restClient.updateBook(sessionToken, foundBook);
Assert.assertNotNull(updatedBook);
// Get All Books
// String allBooks = restClient.getAllBooks(sessionToken);
// Delete Records
restClient.deleteBook(sessionToken, updatedBook, pk1);
restClient.deleteBook(sessionToken, updatedBook, pk2);
// Close Session
restClient.closeSession(sessionToken);
// Close Application
restClient.closeApplication(applicationToken);
}
|
diff --git a/src/org/meta_environment/rascal/interpreter/Evaluator.java b/src/org/meta_environment/rascal/interpreter/Evaluator.java
index 39c30a9914..a544474584 100644
--- a/src/org/meta_environment/rascal/interpreter/Evaluator.java
+++ b/src/org/meta_environment/rascal/interpreter/Evaluator.java
@@ -1,3561 +1,3561 @@
package org.meta_environment.rascal.interpreter;
import static org.meta_environment.rascal.interpreter.result.ResultFactory.makeResult;
import static org.meta_environment.rascal.interpreter.result.ResultFactory.nothing;
import static org.meta_environment.rascal.interpreter.utils.Utils.unescape;
import java.io.IOException;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Stack;
import java.util.Map.Entry;
import org.eclipse.imp.pdb.facts.IConstructor;
import org.eclipse.imp.pdb.facts.IInteger;
import org.eclipse.imp.pdb.facts.IList;
import org.eclipse.imp.pdb.facts.IListWriter;
import org.eclipse.imp.pdb.facts.IMap;
import org.eclipse.imp.pdb.facts.IMapWriter;
import org.eclipse.imp.pdb.facts.INode;
import org.eclipse.imp.pdb.facts.IRelation;
import org.eclipse.imp.pdb.facts.ISet;
import org.eclipse.imp.pdb.facts.ISetWriter;
import org.eclipse.imp.pdb.facts.ISourceLocation;
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.IValueFactory;
import org.eclipse.imp.pdb.facts.IWriter;
import org.eclipse.imp.pdb.facts.exceptions.UndeclaredFieldException;
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.meta_environment.rascal.ast.AbstractAST;
import org.meta_environment.rascal.ast.Bound;
import org.meta_environment.rascal.ast.Case;
import org.meta_environment.rascal.ast.Catch;
import org.meta_environment.rascal.ast.Declaration;
import org.meta_environment.rascal.ast.Declarator;
import org.meta_environment.rascal.ast.Expression;
import org.meta_environment.rascal.ast.Field;
import org.meta_environment.rascal.ast.FunctionDeclaration;
import org.meta_environment.rascal.ast.FunctionModifier;
import org.meta_environment.rascal.ast.Import;
import org.meta_environment.rascal.ast.Module;
import org.meta_environment.rascal.ast.Name;
import org.meta_environment.rascal.ast.NullASTVisitor;
import org.meta_environment.rascal.ast.QualifiedName;
import org.meta_environment.rascal.ast.Replacement;
import org.meta_environment.rascal.ast.Statement;
import org.meta_environment.rascal.ast.Strategy;
import org.meta_environment.rascal.ast.StringLiteral;
import org.meta_environment.rascal.ast.Tags;
import org.meta_environment.rascal.ast.Toplevel;
import org.meta_environment.rascal.ast.Assignable.Constructor;
import org.meta_environment.rascal.ast.Assignable.FieldAccess;
import org.meta_environment.rascal.ast.Declaration.Alias;
import org.meta_environment.rascal.ast.Declaration.Annotation;
import org.meta_environment.rascal.ast.Declaration.Data;
import org.meta_environment.rascal.ast.Declaration.Function;
import org.meta_environment.rascal.ast.Declaration.Rule;
import org.meta_environment.rascal.ast.Declaration.Tag;
import org.meta_environment.rascal.ast.Declaration.Variable;
import org.meta_environment.rascal.ast.Declaration.View;
import org.meta_environment.rascal.ast.Expression.Addition;
import org.meta_environment.rascal.ast.Expression.All;
import org.meta_environment.rascal.ast.Expression.Ambiguity;
import org.meta_environment.rascal.ast.Expression.And;
import org.meta_environment.rascal.ast.Expression.Any;
import org.meta_environment.rascal.ast.Expression.Bracket;
import org.meta_environment.rascal.ast.Expression.CallOrTree;
import org.meta_environment.rascal.ast.Expression.Closure;
import org.meta_environment.rascal.ast.Expression.Composition;
import org.meta_environment.rascal.ast.Expression.Comprehension;
import org.meta_environment.rascal.ast.Expression.Division;
import org.meta_environment.rascal.ast.Expression.EnumeratorWithStrategy;
import org.meta_environment.rascal.ast.Expression.Equivalence;
import org.meta_environment.rascal.ast.Expression.FieldProject;
import org.meta_environment.rascal.ast.Expression.FieldUpdate;
import org.meta_environment.rascal.ast.Expression.GreaterThan;
import org.meta_environment.rascal.ast.Expression.GreaterThanOrEq;
import org.meta_environment.rascal.ast.Expression.IfDefinedOtherwise;
import org.meta_environment.rascal.ast.Expression.Implication;
import org.meta_environment.rascal.ast.Expression.In;
import org.meta_environment.rascal.ast.Expression.Intersection;
import org.meta_environment.rascal.ast.Expression.IsDefined;
import org.meta_environment.rascal.ast.Expression.Join;
import org.meta_environment.rascal.ast.Expression.LessThan;
import org.meta_environment.rascal.ast.Expression.LessThanOrEq;
import org.meta_environment.rascal.ast.Expression.Lexical;
import org.meta_environment.rascal.ast.Expression.List;
import org.meta_environment.rascal.ast.Expression.Literal;
import org.meta_environment.rascal.ast.Expression.Location;
import org.meta_environment.rascal.ast.Expression.Match;
import org.meta_environment.rascal.ast.Expression.Modulo;
import org.meta_environment.rascal.ast.Expression.Negation;
import org.meta_environment.rascal.ast.Expression.Negative;
import org.meta_environment.rascal.ast.Expression.NoMatch;
import org.meta_environment.rascal.ast.Expression.NonEmptyBlock;
import org.meta_environment.rascal.ast.Expression.NotIn;
import org.meta_environment.rascal.ast.Expression.OperatorAsValue;
import org.meta_environment.rascal.ast.Expression.Or;
import org.meta_environment.rascal.ast.Expression.Product;
import org.meta_environment.rascal.ast.Expression.Range;
import org.meta_environment.rascal.ast.Expression.Set;
import org.meta_environment.rascal.ast.Expression.StepRange;
import org.meta_environment.rascal.ast.Expression.Subscript;
import org.meta_environment.rascal.ast.Expression.Subtraction;
import org.meta_environment.rascal.ast.Expression.TransitiveClosure;
import org.meta_environment.rascal.ast.Expression.TransitiveReflexiveClosure;
import org.meta_environment.rascal.ast.Expression.Tuple;
import org.meta_environment.rascal.ast.Expression.TypedVariable;
import org.meta_environment.rascal.ast.Expression.Visit;
import org.meta_environment.rascal.ast.Expression.VoidClosure;
import org.meta_environment.rascal.ast.FunctionDeclaration.Abstract;
import org.meta_environment.rascal.ast.Header.Parameters;
import org.meta_environment.rascal.ast.IntegerLiteral.DecimalIntegerLiteral;
import org.meta_environment.rascal.ast.Literal.Boolean;
import org.meta_environment.rascal.ast.Literal.Integer;
import org.meta_environment.rascal.ast.Literal.Real;
import org.meta_environment.rascal.ast.LocalVariableDeclaration.Default;
import org.meta_environment.rascal.ast.PatternWithAction.Arbitrary;
import org.meta_environment.rascal.ast.PatternWithAction.Replacing;
import org.meta_environment.rascal.ast.Statement.Assert;
import org.meta_environment.rascal.ast.Statement.AssertWithMessage;
import org.meta_environment.rascal.ast.Statement.Assignment;
import org.meta_environment.rascal.ast.Statement.Block;
import org.meta_environment.rascal.ast.Statement.Break;
import org.meta_environment.rascal.ast.Statement.Continue;
import org.meta_environment.rascal.ast.Statement.DoWhile;
import org.meta_environment.rascal.ast.Statement.EmptyStatement;
import org.meta_environment.rascal.ast.Statement.Fail;
import org.meta_environment.rascal.ast.Statement.For;
import org.meta_environment.rascal.ast.Statement.GlobalDirective;
import org.meta_environment.rascal.ast.Statement.IfThen;
import org.meta_environment.rascal.ast.Statement.IfThenElse;
import org.meta_environment.rascal.ast.Statement.Insert;
import org.meta_environment.rascal.ast.Statement.Solve;
import org.meta_environment.rascal.ast.Statement.Switch;
import org.meta_environment.rascal.ast.Statement.Throw;
import org.meta_environment.rascal.ast.Statement.Try;
import org.meta_environment.rascal.ast.Statement.TryFinally;
import org.meta_environment.rascal.ast.Statement.VariableDeclaration;
import org.meta_environment.rascal.ast.Statement.While;
import org.meta_environment.rascal.ast.Toplevel.DefaultVisibility;
import org.meta_environment.rascal.ast.Toplevel.GivenVisibility;
import org.meta_environment.rascal.ast.Visit.DefaultStrategy;
import org.meta_environment.rascal.ast.Visit.GivenStrategy;
import org.meta_environment.rascal.interpreter.asserts.Ambiguous;
import org.meta_environment.rascal.interpreter.asserts.ImplementationError;
import org.meta_environment.rascal.interpreter.asserts.NotYetImplemented;
import org.meta_environment.rascal.interpreter.control_exceptions.Failure;
import org.meta_environment.rascal.interpreter.control_exceptions.Return;
import org.meta_environment.rascal.interpreter.env.ConcreteSyntaxType;
import org.meta_environment.rascal.interpreter.env.Environment;
import org.meta_environment.rascal.interpreter.env.FileParserFunction;
import org.meta_environment.rascal.interpreter.env.GlobalEnvironment;
import org.meta_environment.rascal.interpreter.env.JavaFunction;
import org.meta_environment.rascal.interpreter.env.Lambda;
import org.meta_environment.rascal.interpreter.env.ModuleEnvironment;
import org.meta_environment.rascal.interpreter.env.ParserFunction;
import org.meta_environment.rascal.interpreter.env.RascalFunction;
import org.meta_environment.rascal.interpreter.env.RewriteRule;
import org.meta_environment.rascal.interpreter.load.FromCurrentWorkingDirectoryLoader;
import org.meta_environment.rascal.interpreter.load.FromResourceLoader;
import org.meta_environment.rascal.interpreter.load.IModuleFileLoader;
import org.meta_environment.rascal.interpreter.load.ISdfSearchPathContributor;
import org.meta_environment.rascal.interpreter.load.ModuleLoader;
import org.meta_environment.rascal.interpreter.matching.IBooleanResult;
import org.meta_environment.rascal.interpreter.matching.IMatchingResult;
import org.meta_environment.rascal.interpreter.matching.LiteralPattern;
import org.meta_environment.rascal.interpreter.matching.RegExpPatternValue;
import org.meta_environment.rascal.interpreter.result.BoolResult;
import org.meta_environment.rascal.interpreter.result.ConcreteSyntaxResult;
import org.meta_environment.rascal.interpreter.result.Result;
import org.meta_environment.rascal.interpreter.result.ResultFactory;
import org.meta_environment.rascal.interpreter.staticErrors.AmbiguousConcretePattern;
import org.meta_environment.rascal.interpreter.staticErrors.MissingModifierError;
import org.meta_environment.rascal.interpreter.staticErrors.ModuleNameMismatchError;
import org.meta_environment.rascal.interpreter.staticErrors.NonWellformedTypeError;
import org.meta_environment.rascal.interpreter.staticErrors.RedeclaredVariableError;
import org.meta_environment.rascal.interpreter.staticErrors.SyntaxError;
import org.meta_environment.rascal.interpreter.staticErrors.UndeclaredAnnotationError;
import org.meta_environment.rascal.interpreter.staticErrors.UndeclaredFieldError;
import org.meta_environment.rascal.interpreter.staticErrors.UndeclaredFunctionError;
import org.meta_environment.rascal.interpreter.staticErrors.UndeclaredModuleError;
import org.meta_environment.rascal.interpreter.staticErrors.UnexpectedTypeError;
import org.meta_environment.rascal.interpreter.staticErrors.UnguardedFailError;
import org.meta_environment.rascal.interpreter.staticErrors.UnguardedInsertError;
import org.meta_environment.rascal.interpreter.staticErrors.UnguardedReturnError;
import org.meta_environment.rascal.interpreter.staticErrors.UninitializedVariableError;
import org.meta_environment.rascal.interpreter.staticErrors.UnsupportedOperationError;
import org.meta_environment.rascal.interpreter.utils.JavaBridge;
import org.meta_environment.rascal.interpreter.utils.Names;
import org.meta_environment.rascal.interpreter.utils.Profiler;
import org.meta_environment.rascal.interpreter.utils.RuntimeExceptionFactory;
import org.meta_environment.rascal.interpreter.utils.Symbols;
import org.meta_environment.rascal.parser.ModuleParser;
import org.meta_environment.uptr.Factory;
import org.meta_environment.uptr.SymbolAdapter;
import org.meta_environment.uptr.TreeAdapter;
@SuppressWarnings("unchecked")
public class Evaluator extends NullASTVisitor<Result<IValue>> {
public final IValueFactory vf;
public final TypeFactory tf = TypeFactory.getInstance();
private final TypeEvaluator te = TypeEvaluator.getInstance();
protected Environment currentEnvt;
protected final GlobalEnvironment heap;
private final JavaBridge javaBridge;
// private final boolean LAZY = false;
protected boolean importResetsInterpreter = true;
enum DIRECTION {BottomUp, TopDown} // Parameters for traversing trees
enum FIXEDPOINT {Yes, No}
enum PROGRESS {Continuing, Breaking}
private AbstractAST currentAST; // used in runtime errormessages
private Profiler profiler;
private boolean doProfiling = false;
private TypeDeclarationEvaluator typeDeclarator = new TypeDeclarationEvaluator();
protected final ModuleLoader loader;
private java.util.List<ClassLoader> classLoaders;
protected ModuleEnvironment rootScope;
private boolean concreteListsShouldBeSpliced;
public Evaluator(IValueFactory f, Writer errorWriter, ModuleEnvironment scope) {
this(f, errorWriter, scope, new GlobalEnvironment());
}
public Evaluator(IValueFactory f, Writer errorWriter, ModuleEnvironment scope, GlobalEnvironment heap) {
this(f, errorWriter, scope, new GlobalEnvironment(), new ModuleParser());
}
public Evaluator(IValueFactory f, Writer errorWriter, ModuleEnvironment scope, GlobalEnvironment heap, ModuleParser parser) {
this.vf = f;
this.heap = heap;
currentEnvt = scope;
rootScope = scope;
heap.addModule(scope);
this.classLoaders = new LinkedList<ClassLoader>();
this.javaBridge = new JavaBridge(errorWriter, classLoaders);
loader = new ModuleLoader(parser);
parser.setLoader(loader);
// cwd loader
loader.addFileLoader(new FromCurrentWorkingDirectoryLoader());
// library
loader.addFileLoader(new FromResourceLoader(this.getClass(), "StandardLibrary"));
// everything rooted at the src directory
loader.addFileLoader(new FromResourceLoader(this.getClass()));
// add current wd and sdf-library to search path for SDF modules
loader.addSdfSearchPathContributor(new ISdfSearchPathContributor() {
public java.util.List<String> contributePaths() {
java.util.List<String> result = new LinkedList<String>();
//System.err.println("getproperty user.dir: " + System.getProperty("user.dir"));
result.add(System.getProperty("user.dir"));
result.add(Configuration.getSdfLibraryPathProperty());
return result;
}
});
// load Java classes from the current jar (for the standard library)
classLoaders.add(getClass().getClassLoader());
}
// public IConstructor parseCommand(String command, String fileName) throws IOException {
// return loader.parseCommand(command, fileName);
// }
/**
* In interactive mode this flag should be set to true, such that re-importing
* a module causes a re-initialization.
*/
public void setImportResetsInterpreter(boolean flag) {
this.importResetsInterpreter = flag;
}
private void checkPoint(Environment env) {
env.checkPoint();
}
private void rollback(Environment env) {
env.rollback();
}
private void commit(Environment env) {
env.commit();
}
public void setCurrentAST(AbstractAST currentAST) {
this.currentAST = currentAST;
}
public AbstractAST getCurrentAST() {
return currentAST;
}
public void addModuleLoader(IModuleFileLoader fileLoader) {
loader.addFileLoader(fileLoader);
}
public void addSdfSearchPathContributor(ISdfSearchPathContributor contrib) {
loader.addSdfSearchPathContributor(contrib);
}
public void addClassLoader(ClassLoader loader) {
// later loaders have precedence
classLoaders.add(0, loader);
}
public String getStackTrace() {
StringBuilder b = new StringBuilder();
Environment env = currentEnvt;
while (env != null) {
ISourceLocation loc = env.getLocation();
String name = env.getName();
if (name != null && loc != null) {
URL url = loc.getURL();
b.append('\t');
b.append(url.getAuthority() + url.getPath() + ":" + loc.getBeginLine() + "," + loc.getBeginColumn() + ": " + name);
b.append('\n');
}
env = env.getParent();
}
return b.toString();
}
/**
* Evaluate a statement
* @param stat
* @return
*/
public Result<IValue> eval(Statement stat) {
try {
if(doProfiling){
profiler = new Profiler(this);
profiler.start();
}
currentAST = stat;
Result<IValue> r = stat.accept(this);
if(r != null){
if(doProfiling){
profiler.pleaseStop();
profiler.report();
}
return r;
}
throw new ImplementationError("Not yet implemented: " + stat.toString());
} catch (Return e){
throw new UnguardedReturnError(stat);
}
catch (Failure e){
throw new UnguardedFailError(stat);
}
catch (org.meta_environment.rascal.interpreter.control_exceptions.Insert e){
throw new UnguardedInsertError(stat);
}
}
/**
* Evaluate an expression
* @param expr
* @return
*/
public Result<IValue> eval(Expression expr) {
currentAST = expr;
Result<IValue> r = expr.accept(this);
if(r != null){
return r;
}
throw new NotYetImplemented(expr.toString());
}
/**
* Evaluate a declaration
* @param declaration
* @return
*/
public Result<IValue> eval(Declaration declaration) {
currentAST = declaration;
Result<IValue> r = declaration.accept(this);
if(r != null){
return r;
}
throw new NotYetImplemented(declaration.toString());
}
/**
* Evaluate an import
* @param imp
* @return
*/
public IValue eval(org.meta_environment.rascal.ast.Import imp) {
currentAST = imp;
Result<IValue> r = imp.accept(this);
if(r != null){
return r.getValue();
}
throw new ImplementationError("Not yet implemented: " + imp.getTree());
}
/* First a number of general utility methods */
/*
* Return an evaluation result that is already in normal form,
* i.e., all potential rules have already been applied to it.
*/
Result<IValue> normalizedResult(Type t, IValue v){
Map<Type, Type> bindings = getCurrentEnvt().getTypeBindings();
Type instance;
if (bindings.size() > 0) {
instance = t.instantiate(getCurrentEnvt().getStore(), bindings);
}
else {
instance = t;
}
if (v != null) {
checkType(v.getType(), instance);
}
return makeResult(instance, v, makeEvContext());
}
private Result<IValue> applyRules(Result<IValue> v) {
//System.err.println("applyRules(" + v + ")");
// we search using the run-time type of a value
Type typeToSearchFor = v.getValue().getType();
if (typeToSearchFor.isAbstractDataType()) {
typeToSearchFor = ((IConstructor) v.getValue()).getConstructorType();
}
java.util.List<RewriteRule> rules = heap.getRules(typeToSearchFor);
if(rules.isEmpty()){
// weird side-effect but it works
declareConcreteSyntaxType(v.getValue());
return v;
}
TraverseResult tr = traverseTop(v, new CasesOrRules(rules));
/* innermost is achieved by repeated applications of applyRules
* when intermediate results are produced.
*/
// weird side-effect but it works
declareConcreteSyntaxType(tr.value.getValue());
return tr.value;
}
private void declareConcreteSyntaxType(IValue value) {
// if somebody constructs a sort, then this implicitly declares
// a corresponding Rascal type.
Type type = value.getType();
if (type == Factory.Symbol) {
IConstructor symbol = (IConstructor) value;
if (symbol.getConstructorType() == Factory.Symbol_Sort) {
Environment root = currentEnvt.getRoot();
root.concreteSyntaxType(new SymbolAdapter(symbol).getName(),
(IConstructor) Factory.Symbol_Cf.make(vf, value));
}
}
}
public Environment pushEnv() {
Environment env = new Environment(getCurrentEnvt(), getCurrentEnvt().getName());
setCurrentEnvt(env);
return env;
}
void unwind(Environment old) {
while (getCurrentEnvt() != old) {
goodPopEnv();
}
}
public Environment goodPushEnv() {
Environment env = new Environment(getCurrentEnvt(), getCurrentEnvt().getName());
setCurrentEnvt(env);
return env;
}
public Environment goodPopEnv() {
setCurrentEnvt(getCurrentEnvt().getParent());
return getCurrentEnvt();
}
public Environment popEnv() {
setCurrentEnvt(getCurrentEnvt().getParent());
return getCurrentEnvt();
}
Environment pushEnv(Statement s) {
/* use the same name as the current envt */
Environment env = new Environment(getCurrentEnvt(), s.getLocation(), getCurrentEnvt().getName());
setCurrentEnvt(env);
return env;
}
Environment goodPushEnv(Statement s) {
/* use the same name as the current envt */
Environment env = new Environment(getCurrentEnvt(), s.getLocation(), getCurrentEnvt().getName());
setCurrentEnvt(env);
return env;
}
private void checkType(Type given, Type expected) {
if (expected == org.meta_environment.rascal.interpreter.env.Lambda.getClosureType()) {
return;
}
if (!given.isSubtypeOf(expected)){
throw new UnexpectedTypeError(expected, given, getCurrentAST());
}
}
public boolean mayOccurIn(Type small, Type large) {
return mayOccurIn(small, large, new HashSet<Type>());
}
boolean mayOccurIn(Type small, Type large, java.util.Set<Type> seen){
if(small.isVoidType())
return true;
if(large.isVoidType())
return false;
if(small.isValueType())
return true;
if(small.isSubtypeOf(large))
return true;
if(large.isListType() || large.isSetType())
return mayOccurIn(small,large.getElementType(), seen);
if(large.isMapType())
return mayOccurIn(small, large.getKeyType(), seen) ||
mayOccurIn(small, large.getValueType(), seen);
if(large.isTupleType()){
for(int i = 0; i < large.getArity(); i++){
if(mayOccurIn(small, large.getFieldType(i), seen))
return true;
}
return false;
}
if(large.isConstructorType()){
for(int i = 0; i < large.getArity(); i++){
if(mayOccurIn(small, large.getFieldType(i), seen))
return true;
}
return false;
}
if(large.isAbstractDataType()){
if(small.isNodeType() && !small.isAbstractDataType())
return true;
if(small.isConstructorType() && small.getAbstractDataType().equivalent(large.getAbstractDataType()))
return true;
seen.add(large);
for(Type alt : getCurrentEnvt().lookupAlternatives(large)){
if(alt.isConstructorType()){
for(int i = 0; i < alt.getArity(); i++){
Type fType = alt.getFieldType(i);
if(seen.add(fType) && mayOccurIn(small, fType, seen))
return true;
}
} else
throw new ImplementationError("ADT");
}
return false;
}
return small.isSubtypeOf(large);
}
// Ambiguity ...................................................
@Override
public Result<IValue> visitExpressionAmbiguity(Ambiguity x) {
// TODO: assuming that that is the only reason for an expression to be ambiguous
// we might also check if this is an "appl" constructor...
// System.err.println("Env: " + currentEnvt);
// int i = 0;
// for (Expression exp: x.getAlternatives()) {
// System.err.println("Alt " + i++ + ": " + exp.getTree());
// }
throw new AmbiguousConcretePattern(x);
}
@Override
public Result<IValue> visitStatementAmbiguity(
org.meta_environment.rascal.ast.Statement.Ambiguity x) {
throw new Ambiguous(x.toString());
}
// Modules -------------------------------------------------------------
@Override
public Result<IValue> visitImportDefault(
org.meta_environment.rascal.ast.Import.Default x) {
// TODO support for full complexity of import declarations
String name = getUnescapedModuleName(x);
// TODO: this logic cannot be understood...
// handleSDFModule only loads the ParseTree module,
// yet the SDF module *will* have been loaded
if (isSDFModule(name)) {
handleSDFModule(x);
return nothing();
}
if (isNonExistingRascalModule(name)) {
evalRascalModule(x, name);
}
else {
reloadAllIfNeeded(x);
}
addImportToCurrentModule(x, name);
return nothing();
}
protected void handleSDFModule(
org.meta_environment.rascal.ast.Import.Default x) {
loadParseTreeModule(x);
getCurrentModuleEnvironment().addSDFImport(getUnescapedModuleName(x));
}
private void addImportToCurrentModule(
org.meta_environment.rascal.ast.Import.Default x, String name) {
getCurrentModuleEnvironment().addImport(name, heap.getModule(name, x));
}
private ModuleEnvironment getCurrentModuleEnvironment() {
if (!(currentEnvt instanceof ModuleEnvironment)) {
throw new ImplementationError("Current env should be a module environment");
}
return ((ModuleEnvironment) currentEnvt);
}
private boolean reloadNeeded() {
return importResetsInterpreter && currentEnvt == rootScope;
}
private String getUnescapedModuleName(
org.meta_environment.rascal.ast.Import.Default x) {
String name = x.getModule().getName().toString();
if (name.startsWith("\\")) {
return name.substring(1);
}
return name;
}
private void loadParseTreeModule(
org.meta_environment.rascal.ast.Import.Default x) {
String parseTreeModName = "ParseTree";
if (!heap.existsModule(parseTreeModName)) {
evalRascalModule(x, parseTreeModName);
}
addImportToCurrentModule(x, parseTreeModName);
}
private boolean isSDFModule(String name) {
return loader.isSdfModule(name);
}
private boolean isNonExistingRascalModule(String name) {
return !heap.existsModule(name) && !isSDFModule(name);
}
protected Module evalRascalModule(AbstractAST x,
String name) {
Module module = loader.loadModule(name, x);
if (module != null) {
if (!getModuleName(module).equals(name)) {
throw new ModuleNameMismatchError(getModuleName(module), name, x);
}
module.accept(this);
return module;
}
return null;
// it was an SDF module
}
protected void reloadAllIfNeeded(AbstractAST cause) {
if (!reloadNeeded()) {
return;
}
heap.clear();
java.util.Set<String> topModules = getCurrentModuleEnvironment().getImports();
for (String mod : topModules) {
Module module = evalRascalModule(cause, mod);
if (module != null) {
getCurrentModuleEnvironment().addImport(mod, heap.getModule(mod, cause));
}
}
}
@Override
public Result<IValue> visitModuleDefault(
org.meta_environment.rascal.ast.Module.Default x) {
String name = getModuleName(x);
if (!heap.existsModule(name)) {
ModuleEnvironment env = new ModuleEnvironment(name);
Environment oldEnv = getCurrentEnvt();
setCurrentEnvt(env); // such that declarations end up in the module scope
try {
x.getHeader().accept(this);
java.util.List<Toplevel> decls = x.getBody().getToplevels();
typeDeclarator.evaluateDeclarations(decls, getCurrentEnvt());
for (Toplevel l : decls) {
l.accept(this);
}
// only after everything was successful add the module
heap.addModule(env);
}
finally {
setCurrentEnvt(oldEnv);
}
}
return ResultFactory.nothing();
}
protected String getModuleName(
Module module) {
String name = module.getHeader().getName().toString();
if (name.startsWith("\\")) {
name = name.substring(1);
}
return name;
}
@Override
public Result<IValue> visitHeaderDefault(
org.meta_environment.rascal.ast.Header.Default x) {
visitImports(x.getImports());
return ResultFactory.nothing();
}
@Override
public Result<IValue> visitDeclarationAlias(Alias x) {
typeDeclarator.declareAlias(x, getCurrentEnvt());
return ResultFactory.nothing();
}
@Override
public Result<IValue> visitDeclarationData(Data x) {
typeDeclarator.declareConstructor(x, getCurrentEnvt());
return ResultFactory.nothing();
}
private void visitImports(java.util.List<Import> imports) {
for (Import i : imports) {
i.accept(this);
}
}
@Override
public Result<IValue> visitHeaderParameters(Parameters x) {
visitImports(x.getImports());
return ResultFactory.nothing();
}
@Override
public Result<IValue> visitToplevelDefaultVisibility(DefaultVisibility x) {
Result<IValue> r = x.getDeclaration().accept(this);
r.setPublic(false);
return r;
}
@Override
public Result<IValue> visitToplevelGivenVisibility(GivenVisibility x) {
Result<IValue> r = x.getDeclaration().accept(this);
r.setPublic(x.getVisibility().isPublic());
return r;
}
@Override
public Result<IValue> visitDeclarationFunction(Function x) {
return x.getFunctionDeclaration().accept(this);
}
@Override
public Result<IValue> visitDeclarationVariable(Variable x) {
Type declaredType = te.eval(x.getType(), getCurrentModuleEnvironment());
Result<IValue> r = nothing();
for (org.meta_environment.rascal.ast.Variable var : x.getVariables()) {
// TODO: should this be on getCurrentModuleEnvironment?
// (it probably is same env anyway).
if(getCurrentEnvt().getLocalVariable(var.getName()) != null){
throw new RedeclaredVariableError(var.getName().toString(), var);
}
if (var.isUnInitialized()) {
throw new UninitializedVariableError(var.toString(), var);
}
Result<IValue> v = var.getInitial().accept(this);
if(v.getType().isSubtypeOf(declaredType)){
// TODO: do we actually want to instantiate the locally bound type parameters?
Map<Type,Type> bindings = new HashMap<Type,Type>();
declaredType.match(v.getType(), bindings);
declaredType = declaredType.instantiate(getCurrentEnvt().getStore(), bindings);
r = makeResult(declaredType, v.getValue(), makeEvContext());
getCurrentModuleEnvironment().storeInnermostVariable(var.getName(), r);
} else {
throw new UnexpectedTypeError(declaredType, v.getType(), var);
}
}
return r;
}
@Override
public Result<IValue> visitDeclarationAnnotation(Annotation x) {
Type annoType = te.eval(x.getAnnoType(), getCurrentModuleEnvironment());
String name = x.getName().toString();
Type onType = te.eval(x.getOnType(), getCurrentModuleEnvironment());
getCurrentModuleEnvironment().declareAnnotation(onType, name, annoType);
return ResultFactory.nothing();
}
private Type evalType(org.meta_environment.rascal.ast.Type type) {
return te.eval(type, getCurrentEnvt());
}
@Override
public Result<IValue> visitDeclarationView(View x) {
// TODO implement
throw new NotYetImplemented("Views");
}
@Override
public Result<IValue> visitDeclarationRule(Rule x) {
return x.getPatternAction().accept(this);
}
@Override
public Result<IValue> visitPatternWithActionArbitrary(Arbitrary x) {
IMatchingResult pv = (IMatchingResult) x.getPattern().accept(makePatternEvaluator(x));
Type pt = pv.getType(getCurrentEnvt());
if(!(pt.isAbstractDataType() || pt.isConstructorType() || pt.isNodeType()))
throw new UnexpectedTypeError(tf.nodeType(), pt, x);
heap.storeRule(pv.getType(getCurrentModuleEnvironment()), x, getCurrentModuleEnvironment());
return ResultFactory.nothing();
}
private PatternEvaluator makePatternEvaluator(AbstractAST ast) {
return new PatternEvaluator(vf, new EvaluatorContext(this, ast));
}
@Override
public Result<IValue> visitPatternWithActionReplacing(Replacing x) {
IMatchingResult pv = (IMatchingResult) x.getPattern().accept(makePatternEvaluator(x));
Type pt = pv.getType(getCurrentEnvt());
if(!(pt.isAbstractDataType() || pt.isConstructorType() || pt.isNodeType()))
throw new UnexpectedTypeError(tf.nodeType(), pt, x);
heap.storeRule(pv.getType(getCurrentModuleEnvironment()), x, getCurrentModuleEnvironment());
return ResultFactory.nothing();
}
@Override
public Result<IValue> visitDeclarationTag(Tag x) {
throw new NotYetImplemented("tags");
}
// Variable Declarations -----------------------------------------------
@Override
public Result<IValue> visitLocalVariableDeclarationDefault(Default x) {
// TODO deal with dynamic variables
return x.getDeclarator().accept(this);
}
@Override
public Result<IValue> visitDeclaratorDefault(
org.meta_environment.rascal.ast.Declarator.Default x) {
Type declaredType = evalType(x.getType());
Result<IValue> r = ResultFactory.nothing();
for (org.meta_environment.rascal.ast.Variable var : x.getVariables()) {
String varAsString = var.getName().toString();
if(getCurrentEnvt().getLocalVariable(varAsString) != null ||
getCurrentEnvt().isRootScope() && getCurrentEnvt().getInnermostVariable(var.getName()) != null){
throw new RedeclaredVariableError(varAsString, var);
}
if (var.isUnInitialized()) { // variable declaration without initialization
r = ResultFactory.makeResult(declaredType, null, new EvaluatorContext(this, var));
getCurrentEnvt().storeInnermostVariable(var.getName(), r);
} else { // variable declaration with initialization
Result<IValue> v = var.getInitial().accept(this);
if(v.getType().isSubtypeOf(declaredType)){
// TODO: do we actually want to instantiate the locally bound type parameters?
Map<Type,Type> bindings = new HashMap<Type,Type>();
declaredType.match(v.getType(), bindings);
declaredType = declaredType.instantiate(getCurrentEnvt().getStore(), bindings);
// Was: r = makeResult(declaredType, applyRules(v.getValue()));
r = makeResult(declaredType, v.getValue(), new EvaluatorContext(this, var));
getCurrentEnvt().storeInnermostVariable(var.getName(), r);
} else {
throw new UnexpectedTypeError(declaredType, v.getType(), var);
}
}
}
return r;
}
private org.meta_environment.rascal.ast.QualifiedName makeQualifiedName(IConstructor node, String name) {
Name simple = new Name.Lexical(node, name);
java.util.List<Name> list = new ArrayList<Name>(1);
list.add(simple);
return new QualifiedName.Default(node, list);
}
@Override
public Result<IValue> visitExpressionCallOrTree(CallOrTree x) {
java.util.List<org.meta_environment.rascal.ast.Expression> args = x.getArguments();
// TODO: deal with all the new expressions one can type in now like ("a" + "b")(hello);
Expression nameExpr = x.getExpression();
QualifiedName name;
boolean unTyped = false;
// TODO: store constructors as Lambda's that construct trees and apply rewrite rules. Need to
// figure out what to do with sorted constructors such as Bool::and.
if (nameExpr.isQualifiedName() && getCurrentEnvt().getVariable(nameExpr.getQualifiedName()) == null) {
name = nameExpr.getQualifiedName();
}
else if (nameExpr.isQualifiedName() && getCurrentEnvt().isDeclaredFunctionName(nameExpr.getQualifiedName())) {
name = nameExpr.getQualifiedName();
}
else { // its a computed name or a string name
Result result = nameExpr.accept(this);
// TODO creating an AST here will make things slow, instead pass on the string name to the next phase
if (result.getType().isStringType()) {
String str = ((IString) result.getValue()).getValue();
if (!tf.isIdentifier(str)) {
throw RuntimeExceptionFactory.illegalIdentifier(str, nameExpr, getStackTrace());
}
name = makeQualifiedName((IConstructor) nameExpr.getTree(), str);
unTyped = true;
}
else {
throw new UndeclaredFunctionError(x.toString(), x);
}
}
IValue[] actuals = new IValue[args.size()];
Type[] types = new Type[args.size()];
boolean done = false;
// TODO: this is also not quite acceptible, since other functions might be called appl...
if (Names.name(Names.lastName(name)).equals("appl") && args.size() == 2) {
Result<IValue> resultElem = args.get(0).accept(this);
// TODO: it should be easier to detect this.... What is the accepted way?
if (resultElem.getType() == Factory.Production &&
((IConstructor)resultElem.getValue()).getConstructorType() == Factory.Production_List) {
actuals[0] = resultElem.getValue();
types[0] = resultElem.getType();
concreteListsShouldBeSpliced = true;
Result<IValue> argsResult = args.get(1).accept(this);
concreteListsShouldBeSpliced = false;
actuals[1] = argsResult.getValue();
types[1] = argsResult.getType();
done = true;
}
}
if (!done) {
// The normal case
for (int i = 0; i < args.size(); i++) {
Result<IValue> resultElem = args.get(i).accept(this);
types[i] = resultElem.getType();
actuals[i] = resultElem.getValue();
}
}
Type signature = tf.tupleType(types);
if (unTyped || isTreeConstructorName(name, signature)) {
return constructTree(name, actuals, signature);
}
return call(name, actuals, signature);
}
private Result<IValue> call(QualifiedName name, IValue[] actuals, Type actualTypes) {
String moduleName = Names.moduleName(name);
Result<IValue> func;
if (moduleName == null) {
Environment env = getCurrentEnvt();
// TODO: store all functions in the variable environment, ditch the function environment
func = env.getVariable(name);
if (func == null) {
func = env.getFunction(Names.name(Names.lastName(name)), actualTypes, name);
}
if (!(func instanceof Lambda)) {
throw new UndeclaredFunctionError(name.toString(), name);
}
}
else {
ModuleEnvironment env = getCurrentEnvt().getImport(moduleName);
if (env == null) {
throw new UndeclaredModuleError(moduleName, name);
}
func = env.getLocalPublicFunction(Names.name(Names.lastName(name)), actualTypes, name);
}
if (func != null) {
Environment oldEnv = getCurrentEnvt();
pushCallFrame(((Lambda) func).getEnv(), name.getLocation(), ((Lambda) func).getName());
try {
return ((Lambda) func).call(actuals, actualTypes, getCurrentEnvt());
}
finally {
setCurrentEnvt(oldEnv);
}
}
undefinedFunctionException(name, actualTypes);
return null;
}
private Environment pushCallFrame(Environment env, ISourceLocation loc, String name) {
//create a new Environment with a defined caller scope and location
Environment newEnv = new Environment(env, getCurrentEnvt(), getCurrentAST().getLocation(), loc, name);
setCurrentEnvt(newEnv);
return newEnv;
}
private void undefinedFunctionException(QualifiedName name, Type actualTypes) {
StringBuffer sb = new StringBuffer();
String sep = "";
for(int i = 0; i < actualTypes.getArity(); i++){
sb.append(sep);
sep = ", ";
sb.append(actualTypes.getFieldType(i).toString());
}
throw new UndeclaredFunctionError(name + "(" + sb.toString() + ")", name);
}
private boolean isTreeConstructorName(QualifiedName name, Type signature) {
return getCurrentEnvt().isTreeConstructorName(name, signature);
}
/**
* A top-down algorithm is needed to type check a constructor call since the
* result type of constructors can be overloaded. We bring down the expected type
* of each argument.
* @param expected
* @param functionName
* @param args
* @return
*
* TODO: code does not deal with import structure, rather data def's are global.
* TODO: We now first build the tree and then apply rules to it. Change this so
* that we can avoid building the tree at all.
*/
private Result<IValue> constructTree(QualifiedName functionName, IValue[] actuals, Type signature) {
String sort;
String cons;
Result<IValue> result = null;
cons = Names.consName(functionName);
sort = Names.sortName(functionName);
Type candidate = null;
if (sort != null) {
Type sortType = getCurrentEnvt().getAbstractDataType(sort);
if (sortType != null) {
candidate = getCurrentEnvt().getConstructor(sortType, cons, signature);
}
else {
return applyRules(ResultFactory.makeResult(tf.nodeType(), vf.node(cons, actuals), makeEvContext()));
}
}
candidate = getCurrentEnvt().getConstructor(cons, signature);
if (candidate != null) {
Map<Type,Type> localBindings = new HashMap<Type,Type>();
candidate.getFieldTypes().match(tf.tupleType(actuals), localBindings);
Result<IValue> afterRules = applyRules(ResultFactory.makeResult(candidate.getAbstractDataType(), candidate.make(vf, actuals),
makeEvContext()));
result = makeResult(candidate.getAbstractDataType().instantiate(new TypeStore(), localBindings),
afterRules.getValue(), makeEvContext());
}
else {
result = applyRules(makeResult(tf.nodeType(), vf.node(cons, actuals), makeEvContext()));
}
declareConcreteSyntaxType(result.getValue());
return detectConcreteSyntaxTree(result);
}
private EvaluatorContext makeEvContext() {
return new EvaluatorContext(this, getCurrentAST());
}
private <T extends IValue> Result<T> detectConcreteSyntaxTree(Result<T> result) {
if (result.getType() == Factory.Tree) {
IConstructor tree = (IConstructor) result.getValue();
Type cons = tree.getConstructorType();
if (cons == Factory.Tree_Appl || cons == Factory.Tree_Amb) {
TreeAdapter adapter = new TreeAdapter(tree);
if (adapter.isAppl() && adapter.getProduction().getRhs().isCf()) {
return (Result<T>) new ConcreteSyntaxResult(new ConcreteSyntaxType((IConstructor) result.getValue()), (IConstructor) result.getValue(), makeEvContext());
}
}
}
return result;
}
private boolean hasJavaModifier(FunctionDeclaration func) {
java.util.List<FunctionModifier> mods = func.getSignature().getModifiers().getModifiers();
for (FunctionModifier m : mods) {
if (m.isJava()) {
return true;
}
}
return false;
}
@Override
public Result<IValue> visitFunctionBodyDefault(
org.meta_environment.rascal.ast.FunctionBody.Default x) {
Result<IValue> result = nothing();
for (Statement statement : x.getStatements()) {
setCurrentAST(statement);
result = statement.accept(this);
}
return result;
}
// Statements ---------------------------------------------------------
@Override
public Result<IValue> visitStatementAssert(Assert x) {
Result<IValue> r = x.getExpression().accept(this);
if (!r.getType().equals(tf.boolType())) {
throw new UnexpectedTypeError(tf.boolType(), r.getType(), x);
}
if(r.getValue().isEqual(vf.bool(false))) {
throw RuntimeExceptionFactory.assertionFailed(x, getStackTrace());
}
return r;
}
@Override
public Result<IValue> visitStatementAssertWithMessage(AssertWithMessage x) {
Result<IValue> r = x.getExpression().accept(this);
if (!r.getType().equals(tf.boolType())) {
throw new UnexpectedTypeError(tf.boolType(),r.getType(), x);
}
if(r.getValue().isEqual(vf.bool(false))){
String str = x.getMessage().toString();
IString msg = vf.string(unescape(str, x, getCurrentEnvt()));
throw RuntimeExceptionFactory.assertionFailed(msg, getCurrentAST(), getStackTrace());
}
return r;
}
@Override
public Result<IValue> visitStatementVariableDeclaration(VariableDeclaration x) {
return x.getDeclaration().accept(this);
}
@Override
public Result<IValue> visitStatementExpression(Statement.Expression x) {
Environment old = getCurrentEnvt();
try {
goodPushEnv();
return x.getExpression().accept(this);
}
finally {
unwind(old);
}
}
@Override
public Result<IValue> visitStatementFunctionDeclaration(
org.meta_environment.rascal.ast.Statement.FunctionDeclaration x) {
return x.getFunctionDeclaration().accept(this);
}
@Override
public Result<IValue> visitExpressionSubscript(Subscript x) {
Result<IValue> expr = x.getExpression().accept(this);
int nSubs = x.getSubscripts().size();
Result<?> subscripts[] = new Result<?>[nSubs];
for (int i = 0; i < nSubs; i++) {
Expression subsExpr = x.getSubscripts().get(i);
subscripts[i] = isWildCard(subsExpr.toString()) ? null : subsExpr.accept(this);
}
return expr.subscript(subscripts, new EvaluatorContext(this, x));
}
@Override
public Result<IValue> visitExpressionFieldAccess(
org.meta_environment.rascal.ast.Expression.FieldAccess x) {
Result<IValue> expr = x.getExpression().accept(this);
String field = x.getField().toString();
return expr.fieldAccess(field, getCurrentEnvt().getStore(), new EvaluatorContext(this, x));
}
private boolean isWildCard(String fieldName){
return fieldName.equals("_");
}
@Override
public Result<IValue> visitExpressionFieldProject(FieldProject x) {
// TODO: move to result classes
Result<IValue> base = x.getExpression().accept(this);
java.util.List<Field> fields = x.getFields();
int nFields = fields.size();
int selectedFields[] = new int[nFields];
if(base.getType().isTupleType()){
Type fieldTypes[] = new Type[nFields];
for(int i = 0 ; i < nFields; i++){
Field f = fields.get(i);
if(f.isIndex()){
selectedFields[i] = ((IInteger) f.getFieldIndex().accept(this).getValue()).intValue();
} else {
String fieldName = f.getFieldName().toString();
try {
selectedFields[i] = base.getType().getFieldIndex(fieldName);
} catch (UndeclaredFieldException e){
throw new UndeclaredFieldError(fieldName, base.getType(), x);
}
}
if (selectedFields[i] < 0 || selectedFields[i] > base.getType().getArity()) {
throw RuntimeExceptionFactory.indexOutOfBounds(vf.integer(i), getCurrentAST(), getStackTrace());
}
fieldTypes[i] = base.getType().getFieldType(selectedFields[i]);
}
// if(duplicateIndices(selectedFields)){
// TODO: what does it matter if there are duplicate indices???
// throw new ImplementationError("Duplicate fields in projection");
// }
Type resultType = nFields == 1 ? fieldTypes[0] : tf.tupleType(fieldTypes);
// Was: return makeResult(resultType, applyRules(((ITuple)base.getValue()).select(selectedFields)));
return makeResult(resultType, ((ITuple)base.getValue()).select(selectedFields), makeEvContext());
}
if(base.getType().isRelationType()){
Type fieldTypes[] = new Type[nFields];
for(int i = 0 ; i < nFields; i++){
Field f = fields.get(i);
if(f.isIndex()){
selectedFields[i] = ((IInteger) f.getFieldIndex().accept(this).getValue()).intValue();
} else {
String fieldName = f.getFieldName().toString();
try {
selectedFields[i] = base.getType().getFieldIndex(fieldName);
} catch (Exception e){
throw new UndeclaredFieldError(fieldName, base.getType(), x);
}
}
if(selectedFields[i] < 0 || selectedFields[i] > base.getType().getArity()) {
throw RuntimeExceptionFactory.indexOutOfBounds(vf.integer(i), getCurrentAST(), getStackTrace());
}
fieldTypes[i] = base.getType().getFieldType(selectedFields[i]);
}
//// if(duplicateIndices(selectedFields)){
// TODO: what does it matter if there are duplicate indices? Duplicate
// field names may be a problem, but not this.
// throw new ImplementationError("Duplicate fields in projection");
// }
Type resultType = nFields == 1 ? tf.setType(fieldTypes[0]) : tf.relType(fieldTypes);
//return makeResult(resultType, applyRules(((IRelation)base.getValue()).select(selectedFields)));
return makeResult(resultType, ((IRelation)base.getValue()).select(selectedFields), makeEvContext());
}
throw new UnsupportedOperationError("projection", base.getType(), x);
}
@Override
public Result<IValue> visitStatementEmptyStatement(EmptyStatement x) {
return ResultFactory.nothing();
}
@Override
public Result<IValue> visitStatementFail(Fail x) {
if (x.getFail().isWithLabel()) {
throw new Failure(x.getFail().getLabel().toString());
}
throw new Failure();
}
@Override
public Result<IValue> visitStatementReturn(
org.meta_environment.rascal.ast.Statement.Return x) {
org.meta_environment.rascal.ast.Return r = x.getRet();
if (r.isWithExpression()) {
throw new Return(x.getRet().getExpression().accept(this));
}
throw new Return(nothing());
}
@Override
public Result<IValue> visitStatementBreak(Break x) {
throw new NotYetImplemented(x.toString()); // TODO
}
@Override
public Result<IValue> visitStatementContinue(Continue x) {
throw new NotYetImplemented(x.toString()); // TODO
}
@Override
public Result<IValue> visitStatementGlobalDirective(GlobalDirective x) {
throw new NotYetImplemented(x.toString()); // TODO
}
@Override
public Result<IValue> visitStatementThrow(Throw x) {
throw new org.meta_environment.rascal.interpreter.control_exceptions.Throw(x.getExpression().accept(this).getValue(), getCurrentAST(), getStackTrace());
}
@Override
public Result<IValue> visitStatementTry(Try x) {
return evalStatementTry(x.getBody(), x.getHandlers(), null);
}
@Override
public Result<IValue> visitStatementTryFinally(TryFinally x) {
return evalStatementTry(x.getBody(), x.getHandlers(), x.getFinallyBody());
}
private Result<IValue> evalStatementTry(Statement body, java.util.List<Catch> handlers, Statement finallyBody){
Result<IValue> res = nothing();
try {
res = body.accept(this);
} catch (org.meta_environment.rascal.interpreter.control_exceptions.Throw e){
IValue eValue = e.getException();
for (Catch c : handlers){
if(c.isDefault()){
res = c.getBody().accept(this);
break;
}
// TODO: Throw should contain Result<IValue> instead of IValue
if(matchAndEval(makeResult(eValue.getType(), eValue, makeEvContext()), c.getPattern(), c.getBody())){
break;
}
}
}
finally {
if (finallyBody != null) {
finallyBody.accept(this);
}
}
return res;
}
@Override
public Result<IValue> visitStatementVisit(
org.meta_environment.rascal.ast.Statement.Visit x) {
return x.getVisit().accept(this);
}
@Override
public Result<IValue> visitStatementInsert(Insert x) {
throw new org.meta_environment.rascal.interpreter.control_exceptions.Insert(x.getExpression().accept(this));
}
@Override
public Result<IValue> visitStatementAssignment(Assignment x) {
Result<IValue> right = x.getExpression().accept(this);
return x.getAssignable().accept(new AssignableEvaluator(getCurrentEnvt(), x.getOperator(), right, this));
}
@Override
public Result<IValue> visitStatementBlock(Block x) {
Result<IValue> r = nothing();
Environment old = getCurrentEnvt();
goodPushEnv(x);
try {
for (Statement stat : x.getStatements()) {
setCurrentAST(stat);
r = stat.accept(this);
}
}
finally {
unwind(old);
}
return r;
}
@Override
public Result<IValue> visitAssignableVariable(
org.meta_environment.rascal.ast.Assignable.Variable x) {
return getCurrentEnvt().getVariable(x.getQualifiedName(),x.getQualifiedName().toString());
}
@Override
public Result<IValue> visitAssignableFieldAccess(FieldAccess x) {
Result<IValue> receiver = x.getReceiver().accept(this);
String label = x.getField().toString();
if (receiver.getType().isTupleType()) {
IValue result = ((ITuple) receiver.getValue()).get(label);
Type type = ((ITuple) receiver.getValue()).getType().getFieldType(label);
return makeResult(type, result, new EvaluatorContext(this, x));
}
else if (receiver.getType().isConstructorType() || receiver.getType().isAbstractDataType()) {
IConstructor cons = (IConstructor) receiver.getValue();
Type node = cons.getConstructorType();
if (!receiver.getType().hasField(label)) {
throw new UndeclaredFieldError(label, receiver.getType(), x);
}
if (!node.hasField(label)) {
throw RuntimeExceptionFactory.noSuchField(label, x,getStackTrace());
}
int index = node.getFieldIndex(label);
return makeResult(node.getFieldType(index), cons.get(index), new EvaluatorContext(this, x));
}
else {
throw new UndeclaredFieldError(label, receiver.getType(), x);
}
}
@Override
public Result<IValue> visitAssignableAnnotation(
org.meta_environment.rascal.ast.Assignable.Annotation x) {
Result<IValue> receiver = x.getReceiver().accept(this);
String label = x.getAnnotation().toString();
if (!getCurrentEnvt().declaresAnnotation(receiver.getType(), label)) {
throw new UndeclaredAnnotationError(label, receiver.getType(), x);
}
Type type = getCurrentEnvt().getAnnotationType(receiver.getType(), label);
IValue value = ((IConstructor) receiver.getValue()).getAnnotation(label);
return makeResult(type, value, new EvaluatorContext(this, x));
}
@Override
public Result<IValue> visitAssignableConstructor(Constructor x) {
throw new ImplementationError("Constructor assignable does not represent a value");
}
@Override
public Result<IValue> visitAssignableIfDefinedOrDefault(
org.meta_environment.rascal.ast.Assignable.IfDefinedOrDefault x) {
throw new ImplementationError("ifdefined assignable does not represent a value");
}
@Override
public Result<IValue> visitAssignableSubscript(
org.meta_environment.rascal.ast.Assignable.Subscript x) {
Result<IValue> receiver = x.getReceiver().accept(this);
Result<IValue> subscript = x.getSubscript().accept(this);
if (receiver.getType().isListType()) {
if (subscript.getType().isIntegerType()) {
IList list = (IList) receiver.getValue();
IValue result = list.get(((IInteger) subscript.getValue()).intValue());
Type type = receiver.getType().getElementType();
return normalizedResult(type, result);
}
throw new UnexpectedTypeError(tf.integerType(), subscript.getType(), x);
}
else if (receiver.getType().isMapType()) {
Type keyType = receiver.getType().getKeyType();
if (subscript.getType().isSubtypeOf(keyType)) {
IValue result = ((IMap) receiver.getValue()).get(subscript.getValue());
Type type = receiver.getType().getValueType();
return makeResult(type, result, new EvaluatorContext(this, x));
}
throw new UnexpectedTypeError(keyType, subscript.getType(), x);
}
// TODO implement other subscripts
throw new UnsupportedOperationError("subscript", receiver.getType(), x);
}
@Override
public Result<IValue> visitAssignableTuple(
org.meta_environment.rascal.ast.Assignable.Tuple x) {
throw new ImplementationError("Tuple in assignable does not represent a value:" + x);
}
@Override
public Result<IValue> visitAssignableAmbiguity(
org.meta_environment.rascal.ast.Assignable.Ambiguity x) {
throw new Ambiguous(x.toString());
}
@Override
public Result visitFunctionDeclarationDefault(
org.meta_environment.rascal.ast.FunctionDeclaration.Default x) {
Lambda lambda;
boolean varArgs = x.getSignature().getParameters().isVarArgs();
if (hasJavaModifier(x)) {
lambda = new JavaFunction(this, x, varArgs, getCurrentEnvt(), javaBridge);
}
else {
if (!x.getBody().isDefault()) {
throw new MissingModifierError("java", x);
}
lambda = new RascalFunction(this, x, varArgs, getCurrentEnvt());
}
String name = Names.name(x.getSignature().getName());
getCurrentEnvt().storeFunction(name, lambda);
return lambda;
}
@Override
public Result visitFunctionDeclarationAbstract(Abstract x) {
Lambda lambda = null;
String funcName;
boolean varArgs = x.getSignature().getParameters().isVarArgs();
if (hasTag(x, "stringParser") || hasTag(x, "fileParser")) {
funcName = setupParserFunction(x);
if (hasTag(x, "stringParser")) {
lambda = new ParserFunction(this, x, getCurrentEnvt(), loader);
}
if (hasTag(x, "fileParser")) {
lambda = new FileParserFunction(this, x, getCurrentEnvt(), loader);
}
getCurrentEnvt().storeFunction(funcName, lambda);
return lambda;
}
if (!hasJavaModifier(x)) {
throw new MissingModifierError("java", x);
}
lambda = new org.meta_environment.rascal.interpreter.env.JavaMethod(this, x, varArgs, getCurrentEnvt(), javaBridge);
String name = Names.name(x.getSignature().getName());
getCurrentEnvt().storeFunction(name, lambda);
return lambda;
}
private boolean hasTag(Abstract x, String tagName) {
// TODO: check type and arity of of signature
Tags tags = x.getTags();
if (tags.hasAnnotations()) {
for (org.meta_environment.rascal.ast.Tag tag : tags.getAnnotations()) {
if (tag.getName().toString().equals(tagName)) {
return true;
}
}
}
return false;
}
private String setupParserFunction(Abstract x) {
org.meta_environment.rascal.ast.Type type = x.getSignature().getType();
// TODO: how should we get at the name, and why???
// Why isn't the constructor representing the concrete syntax type enough?
IConstructor cons = (IConstructor) Symbols.typeToSymbol(type);
IConstructor cfSym = (IConstructor) cons.get(0);
IValue typeValue = cfSym.get(0);
if (!typeValue.getType().isStringType()) {
throw new NonWellformedTypeError("result type of parser functions must be sorts", type);
}
String sortName = ((IString)cfSym.get(0)).getValue();
getCurrentEnvt().concreteSyntaxType(sortName, cons);
return Names.name(x.getSignature().getName());
}
@Override
public Result<IValue> visitStatementIfThenElse(IfThenElse x) {
Statement body = x.getThenStatement();
java.util.List<Expression> generators = x.getConditions();
int size = generators.size();
IBooleanResult[] gens = new IBooleanResult[size];
Environment[] olds = new Environment[size];
Environment old = getCurrentEnvt();
int i = 0;
try {
gens[0] = makeBooleanResult(generators.get(0));
gens[0].init();
olds[0] = getCurrentEnvt();
goodPushEnv();
while(i >= 0 && i < size) {
if(gens[i].hasNext() && gens[i].next()){
if(i == size - 1){
return body.accept(this);
} else {
i++;
gens[i] = makeBooleanResult(generators.get(i));
gens[i].init();
olds[i] = getCurrentEnvt();
goodPushEnv();
}
} else {
unwind(olds[i]);
goodPushEnv();
i--;
}
}
} finally {
unwind(old);
}
return x.getElseStatement().accept(this);
}
@Override
public Result<IValue> visitStatementIfThen(IfThen x) {
Statement body = x.getThenStatement();
java.util.List<Expression> generators = x.getConditions();
int size = generators.size();
IBooleanResult[] gens = new IBooleanResult[size];
Environment[] olds = new Environment[size];
Environment old = getCurrentEnvt();
int i = 0;
try {
gens[0] = makeBooleanResult(generators.get(0));
gens[0].init();
olds[0] = getCurrentEnvt();
goodPushEnv();
while(i >= 0 && i < size) {
if(gens[i].hasNext() && gens[i].next()){
if(i == size - 1){
return body.accept(this);
} else {
i++;
gens[i] = makeBooleanResult(generators.get(i));
gens[i].init();
olds[i] = getCurrentEnvt();
goodPushEnv();
}
} else {
unwind(olds[i]);
goodPushEnv();
i--;
}
}
} finally {
unwind(old);
}
return nothing();
}
@Override
public Result<IValue> visitStatementWhile(While x) {
Statement body = x.getBody();
Expression generator = x.getCondition();
IBooleanResult gen;
Environment old = getCurrentEnvt();
Result<IValue> result = nothing();
// a while statement is different from a for statement, the body of the while can influence the
// variables that are used to test the condition of the loop
// while does not iterate over all possible matches, rather it produces every time the first match
// that makes the condition true
while (true) {
try {
gen = makeBooleanResult(generator);
gen.init();
goodPushEnv();
if(gen.hasNext() && gen.next()){
result = body.accept(this);
}
else {
return result;
}
} finally {
unwind(old);
}
}
}
@Override
public Result<IValue> visitStatementDoWhile(DoWhile x) {
Statement body = x.getBody();
Expression generator = x.getCondition();
IBooleanResult gen;
Environment old = getCurrentEnvt();
Result<IValue> result = nothing();
while (true) {
try {
result = body.accept(this);
gen = makeBooleanResult(generator);
gen.init();
if(!(gen.hasNext() && gen.next())) {
return result;
}
} finally {
unwind(old);
}
}
}
@Override
public Result<IValue> visitExpressionMatch(Match x) {
return evalBooleanExpression(x);
}
@Override
public Result<IValue> visitExpressionNoMatch(NoMatch x) {
return evalBooleanExpression(x);
}
// ----- General method for matching --------------------------------------------------
public IBooleanResult makeBooleanResult(org.meta_environment.rascal.ast.Expression pat){
if (pat instanceof Expression.Ambiguity) {
// TODO: wrong exception here.
throw new AmbiguousConcretePattern(pat);
}
BooleanEvaluator pe = new BooleanEvaluator(vf, makeEvContext());
return pat.accept(pe);
}
// Expressions -----------------------------------------------------------
@Override
public Result<IValue> visitExpressionLiteral(Literal x) {
return x.getLiteral().accept(this);
}
@Override
public Result<IValue> visitLiteralInteger(Integer x) {
return x.getIntegerLiteral().accept(this);
}
@Override
public Result<IValue> visitLiteralReal(Real x) {
String str = x.getRealLiteral().toString();
return makeResult(tf.realType(), vf.real(str), new EvaluatorContext(this, x));
}
@Override
public Result<IValue> visitLiteralBoolean(Boolean x) {
String str = x.getBooleanLiteral().toString();
return makeResult(tf.boolType(), vf.bool(str.equals("true")), new EvaluatorContext(this, x));
}
@Override
public Result<IValue> visitLiteralString(
org.meta_environment.rascal.ast.Literal.String x) {
String str = ((StringLiteral.Lexical) x.getStringLiteral()).getString();
return makeResult(tf.stringType(), vf.string(unescape(str, x, getCurrentEnvt())), new EvaluatorContext(this, x));
}
@Override
public Result<IValue> visitIntegerLiteralDecimalIntegerLiteral(
DecimalIntegerLiteral x) {
String str = ((org.meta_environment.rascal.ast.DecimalIntegerLiteral.Lexical) x.getDecimal()).getString();
return makeResult(tf.integerType(), vf.integer(str), new EvaluatorContext(this, x));
}
@Override
public Result<IValue> visitExpressionQualifiedName(
org.meta_environment.rascal.ast.Expression.QualifiedName x) {
QualifiedName name = x.getQualifiedName();
Result<IValue> result ;
try {
result = getCurrentEnvt().getVariable(name);
}
catch (UndeclaredModuleError e) {
// TODO: find a better way to deal with this exception, BTW the Bool::and notation (what this is for) should dissappear
// anyway and be replaced by Bool.and, so this problem should evaporate by itself.
if (isTreeConstructorName(name, tf.tupleEmpty())) {
return constructTree(name, new IValue[0], tf.tupleType(new Type[0]));
}
throw e;
}
if (result != null && result.getValue() != null) {
return result;
}
// TODO: deal with overloading, now only accept unique ones
// TODO: deal with qualified function names
try {
result = getCurrentEnvt().getFunction(Names.name(Names.lastName(name)), tf.voidType(), x);
}
catch (UndeclaredFunctionError e) {
// TODO: change getFunction to return null instead
result = null;
}
if (result != null) {
return result;
}
if (isTreeConstructorName(name, tf.tupleEmpty())) {
return constructTree(name, new IValue[0], tf.tupleType(new Type[0]));
}
throw new UninitializedVariableError(name.toString(), x);
}
@Override
public Result<IValue> visitExpressionList(List x) {
java.util.List<org.meta_environment.rascal.ast.Expression> elements = x
.getElements();
Type elementType = tf.voidType();
java.util.List<IValue> results = new ArrayList<IValue>();
// Splicing is true for the complete list; a terrible, terrible hack.
boolean splicing = concreteListsShouldBeSpliced;
boolean first = true;
int skip = 0;
for (org.meta_environment.rascal.ast.Expression expr : elements) {
Result<IValue> resultElem = expr.accept(this);
if (skip > 0) {
skip--;
continue;
}
Type resultType = resultElem.getType();
if (splicing && resultType instanceof ConcreteSyntaxType) {
SymbolAdapter sym = new SymbolAdapter(((ConcreteSyntaxType)resultType).getSymbol());
if (sym.isAnyList()) {
IConstructor appl = ((IConstructor)resultElem.getValue());
TreeAdapter tree = new TreeAdapter(appl);
IList listElems = tree.getArgs();
// Splice elements in list if element types permit this
if (!listElems.isEmpty()) {
for(IValue val : listElems){
elementType = elementType.lub(val.getType());
results.add(val);
}
}
else {
// make sure to remove surrounding sep
if (!first) {
if (sym.isCf()) {
SymbolAdapter listSym = sym.getSymbol();
if (listSym.isIterStar()) {
results.remove(results.size() - 1);
}
else if (listSym.isIterStarSep()) {
results.remove(results.size() - 1);
results.remove(results.size() - 1);
results.remove(results.size() - 1);
}
}
if (sym.isLex()) {
SymbolAdapter listSym = sym.getSymbol();
if (listSym.isIterStarSep()) {
results.remove(results.size() - 1);
results.remove(results.size() - 1);
}
}
}
else {
if (sym.isCf()) {
SymbolAdapter listSym = sym.getSymbol();
if (listSym.isIterStar()) {
skip = 1;
}
else if (listSym.isIterStarSep()) {
skip = 3;
}
}
if (sym.isLex()) {
SymbolAdapter listSym = sym.getSymbol();
if (listSym.isIterStarSep()) {
skip = 2;
}
}
}
}
}
else {
// Just add it.
elementType = elementType.lub(resultElem.getType());
results.add(results.size(), resultElem.getValue());
}
}
else {
/* = no concrete syntax */
if(resultElem.getType().isListType() &&
!expr.isList() &&
elementType.isSubtypeOf(resultElem.getType().getElementType())
){
/*
* Splice elements in list if element types permit this
*/
for(IValue val : ((IList) resultElem.getValue())){
elementType = elementType.lub(val.getType());
results.add(val);
}
} else {
elementType = elementType.lub(resultElem.getType());
results.add(results.size(), resultElem.getValue());
}
}
first = false;
}
Type resultType = tf.listType(elementType);
IListWriter w = resultType.writer(vf);
w.appendAll(results);
// Was: return makeResult(resultType, applyRules(w.done()));
return makeResult(resultType, w.done(), new EvaluatorContext(this, x));
}
@Override
public Result<IValue> visitExpressionSet(Set x) {
java.util.List<org.meta_environment.rascal.ast.Expression> elements = x
.getElements();
Type elementType = tf.voidType();
java.util.List<IValue> results = new ArrayList<IValue>();
for (org.meta_environment.rascal.ast.Expression expr : elements) {
Result<IValue> resultElem = expr.accept(this);
if(resultElem.getType().isSetType() && !expr.isSet() &&
elementType.isSubtypeOf(resultElem.getType().getElementType())){
/*
* Splice the elements in the set if element types permit this.
*/
for(IValue val : ((ISet) resultElem.getValue())){
elementType = elementType.lub(val.getType());
results.add(val);
}
} else {
elementType = elementType.lub(resultElem.getType());
results.add(results.size(), resultElem.getValue());
}
}
Type resultType = tf.setType(elementType);
ISetWriter w = resultType.writer(vf);
w.insertAll(results);
//Was: return makeResult(resultType, applyRules(w.done()));
return makeResult(resultType, w.done(), new EvaluatorContext(this, x));
}
@Override
public Result<IValue> visitExpressionMap(
org.meta_environment.rascal.ast.Expression.Map x) {
java.util.List<org.meta_environment.rascal.ast.Mapping> mappings = x
.getMappings();
Map<IValue,IValue> result = new HashMap<IValue,IValue>();
Type keyType = tf.voidType();
Type valueType = tf.voidType();
for (org.meta_environment.rascal.ast.Mapping mapping : mappings) {
Result<IValue> keyResult = mapping.getFrom().accept(this);
Result<IValue> valueResult = mapping.getTo().accept(this);
keyType = keyType.lub(keyResult.getType());
valueType = valueType.lub(valueResult.getType());
result.put(keyResult.getValue(), valueResult.getValue());
}
Type type = tf.mapType(keyType, valueType);
IMapWriter w = type.writer(vf);
w.putAll(result);
//return makeResult(type, applyRules(w.done()));
return makeResult(type, w.done(), new EvaluatorContext(this, x));
}
@Override
public Result visitExpressionNonEmptyBlock(NonEmptyBlock x) {
return new Lambda(x, this, tf.voidType(), "", tf.tupleEmpty(), false, x.getStatements(), getCurrentEnvt());
}
@Override
public Result<IValue> visitExpressionTuple(Tuple x) {
java.util.List<org.meta_environment.rascal.ast.Expression> elements = x
.getElements();
IValue[] values = new IValue[elements.size()];
Type[] types = new Type[elements.size()];
for (int i = 0; i < elements.size(); i++) {
Result<IValue> resultElem = elements.get(i).accept(this);
types[i] = resultElem.getType();
values[i] = resultElem.getValue();
}
//return makeResult(tf.tupleType(types), applyRules(vf.tuple(values)));
return makeResult(tf.tupleType(types), vf.tuple(values), new EvaluatorContext(this, x));
}
@Override
public Result<IValue> visitExpressionGetAnnotation(
org.meta_environment.rascal.ast.Expression.GetAnnotation x) {
Result<IValue> base = x.getExpression().accept(this);
String annoName = x.getName().toString();
return base.getAnnotation(annoName, getCurrentEnvt(), new EvaluatorContext(this, x));
}
@Override
public Result<IValue> visitExpressionSetAnnotation(
org.meta_environment.rascal.ast.Expression.SetAnnotation x) {
Result<IValue> base = x.getExpression().accept(this);
String annoName = x.getName().toString();
Result<IValue> anno = x.getValue().accept(this);
return base.setAnnotation(annoName, anno, getCurrentEnvt(), new EvaluatorContext(this, x));
}
@Override
public Result<IValue> visitExpressionAddition(Addition x) {
Result<IValue> left = x.getLhs().accept(this);
Result<IValue> right = x.getRhs().accept(this);
return left.add(right, new EvaluatorContext(this, x));
}
@Override
public Result<IValue> visitExpressionSubtraction(Subtraction x) {
Result<IValue> left = x.getLhs().accept(this);
Result<IValue> right = x.getRhs().accept(this);
return left.subtract(right, new EvaluatorContext(this, x));
}
@Override
public Result<IValue> visitExpressionNegative(Negative x) {
Result<IValue> arg = x.getArgument().accept(this);
return arg.negative(new EvaluatorContext(this, x));
}
@Override
public Result<IValue> visitExpressionProduct(Product x) {
Result<IValue> left = x.getLhs().accept(this);
Result<IValue> right = x.getRhs().accept(this);
return left.multiply(right, new EvaluatorContext(this, x));
}
@Override
public Result<IValue> visitExpressionJoin(Join x) {
Result<IValue> left = x.getLhs().accept(this);
Result<IValue> right = x.getRhs().accept(this);
return left.join(right, new EvaluatorContext(this, x));
}
@Override
public Result<IValue> visitExpressionDivision(Division x) {
Result<IValue> left = x.getLhs().accept(this);
Result<IValue> right = x.getRhs().accept(this);
return left.divide(right, new EvaluatorContext(this, x));
}
@Override
public Result<IValue> visitExpressionModulo(Modulo x) {
Result<IValue> left = x.getLhs().accept(this);
Result<IValue> right = x.getRhs().accept(this);
return left.modulo(right, new EvaluatorContext(this, x));
}
@Override
public Result<IValue> visitExpressionBracket(Bracket x) {
return x.getExpression().accept(this);
}
@Override
public Result<IValue> visitExpressionIntersection(Intersection x) {
Result<IValue> left = x.getLhs().accept(this);
Result<IValue> right = x.getRhs().accept(this);
return left.intersect(right, new EvaluatorContext(this, x));
}
@Override
public Result<IValue> visitExpressionOr(Or x) {
return evalBooleanExpression(x);
}
@Override
public Result<IValue> visitExpressionAnd(And x) {
return evalBooleanExpression(x);
}
private Result<IValue> evalBooleanExpression(Expression x) {
IBooleanResult mp = makeBooleanResult(x);
mp.init();
while(mp.hasNext()){
if(mp.next()) {
return ResultFactory.bool(true);
}
}
return ResultFactory.bool(false);
}
@Override
public Result<IValue> visitExpressionNegation(Negation x) {
return evalBooleanExpression(x);
}
@Override
public Result<IValue> visitExpressionImplication(Implication x) {
return evalBooleanExpression(x);
}
@Override
public Result<IValue> visitExpressionEquivalence(Equivalence x) {
return evalBooleanExpression(x);
}
@Override
public Result<IValue> visitExpressionEquals(
org.meta_environment.rascal.ast.Expression.Equals x) {
Result<IValue> left = x.getLhs().accept(this);
Result<IValue> right = x.getRhs().accept(this);
return left.equals(right, new EvaluatorContext(this, x));
}
@Override
public Result<IValue> visitExpressionOperatorAsValue(OperatorAsValue x) {
// TODO
throw new NotYetImplemented(x);
}
@Override
public Result<IValue> visitExpressionLocation(Location x){
String urlText = x.getUrl().toString();
Result<IValue> length = x.getLength().accept(this);
int iLength = ((IInteger) length.getValue()).intValue();
Result<IValue> offset = x.getOffset().accept(this);
int iOffset = ((IInteger) offset.getValue()).intValue();
Result<IValue> beginLine = x.getBeginLine().accept(this);
int iBeginLine = ((IInteger) beginLine.getValue()).intValue();
Result<IValue> endLine = x.getEndLine().accept(this);
int iEndLine = ((IInteger) endLine.getValue()).intValue();
Result<IValue> beginColumn = x.getBeginColumn().accept(this);
int iBeginColumn = ((IInteger) beginColumn.getValue()).intValue();
Result<IValue> endColumn = x.getEndColumn().accept(this);
int iEndColumn = ((IInteger) endColumn.getValue()).intValue();
try {
URL url = new URL(urlText);
ISourceLocation r = vf.sourceLocation(url, iOffset, iLength, iBeginLine, iEndLine, iBeginColumn, iEndColumn);
return makeResult(tf.sourceLocationType(), r, new EvaluatorContext(this, x));
} catch (MalformedURLException e){
throw new SyntaxError("location (malformed URL)", x.getLocation());
}
}
@Override
public Result visitExpressionClosure(Closure x) {
Type formals = te.eval(x.getParameters(), getCurrentEnvt());
Type returnType = evalType(x.getType());
return new Lambda(x, this, returnType, "", formals, x.getParameters().isVarArgs(), x.getStatements(), getCurrentEnvt());
}
@Override
public Result visitExpressionVoidClosure(VoidClosure x) {
Type formals = te.eval(x.getParameters(), getCurrentEnvt());
return new Lambda(x, this, tf.voidType(), "", formals, x.getParameters().isVarArgs(), x.getStatements(), getCurrentEnvt());
}
@Override
public Result<IValue> visitExpressionFieldUpdate(FieldUpdate x) {
Result<IValue> expr = x.getExpression().accept(this);
Result<IValue> repl = x.getReplacement().accept(this);
String name = x.getKey().toString();
return expr.fieldUpdate(name, repl, getCurrentEnvt().getStore(), new EvaluatorContext(this, x));
}
@Override
public Result<IValue> visitExpressionLexical(Lexical x) {
throw new NotYetImplemented(x);// TODO
}
@Override
public Result<IValue> visitExpressionRange(Range x) {
//IListWriter w = vf.listWriter(tf.integerType());
Result<IValue> from = x.getFirst().accept(this);
Result<IValue> to = x.getLast().accept(this);
return from.makeRange(to, new EvaluatorContext(this, x));
}
@Override
public Result<IValue> visitExpressionStepRange(StepRange x) {
Result<IValue> from = x.getFirst().accept(this);
Result<IValue> to = x.getLast().accept(this);
Result<IValue> second = x.getSecond().accept(this);
return from.makeStepRange(to, second, new EvaluatorContext(this, x));
}
@Override
public Result<IValue> visitExpressionTypedVariable(TypedVariable x) {
// TODO: should allow qualified names in TypeVariables?!?
Result<IValue> result = getCurrentEnvt().getVariable(Names.name(x.getName()));
if (result != null && result.getValue() != null) {
return result;
}
throw new UninitializedVariableError(Names.name(x.getName()), x);
}
private boolean matchAndEval(Result<IValue> subject, org.meta_environment.rascal.ast.Expression pat, Statement stat){
Environment old = getCurrentEnvt();
try {
IMatchingResult mp = (IMatchingResult) pat.accept(makePatternEvaluator(pat));
mp.initMatch(subject);
//System.err.println("matchAndEval: subject=" + subject + ", pat=" + pat);
while(mp.hasNext()){
goodPushEnv();
//System.err.println("matchAndEval: mp.hasNext()==true");
if(mp.next()){
//System.err.println("matchAndEval: mp.next()==true");
try {
checkPoint(getCurrentEnvt());
//System.err.println(stat.toString());
try {
stat.accept(this);
} catch (org.meta_environment.rascal.interpreter.control_exceptions.Insert e){
// Make sure that the match pattern is set
if(e.getMatchPattern() == null) {
e.setMatchPattern(mp);
}
throw e;
}
commit(getCurrentEnvt());
return true;
} catch (Failure e){
//System.err.println("failure occurred");
rollback(getCurrentEnvt());
unwind(old);
}
}
}
} finally {
unwind(old);
}
return false;
}
private boolean matchEvalAndReplace(Result<IValue> subject,
org.meta_environment.rascal.ast.Expression pat,
java.util.List<Expression> conditions,
Expression replacementExpr){
Environment old = getCurrentEnvt();
try {
IMatchingResult mp = (IMatchingResult) makeBooleanResult(pat);
mp.initMatch(subject);
//System.err.println("matchEvalAndReplace: subject=" + subject + ", pat=" + pat + ", conditions=" + conditions);
while(mp.hasNext()){
//System.err.println("mp.hasNext()==true; mp=" + mp);
if(mp.next()){
try {
boolean trueConditions = true;
for(Expression cond : conditions){
//System.err.println("cond = " + cond);
if(!cond.accept(this).isTrue()){
trueConditions = false;
//System.err.println("false cond = " + cond);
break;
}
}
if(trueConditions){
//System.err.println("evaluating replacement expression: " + replacementExpr);
throw new org.meta_environment.rascal.interpreter.control_exceptions.Insert(replacementExpr.accept(this), mp);
}
} catch (Failure e){
//System.err.println("failure occurred");
}
}
}
} finally {
unwind(old);
}
return false;
}
@Override
public Result<IValue> visitStatementSwitch(Switch x) {
Result<IValue> subject = x.getExpression().accept(this);
for(Case cs : x.getCases()){
if(cs.isDefault()){
// TODO: what if the default statement uses a fail statement?
return cs.getStatement().accept(this);
}
org.meta_environment.rascal.ast.PatternWithAction rule = cs.getPatternWithAction();
if(rule.isArbitrary() && matchAndEval(subject, rule.getPattern(), rule.getStatement())){
return ResultFactory.nothing();
/*
} else if(rule.isGuarded()) {
org.meta_environment.rascal.ast.Type tp = rule.getType();
Type t = evalType(tp);
if(subject.getType().isSubtypeOf(t) && matchAndEval(subject.getValue(), rule.getPattern(), rule.getStatement())){
return ResultFactory.nothing();
}
*/
} else if(rule.isReplacing()){
throw new NotYetImplemented(rule);
}
}
return null;
}
@Override
public Result<IValue> visitExpressionVisit(Visit x) {
return x.getVisit().accept(this);
}
/*
* TraverseResult contains the value returned by a traversal
* and a changed flag that indicates whether the value itself or
* any of its children has been changed during the traversal.
*/
class TraverseResult {
boolean matched; // Some rule matched;
Result<IValue> value; // Result<IValue> of the
boolean changed; // Original subject has been changed
TraverseResult(boolean someMatch, Result<IValue> value){
this.matched = someMatch;
this.value = value;
this.changed = false;
}
TraverseResult(Result<IValue> value){
this.matched = false;
this.value = value;
this.changed = false;
}
TraverseResult(Result<IValue> value, boolean changed){
this.matched = true;
this.value = value;
this.changed = changed;
}
TraverseResult(boolean someMatch, Result<IValue> value, boolean changed){
this.matched = someMatch;
this.value = value;
this.changed = changed;
}
}
/*
* CaseOrRule is the union of a Case or a Rule and allows the sharing of
* traversal code for both.
*/
class CasesOrRules {
private java.util.List<Case> cases;
private java.util.List<RewriteRule> rules;
CasesOrRules(java.util.List<?> casesOrRules){
if(casesOrRules.get(0) instanceof Case){
this.cases = (java.util.List<Case>) casesOrRules;
} else {
rules = (java.util.List<RewriteRule>)casesOrRules;
}
}
public boolean hasRules(){
return rules != null;
}
public boolean hasCases(){
return cases != null;
}
public int length(){
return (cases != null) ? cases.size() : rules.size();
}
public java.util.List<Case> getCases(){
return cases;
}
public java.util.List<RewriteRule> getRules(){
return rules;
}
}
private TraverseResult traverse(Result<IValue> subject, CasesOrRules casesOrRules,
DIRECTION direction, PROGRESS progress, FIXEDPOINT fixedpoint) {
//System.err.println("traverse: subject=" + subject + ", casesOrRules=" + casesOrRules);
do {
TraverseResult tr = traverseOnce(subject, casesOrRules, direction, progress);
if(fixedpoint == FIXEDPOINT.Yes){
if (!tr.changed) {
return tr;
}
subject = tr.value;
} else {
return tr;
}
} while (true);
}
/*
* StringReplacement represents a single replacement in the subject string.
*/
private class StringReplacement {
int start;
int end;
String replacement;
StringReplacement(int start, int end, String repl){
this.start = start;
this.end = end;
replacement = repl;
}
@Override
public String toString(){
return "StringReplacement(" + start + ", " + end + ", " + replacement + ")";
}
}
/*
* singleCase returns a single case or rules if casesOrRueles has length 1 and null otherwise.
*/
private Object singleCase(CasesOrRules casesOrRules){
if(casesOrRules.length() == 1){
if(casesOrRules.hasCases()){
return casesOrRules.getCases().get(0);
}
return casesOrRules.getRules().get(0);
}
return null;
}
/*
* traverString implements a visit of a string subject and applies the set of cases
* for all substrings of the subject. At the end, all replacements are applied and the modified
* subject is returned.
*/
// TODO: decouple visiting of strings from case statement
private TraverseResult traverseString(Result<IValue> subject, CasesOrRules casesOrRules){
String subjectString = ((IString) subject.getValue()).getValue();
int len = subjectString.length();
java.util.List<StringReplacement> replacements = new ArrayList<StringReplacement>();
boolean matched = false;
boolean changed = false;
int cursor = 0;
Case cs = (Case) singleCase(casesOrRules);
// PatternEvaluator re = new PatternEvaluator(vf, this, getCurrentEnvt());
if(cs != null && cs.isPatternWithAction() && cs.getPatternWithAction().getPattern().isLiteral() && cs.getPatternWithAction().getPattern().getLiteral().isRegExp()){
/*
* In the frequently occurring case that there is one case with a regexp as pattern,
* we can delegate all the work to the regexp matcher.
*/
org.meta_environment.rascal.ast.PatternWithAction rule = cs.getPatternWithAction();
Expression patexp = rule.getPattern();
IMatchingResult mp = (IMatchingResult) makeBooleanResult(patexp);
mp.initMatch(subject);
Environment old = getCurrentEnvt();
try {
while(mp.hasNext()){
if(mp.next()){
try {
if(rule.isReplacing()){
Replacement repl = rule.getReplacement();
boolean trueConditions = true;
if(repl.isConditional()){
for(Expression cond : repl.getConditions()){
Result<IValue> res = cond.accept(this);
if(!res.isTrue()){ // TODO: How about alternatives?
trueConditions = false;
break;
}
}
}
if(trueConditions){
throw new org.meta_environment.rascal.interpreter.control_exceptions.Insert(repl.getReplacementExpression().accept(this), mp);
}
} else {
rule.getStatement().accept(this);
}
} catch (org.meta_environment.rascal.interpreter.control_exceptions.Insert e){
changed = true;
IValue repl = e.getValue().getValue();
if(repl.getType().isStringType()){
int start = ((RegExpPatternValue) mp).getStart();
int end = ((RegExpPatternValue) mp).getEnd();
replacements.add(new StringReplacement(start, end, ((IString)repl).getValue()));
} else {
throw new UnexpectedTypeError(tf.stringType(),repl.getType(), rule);
}
} catch (Failure e){
//System.err.println("failure occurred");
}
}
}
} finally {
unwind(old);
}
} else {
/*
* In all other cases we generate subsequent substrings subject[0,len], subject[1,len] ...
* and try to match all the cases.
* Performance issue: we create a lot of garbage by producing all these substrings.
*/
while(cursor < len){
//System.err.println("cursor = " + cursor);
try {
IString substring = vf.string(subjectString.substring(cursor, len));
Result<IValue> subresult = ResultFactory.makeResult(tf.stringType(), substring, makeEvContext());
TraverseResult tr = applyCasesOrRules(subresult, casesOrRules);
matched |= tr.matched;
changed |= tr.changed;
//System.err.println("matched=" + matched + ", changed=" + changed);
cursor++;
} catch (org.meta_environment.rascal.interpreter.control_exceptions.Insert e){
IValue repl = e.getValue().getValue();
if(repl.getType().isStringType()){
int start;
int end;
IBooleanResult lastPattern = e.getMatchPattern();
if(lastPattern == null)
throw new ImplementationError("no last pattern known");
if(lastPattern instanceof RegExpPatternValue){
start = ((RegExpPatternValue)lastPattern).getStart();
end = ((RegExpPatternValue)lastPattern).getEnd();
} else if(lastPattern instanceof LiteralPattern){
start = 0;
end = ((IString)repl).getValue().length();
} else {
throw new SyntaxError("Illegal pattern " + lastPattern + " in string visit", getCurrentAST().getLocation());
}
replacements.add(new StringReplacement(cursor + start, cursor + end, ((IString)repl).getValue()));
matched = changed = true;
cursor += end;
} else {
throw new UnexpectedTypeError(tf.stringType(),repl.getType(), getCurrentAST());
}
}
}
}
if(!changed){
return new TraverseResult(matched, subject, changed);
}
/*
* The replacements are now known. Create a version of the subject with all replacement applied.
*/
StringBuffer res = new StringBuffer();
cursor = 0;
for(StringReplacement sr : replacements){
for( ;cursor < sr.start; cursor++){
res.append(subjectString.charAt(cursor));
}
cursor = sr.end;
res.append(sr.replacement);
}
for( ; cursor < len; cursor++){
res.append(subjectString.charAt(cursor));
}
return new TraverseResult(matched, ResultFactory.makeResult(tf.stringType(), vf.string(res.toString()), makeEvContext()), changed);
}
/*
* traverseOnce: traverse an arbitrary IVAlue once. Implements the strategies bottomup/topdown.
*/
private TraverseResult traverseOnce(Result<IValue> subject, CasesOrRules casesOrRules,
DIRECTION direction,
PROGRESS progress){
Type subjectType = subject.getType();
boolean matched = false;
boolean changed = false;
Result<IValue> result = subject;
//System.err.println("traverseOnce: " + subject + ", type=" + subject.getType());
if(subjectType.isStringType()){
return traverseString(subject, casesOrRules);
}
if(direction == DIRECTION.TopDown){
TraverseResult tr = traverseTop(subject, casesOrRules);
matched |= tr.matched;
changed |= tr.changed;
if((progress == PROGRESS.Breaking) && changed){
return tr;
}
subject = tr.value;
}
if(subjectType.isAbstractDataType()){
IConstructor cons = (IConstructor)subject.getValue();
if(cons.arity() == 0){
result = subject;
} else {
IValue args[] = new IValue[cons.arity()];
for(int i = 0; i < cons.arity(); i++){
IValue child = cons.get(i);
Type childType = cons.getConstructorType().getFieldType(i);
TraverseResult tr = traverseOnce(ResultFactory.makeResult(childType, child, makeEvContext()), casesOrRules, direction, progress);
matched |= tr.matched;
changed |= tr.changed;
args[i] = tr.value.getValue();
}
IConstructor rcons = vf.constructor(cons.getConstructorType(), args);
result = applyRules(makeResult(subjectType, rcons.setAnnotations(cons.getAnnotations()), makeEvContext()));
}
} else
if(subjectType.isNodeType()){
INode node = (INode)subject.getValue();
if(node.arity() == 0){
result = subject;
} else {
IValue args[] = new IValue[node.arity()];
for(int i = 0; i < node.arity(); i++){
IValue child = node.get(i);
TraverseResult tr = traverseOnce(ResultFactory.makeResult(tf.valueType(), child, makeEvContext()), casesOrRules, direction, progress);
matched |= tr.matched;
changed |= tr.changed;
args[i] = tr.value.getValue();
}
result = applyRules(makeResult(tf.nodeType(), vf.node(node.getName(), args).setAnnotations(node.getAnnotations()), makeEvContext()));
}
} else
if(subjectType.isListType()){
- IList list = (IList) subject;
+ IList list = (IList) subject.getValue();
int len = list.length();
if(len > 0){
IListWriter w = list.getType().writer(vf);
Type elemType = list.getType().getElementType();
for(int i = len - 1; i >= 0; i--){
IValue elem = list.get(i);
TraverseResult tr = traverseOnce(ResultFactory.makeResult(elemType, elem, makeEvContext()), casesOrRules, direction, progress);
matched |= tr.matched;
changed |= tr.changed;
w.insert(tr.value.getValue());
}
result = makeResult(subjectType, w.done(), makeEvContext());
} else {
result = subject;
}
} else
if(subjectType.isSetType()){
ISet set = (ISet) subject;
if(!set.isEmpty()){
ISetWriter w = set.getType().writer(vf);
Type elemType = set.getType().getElementType();
for (IValue v : set){
TraverseResult tr = traverseOnce(ResultFactory.makeResult(elemType, v, makeEvContext()), casesOrRules, direction, progress);
matched |= tr.matched;
changed |= tr.changed;
w.insert(tr.value.getValue());
}
result = makeResult(subjectType, w.done(), makeEvContext());
} else {
result = subject;
}
} else
if (subjectType.isMapType()) {
IMap map = (IMap) subject.getValue();
if(!map.isEmpty()){
IMapWriter w = map.getType().writer(vf);
Iterator<Entry<IValue,IValue>> iter = map.entryIterator();
Type keyType = map.getKeyType();
Type valueType = map.getValueType();
while (iter.hasNext()) {
Entry<IValue,IValue> entry = iter.next();
TraverseResult tr = traverseOnce(ResultFactory.makeResult(keyType, entry.getKey(), makeEvContext()), casesOrRules, direction, progress);
matched |= tr.matched;
changed |= tr.changed;
IValue newKey = tr.value.getValue();
tr = traverseOnce(ResultFactory.makeResult(valueType, entry.getValue(), makeEvContext()), casesOrRules, direction, progress);
matched |= tr.matched;
changed |= tr.changed;
IValue newValue = tr.value.getValue();
w.put(newKey, newValue);
}
result = makeResult(subjectType, w.done(), makeEvContext());
} else {
result = subject;
}
} else
if(subjectType.isTupleType()){
ITuple tuple = (ITuple) subject.getValue();
int arity = tuple.arity();
IValue args[] = new IValue[arity];
for(int i = 0; i < arity; i++){
Type fieldType = subjectType.getFieldType(i);
TraverseResult tr = traverseOnce(ResultFactory.makeResult(fieldType, tuple.get(i), makeEvContext()), casesOrRules, direction, progress);
matched |= tr.matched;
changed |= tr.changed;
args[i] = tr.value.getValue();
}
result = makeResult(subjectType, vf.tuple(args), makeEvContext());
} else {
result = subject;
}
if(direction == DIRECTION.BottomUp){
if((progress == PROGRESS.Breaking) && changed){
return new TraverseResult(matched, result, changed);
}
TraverseResult tr = traverseTop(result, casesOrRules);
matched |= tr.matched;
changed |= tr.changed;
return new TraverseResult(matched, tr.value, changed);
}
return new TraverseResult(matched,result,changed);
}
/**
* Replace an old subject by a new one as result of an insert statement.
*/
private TraverseResult replacement(Result<IValue> oldSubject, Result<IValue> newSubject){
if(newSubject.getType().equivalent((oldSubject.getType())))
return new TraverseResult(true, newSubject, true);
throw new UnexpectedTypeError(oldSubject.getType(), newSubject.getType(), getCurrentAST());
}
/**
* Loop over all cases or rules.
*/
private TraverseResult applyCasesOrRules(Result<IValue> subject, CasesOrRules casesOrRules) {
if(casesOrRules.hasCases()){
for (Case cs : casesOrRules.getCases()) {
setCurrentAST(cs);
if (cs.isDefault()) {
cs.getStatement().accept(this);
return new TraverseResult(true,subject);
}
TraverseResult tr = applyOneRule(subject, cs.getPatternWithAction());
if(tr.matched){
return tr;
}
}
} else {
//System.err.println("hasRules");
for(RewriteRule rule : casesOrRules.getRules()){
setCurrentAST(rule.getRule());
Environment oldEnv = getCurrentEnvt();
setCurrentEnvt(rule.getEnvironment());
try {
TraverseResult tr = applyOneRule(subject, rule.getRule());
if(tr.matched){
return tr;
}
}
finally {
setCurrentEnvt(oldEnv);
}
}
}
//System.err.println("applyCasesorRules does not match");
return new TraverseResult(subject);
}
/*
* traverseTop: traverse the outermost symbol of the subject.
*/
private TraverseResult traverseTop(Result<IValue> subject, CasesOrRules casesOrRules) {
//System.err.println("traversTop(" + subject + ")");
try {
return applyCasesOrRules(subject, casesOrRules);
} catch (org.meta_environment.rascal.interpreter.control_exceptions.Insert e) {
return replacement(subject, e.getValue());
}
}
/*
* applyOneRule: try to apply one rule to the subject.
*/
private TraverseResult applyOneRule(Result<IValue> subject,
org.meta_environment.rascal.ast.PatternWithAction rule) {
//System.err.println("applyOneRule: subject=" + subject + ", type=" + subject.getType() + ", rule=" + rule);
if (rule.isArbitrary()){
if(matchAndEval(subject, rule.getPattern(), rule.getStatement())) {
return new TraverseResult(true, subject);
}
/*
} else if (rule.isGuarded()) {
org.meta_environment.rascal.ast.Type tp = rule.getType();
Type type = evalType(tp);
rule = rule.getRule();
if (subject.getType().isSubtypeOf(type) &&
matchAndEval(subject, rule.getPattern(), rule.getStatement())) {
return new TraverseResult(true, subject);
}
*/
} else if (rule.isReplacing()) {
Replacement repl = rule.getReplacement();
java.util.List<Expression> conditions = repl.isConditional() ? repl.getConditions() : new ArrayList<Expression>();
if(matchEvalAndReplace(subject, rule.getPattern(), conditions, repl.getReplacementExpression())){
return new TraverseResult(true, subject);
}
} else {
throw new ImplementationError("Impossible case in rule");
}
return new TraverseResult(subject);
}
@Override
public Result<IValue> visitVisitDefaultStrategy(DefaultStrategy x) {
Result<IValue> subject = x.getSubject().accept(this);
java.util.List<Case> cases = x.getCases();
TraverseResult tr = traverse(subject, new CasesOrRules(cases),
DIRECTION.BottomUp,
PROGRESS.Continuing,
FIXEDPOINT.No);
return tr.value;
}
@Override
public Result<IValue> visitVisitGivenStrategy(GivenStrategy x) {
Result<IValue> subject = x.getSubject().accept(this);
// TODO: warning switched to static type here, but not sure if that's correct...
Type subjectType = subject.getType();
if(subjectType.isConstructorType()){
subjectType = subjectType.getAbstractDataType();
}
java.util.List<Case> cases = x.getCases();
Strategy s = x.getStrategy();
DIRECTION direction = DIRECTION.BottomUp;
PROGRESS progress = PROGRESS.Continuing;
FIXEDPOINT fixedpoint = FIXEDPOINT.No;
if(s.isBottomUp()){
direction = DIRECTION.BottomUp;
} else if(s.isBottomUpBreak()){
direction = DIRECTION.BottomUp;
progress = PROGRESS.Breaking;
} else if(s.isInnermost()){
direction = DIRECTION.BottomUp;
fixedpoint = FIXEDPOINT.Yes;
} else if(s.isTopDown()){
direction = DIRECTION.TopDown;
} else if(s.isTopDownBreak()){
direction = DIRECTION.TopDown;
progress = PROGRESS.Breaking;
} else if(s.isOutermost()){
direction = DIRECTION.TopDown;
fixedpoint = FIXEDPOINT.Yes;
} else {
throw new ImplementationError("Unknown strategy " + s);
}
TraverseResult tr = traverse(subject, new CasesOrRules(cases), direction, progress, fixedpoint);
return tr.value;
}
@Override
public Result<IValue> visitExpressionNonEquals(
org.meta_environment.rascal.ast.Expression.NonEquals x) {
Result<IValue> left = x.getLhs().accept(this);
Result<IValue> right = x.getRhs().accept(this);
return left.nonEquals(right, new EvaluatorContext(this, x));
}
@Override
public Result<IValue> visitExpressionLessThan(LessThan x) {
Result<IValue> left = x.getLhs().accept(this);
Result<IValue> right = x.getRhs().accept(this);
return left.lessThan(right, new EvaluatorContext(this, x));
}
@Override
public Result<IValue> visitExpressionLessThanOrEq(LessThanOrEq x) {
Result<IValue> left = x.getLhs().accept(this);
Result<IValue> right = x.getRhs().accept(this);
return left.lessThanOrEqual(right, new EvaluatorContext(this, x));
}
@Override
public Result<IValue> visitExpressionGreaterThan(GreaterThan x) {
Result<IValue> left = x.getLhs().accept(this);
Result<IValue> right = x.getRhs().accept(this);
return left.greaterThan(right, new EvaluatorContext(this, x));
}
@Override
public Result<IValue> visitExpressionGreaterThanOrEq(GreaterThanOrEq x) {
Result<IValue> left = x.getLhs().accept(this);
Result<IValue> right = x.getRhs().accept(this);
return left.greaterThanOrEqual(right, new EvaluatorContext(this, x));
}
@Override
public Result<IValue> visitExpressionIfThenElse(
org.meta_environment.rascal.ast.Expression.IfThenElse x) {
Result<IValue> cval = x.getCondition().accept(this);
if (!cval.getType().isBoolType()) {
throw new UnexpectedTypeError(tf.boolType(), cval.getType(), x);
}
if (cval.isTrue()) {
return x.getThenExp().accept(this);
}
return x.getElseExp().accept(this);
}
@Override
public Result<IValue> visitExpressionIfDefinedOtherwise(IfDefinedOtherwise x) {
try {
return x.getLhs().accept(this);
}
catch (UninitializedVariableError e){
return x.getRhs().accept(this);
}
catch (org.meta_environment.rascal.interpreter.control_exceptions.Throw e) {
// TODO For now we accept any Throw here, restrict to NoSuchKey and NoSuchAnno?
return x.getRhs().accept(this);
}
}
@Override
public Result<IValue> visitExpressionIsDefined(IsDefined x) {
try {
x.getArgument().accept(this); // wait for exception
return makeResult(tf.boolType(), vf.bool(true), new EvaluatorContext(this, x));
} catch (org.meta_environment.rascal.interpreter.control_exceptions.Throw e) {
// TODO For now we accept any Throw here, restrict to NoSuchKey and NoSuchAnno?
return makeResult(tf.boolType(), vf.bool(false), new EvaluatorContext(this, x));
}
}
@Override
public Result<IValue> visitExpressionIn(In x) {
Result<IValue> left = x.getLhs().accept(this);
Result<IValue> right = x.getRhs().accept(this);
// TODO:?!?!!? makes this less obtrusive?
return right.in(left, new EvaluatorContext(this, x));
//return result(vf.bool(in(x.getLhs(), x.getRhs())));
}
@Override
public Result<IValue> visitExpressionNotIn(NotIn x) {
Result<IValue> left = x.getLhs().accept(this);
Result<IValue> right = x.getRhs().accept(this);
// TODO:?!?!!? makes this less obtrusive?
return right.notIn(left, new EvaluatorContext(this, x));
//return result(vf.bool(!in(x.getLhs(), x.getRhs())));
}
@Override
public Result<IValue> visitExpressionComposition(Composition x) {
Result<IValue> left = x.getLhs().accept(this);
Result<IValue> right = x.getRhs().accept(this);
return left.compose(right, new EvaluatorContext(this, x));
}
@Override
public Result<IValue> visitExpressionTransitiveClosure(TransitiveClosure x) {
return x.getArgument().accept(this).transitiveClosure(new EvaluatorContext(this, x));
}
@Override
public Result<IValue> visitExpressionTransitiveReflexiveClosure(TransitiveReflexiveClosure x) {
return x.getArgument().accept(this).transitiveReflexiveClosure(new EvaluatorContext(this, x));
}
// Comprehensions ----------------------------------------------------
@Override
public Result<IValue> visitExpressionComprehension(Comprehension x) {
return x.getComprehension().accept(this);
}
@Override
public Result<IValue> visitExpressionEnumerator(
org.meta_environment.rascal.ast.Expression.Enumerator x) {
return evalBooleanExpression(x);
}
@Override
public Result<IValue> visitExpressionEnumeratorWithStrategy(
EnumeratorWithStrategy x) {
return evalBooleanExpression(x);
}
private Result<IValue> makeGenerator(Expression x){
return evalBooleanExpression(x);
}
/*
* ComprehensionWriter provides a uniform framework for writing elements
* to a list/set/map during the evaluation of a list/set/map comprehension.
*/
private abstract class ComprehensionWriter {
protected Type elementType1;
protected Type elementType2;
protected Type resultType;
protected java.util.List<org.meta_environment.rascal.ast.Expression> resultExprs;
protected IWriter writer;
protected Evaluator ev;
ComprehensionWriter(
java.util.List<org.meta_environment.rascal.ast.Expression> resultExprs,
Evaluator ev){
this.ev = ev;
this.resultExprs = resultExprs;
this.writer = null;
}
public void check(Result<IValue> r, Type t, String kind, org.meta_environment.rascal.ast.Expression expr){
if(!r.getType().isSubtypeOf(t)){
throw new UnexpectedTypeError(t, r.getType() ,
expr);
}
}
public EvaluatorContext getContext(AbstractAST ast) {
return new EvaluatorContext(ev, ast);
}
public abstract void append();
public abstract Result<IValue> done();
}
private class ListComprehensionWriter extends
ComprehensionWriter {
private boolean splicing[];
ListComprehensionWriter(
java.util.List<org.meta_environment.rascal.ast.Expression> resultExprs,
Evaluator ev) {
super(resultExprs, ev);
splicing = new boolean[resultExprs.size()];
}
@Override
public void append() {
if(writer == null){
int k = 0;
elementType1 = tf.voidType();
for(Expression resExpr : resultExprs){
Result<IValue> res = resExpr.accept(ev);
Type elementType = res.getType();
if(elementType.isListType() && !resExpr.isList()){
elementType = elementType.getElementType();
splicing[k] = true;
} else
splicing[k] = false;
k++;
elementType1 = elementType1.lub(elementType);
}
resultType = tf.listType(elementType1);
writer = resultType.writer(vf);
}
int k = 0;
for(Expression resExpr : resultExprs){
Result<IValue> res = resExpr.accept(ev);
if(splicing[k++]){
/*
* Splice elements of the value of the result expression in the result list
*/
for(IValue val : ((IList) res.getValue())){
if(!val.getType().isSubtypeOf(elementType1))
throw new UnexpectedTypeError(elementType1, val.getType(), resExpr);
elementType1 = elementType1.lub(val.getType());
((IListWriter) writer).append(val);
}
} else {
check(res, elementType1, "list", resExpr);
elementType1 = elementType1.lub(res.getType());
((IListWriter) writer).append(res.getValue());
}
}
}
@Override
public Result<IValue> done() {
return (writer == null) ? makeResult(tf.listType(tf.voidType()), vf.list(), getContext(resultExprs.get(0))) :
makeResult(tf.listType(elementType1), writer.done(), getContext(resultExprs.get(0)));
}
}
private class SetComprehensionWriter extends
ComprehensionWriter {
private boolean splicing[];
SetComprehensionWriter(
java.util.List<org.meta_environment.rascal.ast.Expression> resultExprs,
Evaluator ev) {
super(resultExprs, ev);
splicing = new boolean[resultExprs.size()];
}
@Override
public void append() {
if(writer == null){
int k = 0;
elementType1 = tf.voidType();
for(Expression resExpr : resultExprs){
Result<IValue> res = resExpr.accept(ev);
Type elementType = res.getType();
if(elementType.isSetType() && !resExpr.isSet()){
elementType = elementType.getElementType();
splicing[k] = true;
} else
splicing[k] = false;
k++;
elementType1 = elementType1.lub(elementType);
}
resultType = tf.setType(elementType1);
writer = resultType.writer(vf);
}
int k = 0;
for(Expression resExpr : resultExprs){
Result<IValue> res = resExpr.accept(ev);
if(splicing[k++]){
/*
* Splice elements of the value of the result expression in the result set
*/
for(IValue val : ((ISet) res.getValue())){
if(!val.getType().isSubtypeOf(elementType1))
throw new UnexpectedTypeError(elementType1, val.getType(), resExpr);
elementType1 = elementType1.lub(val.getType());
((ISetWriter) writer).insert(val);
}
} else {
check(res, elementType1, "set", resExpr);
elementType1 = elementType1.lub(res.getType());
((ISetWriter) writer).insert(res.getValue());
}
}
}
@Override
public Result<IValue> done() {
return (writer == null) ? makeResult(tf.setType(tf.voidType()), vf.set(), getContext(resultExprs.get(0))) :
makeResult(tf.setType(elementType1), writer.done(), getContext(resultExprs.get(0)));
}
}
private class MapComprehensionWriter extends
ComprehensionWriter {
MapComprehensionWriter(
java.util.List<org.meta_environment.rascal.ast.Expression> resultExprs,
Evaluator ev) {
super(resultExprs, ev);
if(resultExprs.size() != 2)
throw new ImplementationError("Map comprehensions needs two result expressions");
}
@Override
public void append() {
Result<IValue> r1 = resultExprs.get(0).accept(ev);
Result<IValue> r2 = resultExprs.get(1).accept(ev);
if (writer == null) {
elementType1 = r1.getType();
elementType2 = r2.getType();
resultType = tf.mapType(elementType1, elementType2);
writer = resultType.writer(vf);
}
check(r1, elementType1, "map", resultExprs.get(0));
check(r2, elementType2, "map", resultExprs.get(1));
((IMapWriter) writer).put(r1.getValue(), r2.getValue());
}
@Override
public Result<IValue> done() {
return (writer == null) ?
makeResult(tf.mapType(tf.voidType(), tf.voidType()), vf.map(tf.voidType(), tf.voidType()), getContext(resultExprs.get(0)))
: makeResult(tf.mapType(elementType1, elementType2), writer.done(), getContext(resultExprs.get(0)));
}
}
/*
* The common comprehension evaluator
*/
private Result<IValue> evalComprehension(java.util.List<Expression> generators,
ComprehensionWriter w){
int size = generators.size();
IBooleanResult[] gens = new IBooleanResult[size];
Environment[] olds = new Environment[size];
Environment old = getCurrentEnvt();
int i = 0;
try {
gens[0] = makeBooleanResult(generators.get(0));
gens[0].init();
olds[0] = getCurrentEnvt();
goodPushEnv();
while (i >= 0 && i < size) {
if (gens[i].hasNext() && gens[i].next()) {
if(i == size - 1){
w.append();
unwind(olds[i]);
goodPushEnv();
}
else {
i++;
gens[i] = makeBooleanResult(generators.get(i));
gens[i].init();
olds[i] = getCurrentEnvt();
goodPushEnv();
}
} else {
unwind(olds[i]);
i--;
}
}
}
finally {
unwind(old);
}
return w.done();
}
@Override
public Result<IValue> visitComprehensionList(org.meta_environment.rascal.ast.Comprehension.List x) {
return evalComprehension(
x.getGenerators(),
new ListComprehensionWriter(x.getResults(), this));
}
@Override
public Result<IValue> visitComprehensionSet(
org.meta_environment.rascal.ast.Comprehension.Set x) {
return evalComprehension(
x.getGenerators(),
new SetComprehensionWriter(x.getResults(), this));
}
@Override
public Result<IValue> visitComprehensionMap(
org.meta_environment.rascal.ast.Comprehension.Map x) {
java.util.List<Expression> resultExprs = new LinkedList<Expression>();
resultExprs.add(x.getFrom());
resultExprs.add(x.getTo());
return evalComprehension(
x.getGenerators(),
new MapComprehensionWriter(resultExprs, this));
}
@Override
public Result<IValue> visitStatementFor(For x) {
Statement body = x.getBody();
java.util.List<Expression> generators = x.getGenerators();
int size = generators.size();
IBooleanResult[] gens = new IBooleanResult[size];
Environment old = getCurrentEnvt();
Environment[] olds = new Environment[size];
Result<IValue> result = nothing();
// TODO: does this prohibit that the body influences the behavior of the generators??
int i = 0;
try {
gens[0] = makeBooleanResult(generators.get(0));
gens[0].init();
olds[0] = getCurrentEnvt();
goodPushEnv();
while(i >= 0 && i < size) {
if(gens[i].hasNext() && gens[i].next()){
if(i == size - 1){
result = body.accept(this);
} else {
i++;
gens[i] = makeBooleanResult(generators.get(i));
gens[i].init();
olds[i] = getCurrentEnvt();
goodPushEnv();
}
} else {
unwind(olds[i]);
i--;
goodPushEnv();
}
}
} finally {
unwind(old);
}
return result;
}
@Override
public Result visitExpressionAny(Any x) {
java.util.List<Expression> generators = x.getGenerators();
int size = generators.size();
IBooleanResult[] gens = new IBooleanResult[size];
int i = 0;
gens[0] = makeBooleanResult(generators.get(0));
gens[0].init();
while (i >= 0 && i < size) {
if (gens[i].hasNext() && gens[i].next()) {
if (i == size - 1) {
return new BoolResult(true, null, null);
}
i++;
gens[i] = makeBooleanResult(generators.get(i));
gens[i].init();
} else {
i--;
}
}
return new BoolResult(false, null, null);
}
@Override
public Result visitExpressionAll(All x) {
java.util.List<Expression> producers = x.getGenerators();
int size = producers.size();
IBooleanResult[] gens = new IBooleanResult[size];
int i = 0;
gens[0] = makeBooleanResult(producers.get(0));
gens[0].init();
while (i >= 0 && i < size) {
if (gens[i].hasNext()) {
if (!gens[i].next()) {
return new BoolResult(false, null, null);
}
if (i < size - 1) {
i++;
gens[i] = makeBooleanResult(producers.get(i));
gens[i].init();
}
} else {
i--;
}
}
return new BoolResult(true, null, null);
}
// ------------ solve -----------------------------------------
@Override
public Result<IValue> visitStatementSolve(Solve x) {
java.util.ArrayList<org.meta_environment.rascal.ast.Variable> vars = new java.util.ArrayList<org.meta_environment.rascal.ast.Variable>();
Environment old = getCurrentEnvt();
goodPushEnv();
try {
for(Declarator d : x.getDeclarations()){
for(org.meta_environment.rascal.ast.Variable v : d.getVariables()){
vars.add(v);
}
d.accept(this);
}
IValue currentValue[] = new IValue[vars.size()];
for(int i = 0; i < vars.size(); i++){
org.meta_environment.rascal.ast.Variable v = vars.get(i);
currentValue[i] = getCurrentEnvt().getVariable(v, Names.name(v.getName())).getValue();
}
Statement body = x.getBody();
int max = -1;
Bound bound= x.getBound();
if(bound.isDefault()){
Result<IValue> res = bound.getExpression().accept(this);
if(!res.getType().isIntegerType()){
throw new UnexpectedTypeError(tf.integerType(),res.getType(), x);
}
max = ((IInteger)res.getValue()).intValue();
if(max <= 0){
throw RuntimeExceptionFactory.indexOutOfBounds((IInteger) res.getValue(), getCurrentAST(), getStackTrace());
}
}
Result<IValue> bodyResult = null;
boolean change = true;
int iterations = 0;
while (change && (max == -1 || iterations < max)){
change = false;
iterations++;
bodyResult = body.accept(this);
for(int i = 0; i < vars.size(); i++){
org.meta_environment.rascal.ast.Variable var = vars.get(i);
Result<IValue> v = getCurrentEnvt().getVariable(var, Names.name(var.getName()));
if(currentValue[i] == null || !v.getValue().isEqual(currentValue[i])){
change = true;
currentValue[i] = v.getValue();
}
}
}
return bodyResult;
}
finally {
unwind(old);
}
}
public Stack<Environment> getCallStack() {
Stack<Environment> stack = new Stack<Environment>();
Environment env = currentEnvt;
while (env != null) {
stack.add(0, env);
env = env.getCallerScope();
}
return stack;
}
public ModuleLoader getModuleLoader() {
return loader;
}
public Environment getCurrentEnvt() {
return currentEnvt;
}
public void setCurrentEnvt(Environment env) {
currentEnvt = env;
}
public IConstructor parseCommand(String command) throws IOException {
throw new ImplementationError("should not be called in Evaluator but only in subclasses");
}
}
| true | true | private TraverseResult traverseOnce(Result<IValue> subject, CasesOrRules casesOrRules,
DIRECTION direction,
PROGRESS progress){
Type subjectType = subject.getType();
boolean matched = false;
boolean changed = false;
Result<IValue> result = subject;
//System.err.println("traverseOnce: " + subject + ", type=" + subject.getType());
if(subjectType.isStringType()){
return traverseString(subject, casesOrRules);
}
if(direction == DIRECTION.TopDown){
TraverseResult tr = traverseTop(subject, casesOrRules);
matched |= tr.matched;
changed |= tr.changed;
if((progress == PROGRESS.Breaking) && changed){
return tr;
}
subject = tr.value;
}
if(subjectType.isAbstractDataType()){
IConstructor cons = (IConstructor)subject.getValue();
if(cons.arity() == 0){
result = subject;
} else {
IValue args[] = new IValue[cons.arity()];
for(int i = 0; i < cons.arity(); i++){
IValue child = cons.get(i);
Type childType = cons.getConstructorType().getFieldType(i);
TraverseResult tr = traverseOnce(ResultFactory.makeResult(childType, child, makeEvContext()), casesOrRules, direction, progress);
matched |= tr.matched;
changed |= tr.changed;
args[i] = tr.value.getValue();
}
IConstructor rcons = vf.constructor(cons.getConstructorType(), args);
result = applyRules(makeResult(subjectType, rcons.setAnnotations(cons.getAnnotations()), makeEvContext()));
}
} else
if(subjectType.isNodeType()){
INode node = (INode)subject.getValue();
if(node.arity() == 0){
result = subject;
} else {
IValue args[] = new IValue[node.arity()];
for(int i = 0; i < node.arity(); i++){
IValue child = node.get(i);
TraverseResult tr = traverseOnce(ResultFactory.makeResult(tf.valueType(), child, makeEvContext()), casesOrRules, direction, progress);
matched |= tr.matched;
changed |= tr.changed;
args[i] = tr.value.getValue();
}
result = applyRules(makeResult(tf.nodeType(), vf.node(node.getName(), args).setAnnotations(node.getAnnotations()), makeEvContext()));
}
} else
if(subjectType.isListType()){
IList list = (IList) subject;
int len = list.length();
if(len > 0){
IListWriter w = list.getType().writer(vf);
Type elemType = list.getType().getElementType();
for(int i = len - 1; i >= 0; i--){
IValue elem = list.get(i);
TraverseResult tr = traverseOnce(ResultFactory.makeResult(elemType, elem, makeEvContext()), casesOrRules, direction, progress);
matched |= tr.matched;
changed |= tr.changed;
w.insert(tr.value.getValue());
}
result = makeResult(subjectType, w.done(), makeEvContext());
} else {
result = subject;
}
} else
if(subjectType.isSetType()){
ISet set = (ISet) subject;
if(!set.isEmpty()){
ISetWriter w = set.getType().writer(vf);
Type elemType = set.getType().getElementType();
for (IValue v : set){
TraverseResult tr = traverseOnce(ResultFactory.makeResult(elemType, v, makeEvContext()), casesOrRules, direction, progress);
matched |= tr.matched;
changed |= tr.changed;
w.insert(tr.value.getValue());
}
result = makeResult(subjectType, w.done(), makeEvContext());
} else {
result = subject;
}
} else
if (subjectType.isMapType()) {
IMap map = (IMap) subject.getValue();
if(!map.isEmpty()){
IMapWriter w = map.getType().writer(vf);
Iterator<Entry<IValue,IValue>> iter = map.entryIterator();
Type keyType = map.getKeyType();
Type valueType = map.getValueType();
while (iter.hasNext()) {
Entry<IValue,IValue> entry = iter.next();
TraverseResult tr = traverseOnce(ResultFactory.makeResult(keyType, entry.getKey(), makeEvContext()), casesOrRules, direction, progress);
matched |= tr.matched;
changed |= tr.changed;
IValue newKey = tr.value.getValue();
tr = traverseOnce(ResultFactory.makeResult(valueType, entry.getValue(), makeEvContext()), casesOrRules, direction, progress);
matched |= tr.matched;
changed |= tr.changed;
IValue newValue = tr.value.getValue();
w.put(newKey, newValue);
}
result = makeResult(subjectType, w.done(), makeEvContext());
} else {
result = subject;
}
} else
if(subjectType.isTupleType()){
ITuple tuple = (ITuple) subject.getValue();
int arity = tuple.arity();
IValue args[] = new IValue[arity];
for(int i = 0; i < arity; i++){
Type fieldType = subjectType.getFieldType(i);
TraverseResult tr = traverseOnce(ResultFactory.makeResult(fieldType, tuple.get(i), makeEvContext()), casesOrRules, direction, progress);
matched |= tr.matched;
changed |= tr.changed;
args[i] = tr.value.getValue();
}
result = makeResult(subjectType, vf.tuple(args), makeEvContext());
} else {
result = subject;
}
if(direction == DIRECTION.BottomUp){
if((progress == PROGRESS.Breaking) && changed){
return new TraverseResult(matched, result, changed);
}
TraverseResult tr = traverseTop(result, casesOrRules);
matched |= tr.matched;
changed |= tr.changed;
return new TraverseResult(matched, tr.value, changed);
}
return new TraverseResult(matched,result,changed);
}
| private TraverseResult traverseOnce(Result<IValue> subject, CasesOrRules casesOrRules,
DIRECTION direction,
PROGRESS progress){
Type subjectType = subject.getType();
boolean matched = false;
boolean changed = false;
Result<IValue> result = subject;
//System.err.println("traverseOnce: " + subject + ", type=" + subject.getType());
if(subjectType.isStringType()){
return traverseString(subject, casesOrRules);
}
if(direction == DIRECTION.TopDown){
TraverseResult tr = traverseTop(subject, casesOrRules);
matched |= tr.matched;
changed |= tr.changed;
if((progress == PROGRESS.Breaking) && changed){
return tr;
}
subject = tr.value;
}
if(subjectType.isAbstractDataType()){
IConstructor cons = (IConstructor)subject.getValue();
if(cons.arity() == 0){
result = subject;
} else {
IValue args[] = new IValue[cons.arity()];
for(int i = 0; i < cons.arity(); i++){
IValue child = cons.get(i);
Type childType = cons.getConstructorType().getFieldType(i);
TraverseResult tr = traverseOnce(ResultFactory.makeResult(childType, child, makeEvContext()), casesOrRules, direction, progress);
matched |= tr.matched;
changed |= tr.changed;
args[i] = tr.value.getValue();
}
IConstructor rcons = vf.constructor(cons.getConstructorType(), args);
result = applyRules(makeResult(subjectType, rcons.setAnnotations(cons.getAnnotations()), makeEvContext()));
}
} else
if(subjectType.isNodeType()){
INode node = (INode)subject.getValue();
if(node.arity() == 0){
result = subject;
} else {
IValue args[] = new IValue[node.arity()];
for(int i = 0; i < node.arity(); i++){
IValue child = node.get(i);
TraverseResult tr = traverseOnce(ResultFactory.makeResult(tf.valueType(), child, makeEvContext()), casesOrRules, direction, progress);
matched |= tr.matched;
changed |= tr.changed;
args[i] = tr.value.getValue();
}
result = applyRules(makeResult(tf.nodeType(), vf.node(node.getName(), args).setAnnotations(node.getAnnotations()), makeEvContext()));
}
} else
if(subjectType.isListType()){
IList list = (IList) subject.getValue();
int len = list.length();
if(len > 0){
IListWriter w = list.getType().writer(vf);
Type elemType = list.getType().getElementType();
for(int i = len - 1; i >= 0; i--){
IValue elem = list.get(i);
TraverseResult tr = traverseOnce(ResultFactory.makeResult(elemType, elem, makeEvContext()), casesOrRules, direction, progress);
matched |= tr.matched;
changed |= tr.changed;
w.insert(tr.value.getValue());
}
result = makeResult(subjectType, w.done(), makeEvContext());
} else {
result = subject;
}
} else
if(subjectType.isSetType()){
ISet set = (ISet) subject;
if(!set.isEmpty()){
ISetWriter w = set.getType().writer(vf);
Type elemType = set.getType().getElementType();
for (IValue v : set){
TraverseResult tr = traverseOnce(ResultFactory.makeResult(elemType, v, makeEvContext()), casesOrRules, direction, progress);
matched |= tr.matched;
changed |= tr.changed;
w.insert(tr.value.getValue());
}
result = makeResult(subjectType, w.done(), makeEvContext());
} else {
result = subject;
}
} else
if (subjectType.isMapType()) {
IMap map = (IMap) subject.getValue();
if(!map.isEmpty()){
IMapWriter w = map.getType().writer(vf);
Iterator<Entry<IValue,IValue>> iter = map.entryIterator();
Type keyType = map.getKeyType();
Type valueType = map.getValueType();
while (iter.hasNext()) {
Entry<IValue,IValue> entry = iter.next();
TraverseResult tr = traverseOnce(ResultFactory.makeResult(keyType, entry.getKey(), makeEvContext()), casesOrRules, direction, progress);
matched |= tr.matched;
changed |= tr.changed;
IValue newKey = tr.value.getValue();
tr = traverseOnce(ResultFactory.makeResult(valueType, entry.getValue(), makeEvContext()), casesOrRules, direction, progress);
matched |= tr.matched;
changed |= tr.changed;
IValue newValue = tr.value.getValue();
w.put(newKey, newValue);
}
result = makeResult(subjectType, w.done(), makeEvContext());
} else {
result = subject;
}
} else
if(subjectType.isTupleType()){
ITuple tuple = (ITuple) subject.getValue();
int arity = tuple.arity();
IValue args[] = new IValue[arity];
for(int i = 0; i < arity; i++){
Type fieldType = subjectType.getFieldType(i);
TraverseResult tr = traverseOnce(ResultFactory.makeResult(fieldType, tuple.get(i), makeEvContext()), casesOrRules, direction, progress);
matched |= tr.matched;
changed |= tr.changed;
args[i] = tr.value.getValue();
}
result = makeResult(subjectType, vf.tuple(args), makeEvContext());
} else {
result = subject;
}
if(direction == DIRECTION.BottomUp){
if((progress == PROGRESS.Breaking) && changed){
return new TraverseResult(matched, result, changed);
}
TraverseResult tr = traverseTop(result, casesOrRules);
matched |= tr.matched;
changed |= tr.changed;
return new TraverseResult(matched, tr.value, changed);
}
return new TraverseResult(matched,result,changed);
}
|
diff --git a/src/main/java/org/apache/commons/codec/digest/Sha2Crypt.java b/src/main/java/org/apache/commons/codec/digest/Sha2Crypt.java
index def37892..9c973992 100644
--- a/src/main/java/org/apache/commons/codec/digest/Sha2Crypt.java
+++ b/src/main/java/org/apache/commons/codec/digest/Sha2Crypt.java
@@ -1,515 +1,515 @@
/*
* 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.commons.codec.digest;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* SHA2-based Unix crypt implementation.
*
* <p>
* Based on the C implementation released into the Public Domain by Ulrich Drepper <[email protected]>
* http://www.akkadia.org/drepper/SHA-crypt.txt
* </p>
*
* <p>
* Conversion to Kotlin and from there to Java in 2012 by Christian Hammers <[email protected]> and likewise put
* into the Public Domain.
* </p>
*
* This class is immutable and thread-safe.
*
* @version $Id$
* @since 1.7
*/
public class Sha2Crypt {
/**
* Default number of rounds if not explicitly specified.
*/
private static final int ROUNDS_DEFAULT = 5000;
/**
* Maximum number of rounds.
*/
private static final int ROUNDS_MAX = 999999999;
/**
* Minimum number of rounds.
*/
private static final int ROUNDS_MIN = 1000;
/**
* Prefix for optional rounds specification.
*/
private static final String ROUNDS_PREFIX = "rounds=";
/**
* The MessageDigest algorithm.
*/
private static final String SHA256_ALGORITHM = "SHA-256";
/**
* The number of bytes the final hash value will have.
*/
private static final int SHA256_BLOCKSIZE = 32;
/**
* The prefixes that can be used to identify this crypt() variant.
*/
static final String SHA256_PREFIX = "$5$";
private static final String SHA512_ALGORITHM = "SHA-512";
private static final int SHA512_BLOCKSIZE = 64;
static final String SHA512_PREFIX = "$6$";
/**
* Generates a libc crypt() compatible "$5$" hash value with random salt.
*
* See {@link Crypt#crypt(String, String)} for details.
*/
public static String sha256Crypt(byte[] keyBytes) throws Exception {
return sha256Crypt(keyBytes, null);
}
/**
* Generates a libc6 crypt() compatible "$5$" hash value.
*
* See {@link Crypt#crypt(String, String)} for details.
*/
public static String sha256Crypt(byte[] keyBytes, String salt) throws Exception {
if (salt == null) {
salt = SHA256_PREFIX + B64.getRandomSalt(8);
}
return sha2Crypt(keyBytes, salt, SHA256_PREFIX, SHA256_BLOCKSIZE, SHA256_ALGORITHM);
}
/**
* Generates a libc6 crypt() compatible "$5$" or "$6$" SHA2 based hash value.
*
* This is a nearly line by line conversion of the original C function. The numbered comments are from the algorithm
* description, the short C-style ones from the original C code and the ones with "Remark" from me.
*
* See {@link Crypt#crypt(String, String)} for details.
*
* @param keyBytes
* The plaintext that should be hashed.
* @param salt_string
* The real salt value without prefix or "rounds=".
* @param saltPrefix
* Either $5$ or $6$.
* @param blocksize
* A value that differs between $5$ and $6$.
* @param algorithm
* The MessageDigest algorithm identifier string.
* @return The complete hash value including prefix and salt.
*/
private static String sha2Crypt(byte[] keyBytes, String salt, String saltPrefix, int blocksize, String algorithm)
throws Exception {
int keyLen = keyBytes.length;
// Extracts effective salt and the number of rounds from the given salt.
int rounds = ROUNDS_DEFAULT;
boolean roundsCustom = false;
if (salt == null) {
throw new IllegalArgumentException("Invalid salt value: null");
}
Pattern p = Pattern.compile("^\\$([56])\\$(rounds=(\\d+)\\$)?([\\.\\/a-zA-Z0-9]{1,16}).*");
Matcher m = p.matcher(salt);
if (m == null || !m.find()) {
throw new IllegalArgumentException("Invalid salt value: " + salt);
}
if (m.group(3) != null) {
- rounds = Integer.valueOf(m.group(3));
+ rounds = Integer.parseInt(m.group(3));
rounds = Math.max(ROUNDS_MIN, Math.min(ROUNDS_MAX, rounds));
roundsCustom = true;
}
String saltString = m.group(4);
byte[] saltBytes = saltString.getBytes("UTF-8");
int saltLen = saltBytes.length;
// 1. start digest A
// Prepare for the real work.
MessageDigest ctx = MessageDigest.getInstance(algorithm);
// 2. the password string is added to digest A
/*
* Add the key string.
*/
ctx.update(keyBytes);
// 3. the salt string is added to digest A. This is just the salt string
// itself without the enclosing '$', without the magic salt_prefix $5$ and
// $6$ respectively and without the rounds=<N> specification.
//
// NB: the MD5 algorithm did add the $1$ salt_prefix. This is not deemed
// necessary since it is a constant string and does not add security
// and /possibly/ allows a plain text attack. Since the rounds=<N>
// specification should never be added this would also create an
// inconsistency.
/*
* The last part is the salt string. This must be at most 16 characters and it ends at the first `$' character
* (for compatibility with existing implementations).
*/
ctx.update(saltBytes);
// 4. start digest B
/*
* Compute alternate sha512 sum with input KEY, SALT, and KEY. The final result will be added to the first
* context.
*/
MessageDigest altCtx = MessageDigest.getInstance(algorithm);
// 5. add the password to digest B
/*
* Add key.
*/
altCtx.update(keyBytes);
// 6. add the salt string to digest B
/*
* Add salt.
*/
altCtx.update(saltBytes);
// 7. add the password again to digest B
/*
* Add key again.
*/
altCtx.update(keyBytes);
// 8. finish digest B
/*
* Now get result of this (32 bytes) and add it to the other context.
*/
byte[] altResult = altCtx.digest();
// 9. For each block of 32 or 64 bytes in the password string (excluding
// the terminating NUL in the C representation), add digest B to digest A
/*
* Add for any character in the key one byte of the alternate sum.
*/
/*
* (Remark: the C code comment seems wrong for key length > 32!)
*/
int cnt = keyBytes.length;
while (cnt > blocksize) {
ctx.update(altResult, 0, blocksize);
cnt -= blocksize;
}
// 10. For the remaining N bytes of the password string add the first
// N bytes of digest B to digest A
ctx.update(altResult, 0, cnt);
// 11. For each bit of the binary representation of the length of the
// password string up to and including the highest 1-digit, starting
// from to lowest bit position (numeric value 1):
//
// a) for a 1-digit add digest B to digest A
//
// b) for a 0-digit add the password string
//
// NB: this step differs significantly from the MD5 algorithm. It
// adds more randomness.
/*
* Take the binary representation of the length of the key and for every 1 add the alternate sum, for every 0
* the key.
*/
cnt = keyBytes.length;
while (cnt > 0) {
if ((cnt & 1) != 0) {
ctx.update(altResult, 0, blocksize);
} else {
ctx.update(keyBytes);
}
cnt >>= 1;
}
// 12. finish digest A
/*
* Create intermediate result.
*/
altResult = ctx.digest();
// 13. start digest DP
/*
* Start computation of P byte sequence.
*/
altCtx = MessageDigest.getInstance(algorithm);
// 14. for every byte in the password (excluding the terminating NUL byte
// in the C representation of the string)
//
// add the password to digest DP
/*
* For every character in the password add the entire password.
*/
for (int i = 1; i <= keyLen; i++) {
altCtx.update(keyBytes);
}
// 15. finish digest DP
/*
* Finish the digest.
*/
byte[] tempResult = altCtx.digest();
// 16. produce byte sequence P of the same length as the password where
//
// a) for each block of 32 or 64 bytes of length of the password string
// the entire digest DP is used
//
// b) for the remaining N (up to 31 or 63) bytes use the first N
// bytes of digest DP
/*
* Create byte sequence P.
*/
byte[] pBytes = new byte[keyLen];
int cp = 0;
while (cp < keyLen - blocksize) {
System.arraycopy(tempResult, 0, pBytes, cp, blocksize);
cp += blocksize;
}
System.arraycopy(tempResult, 0, pBytes, cp, keyLen - cp);
// 17. start digest DS
/*
* Start computation of S byte sequence.
*/
altCtx = MessageDigest.getInstance(algorithm);
// 18. repeast the following 16+A[0] times, where A[0] represents the first
// byte in digest A interpreted as an 8-bit unsigned value
//
// add the salt to digest DS
/*
* For every character in the password add the entire password.
*/
for (int i = 1; i <= 16 + (altResult[0] & 0xff); i++) {
altCtx.update(saltBytes);
}
// 19. finish digest DS
/*
* Finish the digest.
*/
tempResult = altCtx.digest();
// 20. produce byte sequence S of the same length as the salt string where
//
// a) for each block of 32 or 64 bytes of length of the salt string
// the entire digest DS is used
//
// b) for the remaining N (up to 31 or 63) bytes use the first N
// bytes of digest DS
/*
* Create byte sequence S.
*/
// Remark: The salt is limited to 16 chars, how does this make sense?
byte[] sBytes = new byte[saltLen];
cp = 0;
while (cp < saltLen - blocksize) {
System.arraycopy(tempResult, 0, sBytes, cp, blocksize);
cp += blocksize;
}
System.arraycopy(tempResult, 0, sBytes, cp, saltLen - cp);
// 21. repeat a loop according to the number specified in the rounds=<N>
// specification in the salt (or the default value if none is
// present). Each round is numbered, starting with 0 and up to N-1.
//
// The loop uses a digest as input. In the first round it is the
// digest produced in step 12. In the latter steps it is the digest
// produced in step 21.h. The following text uses the notation
// "digest A/C" to desribe this behavior.
/*
* Repeatedly run the collected hash value through sha512 to burn CPU cycles.
*/
for (int i = 0; i <= rounds - 1; i++) {
// a) start digest C
/*
* New context.
*/
ctx = MessageDigest.getInstance(algorithm);
// b) for odd round numbers add the byte sequense P to digest C
// c) for even round numbers add digest A/C
/*
* Add key or last result.
*/
if ((i & 1) != 0) {
ctx.update(pBytes, 0, keyLen);
} else {
ctx.update(altResult, 0, blocksize);
}
// d) for all round numbers not divisible by 3 add the byte sequence S
/*
* Add salt for numbers not divisible by 3.
*/
if (i % 3 != 0) {
ctx.update(sBytes, 0, saltLen);
}
// e) for all round numbers not divisible by 7 add the byte sequence P
/*
* Add key for numbers not divisible by 7.
*/
if (i % 7 != 0) {
ctx.update(pBytes, 0, keyLen);
}
// f) for odd round numbers add digest A/C
// g) for even round numbers add the byte sequence P
/*
* Add key or last result.
*/
if ((i & 1) != 0) {
ctx.update(altResult, 0, blocksize);
} else {
ctx.update(pBytes, 0, keyLen);
}
// h) finish digest C.
/*
* Create intermediate result.
*/
altResult = ctx.digest();
}
// 22. Produce the output string. This is an ASCII string of the maximum
// size specified above, consisting of multiple pieces:
//
// a) the salt salt_prefix, $5$ or $6$ respectively
//
// b) the rounds=<N> specification, if one was present in the input
// salt string. A trailing '$' is added in this case to separate
// the rounds specification from the following text.
//
// c) the salt string truncated to 16 characters
//
// d) a '$' character
/*
* Now we can construct the result string. It consists of three parts.
*/
StringBuilder buffer = new StringBuilder(saltPrefix + (roundsCustom ? ROUNDS_PREFIX + rounds + "$" : "")
+ saltString + "$");
// e) the base-64 encoded final C digest. The encoding used is as
// follows:
// [...]
//
// Each group of three bytes from the digest produces four
// characters as output:
//
// 1. character: the six low bits of the first byte
// 2. character: the two high bits of the first byte and the
// four low bytes from the second byte
// 3. character: the four high bytes from the second byte and
// the two low bits from the third byte
// 4. character: the six high bits from the third byte
//
// The groups of three bytes are as follows (in this sequence).
// These are the indices into the byte array containing the
// digest, starting with index 0. For the last group there are
// not enough bytes left in the digest and the value zero is used
// in its place. This group also produces only three or two
// characters as output for SHA-512 and SHA-512 respectively.
// This was just a safeguard in the C implementation:
// int buflen = salt_prefix.length() - 1 + ROUNDS_PREFIX.length() + 9 + 1 + salt_string.length() + 1 + 86 + 1;
if (blocksize == 32) {
B64.b64from24bit(altResult[0], altResult[10], altResult[20], 4, buffer);
B64.b64from24bit(altResult[21], altResult[1], altResult[11], 4, buffer);
B64.b64from24bit(altResult[12], altResult[22], altResult[2], 4, buffer);
B64.b64from24bit(altResult[3], altResult[13], altResult[23], 4, buffer);
B64.b64from24bit(altResult[24], altResult[4], altResult[14], 4, buffer);
B64.b64from24bit(altResult[15], altResult[25], altResult[5], 4, buffer);
B64.b64from24bit(altResult[6], altResult[16], altResult[26], 4, buffer);
B64.b64from24bit(altResult[27], altResult[7], altResult[17], 4, buffer);
B64.b64from24bit(altResult[18], altResult[28], altResult[8], 4, buffer);
B64.b64from24bit(altResult[9], altResult[19], altResult[29], 4, buffer);
B64.b64from24bit((byte) 0, altResult[31], altResult[30], 3, buffer);
} else {
B64.b64from24bit(altResult[0], altResult[21], altResult[42], 4, buffer);
B64.b64from24bit(altResult[22], altResult[43], altResult[1], 4, buffer);
B64.b64from24bit(altResult[44], altResult[2], altResult[23], 4, buffer);
B64.b64from24bit(altResult[3], altResult[24], altResult[45], 4, buffer);
B64.b64from24bit(altResult[25], altResult[46], altResult[4], 4, buffer);
B64.b64from24bit(altResult[47], altResult[5], altResult[26], 4, buffer);
B64.b64from24bit(altResult[6], altResult[27], altResult[48], 4, buffer);
B64.b64from24bit(altResult[28], altResult[49], altResult[7], 4, buffer);
B64.b64from24bit(altResult[50], altResult[8], altResult[29], 4, buffer);
B64.b64from24bit(altResult[9], altResult[30], altResult[51], 4, buffer);
B64.b64from24bit(altResult[31], altResult[52], altResult[10], 4, buffer);
B64.b64from24bit(altResult[53], altResult[11], altResult[32], 4, buffer);
B64.b64from24bit(altResult[12], altResult[33], altResult[54], 4, buffer);
B64.b64from24bit(altResult[34], altResult[55], altResult[13], 4, buffer);
B64.b64from24bit(altResult[56], altResult[14], altResult[35], 4, buffer);
B64.b64from24bit(altResult[15], altResult[36], altResult[57], 4, buffer);
B64.b64from24bit(altResult[37], altResult[58], altResult[16], 4, buffer);
B64.b64from24bit(altResult[59], altResult[17], altResult[38], 4, buffer);
B64.b64from24bit(altResult[18], altResult[39], altResult[60], 4, buffer);
B64.b64from24bit(altResult[40], altResult[61], altResult[19], 4, buffer);
B64.b64from24bit(altResult[62], altResult[20], altResult[41], 4, buffer);
B64.b64from24bit((byte) 0, (byte) 0, altResult[63], 2, buffer);
}
/*
* Clear the buffer for the intermediate result so that people attaching to processes or reading core dumps
* cannot get any information.
*/
// Is there a better way to do this with the JVM?
Arrays.fill(tempResult, (byte) 0);
Arrays.fill(pBytes, (byte) 0);
Arrays.fill(sBytes, (byte) 0);
ctx.reset();
altCtx.reset();
Arrays.fill(keyBytes, (byte) 0);
Arrays.fill(saltBytes, (byte) 0);
return buffer.toString();
}
/**
* Generates a libc crypt() compatible "$6$" hash value with random salt.
*
* See {@link Crypt#crypt(String, String)} for details.
*/
public static String sha512Crypt(byte[] keyBytes) throws Exception {
return sha512Crypt(keyBytes, null);
}
/**
* Generates a libc6 crypt() compatible "$6$" hash value.
*
* See {@link Crypt#crypt(String, String)} for details.
*/
public static String sha512Crypt(byte[] keyBytes, String salt) throws Exception {
if (salt == null) {
salt = SHA512_PREFIX + B64.getRandomSalt(8);
}
return sha2Crypt(keyBytes, salt, SHA512_PREFIX, SHA512_BLOCKSIZE, SHA512_ALGORITHM);
}
}
| true | true | private static String sha2Crypt(byte[] keyBytes, String salt, String saltPrefix, int blocksize, String algorithm)
throws Exception {
int keyLen = keyBytes.length;
// Extracts effective salt and the number of rounds from the given salt.
int rounds = ROUNDS_DEFAULT;
boolean roundsCustom = false;
if (salt == null) {
throw new IllegalArgumentException("Invalid salt value: null");
}
Pattern p = Pattern.compile("^\\$([56])\\$(rounds=(\\d+)\\$)?([\\.\\/a-zA-Z0-9]{1,16}).*");
Matcher m = p.matcher(salt);
if (m == null || !m.find()) {
throw new IllegalArgumentException("Invalid salt value: " + salt);
}
if (m.group(3) != null) {
rounds = Integer.valueOf(m.group(3));
rounds = Math.max(ROUNDS_MIN, Math.min(ROUNDS_MAX, rounds));
roundsCustom = true;
}
String saltString = m.group(4);
byte[] saltBytes = saltString.getBytes("UTF-8");
int saltLen = saltBytes.length;
// 1. start digest A
// Prepare for the real work.
MessageDigest ctx = MessageDigest.getInstance(algorithm);
// 2. the password string is added to digest A
/*
* Add the key string.
*/
ctx.update(keyBytes);
// 3. the salt string is added to digest A. This is just the salt string
// itself without the enclosing '$', without the magic salt_prefix $5$ and
// $6$ respectively and without the rounds=<N> specification.
//
// NB: the MD5 algorithm did add the $1$ salt_prefix. This is not deemed
// necessary since it is a constant string and does not add security
// and /possibly/ allows a plain text attack. Since the rounds=<N>
// specification should never be added this would also create an
// inconsistency.
/*
* The last part is the salt string. This must be at most 16 characters and it ends at the first `$' character
* (for compatibility with existing implementations).
*/
ctx.update(saltBytes);
// 4. start digest B
/*
* Compute alternate sha512 sum with input KEY, SALT, and KEY. The final result will be added to the first
* context.
*/
MessageDigest altCtx = MessageDigest.getInstance(algorithm);
// 5. add the password to digest B
/*
* Add key.
*/
altCtx.update(keyBytes);
// 6. add the salt string to digest B
/*
* Add salt.
*/
altCtx.update(saltBytes);
// 7. add the password again to digest B
/*
* Add key again.
*/
altCtx.update(keyBytes);
// 8. finish digest B
/*
* Now get result of this (32 bytes) and add it to the other context.
*/
byte[] altResult = altCtx.digest();
// 9. For each block of 32 or 64 bytes in the password string (excluding
// the terminating NUL in the C representation), add digest B to digest A
/*
* Add for any character in the key one byte of the alternate sum.
*/
/*
* (Remark: the C code comment seems wrong for key length > 32!)
*/
int cnt = keyBytes.length;
while (cnt > blocksize) {
ctx.update(altResult, 0, blocksize);
cnt -= blocksize;
}
// 10. For the remaining N bytes of the password string add the first
// N bytes of digest B to digest A
ctx.update(altResult, 0, cnt);
// 11. For each bit of the binary representation of the length of the
// password string up to and including the highest 1-digit, starting
// from to lowest bit position (numeric value 1):
//
// a) for a 1-digit add digest B to digest A
//
// b) for a 0-digit add the password string
//
// NB: this step differs significantly from the MD5 algorithm. It
// adds more randomness.
/*
* Take the binary representation of the length of the key and for every 1 add the alternate sum, for every 0
* the key.
*/
cnt = keyBytes.length;
while (cnt > 0) {
if ((cnt & 1) != 0) {
ctx.update(altResult, 0, blocksize);
} else {
ctx.update(keyBytes);
}
cnt >>= 1;
}
// 12. finish digest A
/*
* Create intermediate result.
*/
altResult = ctx.digest();
// 13. start digest DP
/*
* Start computation of P byte sequence.
*/
altCtx = MessageDigest.getInstance(algorithm);
// 14. for every byte in the password (excluding the terminating NUL byte
// in the C representation of the string)
//
// add the password to digest DP
/*
* For every character in the password add the entire password.
*/
for (int i = 1; i <= keyLen; i++) {
altCtx.update(keyBytes);
}
// 15. finish digest DP
/*
* Finish the digest.
*/
byte[] tempResult = altCtx.digest();
// 16. produce byte sequence P of the same length as the password where
//
// a) for each block of 32 or 64 bytes of length of the password string
// the entire digest DP is used
//
// b) for the remaining N (up to 31 or 63) bytes use the first N
// bytes of digest DP
/*
* Create byte sequence P.
*/
byte[] pBytes = new byte[keyLen];
int cp = 0;
while (cp < keyLen - blocksize) {
System.arraycopy(tempResult, 0, pBytes, cp, blocksize);
cp += blocksize;
}
System.arraycopy(tempResult, 0, pBytes, cp, keyLen - cp);
// 17. start digest DS
/*
* Start computation of S byte sequence.
*/
altCtx = MessageDigest.getInstance(algorithm);
// 18. repeast the following 16+A[0] times, where A[0] represents the first
// byte in digest A interpreted as an 8-bit unsigned value
//
// add the salt to digest DS
/*
* For every character in the password add the entire password.
*/
for (int i = 1; i <= 16 + (altResult[0] & 0xff); i++) {
altCtx.update(saltBytes);
}
// 19. finish digest DS
/*
* Finish the digest.
*/
tempResult = altCtx.digest();
// 20. produce byte sequence S of the same length as the salt string where
//
// a) for each block of 32 or 64 bytes of length of the salt string
// the entire digest DS is used
//
// b) for the remaining N (up to 31 or 63) bytes use the first N
// bytes of digest DS
/*
* Create byte sequence S.
*/
// Remark: The salt is limited to 16 chars, how does this make sense?
byte[] sBytes = new byte[saltLen];
cp = 0;
while (cp < saltLen - blocksize) {
System.arraycopy(tempResult, 0, sBytes, cp, blocksize);
cp += blocksize;
}
System.arraycopy(tempResult, 0, sBytes, cp, saltLen - cp);
// 21. repeat a loop according to the number specified in the rounds=<N>
// specification in the salt (or the default value if none is
// present). Each round is numbered, starting with 0 and up to N-1.
//
// The loop uses a digest as input. In the first round it is the
// digest produced in step 12. In the latter steps it is the digest
// produced in step 21.h. The following text uses the notation
// "digest A/C" to desribe this behavior.
/*
* Repeatedly run the collected hash value through sha512 to burn CPU cycles.
*/
for (int i = 0; i <= rounds - 1; i++) {
// a) start digest C
/*
* New context.
*/
ctx = MessageDigest.getInstance(algorithm);
// b) for odd round numbers add the byte sequense P to digest C
// c) for even round numbers add digest A/C
/*
* Add key or last result.
*/
if ((i & 1) != 0) {
ctx.update(pBytes, 0, keyLen);
} else {
ctx.update(altResult, 0, blocksize);
}
// d) for all round numbers not divisible by 3 add the byte sequence S
/*
* Add salt for numbers not divisible by 3.
*/
if (i % 3 != 0) {
ctx.update(sBytes, 0, saltLen);
}
// e) for all round numbers not divisible by 7 add the byte sequence P
/*
* Add key for numbers not divisible by 7.
*/
if (i % 7 != 0) {
ctx.update(pBytes, 0, keyLen);
}
// f) for odd round numbers add digest A/C
// g) for even round numbers add the byte sequence P
/*
* Add key or last result.
*/
if ((i & 1) != 0) {
ctx.update(altResult, 0, blocksize);
} else {
ctx.update(pBytes, 0, keyLen);
}
// h) finish digest C.
/*
* Create intermediate result.
*/
altResult = ctx.digest();
}
// 22. Produce the output string. This is an ASCII string of the maximum
// size specified above, consisting of multiple pieces:
//
// a) the salt salt_prefix, $5$ or $6$ respectively
//
// b) the rounds=<N> specification, if one was present in the input
// salt string. A trailing '$' is added in this case to separate
// the rounds specification from the following text.
//
// c) the salt string truncated to 16 characters
//
// d) a '$' character
/*
* Now we can construct the result string. It consists of three parts.
*/
StringBuilder buffer = new StringBuilder(saltPrefix + (roundsCustom ? ROUNDS_PREFIX + rounds + "$" : "")
+ saltString + "$");
// e) the base-64 encoded final C digest. The encoding used is as
// follows:
// [...]
//
// Each group of three bytes from the digest produces four
// characters as output:
//
// 1. character: the six low bits of the first byte
// 2. character: the two high bits of the first byte and the
// four low bytes from the second byte
// 3. character: the four high bytes from the second byte and
// the two low bits from the third byte
// 4. character: the six high bits from the third byte
//
// The groups of three bytes are as follows (in this sequence).
// These are the indices into the byte array containing the
// digest, starting with index 0. For the last group there are
// not enough bytes left in the digest and the value zero is used
// in its place. This group also produces only three or two
// characters as output for SHA-512 and SHA-512 respectively.
// This was just a safeguard in the C implementation:
// int buflen = salt_prefix.length() - 1 + ROUNDS_PREFIX.length() + 9 + 1 + salt_string.length() + 1 + 86 + 1;
if (blocksize == 32) {
B64.b64from24bit(altResult[0], altResult[10], altResult[20], 4, buffer);
B64.b64from24bit(altResult[21], altResult[1], altResult[11], 4, buffer);
B64.b64from24bit(altResult[12], altResult[22], altResult[2], 4, buffer);
B64.b64from24bit(altResult[3], altResult[13], altResult[23], 4, buffer);
B64.b64from24bit(altResult[24], altResult[4], altResult[14], 4, buffer);
B64.b64from24bit(altResult[15], altResult[25], altResult[5], 4, buffer);
B64.b64from24bit(altResult[6], altResult[16], altResult[26], 4, buffer);
B64.b64from24bit(altResult[27], altResult[7], altResult[17], 4, buffer);
B64.b64from24bit(altResult[18], altResult[28], altResult[8], 4, buffer);
B64.b64from24bit(altResult[9], altResult[19], altResult[29], 4, buffer);
B64.b64from24bit((byte) 0, altResult[31], altResult[30], 3, buffer);
} else {
B64.b64from24bit(altResult[0], altResult[21], altResult[42], 4, buffer);
B64.b64from24bit(altResult[22], altResult[43], altResult[1], 4, buffer);
B64.b64from24bit(altResult[44], altResult[2], altResult[23], 4, buffer);
B64.b64from24bit(altResult[3], altResult[24], altResult[45], 4, buffer);
B64.b64from24bit(altResult[25], altResult[46], altResult[4], 4, buffer);
B64.b64from24bit(altResult[47], altResult[5], altResult[26], 4, buffer);
B64.b64from24bit(altResult[6], altResult[27], altResult[48], 4, buffer);
B64.b64from24bit(altResult[28], altResult[49], altResult[7], 4, buffer);
B64.b64from24bit(altResult[50], altResult[8], altResult[29], 4, buffer);
B64.b64from24bit(altResult[9], altResult[30], altResult[51], 4, buffer);
B64.b64from24bit(altResult[31], altResult[52], altResult[10], 4, buffer);
B64.b64from24bit(altResult[53], altResult[11], altResult[32], 4, buffer);
B64.b64from24bit(altResult[12], altResult[33], altResult[54], 4, buffer);
B64.b64from24bit(altResult[34], altResult[55], altResult[13], 4, buffer);
B64.b64from24bit(altResult[56], altResult[14], altResult[35], 4, buffer);
B64.b64from24bit(altResult[15], altResult[36], altResult[57], 4, buffer);
B64.b64from24bit(altResult[37], altResult[58], altResult[16], 4, buffer);
B64.b64from24bit(altResult[59], altResult[17], altResult[38], 4, buffer);
B64.b64from24bit(altResult[18], altResult[39], altResult[60], 4, buffer);
B64.b64from24bit(altResult[40], altResult[61], altResult[19], 4, buffer);
B64.b64from24bit(altResult[62], altResult[20], altResult[41], 4, buffer);
B64.b64from24bit((byte) 0, (byte) 0, altResult[63], 2, buffer);
}
/*
* Clear the buffer for the intermediate result so that people attaching to processes or reading core dumps
* cannot get any information.
*/
// Is there a better way to do this with the JVM?
Arrays.fill(tempResult, (byte) 0);
Arrays.fill(pBytes, (byte) 0);
Arrays.fill(sBytes, (byte) 0);
ctx.reset();
altCtx.reset();
Arrays.fill(keyBytes, (byte) 0);
Arrays.fill(saltBytes, (byte) 0);
return buffer.toString();
}
| private static String sha2Crypt(byte[] keyBytes, String salt, String saltPrefix, int blocksize, String algorithm)
throws Exception {
int keyLen = keyBytes.length;
// Extracts effective salt and the number of rounds from the given salt.
int rounds = ROUNDS_DEFAULT;
boolean roundsCustom = false;
if (salt == null) {
throw new IllegalArgumentException("Invalid salt value: null");
}
Pattern p = Pattern.compile("^\\$([56])\\$(rounds=(\\d+)\\$)?([\\.\\/a-zA-Z0-9]{1,16}).*");
Matcher m = p.matcher(salt);
if (m == null || !m.find()) {
throw new IllegalArgumentException("Invalid salt value: " + salt);
}
if (m.group(3) != null) {
rounds = Integer.parseInt(m.group(3));
rounds = Math.max(ROUNDS_MIN, Math.min(ROUNDS_MAX, rounds));
roundsCustom = true;
}
String saltString = m.group(4);
byte[] saltBytes = saltString.getBytes("UTF-8");
int saltLen = saltBytes.length;
// 1. start digest A
// Prepare for the real work.
MessageDigest ctx = MessageDigest.getInstance(algorithm);
// 2. the password string is added to digest A
/*
* Add the key string.
*/
ctx.update(keyBytes);
// 3. the salt string is added to digest A. This is just the salt string
// itself without the enclosing '$', without the magic salt_prefix $5$ and
// $6$ respectively and without the rounds=<N> specification.
//
// NB: the MD5 algorithm did add the $1$ salt_prefix. This is not deemed
// necessary since it is a constant string and does not add security
// and /possibly/ allows a plain text attack. Since the rounds=<N>
// specification should never be added this would also create an
// inconsistency.
/*
* The last part is the salt string. This must be at most 16 characters and it ends at the first `$' character
* (for compatibility with existing implementations).
*/
ctx.update(saltBytes);
// 4. start digest B
/*
* Compute alternate sha512 sum with input KEY, SALT, and KEY. The final result will be added to the first
* context.
*/
MessageDigest altCtx = MessageDigest.getInstance(algorithm);
// 5. add the password to digest B
/*
* Add key.
*/
altCtx.update(keyBytes);
// 6. add the salt string to digest B
/*
* Add salt.
*/
altCtx.update(saltBytes);
// 7. add the password again to digest B
/*
* Add key again.
*/
altCtx.update(keyBytes);
// 8. finish digest B
/*
* Now get result of this (32 bytes) and add it to the other context.
*/
byte[] altResult = altCtx.digest();
// 9. For each block of 32 or 64 bytes in the password string (excluding
// the terminating NUL in the C representation), add digest B to digest A
/*
* Add for any character in the key one byte of the alternate sum.
*/
/*
* (Remark: the C code comment seems wrong for key length > 32!)
*/
int cnt = keyBytes.length;
while (cnt > blocksize) {
ctx.update(altResult, 0, blocksize);
cnt -= blocksize;
}
// 10. For the remaining N bytes of the password string add the first
// N bytes of digest B to digest A
ctx.update(altResult, 0, cnt);
// 11. For each bit of the binary representation of the length of the
// password string up to and including the highest 1-digit, starting
// from to lowest bit position (numeric value 1):
//
// a) for a 1-digit add digest B to digest A
//
// b) for a 0-digit add the password string
//
// NB: this step differs significantly from the MD5 algorithm. It
// adds more randomness.
/*
* Take the binary representation of the length of the key and for every 1 add the alternate sum, for every 0
* the key.
*/
cnt = keyBytes.length;
while (cnt > 0) {
if ((cnt & 1) != 0) {
ctx.update(altResult, 0, blocksize);
} else {
ctx.update(keyBytes);
}
cnt >>= 1;
}
// 12. finish digest A
/*
* Create intermediate result.
*/
altResult = ctx.digest();
// 13. start digest DP
/*
* Start computation of P byte sequence.
*/
altCtx = MessageDigest.getInstance(algorithm);
// 14. for every byte in the password (excluding the terminating NUL byte
// in the C representation of the string)
//
// add the password to digest DP
/*
* For every character in the password add the entire password.
*/
for (int i = 1; i <= keyLen; i++) {
altCtx.update(keyBytes);
}
// 15. finish digest DP
/*
* Finish the digest.
*/
byte[] tempResult = altCtx.digest();
// 16. produce byte sequence P of the same length as the password where
//
// a) for each block of 32 or 64 bytes of length of the password string
// the entire digest DP is used
//
// b) for the remaining N (up to 31 or 63) bytes use the first N
// bytes of digest DP
/*
* Create byte sequence P.
*/
byte[] pBytes = new byte[keyLen];
int cp = 0;
while (cp < keyLen - blocksize) {
System.arraycopy(tempResult, 0, pBytes, cp, blocksize);
cp += blocksize;
}
System.arraycopy(tempResult, 0, pBytes, cp, keyLen - cp);
// 17. start digest DS
/*
* Start computation of S byte sequence.
*/
altCtx = MessageDigest.getInstance(algorithm);
// 18. repeast the following 16+A[0] times, where A[0] represents the first
// byte in digest A interpreted as an 8-bit unsigned value
//
// add the salt to digest DS
/*
* For every character in the password add the entire password.
*/
for (int i = 1; i <= 16 + (altResult[0] & 0xff); i++) {
altCtx.update(saltBytes);
}
// 19. finish digest DS
/*
* Finish the digest.
*/
tempResult = altCtx.digest();
// 20. produce byte sequence S of the same length as the salt string where
//
// a) for each block of 32 or 64 bytes of length of the salt string
// the entire digest DS is used
//
// b) for the remaining N (up to 31 or 63) bytes use the first N
// bytes of digest DS
/*
* Create byte sequence S.
*/
// Remark: The salt is limited to 16 chars, how does this make sense?
byte[] sBytes = new byte[saltLen];
cp = 0;
while (cp < saltLen - blocksize) {
System.arraycopy(tempResult, 0, sBytes, cp, blocksize);
cp += blocksize;
}
System.arraycopy(tempResult, 0, sBytes, cp, saltLen - cp);
// 21. repeat a loop according to the number specified in the rounds=<N>
// specification in the salt (or the default value if none is
// present). Each round is numbered, starting with 0 and up to N-1.
//
// The loop uses a digest as input. In the first round it is the
// digest produced in step 12. In the latter steps it is the digest
// produced in step 21.h. The following text uses the notation
// "digest A/C" to desribe this behavior.
/*
* Repeatedly run the collected hash value through sha512 to burn CPU cycles.
*/
for (int i = 0; i <= rounds - 1; i++) {
// a) start digest C
/*
* New context.
*/
ctx = MessageDigest.getInstance(algorithm);
// b) for odd round numbers add the byte sequense P to digest C
// c) for even round numbers add digest A/C
/*
* Add key or last result.
*/
if ((i & 1) != 0) {
ctx.update(pBytes, 0, keyLen);
} else {
ctx.update(altResult, 0, blocksize);
}
// d) for all round numbers not divisible by 3 add the byte sequence S
/*
* Add salt for numbers not divisible by 3.
*/
if (i % 3 != 0) {
ctx.update(sBytes, 0, saltLen);
}
// e) for all round numbers not divisible by 7 add the byte sequence P
/*
* Add key for numbers not divisible by 7.
*/
if (i % 7 != 0) {
ctx.update(pBytes, 0, keyLen);
}
// f) for odd round numbers add digest A/C
// g) for even round numbers add the byte sequence P
/*
* Add key or last result.
*/
if ((i & 1) != 0) {
ctx.update(altResult, 0, blocksize);
} else {
ctx.update(pBytes, 0, keyLen);
}
// h) finish digest C.
/*
* Create intermediate result.
*/
altResult = ctx.digest();
}
// 22. Produce the output string. This is an ASCII string of the maximum
// size specified above, consisting of multiple pieces:
//
// a) the salt salt_prefix, $5$ or $6$ respectively
//
// b) the rounds=<N> specification, if one was present in the input
// salt string. A trailing '$' is added in this case to separate
// the rounds specification from the following text.
//
// c) the salt string truncated to 16 characters
//
// d) a '$' character
/*
* Now we can construct the result string. It consists of three parts.
*/
StringBuilder buffer = new StringBuilder(saltPrefix + (roundsCustom ? ROUNDS_PREFIX + rounds + "$" : "")
+ saltString + "$");
// e) the base-64 encoded final C digest. The encoding used is as
// follows:
// [...]
//
// Each group of three bytes from the digest produces four
// characters as output:
//
// 1. character: the six low bits of the first byte
// 2. character: the two high bits of the first byte and the
// four low bytes from the second byte
// 3. character: the four high bytes from the second byte and
// the two low bits from the third byte
// 4. character: the six high bits from the third byte
//
// The groups of three bytes are as follows (in this sequence).
// These are the indices into the byte array containing the
// digest, starting with index 0. For the last group there are
// not enough bytes left in the digest and the value zero is used
// in its place. This group also produces only three or two
// characters as output for SHA-512 and SHA-512 respectively.
// This was just a safeguard in the C implementation:
// int buflen = salt_prefix.length() - 1 + ROUNDS_PREFIX.length() + 9 + 1 + salt_string.length() + 1 + 86 + 1;
if (blocksize == 32) {
B64.b64from24bit(altResult[0], altResult[10], altResult[20], 4, buffer);
B64.b64from24bit(altResult[21], altResult[1], altResult[11], 4, buffer);
B64.b64from24bit(altResult[12], altResult[22], altResult[2], 4, buffer);
B64.b64from24bit(altResult[3], altResult[13], altResult[23], 4, buffer);
B64.b64from24bit(altResult[24], altResult[4], altResult[14], 4, buffer);
B64.b64from24bit(altResult[15], altResult[25], altResult[5], 4, buffer);
B64.b64from24bit(altResult[6], altResult[16], altResult[26], 4, buffer);
B64.b64from24bit(altResult[27], altResult[7], altResult[17], 4, buffer);
B64.b64from24bit(altResult[18], altResult[28], altResult[8], 4, buffer);
B64.b64from24bit(altResult[9], altResult[19], altResult[29], 4, buffer);
B64.b64from24bit((byte) 0, altResult[31], altResult[30], 3, buffer);
} else {
B64.b64from24bit(altResult[0], altResult[21], altResult[42], 4, buffer);
B64.b64from24bit(altResult[22], altResult[43], altResult[1], 4, buffer);
B64.b64from24bit(altResult[44], altResult[2], altResult[23], 4, buffer);
B64.b64from24bit(altResult[3], altResult[24], altResult[45], 4, buffer);
B64.b64from24bit(altResult[25], altResult[46], altResult[4], 4, buffer);
B64.b64from24bit(altResult[47], altResult[5], altResult[26], 4, buffer);
B64.b64from24bit(altResult[6], altResult[27], altResult[48], 4, buffer);
B64.b64from24bit(altResult[28], altResult[49], altResult[7], 4, buffer);
B64.b64from24bit(altResult[50], altResult[8], altResult[29], 4, buffer);
B64.b64from24bit(altResult[9], altResult[30], altResult[51], 4, buffer);
B64.b64from24bit(altResult[31], altResult[52], altResult[10], 4, buffer);
B64.b64from24bit(altResult[53], altResult[11], altResult[32], 4, buffer);
B64.b64from24bit(altResult[12], altResult[33], altResult[54], 4, buffer);
B64.b64from24bit(altResult[34], altResult[55], altResult[13], 4, buffer);
B64.b64from24bit(altResult[56], altResult[14], altResult[35], 4, buffer);
B64.b64from24bit(altResult[15], altResult[36], altResult[57], 4, buffer);
B64.b64from24bit(altResult[37], altResult[58], altResult[16], 4, buffer);
B64.b64from24bit(altResult[59], altResult[17], altResult[38], 4, buffer);
B64.b64from24bit(altResult[18], altResult[39], altResult[60], 4, buffer);
B64.b64from24bit(altResult[40], altResult[61], altResult[19], 4, buffer);
B64.b64from24bit(altResult[62], altResult[20], altResult[41], 4, buffer);
B64.b64from24bit((byte) 0, (byte) 0, altResult[63], 2, buffer);
}
/*
* Clear the buffer for the intermediate result so that people attaching to processes or reading core dumps
* cannot get any information.
*/
// Is there a better way to do this with the JVM?
Arrays.fill(tempResult, (byte) 0);
Arrays.fill(pBytes, (byte) 0);
Arrays.fill(sBytes, (byte) 0);
ctx.reset();
altCtx.reset();
Arrays.fill(keyBytes, (byte) 0);
Arrays.fill(saltBytes, (byte) 0);
return buffer.toString();
}
|
diff --git a/src/com/NSBCoding/Nicolas.java b/src/com/NSBCoding/Nicolas.java
index 8fd4e3f..1624527 100644
--- a/src/com/NSBCoding/Nicolas.java
+++ b/src/com/NSBCoding/Nicolas.java
@@ -1,1192 +1,1192 @@
package com.NSBCoding;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Nicolas extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
public Rectangle character;
public Rectangle FinalBoss;
public Rectangle Boss;
public Rectangle Boss2;
public Rectangle Boss3;
public Rectangle Boss4;
public Rectangle Boss5;
public Rectangle StartingPoint;
public Rectangle Top;
public Rectangle Bottom;
public Rectangle Left;
public Rectangle Right;
public Rectangle Line;
public Rectangle Line2;
public Rectangle InvLine;
public Rectangle InvLine2;
public Rectangle InvLine3;
public Rectangle Line3;
public Rectangle Line4;
public Rectangle Line5;
public Rectangle Line6;
public Rectangle Line7;
public Rectangle Line8;
public Rectangle Line9;
public Rectangle Line10;
public Rectangle Line11;
public Rectangle Line12;
public Rectangle Line13;
public Rectangle Line14;
public Rectangle Line15;
public Rectangle Line16;
public Rectangle Line17;
public Rectangle Line18;
public Rectangle Line19;
public Rectangle Line20;
public Rectangle Line21;
public Rectangle Line22;
public Rectangle Line23;
public Rectangle Line24;
public Rectangle Line25;
public Rectangle Line26;
public Rectangle line3;
public Rectangle line4;
public Rectangle line5;
public Rectangle line6;
public Rectangle line7;
public Rectangle line8;
public Rectangle line9;
public Rectangle line10;
public Rectangle line11;
public Rectangle line12;
public Rectangle line13;
public Rectangle line14;
public Rectangle line15;
public Rectangle line16;
public Rectangle line17;
public Rectangle line18;
public Rectangle line19;
public Rectangle line20;
public Rectangle line21;
public Rectangle line22;
public Rectangle line23;
public Rectangle line24;
public Rectangle line25;
public Rectangle line26;
public Rectangle Holder1;
public Rectangle Holder2;
public Rectangle Holder3;
public int charW = 25;
public int charH = 25;
public int LineH = 720;
public int LineW = 5;
public int Line2H = 242;
public int LineInv = 60;
public int InvRectH = 720;
public int InvRectW = 100;
public int FBossW = 20;
public int FBossH = 60;
public int BossW = 30;
public int BossH = 400;
public int HolderW = 70;
public int maxHealth = 3;
public int midHealth = 2;
public int lowHealth = 1;
public float verticalSpeed = 1f;
public boolean Map1 = true;
public boolean Map2 = false;
public boolean Map3 = false;
public boolean right = false;
public boolean left = false;
public boolean mouseActive = false;
public boolean LeftSide = false;
public boolean RightSide = false;
public boolean up = false;
public boolean down = false;
public boolean jumping = false;
public boolean Reset = false;
public boolean StopReset1 = false;
public boolean Restart = false;
public boolean KeysIns = false;
public boolean Dead = false;
public boolean DeathScreen = false;
public boolean isMoving = true;
public boolean FMoving = true;
public boolean BossMoving = true;
public boolean BossMoving2 = true;
public boolean BossMoving3 = true;
public boolean BossMoving4 = true;
public boolean BossMoving5 = true;
public boolean FUp = true;
public boolean FDown = false;
public boolean FLeft = false;
public boolean FRight = true;
public boolean BUp = true;
public boolean BDown = false;
public boolean BUp2 = true;
public boolean BDown2 = false;
public boolean BUp3 = true;
public boolean BDown3 = false;
public boolean BUp4 = true;
public boolean BDown4 = false;
public boolean BUp5 = true;
public boolean BDown5 = false;
public boolean Finished = false;
public boolean SpeedBoost = false;
public boolean lost = false;
public Point mouse;
public Nicolas(Screen f, Images i){
//if(i.imagesLoaded){
//Rectangles Being Drawn
character = new Rectangle(52, 52, charW, charH);
FinalBoss = new Rectangle(1103, 66, FBossW, FBossH);
Boss = new Rectangle(315, 315, BossW, BossH - 50);
Boss2 = new Rectangle(865, 130, BossW - 10, BossH - 200);
Boss3 = new Rectangle(629, 38, BossW - 10, BossH - 300);
Boss4 = new Rectangle(952, 106, BossW - 10, BossH - 100);
Boss5 = new Rectangle(455, 130, BossW - 10, BossH + 600);
StartingPoint = new Rectangle(52, 52, charW, charH);
Top = new Rectangle(0, 0, 1280, 1);
Bottom = new Rectangle(0, 720, 1280, 1);
Left = new Rectangle(0, 0, 1, 720);
Right = new Rectangle(1280, 0, 1, 720);
Line = new Rectangle(1200, 302, LineW, LineH);
Line2 = new Rectangle(1200, 0, LineW, Line2H);
InvLine = new Rectangle(1200, 242, LineW, LineInv);
InvLine2 = new Rectangle(1220, 0, InvRectW, InvRectH);
InvLine3 = new Rectangle(1066, 450, LineW, 50);
//Map1
Holder1 = new Rectangle(235, 300, HolderW, 5);
Holder2 = new Rectangle(403, 120, HolderW - 20, 5);
Holder3 = new Rectangle(889, 100, HolderW - 20, 5);
//Map1
Line3 = new Rectangle(109, 0, LineW, 500);
Line4 = new Rectangle(235, 0, LineW, 300);
Line5 = new Rectangle(403, 0, LineW, 120);
Line6 = new Rectangle(511, 0, LineW, 30);
Line7 = new Rectangle(580, 0, LineW, 50);
Line8 = new Rectangle(671, 0, LineW, 300);
Line9 = new Rectangle(770, 0, LineW, 200);
Line10 = new Rectangle(838, 0, LineW, 50);
Line11 = new Rectangle(936, 0, LineW, 600);
Line12 = new Rectangle(1016, 0, LineW, 50);
Line13 = new Rectangle(1066, 0, LineW, 450);
Line14 = new Rectangle(1131, 0, LineW, 10);
//Map2
Line15 = new Rectangle(109, 0, LineW, 500);
Line16 = new Rectangle(235, 0, LineW, 300);
Line17 = new Rectangle(403, 0, LineW, 120);
Line18 = new Rectangle(511, 0, LineW, 30);
Line19 = new Rectangle(580, 0, LineW, 50);
Line20 = new Rectangle(671, 0, LineW, 300);
Line21 = new Rectangle(770, 0, LineW, 200);
Line22 = new Rectangle(838, 0, LineW, 50);
Line23 = new Rectangle(936, 0, LineW, 600);
Line24 = new Rectangle(1016, 0, LineW, 50);
Line25 = new Rectangle(1066, 0, LineW, 450);
Line26 = new Rectangle(1131, 0, LineW, 10);
//Map1
line3 = new Rectangle(109, 600, LineW, 1000);
line4 = new Rectangle(235, 360, LineW, 1000);
line5 = new Rectangle(403, 180, LineW, 1000);
line6 = new Rectangle(511, 80, LineW, 1000);
line7 = new Rectangle(580, 80, LineW, 1000);
line8 = new Rectangle(671, 400, LineW, 10000);
line9 = new Rectangle(770, 250, LineW, 100000);
line10 = new Rectangle(838, 100, LineW, 10000);
line11 = new Rectangle(936, 640, LineW, 100000);
line12 = new Rectangle(1016, 100, LineW, 100000);
line13 = new Rectangle(1066, 500, LineW, 100000);
line14 = new Rectangle(1131, 60, LineW, 100000);
//map2
line15 = new Rectangle(109, 600, LineW, 1000);
line16 = new Rectangle(235, 360, LineW, 1000);
line17 = new Rectangle(403, 180, LineW, 1000);
line18 = new Rectangle(511, 80, LineW, 1000);
line19 = new Rectangle(580, 80, LineW, 1000);
line20 = new Rectangle(671, 400, LineW, 10000);
line21 = new Rectangle(770, 250, LineW, 100000);
line22 = new Rectangle(838, 100, LineW, 10000);
line23 = new Rectangle(936, 640, LineW, 100000);
line24 = new Rectangle(1016, 100, LineW, 100000);
line25 = new Rectangle(1066, 500, LineW, 100000);
line26 = new Rectangle(1131, 60, LineW, 100000);
//KeyListener
if(isMoving){
f.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_D){
right = true;
RightSide = true;
}
if(e.getKeyCode() == KeyEvent.VK_RIGHT){
right = true;
RightSide = true;
}
if(e.getKeyCode() == KeyEvent.VK_A){
left = true;
LeftSide = true;
}
if(e.getKeyCode() == KeyEvent.VK_K){
KeysIns = true;
}
if(e.getKeyCode() == KeyEvent.VK_LEFT){
left = true;
LeftSide = true;
}
if(e.getKeyCode() == KeyEvent.VK_M) {
mouseActive = true;
System.out.println(mouse.x);
System.out.println(mouse.y);
}
if(e.getKeyCode() == KeyEvent.VK_S){
down = true; }
if(e.getKeyCode() == KeyEvent.VK_DOWN){
down = true; }
if(e.getKeyCode() == KeyEvent.VK_W){
up = true; }
if(e.getKeyCode() == KeyEvent.VK_UP){
up = true; }
if(e.getKeyCode() == KeyEvent.VK_SPACE) {
verticalSpeed = 2f;
//jumping = true;
//new Thread(new thread().start();
}
if(e.getKeyCode() == KeyEvent.VK_ESCAPE) {
System.exit(0);
}
if(e.getKeyCode() == KeyEvent.VK_R) {
Restart = true;
}
if(e.getKeyCode() == KeyEvent.VK_C) {
mouseActive = true;
}
if(e.getKeyCode() == KeyEvent.VK_SHIFT) {
up = false;
down = false;
left = false;
right = false;
}
}
public void keyReleased(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_D){
right = false;
mouseActive = false;
RightSide = false;
}
if(e.getKeyCode() == KeyEvent.VK_RIGHT){
right = false;
mouseActive = false;
RightSide = false;
}
if(e.getKeyCode() == KeyEvent.VK_A){
left = false;
mouseActive = false;
LeftSide = false; }
if(e.getKeyCode() == KeyEvent.VK_LEFT){
left = false;
mouseActive = false;
LeftSide = false; }
if(e.getKeyCode() == KeyEvent.VK_M) {
mouseActive = false;
}
if(e.getKeyCode() == KeyEvent.VK_S){
down = false; }
if(e.getKeyCode() == KeyEvent.VK_DOWN){
down = false; }
if(e.getKeyCode() == KeyEvent.VK_W){
up = false; }
if(e.getKeyCode() == KeyEvent.VK_UP){
up = false; }
if(e.getKeyCode() == KeyEvent.VK_SPACE) {
verticalSpeed = 1f;
}
if(e.getKeyCode() == KeyEvent.VK_R) {
Restart = false;
}
if(e.getKeyCode() == KeyEvent.VK_K) {
KeysIns = false;
}
isMoving = false;
if(e.getKeyCode() == KeyEvent.VK_C) {
mouseActive = false;
//System.out.println(System.getProperty("user.dir"));
}
}
});
//MouseListener
f.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseMoved(MouseEvent e){
mouse = new Point(e.getX(), e.getY() -25);
if(mouseActive){
character.x = mouse.x;
character.y = mouse.y;
}
repaint();
}
}); }
}
//}
@Override
public void paintComponent(Graphics g){
//if(Main.f.i.imagesLoaded) {
super.paintComponent(g);
this.setBackground(Color.WHITE);
if(Reset){
character.x -= 10;
}
if(Restart){
maxHealth -= 1;
}
//Invisible lines being colored and filled
g.setColor(getBackground());
g.fillRect(InvLine.x, InvLine.y, InvLine.width, InvLine.height);
g.setColor(getBackground());
g.fillRect(InvLine2.x, InvLine2.y, InvLine2.width, InvLine2.height);
g.fillRect(InvLine3.x, InvLine3.y, InvLine3.width, InvLine3.height);
g.fillRect(StartingPoint.x, StartingPoint.y, StartingPoint.width, StartingPoint.height);
// Boss and character being colored and filled
g.setColor(Color.BLUE);
g.fillRect(FinalBoss.x, FinalBoss.y, FinalBoss.width, FinalBoss.height);
g.setColor(Color.RED);
g.fillRect(Boss.x, Boss.y, Boss.width, Boss.height);
g.fillRect(Boss2.x, Boss2.y, Boss2.width, Boss2.height);
g.fillRect(Boss3.x, Boss3.y, Boss3.width, Boss3.height);
g.fillRect(Boss4.x, Boss4.y, Boss4.width, Boss4.height);
g.fillRect(Boss5.x, Boss5.y, Boss5.width, Boss5.height);
g.setColor(Color.RED);
g.setFont(g.getFont().deriveFont(35f));
g.drawString("Life left " + maxHealth, 10, 35);
if(RightSide)
g.setColor(Color.BLUE);
else
g.setColor(Color.BLUE);
if(LeftSide)
g.setColor(Color.BLUE);
g.fillRect(character.x, character.y, character.width, character.height);
//Rectangle Being colored and filled
g.setColor(Color.BLACK);
g.fillRect(Top.x, Top.y, Top.width, Top.height);
g.fillRect(Bottom.x, Bottom.y, Bottom.width, Bottom.height);
g.fillRect(Left.x, Left.y, Left.width, Left.height);
g.fillRect(Right.x, Right.y, Right.width, Right.height);
g.fillRect(Line.x, Line.y, Line.width, Line.height);
g.fillRect(Line2.x, Line2.y, Line2.width, Line2.height);
if(Map1){
g.setColor(Color.GREEN);
g.fillRect(Holder1.x, Holder1.y, Holder1.width, Holder1.height);
g.fillRect(Holder2.x, Holder2.y, Holder2.width, Holder2.height);
g.fillRect(Holder3.x, Holder3.y, Holder3.width, Holder3.height);
g.fillRect(Line3.x, Line3.y, Line3.width, Line3.height);
g.fillRect(Line4.x, Line4.y, Line4.width, Line4.height);
g.fillRect(Line5.x, Line5.y, Line5.width, Line5.height);
g.fillRect(Line6.x, Line6.y, Line6.width, Line6.height);
g.fillRect(line3.x, line3.y, line3.width, line3.height);
g.fillRect(line4.x, line4.y, line4.width, line4.height);
g.fillRect(line5.x, line5.y, line5.width, line5.height);
g.fillRect(line6.x, line6.y, line6.width, line6.height);
g.fillRect(line7.x, line7.y, line7.width, line7.height);
g.fillRect(Line7.x, Line7.y, Line7.width, Line7.height);
g.fillRect(Line8.x, Line8.y, Line8.width, Line8.height);
g.fillRect(line8.x, line8.y, line8.width, line8.height);
g.fillRect(Line9.x, Line9.y, Line9.width, Line9.height);
g.fillRect(line9.x, line9.y, line9.width, line9.height);
g.fillRect(Line10.x, Line10.y, Line10.width, Line10.height);
g.fillRect(line10.x, line10.y, line10.width, line10.height);
g.fillRect(Line11.x, Line11.y, Line11.width, Line11.height);
g.fillRect(line11.x, line11.y, line11.width, line11.height);
g.fillRect(Line12.x, Line12.y, Line12.width, Line12.height);
g.fillRect(line12.x, line12.y, line12.width, line12.height);
g.fillRect(Line13.x, Line13.y, Line13.width, Line13.height);
g.fillRect(line13.x, line13.y, line13.width, line13.height);
g.fillRect(Line14.x, Line14.y, Line14.width, Line14.height);
g.fillRect(line14.x, line14.y, line14.width, line14.height);
}
if(Map2){
g.setColor(Color.RED);
g.fillRect(Line15.x, Line15.y, Line15.width, Line15.height);
g.fillRect(Line16.x, Line16.y, Line16.width, Line16.height);
g.fillRect(Line17.x, Line17.y, Line17.width, Line17.height);
g.fillRect(Line18.x, Line18.y, Line18.width, Line18.height);
g.fillRect(Line19.x, Line19.y, Line19.width, Line19.height);
g.fillRect(Line20.x, Line20.y, Line20.width, Line20.height);
g.fillRect(Line21.x, Line21.y, Line21.width, Line21.height);
g.fillRect(Line22.x, Line22.y, Line22.width, Line22.height);
g.fillRect(Line23.x, Line23.y, Line23.width, Line23.height);
g.fillRect(Line24.x, Line24.y, Line24.width, Line24.height);
g.fillRect(Line25.x, Line25.y, Line25.width, Line25.height);
g.fillRect(Line26.x, Line26.y, Line26.width, Line26.height);
g.fillRect(line15.x, line15.y, line15.width, line15.height);
g.fillRect(line16.x, line16.y, line16.width, line16.height);
g.fillRect(line17.x, line17.y, line17.width, line17.height);
g.fillRect(line18.x, line18.y, line18.width, line18.height);
g.fillRect(line19.x, line19.y, line19.width, line19.height);
g.fillRect(line20.x, line20.y, line20.width, line20.height);
g.fillRect(line21.x, line21.y, line21.width, line21.height);
g.fillRect(line22.x, line22.y, line22.width, line22.height);
g.fillRect(line23.x, line23.y, line23.width, line23.height);
g.fillRect(line24.x, line24.y, line24.width, line24.height);
g.fillRect(line25.x, line25.y, line25.width, line25.height);
g.fillRect(line26.x, line26.y, line26.width, line26.height);
}
if(Map3){
g.setColor(Color.GREEN);
g.fillRect(Holder1.x, Holder1.y, Holder1.width, Holder1.height);
g.fillRect(Holder2.x, Holder2.y, Holder2.width, Holder2.height);
g.fillRect(Holder3.x, Holder3.y, Holder3.width, Holder3.height);
g.fillRect(Line3.x, Line3.y, Line3.width, Line3.height);
g.fillRect(Line4.x, Line4.y, Line4.width, Line4.height);
g.fillRect(Line5.x, Line5.y, Line5.width, Line5.height);
g.fillRect(Line6.x, Line6.y, Line6.width, Line6.height);
g.fillRect(line3.x, line3.y, line3.width, line3.height);
g.fillRect(line4.x, line4.y, line4.width, line4.height);
g.fillRect(line5.x, line5.y, line5.width, line5.height);
g.fillRect(line6.x, line6.y, line6.width, line6.height);
g.fillRect(line7.x, line7.y, line7.width, line7.height);
g.fillRect(Line7.x, Line7.y, Line7.width, Line7.height);
g.fillRect(Line8.x, Line8.y, Line8.width, Line8.height);
g.fillRect(line8.x, line8.y, line8.width, line8.height);
g.fillRect(Line9.x, Line9.y, Line9.width, Line9.height);
g.fillRect(line9.x, line9.y, line9.width, line9.height);
g.fillRect(Line10.x, Line10.y, Line10.width, Line10.height);
g.fillRect(line10.x, line10.y, line10.width, line10.height);
g.fillRect(Line11.x, Line11.y, Line11.width, Line11.height);
g.fillRect(line11.x, line11.y, line11.width, line11.height);
g.fillRect(Line12.x, Line12.y, Line12.width, Line12.height);
g.fillRect(line12.x, line12.y, line12.width, line12.height);
g.fillRect(Line13.x, Line13.y, Line13.width, Line13.height);
g.fillRect(line13.x, line13.y, line13.width, line13.height);
g.fillRect(Line14.x, Line14.y, Line14.width, Line14.height);
g.fillRect(line14.x, line14.y, line14.width, line14.height);
}
//Information If statement
if(KeysIns){
g.setColor(Color.BLACK);
g.setFont(g.getFont().deriveFont(25f));
g.drawString("Your goal", 123, 140);
g.drawString("is to get", 126, 200);
g.drawString("your character", 126, 250);
g.drawString("to the SafeZone", 126, 300);
g.drawString("Without touching the black line", 126, 350);
g.drawString("Careful that you can go to the left", 126, 400);
g.drawString("Through the walls but not right.", 126, 450);
g.drawString("Be careful not to touch the Bosses.", 126, 500);
g.setColor(Color.BLUE);
g.drawString("WASD / arrow", 251,550);
g.drawString("keys to move", 251, 580);
g.drawString("Shift in case of panic", 251, 615);
g.drawString("R to Reset", 251, 650);
g.drawString("Escape to Quit", 251, 670);
g.drawString("Space to Sprint", 251, 690);
//IF Statements
if(DeathScreen){
g.setColor(Color.BLACK);
g.setFont(g.getFont().deriveFont(25f));
g.drawString("Press R to restart", 496, 300);
isMoving = false;
}
}
if(Map1){
g.setColor(Color.BLUE);
g.setFont(g.getFont().deriveFont(25f));
g.drawString("Level: 1 ", 253, 25);
}
if(Map2){
g.setColor(Color.BLUE);
g.setFont(g.getFont().deriveFont(25f));
g.drawString("Level: 2 ", 253, 25);
}
if(Dead) {
g.setColor(Color.RED);
g.setFont(g.getFont().deriveFont(25f));
g.drawString("You Died", 496, 260);
g.drawString("Press R to restart", 496, 310);
isMoving = false;
}
if(Restart){
character.x = 52;
character.y = 52;
Dead = false;
DeathScreen = false;
Finished = false;
}
if(StopReset1) {
Reset = false;
}
if(FUp){
FDown = false;
FinalBoss.y -= 1;
}
if(FDown){
FUp = false;
FinalBoss.y += 1;
}
if(FRight){
FLeft = false;
FinalBoss.x += 1;
}
if(FLeft){
FRight = false;
FinalBoss.x -= 1;
}
if(FMoving){
if(FinalBoss.intersects(InvLine3)){
FLeft = false;
FRight = true;
}
if(FinalBoss.intersects(InvLine)){
FRight = false;
FLeft = true;
}
if(FinalBoss.intersects(Top)){
FUp = false;
FDown = true;
}
if(FinalBoss.intersects(Bottom)){
FDown = false;
FUp = true;
}
if(FinalBoss.intersects(Line)){
FRight = false;
FLeft = true;
}
if(FinalBoss.intersects(Line2)){
FRight = false;
FLeft = true;
}
if(FinalBoss.intersects(Line14)){
FLeft = false;
FRight = true;
}
if(FinalBoss.intersects(line14)){
FLeft = false;
FRight = true;
}
}
if(BUp){
BDown = false;
Boss.y -= 1;
}
if(BDown){
BUp = false;
Boss.y += 1;
}
if(BUp2){
BDown2 = false;
Boss2.y -= 1;
}
if(BDown2){
BUp2 = false;
Boss2.y += 1;
}
if(BUp3){
BDown3 = false;
Boss3.y -= 1;
}
if(BDown3){
BUp3 = false;
Boss3.y += 1;
}
if(BUp4){
BDown4 = false;
Boss4.y -= 1;
}
if(BDown4){
BUp4 = false;
Boss4.y += 1;
}
if(BUp5){
BDown5 = false;
Boss5.y -= 1;
}
if(BDown5){
BUp5 = false;
Boss5.y += 1;
}
if(BossMoving){
if(Boss.intersects(Top)){
BUp = false;
BDown = true;
}
if(Boss.intersects(Bottom)){
BDown = false;
BUp = true;
}
}
if(BossMoving2){
if(Boss2.intersects(Top)){
BUp2 = false;
BDown2 = true;
}
if(Boss2.intersects(Bottom)){
BDown2 = false;
BUp2 = true;
}
}
if(BossMoving3){
if(Boss3.intersects(Top)){
BUp3 = false;
BDown3 = true;
}
if(Boss3.intersects(Bottom)){
BDown3 = false;
BUp3 = true;
}
}
if(BossMoving4){
if(Boss4.intersects(Top)){
BUp4 = false;
BDown4 = true;
}
if(Boss4.intersects(Bottom)){
BDown4 = false;
BUp4 = true;
}
}
if(BossMoving5){
if(Boss5.intersects(Top)){
BUp5 = false;
BDown5 = true;
}
if(Boss3.intersects(Bottom)){
BDown5 = false;
BUp5 = true;
}
}
//If Statements for walls
if(character.intersects(FinalBoss)) {
Dead = true;
isMoving = false;
DeathScreen = true;
character.x = 40000;
}
if(character.intersects(Boss)) {
Dead = true;
isMoving = false;
DeathScreen = true;
character.x = 40000;
}
if(character.intersects(Boss2)) {
Dead = true;
isMoving = false;
DeathScreen = true;
character.x = 40000;
}
if(character.intersects(Boss3)) {
Dead = true;
isMoving = false;
DeathScreen = true;
character.x = 40000;
}
if(character.intersects(Boss4)) {
Dead = true;
isMoving = false;
DeathScreen = true;
character.x = 40000;
}
if(character.intersects(Boss5)) {
Dead = true;
isMoving = false;
DeathScreen = true;
character.x = 40000;
}
if(character.intersects(Right)) {
character.x -= 10;
StopReset1 = true;
}
if(character.intersects(Left)) {
character.x += 10;
StopReset1 = true;
}
if(character.intersects(Bottom)) {
character.y -= 10;
StopReset1 = true;
}
if(Map1){
if(character.intersects(Holder1)) {
character.y += 10;
StopReset1 = true;
SpeedBoost = true;
}
if(character.intersects(Holder2)) {
character.y += 10;
StopReset1 = true;
}
if(character.intersects(Holder3)) {
- character.y += 10;
+ character.y -= 10;
StopReset1 = true;
}
if(character.intersects(Top)) {
character.y += 10;
StopReset1 = true;
}
if(character.intersects(Line)) {
Dead = true;
isMoving = false;
DeathScreen = true;
character.x = 40000;
}
if(character.intersects(Line2)) {
Dead = true;
isMoving = false;
DeathScreen = true;
character.x = 40000;
}
if(character.intersects(Line3)) {
Reset = true;
StopReset1 = true;
}
if(character.intersects(Line4)) {
Reset = true;
StopReset1 = true;
}
if(character.intersects(Line5)) {
Reset = true;
StopReset1 = true;
}
if(character.intersects(Line6)) {
Reset = true;
StopReset1 = true;
}
if(character.intersects(line3)) {
Reset = true;
StopReset1 = true;
}
if(character.intersects(line4)) {
Reset = true;
StopReset1 = true;
}
if(character.intersects(line5)) {
Reset = true;
StopReset1 = true;
}
if(character.intersects(line6)) {
Reset = true;
StopReset1 = true;
}
if(character.intersects(line7)) {
Reset = true;
StopReset1 = true;
}
if(character.intersects(Line7)) {
Reset = true;
StopReset1 = true;
}
if(character.intersects(line8)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line8)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line9)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line9)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line10)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line10)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line11)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line11)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line12)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line12)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line13)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line13)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line14)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line14)) {
Reset = true;
StopReset1 = true;}
}
if(Map2){
if(character.intersects(Line15)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line16)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line17)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line18)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line19)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line20)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line21)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line22)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line23)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line24)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line25)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line26)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line15)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line16)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line17)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line18)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line19)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line20)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line21)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line22)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line23)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line24)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line25)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line26)) {
Reset = true;
StopReset1 = true;}
}
//If Statements for Invisible lines
if(character.intersects(InvLine)) {
g.setColor(Color.BLUE);
g.setFont(g.getFont().deriveFont(25f));
}
if(character.intersects(InvLine2)) {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
Finished = true;
}
if(Finished){
character.x = 52;
character.y = 52;
g.setColor(Color.BLACK);
g.setFont(g.getFont().deriveFont(35f));
g.drawString("Thank you for Playing!", 440, 260);
g.drawString("You Passed!", 500, 300);
g.setColor(Color.BLUE);
g.setFont(g.getFont().deriveFont(30));
g.drawString("Close to Restart", 500, 500);
Map1 = false;
Map2 = true;
if(character.intersects(InvLine)){
if(Map2){
Map1 = Map2;
Map2 = Map3;
Map3 = true;
Map2 = false;
}
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Finished = false;
}
if(character.intersects(StartingPoint)) {
Restart = false;
g.setColor(Color.BLACK);
g.setFont(g.getFont().deriveFont(25f));
g.drawString("Press K", 258, 100);
g.drawString("for Instructions", 260, 145);
g.setColor(Color.BLUE);
g.drawString("WASD / arrow", 251,550);
g.drawString("keys to move", 251, 580);
}
if(maxHealth <= 0){
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
lost = true;
}
if(lost){
character.x = 52;
character.y = 52;
g.setColor(Color.BLACK);
g.setFont(g.getFont().deriveFont(35f));
g.drawString("You Lost!", 440, 260);
g.setColor(Color.BLUE);
g.setFont(g.getFont().deriveFont(30));
g.drawString("Close to Restart", 500, 500);
}
//If Statements for character movement
if(jumping){
character.y --;
}
if(right){
character.x += verticalSpeed;
}
if(left){
character.x -= verticalSpeed;
}
if(up)
character.y += -verticalSpeed;
if(down){
character.y += verticalSpeed;
}
repaint();
}
public void NextMap(){
if(Map2){
if(Finished){
System.exit(0);
}
}
}
}
//}
| true | true | public void paintComponent(Graphics g){
//if(Main.f.i.imagesLoaded) {
super.paintComponent(g);
this.setBackground(Color.WHITE);
if(Reset){
character.x -= 10;
}
if(Restart){
maxHealth -= 1;
}
//Invisible lines being colored and filled
g.setColor(getBackground());
g.fillRect(InvLine.x, InvLine.y, InvLine.width, InvLine.height);
g.setColor(getBackground());
g.fillRect(InvLine2.x, InvLine2.y, InvLine2.width, InvLine2.height);
g.fillRect(InvLine3.x, InvLine3.y, InvLine3.width, InvLine3.height);
g.fillRect(StartingPoint.x, StartingPoint.y, StartingPoint.width, StartingPoint.height);
// Boss and character being colored and filled
g.setColor(Color.BLUE);
g.fillRect(FinalBoss.x, FinalBoss.y, FinalBoss.width, FinalBoss.height);
g.setColor(Color.RED);
g.fillRect(Boss.x, Boss.y, Boss.width, Boss.height);
g.fillRect(Boss2.x, Boss2.y, Boss2.width, Boss2.height);
g.fillRect(Boss3.x, Boss3.y, Boss3.width, Boss3.height);
g.fillRect(Boss4.x, Boss4.y, Boss4.width, Boss4.height);
g.fillRect(Boss5.x, Boss5.y, Boss5.width, Boss5.height);
g.setColor(Color.RED);
g.setFont(g.getFont().deriveFont(35f));
g.drawString("Life left " + maxHealth, 10, 35);
if(RightSide)
g.setColor(Color.BLUE);
else
g.setColor(Color.BLUE);
if(LeftSide)
g.setColor(Color.BLUE);
g.fillRect(character.x, character.y, character.width, character.height);
//Rectangle Being colored and filled
g.setColor(Color.BLACK);
g.fillRect(Top.x, Top.y, Top.width, Top.height);
g.fillRect(Bottom.x, Bottom.y, Bottom.width, Bottom.height);
g.fillRect(Left.x, Left.y, Left.width, Left.height);
g.fillRect(Right.x, Right.y, Right.width, Right.height);
g.fillRect(Line.x, Line.y, Line.width, Line.height);
g.fillRect(Line2.x, Line2.y, Line2.width, Line2.height);
if(Map1){
g.setColor(Color.GREEN);
g.fillRect(Holder1.x, Holder1.y, Holder1.width, Holder1.height);
g.fillRect(Holder2.x, Holder2.y, Holder2.width, Holder2.height);
g.fillRect(Holder3.x, Holder3.y, Holder3.width, Holder3.height);
g.fillRect(Line3.x, Line3.y, Line3.width, Line3.height);
g.fillRect(Line4.x, Line4.y, Line4.width, Line4.height);
g.fillRect(Line5.x, Line5.y, Line5.width, Line5.height);
g.fillRect(Line6.x, Line6.y, Line6.width, Line6.height);
g.fillRect(line3.x, line3.y, line3.width, line3.height);
g.fillRect(line4.x, line4.y, line4.width, line4.height);
g.fillRect(line5.x, line5.y, line5.width, line5.height);
g.fillRect(line6.x, line6.y, line6.width, line6.height);
g.fillRect(line7.x, line7.y, line7.width, line7.height);
g.fillRect(Line7.x, Line7.y, Line7.width, Line7.height);
g.fillRect(Line8.x, Line8.y, Line8.width, Line8.height);
g.fillRect(line8.x, line8.y, line8.width, line8.height);
g.fillRect(Line9.x, Line9.y, Line9.width, Line9.height);
g.fillRect(line9.x, line9.y, line9.width, line9.height);
g.fillRect(Line10.x, Line10.y, Line10.width, Line10.height);
g.fillRect(line10.x, line10.y, line10.width, line10.height);
g.fillRect(Line11.x, Line11.y, Line11.width, Line11.height);
g.fillRect(line11.x, line11.y, line11.width, line11.height);
g.fillRect(Line12.x, Line12.y, Line12.width, Line12.height);
g.fillRect(line12.x, line12.y, line12.width, line12.height);
g.fillRect(Line13.x, Line13.y, Line13.width, Line13.height);
g.fillRect(line13.x, line13.y, line13.width, line13.height);
g.fillRect(Line14.x, Line14.y, Line14.width, Line14.height);
g.fillRect(line14.x, line14.y, line14.width, line14.height);
}
if(Map2){
g.setColor(Color.RED);
g.fillRect(Line15.x, Line15.y, Line15.width, Line15.height);
g.fillRect(Line16.x, Line16.y, Line16.width, Line16.height);
g.fillRect(Line17.x, Line17.y, Line17.width, Line17.height);
g.fillRect(Line18.x, Line18.y, Line18.width, Line18.height);
g.fillRect(Line19.x, Line19.y, Line19.width, Line19.height);
g.fillRect(Line20.x, Line20.y, Line20.width, Line20.height);
g.fillRect(Line21.x, Line21.y, Line21.width, Line21.height);
g.fillRect(Line22.x, Line22.y, Line22.width, Line22.height);
g.fillRect(Line23.x, Line23.y, Line23.width, Line23.height);
g.fillRect(Line24.x, Line24.y, Line24.width, Line24.height);
g.fillRect(Line25.x, Line25.y, Line25.width, Line25.height);
g.fillRect(Line26.x, Line26.y, Line26.width, Line26.height);
g.fillRect(line15.x, line15.y, line15.width, line15.height);
g.fillRect(line16.x, line16.y, line16.width, line16.height);
g.fillRect(line17.x, line17.y, line17.width, line17.height);
g.fillRect(line18.x, line18.y, line18.width, line18.height);
g.fillRect(line19.x, line19.y, line19.width, line19.height);
g.fillRect(line20.x, line20.y, line20.width, line20.height);
g.fillRect(line21.x, line21.y, line21.width, line21.height);
g.fillRect(line22.x, line22.y, line22.width, line22.height);
g.fillRect(line23.x, line23.y, line23.width, line23.height);
g.fillRect(line24.x, line24.y, line24.width, line24.height);
g.fillRect(line25.x, line25.y, line25.width, line25.height);
g.fillRect(line26.x, line26.y, line26.width, line26.height);
}
if(Map3){
g.setColor(Color.GREEN);
g.fillRect(Holder1.x, Holder1.y, Holder1.width, Holder1.height);
g.fillRect(Holder2.x, Holder2.y, Holder2.width, Holder2.height);
g.fillRect(Holder3.x, Holder3.y, Holder3.width, Holder3.height);
g.fillRect(Line3.x, Line3.y, Line3.width, Line3.height);
g.fillRect(Line4.x, Line4.y, Line4.width, Line4.height);
g.fillRect(Line5.x, Line5.y, Line5.width, Line5.height);
g.fillRect(Line6.x, Line6.y, Line6.width, Line6.height);
g.fillRect(line3.x, line3.y, line3.width, line3.height);
g.fillRect(line4.x, line4.y, line4.width, line4.height);
g.fillRect(line5.x, line5.y, line5.width, line5.height);
g.fillRect(line6.x, line6.y, line6.width, line6.height);
g.fillRect(line7.x, line7.y, line7.width, line7.height);
g.fillRect(Line7.x, Line7.y, Line7.width, Line7.height);
g.fillRect(Line8.x, Line8.y, Line8.width, Line8.height);
g.fillRect(line8.x, line8.y, line8.width, line8.height);
g.fillRect(Line9.x, Line9.y, Line9.width, Line9.height);
g.fillRect(line9.x, line9.y, line9.width, line9.height);
g.fillRect(Line10.x, Line10.y, Line10.width, Line10.height);
g.fillRect(line10.x, line10.y, line10.width, line10.height);
g.fillRect(Line11.x, Line11.y, Line11.width, Line11.height);
g.fillRect(line11.x, line11.y, line11.width, line11.height);
g.fillRect(Line12.x, Line12.y, Line12.width, Line12.height);
g.fillRect(line12.x, line12.y, line12.width, line12.height);
g.fillRect(Line13.x, Line13.y, Line13.width, Line13.height);
g.fillRect(line13.x, line13.y, line13.width, line13.height);
g.fillRect(Line14.x, Line14.y, Line14.width, Line14.height);
g.fillRect(line14.x, line14.y, line14.width, line14.height);
}
//Information If statement
if(KeysIns){
g.setColor(Color.BLACK);
g.setFont(g.getFont().deriveFont(25f));
g.drawString("Your goal", 123, 140);
g.drawString("is to get", 126, 200);
g.drawString("your character", 126, 250);
g.drawString("to the SafeZone", 126, 300);
g.drawString("Without touching the black line", 126, 350);
g.drawString("Careful that you can go to the left", 126, 400);
g.drawString("Through the walls but not right.", 126, 450);
g.drawString("Be careful not to touch the Bosses.", 126, 500);
g.setColor(Color.BLUE);
g.drawString("WASD / arrow", 251,550);
g.drawString("keys to move", 251, 580);
g.drawString("Shift in case of panic", 251, 615);
g.drawString("R to Reset", 251, 650);
g.drawString("Escape to Quit", 251, 670);
g.drawString("Space to Sprint", 251, 690);
//IF Statements
if(DeathScreen){
g.setColor(Color.BLACK);
g.setFont(g.getFont().deriveFont(25f));
g.drawString("Press R to restart", 496, 300);
isMoving = false;
}
}
if(Map1){
g.setColor(Color.BLUE);
g.setFont(g.getFont().deriveFont(25f));
g.drawString("Level: 1 ", 253, 25);
}
if(Map2){
g.setColor(Color.BLUE);
g.setFont(g.getFont().deriveFont(25f));
g.drawString("Level: 2 ", 253, 25);
}
if(Dead) {
g.setColor(Color.RED);
g.setFont(g.getFont().deriveFont(25f));
g.drawString("You Died", 496, 260);
g.drawString("Press R to restart", 496, 310);
isMoving = false;
}
if(Restart){
character.x = 52;
character.y = 52;
Dead = false;
DeathScreen = false;
Finished = false;
}
if(StopReset1) {
Reset = false;
}
if(FUp){
FDown = false;
FinalBoss.y -= 1;
}
if(FDown){
FUp = false;
FinalBoss.y += 1;
}
if(FRight){
FLeft = false;
FinalBoss.x += 1;
}
if(FLeft){
FRight = false;
FinalBoss.x -= 1;
}
if(FMoving){
if(FinalBoss.intersects(InvLine3)){
FLeft = false;
FRight = true;
}
if(FinalBoss.intersects(InvLine)){
FRight = false;
FLeft = true;
}
if(FinalBoss.intersects(Top)){
FUp = false;
FDown = true;
}
if(FinalBoss.intersects(Bottom)){
FDown = false;
FUp = true;
}
if(FinalBoss.intersects(Line)){
FRight = false;
FLeft = true;
}
if(FinalBoss.intersects(Line2)){
FRight = false;
FLeft = true;
}
if(FinalBoss.intersects(Line14)){
FLeft = false;
FRight = true;
}
if(FinalBoss.intersects(line14)){
FLeft = false;
FRight = true;
}
}
if(BUp){
BDown = false;
Boss.y -= 1;
}
if(BDown){
BUp = false;
Boss.y += 1;
}
if(BUp2){
BDown2 = false;
Boss2.y -= 1;
}
if(BDown2){
BUp2 = false;
Boss2.y += 1;
}
if(BUp3){
BDown3 = false;
Boss3.y -= 1;
}
if(BDown3){
BUp3 = false;
Boss3.y += 1;
}
if(BUp4){
BDown4 = false;
Boss4.y -= 1;
}
if(BDown4){
BUp4 = false;
Boss4.y += 1;
}
if(BUp5){
BDown5 = false;
Boss5.y -= 1;
}
if(BDown5){
BUp5 = false;
Boss5.y += 1;
}
if(BossMoving){
if(Boss.intersects(Top)){
BUp = false;
BDown = true;
}
if(Boss.intersects(Bottom)){
BDown = false;
BUp = true;
}
}
if(BossMoving2){
if(Boss2.intersects(Top)){
BUp2 = false;
BDown2 = true;
}
if(Boss2.intersects(Bottom)){
BDown2 = false;
BUp2 = true;
}
}
if(BossMoving3){
if(Boss3.intersects(Top)){
BUp3 = false;
BDown3 = true;
}
if(Boss3.intersects(Bottom)){
BDown3 = false;
BUp3 = true;
}
}
if(BossMoving4){
if(Boss4.intersects(Top)){
BUp4 = false;
BDown4 = true;
}
if(Boss4.intersects(Bottom)){
BDown4 = false;
BUp4 = true;
}
}
if(BossMoving5){
if(Boss5.intersects(Top)){
BUp5 = false;
BDown5 = true;
}
if(Boss3.intersects(Bottom)){
BDown5 = false;
BUp5 = true;
}
}
//If Statements for walls
if(character.intersects(FinalBoss)) {
Dead = true;
isMoving = false;
DeathScreen = true;
character.x = 40000;
}
if(character.intersects(Boss)) {
Dead = true;
isMoving = false;
DeathScreen = true;
character.x = 40000;
}
if(character.intersects(Boss2)) {
Dead = true;
isMoving = false;
DeathScreen = true;
character.x = 40000;
}
if(character.intersects(Boss3)) {
Dead = true;
isMoving = false;
DeathScreen = true;
character.x = 40000;
}
if(character.intersects(Boss4)) {
Dead = true;
isMoving = false;
DeathScreen = true;
character.x = 40000;
}
if(character.intersects(Boss5)) {
Dead = true;
isMoving = false;
DeathScreen = true;
character.x = 40000;
}
if(character.intersects(Right)) {
character.x -= 10;
StopReset1 = true;
}
if(character.intersects(Left)) {
character.x += 10;
StopReset1 = true;
}
if(character.intersects(Bottom)) {
character.y -= 10;
StopReset1 = true;
}
if(Map1){
if(character.intersects(Holder1)) {
character.y += 10;
StopReset1 = true;
SpeedBoost = true;
}
if(character.intersects(Holder2)) {
character.y += 10;
StopReset1 = true;
}
if(character.intersects(Holder3)) {
character.y += 10;
StopReset1 = true;
}
if(character.intersects(Top)) {
character.y += 10;
StopReset1 = true;
}
if(character.intersects(Line)) {
Dead = true;
isMoving = false;
DeathScreen = true;
character.x = 40000;
}
if(character.intersects(Line2)) {
Dead = true;
isMoving = false;
DeathScreen = true;
character.x = 40000;
}
if(character.intersects(Line3)) {
Reset = true;
StopReset1 = true;
}
if(character.intersects(Line4)) {
Reset = true;
StopReset1 = true;
}
if(character.intersects(Line5)) {
Reset = true;
StopReset1 = true;
}
if(character.intersects(Line6)) {
Reset = true;
StopReset1 = true;
}
if(character.intersects(line3)) {
Reset = true;
StopReset1 = true;
}
if(character.intersects(line4)) {
Reset = true;
StopReset1 = true;
}
if(character.intersects(line5)) {
Reset = true;
StopReset1 = true;
}
if(character.intersects(line6)) {
Reset = true;
StopReset1 = true;
}
if(character.intersects(line7)) {
Reset = true;
StopReset1 = true;
}
if(character.intersects(Line7)) {
Reset = true;
StopReset1 = true;
}
if(character.intersects(line8)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line8)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line9)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line9)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line10)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line10)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line11)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line11)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line12)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line12)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line13)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line13)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line14)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line14)) {
Reset = true;
StopReset1 = true;}
}
if(Map2){
if(character.intersects(Line15)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line16)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line17)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line18)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line19)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line20)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line21)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line22)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line23)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line24)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line25)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line26)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line15)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line16)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line17)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line18)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line19)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line20)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line21)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line22)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line23)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line24)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line25)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line26)) {
Reset = true;
StopReset1 = true;}
}
//If Statements for Invisible lines
if(character.intersects(InvLine)) {
g.setColor(Color.BLUE);
g.setFont(g.getFont().deriveFont(25f));
}
if(character.intersects(InvLine2)) {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
Finished = true;
}
if(Finished){
character.x = 52;
character.y = 52;
g.setColor(Color.BLACK);
g.setFont(g.getFont().deriveFont(35f));
g.drawString("Thank you for Playing!", 440, 260);
g.drawString("You Passed!", 500, 300);
g.setColor(Color.BLUE);
g.setFont(g.getFont().deriveFont(30));
g.drawString("Close to Restart", 500, 500);
Map1 = false;
Map2 = true;
if(character.intersects(InvLine)){
if(Map2){
Map1 = Map2;
Map2 = Map3;
Map3 = true;
Map2 = false;
}
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Finished = false;
}
if(character.intersects(StartingPoint)) {
Restart = false;
g.setColor(Color.BLACK);
g.setFont(g.getFont().deriveFont(25f));
g.drawString("Press K", 258, 100);
g.drawString("for Instructions", 260, 145);
g.setColor(Color.BLUE);
g.drawString("WASD / arrow", 251,550);
g.drawString("keys to move", 251, 580);
}
if(maxHealth <= 0){
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
lost = true;
}
if(lost){
character.x = 52;
character.y = 52;
g.setColor(Color.BLACK);
g.setFont(g.getFont().deriveFont(35f));
g.drawString("You Lost!", 440, 260);
g.setColor(Color.BLUE);
g.setFont(g.getFont().deriveFont(30));
g.drawString("Close to Restart", 500, 500);
}
//If Statements for character movement
if(jumping){
character.y --;
}
if(right){
character.x += verticalSpeed;
}
if(left){
character.x -= verticalSpeed;
}
if(up)
character.y += -verticalSpeed;
if(down){
character.y += verticalSpeed;
}
repaint();
}
| public void paintComponent(Graphics g){
//if(Main.f.i.imagesLoaded) {
super.paintComponent(g);
this.setBackground(Color.WHITE);
if(Reset){
character.x -= 10;
}
if(Restart){
maxHealth -= 1;
}
//Invisible lines being colored and filled
g.setColor(getBackground());
g.fillRect(InvLine.x, InvLine.y, InvLine.width, InvLine.height);
g.setColor(getBackground());
g.fillRect(InvLine2.x, InvLine2.y, InvLine2.width, InvLine2.height);
g.fillRect(InvLine3.x, InvLine3.y, InvLine3.width, InvLine3.height);
g.fillRect(StartingPoint.x, StartingPoint.y, StartingPoint.width, StartingPoint.height);
// Boss and character being colored and filled
g.setColor(Color.BLUE);
g.fillRect(FinalBoss.x, FinalBoss.y, FinalBoss.width, FinalBoss.height);
g.setColor(Color.RED);
g.fillRect(Boss.x, Boss.y, Boss.width, Boss.height);
g.fillRect(Boss2.x, Boss2.y, Boss2.width, Boss2.height);
g.fillRect(Boss3.x, Boss3.y, Boss3.width, Boss3.height);
g.fillRect(Boss4.x, Boss4.y, Boss4.width, Boss4.height);
g.fillRect(Boss5.x, Boss5.y, Boss5.width, Boss5.height);
g.setColor(Color.RED);
g.setFont(g.getFont().deriveFont(35f));
g.drawString("Life left " + maxHealth, 10, 35);
if(RightSide)
g.setColor(Color.BLUE);
else
g.setColor(Color.BLUE);
if(LeftSide)
g.setColor(Color.BLUE);
g.fillRect(character.x, character.y, character.width, character.height);
//Rectangle Being colored and filled
g.setColor(Color.BLACK);
g.fillRect(Top.x, Top.y, Top.width, Top.height);
g.fillRect(Bottom.x, Bottom.y, Bottom.width, Bottom.height);
g.fillRect(Left.x, Left.y, Left.width, Left.height);
g.fillRect(Right.x, Right.y, Right.width, Right.height);
g.fillRect(Line.x, Line.y, Line.width, Line.height);
g.fillRect(Line2.x, Line2.y, Line2.width, Line2.height);
if(Map1){
g.setColor(Color.GREEN);
g.fillRect(Holder1.x, Holder1.y, Holder1.width, Holder1.height);
g.fillRect(Holder2.x, Holder2.y, Holder2.width, Holder2.height);
g.fillRect(Holder3.x, Holder3.y, Holder3.width, Holder3.height);
g.fillRect(Line3.x, Line3.y, Line3.width, Line3.height);
g.fillRect(Line4.x, Line4.y, Line4.width, Line4.height);
g.fillRect(Line5.x, Line5.y, Line5.width, Line5.height);
g.fillRect(Line6.x, Line6.y, Line6.width, Line6.height);
g.fillRect(line3.x, line3.y, line3.width, line3.height);
g.fillRect(line4.x, line4.y, line4.width, line4.height);
g.fillRect(line5.x, line5.y, line5.width, line5.height);
g.fillRect(line6.x, line6.y, line6.width, line6.height);
g.fillRect(line7.x, line7.y, line7.width, line7.height);
g.fillRect(Line7.x, Line7.y, Line7.width, Line7.height);
g.fillRect(Line8.x, Line8.y, Line8.width, Line8.height);
g.fillRect(line8.x, line8.y, line8.width, line8.height);
g.fillRect(Line9.x, Line9.y, Line9.width, Line9.height);
g.fillRect(line9.x, line9.y, line9.width, line9.height);
g.fillRect(Line10.x, Line10.y, Line10.width, Line10.height);
g.fillRect(line10.x, line10.y, line10.width, line10.height);
g.fillRect(Line11.x, Line11.y, Line11.width, Line11.height);
g.fillRect(line11.x, line11.y, line11.width, line11.height);
g.fillRect(Line12.x, Line12.y, Line12.width, Line12.height);
g.fillRect(line12.x, line12.y, line12.width, line12.height);
g.fillRect(Line13.x, Line13.y, Line13.width, Line13.height);
g.fillRect(line13.x, line13.y, line13.width, line13.height);
g.fillRect(Line14.x, Line14.y, Line14.width, Line14.height);
g.fillRect(line14.x, line14.y, line14.width, line14.height);
}
if(Map2){
g.setColor(Color.RED);
g.fillRect(Line15.x, Line15.y, Line15.width, Line15.height);
g.fillRect(Line16.x, Line16.y, Line16.width, Line16.height);
g.fillRect(Line17.x, Line17.y, Line17.width, Line17.height);
g.fillRect(Line18.x, Line18.y, Line18.width, Line18.height);
g.fillRect(Line19.x, Line19.y, Line19.width, Line19.height);
g.fillRect(Line20.x, Line20.y, Line20.width, Line20.height);
g.fillRect(Line21.x, Line21.y, Line21.width, Line21.height);
g.fillRect(Line22.x, Line22.y, Line22.width, Line22.height);
g.fillRect(Line23.x, Line23.y, Line23.width, Line23.height);
g.fillRect(Line24.x, Line24.y, Line24.width, Line24.height);
g.fillRect(Line25.x, Line25.y, Line25.width, Line25.height);
g.fillRect(Line26.x, Line26.y, Line26.width, Line26.height);
g.fillRect(line15.x, line15.y, line15.width, line15.height);
g.fillRect(line16.x, line16.y, line16.width, line16.height);
g.fillRect(line17.x, line17.y, line17.width, line17.height);
g.fillRect(line18.x, line18.y, line18.width, line18.height);
g.fillRect(line19.x, line19.y, line19.width, line19.height);
g.fillRect(line20.x, line20.y, line20.width, line20.height);
g.fillRect(line21.x, line21.y, line21.width, line21.height);
g.fillRect(line22.x, line22.y, line22.width, line22.height);
g.fillRect(line23.x, line23.y, line23.width, line23.height);
g.fillRect(line24.x, line24.y, line24.width, line24.height);
g.fillRect(line25.x, line25.y, line25.width, line25.height);
g.fillRect(line26.x, line26.y, line26.width, line26.height);
}
if(Map3){
g.setColor(Color.GREEN);
g.fillRect(Holder1.x, Holder1.y, Holder1.width, Holder1.height);
g.fillRect(Holder2.x, Holder2.y, Holder2.width, Holder2.height);
g.fillRect(Holder3.x, Holder3.y, Holder3.width, Holder3.height);
g.fillRect(Line3.x, Line3.y, Line3.width, Line3.height);
g.fillRect(Line4.x, Line4.y, Line4.width, Line4.height);
g.fillRect(Line5.x, Line5.y, Line5.width, Line5.height);
g.fillRect(Line6.x, Line6.y, Line6.width, Line6.height);
g.fillRect(line3.x, line3.y, line3.width, line3.height);
g.fillRect(line4.x, line4.y, line4.width, line4.height);
g.fillRect(line5.x, line5.y, line5.width, line5.height);
g.fillRect(line6.x, line6.y, line6.width, line6.height);
g.fillRect(line7.x, line7.y, line7.width, line7.height);
g.fillRect(Line7.x, Line7.y, Line7.width, Line7.height);
g.fillRect(Line8.x, Line8.y, Line8.width, Line8.height);
g.fillRect(line8.x, line8.y, line8.width, line8.height);
g.fillRect(Line9.x, Line9.y, Line9.width, Line9.height);
g.fillRect(line9.x, line9.y, line9.width, line9.height);
g.fillRect(Line10.x, Line10.y, Line10.width, Line10.height);
g.fillRect(line10.x, line10.y, line10.width, line10.height);
g.fillRect(Line11.x, Line11.y, Line11.width, Line11.height);
g.fillRect(line11.x, line11.y, line11.width, line11.height);
g.fillRect(Line12.x, Line12.y, Line12.width, Line12.height);
g.fillRect(line12.x, line12.y, line12.width, line12.height);
g.fillRect(Line13.x, Line13.y, Line13.width, Line13.height);
g.fillRect(line13.x, line13.y, line13.width, line13.height);
g.fillRect(Line14.x, Line14.y, Line14.width, Line14.height);
g.fillRect(line14.x, line14.y, line14.width, line14.height);
}
//Information If statement
if(KeysIns){
g.setColor(Color.BLACK);
g.setFont(g.getFont().deriveFont(25f));
g.drawString("Your goal", 123, 140);
g.drawString("is to get", 126, 200);
g.drawString("your character", 126, 250);
g.drawString("to the SafeZone", 126, 300);
g.drawString("Without touching the black line", 126, 350);
g.drawString("Careful that you can go to the left", 126, 400);
g.drawString("Through the walls but not right.", 126, 450);
g.drawString("Be careful not to touch the Bosses.", 126, 500);
g.setColor(Color.BLUE);
g.drawString("WASD / arrow", 251,550);
g.drawString("keys to move", 251, 580);
g.drawString("Shift in case of panic", 251, 615);
g.drawString("R to Reset", 251, 650);
g.drawString("Escape to Quit", 251, 670);
g.drawString("Space to Sprint", 251, 690);
//IF Statements
if(DeathScreen){
g.setColor(Color.BLACK);
g.setFont(g.getFont().deriveFont(25f));
g.drawString("Press R to restart", 496, 300);
isMoving = false;
}
}
if(Map1){
g.setColor(Color.BLUE);
g.setFont(g.getFont().deriveFont(25f));
g.drawString("Level: 1 ", 253, 25);
}
if(Map2){
g.setColor(Color.BLUE);
g.setFont(g.getFont().deriveFont(25f));
g.drawString("Level: 2 ", 253, 25);
}
if(Dead) {
g.setColor(Color.RED);
g.setFont(g.getFont().deriveFont(25f));
g.drawString("You Died", 496, 260);
g.drawString("Press R to restart", 496, 310);
isMoving = false;
}
if(Restart){
character.x = 52;
character.y = 52;
Dead = false;
DeathScreen = false;
Finished = false;
}
if(StopReset1) {
Reset = false;
}
if(FUp){
FDown = false;
FinalBoss.y -= 1;
}
if(FDown){
FUp = false;
FinalBoss.y += 1;
}
if(FRight){
FLeft = false;
FinalBoss.x += 1;
}
if(FLeft){
FRight = false;
FinalBoss.x -= 1;
}
if(FMoving){
if(FinalBoss.intersects(InvLine3)){
FLeft = false;
FRight = true;
}
if(FinalBoss.intersects(InvLine)){
FRight = false;
FLeft = true;
}
if(FinalBoss.intersects(Top)){
FUp = false;
FDown = true;
}
if(FinalBoss.intersects(Bottom)){
FDown = false;
FUp = true;
}
if(FinalBoss.intersects(Line)){
FRight = false;
FLeft = true;
}
if(FinalBoss.intersects(Line2)){
FRight = false;
FLeft = true;
}
if(FinalBoss.intersects(Line14)){
FLeft = false;
FRight = true;
}
if(FinalBoss.intersects(line14)){
FLeft = false;
FRight = true;
}
}
if(BUp){
BDown = false;
Boss.y -= 1;
}
if(BDown){
BUp = false;
Boss.y += 1;
}
if(BUp2){
BDown2 = false;
Boss2.y -= 1;
}
if(BDown2){
BUp2 = false;
Boss2.y += 1;
}
if(BUp3){
BDown3 = false;
Boss3.y -= 1;
}
if(BDown3){
BUp3 = false;
Boss3.y += 1;
}
if(BUp4){
BDown4 = false;
Boss4.y -= 1;
}
if(BDown4){
BUp4 = false;
Boss4.y += 1;
}
if(BUp5){
BDown5 = false;
Boss5.y -= 1;
}
if(BDown5){
BUp5 = false;
Boss5.y += 1;
}
if(BossMoving){
if(Boss.intersects(Top)){
BUp = false;
BDown = true;
}
if(Boss.intersects(Bottom)){
BDown = false;
BUp = true;
}
}
if(BossMoving2){
if(Boss2.intersects(Top)){
BUp2 = false;
BDown2 = true;
}
if(Boss2.intersects(Bottom)){
BDown2 = false;
BUp2 = true;
}
}
if(BossMoving3){
if(Boss3.intersects(Top)){
BUp3 = false;
BDown3 = true;
}
if(Boss3.intersects(Bottom)){
BDown3 = false;
BUp3 = true;
}
}
if(BossMoving4){
if(Boss4.intersects(Top)){
BUp4 = false;
BDown4 = true;
}
if(Boss4.intersects(Bottom)){
BDown4 = false;
BUp4 = true;
}
}
if(BossMoving5){
if(Boss5.intersects(Top)){
BUp5 = false;
BDown5 = true;
}
if(Boss3.intersects(Bottom)){
BDown5 = false;
BUp5 = true;
}
}
//If Statements for walls
if(character.intersects(FinalBoss)) {
Dead = true;
isMoving = false;
DeathScreen = true;
character.x = 40000;
}
if(character.intersects(Boss)) {
Dead = true;
isMoving = false;
DeathScreen = true;
character.x = 40000;
}
if(character.intersects(Boss2)) {
Dead = true;
isMoving = false;
DeathScreen = true;
character.x = 40000;
}
if(character.intersects(Boss3)) {
Dead = true;
isMoving = false;
DeathScreen = true;
character.x = 40000;
}
if(character.intersects(Boss4)) {
Dead = true;
isMoving = false;
DeathScreen = true;
character.x = 40000;
}
if(character.intersects(Boss5)) {
Dead = true;
isMoving = false;
DeathScreen = true;
character.x = 40000;
}
if(character.intersects(Right)) {
character.x -= 10;
StopReset1 = true;
}
if(character.intersects(Left)) {
character.x += 10;
StopReset1 = true;
}
if(character.intersects(Bottom)) {
character.y -= 10;
StopReset1 = true;
}
if(Map1){
if(character.intersects(Holder1)) {
character.y += 10;
StopReset1 = true;
SpeedBoost = true;
}
if(character.intersects(Holder2)) {
character.y += 10;
StopReset1 = true;
}
if(character.intersects(Holder3)) {
character.y -= 10;
StopReset1 = true;
}
if(character.intersects(Top)) {
character.y += 10;
StopReset1 = true;
}
if(character.intersects(Line)) {
Dead = true;
isMoving = false;
DeathScreen = true;
character.x = 40000;
}
if(character.intersects(Line2)) {
Dead = true;
isMoving = false;
DeathScreen = true;
character.x = 40000;
}
if(character.intersects(Line3)) {
Reset = true;
StopReset1 = true;
}
if(character.intersects(Line4)) {
Reset = true;
StopReset1 = true;
}
if(character.intersects(Line5)) {
Reset = true;
StopReset1 = true;
}
if(character.intersects(Line6)) {
Reset = true;
StopReset1 = true;
}
if(character.intersects(line3)) {
Reset = true;
StopReset1 = true;
}
if(character.intersects(line4)) {
Reset = true;
StopReset1 = true;
}
if(character.intersects(line5)) {
Reset = true;
StopReset1 = true;
}
if(character.intersects(line6)) {
Reset = true;
StopReset1 = true;
}
if(character.intersects(line7)) {
Reset = true;
StopReset1 = true;
}
if(character.intersects(Line7)) {
Reset = true;
StopReset1 = true;
}
if(character.intersects(line8)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line8)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line9)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line9)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line10)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line10)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line11)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line11)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line12)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line12)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line13)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line13)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line14)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line14)) {
Reset = true;
StopReset1 = true;}
}
if(Map2){
if(character.intersects(Line15)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line16)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line17)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line18)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line19)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line20)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line21)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line22)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line23)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line24)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line25)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(Line26)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line15)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line16)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line17)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line18)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line19)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line20)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line21)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line22)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line23)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line24)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line25)) {
Reset = true;
StopReset1 = true;}
if(character.intersects(line26)) {
Reset = true;
StopReset1 = true;}
}
//If Statements for Invisible lines
if(character.intersects(InvLine)) {
g.setColor(Color.BLUE);
g.setFont(g.getFont().deriveFont(25f));
}
if(character.intersects(InvLine2)) {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
Finished = true;
}
if(Finished){
character.x = 52;
character.y = 52;
g.setColor(Color.BLACK);
g.setFont(g.getFont().deriveFont(35f));
g.drawString("Thank you for Playing!", 440, 260);
g.drawString("You Passed!", 500, 300);
g.setColor(Color.BLUE);
g.setFont(g.getFont().deriveFont(30));
g.drawString("Close to Restart", 500, 500);
Map1 = false;
Map2 = true;
if(character.intersects(InvLine)){
if(Map2){
Map1 = Map2;
Map2 = Map3;
Map3 = true;
Map2 = false;
}
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Finished = false;
}
if(character.intersects(StartingPoint)) {
Restart = false;
g.setColor(Color.BLACK);
g.setFont(g.getFont().deriveFont(25f));
g.drawString("Press K", 258, 100);
g.drawString("for Instructions", 260, 145);
g.setColor(Color.BLUE);
g.drawString("WASD / arrow", 251,550);
g.drawString("keys to move", 251, 580);
}
if(maxHealth <= 0){
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
lost = true;
}
if(lost){
character.x = 52;
character.y = 52;
g.setColor(Color.BLACK);
g.setFont(g.getFont().deriveFont(35f));
g.drawString("You Lost!", 440, 260);
g.setColor(Color.BLUE);
g.setFont(g.getFont().deriveFont(30));
g.drawString("Close to Restart", 500, 500);
}
//If Statements for character movement
if(jumping){
character.y --;
}
if(right){
character.x += verticalSpeed;
}
if(left){
character.x -= verticalSpeed;
}
if(up)
character.y += -verticalSpeed;
if(down){
character.y += verticalSpeed;
}
repaint();
}
|
diff --git a/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/FeedServlet.java b/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/FeedServlet.java
index dc22d6211..c8e0b6c95 100644
--- a/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/FeedServlet.java
+++ b/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/FeedServlet.java
@@ -1,672 +1,672 @@
/*
* FeedServlet.java
*
* Version: $Revision$
*
* Date: $Date$
*
* Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts
* Institute of Technology. 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 Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* 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
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.app.webui.servlet;
import java.io.IOException;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.StringTokenizer;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.dspace.app.webui.util.JSPManager;
import org.dspace.authorize.AuthorizeException;
import org.dspace.browse.BrowseEngine;
import org.dspace.browse.BrowseException;
import org.dspace.browse.BrowseIndex;
import org.dspace.browse.BrowseInfo;
import org.dspace.browse.BrowserScope;
import org.dspace.sort.SortOption;
import org.dspace.sort.SortException;
import org.dspace.content.Bitstream;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.content.DCDate;
import org.dspace.content.DCValue;
import org.dspace.content.DSpaceObject;
import org.dspace.content.Item;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.dspace.core.LogManager;
import org.dspace.handle.HandleManager;
import org.dspace.search.Harvest;
import com.sun.syndication.feed.rss.Channel;
import com.sun.syndication.feed.rss.Description;
import com.sun.syndication.feed.rss.Image;
import com.sun.syndication.feed.rss.TextInput;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.WireFeedOutput;
/**
* Servlet for handling requests for a syndication feed. The Handle of the collection
* or community is extracted from the URL, e.g: <code>/feed/rss_1.0/1234/5678</code>.
* Currently supports only RSS feed formats.
*
* @author Ben Bosman, Richard Rodgers
* @version $Revision$
*/
public class FeedServlet extends DSpaceServlet
{
// key for site-wide feed
public static final String SITE_FEED_KEY = "site";
// one hour in milliseconds
private static final long HOUR_MSECS = 60 * 60 * 1000;
/** log4j category */
private static Logger log = Logger.getLogger(FeedServlet.class);
private String clazz = "org.dspace.app.webui.servlet.FeedServlet";
// are syndication feeds enabled?
private static boolean enabled = false;
// number of DSpace items per feed
private static int itemCount = 0;
// optional cache of feeds
private static Map feedCache = null;
// maximum size of cache - 0 means caching disabled
private static int cacheSize = 0;
// how many days to keep a feed in cache before checking currency
private static int cacheAge = 0;
// supported syndication formats
private static List formats = null;
// localized resource bundle
private static ResourceBundle labels = null;
//default fields to display in item description
private static String defaultDescriptionFields = "dc.title, dc.contributor.author, dc.contributor.editor, dc.description.abstract, dc.description";
static
{
enabled = ConfigurationManager.getBooleanProperty("webui.feed.enable");
}
public void init()
{
// read rest of config info if enabled
if (enabled)
{
String fmtsStr = ConfigurationManager.getProperty("webui.feed.formats");
if ( fmtsStr != null )
{
formats = new ArrayList();
String[] fmts = fmtsStr.split(",");
for (int i = 0; i < fmts.length; i++)
{
formats.add(fmts[i]);
}
}
itemCount = ConfigurationManager.getIntProperty("webui.feed.items");
cacheSize = ConfigurationManager.getIntProperty("webui.feed.cache.size");
if (cacheSize > 0)
{
feedCache = new HashMap();
cacheAge = ConfigurationManager.getIntProperty("webui.feed.cache.age");
}
}
}
protected void doDSGet(Context context, HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException,
SQLException, AuthorizeException
{
String path = request.getPathInfo();
String feedType = null;
String handle = null;
if(labels==null)
{
// Get access to the localized resource bundle
Locale locale = request.getLocale();
labels = ResourceBundle.getBundle("Messages", locale);
}
if (path != null)
{
// substring(1) is to remove initial '/'
path = path.substring(1);
int split = path.indexOf("/");
if (split != -1)
{
feedType = path.substring(0,split);
handle = path.substring(split+1);
}
}
DSpaceObject dso = null;
//as long as this is not a site wide feed,
//attempt to retrieve the Collection or Community object
if(!handle.equals(SITE_FEED_KEY))
{
// Determine if handle is a valid reference
dso = HandleManager.resolveToObject(context, handle);
}
if (! enabled || (dso != null &&
(dso.getType() != Constants.COLLECTION && dso.getType() != Constants.COMMUNITY)) )
{
log.info(LogManager.getHeader(context, "invalid_id", "path=" + path));
JSPManager.showInvalidIDError(request, response, path, -1);
return;
}
// Determine if requested format is supported
if( feedType == null || ! formats.contains( feedType ) )
{
log.info(LogManager.getHeader(context, "invalid_syndformat", "path=" + path));
JSPManager.showInvalidIDError(request, response, path, -1);
return;
}
// Lookup or generate the feed
Channel channel = null;
if (feedCache != null)
{
// Cache key is handle
CacheFeed cFeed = (CacheFeed)feedCache.get(handle);
if (cFeed != null) // cache hit, but...
{
// Is the feed current?
boolean cacheFeedCurrent = false;
if (cFeed.timeStamp + (cacheAge * HOUR_MSECS) < System.currentTimeMillis())
{
cacheFeedCurrent = true;
}
// Not current, but have any items changed since feed was created/last checked?
else if ( ! itemsChanged(context, dso, cFeed.timeStamp))
{
// no items have changed, re-stamp feed and use it
cFeed.timeStamp = System.currentTimeMillis();
cacheFeedCurrent = true;
}
if (cacheFeedCurrent)
{
channel = cFeed.access();
}
}
}
// either not caching, not found in cache, or feed in cache not current
if (channel == null)
{
channel = generateFeed(context, dso);
if (feedCache != null)
{
cache(handle, new CacheFeed(channel));
}
}
// set the feed to the requested type & return it
channel.setFeedType(feedType);
WireFeedOutput feedWriter = new WireFeedOutput();
try
{
response.setContentType("text/xml; charset=UTF-8");
feedWriter.output(channel, response.getWriter());
}
catch( FeedException fex )
{
throw new IOException(fex.getMessage());
}
}
private boolean itemsChanged(Context context, DSpaceObject dso, long timeStamp)
throws SQLException
{
// construct start and end dates
DCDate dcStartDate = new DCDate( new Date(timeStamp) );
DCDate dcEndDate = new DCDate( new Date(System.currentTimeMillis()) );
// convert dates to ISO 8601, stripping the time
String startDate = dcStartDate.toString().substring(0, 10);
String endDate = dcEndDate.toString().substring(0, 10);
// this invocation should return a non-empty list if even 1 item has changed
try {
return (Harvest.harvest(context, dso, startDate, endDate,
0, 1, false, false, false).size() > 0);
}
catch (ParseException pe)
{
// This should never get thrown as we have generated the dates ourselves
return false;
}
}
/**
* Generate a syndication feed for a collection or community
* or community
*
* @param context the DSpace context object
*
* @param dso DSpace object - collection or community
*
* @return an object representing the feed
*/
private Channel generateFeed(Context context, DSpaceObject dso)
throws IOException, SQLException
{
try
{
// container-level elements
String dspaceUrl = ConfigurationManager.getProperty("dspace.url");
String type = null;
String description = null;
String title = null;
Bitstream logo = null;
// browse scope
// BrowseScope scope = new BrowseScope(context);
// new method of doing the browse:
String idx = ConfigurationManager.getProperty("recent.submissions.sort-option");
if (idx == null)
{
throw new IOException("There is no configuration supplied for: recent.submissions.sort-option");
}
BrowseIndex bix = BrowseIndex.getItemBrowseIndex();
if (bix == null)
{
throw new IOException("There is no browse index with the name: " + idx);
}
BrowserScope scope = new BrowserScope(context);
scope.setBrowseIndex(bix);
for (SortOption so : SortOption.getSortOptions())
{
if (so.getName().equals(idx))
scope.setSortBy(so.getNumber());
}
scope.setOrder(SortOption.DESCENDING);
// the feed
Channel channel = new Channel();
//Special Case: if DSpace Object passed in is null,
//generate a feed for the entire DSpace site!
if(dso == null)
{
channel.setTitle(ConfigurationManager.getProperty("dspace.name"));
channel.setLink(dspaceUrl);
channel.setDescription(labels.getString(clazz + ".general-feed.description"));
}
else //otherwise, this is a Collection or Community specific feed
{
if (dso.getType() == Constants.COLLECTION)
{
type = labels.getString(clazz + ".feed-type.collection");
Collection col = (Collection)dso;
description = col.getMetadata("short_description");
title = col.getMetadata("name");
logo = col.getLogo();
// scope.setScope(col);
scope.setBrowseContainer(col);
}
else if (dso.getType() == Constants.COMMUNITY)
{
type = labels.getString(clazz + ".feed-type.community");
Community comm = (Community)dso;
description = comm.getMetadata("short_description");
title = comm.getMetadata("name");
logo = comm.getLogo();
// scope.setScope(comm);
scope.setBrowseContainer(comm);
}
String objectUrl = ConfigurationManager.getBooleanProperty("webui.feed.localresolve")
? HandleManager.resolveToURL(context, dso.getHandle())
: HandleManager.getCanonicalForm(dso.getHandle());
// put in container-level data
channel.setDescription(description);
channel.setLink(objectUrl);
//build channel title by passing in type and title
String channelTitle = MessageFormat.format(labels.getString(clazz + ".feed.title"),
new Object[]{type, title});
channel.setTitle(channelTitle);
//if collection or community has a logo
if (logo != null)
{
// we use the path to the logo for this, the logo itself cannot
// be contained in the rdf. Not all RSS-viewers show this logo.
Image image = new Image();
image.setLink(objectUrl);
image.setTitle(labels.getString(clazz + ".logo.title"));
image.setUrl(dspaceUrl + "/retrieve/" + logo.getID());
channel.setImage(image);
}
}
// this is a direct link to the search-engine of dspace. It searches
// in the current collection. Since the current version of DSpace
// can't search within collections anymore, this works only in older
// version until this bug is fixed.
TextInput input = new TextInput();
input.setLink(dspaceUrl + "/simple-search");
input.setDescription( labels.getString(clazz + ".search.description") );
String searchTitle = "";
//if a "type" of feed was specified, build search title off that
if(type!=null)
{
searchTitle = MessageFormat.format(labels.getString(clazz + ".search.title"),
new Object[]{type});
}
else //otherwise, default to a more generic search title
{
searchTitle = labels.getString(clazz + ".search.title.default");
}
input.setTitle(searchTitle);
input.setName(labels.getString(clazz + ".search.name"));
channel.setTextInput(input);
// gather & add items to the feed.
scope.setResultsPerPage(itemCount);
BrowseEngine be = new BrowseEngine(context);
BrowseInfo bi = be.browseMini(scope);
Item[] results = bi.getItemResults(context);
List items = new ArrayList();
for (int i = 0; i < results.length; i++)
{
items.add(itemFromDSpaceItem(context, results[i]));
}
channel.setItems(items);
// If the description is null, replace it with an empty string
// to avoid a FeedException
if (channel.getDescription() == null)
channel.setDescription("");
return channel;
}
catch (SortException se)
{
log.error("caught exception: ", se);
- throw new IOException(se);
+ throw new IOException(se.getMessage());
}
catch (BrowseException e)
{
log.error("caught exception: ", e);
throw new IOException(e.getMessage());
}
}
/**
* The metadata fields of the given item will be added to the given feed.
*
* @param context DSpace context object
*
* @param dspaceItem DSpace Item
*
* @return an object representing a feed entry
*/
private com.sun.syndication.feed.rss.Item itemFromDSpaceItem(Context context,
Item dspaceItem)
throws SQLException
{
com.sun.syndication.feed.rss.Item rssItem =
new com.sun.syndication.feed.rss.Item();
//get the title and date fields
String titleField = ConfigurationManager.getProperty("webui.feed.item.title");
if (titleField == null)
{
titleField = "dc.title";
}
String dateField = ConfigurationManager.getProperty("webui.feed.item.date");
if (dateField == null)
{
dateField = "dc.date.issued";
}
//Set item handle
String itHandle = ConfigurationManager.getBooleanProperty("webui.feed.localresolve")
? HandleManager.resolveToURL(context, dspaceItem.getHandle())
: HandleManager.getCanonicalForm(dspaceItem.getHandle());
rssItem.setLink(itHandle);
//get first title
String title = null;
try
{
title = dspaceItem.getMetadata(titleField)[0].value;
}
catch (ArrayIndexOutOfBoundsException e)
{
title = labels.getString(clazz + ".notitle");
}
rssItem.setTitle(title);
// We put some metadata in the description field. This field is
// displayed by most RSS viewers
String descriptionFields = ConfigurationManager
.getProperty("webui.feed.item.description");
if (descriptionFields == null)
{
descriptionFields = defaultDescriptionFields;
}
//loop through all the metadata fields to put in the description
StringBuffer descBuf = new StringBuffer();
StringTokenizer st = new StringTokenizer(descriptionFields, ",");
while (st.hasMoreTokens())
{
String field = st.nextToken().trim();
boolean isDate = false;
// Find out if the field should rendered as a date
if (field.indexOf("(date)") > 0)
{
field = field.replaceAll("\\(date\\)", "");
isDate = true;
}
//print out this field, along with its value(s)
DCValue[] values = dspaceItem.getMetadata(field);
if(values != null && values.length>0)
{
//as long as there is already something in the description
//buffer, print out a few line breaks before the next field
if(descBuf.length() > 0)
{
descBuf.append("\n<br/>");
descBuf.append("\n<br/>");
}
String fieldLabel = null;
try
{
fieldLabel = labels.getString("metadata." + field);
}
catch(java.util.MissingResourceException e) {}
if(fieldLabel !=null && fieldLabel.length()>0)
descBuf.append(fieldLabel + ": ");
for(int i=0; i<values.length; i++)
{
String fieldValue = values[i].value;
if(isDate)
fieldValue = (new DCDate(fieldValue)).toString();
descBuf.append(fieldValue);
if (i < values.length - 1)
{
descBuf.append("; ");
}
}
}
}//end while
Description descrip = new Description();
descrip.setValue(descBuf.toString());
rssItem.setDescription(descrip);
// set date field
String dcDate = null;
try
{
dcDate = dspaceItem.getMetadata(dateField)[0].value;
}
catch (ArrayIndexOutOfBoundsException e)
{
}
if (dcDate != null)
{
rssItem.setPubDate((new DCDate(dcDate)).toDate());
}
return rssItem;
}
/************************************************
* private cache management classes and methods *
************************************************/
/**
* Add a feed to the cache - reducing the size of the cache by 1 to make room if
* necessary. The removed entry has an access count equal to the minumum in the cache.
* @param feedKey
* The cache key for the feed
* @param newFeed
* The CacheFeed feed to be cached
*/
private static void cache(String feedKey, CacheFeed newFeed)
{
// remove older feed to make room if cache full
if (feedCache.size() >= cacheSize)
{
// cache profiling data
int total = 0;
String minKey = null;
CacheFeed minFeed = null;
CacheFeed maxFeed = null;
Iterator iter = feedCache.keySet().iterator();
while (iter.hasNext())
{
String key = (String)iter.next();
CacheFeed feed = (CacheFeed)feedCache.get(key);
if (minKey != null)
{
if (feed.hits < minFeed.hits)
{
minKey = key;
minFeed = feed;
}
if (feed.hits >= maxFeed.hits)
{
maxFeed = feed;
}
}
else
{
minKey = key;
minFeed = maxFeed = feed;
}
total += feed.hits;
}
// log a profile of the cache to assist administrator in tuning it
int avg = total / feedCache.size();
String logMsg = "feedCache() - size: " + feedCache.size() +
" Hits - total: " + total + " avg: " + avg +
" max: " + maxFeed.hits + " min: " + minFeed.hits;
log.info(logMsg);
// remove minimum hits entry
feedCache.remove(minKey);
}
// add feed to cache
feedCache.put(feedKey, newFeed);
}
/**
* Class to instrument accesses & currency of a given feed in cache
*/
private class CacheFeed
{
// currency timestamp
public long timeStamp = 0L;
// access count
public int hits = 0;
// the feed
private Channel feed = null;
public CacheFeed(Channel feed)
{
this.feed = feed;
timeStamp = System.currentTimeMillis();
}
public Channel access()
{
++hits;
return feed;
}
}
}
| true | true | private Channel generateFeed(Context context, DSpaceObject dso)
throws IOException, SQLException
{
try
{
// container-level elements
String dspaceUrl = ConfigurationManager.getProperty("dspace.url");
String type = null;
String description = null;
String title = null;
Bitstream logo = null;
// browse scope
// BrowseScope scope = new BrowseScope(context);
// new method of doing the browse:
String idx = ConfigurationManager.getProperty("recent.submissions.sort-option");
if (idx == null)
{
throw new IOException("There is no configuration supplied for: recent.submissions.sort-option");
}
BrowseIndex bix = BrowseIndex.getItemBrowseIndex();
if (bix == null)
{
throw new IOException("There is no browse index with the name: " + idx);
}
BrowserScope scope = new BrowserScope(context);
scope.setBrowseIndex(bix);
for (SortOption so : SortOption.getSortOptions())
{
if (so.getName().equals(idx))
scope.setSortBy(so.getNumber());
}
scope.setOrder(SortOption.DESCENDING);
// the feed
Channel channel = new Channel();
//Special Case: if DSpace Object passed in is null,
//generate a feed for the entire DSpace site!
if(dso == null)
{
channel.setTitle(ConfigurationManager.getProperty("dspace.name"));
channel.setLink(dspaceUrl);
channel.setDescription(labels.getString(clazz + ".general-feed.description"));
}
else //otherwise, this is a Collection or Community specific feed
{
if (dso.getType() == Constants.COLLECTION)
{
type = labels.getString(clazz + ".feed-type.collection");
Collection col = (Collection)dso;
description = col.getMetadata("short_description");
title = col.getMetadata("name");
logo = col.getLogo();
// scope.setScope(col);
scope.setBrowseContainer(col);
}
else if (dso.getType() == Constants.COMMUNITY)
{
type = labels.getString(clazz + ".feed-type.community");
Community comm = (Community)dso;
description = comm.getMetadata("short_description");
title = comm.getMetadata("name");
logo = comm.getLogo();
// scope.setScope(comm);
scope.setBrowseContainer(comm);
}
String objectUrl = ConfigurationManager.getBooleanProperty("webui.feed.localresolve")
? HandleManager.resolveToURL(context, dso.getHandle())
: HandleManager.getCanonicalForm(dso.getHandle());
// put in container-level data
channel.setDescription(description);
channel.setLink(objectUrl);
//build channel title by passing in type and title
String channelTitle = MessageFormat.format(labels.getString(clazz + ".feed.title"),
new Object[]{type, title});
channel.setTitle(channelTitle);
//if collection or community has a logo
if (logo != null)
{
// we use the path to the logo for this, the logo itself cannot
// be contained in the rdf. Not all RSS-viewers show this logo.
Image image = new Image();
image.setLink(objectUrl);
image.setTitle(labels.getString(clazz + ".logo.title"));
image.setUrl(dspaceUrl + "/retrieve/" + logo.getID());
channel.setImage(image);
}
}
// this is a direct link to the search-engine of dspace. It searches
// in the current collection. Since the current version of DSpace
// can't search within collections anymore, this works only in older
// version until this bug is fixed.
TextInput input = new TextInput();
input.setLink(dspaceUrl + "/simple-search");
input.setDescription( labels.getString(clazz + ".search.description") );
String searchTitle = "";
//if a "type" of feed was specified, build search title off that
if(type!=null)
{
searchTitle = MessageFormat.format(labels.getString(clazz + ".search.title"),
new Object[]{type});
}
else //otherwise, default to a more generic search title
{
searchTitle = labels.getString(clazz + ".search.title.default");
}
input.setTitle(searchTitle);
input.setName(labels.getString(clazz + ".search.name"));
channel.setTextInput(input);
// gather & add items to the feed.
scope.setResultsPerPage(itemCount);
BrowseEngine be = new BrowseEngine(context);
BrowseInfo bi = be.browseMini(scope);
Item[] results = bi.getItemResults(context);
List items = new ArrayList();
for (int i = 0; i < results.length; i++)
{
items.add(itemFromDSpaceItem(context, results[i]));
}
channel.setItems(items);
// If the description is null, replace it with an empty string
// to avoid a FeedException
if (channel.getDescription() == null)
channel.setDescription("");
return channel;
}
catch (SortException se)
{
log.error("caught exception: ", se);
throw new IOException(se);
}
catch (BrowseException e)
{
log.error("caught exception: ", e);
throw new IOException(e.getMessage());
}
}
| private Channel generateFeed(Context context, DSpaceObject dso)
throws IOException, SQLException
{
try
{
// container-level elements
String dspaceUrl = ConfigurationManager.getProperty("dspace.url");
String type = null;
String description = null;
String title = null;
Bitstream logo = null;
// browse scope
// BrowseScope scope = new BrowseScope(context);
// new method of doing the browse:
String idx = ConfigurationManager.getProperty("recent.submissions.sort-option");
if (idx == null)
{
throw new IOException("There is no configuration supplied for: recent.submissions.sort-option");
}
BrowseIndex bix = BrowseIndex.getItemBrowseIndex();
if (bix == null)
{
throw new IOException("There is no browse index with the name: " + idx);
}
BrowserScope scope = new BrowserScope(context);
scope.setBrowseIndex(bix);
for (SortOption so : SortOption.getSortOptions())
{
if (so.getName().equals(idx))
scope.setSortBy(so.getNumber());
}
scope.setOrder(SortOption.DESCENDING);
// the feed
Channel channel = new Channel();
//Special Case: if DSpace Object passed in is null,
//generate a feed for the entire DSpace site!
if(dso == null)
{
channel.setTitle(ConfigurationManager.getProperty("dspace.name"));
channel.setLink(dspaceUrl);
channel.setDescription(labels.getString(clazz + ".general-feed.description"));
}
else //otherwise, this is a Collection or Community specific feed
{
if (dso.getType() == Constants.COLLECTION)
{
type = labels.getString(clazz + ".feed-type.collection");
Collection col = (Collection)dso;
description = col.getMetadata("short_description");
title = col.getMetadata("name");
logo = col.getLogo();
// scope.setScope(col);
scope.setBrowseContainer(col);
}
else if (dso.getType() == Constants.COMMUNITY)
{
type = labels.getString(clazz + ".feed-type.community");
Community comm = (Community)dso;
description = comm.getMetadata("short_description");
title = comm.getMetadata("name");
logo = comm.getLogo();
// scope.setScope(comm);
scope.setBrowseContainer(comm);
}
String objectUrl = ConfigurationManager.getBooleanProperty("webui.feed.localresolve")
? HandleManager.resolveToURL(context, dso.getHandle())
: HandleManager.getCanonicalForm(dso.getHandle());
// put in container-level data
channel.setDescription(description);
channel.setLink(objectUrl);
//build channel title by passing in type and title
String channelTitle = MessageFormat.format(labels.getString(clazz + ".feed.title"),
new Object[]{type, title});
channel.setTitle(channelTitle);
//if collection or community has a logo
if (logo != null)
{
// we use the path to the logo for this, the logo itself cannot
// be contained in the rdf. Not all RSS-viewers show this logo.
Image image = new Image();
image.setLink(objectUrl);
image.setTitle(labels.getString(clazz + ".logo.title"));
image.setUrl(dspaceUrl + "/retrieve/" + logo.getID());
channel.setImage(image);
}
}
// this is a direct link to the search-engine of dspace. It searches
// in the current collection. Since the current version of DSpace
// can't search within collections anymore, this works only in older
// version until this bug is fixed.
TextInput input = new TextInput();
input.setLink(dspaceUrl + "/simple-search");
input.setDescription( labels.getString(clazz + ".search.description") );
String searchTitle = "";
//if a "type" of feed was specified, build search title off that
if(type!=null)
{
searchTitle = MessageFormat.format(labels.getString(clazz + ".search.title"),
new Object[]{type});
}
else //otherwise, default to a more generic search title
{
searchTitle = labels.getString(clazz + ".search.title.default");
}
input.setTitle(searchTitle);
input.setName(labels.getString(clazz + ".search.name"));
channel.setTextInput(input);
// gather & add items to the feed.
scope.setResultsPerPage(itemCount);
BrowseEngine be = new BrowseEngine(context);
BrowseInfo bi = be.browseMini(scope);
Item[] results = bi.getItemResults(context);
List items = new ArrayList();
for (int i = 0; i < results.length; i++)
{
items.add(itemFromDSpaceItem(context, results[i]));
}
channel.setItems(items);
// If the description is null, replace it with an empty string
// to avoid a FeedException
if (channel.getDescription() == null)
channel.setDescription("");
return channel;
}
catch (SortException se)
{
log.error("caught exception: ", se);
throw new IOException(se.getMessage());
}
catch (BrowseException e)
{
log.error("caught exception: ", e);
throw new IOException(e.getMessage());
}
}
|
diff --git a/src/org/pentaho/agilebi/platform/JettyServer.java b/src/org/pentaho/agilebi/platform/JettyServer.java
index a99afb8..35f589c 100755
--- a/src/org/pentaho/agilebi/platform/JettyServer.java
+++ b/src/org/pentaho/agilebi/platform/JettyServer.java
@@ -1,93 +1,93 @@
package org.pentaho.agilebi.platform;
import org.mortbay.jetty.Connector;
import org.mortbay.jetty.Handler;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.bio.SocketConnector;
import org.mortbay.jetty.handler.DefaultHandler;
import org.mortbay.jetty.handler.HandlerCollection;
import org.mortbay.jetty.webapp.WebAppContext;
import org.pentaho.di.core.logging.LogWriter;
public class JettyServer {
private static Class<?> PKG = JettyServer.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$
private static LogWriter log = LogWriter.getInstance();
public static final int PORT = 80;
private Server server;
private String hostname;
private int port;
public JettyServer(String hostname, int port) throws Exception {
this.hostname = hostname;
this.port = port;
}
public Server getServer() {
return server;
}
public void startServer() throws Exception {
server = new Server();
WebAppContext pentahoContext = new WebAppContext();
pentahoContext.setContextPath("/pentaho"); //$NON-NLS-1$
- pentahoContext.setWar("agile-bi/platform/webapps/pentaho"); //$NON-NLS-1$
+ pentahoContext.setWar("plugins/spoon/agile-bi/platform/webapps/pentaho"); //$NON-NLS-1$
pentahoContext.setParentLoaderPriority(true);
HandlerCollection handlers= new HandlerCollection();
handlers.setHandlers(new Handler[]{pentahoContext, new DefaultHandler()});
server.setHandler(handlers);
// Start execution
createListeners();
server.start();
}
protected void setupListeners() {
}
public void stopServer() {
try {
if (server != null) {
server.stop();
}
} catch (Exception e) {
log.logError(toString(), "WebServer.Error.FailedToStop.Title");
}
}
private void createListeners() {
SocketConnector connector = new SocketConnector();
connector.setPort(port);
connector.setHost(hostname);
connector.setName(hostname);
log.logBasic(toString(), "WebServer.Log.CreateListener" + hostname + ":" + port);
server.setConnectors(new Connector[] { connector });
}
/**
* @return the hostname
*/
public String getHostname() {
return hostname;
}
/**
* @param hostname the hostname to set
*/
public void setHostname(String hostname) {
this.hostname = hostname;
}
}
| true | true | public void startServer() throws Exception {
server = new Server();
WebAppContext pentahoContext = new WebAppContext();
pentahoContext.setContextPath("/pentaho"); //$NON-NLS-1$
pentahoContext.setWar("agile-bi/platform/webapps/pentaho"); //$NON-NLS-1$
pentahoContext.setParentLoaderPriority(true);
HandlerCollection handlers= new HandlerCollection();
handlers.setHandlers(new Handler[]{pentahoContext, new DefaultHandler()});
server.setHandler(handlers);
// Start execution
createListeners();
server.start();
}
| public void startServer() throws Exception {
server = new Server();
WebAppContext pentahoContext = new WebAppContext();
pentahoContext.setContextPath("/pentaho"); //$NON-NLS-1$
pentahoContext.setWar("plugins/spoon/agile-bi/platform/webapps/pentaho"); //$NON-NLS-1$
pentahoContext.setParentLoaderPriority(true);
HandlerCollection handlers= new HandlerCollection();
handlers.setHandlers(new Handler[]{pentahoContext, new DefaultHandler()});
server.setHandler(handlers);
// Start execution
createListeners();
server.start();
}
|
diff --git a/org.eclipse.bpmn2.modeler.runtime.jboss.jbpm5/src/org/eclipse/bpmn2/modeler/runtime/jboss/jbpm5/property/JbpmDataItemsPropertiesComposite.java b/org.eclipse.bpmn2.modeler.runtime.jboss.jbpm5/src/org/eclipse/bpmn2/modeler/runtime/jboss/jbpm5/property/JbpmDataItemsPropertiesComposite.java
index ba6a2df2..583d308a 100644
--- a/org.eclipse.bpmn2.modeler.runtime.jboss.jbpm5/src/org/eclipse/bpmn2/modeler/runtime/jboss/jbpm5/property/JbpmDataItemsPropertiesComposite.java
+++ b/org.eclipse.bpmn2.modeler.runtime.jboss.jbpm5/src/org/eclipse/bpmn2/modeler/runtime/jboss/jbpm5/property/JbpmDataItemsPropertiesComposite.java
@@ -1,96 +1,96 @@
/*******************************************************************************
* Copyright (c) 2011 Red Hat, Inc.
* All rights reserved.
* This program is 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:
* Red Hat, Inc. - initial API and implementation
*
* @author Bob Brodt
******************************************************************************/
package org.eclipse.bpmn2.modeler.runtime.jboss.jbpm5.property;
import org.eclipse.bpmn2.Definitions;
import org.eclipse.bpmn2.Process;
import org.eclipse.bpmn2.RootElement;
import org.eclipse.bpmn2.modeler.runtime.jboss.jbpm5.model.GlobalType;
import org.eclipse.bpmn2.modeler.runtime.jboss.jbpm5.model.ModelFactory;
import org.eclipse.bpmn2.modeler.runtime.jboss.jbpm5.model.ModelPackage;
import org.eclipse.bpmn2.modeler.ui.property.AbstractBpmn2PropertySection;
import org.eclipse.bpmn2.modeler.ui.property.AbstractBpmn2TableComposite;
import org.eclipse.bpmn2.modeler.ui.property.ExtensionValueTableComposite;
import org.eclipse.bpmn2.modeler.ui.property.diagrams.DataItemsPropertiesComposite;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.jface.dialogs.IInputValidator;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Composite;
/**
* @author Bob Brodt
*
*/
public class JbpmDataItemsPropertiesComposite extends DataItemsPropertiesComposite {
/**
* @param section
*/
public JbpmDataItemsPropertiesComposite(AbstractBpmn2PropertySection section) {
super(section);
}
public JbpmDataItemsPropertiesComposite(Composite parent, int style) {
super(parent, style);
}
@Override
public void createBindings(EObject be) {
if (be instanceof Definitions) {
Definitions definitions = (Definitions)be;
for (RootElement re : definitions.getRootElements()) {
if (re instanceof Process) {
Process process = (Process)re;
ExtensionValueTableComposite globalsTable = new ExtensionValueTableComposite(
this, AbstractBpmn2TableComposite.DEFAULT_STYLE)
{
@Override
protected EObject addListItem(EObject object, EStructuralFeature feature) {
InputDialog dialog = new InputDialog(getShell(), "Add Global",
"Enter new global variable name","", new IInputValidator() {
@Override
public String isValid(String newText) {
if (newText==null || newText.isEmpty() || newText.contains(" "))
return "Please enter a valid name";
return null;
}
});
if (dialog.open()!=Window.OK){
return null;
}
String name = dialog.getValue();
GlobalType newGlobal = (GlobalType)ModelFactory.eINSTANCE.create(listItemClass);
newGlobal.setIdentifier(name);
addExtensionValue(newGlobal);
return newGlobal;
}
};
globalsTable.bindList(process, ModelPackage.eINSTANCE.getDocumentRoot_Global());
globalsTable.setTitle("Globals");
- bindList(process, "properties");
+// bindList(process, "properties");
}
}
}
super.createBindings(be);
}
}
| true | true | public void createBindings(EObject be) {
if (be instanceof Definitions) {
Definitions definitions = (Definitions)be;
for (RootElement re : definitions.getRootElements()) {
if (re instanceof Process) {
Process process = (Process)re;
ExtensionValueTableComposite globalsTable = new ExtensionValueTableComposite(
this, AbstractBpmn2TableComposite.DEFAULT_STYLE)
{
@Override
protected EObject addListItem(EObject object, EStructuralFeature feature) {
InputDialog dialog = new InputDialog(getShell(), "Add Global",
"Enter new global variable name","", new IInputValidator() {
@Override
public String isValid(String newText) {
if (newText==null || newText.isEmpty() || newText.contains(" "))
return "Please enter a valid name";
return null;
}
});
if (dialog.open()!=Window.OK){
return null;
}
String name = dialog.getValue();
GlobalType newGlobal = (GlobalType)ModelFactory.eINSTANCE.create(listItemClass);
newGlobal.setIdentifier(name);
addExtensionValue(newGlobal);
return newGlobal;
}
};
globalsTable.bindList(process, ModelPackage.eINSTANCE.getDocumentRoot_Global());
globalsTable.setTitle("Globals");
bindList(process, "properties");
}
}
}
super.createBindings(be);
}
| public void createBindings(EObject be) {
if (be instanceof Definitions) {
Definitions definitions = (Definitions)be;
for (RootElement re : definitions.getRootElements()) {
if (re instanceof Process) {
Process process = (Process)re;
ExtensionValueTableComposite globalsTable = new ExtensionValueTableComposite(
this, AbstractBpmn2TableComposite.DEFAULT_STYLE)
{
@Override
protected EObject addListItem(EObject object, EStructuralFeature feature) {
InputDialog dialog = new InputDialog(getShell(), "Add Global",
"Enter new global variable name","", new IInputValidator() {
@Override
public String isValid(String newText) {
if (newText==null || newText.isEmpty() || newText.contains(" "))
return "Please enter a valid name";
return null;
}
});
if (dialog.open()!=Window.OK){
return null;
}
String name = dialog.getValue();
GlobalType newGlobal = (GlobalType)ModelFactory.eINSTANCE.create(listItemClass);
newGlobal.setIdentifier(name);
addExtensionValue(newGlobal);
return newGlobal;
}
};
globalsTable.bindList(process, ModelPackage.eINSTANCE.getDocumentRoot_Global());
globalsTable.setTitle("Globals");
// bindList(process, "properties");
}
}
}
super.createBindings(be);
}
|
diff --git a/src/com/homework/hw3/hsql/DbAccess.java b/src/com/homework/hw3/hsql/DbAccess.java
index 7b072d2..5811016 100644
--- a/src/com/homework/hw3/hsql/DbAccess.java
+++ b/src/com/homework/hw3/hsql/DbAccess.java
@@ -1,237 +1,237 @@
package com.homework.hw3.hsql;
import java.sql.*;
import java.util.ArrayList;
import org.apache.commons.dbutils.DbUtils;
public class DbAccess {
private static final String DB_URL = "jdbc:hsqldb:file:${user.home}/data/fpoobus/db;shutdown=true"; //hsqldb.lock_file=false
static {
try {
Class.forName("org.hsqldb.jdbcDriver");
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
};
public static void main(String[] args) throws Exception {
}
public static void setupDatabase() {
try {
DbAccess db = new DbAccess();
db.deleteTable();
db.createTable();
db.createSequence();
//db.getAll();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void createTable() throws SQLException {
Connection conn = DriverManager.getConnection(DB_URL);
Statement stmt = null;
try {
stmt = conn.createStatement();
stmt.executeUpdate(
"CREATE TABLE unit ("+
"id BIGINT NOT NULL PRIMARY KEY,"+
"name VARCHAR(255) NOT NULL,"+
"code VARCHAR(255) NOT NULL,"+
");"
);
} catch(Exception e) {
System.out.println("Table already exists, TODO: fix duplicate insert");
e.printStackTrace();
} finally {
DbUtils.closeQuietly(stmt);
DbUtils.closeQuietly(conn);
}
}
private void createSequence() throws SQLException {
Connection conn = DriverManager.getConnection(DB_URL);
Statement stmt = null;
try {
stmt = conn.createStatement();
stmt.executeUpdate("CREATE SEQUENCE sequence AS INTEGER START WITH 1");
} catch(Exception e) {
System.out.println("Sequence already exists, TODO: fix duplicate insert");
} finally {
DbUtils.closeQuietly(stmt);
DbUtils.closeQuietly(conn);
}
}
public ArrayList<DbItem> getByLike(String str) throws SQLException {
ArrayList list = new ArrayList();
Connection conn = DriverManager.getConnection(DB_URL);
PreparedStatement ps = null;
Statement stmt = null;
ResultSet rset = null;
try {
- ps = conn.prepareStatement("SELECT * FROM unit " + "WHERE name LIKE '%"+str+"%'");
+ ps = conn.prepareStatement("SELECT * FROM unit " + "WHERE name LIKE '%"+str+"%' OR code LIKE '%"+str+"%'");
rset = ps.executeQuery();
while (rset.next()) {
long id = rset.getLong(1);
String name = rset.getString(2);
String code = rset.getString(3);
//long superior = rset.getLong(4);
DbItem item = new DbItem(id, name, code);
list.add(item);
System.out.println(rset.getInt(1) + ", " + rset.getString(2));
}
} catch(Exception e) {
e.getStackTrace();
} finally {
DbUtils.closeQuietly(rset);
DbUtils.closeQuietly(stmt);
DbUtils.closeQuietly(conn);
}
return list;
}
public ArrayList getAll() throws SQLException {
ArrayList list = new ArrayList();
Connection conn = DriverManager.getConnection(DB_URL);
Statement stmt = null;
ResultSet rset = null;
try {
stmt = conn.createStatement();
rset = stmt.executeQuery("SELECT * FROM unit");
while (rset.next()) {
long id = rset.getLong(1);
String name = rset.getString(2);
String code = rset.getString(3);
//long superior = rset.getLong(4);
DbItem item = new DbItem(id, name, code);
list.add(item);
System.out.println(rset.getLong(1) + ", " + rset.getString(2));
}
} finally {
DbUtils.closeQuietly(rset);
DbUtils.closeQuietly(stmt);
DbUtils.closeQuietly(conn);
}
return list;
}
public void deleteTable() throws SQLException {
Connection conn = DriverManager.getConnection(DB_URL);
Statement stmt = null;
try {
stmt = conn.createStatement();
stmt.executeUpdate("DROP SCHEMA public CASCADE");
System.out.println("Schema dropped");
} catch(Exception e) {
System.out.println("Error deleting table");
} finally {
DbUtils.closeQuietly(stmt);
DbUtils.closeQuietly(conn);
}
}
public void clearTable() throws SQLException {
Connection conn = DriverManager.getConnection(DB_URL);
Statement stmt = null;
try {
stmt = conn.createStatement();
stmt.executeUpdate("TRUNCATE SCHEMA public AND COMMIT");
System.out.println("Schema dropped");
} catch(Exception e) {
System.out.println("Error emptying table");
} finally {
DbUtils.closeQuietly(stmt);
DbUtils.closeQuietly(conn);
}
}
public void insertData(String name, String code) throws SQLException {
System.out.println("Inserting item. Name: " + name + " Code: " + code);
//executeQuery("INSERT INTO unit (id, name, code) VALUES(NEXT VALUE FOR sequence, '"+ name +"', '"+ code +"')");
Connection conn = DriverManager.getConnection(DB_URL);
Statement stmt = null;
try {
stmt = conn.createStatement();
stmt.executeUpdate(
"INSERT INTO unit (id, name, code) VALUES(NEXT VALUE FOR sequence, '"+ name +"', '"+ code +"')"
);
} catch(Exception e) {
System.out.println("Table already exists, TODO: fix duplicate insert");
e.printStackTrace();
} finally {
DbUtils.closeQuietly(stmt);
DbUtils.closeQuietly(conn);
}
}
public void insertDummyData() {
try {
insertData("CEO", "1");
insertData("Administration", "1-1");
insertData("Legal", "1-1-1");
insertData("Archives", "1-1-2");
insertData("Production", "1-2");
insertData("Sales", "2");
} catch (SQLException e) {
throw new RuntimeException(e);
//e.printStackTrace();
}
}
public void deleteItem(String key) throws SQLException {
int delkey = Integer.valueOf(key);
//executeQuery("DELETE FROM unit WHERE id = " + delkey);
Connection conn = DriverManager.getConnection(DB_URL);
Statement stmt = null;
try {
stmt = conn.createStatement();
stmt.executeUpdate(
"DELETE FROM unit WHERE id = " + delkey + ""
);
} catch(Exception e) {
System.out.println("Table already exists, TODO: fix duplicate insert");
e.printStackTrace();
} finally {
DbUtils.closeQuietly(stmt);
DbUtils.closeQuietly(conn);
}
}
private void executeQuery(String queryString) {
Statement stmt = null;
Connection conn = null;
try {
conn = DriverManager.getConnection(DB_URL);
stmt = conn.createStatement();
stmt.executeUpdate(queryString);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
DbUtils.closeQuietly(stmt);
DbUtils.closeQuietly(conn);
}
}
}
| true | true | public ArrayList<DbItem> getByLike(String str) throws SQLException {
ArrayList list = new ArrayList();
Connection conn = DriverManager.getConnection(DB_URL);
PreparedStatement ps = null;
Statement stmt = null;
ResultSet rset = null;
try {
ps = conn.prepareStatement("SELECT * FROM unit " + "WHERE name LIKE '%"+str+"%'");
rset = ps.executeQuery();
while (rset.next()) {
long id = rset.getLong(1);
String name = rset.getString(2);
String code = rset.getString(3);
//long superior = rset.getLong(4);
DbItem item = new DbItem(id, name, code);
list.add(item);
System.out.println(rset.getInt(1) + ", " + rset.getString(2));
}
} catch(Exception e) {
e.getStackTrace();
} finally {
DbUtils.closeQuietly(rset);
DbUtils.closeQuietly(stmt);
DbUtils.closeQuietly(conn);
}
return list;
}
| public ArrayList<DbItem> getByLike(String str) throws SQLException {
ArrayList list = new ArrayList();
Connection conn = DriverManager.getConnection(DB_URL);
PreparedStatement ps = null;
Statement stmt = null;
ResultSet rset = null;
try {
ps = conn.prepareStatement("SELECT * FROM unit " + "WHERE name LIKE '%"+str+"%' OR code LIKE '%"+str+"%'");
rset = ps.executeQuery();
while (rset.next()) {
long id = rset.getLong(1);
String name = rset.getString(2);
String code = rset.getString(3);
//long superior = rset.getLong(4);
DbItem item = new DbItem(id, name, code);
list.add(item);
System.out.println(rset.getInt(1) + ", " + rset.getString(2));
}
} catch(Exception e) {
e.getStackTrace();
} finally {
DbUtils.closeQuietly(rset);
DbUtils.closeQuietly(stmt);
DbUtils.closeQuietly(conn);
}
return list;
}
|
diff --git a/core/src/main/java/com/metsci/glimpse/painter/info/SimpleTextPainter.java b/core/src/main/java/com/metsci/glimpse/painter/info/SimpleTextPainter.java
index 707ab505..3d53fe60 100644
--- a/core/src/main/java/com/metsci/glimpse/painter/info/SimpleTextPainter.java
+++ b/core/src/main/java/com/metsci/glimpse/painter/info/SimpleTextPainter.java
@@ -1,413 +1,413 @@
/*
* Copyright (c) 2012, Metron, 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 Metron, 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 METRON, INC. 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.metsci.glimpse.painter.info;
import static com.metsci.glimpse.support.font.FontUtils.getDefaultBold;
import static com.metsci.glimpse.support.font.FontUtils.getDefaultPlain;
import java.awt.Font;
import java.awt.geom.Rectangle2D;
import javax.media.opengl.GL;
import com.metsci.glimpse.context.GlimpseBounds;
import com.metsci.glimpse.context.GlimpseContext;
import com.metsci.glimpse.painter.base.GlimpsePainterImpl;
import com.metsci.glimpse.support.color.GlimpseColor;
import com.metsci.glimpse.support.settings.AbstractLookAndFeel;
import com.metsci.glimpse.support.settings.LookAndFeel;
import com.sun.opengl.util.j2d.TextRenderer;
/**
* A painter which displays arbitrary text at a fixed pixel
* location on the screen.
*
* @author ulman
*/
public class SimpleTextPainter extends GlimpsePainterImpl
{
public enum HorizontalPosition
{
Left, Center, Right;
}
public enum VerticalPosition
{
Bottom, Center, Top;
}
private float[] textColor = GlimpseColor.getBlack( );
private boolean paintBackground = false;
private float[] backgroundColor = GlimpseColor.getBlack( 0.3f );
private int padding = 5;
private HorizontalPosition hPos;
private VerticalPosition vPos;
private TextRenderer textRenderer;
private String sizeText;
private String text;
private boolean horizontal = true;
private boolean fontSet = false;
private volatile Font newFont = null;
private volatile boolean antialias = false;
public SimpleTextPainter( )
{
setFont( 12, true, false );
hPos = HorizontalPosition.Left;
vPos = VerticalPosition.Bottom;
}
public SimpleTextPainter setHorizontalLabels( boolean horizontal )
{
this.horizontal = horizontal;
return this;
}
public SimpleTextPainter setPaintBackground( boolean paintBackground )
{
this.paintBackground = paintBackground;
return this;
}
public SimpleTextPainter setBackgroundColor( float[] backgroundColor )
{
this.backgroundColor = backgroundColor;
return this;
}
public SimpleTextPainter setHorizontalPosition( HorizontalPosition hPos )
{
this.hPos = hPos;
return this;
}
public SimpleTextPainter setVerticalPosition( VerticalPosition vPos )
{
this.vPos = vPos;
return this;
}
public SimpleTextPainter setFont( Font font )
{
setFont( font, false );
return this;
}
public SimpleTextPainter setFont( Font font, boolean antialias )
{
this.newFont = font;
this.antialias = antialias;
this.fontSet = true;
return this;
}
public SimpleTextPainter setFont( int size, boolean bold )
{
setFont( size, bold, false );
return this;
}
public SimpleTextPainter setFont( int size, boolean bold, boolean antialias )
{
if ( bold )
{
setFont( getDefaultBold( size ), antialias );
}
else
{
setFont( getDefaultPlain( size ), antialias );
}
return this;
}
public SimpleTextPainter setSizeText( String sizeText )
{
this.sizeText = sizeText;
return this;
}
public SimpleTextPainter setText( String text )
{
this.text = text;
return this;
}
public SimpleTextPainter setPadding( int padding )
{
this.padding = padding;
return this;
}
public SimpleTextPainter setColor( float[] rgba )
{
textColor = rgba;
return this;
}
public SimpleTextPainter setColor( float r, float g, float b, float a )
{
textColor[0] = r;
textColor[1] = g;
textColor[2] = b;
textColor[3] = a;
return this;
}
public int getPadding( )
{
return padding;
}
@Override
public void setLookAndFeel( LookAndFeel laf )
{
// ignore the look and feel if a font has been manually set
if ( !fontSet )
{
setFont( laf.getFont( AbstractLookAndFeel.TITLE_FONT ), false );
fontSet = false;
}
}
@Override
public void dispose( GlimpseContext context )
{
if ( textRenderer != null ) textRenderer.dispose( );
textRenderer = null;
}
protected void paintToHorizontal( GL gl, int width, int height, Rectangle2D textBounds )
{
int xText = padding;
int yText = padding;
switch ( hPos )
{
case Left:
xText = ( int ) padding;
break;
case Center:
xText = ( int ) ( width / 2d - textBounds.getWidth( ) / 2d );
break;
case Right:
xText = ( int ) ( width - textBounds.getWidth( ) - padding );
break;
}
switch ( vPos )
{
case Bottom:
yText = ( int ) padding;
break;
case Center:
yText = ( int ) ( height / 2d - textBounds.getHeight( ) / 2d );
break;
case Top:
yText = ( int ) ( height - textBounds.getHeight( ) - padding );
break;
}
if ( this.paintBackground )
{
gl.glMatrixMode( GL.GL_PROJECTION );
gl.glLoadIdentity( );
gl.glOrtho( -0.5, width - 1 + 0.5, -0.5, height - 1 + 0.5, -1, 1 );
gl.glMatrixMode( GL.GL_MODELVIEW );
gl.glLoadIdentity( );
gl.glBlendFunc( GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA );
gl.glEnable( GL.GL_BLEND );
Rectangle2D bound = sizeText == null ? textRenderer.getBounds( text ) : textRenderer.getBounds( sizeText );
int xTextMax = ( int ) ( xText + bound.getWidth( ) + ( bound.getMinX( ) ) - 1 );
int yTextMax = ( int ) ( yText + bound.getHeight( ) - 3 );
// Draw Text Background
gl.glColor4fv( backgroundColor, 0 );
gl.glBegin( GL.GL_QUADS );
try
{
gl.glVertex2f( xText - 0.5f - 2, yText - 0.5f - 2 );
gl.glVertex2f( xTextMax + 0.5f + 2, yText - 0.5f - 2 );
gl.glVertex2f( xTextMax + 0.5f + 2, yTextMax + 0.5f + 2 );
gl.glVertex2f( xText - 0.5f - 2, yTextMax + 0.5f + 2 );
}
finally
{
gl.glEnd( );
}
}
gl.glDisable( GL.GL_BLEND );
textRenderer.beginRendering( width, height );
try
{
textRenderer.setColor( textColor[0], textColor[1], textColor[2], textColor[3] );
textRenderer.draw( text, xText, yText );
}
finally
{
textRenderer.endRendering( );
}
}
protected void paintToVertical( GL gl, int width, int height, Rectangle2D textBounds )
{
int xText = padding;
int yText = padding;
double textWidth = textBounds.getWidth( );
double textHeight = textBounds.getHeight( );
- double halfTextWidth = textWidth / 2d;
- double halfTextHeight = textHeight / 2d;
+ int halfTextWidth = (int) ( textWidth / 2d );
+ int halfTextHeight = (int) ( textHeight / 2d );
switch ( hPos )
{
case Left:
xText = ( int ) ( padding - halfTextWidth + halfTextHeight );
break;
case Center:
xText = ( int ) ( width / 2d - halfTextWidth );
break;
case Right:
xText = ( int ) ( width - halfTextWidth - halfTextHeight - padding );
break;
}
switch ( vPos )
{
case Bottom:
yText = ( int ) ( padding - halfTextHeight + halfTextWidth );
break;
case Center:
yText = ( int ) ( height / 2d - halfTextHeight );
break;
case Top:
yText = ( int ) ( height - halfTextHeight - halfTextWidth - padding );
break;
}
if ( this.paintBackground )
{
gl.glMatrixMode( GL.GL_PROJECTION );
gl.glLoadIdentity( );
gl.glOrtho( 0, width, 0, height, -1, 1 );
gl.glMatrixMode( GL.GL_MODELVIEW );
gl.glLoadIdentity( );
gl.glBlendFunc( GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA );
gl.glEnable( GL.GL_BLEND );
int buffer = 2;
int xTextMin = ( int ) ( xText + halfTextWidth - halfTextHeight - buffer );
int yTextMin = ( int ) ( yText + halfTextWidth + halfTextHeight + buffer );
int xTextMax = ( int ) ( xText + halfTextWidth + halfTextHeight + buffer + 3 );
int yTextMax = ( int ) ( yText - halfTextWidth + halfTextHeight - buffer );
// Draw Text Background
gl.glColor4fv( backgroundColor, 0 );
gl.glBegin( GL.GL_QUADS );
try
{
gl.glVertex2f( xTextMin, yTextMin );
gl.glVertex2f( xTextMax, yTextMin );
gl.glVertex2f( xTextMax, yTextMax );
gl.glVertex2f( xTextMin, yTextMax );
}
finally
{
gl.glEnd( );
}
}
gl.glDisable( GL.GL_BLEND );
textRenderer.beginRendering( width, height );
try
{
double xShift = xText + halfTextWidth;
double yShift = yText + halfTextHeight;
gl.glMatrixMode( GL.GL_PROJECTION );
gl.glTranslated( xShift, yShift, 0 );
gl.glRotated( 90, 0, 0, 1.0f );
gl.glTranslated( -xShift, -yShift, 0 );
textRenderer.setColor( textColor[0], textColor[1], textColor[2], textColor[3] );
textRenderer.draw( text, xText, yText );
}
finally
{
textRenderer.endRendering( );
}
}
@Override
protected void paintTo( GlimpseContext context, GlimpseBounds bounds )
{
if ( newFont != null )
{
if ( textRenderer != null ) textRenderer.dispose( );
textRenderer = new TextRenderer( newFont, antialias, false );
newFont = null;
}
if ( text == null ) return;
GL gl = context.getGL( );
int width = bounds.getWidth( );
int height = bounds.getHeight( );
Rectangle2D textBounds = sizeText == null ? textRenderer.getBounds( text ) : textRenderer.getBounds( sizeText );
if ( horizontal )
{
paintToHorizontal( gl, width, height, textBounds );
}
else
{
paintToVertical( gl, width, height, textBounds );
}
}
}
| true | true | protected void paintToVertical( GL gl, int width, int height, Rectangle2D textBounds )
{
int xText = padding;
int yText = padding;
double textWidth = textBounds.getWidth( );
double textHeight = textBounds.getHeight( );
double halfTextWidth = textWidth / 2d;
double halfTextHeight = textHeight / 2d;
switch ( hPos )
{
case Left:
xText = ( int ) ( padding - halfTextWidth + halfTextHeight );
break;
case Center:
xText = ( int ) ( width / 2d - halfTextWidth );
break;
case Right:
xText = ( int ) ( width - halfTextWidth - halfTextHeight - padding );
break;
}
switch ( vPos )
{
case Bottom:
yText = ( int ) ( padding - halfTextHeight + halfTextWidth );
break;
case Center:
yText = ( int ) ( height / 2d - halfTextHeight );
break;
case Top:
yText = ( int ) ( height - halfTextHeight - halfTextWidth - padding );
break;
}
if ( this.paintBackground )
{
gl.glMatrixMode( GL.GL_PROJECTION );
gl.glLoadIdentity( );
gl.glOrtho( 0, width, 0, height, -1, 1 );
gl.glMatrixMode( GL.GL_MODELVIEW );
gl.glLoadIdentity( );
gl.glBlendFunc( GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA );
gl.glEnable( GL.GL_BLEND );
int buffer = 2;
int xTextMin = ( int ) ( xText + halfTextWidth - halfTextHeight - buffer );
int yTextMin = ( int ) ( yText + halfTextWidth + halfTextHeight + buffer );
int xTextMax = ( int ) ( xText + halfTextWidth + halfTextHeight + buffer + 3 );
int yTextMax = ( int ) ( yText - halfTextWidth + halfTextHeight - buffer );
// Draw Text Background
gl.glColor4fv( backgroundColor, 0 );
gl.glBegin( GL.GL_QUADS );
try
{
gl.glVertex2f( xTextMin, yTextMin );
gl.glVertex2f( xTextMax, yTextMin );
gl.glVertex2f( xTextMax, yTextMax );
gl.glVertex2f( xTextMin, yTextMax );
}
finally
{
gl.glEnd( );
}
}
gl.glDisable( GL.GL_BLEND );
textRenderer.beginRendering( width, height );
try
{
double xShift = xText + halfTextWidth;
double yShift = yText + halfTextHeight;
gl.glMatrixMode( GL.GL_PROJECTION );
gl.glTranslated( xShift, yShift, 0 );
gl.glRotated( 90, 0, 0, 1.0f );
gl.glTranslated( -xShift, -yShift, 0 );
textRenderer.setColor( textColor[0], textColor[1], textColor[2], textColor[3] );
textRenderer.draw( text, xText, yText );
}
finally
{
textRenderer.endRendering( );
}
}
| protected void paintToVertical( GL gl, int width, int height, Rectangle2D textBounds )
{
int xText = padding;
int yText = padding;
double textWidth = textBounds.getWidth( );
double textHeight = textBounds.getHeight( );
int halfTextWidth = (int) ( textWidth / 2d );
int halfTextHeight = (int) ( textHeight / 2d );
switch ( hPos )
{
case Left:
xText = ( int ) ( padding - halfTextWidth + halfTextHeight );
break;
case Center:
xText = ( int ) ( width / 2d - halfTextWidth );
break;
case Right:
xText = ( int ) ( width - halfTextWidth - halfTextHeight - padding );
break;
}
switch ( vPos )
{
case Bottom:
yText = ( int ) ( padding - halfTextHeight + halfTextWidth );
break;
case Center:
yText = ( int ) ( height / 2d - halfTextHeight );
break;
case Top:
yText = ( int ) ( height - halfTextHeight - halfTextWidth - padding );
break;
}
if ( this.paintBackground )
{
gl.glMatrixMode( GL.GL_PROJECTION );
gl.glLoadIdentity( );
gl.glOrtho( 0, width, 0, height, -1, 1 );
gl.glMatrixMode( GL.GL_MODELVIEW );
gl.glLoadIdentity( );
gl.glBlendFunc( GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA );
gl.glEnable( GL.GL_BLEND );
int buffer = 2;
int xTextMin = ( int ) ( xText + halfTextWidth - halfTextHeight - buffer );
int yTextMin = ( int ) ( yText + halfTextWidth + halfTextHeight + buffer );
int xTextMax = ( int ) ( xText + halfTextWidth + halfTextHeight + buffer + 3 );
int yTextMax = ( int ) ( yText - halfTextWidth + halfTextHeight - buffer );
// Draw Text Background
gl.glColor4fv( backgroundColor, 0 );
gl.glBegin( GL.GL_QUADS );
try
{
gl.glVertex2f( xTextMin, yTextMin );
gl.glVertex2f( xTextMax, yTextMin );
gl.glVertex2f( xTextMax, yTextMax );
gl.glVertex2f( xTextMin, yTextMax );
}
finally
{
gl.glEnd( );
}
}
gl.glDisable( GL.GL_BLEND );
textRenderer.beginRendering( width, height );
try
{
double xShift = xText + halfTextWidth;
double yShift = yText + halfTextHeight;
gl.glMatrixMode( GL.GL_PROJECTION );
gl.glTranslated( xShift, yShift, 0 );
gl.glRotated( 90, 0, 0, 1.0f );
gl.glTranslated( -xShift, -yShift, 0 );
textRenderer.setColor( textColor[0], textColor[1], textColor[2], textColor[3] );
textRenderer.draw( text, xText, yText );
}
finally
{
textRenderer.endRendering( );
}
}
|
diff --git a/bundles/extensions/bundleresource/src/main/java/org/apache/sling/bundleresource/impl/BundleResourceProvider.java b/bundles/extensions/bundleresource/src/main/java/org/apache/sling/bundleresource/impl/BundleResourceProvider.java
index 72870b6d53..c40222e8be 100644
--- a/bundles/extensions/bundleresource/src/main/java/org/apache/sling/bundleresource/impl/BundleResourceProvider.java
+++ b/bundles/extensions/bundleresource/src/main/java/org/apache/sling/bundleresource/impl/BundleResourceProvider.java
@@ -1,168 +1,168 @@
/*
* 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.sling.bundleresource.impl;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.sling.api.SlingException;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceProvider;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.commons.osgi.ManifestHeader;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceRegistration;
public class BundleResourceProvider implements ResourceProvider {
/** The bundle providing the resources */
private final BundleResourceCache bundle;
/** The root paths */
private final MappedPath[] roots;
private ServiceRegistration serviceRegistration;
/**
* Creates Bundle resource provider accessing entries in the given Bundle an
* supporting resources below root paths given by the rootList which is a
* comma (and whitespace) separated list of absolute paths.
*/
public BundleResourceProvider(Bundle bundle, String rootList) {
this.bundle = new BundleResourceCache(bundle);
List<MappedPath> prefixList = new ArrayList<MappedPath>();
final ManifestHeader header = ManifestHeader.parse(rootList);
for (final ManifestHeader.Entry entry : header.getEntries()) {
final String resourceRoot = entry.getValue();
final String pathDirective = entry.getDirectiveValue("path");
if (pathDirective != null) {
prefixList.add(new MappedPath(resourceRoot, pathDirective));
} else {
prefixList.add(MappedPath.create(resourceRoot));
}
}
this.roots = prefixList.toArray(new MappedPath[prefixList.size()]);
}
//---------- Service Registration
long registerService(BundleContext context) {
Dictionary<String, Object> props = new Hashtable<String, Object>();
props.put(Constants.SERVICE_DESCRIPTION,
"Provider of bundle based resources");
props.put(Constants.SERVICE_VENDOR, "The Apache Software Foundation");
props.put(ROOTS, getRoots());
serviceRegistration = context.registerService(SERVICE_NAME, this, props);
return (Long) serviceRegistration.getReference().getProperty(
Constants.SERVICE_ID);
}
void unregisterService() {
if (serviceRegistration != null) {
serviceRegistration.unregister();
}
}
// ---------- ResourceProvider interface
public Resource getResource(ResourceResolver resourceResolver,
HttpServletRequest request, String path) {
return getResource(resourceResolver, path);
}
/**
* Returns a BundleResource for the path if such an entry exists in the
* bundle of this provider. The JcrResourceResolver is ignored by this
* implementation.
*/
public Resource getResource(ResourceResolver resourceResolver, String path) {
MappedPath mappedPath = getMappedPath(path);
if (mappedPath != null) {
return BundleResource.getResource(resourceResolver, bundle,
mappedPath, path);
}
return null;
}
public Iterator<Resource> listChildren(final Resource parent)
throws SlingException {
- if (((BundleResource)parent).getBundle() == this.bundle) {
+ if (parent instanceof BundleResource && ((BundleResource)parent).getBundle() == this.bundle) {
// bundle resources can handle this request directly when the parent
// resource is in the same bundle as this provider.
return ((BundleResource) parent).listChildren();
}
// ensure this provider may have children of the parent
String parentPath = parent.getPath();
MappedPath mappedPath = getMappedPath(parentPath);
if (mappedPath != null) {
return new BundleResourceIterator(parent.getResourceResolver(),
bundle, mappedPath, parentPath);
}
// the parent resource cannot have children in this provider,
// though this is basically not expected, we still have to
// be prepared for such a situation
return Collections.<Resource> emptyList().iterator();
}
// ---------- Web Console plugin support
BundleResourceCache getBundleResourceCache() {
return bundle;
}
MappedPath[] getMappedPaths() {
return roots;
}
// ---------- internal
/** Returns the root paths */
private String[] getRoots() {
String[] rootPaths = new String[roots.length];
for (int i = 0; i < roots.length; i++) {
rootPaths[i] = roots[i].getResourceRoot();
}
return rootPaths;
}
private MappedPath getMappedPath(String resourcePath) {
for (MappedPath mappedPath : roots) {
if (mappedPath.isChild(resourcePath)) {
return mappedPath;
}
}
return null;
}
}
| true | true | public Iterator<Resource> listChildren(final Resource parent)
throws SlingException {
if (((BundleResource)parent).getBundle() == this.bundle) {
// bundle resources can handle this request directly when the parent
// resource is in the same bundle as this provider.
return ((BundleResource) parent).listChildren();
}
// ensure this provider may have children of the parent
String parentPath = parent.getPath();
MappedPath mappedPath = getMappedPath(parentPath);
if (mappedPath != null) {
return new BundleResourceIterator(parent.getResourceResolver(),
bundle, mappedPath, parentPath);
}
// the parent resource cannot have children in this provider,
// though this is basically not expected, we still have to
// be prepared for such a situation
return Collections.<Resource> emptyList().iterator();
}
| public Iterator<Resource> listChildren(final Resource parent)
throws SlingException {
if (parent instanceof BundleResource && ((BundleResource)parent).getBundle() == this.bundle) {
// bundle resources can handle this request directly when the parent
// resource is in the same bundle as this provider.
return ((BundleResource) parent).listChildren();
}
// ensure this provider may have children of the parent
String parentPath = parent.getPath();
MappedPath mappedPath = getMappedPath(parentPath);
if (mappedPath != null) {
return new BundleResourceIterator(parent.getResourceResolver(),
bundle, mappedPath, parentPath);
}
// the parent resource cannot have children in this provider,
// though this is basically not expected, we still have to
// be prepared for such a situation
return Collections.<Resource> emptyList().iterator();
}
|
diff --git a/source/RMG/jing/rxn/FastMasterEqn.java b/source/RMG/jing/rxn/FastMasterEqn.java
index 0f9deba4..b4f10b49 100644
--- a/source/RMG/jing/rxn/FastMasterEqn.java
+++ b/source/RMG/jing/rxn/FastMasterEqn.java
@@ -1,1194 +1,1194 @@
////////////////////////////////////////////////////////////////////////////////
//
// RMG - Reaction Mechanism Generator
//
// Copyright (c) 2002-2009 Prof. William H. Green ([email protected]) and the
// RMG Team ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
////////////////////////////////////////////////////////////////////////////////
package jing.rxn;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.StringReader;
import java.text.DecimalFormat;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import Jama.Matrix;
import jing.chem.Species;
import jing.chem.SpectroscopicData;
import jing.mathTool.UncertainDouble;
import jing.param.GasConstant;
import jing.param.Pressure;
import jing.param.Temperature;
import jing.rxnSys.CoreEdgeReactionModel;
import jing.rxnSys.ReactionModelGenerator;
import jing.rxnSys.ReactionSystem;
/**
* Used to estimate pressure-dependent rate coefficients k(T, P) for a
* PDepNetwork object. The estimation is done by a call to the Fortran module
* FAME. There are two methods for estimating k(T, P): the modified strong
* collision and the reservoir state methods.
* @author jwallen
*/
public class FastMasterEqn implements PDepKineticsEstimator {
/**
* The number of times the FAME module has been called for any network
* since the inception of this RMG execution. Used to be used to number the
* FAME input and output files, but now the networks have individual IDs
* that are used for this purpose.
*/
private static int runCount = 0;
/**
* An enumeraction of pressure-dependent kinetics estimation methods:
* <ul>
* <li>NONE - The method could not be assessed.
* <li>STRONGCOLLISION - The steady state/modified strong collision method of Chang, Bozzelli, and Dean.
* <li>RESERVOIRSTATE - The steady state/reservoir state method of N. J. B. Green and Bhatti.
* </ul>
*/
public enum Mode { NONE, STRONGCOLLISION, RESERVOIRSTATE };
/**
* The mode to use for estimating the pressure-dependent kinetics. The mode
* represents the set of approximations used to estimate the k(T, P) values.
*/
private Mode mode;
/**
* A list of the temperatures at which the rate coefficient has been
* explicitly calculated..
*/
private static Temperature[] temperatures;
/**
* A list of the pressures at which the rate coefficient has been
* explicitly calculated.
*/
private static Pressure[] pressures;
private static int numTBasisFuncs = -1;
private static int numPBasisFuncs = -1;
/**
* The number of grains to use in a fame calculation (written in input file)
*/
private static int numGrains = 251;
/**
* boolean, detailing whether the high-P-limit is greater than all of the
* fame-computed k(T,P)
*/
private static boolean pdepRatesOK = true;
//==========================================================================
//
// Constructors
//
/**
* Creates a new object with the desired mode. The mode represents the
* set of approximations used to estimate the k(T, P) values.
* @param m The mode to use for estimating the pressure-dependent kinetics.
*/
public FastMasterEqn(Mode m) {
setMode(m);
}
//==========================================================================
//
// Accessors
//
/**
* Returns the current pressure-dependent kinetics estimation mode.
* @return The current pressure-dependent kinetics estimation mode.
*/
public Mode getMode() {
return mode;
}
/**
* Sets the pressure-dependent kinetics estimation mode.
* @param m The new pressure-dependent kinetics estimation mode.
*/
public void setMode(Mode m) {
mode = m;
}
//==========================================================================
//
// Other methods
//
/**
* Executes a pressure-dependent rate coefficient calculation.
* @param pdn The pressure-dependent reaction network of interest
* @param rxnSystem The reaction system of interest
* @param cerm The current core/edge reaction model
*/
public void runPDepCalculation(PDepNetwork pdn, ReactionSystem rxnSystem,
CoreEdgeReactionModel cerm) {
// No update needed if network is not altered
if (pdn.getAltered() == false)
return;
// Don't do networks with isomers made up of only monatomic species
boolean shouldContinue = true;
for (ListIterator iter = pdn.getIsomers().listIterator(); iter.hasNext(); ) {
PDepIsomer isomer = (PDepIsomer) iter.next();
boolean allMonatomic = true;
for (int i = 0; i < isomer.getNumSpecies(); i++) {
if (!isomer.getSpecies(i).isMonatomic())
allMonatomic = false;
}
if (allMonatomic)
shouldContinue = false;
}
// No update needed if network is only two wells and one reaction (?)
/*if (pdn.getUniIsomers().size() + pdn.getMultiIsomers().size() == 2 &&
pdn.getPathReactions().size() == 1)
shouldContinue = false;*/
if (!shouldContinue)
{
/*LinkedList<PDepReaction> paths = pdn.getPathReactions();
LinkedList<PDepReaction> net = pdn.getNetReactions();
net.clear();
for (int i = 0; i < paths.size(); i++)
net.add(paths.get(i));*/
return;
}
// Get working directory (to find FAME executable)
String dir = System.getProperty("RMG.workingDirectory");
// Determine wells and reactions; skip if no reactions in network
LinkedList<Species> speciesList = pdn.getSpeciesList();
LinkedList<PDepIsomer> isomerList = pdn.getIsomers();
LinkedList<PDepReaction> pathReactionList = pdn.getPathReactions();
if (pathReactionList.size() == 0) {
System.out.println("Warning: Empty pressure-dependent network detected. Skipping.");
return;
}
// Make sure all species have spectroscopic data
for (ListIterator<PDepIsomer> iter = isomerList.listIterator(); iter.hasNext(); ) {
PDepIsomer isomer = iter.next();
for (int i = 0; i < isomer.getNumSpecies(); i++) {
Species species = isomer.getSpecies(i);
if (!species.hasSpectroscopicData())
species.generateSpectroscopicData();
}
}
// Run garbage collection before we submit to FAME to prevent jobs from crashing with large P-Dep networks.
// JDM January 22, 2010
//if (runTime.freeMemory() < runTime.totalMemory()/3) {
if (isomerList.size() >= 10) {
// System.out.println("Number of isomers in PDepNetwork to follow: " + isomerList.size());
// Find current time BEFORE running garbage collection.
// JDM January 27, 2010
// System.out.println("Running Time is: " + String.valueOf((System.currentTimeMillis())/1000/60) + " minutes before garbage collection.");
Runtime runTime = Runtime.getRuntime();
runTime.gc();
// Find current time AFTER running garbage collection.
// JDM January 27, 2010
// System.out.println("Running Time is: " + String.valueOf((System.currentTimeMillis())/1000/60) + " minutes after garbage collection.");
}
//}
// Create FAME input files
String input = writeInputString(pdn, rxnSystem, speciesList, isomerList, pathReactionList);
String output = "";
// DEBUG only: Write input file
/*try {
FileWriter fw = new FileWriter(new File("fame/" + Integer.toString(pdn.getID()) + "_input.txt"));
fw.write(input);
fw.close();
} catch (IOException ex) {
System.out.println("Unable to write FAME input file.");
System.exit(0);
}*/
// Touch FAME output file
//touchOutputFile(); //no longer needed with standard input/output
// FAME system call
try {
//System.out.println("Running FAME...");
String[] command = {dir + "/bin/fame.exe"};
File runningDir = new File("fame/");
Process fame = Runtime.getRuntime().exec(command, null, runningDir);
BufferedReader stdout = new BufferedReader(new InputStreamReader(fame.getInputStream()));
BufferedReader stderr = new BufferedReader(new InputStreamReader(fame.getErrorStream()));
PrintStream stdin = new PrintStream( new BufferedOutputStream( fame.getOutputStream(), 1024), true);
stdin.print( input );
stdin.flush();
if (stdin.checkError()) { // Flush the stream and check its error state.
System.out.println("ERROR sending input to fame.exe!!");
}
stdin.close();
String line = stdout.readLine().trim();
// advance to first line that's not for debug purposes
while ( line.startsWith("#IN:") || line.contains("#DEBUG:") ) {
output += line + "\n";
line = stdout.readLine().trim();
}
if (line.startsWith("#####")) { // correct output begins with ######...
output += line + "\n";
while ( (line = stdout.readLine()) != null) {
output += line + "\n";
}
}
else { // erroneous output does not begin with ######...
// Print FAME stdout and error
System.out.println("FAME Error::");
System.out.println(line);
output += line + "\n";
while ( ((line = stdout.readLine()) != null) || ((line = stderr.readLine()) != null) ) {
output += line + "\n";
System.out.println(line);
}
// clean up i/o streams (we may be trying again with ModifiedStrongCollision and carrying on)
stdout.close();
stderr.close();
throw new Exception();
}
int exitValue = fame.waitFor();
// Clean up i/o streams
// This may be needed to release memory, which is especially
// important for FAME since it can easily be called tens of
// thousands of times in a single job
stdout.close();
stderr.close();
// Parse FAME output file and update accordingly
if (parseOutputString(output, pdn, rxnSystem, cerm, isomerList)) {
// Reset altered flag
pdn.setAltered(false);
// Clean up files
int id = pdn.getID();
/*String path = "fame/";
if (id < 10) path += "000";
else if (id < 100) path += "00";
else if (id < 1000) path += "0";
path += Integer.toString(id);
File input = new File("fame/fame_input.txt");
File newInput = new File(path + "_input.txt");
input.renameTo(newInput);
File output = new File("fame/fame_output.txt");
File newOutput = new File(path + "_output.txt");
output.renameTo(newOutput);*/
// Write finished indicator to console
//System.out.println("FAME execution for network " + Integer.toString(id) + " complete.");
String formula = pdn.getSpeciesType();
System.out.println("PDepNetwork #" + Integer.toString(id) +
" (" + formula + "): " +
pdn.getNetReactions().size() + " included and " +
pdn.getNonincludedReactions().size() + " nonincluded net reactions.");
// Find time required to run FAME for large networks.
// JDM January 27, 2010
// if (isomerList.size() >= 10) {
// System.out.println("Running Time is: " + String.valueOf((System.currentTimeMillis())/1000/60) + " minutes after running fame.");
// }
}
}
catch (Exception e) {
e.printStackTrace();
System.out.println(e.getMessage());
// Save bad input to file
try {
FileWriter fw = new FileWriter(new File("fame/" + Integer.toString(pdn.getID()) + "_input.txt"));
fw.write(input);
fw.close();
System.out.println("Troublesome FAME input saved to ./fame/" + Integer.toString(pdn.getID()) + "_input.txt");
FileWriter fwo = new FileWriter(new File("fame/" + Integer.toString(pdn.getID()) + "_output.txt"));
fwo.write(output);
fwo.close();
System.out.println("Troublesome FAME result saved to ./fame/" + Integer.toString(pdn.getID()) + "_output.txt");
} catch (IOException ex) {
System.out.println("Unable to save FAME input that caused the error.");
System.exit(0);
}
// If using RS method, fall back to MSC
if (mode == Mode.RESERVOIRSTATE) { /// mode is not defined if running modified strong collision
System.out.println("Falling back to modified strong collision mode for this network.");
mode = Mode.STRONGCOLLISION;
runPDepCalculation(pdn, rxnSystem, cerm);
mode = Mode.RESERVOIRSTATE;
return;
}
else {
System.out.println("Error running FAME.");
System.exit(0);
}
}
/*
* MRH 26Feb2010:
* Checking whether pdep rates exceed the high-P-limit
*
* Although fame converges, the computed k(T,P) may exceed the high-P-limit,
* due to the number of grains being too small. If any of the pdep rates
* exceed the high-P-limit by greater than a factor of 2, the "pdepRatesOK" boolean
* is set to false and fame will be re-executed, using an increased number
* of grains
* After all pdep rates are below the high-P-limit (or the number of grains
* exceeds 1000), we exit the while loop. The number of grains is then
* reset to 251 (which was the standard before)
*/
while (!pdepRatesOK) {
numGrains = numGrains + 200;
runPDepCalculation(pdn, rxnSystem, cerm);
}
numGrains = 251;
runCount++;
}
/**
* Creates the input file needed by FAME that represents a pressure-
* dependent reaction network.
* @param pdn The reaction network of interest
* @param rxnSystem The reaction system of interest
* @param speciesList The set of species in the network
* @param isomerList The set of isomers in the network
* @param pathReactionList The set of path reactions in the network
*/
public String writeInputString(PDepNetwork pdn, ReactionSystem rxnSystem,
LinkedList<Species> speciesList,
LinkedList<PDepIsomer> isomerList,
LinkedList<PDepReaction> pathReactionList) {
String input = "";
Temperature stdTemp = new Temperature(298, "K");
// Collect simulation parameters
// MRH 28Feb: Commented temperature/pressure lines (variables are never read)
// Temperature temperature = rxnSystem.getPresentTemperature();
// Pressure pressure = rxnSystem.getPresentPressure();
BathGas bathGas = new BathGas(rxnSystem);
int numChebTempPolys, numChebPressPolys;
if (numTBasisFuncs == -1) {
numChebTempPolys = 4;
numChebPressPolys = 4;
}
else {
numChebTempPolys = numTBasisFuncs;
numChebPressPolys = numPBasisFuncs;
}
// Determine reference energies
double grainMinEnergy = getGrainMinEnergy(isomerList); // [=] kJ/mol
double grainMaxEnergy = getGrainMaxEnergy(isomerList, 2100); // [=] kJ/mol
double grainSize = getGrainSize(grainMinEnergy, grainMaxEnergy, pdn.getNumUniIsomers()); // [=] kJ/mol
// Create the input string
try {
// Header
input += "################################################################################\n";
input += "#\n";
input += "# FAME input file\n";
input += "#\n";
input += "################################################################################\n";
input += "\n";
input += "# All syntax in this file is case-insensitive\n";
input += "\n";
// Method
input += "# The method to use to extract the phenomenological rate coefficients k(T, P)\n";
input += "# Options: ModifiedStrongCollision, ReservoirState\n";
if (mode == Mode.STRONGCOLLISION) input += "ModifiedStrongCollision\n";
else if (mode == Mode.RESERVOIRSTATE) input += "ReservoirState\n";
else throw new Exception("Unable to determine method to use to estimate phenomenological rate coefficients.");
input += "\n";
// Temperatures
input += "# The temperatures at which to estimate k(T, P)\n";
input += "# First item is the number of temperatures \n";
input += "# Second item is the units; options are K, C, F, or R\n";
input += "# Remaining items are the temperature values in the specified units\n";
input += Integer.toString(temperatures.length) + " K\n";
for (int i = 0; i < temperatures.length; i++)
input += Double.toString(temperatures[i].getK()) + "\n";
input += "\n";
// Pressures
input += "# The pressures at which to estimate k(T, P)\n";
input += "# First item is the number of pressures \n";
input += "# Second item is the units; options are bar, atm, Pa, or torr\n";
input += "# Remaining items are the temperature values in the specified units\n";
input += Integer.toString(pressures.length) + " Pa\n";
for (int i = 0; i < pressures.length; i++)
input += Double.toString(pressures[i].getPa()) + "\n";
input += "\n";
// Interpolation model
input += "# The interpolation model to use to fit k(T, P)\n";
input += "# Option 1: No interpolation\n";
input += "# Example: None\n";
input += "# Option 2: Chebyshev polynomials\n";
input += "# Option must be accompanied by two numbers, indicating the number of\n";
input += "# terms in the Chebyshev polynomials for temperature and pressure, \n";
input += "# respectively\n";
input += "# Example: Chebyshev 4 4\n";
input += "# Option 3: Pressure-dependent Arrhenius\n";
input += "# Example: PDepArrhenius\n";
if (PDepRateConstant.getMode() == PDepRateConstant.Mode.CHEBYSHEV)
input += "Chebyshev " + Integer.toString(numChebTempPolys) +
" " + Integer.toString(numChebPressPolys) + "\n";
else if (PDepRateConstant.getMode() == PDepRateConstant.Mode.PDEPARRHENIUS)
input += "PDepArrhenius\n";
else
input += "None\n";
input += "\n";
// Number of energy grains to use (determines to an extent the accuracy and precision of the results)
input += "# A method for determining the number of energy grains to use\n";
input += "# Option 1: Specifying the number to use directly\n";
input += "# Example: NumGrains 201\n";
input += "# Option 2: Specifying the grain size in J/mol, kJ/mol, cal/mol, kcal/mol, or cm^-1\n";
input += "# Example: GrainSize J/mol 4.184\n";
input += "NumGrains " + numGrains;
input += "\n\n";
// Collisional transfer probability model to use
input += "# Collisional transfer probability model\n";
input += "# Option 1: Single exponential down\n";
input += "# Option must also be accompanied by unit and value of the parameter\n";
input += "# Allowed units are J/mol, kJ/mol, cal/mol, kcal/mol, or cm^-1\n";
input += "# Example: SingleExpDown kJ/mol 7.14\n";
input += "SingleExpDown J/mol " + Double.toString(bathGas.getExpDownParam() * 1000);
input += "\n\n";
// Other parameters for bath gas
input += "# Bath gas parameters\n";
input += "# Molecular weight; allowed units are g/mol or u\n";
input += "# Lennard-Jones sigma parameter; allowed units are m or A\n";
input += "# Lennard-Jones epsilon parameter; allowed units are J or K\n";
input += "u " + Double.toString(bathGas.getMolecularWeight()) + "\n";
input += "m " + Double.toString(bathGas.getLJSigma()) + "\n";
input += "J " + Double.toString(bathGas.getLJEpsilon()) + "\n";
input += "\n";
input += "# The number of species in the network (minimum of 2)\n";
input += Integer.toString(speciesList.size()) + "\n";
input += "\n";
for (int i = 0; i < speciesList.size(); i++) {
Species spec = speciesList.get(i);
spec.calculateLJParameters();
input += "# Species identifier (128 characters or less, no spaces)\n";
input += spec.getName() + "(" + Integer.toString(spec.getID()) + ")\n";
input += "# Ground-state energy; allowed units are J/mol, kJ/mol, cal/mol, kcal/mol, or cm^-1\n";
input += "J/mol " + Double.toString(spec.calculateH(stdTemp) * 4184) + "\n";
input += "# Thermodynamics data:\n";
input += "# Standard enthalpy of formation; allowed units are J/mol, kJ/mol, cal/mol, kcal/mol, or cm^-1\n";
input += "# Standard entropy of formation; allowed units are permutations of energy (J, kJ, cal, or kcal) and temperature (K, C, F, or R)\n";
input += "# Heat capacity at 300, 400, 500, 600, 800, 1000, and 1500 K\n";
input += "J/mol " + Double.toString(spec.calculateH(stdTemp) * 4184) + "\n";
input += "J/mol*K " + Double.toString(spec.calculateS(stdTemp) * 4.184) + "\n";
input += "7 J/mol*K\n";
input += Double.toString(spec.calculateCp(new Temperature(300, "K")) * 4.184) + "\n";
input += Double.toString(spec.calculateCp(new Temperature(400, "K")) * 4.184) + "\n";
input += Double.toString(spec.calculateCp(new Temperature(500, "K")) * 4.184) + "\n";
input += Double.toString(spec.calculateCp(new Temperature(600, "K")) * 4.184) + "\n";
input += Double.toString(spec.calculateCp(new Temperature(800, "K")) * 4.184) + "\n";
input += Double.toString(spec.calculateCp(new Temperature(1000, "K")) * 4.184) + "\n";
input += Double.toString(spec.calculateCp(new Temperature(1500, "K")) * 4.184) + "\n";
input += "# Species gas parameters\n";
input += "# Molecular weight; allowed units are g/mol or u\n";
input += "# Lennard-Jones sigma parameter; allowed units are m or A\n";
input += "# Lennard-Jones epsilon parameter; allowed units are J or K\n";
input += "u " + Double.toString(spec.getMolecularWeight()) + "\n";
input += "m " + Double.toString(spec.getLJ().getSigma() * 1e-10) + "\n";
input += "J " + Double.toString(spec.getLJ().getEpsilon() * 1.380665e-23) + "\n";
input += "# Harmonic oscillators; allowed units are Hz and cm^-1\n";
SpectroscopicData data = spec.getSpectroscopicData();
input += Integer.toString(data.getVibrationCount()) + " cm^-1\n";
for (int j = 0; j < data.getVibrationCount(); j++)
input += Double.toString(data.getVibration(j)) + "\n";
input += "# Rigid rotors; allowed units are Hz and cm^-1\n";
input += Integer.toString(data.getRotationCount()) + " cm^-1\n";
for (int j = 0; j < data.getRotationCount(); j++)
input += Double.toString(data.getRotation(j));
input += "# Hindered rotor frequencies and barriers\n";
input += Integer.toString(data.getHinderedCount()) + " cm^-1\n";
for (int j = 0; j < data.getHinderedCount(); j++)
input += Double.toString(data.getHinderedFrequency(j)) + "\n";
input += Integer.toString(data.getHinderedCount()) + " cm^-1\n";
for (int j = 0; j < data.getHinderedCount(); j++)
input += Double.toString(data.getHinderedBarrier(j)) + "\n";
input += "# Symmetry number\n";
input += Integer.toString(spec.getChemGraph().calculateSymmetryNumber()) + "\n";
input += "\n";
}
input += "# The number of isomers in the network (minimum of 2)\n";
input += Integer.toString(isomerList.size()) + "\n";
input += "\n";
for (int i = 0; i < isomerList.size(); i++) {
PDepIsomer isomer = isomerList.get(i);
input += "# The number and identifiers of each species in the isomer\n";
input += Integer.toString(isomer.getNumSpecies());
for (int j = 0; j < isomer.getNumSpecies(); j++) {
Species spec = isomer.getSpecies(j);
input += " " + spec.getName() + "(" + Integer.toString(spec.getID()) + ")";
}
input += "\n\n";
}
input += "# The number of reactions in the network (minimum of 2)\n";
input += Integer.toString(pathReactionList.size()) + "\n";
input += "\n";
for (int i = 0; i < pathReactionList.size(); i++) {
PDepReaction rxn = pathReactionList.get(i);
double A = 0.0, Ea = 0.0, n = 0.0;
if (rxn.isForward()) {
Kinetics[] k_array = rxn.getKinetics();
Kinetics kin = computeKUsingLeastSquares(k_array);
A = kin.getAValue();
n = kin.getNValue();
Ea = kin.getEValue();
// A = rxn.getKinetics().getAValue();
// Ea = rxn.getKinetics().getEValue();
// n = rxn.getKinetics().getNValue();
}
else {
((Reaction) rxn).generateReverseReaction();
Kinetics[] k_array = ((Reaction)rxn).getFittedReverseKinetics();
Kinetics kin = computeKUsingLeastSquares(k_array);
// Kinetics kin = ((Reaction) rxn).getFittedReverseKinetics();
A = kin.getAValue();
Ea = kin.getEValue();
n = kin.getNValue();
}
input += "# The reaction equation, in the form A + B --> C + D\n";
input += rxn.toString() + "\n";
input += "# Indices of the reactant and product isomers, starting with 1\n";
input += Integer.toString(isomerList.indexOf(rxn.getReactant()) + 1) + " ";
input += Integer.toString(isomerList.indexOf(rxn.getProduct()) + 1) + "\n";
input += "# Ground-state energy; allowed units are J/mol, kJ/mol, cal/mol, kcal/mol, or cm^-1\n";
if (Ea < 0.0)
input += "J/mol " + Double.toString((rxn.getReactant().calculateH(stdTemp)) * 4184) + "\n";
else
input += "J/mol " + Double.toString((Ea + rxn.getReactant().calculateH(stdTemp)) * 4184) + "\n";
input += "# High-pressure-limit kinetics model k(T):\n";
input += "# Option 1: Arrhenius\n";
input += "# Arrhenius preexponential factor; allowed units are combinations of volume {m^3, L, or cm^3} and time {s^-1}\n";
input += "# Arrhenius activation energy; allowed units are J/mol, kJ/mol, cal/mol, or kcal/mol\n";
input += "# Arrhenius temperature exponent\n";
input += "Arrhenius\n";
if (rxn.getReactant().isUnimolecular())
input += "s^-1 " + Double.toString(A) + "\n";
else if (rxn.getReactant().isMultimolecular())
input += "cm^3/mol*s " + Double.toString(A) + "\n";
input += "J/mol " + Double.toString(Ea * 4184) + "\n";
input += Double.toString(n) + "\n";
input += "\n";
}
}
catch(IndexOutOfBoundsException e) {
System.out.println("Error: IndexOutOfBoundsException thrown.");
e.printStackTrace(System.out);
}
catch(Exception e) {
System.out.println(e.getMessage());
e.printStackTrace(System.out);
}
return input;
}
/**
* Parses one meaningful line from a FAME output buffer.
*/
public String readMeaningfulLine(BufferedReader br) throws IOException {
String str = "";
boolean found = false;
while (!found) {
str = br.readLine().trim();
found = !(str.length() == 0 || str.startsWith("#"));
}
return str;
}
/**
* Parses a FAME output file and updates the reaction network and system
* accordingly.
* @param pdn The pressure-dependent reaction network of interest
* @param rxnSystem The reaction system of interest
* @param cerm The current core/edge reaction model
* @param isomerList The set of isomers in the network
*/
public boolean parseOutputString(String output, PDepNetwork pdn,
ReactionSystem rxnSystem, CoreEdgeReactionModel cerm,
LinkedList<PDepIsomer> isomerList) throws PDepException {
String dir = System.getProperty("RMG.workingDirectory");
double Tmin = 0, Tmax = 0, Pmin = 0, Pmax = 0;
// JWA January 28 2010
// Clear the included reactions from the last successful fame execution
LinkedList<PDepReaction> netReactionList = pdn.getNetReactions();
netReactionList.clear();
// Also need to clear the nonincluded reactions - we will regenerate them
// based on the new output from fame
pdn.getNonincludedReactions().clear();
// Below we are going to use netReactionList to temporarily store all
// reactions, both included and nonincluded, and will then sort them
// into included and nonincluded
boolean ignoredARate = false;
/*
* MRH 26Feb2010:
* Checking whether pdep rates exceed the high-P-limit
*
* This boolean reflects whether all pdep rates are below the high-P-limit.
* The variable is initialized to true for each call (in hope of avoiding
* any infinite loop scenarios). If any of the pdep rates exceed the
* high-P-limit, the boolean is changed to false (see code below)
*/
pdepRatesOK = true;
try {
BufferedReader br = new BufferedReader(new StringReader(output));
String str = "";
StringTokenizer tkn;
String method = readMeaningfulLine(br);
str = readMeaningfulLine(br);
tkn = new StringTokenizer(str);
int numTemp = Integer.parseInt(tkn.nextToken());
tkn.nextToken();
Tmin = Double.parseDouble(tkn.nextToken());
for (int i = 0; i < numTemp-2; i++) tkn.nextToken();
Tmax = Double.parseDouble(tkn.nextToken());
str = readMeaningfulLine(br);
tkn = new StringTokenizer(str);
int numPress = Integer.parseInt(tkn.nextToken());
tkn.nextToken();
Pmin = Double.parseDouble(tkn.nextToken());
for (int i = 0; i < numPress-2; i++) tkn.nextToken();
// Added by MRH on 10Feb2010 to handle the case where user only specifies one pressure
if (numPress == 1) Pmax = Pmin;
else Pmax = Double.parseDouble(tkn.nextToken());
str = readMeaningfulLine(br);
tkn = new StringTokenizer(str);
String model = tkn.nextToken();
int numChebT = 0, numChebP = 0;
if (model.toLowerCase().contains("chebyshev")) {
numChebT = Integer.parseInt(tkn.nextToken());
numChebP = Integer.parseInt(tkn.nextToken());
}
str = readMeaningfulLine(br);
int numSpecies = Integer.parseInt(str);
str = readMeaningfulLine(br);
int numIsomers = Integer.parseInt(str);
str = readMeaningfulLine(br);
int numReactions = Integer.parseInt(str);
str = readMeaningfulLine(br);
int numKinetics = Integer.parseInt(str);
for (int i = 0; i < numKinetics; i++) {
double[][] rates = new double[numTemp][numPress];
double[][] chebyshev = null;
PDepArrheniusKinetics pDepArrhenius = null;
// Reactant and product isomers
str = readMeaningfulLine(br);
tkn = new StringTokenizer(str);
int reac = Integer.parseInt(tkn.nextToken()) - 1;
int prod = Integer.parseInt(tkn.nextToken()) - 1;
// Table of phenomenological rate coefficients
boolean valid = true;
str = readMeaningfulLine(br); // First row is list of pressures
for (int t = 0; t < numTemp; t++) {
str = readMeaningfulLine(br);
tkn = new StringTokenizer(str);
tkn.nextToken();
for (int p = 0; p < numPress; p++) {
rates[t][p] = Double.parseDouble(tkn.nextToken());
if (rates[t][p] < 0 ||
Double.isNaN(rates[t][p]) ||
Double.isInfinite(rates[t][p]))
valid = false;
}
}
PDepRateConstant pDepRate = new PDepRateConstant(rates);
// Chebyshev interpolation model
if (model.toLowerCase().contains("chebyshev")) {
chebyshev = new double[numChebT][numChebP];
for (int t = 0; t < numChebT; t++) {
str = readMeaningfulLine(br);
tkn = new StringTokenizer(str);
for (int p = 0; p < numChebP; p++) {
chebyshev[t][p] = Double.parseDouble(tkn.nextToken());
}
}
pDepRate.setChebyshev(chebyshev);
}
// PDepArrhenius interpolation model
else if (model.toLowerCase().contains("pdeparrhenius")) {
pDepArrhenius = new PDepArrheniusKinetics(numPress);
for (int p = 0; p < numPress; p++) {
str = readMeaningfulLine(br);
tkn = new StringTokenizer(str);
tkn.nextToken();
UncertainDouble A = new UncertainDouble(Double.parseDouble(tkn.nextToken()), 0.0, "A");
UncertainDouble Ea = new UncertainDouble(Double.parseDouble(tkn.nextToken()) / 4184.0, 0.0, "A");
UncertainDouble n = new UncertainDouble(Double.parseDouble(tkn.nextToken()), 0.0, "A");
String Trange = Double.toString(Tmin) + "-" + Double.toString(Tmax) + " K";
String Prange = Double.toString(Pmin / 1.0e5) + "-" + Double.toString(Pmax / 1.0e5) + " bar";
ArrheniusKinetics kinetics = new ArrheniusKinetics(A, n, Ea, Trange, 0, "Result of FAME calculation", "Prange = " + Prange);
pDepArrhenius.setKinetics(p, pressures[p], kinetics);
}
pDepRate.setPDepArrheniusKinetics(pDepArrhenius);
}
// If the fitted rate coefficient is not valid, then don't add the net reaction
if (!valid) {
ignoredARate = true;
continue;
}
// Initialize net reaction
PDepIsomer reactant = isomerList.get(reac);
PDepIsomer product = isomerList.get(prod);
PDepReaction rxn = new PDepReaction(reactant, product, pDepRate);
/*
* MRH 26Feb2010:
* Checking whether pdep rates exceed the high-P-limit
*
* We grab all of the reactions in the pathReactionList. These are the
* RMG-generated reactions (not chemically-activated reactions) and thus
* have "natural" high-P-limit kinetics.
* If the current PDepReaction "rxn"'s structure matches one of the structures
* of the PDepReactions located in the pathReactionList, we compare the high-P-limit
* kinetics of the pathReactionList (these values either come from the RMG database
* or are "fitted" parameters, based on the reverse kinetics + equilibrium constant)
* with the k(T,P_max) for each T in the "temperatures" array. NOTE: Not every "rxn"
* will have a match in the pathReactionList.
* If the pdep rate is greater than 2x the high-P-limit, we consider this to be different.
* If the number of grains is less than 1000, we set the pdepRatesOK boolean to false,
* so that another fame calculation will ensue
* If the number of grains exceeds 1000, we continue on with the simulation, but alert the
* user of the discrepancy.
*
* The value of 2 was somewhat randomly chosen by MRH.
* For a toy case of tBuOH pyrolysis (with 1e-6 reaction time and 0.9 error tolerance):
* Before code addition: iC4H8/H2O final concentration = 7.830282E-10, run time < 1 min
* 2x : iC4H8/H2O final concentration = 6.838976E-10, run time ~ 2 min
* 1.5x : iC4H8/H2O final concentration = 6.555548E-10, run time ~ 4 min
* 1.1x : iC4H8/H2O final concentration = 6.555548E-10, run time ~ 10 min
*
* The value of 2 (for the toy model) seems to be a good balance between speed and accuracy
*
* P.S. Want to keep the name fame (fast approximate me) instead of having to change to
* smame (slow more accurate me). ;)
*
*/
LinkedList pathReactionList = pdn.getPathReactions();
for (int HighPRxNum = 0; HighPRxNum < pathReactionList.size(); HighPRxNum++) {
PDepReaction rxnWHighPLimit = (PDepReaction)pathReactionList.get(HighPRxNum);
if (rxn.getStructure().equals(rxnWHighPLimit.getStructure())) {
double A = 0.0, Ea = 0.0, n = 0.0;
if (rxnWHighPLimit.isForward()) {
Kinetics[] k_array = rxnWHighPLimit.getKinetics();
Kinetics kin = computeKUsingLeastSquares(k_array);
A = kin.getAValue();
Ea = kin.getEValue();
n = kin.getNValue();
// While I'm here, and know which reaction was the High-P limit, set the comment in the P-dep reaction
- rxn.setComments("High-P Limit: " + kin.getSource().toString() + "\n" + kin.getComment().toString() );
+ rxn.setComments("High-P Limit: " + kin.getSource().toString() + " " + kin.getComment().toString() );
}
else {
Kinetics[] k_array = rxnWHighPLimit.getFittedReverseKinetics();
Kinetics kin = computeKUsingLeastSquares(k_array);
A = kin.getAValue();
Ea = kin.getEValue();
n = kin.getNValue();
// While I'm here, and know which reaction was the High-P limit, set the comment in the P-dep reaction
Kinetics[] fwd_kin = rxnWHighPLimit.getKinetics();
String commentsForForwardKinetics = "";
if (fwd_kin.length > 1) commentsForForwardKinetics += "Summation of kinetics:\n!";
for (int numKs=0; numKs<fwd_kin.length; ++numKs) {
commentsForForwardKinetics += "High-P Limit Reverse: " + fwd_kin[numKs].getSource().toString() +fwd_kin[numKs].getComment().toString();
if (numKs != fwd_kin.length-1) commentsForForwardKinetics += "\n!";
}
rxn.setComments(commentsForForwardKinetics);
}
if (ReactionModelGenerator.rerunFameWithAdditionalGrains()) {
double[][] all_ks = rxn.getPDepRate().getRateConstants();
for (int numTemps=0; numTemps<temperatures.length; numTemps++) {
double T = temperatures[numTemps].getK();
double k_highPlimit = A * Math.pow(T,n) * Math.exp(-Ea/GasConstant.getKcalMolK()/T);
if (all_ks[numTemps][pressures.length-1] > 2*k_highPlimit) {
if (numGrains > 1000) {
System.out.println("Pressure-dependent rate exceeds high-P-limit rate: " +
"Number of grains already exceeds 1000. Continuing RMG simulation " +
"with results from current fame run.");
break; // No need to continue checking the rates for this one reaction
}
else {
System.out.println("Pressure-dependent rate exceeds high-P-limit rate: " +
"Re-running fame with additional number of grains");
pdepRatesOK = false;
return false;
}
}
}
//break; // Why did MRH put this break here?
}
}
}
// Add net reaction to list
netReactionList.add(rxn);
}
// Close file when finished
br.close();
// Set reverse reactions
int i = 0;
while (i < netReactionList.size()) {
PDepReaction rxn1 = netReactionList.get(i);
if (rxn1.getReverseReaction() == null) {
boolean found = false;
for (int j = 0; j < netReactionList.size(); j++) {
PDepReaction rxn2 = netReactionList.get(j);
if (rxn1.getReactant().equals(rxn2.getProduct()) &&
rxn2.getReactant().equals(rxn1.getProduct())) {
rxn1.setReverseReaction(rxn2);
rxn2.setReverseReaction(rxn1);
netReactionList.remove(rxn2);
found = true;
break;
}
}
if (!found)
throw new PDepException("Unable to identify reverse reaction for " + rxn1.toString() + " after FAME calculation.");
}
else
i++;
}
// Update reaction lists (sort into included and nonincluded)
pdn.updateReactionLists(cerm);
}
catch (PDepException e) {
System.out.println(pdn);
System.out.println(e.getMessage());
e.printStackTrace();
throw new PDepException("Unable to parse FAME output file.");
}
catch(IOException e) {
System.out.println("Error: Unable to read from file \"fame_output.txt\".");
System.exit(0);
}
return true;
}
/**
* Determines the maximum energy grain to use in the calculation. The
* maximum energy grain is chosen to be 25 * R * T above the highest
* potential energy on the potential energy surface, which hopefully will
* capture the majority of the equilibrium distributions even at the
* high temperature end of the calculation.
*
* @param uniIsomers The set of unimolecular isomers in the network
* @param multiIsomers The set of multimolecular isomers in the network
* @param T The temperature of the calculation in K
* @return The maximum grain energy in kJ/mol
*/
private double getGrainMaxEnergy(LinkedList<PDepIsomer> isomerList, double T) {
double Emax = 0.0;
Temperature stdTemp = new Temperature(298, "K");
for (int i = 0; i < isomerList.size(); i++) {
PDepIsomer isomer = isomerList.get(i);
double E = isomer.calculateH(stdTemp);
if (E > Emax)
Emax = E;
}
Emax *= 4.184;
//Emax += 100 * 0.008314 * T;
Emax += 50 * 0.008314 * T;
// Round up to nearest ten kJ/mol
return Math.ceil(Emax / 10) * 10.0; // [=] kJ/mol
}
/**
* Determines the minimum energy grain to use in the calculation. The
* maximum energy grain is chosen to be at or just below the energy of the
* lowest energy isomer in the system.
*
* @param uniIsomers The set of unimolecular isomers in the network
* @param multiIsomers The set of multimolecular isomers in the network
* @return The minimum grain energy in kJ/mol
*/
private double getGrainMinEnergy(LinkedList<PDepIsomer> isomerList) {
double Emin = 1000000.0;
Temperature stdTemp = new Temperature(298, "K");
for (int i = 0; i < isomerList.size(); i++) {
PDepIsomer isomer = isomerList.get(i);
double E = isomer.calculateH(stdTemp);
if (E < Emin)
Emin = E;
}
Emin *= 4.184;
// Round down to nearest ten kJ/mol
return Math.floor(Emin / 10) * 10.0; // [=] kJ/mol
}
/**
* Determines a suitable grain size for the calculation. Too small a grain
* size will cause the simulation to take a very long time to conduct; too
* large a grain size will cause the simulation results to not be very
* precise. The choice is hopefully made such that the grains get larger
* as the system does, so as to not get completely bogged down in the
* larger networks.
*
* @param grainMinEnergy The minimum energy grain in kJ/mol
* @param grainMaxEnergy The maximum energy grain in kJ/mol
* @param numUniWells The number of unimolecular isomers in the network.
* @return
*/
private double getGrainSize(double grainMinEnergy, double grainMaxEnergy, int numUniWells) {
if (numUniWells < 5)
return (grainMaxEnergy - grainMinEnergy) / 200;
else if (numUniWells < 10)
return (grainMaxEnergy - grainMinEnergy) / 100;
else if (numUniWells < 20)
return (grainMaxEnergy - grainMinEnergy) / 50;
else
return (grainMaxEnergy - grainMinEnergy) / 20;
}
/**
* Creates an empty file on the hard disk for the FORTRAN executable to
* use to write its output. If this file is not created, the FORTRAN
* executable will write to the file 'fort.2', which is checked by the
* readOutputFile() function but still discouraged.
*/
public void touchOutputFile() {
try {
File output = new File("fame/fame_output.txt");
if (output.exists())
output.delete();
output.createNewFile();
}
catch(IOException e) {
System.out.println("Error: Unable to touch file \"fame_output.txt\".");
System.out.println(e.getMessage());
System.exit(0);
}
catch(Exception e) {
System.out.println(e.getMessage());
}
}
/**
* Returns the mode as a string suitable for writing the FAME input file.
* @return The mode as a string suitable for writing the FAME input file.
*/
public String getModeString() {
if (mode == Mode.STRONGCOLLISION)
return "ModifiedStrongCollision";
else if (mode == Mode.RESERVOIRSTATE)
return "ReservoirState";
else
return "";
}
public static Temperature[] getTemperatures() {
return temperatures;
}
public static void setTemperatures(Temperature[] temps) {
temperatures = temps;
}
public static Pressure[] getPressures() {
return pressures;
}
public static void setPressures(Pressure[] press) {
pressures = press;
}
public static void setNumTBasisFuncs(int n) {
numTBasisFuncs = n;
}
public static void setNumPBasisFuncs(int m) {
numPBasisFuncs = m;
}
public static Kinetics computeKUsingLeastSquares(Kinetics[] k_array) {
/*
* MRH 24MAR2010:
* If the reaction has more than one set of Arrhenius kinetics,
* sum all kinetics and re-fit for a single set of Arrhenius kinetics
*/
Kinetics k = null;
if (k_array.length > 1) {
double[] T = new double[5];
T[0] = 300; T[1] = 600; T[2] = 900; T[3] = 1200; T[4] = 1500;
double[] k_total = new double[5];
for (int numKinetics=0; numKinetics<k_array.length; ++numKinetics) {
for (int numTemperatures=0; numTemperatures<T.length; ++numTemperatures) {
k_total[numTemperatures] += k_array[numKinetics].getAValue() *
Math.pow(T[numTemperatures], k_array[numKinetics].getNValue()) *
Math.exp(-k_array[numKinetics].getEValue()/GasConstant.getKcalMolK()/T[numTemperatures]);
}
}
// Construct matrix X and vector y
double[][] y = new double[k_total.length][1];
double[][] X = new double[k_total.length][3];
for (int i=0; i<5; i++) {
y[i][0] = Math.log(k_total[i]);
X[i][0] = 1;
X[i][1] = Math.log(T[i]);
X[i][2] = 1/T[i];
}
// Solve least-squares problem using inv(XT*X)*(XT*y)
Matrix X_matrix = new Matrix(X);
Matrix y_matrix = new Matrix(y);
Matrix b_matrix = X_matrix.solve(y_matrix);
UncertainDouble uA = new UncertainDouble(Math.exp(b_matrix.get(0,0)),0.0,"Adding");
UncertainDouble un = new UncertainDouble(b_matrix.get(1,0),0.0,"Adding");
UncertainDouble uE = new UncertainDouble(-GasConstant.getKcalMolK()*b_matrix.get(2,0),0.0,"Adding");
String commentsForFittedKinetics = "";
for (int numKs=0; numKs<k_array.length; ++numKs) {
commentsForFittedKinetics += "!" + k_array[numKs].getSource().toString();
if (k_array[numKs].getComment() != null) commentsForFittedKinetics += k_array[numKs].getComment().toString();
if (numKs != k_array.length-1) commentsForFittedKinetics += "\n";
}
k = new ArrheniusKinetics(uA,un,uE,"300-1500K",5,"Summation of kinetics:",commentsForFittedKinetics);
} else {
k = k_array[0];
}
return k;
}
public static int getNumTBasisFuncs() {
return numTBasisFuncs;
}
public static int getNumPBasisFuncs() {
return numPBasisFuncs;
}
}
| true | true | public boolean parseOutputString(String output, PDepNetwork pdn,
ReactionSystem rxnSystem, CoreEdgeReactionModel cerm,
LinkedList<PDepIsomer> isomerList) throws PDepException {
String dir = System.getProperty("RMG.workingDirectory");
double Tmin = 0, Tmax = 0, Pmin = 0, Pmax = 0;
// JWA January 28 2010
// Clear the included reactions from the last successful fame execution
LinkedList<PDepReaction> netReactionList = pdn.getNetReactions();
netReactionList.clear();
// Also need to clear the nonincluded reactions - we will regenerate them
// based on the new output from fame
pdn.getNonincludedReactions().clear();
// Below we are going to use netReactionList to temporarily store all
// reactions, both included and nonincluded, and will then sort them
// into included and nonincluded
boolean ignoredARate = false;
/*
* MRH 26Feb2010:
* Checking whether pdep rates exceed the high-P-limit
*
* This boolean reflects whether all pdep rates are below the high-P-limit.
* The variable is initialized to true for each call (in hope of avoiding
* any infinite loop scenarios). If any of the pdep rates exceed the
* high-P-limit, the boolean is changed to false (see code below)
*/
pdepRatesOK = true;
try {
BufferedReader br = new BufferedReader(new StringReader(output));
String str = "";
StringTokenizer tkn;
String method = readMeaningfulLine(br);
str = readMeaningfulLine(br);
tkn = new StringTokenizer(str);
int numTemp = Integer.parseInt(tkn.nextToken());
tkn.nextToken();
Tmin = Double.parseDouble(tkn.nextToken());
for (int i = 0; i < numTemp-2; i++) tkn.nextToken();
Tmax = Double.parseDouble(tkn.nextToken());
str = readMeaningfulLine(br);
tkn = new StringTokenizer(str);
int numPress = Integer.parseInt(tkn.nextToken());
tkn.nextToken();
Pmin = Double.parseDouble(tkn.nextToken());
for (int i = 0; i < numPress-2; i++) tkn.nextToken();
// Added by MRH on 10Feb2010 to handle the case where user only specifies one pressure
if (numPress == 1) Pmax = Pmin;
else Pmax = Double.parseDouble(tkn.nextToken());
str = readMeaningfulLine(br);
tkn = new StringTokenizer(str);
String model = tkn.nextToken();
int numChebT = 0, numChebP = 0;
if (model.toLowerCase().contains("chebyshev")) {
numChebT = Integer.parseInt(tkn.nextToken());
numChebP = Integer.parseInt(tkn.nextToken());
}
str = readMeaningfulLine(br);
int numSpecies = Integer.parseInt(str);
str = readMeaningfulLine(br);
int numIsomers = Integer.parseInt(str);
str = readMeaningfulLine(br);
int numReactions = Integer.parseInt(str);
str = readMeaningfulLine(br);
int numKinetics = Integer.parseInt(str);
for (int i = 0; i < numKinetics; i++) {
double[][] rates = new double[numTemp][numPress];
double[][] chebyshev = null;
PDepArrheniusKinetics pDepArrhenius = null;
// Reactant and product isomers
str = readMeaningfulLine(br);
tkn = new StringTokenizer(str);
int reac = Integer.parseInt(tkn.nextToken()) - 1;
int prod = Integer.parseInt(tkn.nextToken()) - 1;
// Table of phenomenological rate coefficients
boolean valid = true;
str = readMeaningfulLine(br); // First row is list of pressures
for (int t = 0; t < numTemp; t++) {
str = readMeaningfulLine(br);
tkn = new StringTokenizer(str);
tkn.nextToken();
for (int p = 0; p < numPress; p++) {
rates[t][p] = Double.parseDouble(tkn.nextToken());
if (rates[t][p] < 0 ||
Double.isNaN(rates[t][p]) ||
Double.isInfinite(rates[t][p]))
valid = false;
}
}
PDepRateConstant pDepRate = new PDepRateConstant(rates);
// Chebyshev interpolation model
if (model.toLowerCase().contains("chebyshev")) {
chebyshev = new double[numChebT][numChebP];
for (int t = 0; t < numChebT; t++) {
str = readMeaningfulLine(br);
tkn = new StringTokenizer(str);
for (int p = 0; p < numChebP; p++) {
chebyshev[t][p] = Double.parseDouble(tkn.nextToken());
}
}
pDepRate.setChebyshev(chebyshev);
}
// PDepArrhenius interpolation model
else if (model.toLowerCase().contains("pdeparrhenius")) {
pDepArrhenius = new PDepArrheniusKinetics(numPress);
for (int p = 0; p < numPress; p++) {
str = readMeaningfulLine(br);
tkn = new StringTokenizer(str);
tkn.nextToken();
UncertainDouble A = new UncertainDouble(Double.parseDouble(tkn.nextToken()), 0.0, "A");
UncertainDouble Ea = new UncertainDouble(Double.parseDouble(tkn.nextToken()) / 4184.0, 0.0, "A");
UncertainDouble n = new UncertainDouble(Double.parseDouble(tkn.nextToken()), 0.0, "A");
String Trange = Double.toString(Tmin) + "-" + Double.toString(Tmax) + " K";
String Prange = Double.toString(Pmin / 1.0e5) + "-" + Double.toString(Pmax / 1.0e5) + " bar";
ArrheniusKinetics kinetics = new ArrheniusKinetics(A, n, Ea, Trange, 0, "Result of FAME calculation", "Prange = " + Prange);
pDepArrhenius.setKinetics(p, pressures[p], kinetics);
}
pDepRate.setPDepArrheniusKinetics(pDepArrhenius);
}
// If the fitted rate coefficient is not valid, then don't add the net reaction
if (!valid) {
ignoredARate = true;
continue;
}
// Initialize net reaction
PDepIsomer reactant = isomerList.get(reac);
PDepIsomer product = isomerList.get(prod);
PDepReaction rxn = new PDepReaction(reactant, product, pDepRate);
/*
* MRH 26Feb2010:
* Checking whether pdep rates exceed the high-P-limit
*
* We grab all of the reactions in the pathReactionList. These are the
* RMG-generated reactions (not chemically-activated reactions) and thus
* have "natural" high-P-limit kinetics.
* If the current PDepReaction "rxn"'s structure matches one of the structures
* of the PDepReactions located in the pathReactionList, we compare the high-P-limit
* kinetics of the pathReactionList (these values either come from the RMG database
* or are "fitted" parameters, based on the reverse kinetics + equilibrium constant)
* with the k(T,P_max) for each T in the "temperatures" array. NOTE: Not every "rxn"
* will have a match in the pathReactionList.
* If the pdep rate is greater than 2x the high-P-limit, we consider this to be different.
* If the number of grains is less than 1000, we set the pdepRatesOK boolean to false,
* so that another fame calculation will ensue
* If the number of grains exceeds 1000, we continue on with the simulation, but alert the
* user of the discrepancy.
*
* The value of 2 was somewhat randomly chosen by MRH.
* For a toy case of tBuOH pyrolysis (with 1e-6 reaction time and 0.9 error tolerance):
* Before code addition: iC4H8/H2O final concentration = 7.830282E-10, run time < 1 min
* 2x : iC4H8/H2O final concentration = 6.838976E-10, run time ~ 2 min
* 1.5x : iC4H8/H2O final concentration = 6.555548E-10, run time ~ 4 min
* 1.1x : iC4H8/H2O final concentration = 6.555548E-10, run time ~ 10 min
*
* The value of 2 (for the toy model) seems to be a good balance between speed and accuracy
*
* P.S. Want to keep the name fame (fast approximate me) instead of having to change to
* smame (slow more accurate me). ;)
*
*/
LinkedList pathReactionList = pdn.getPathReactions();
for (int HighPRxNum = 0; HighPRxNum < pathReactionList.size(); HighPRxNum++) {
PDepReaction rxnWHighPLimit = (PDepReaction)pathReactionList.get(HighPRxNum);
if (rxn.getStructure().equals(rxnWHighPLimit.getStructure())) {
double A = 0.0, Ea = 0.0, n = 0.0;
if (rxnWHighPLimit.isForward()) {
Kinetics[] k_array = rxnWHighPLimit.getKinetics();
Kinetics kin = computeKUsingLeastSquares(k_array);
A = kin.getAValue();
Ea = kin.getEValue();
n = kin.getNValue();
// While I'm here, and know which reaction was the High-P limit, set the comment in the P-dep reaction
rxn.setComments("High-P Limit: " + kin.getSource().toString() + "\n" + kin.getComment().toString() );
}
else {
Kinetics[] k_array = rxnWHighPLimit.getFittedReverseKinetics();
Kinetics kin = computeKUsingLeastSquares(k_array);
A = kin.getAValue();
Ea = kin.getEValue();
n = kin.getNValue();
// While I'm here, and know which reaction was the High-P limit, set the comment in the P-dep reaction
Kinetics[] fwd_kin = rxnWHighPLimit.getKinetics();
String commentsForForwardKinetics = "";
if (fwd_kin.length > 1) commentsForForwardKinetics += "Summation of kinetics:\n!";
for (int numKs=0; numKs<fwd_kin.length; ++numKs) {
commentsForForwardKinetics += "High-P Limit Reverse: " + fwd_kin[numKs].getSource().toString() +fwd_kin[numKs].getComment().toString();
if (numKs != fwd_kin.length-1) commentsForForwardKinetics += "\n!";
}
rxn.setComments(commentsForForwardKinetics);
}
if (ReactionModelGenerator.rerunFameWithAdditionalGrains()) {
double[][] all_ks = rxn.getPDepRate().getRateConstants();
for (int numTemps=0; numTemps<temperatures.length; numTemps++) {
double T = temperatures[numTemps].getK();
double k_highPlimit = A * Math.pow(T,n) * Math.exp(-Ea/GasConstant.getKcalMolK()/T);
if (all_ks[numTemps][pressures.length-1] > 2*k_highPlimit) {
if (numGrains > 1000) {
System.out.println("Pressure-dependent rate exceeds high-P-limit rate: " +
"Number of grains already exceeds 1000. Continuing RMG simulation " +
"with results from current fame run.");
break; // No need to continue checking the rates for this one reaction
}
else {
System.out.println("Pressure-dependent rate exceeds high-P-limit rate: " +
"Re-running fame with additional number of grains");
pdepRatesOK = false;
return false;
}
}
}
//break; // Why did MRH put this break here?
}
}
}
// Add net reaction to list
netReactionList.add(rxn);
}
// Close file when finished
br.close();
// Set reverse reactions
int i = 0;
while (i < netReactionList.size()) {
PDepReaction rxn1 = netReactionList.get(i);
if (rxn1.getReverseReaction() == null) {
boolean found = false;
for (int j = 0; j < netReactionList.size(); j++) {
PDepReaction rxn2 = netReactionList.get(j);
if (rxn1.getReactant().equals(rxn2.getProduct()) &&
rxn2.getReactant().equals(rxn1.getProduct())) {
rxn1.setReverseReaction(rxn2);
rxn2.setReverseReaction(rxn1);
netReactionList.remove(rxn2);
found = true;
break;
}
}
if (!found)
throw new PDepException("Unable to identify reverse reaction for " + rxn1.toString() + " after FAME calculation.");
}
else
i++;
}
// Update reaction lists (sort into included and nonincluded)
pdn.updateReactionLists(cerm);
}
catch (PDepException e) {
System.out.println(pdn);
System.out.println(e.getMessage());
e.printStackTrace();
throw new PDepException("Unable to parse FAME output file.");
}
catch(IOException e) {
System.out.println("Error: Unable to read from file \"fame_output.txt\".");
System.exit(0);
}
return true;
}
| public boolean parseOutputString(String output, PDepNetwork pdn,
ReactionSystem rxnSystem, CoreEdgeReactionModel cerm,
LinkedList<PDepIsomer> isomerList) throws PDepException {
String dir = System.getProperty("RMG.workingDirectory");
double Tmin = 0, Tmax = 0, Pmin = 0, Pmax = 0;
// JWA January 28 2010
// Clear the included reactions from the last successful fame execution
LinkedList<PDepReaction> netReactionList = pdn.getNetReactions();
netReactionList.clear();
// Also need to clear the nonincluded reactions - we will regenerate them
// based on the new output from fame
pdn.getNonincludedReactions().clear();
// Below we are going to use netReactionList to temporarily store all
// reactions, both included and nonincluded, and will then sort them
// into included and nonincluded
boolean ignoredARate = false;
/*
* MRH 26Feb2010:
* Checking whether pdep rates exceed the high-P-limit
*
* This boolean reflects whether all pdep rates are below the high-P-limit.
* The variable is initialized to true for each call (in hope of avoiding
* any infinite loop scenarios). If any of the pdep rates exceed the
* high-P-limit, the boolean is changed to false (see code below)
*/
pdepRatesOK = true;
try {
BufferedReader br = new BufferedReader(new StringReader(output));
String str = "";
StringTokenizer tkn;
String method = readMeaningfulLine(br);
str = readMeaningfulLine(br);
tkn = new StringTokenizer(str);
int numTemp = Integer.parseInt(tkn.nextToken());
tkn.nextToken();
Tmin = Double.parseDouble(tkn.nextToken());
for (int i = 0; i < numTemp-2; i++) tkn.nextToken();
Tmax = Double.parseDouble(tkn.nextToken());
str = readMeaningfulLine(br);
tkn = new StringTokenizer(str);
int numPress = Integer.parseInt(tkn.nextToken());
tkn.nextToken();
Pmin = Double.parseDouble(tkn.nextToken());
for (int i = 0; i < numPress-2; i++) tkn.nextToken();
// Added by MRH on 10Feb2010 to handle the case where user only specifies one pressure
if (numPress == 1) Pmax = Pmin;
else Pmax = Double.parseDouble(tkn.nextToken());
str = readMeaningfulLine(br);
tkn = new StringTokenizer(str);
String model = tkn.nextToken();
int numChebT = 0, numChebP = 0;
if (model.toLowerCase().contains("chebyshev")) {
numChebT = Integer.parseInt(tkn.nextToken());
numChebP = Integer.parseInt(tkn.nextToken());
}
str = readMeaningfulLine(br);
int numSpecies = Integer.parseInt(str);
str = readMeaningfulLine(br);
int numIsomers = Integer.parseInt(str);
str = readMeaningfulLine(br);
int numReactions = Integer.parseInt(str);
str = readMeaningfulLine(br);
int numKinetics = Integer.parseInt(str);
for (int i = 0; i < numKinetics; i++) {
double[][] rates = new double[numTemp][numPress];
double[][] chebyshev = null;
PDepArrheniusKinetics pDepArrhenius = null;
// Reactant and product isomers
str = readMeaningfulLine(br);
tkn = new StringTokenizer(str);
int reac = Integer.parseInt(tkn.nextToken()) - 1;
int prod = Integer.parseInt(tkn.nextToken()) - 1;
// Table of phenomenological rate coefficients
boolean valid = true;
str = readMeaningfulLine(br); // First row is list of pressures
for (int t = 0; t < numTemp; t++) {
str = readMeaningfulLine(br);
tkn = new StringTokenizer(str);
tkn.nextToken();
for (int p = 0; p < numPress; p++) {
rates[t][p] = Double.parseDouble(tkn.nextToken());
if (rates[t][p] < 0 ||
Double.isNaN(rates[t][p]) ||
Double.isInfinite(rates[t][p]))
valid = false;
}
}
PDepRateConstant pDepRate = new PDepRateConstant(rates);
// Chebyshev interpolation model
if (model.toLowerCase().contains("chebyshev")) {
chebyshev = new double[numChebT][numChebP];
for (int t = 0; t < numChebT; t++) {
str = readMeaningfulLine(br);
tkn = new StringTokenizer(str);
for (int p = 0; p < numChebP; p++) {
chebyshev[t][p] = Double.parseDouble(tkn.nextToken());
}
}
pDepRate.setChebyshev(chebyshev);
}
// PDepArrhenius interpolation model
else if (model.toLowerCase().contains("pdeparrhenius")) {
pDepArrhenius = new PDepArrheniusKinetics(numPress);
for (int p = 0; p < numPress; p++) {
str = readMeaningfulLine(br);
tkn = new StringTokenizer(str);
tkn.nextToken();
UncertainDouble A = new UncertainDouble(Double.parseDouble(tkn.nextToken()), 0.0, "A");
UncertainDouble Ea = new UncertainDouble(Double.parseDouble(tkn.nextToken()) / 4184.0, 0.0, "A");
UncertainDouble n = new UncertainDouble(Double.parseDouble(tkn.nextToken()), 0.0, "A");
String Trange = Double.toString(Tmin) + "-" + Double.toString(Tmax) + " K";
String Prange = Double.toString(Pmin / 1.0e5) + "-" + Double.toString(Pmax / 1.0e5) + " bar";
ArrheniusKinetics kinetics = new ArrheniusKinetics(A, n, Ea, Trange, 0, "Result of FAME calculation", "Prange = " + Prange);
pDepArrhenius.setKinetics(p, pressures[p], kinetics);
}
pDepRate.setPDepArrheniusKinetics(pDepArrhenius);
}
// If the fitted rate coefficient is not valid, then don't add the net reaction
if (!valid) {
ignoredARate = true;
continue;
}
// Initialize net reaction
PDepIsomer reactant = isomerList.get(reac);
PDepIsomer product = isomerList.get(prod);
PDepReaction rxn = new PDepReaction(reactant, product, pDepRate);
/*
* MRH 26Feb2010:
* Checking whether pdep rates exceed the high-P-limit
*
* We grab all of the reactions in the pathReactionList. These are the
* RMG-generated reactions (not chemically-activated reactions) and thus
* have "natural" high-P-limit kinetics.
* If the current PDepReaction "rxn"'s structure matches one of the structures
* of the PDepReactions located in the pathReactionList, we compare the high-P-limit
* kinetics of the pathReactionList (these values either come from the RMG database
* or are "fitted" parameters, based on the reverse kinetics + equilibrium constant)
* with the k(T,P_max) for each T in the "temperatures" array. NOTE: Not every "rxn"
* will have a match in the pathReactionList.
* If the pdep rate is greater than 2x the high-P-limit, we consider this to be different.
* If the number of grains is less than 1000, we set the pdepRatesOK boolean to false,
* so that another fame calculation will ensue
* If the number of grains exceeds 1000, we continue on with the simulation, but alert the
* user of the discrepancy.
*
* The value of 2 was somewhat randomly chosen by MRH.
* For a toy case of tBuOH pyrolysis (with 1e-6 reaction time and 0.9 error tolerance):
* Before code addition: iC4H8/H2O final concentration = 7.830282E-10, run time < 1 min
* 2x : iC4H8/H2O final concentration = 6.838976E-10, run time ~ 2 min
* 1.5x : iC4H8/H2O final concentration = 6.555548E-10, run time ~ 4 min
* 1.1x : iC4H8/H2O final concentration = 6.555548E-10, run time ~ 10 min
*
* The value of 2 (for the toy model) seems to be a good balance between speed and accuracy
*
* P.S. Want to keep the name fame (fast approximate me) instead of having to change to
* smame (slow more accurate me). ;)
*
*/
LinkedList pathReactionList = pdn.getPathReactions();
for (int HighPRxNum = 0; HighPRxNum < pathReactionList.size(); HighPRxNum++) {
PDepReaction rxnWHighPLimit = (PDepReaction)pathReactionList.get(HighPRxNum);
if (rxn.getStructure().equals(rxnWHighPLimit.getStructure())) {
double A = 0.0, Ea = 0.0, n = 0.0;
if (rxnWHighPLimit.isForward()) {
Kinetics[] k_array = rxnWHighPLimit.getKinetics();
Kinetics kin = computeKUsingLeastSquares(k_array);
A = kin.getAValue();
Ea = kin.getEValue();
n = kin.getNValue();
// While I'm here, and know which reaction was the High-P limit, set the comment in the P-dep reaction
rxn.setComments("High-P Limit: " + kin.getSource().toString() + " " + kin.getComment().toString() );
}
else {
Kinetics[] k_array = rxnWHighPLimit.getFittedReverseKinetics();
Kinetics kin = computeKUsingLeastSquares(k_array);
A = kin.getAValue();
Ea = kin.getEValue();
n = kin.getNValue();
// While I'm here, and know which reaction was the High-P limit, set the comment in the P-dep reaction
Kinetics[] fwd_kin = rxnWHighPLimit.getKinetics();
String commentsForForwardKinetics = "";
if (fwd_kin.length > 1) commentsForForwardKinetics += "Summation of kinetics:\n!";
for (int numKs=0; numKs<fwd_kin.length; ++numKs) {
commentsForForwardKinetics += "High-P Limit Reverse: " + fwd_kin[numKs].getSource().toString() +fwd_kin[numKs].getComment().toString();
if (numKs != fwd_kin.length-1) commentsForForwardKinetics += "\n!";
}
rxn.setComments(commentsForForwardKinetics);
}
if (ReactionModelGenerator.rerunFameWithAdditionalGrains()) {
double[][] all_ks = rxn.getPDepRate().getRateConstants();
for (int numTemps=0; numTemps<temperatures.length; numTemps++) {
double T = temperatures[numTemps].getK();
double k_highPlimit = A * Math.pow(T,n) * Math.exp(-Ea/GasConstant.getKcalMolK()/T);
if (all_ks[numTemps][pressures.length-1] > 2*k_highPlimit) {
if (numGrains > 1000) {
System.out.println("Pressure-dependent rate exceeds high-P-limit rate: " +
"Number of grains already exceeds 1000. Continuing RMG simulation " +
"with results from current fame run.");
break; // No need to continue checking the rates for this one reaction
}
else {
System.out.println("Pressure-dependent rate exceeds high-P-limit rate: " +
"Re-running fame with additional number of grains");
pdepRatesOK = false;
return false;
}
}
}
//break; // Why did MRH put this break here?
}
}
}
// Add net reaction to list
netReactionList.add(rxn);
}
// Close file when finished
br.close();
// Set reverse reactions
int i = 0;
while (i < netReactionList.size()) {
PDepReaction rxn1 = netReactionList.get(i);
if (rxn1.getReverseReaction() == null) {
boolean found = false;
for (int j = 0; j < netReactionList.size(); j++) {
PDepReaction rxn2 = netReactionList.get(j);
if (rxn1.getReactant().equals(rxn2.getProduct()) &&
rxn2.getReactant().equals(rxn1.getProduct())) {
rxn1.setReverseReaction(rxn2);
rxn2.setReverseReaction(rxn1);
netReactionList.remove(rxn2);
found = true;
break;
}
}
if (!found)
throw new PDepException("Unable to identify reverse reaction for " + rxn1.toString() + " after FAME calculation.");
}
else
i++;
}
// Update reaction lists (sort into included and nonincluded)
pdn.updateReactionLists(cerm);
}
catch (PDepException e) {
System.out.println(pdn);
System.out.println(e.getMessage());
e.printStackTrace();
throw new PDepException("Unable to parse FAME output file.");
}
catch(IOException e) {
System.out.println("Error: Unable to read from file \"fame_output.txt\".");
System.exit(0);
}
return true;
}
|
diff --git a/src/main/java/vazkii/tinkerer/common/item/kami/tool/ToolHandler.java b/src/main/java/vazkii/tinkerer/common/item/kami/tool/ToolHandler.java
index b77ab74d..c633c285 100644
--- a/src/main/java/vazkii/tinkerer/common/item/kami/tool/ToolHandler.java
+++ b/src/main/java/vazkii/tinkerer/common/item/kami/tool/ToolHandler.java
@@ -1,144 +1,144 @@
/**
* This class was created by <Vazkii>. It's distributed as
* part of the ThaumicTinkerer Mod.
*
* ThaumicTinkerer is Open Source and distributed under a
* Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License
* (http://creativecommons.org/licenses/by-nc-sa/3.0/deed.en_GB)
*
* ThaumicTinkerer is a Derivative Work on Thaumcraft 4.
* Thaumcraft 4 (c) Azanor 2012
* (http://www.minecraftforum.net/topic/1585216-)
*
* File Created @ [Dec 29, 2013, 6:01:31 PM (GMT)]
*/
package vazkii.tinkerer.common.item.kami.tool;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import net.minecraft.util.MathHelper;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.StatCollector;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
import vazkii.tinkerer.common.core.handler.ConfigHandler;
import vazkii.tinkerer.common.dim.WorldProviderBedrock;
import vazkii.tinkerer.common.lib.LibBlockIDs;
import java.util.ArrayList;
import java.util.List;
public final class ToolHandler {
public static Material[] materialsPick = new Material[] { Material.rock, Material.iron, Material.ice, Material.glass, Material.piston, Material.anvil };
public static Material[] materialsShovel = new Material[] { Material.grass, Material.ground, Material.sand, Material.snow, Material.craftedSnow, Material.clay };
public static Material[] materialsAxe = new Material[] { Material.coral, Material.leaves, Material.plants, Material.wood };
public static int getMode(ItemStack tool) {
return tool.getItemDamage();
}
public static int getNextMode(int mode) {
return mode == 2 ? 0 : mode + 1;
}
public static void changeMode(ItemStack tool) {
int mode = getMode(tool);
tool.setItemDamage(getNextMode(mode));
}
public static boolean isRightMaterial(Material material, Material[] materialsListing) {
for(Material mat : materialsListing)
if(material == mat)
return true;
return false;
}
public static void removeBlocksInIteration(EntityPlayer player, World world, int x, int y, int z, int xs, int ys, int zs, int xe, int ye, int ze, int lockID, Material[] materialsListing, boolean silk, int fortune) {
for(int x1 = xs; x1 < xe; x1++){
for(int y1 = ys; y1 < ye; y1++){
for(int z1 = zs; z1 < ze; z1++){
if(x != x1 && y != y1 && z != z1){
ToolHandler.removeBlockWithDrops(player, world, x1 + x, y1 + y, z1 + z, x, y, z, lockID, materialsListing, silk, fortune);
}
}
}
}
}
public static void removeBlockWithDrops(EntityPlayer player, World world, int x, int y, int z, int bx, int by, int bz, int lockID, Material[] materialsListing, boolean silk, int fortune) {
if(!world.blockExists(x, y, z))
return;
int id = world.getBlockId(x, y, z);
if(lockID != -1 && id != lockID)
return;
int meta = world.getBlockMetadata(x, y, z);
Material mat = world.getBlockMaterial(x, y, z);
Block block = Block.blocksList[id];
- if(block != null && !block.isAirBlock(world, x, y, z) && block.getPlayerRelativeBlockHardness(player, world, x, y, z) != -1) {
+ if(block != null && !block.isAirBlock(world, x, y, z) && (block.getPlayerRelativeBlockHardness(player, world, x, y, z) != 0)) {
List<ItemStack> items = new ArrayList();
if(!block.canHarvestBlock(player, meta) || !isRightMaterial(mat, materialsListing))
return;
if(silk && block.canSilkHarvest(world, player, x, y, z, meta))
items.add(new ItemStack(id, 1, meta));
else {
items.addAll(block.getBlockDropped(world, x, y, z, meta, fortune));
if(!player.capabilities.isCreativeMode)
block.dropXpOnBlockBreak(world, x, y, z, block.getExpDrop(world, meta, fortune));
}
block.onBlockDestroyedByPlayer(world, x, y, z, meta);
world.setBlockToAir(x, y, z);
if(!world.isRemote && !player.capabilities.isCreativeMode)
for(ItemStack stack : items)
world.spawnEntityInWorld(new EntityItem(world, bx + 0.5, by + 0.5, bz + 0.5, stack));
if(ConfigHandler.bedrockDimensionID != 0 && id==7 && ((world.provider.isSurfaceWorld() && y<5) || (y>253 && world.provider instanceof WorldProviderBedrock))){
world.setBlock(x, y, z, LibBlockIDs.idPortal);
}
}
}
public static String getToolModeStr(IAdvancedTool tool, ItemStack stack) {
return StatCollector.translateToLocal("ttmisc.mode." + tool.getType() + "." + ToolHandler.getMode(stack));
}
/**
* @author mDiyo
*/
public static MovingObjectPosition raytraceFromEntity(World world, Entity player, boolean par3, double range) {
float f = 1.0F;
float f1 = player.prevRotationPitch + (player.rotationPitch - player.prevRotationPitch) * f;
float f2 = player.prevRotationYaw + (player.rotationYaw - player.prevRotationYaw) * f;
double d0 = player.prevPosX + (player.posX - player.prevPosX) * f;
double d1 = player.prevPosY + (player.posY - player.prevPosY) * f;
if (!world.isRemote && player instanceof EntityPlayer)
d1 += 1.62D;
double d2 = player.prevPosZ + (player.posZ - player.prevPosZ) * f;
Vec3 vec3 = world.getWorldVec3Pool().getVecFromPool(d0, d1, d2);
float f3 = MathHelper.cos(-f2 * 0.017453292F - (float) Math.PI);
float f4 = MathHelper.sin(-f2 * 0.017453292F - (float) Math.PI);
float f5 = -MathHelper.cos(-f1 * 0.017453292F);
float f6 = MathHelper.sin(-f1 * 0.017453292F);
float f7 = f4 * f5;
float f8 = f3 * f5;
double d3 = range;
if (player instanceof EntityPlayerMP)
d3 = ((EntityPlayerMP) player).theItemInWorldManager.getBlockReachDistance();
Vec3 vec31 = vec3.addVector(f7 * d3, f6 * d3, f8 * d3);
return world.rayTraceBlocks_do_do(vec3, vec31, par3, !par3);
}
}
| true | true | public static void removeBlockWithDrops(EntityPlayer player, World world, int x, int y, int z, int bx, int by, int bz, int lockID, Material[] materialsListing, boolean silk, int fortune) {
if(!world.blockExists(x, y, z))
return;
int id = world.getBlockId(x, y, z);
if(lockID != -1 && id != lockID)
return;
int meta = world.getBlockMetadata(x, y, z);
Material mat = world.getBlockMaterial(x, y, z);
Block block = Block.blocksList[id];
if(block != null && !block.isAirBlock(world, x, y, z) && block.getPlayerRelativeBlockHardness(player, world, x, y, z) != -1) {
List<ItemStack> items = new ArrayList();
if(!block.canHarvestBlock(player, meta) || !isRightMaterial(mat, materialsListing))
return;
if(silk && block.canSilkHarvest(world, player, x, y, z, meta))
items.add(new ItemStack(id, 1, meta));
else {
items.addAll(block.getBlockDropped(world, x, y, z, meta, fortune));
if(!player.capabilities.isCreativeMode)
block.dropXpOnBlockBreak(world, x, y, z, block.getExpDrop(world, meta, fortune));
}
block.onBlockDestroyedByPlayer(world, x, y, z, meta);
world.setBlockToAir(x, y, z);
if(!world.isRemote && !player.capabilities.isCreativeMode)
for(ItemStack stack : items)
world.spawnEntityInWorld(new EntityItem(world, bx + 0.5, by + 0.5, bz + 0.5, stack));
if(ConfigHandler.bedrockDimensionID != 0 && id==7 && ((world.provider.isSurfaceWorld() && y<5) || (y>253 && world.provider instanceof WorldProviderBedrock))){
world.setBlock(x, y, z, LibBlockIDs.idPortal);
}
}
}
| public static void removeBlockWithDrops(EntityPlayer player, World world, int x, int y, int z, int bx, int by, int bz, int lockID, Material[] materialsListing, boolean silk, int fortune) {
if(!world.blockExists(x, y, z))
return;
int id = world.getBlockId(x, y, z);
if(lockID != -1 && id != lockID)
return;
int meta = world.getBlockMetadata(x, y, z);
Material mat = world.getBlockMaterial(x, y, z);
Block block = Block.blocksList[id];
if(block != null && !block.isAirBlock(world, x, y, z) && (block.getPlayerRelativeBlockHardness(player, world, x, y, z) != 0)) {
List<ItemStack> items = new ArrayList();
if(!block.canHarvestBlock(player, meta) || !isRightMaterial(mat, materialsListing))
return;
if(silk && block.canSilkHarvest(world, player, x, y, z, meta))
items.add(new ItemStack(id, 1, meta));
else {
items.addAll(block.getBlockDropped(world, x, y, z, meta, fortune));
if(!player.capabilities.isCreativeMode)
block.dropXpOnBlockBreak(world, x, y, z, block.getExpDrop(world, meta, fortune));
}
block.onBlockDestroyedByPlayer(world, x, y, z, meta);
world.setBlockToAir(x, y, z);
if(!world.isRemote && !player.capabilities.isCreativeMode)
for(ItemStack stack : items)
world.spawnEntityInWorld(new EntityItem(world, bx + 0.5, by + 0.5, bz + 0.5, stack));
if(ConfigHandler.bedrockDimensionID != 0 && id==7 && ((world.provider.isSurfaceWorld() && y<5) || (y>253 && world.provider instanceof WorldProviderBedrock))){
world.setBlock(x, y, z, LibBlockIDs.idPortal);
}
}
}
|
diff --git a/orbisgis-core/src/test/java/org/orbisgis/core/plugin/PluginHostTest.java b/orbisgis-core/src/test/java/org/orbisgis/core/plugin/PluginHostTest.java
index d1ab63d7f..471f91585 100644
--- a/orbisgis-core/src/test/java/org/orbisgis/core/plugin/PluginHostTest.java
+++ b/orbisgis-core/src/test/java/org/orbisgis/core/plugin/PluginHostTest.java
@@ -1,121 +1,121 @@
/*
* OrbisGIS is a GIS application dedicated to scientific spatial simulation.
* This cross-platform GIS is developed at French IRSTV institute and is able to
* manipulate and create vector and raster spatial information.
*
* OrbisGIS is distributed under GPL 3 license. It is produced by the "Atelier SIG"
* team of the IRSTV Institute <http://www.irstv.fr/> CNRS FR 2488.
*
* Copyright (C) 2007-2012 IRSTV (FR CNRS 2488)
*
* This file is part of OrbisGIS.
*
* OrbisGIS 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.
*
* OrbisGIS 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
* OrbisGIS. If not, see <http://www.gnu.org/licenses/>.
*
* For more information, please consult: <http://www.orbisgis.org/>
* or contact directly:
* info_at_ orbisgis.org
*/
package org.orbisgis.core.plugin;
import java.io.File;
import org.gdms.sql.function.Function;
import org.gdms.sql.function.FunctionManager;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.orbisgis.core.AbstractTest;
import org.orbisgis.core.DataManager;
import org.orbisgis.core.plugin.gdms.DummyScalarFunction;
import org.osgi.framework.Bundle;
import org.osgi.framework.ServiceRegistration;
/**
* Unit test of plugin-system
* @author Nicolas Fortin
*/
public class PluginHostTest extends AbstractTest {
@Override
public void setUp() throws Exception {
super.setUp();
registerDataManager();
}
private PluginHost startHost() {
PluginHost host = new PluginHost(new File("target"+File.separator+"plugins"));
host.start();
return host;
}
/**
* Unit test of gdms function tracker
* @throws Exception
*/
@Test
public void installGDMSFunctionService() throws Exception {
PluginHost host = startHost();
// Register dummy sql function service
ServiceRegistration<Function> serv = host.getHostBundleContext()
.registerService(Function.class, new DummyScalarFunction(),null);
// check if the function is registered
DataManager dataManager = getDataManager();
assertNotNull(dataManager);
FunctionManager manager = dataManager.getDataSourceFactory().getFunctionManager();
assertTrue(manager.contains("dummy"));
//The bundle normally unregister the service, but there is no bundle in this unit test
serv.unregister();
//end plugin host
host.stop();
//test if the function has been successfully removed
assertFalse(manager.contains("dummy"));
}
/**
* Unit test of the entire plugin system
* @throws Exception
*/
@Test
public void installGDMSFunctionBundle() throws Exception {
DataManager dataManager = getDataManager();
assertNotNull(dataManager);
FunctionManager manager = dataManager.getDataSourceFactory().getFunctionManager();
PluginHost host = startHost();
- File bundlePath = new File("target/bundle/plugin-4.0-SNAPSHOT.jar");
+ File bundlePath = new File("target/bundle/plugin-1.0.jar");
System.out.println("Install plugin :"+bundlePath.getAbsolutePath());
assertTrue(bundlePath.exists());
// Install the external package
Bundle plugin = host.getHostBundleContext().installBundle("file:"+bundlePath.getAbsolutePath());
// start it
plugin.start();
// test if function exists
assertTrue(manager.contains("dummy"));
host.getHostBundleContext().getBundle().stop();
//end plugin host
host.stop();
//test if the function has been successfully removed
assertFalse(manager.contains("dummy"));
}
@Override
public void tearDown() throws Exception {
super.tearDown();
}
}
| true | true | public void installGDMSFunctionBundle() throws Exception {
DataManager dataManager = getDataManager();
assertNotNull(dataManager);
FunctionManager manager = dataManager.getDataSourceFactory().getFunctionManager();
PluginHost host = startHost();
File bundlePath = new File("target/bundle/plugin-4.0-SNAPSHOT.jar");
System.out.println("Install plugin :"+bundlePath.getAbsolutePath());
assertTrue(bundlePath.exists());
// Install the external package
Bundle plugin = host.getHostBundleContext().installBundle("file:"+bundlePath.getAbsolutePath());
// start it
plugin.start();
// test if function exists
assertTrue(manager.contains("dummy"));
host.getHostBundleContext().getBundle().stop();
//end plugin host
host.stop();
//test if the function has been successfully removed
assertFalse(manager.contains("dummy"));
}
| public void installGDMSFunctionBundle() throws Exception {
DataManager dataManager = getDataManager();
assertNotNull(dataManager);
FunctionManager manager = dataManager.getDataSourceFactory().getFunctionManager();
PluginHost host = startHost();
File bundlePath = new File("target/bundle/plugin-1.0.jar");
System.out.println("Install plugin :"+bundlePath.getAbsolutePath());
assertTrue(bundlePath.exists());
// Install the external package
Bundle plugin = host.getHostBundleContext().installBundle("file:"+bundlePath.getAbsolutePath());
// start it
plugin.start();
// test if function exists
assertTrue(manager.contains("dummy"));
host.getHostBundleContext().getBundle().stop();
//end plugin host
host.stop();
//test if the function has been successfully removed
assertFalse(manager.contains("dummy"));
}
|
diff --git a/src/com/zynick/comparison/sites/Rakuten.java b/src/com/zynick/comparison/sites/Rakuten.java
index 22f3adb..ca58622 100644
--- a/src/com/zynick/comparison/sites/Rakuten.java
+++ b/src/com/zynick/comparison/sites/Rakuten.java
@@ -1,54 +1,54 @@
package com.zynick.comparison.sites;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import com.zynick.comparison.Constant;
import com.zynick.comparison.Item;
public class Rakuten implements Website {
@Override
public List<Item> parse(String query, int size) throws IOException {
// request for a page
Document doc = Jsoup.connect("http://www.rakuten.com.my/search/" + query)
.userAgent(Constant.HTTP_USER_AGENT)
.timeout(Constant.HTTP_TIMEOUT).get();
Elements rowS = doc.select("div.b-layout-right div.b-container").get(2).children();
ArrayList<Item> result = new ArrayList<Item>(size);
int count = 0;
loop: for (Element rowE : rowS) {
if (count >= size)
break;
Elements colS = rowE.children();
for (Element colE : colS) {
if (count >= size)
break loop;
Element aE = colE.getElementsByTag("a").first();
- String img = aE.child(0).attr("src");
+ String img = aE.child(0).attr("data-frz-src");
String title = colE.select("div.b-fix-2lines a").first().text();
String price = colE.select("span.b-text-prime").first().text().replaceAll(",", "");
double dPrice = Double.parseDouble(price);
String url = aE.attr("href");
url = "http://www.rakuten.com.my" + url;
result.add(new Item("Rakuten", title, dPrice, img, url));
count++;
}
}
return result;
}
}
| true | true | public List<Item> parse(String query, int size) throws IOException {
// request for a page
Document doc = Jsoup.connect("http://www.rakuten.com.my/search/" + query)
.userAgent(Constant.HTTP_USER_AGENT)
.timeout(Constant.HTTP_TIMEOUT).get();
Elements rowS = doc.select("div.b-layout-right div.b-container").get(2).children();
ArrayList<Item> result = new ArrayList<Item>(size);
int count = 0;
loop: for (Element rowE : rowS) {
if (count >= size)
break;
Elements colS = rowE.children();
for (Element colE : colS) {
if (count >= size)
break loop;
Element aE = colE.getElementsByTag("a").first();
String img = aE.child(0).attr("src");
String title = colE.select("div.b-fix-2lines a").first().text();
String price = colE.select("span.b-text-prime").first().text().replaceAll(",", "");
double dPrice = Double.parseDouble(price);
String url = aE.attr("href");
url = "http://www.rakuten.com.my" + url;
result.add(new Item("Rakuten", title, dPrice, img, url));
count++;
}
}
return result;
}
| public List<Item> parse(String query, int size) throws IOException {
// request for a page
Document doc = Jsoup.connect("http://www.rakuten.com.my/search/" + query)
.userAgent(Constant.HTTP_USER_AGENT)
.timeout(Constant.HTTP_TIMEOUT).get();
Elements rowS = doc.select("div.b-layout-right div.b-container").get(2).children();
ArrayList<Item> result = new ArrayList<Item>(size);
int count = 0;
loop: for (Element rowE : rowS) {
if (count >= size)
break;
Elements colS = rowE.children();
for (Element colE : colS) {
if (count >= size)
break loop;
Element aE = colE.getElementsByTag("a").first();
String img = aE.child(0).attr("data-frz-src");
String title = colE.select("div.b-fix-2lines a").first().text();
String price = colE.select("span.b-text-prime").first().text().replaceAll(",", "");
double dPrice = Double.parseDouble(price);
String url = aE.attr("href");
url = "http://www.rakuten.com.my" + url;
result.add(new Item("Rakuten", title, dPrice, img, url));
count++;
}
}
return result;
}
|
diff --git a/RankingAPI/src/org/gephi/ranking/impl/AbstractSizeTransformer.java b/RankingAPI/src/org/gephi/ranking/impl/AbstractSizeTransformer.java
index ada849305..4ab926801 100644
--- a/RankingAPI/src/org/gephi/ranking/impl/AbstractSizeTransformer.java
+++ b/RankingAPI/src/org/gephi/ranking/impl/AbstractSizeTransformer.java
@@ -1,69 +1,69 @@
/*
Copyright 2008 WebAtlas
Authors : Mathieu Bastian, Mathieu Jacomy, Julian Bilcke
Website : http://www.gephi.org
This file is part of Gephi.
Gephi is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Gephi is distributed in the hope that it will be useful,
but WITHOUType 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 Gephi. If not, see <http://www.gnu.org/licenses/>.
*/
package org.gephi.ranking.impl;
import org.gephi.ranking.api.SizeTransformer;
/**
*
* @author Mathieu Bastian
*/
public abstract class AbstractSizeTransformer<Target> extends AbstractTransformer<Target> implements SizeTransformer<Target> {
protected float minSize = 1f;
protected float maxSize = 4f;
public AbstractSizeTransformer() {
}
public AbstractSizeTransformer(float lowerBound, float upperBound) {
super(lowerBound, upperBound);
}
public AbstractSizeTransformer(float lowerBound, float upperBound, float minSize, float maxSize) {
super(lowerBound, upperBound);
this.minSize = minSize;
this.maxSize = maxSize;
}
public float getMinSize() {
return minSize;
}
public float getMaxSize() {
return maxSize;
}
public void setMinSize(float minSize) {
this.minSize = minSize;
}
public void setMaxSize(float maxSize) {
this.maxSize = maxSize;
}
public float getSize(float normalizedValue) {
if (interpolator != null) {
normalizedValue = interpolator.interpolate(normalizedValue);
}
- return normalizedValue * maxSize + minSize;
+ return normalizedValue * (maxSize - minSize) + minSize;
}
}
| true | true | public float getSize(float normalizedValue) {
if (interpolator != null) {
normalizedValue = interpolator.interpolate(normalizedValue);
}
return normalizedValue * maxSize + minSize;
}
| public float getSize(float normalizedValue) {
if (interpolator != null) {
normalizedValue = interpolator.interpolate(normalizedValue);
}
return normalizedValue * (maxSize - minSize) + minSize;
}
|
diff --git a/src/net/k3rnel/arena/client/network/TCPManager.java b/src/net/k3rnel/arena/client/network/TCPManager.java
index 29afc83..59eb0a7 100644
--- a/src/net/k3rnel/arena/client/network/TCPManager.java
+++ b/src/net/k3rnel/arena/client/network/TCPManager.java
@@ -1,128 +1,128 @@
/**
* This file is part of Distro Wars (Client).
*
* Distro Wars (Client) 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.
* Distro Wars (Client) 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 Distro Wars (Client). If not, see <http://www.gnu.org/licenses/>.
*/
package net.k3rnel.arena.client.network;
import java.awt.EventQueue;
import java.io.IOException;
import net.k3rnel.arena.client.GameClient;
import net.k3rnel.arena.client.network.NetworkProtocols.LoginData;
import net.k3rnel.arena.client.network.NetworkProtocols.RegistrationData;
import com.esotericsoftware.kryonet.Client;
import com.esotericsoftware.kryonet.Connection;
import com.esotericsoftware.kryonet.Listener;
/**
* Handles packets received from players over TCP
* @author Nushio
*
*/
public class TCPManager {
private String host;
private Client client;
private GameClient m_game;
/**
* Constructor
* @param login
* @param logout
*/
public TCPManager(String server,GameClient game) throws IOException {
this.m_game = game;
this.client = new Client();
this.host = server;
client.start();
NetworkProtocols.register(client);
//This allows us to get incoming classes and all.
client.addListener(new Listener(){
public void connected (Connection connection) {
}
public void received (Connection connection, Object object) {
if(object instanceof LoginData){
LoginData data = (LoginData)object;
switch(data.state) {
case 0:
- GameClient.messageDialog("Registration Successful.", GameClient.getInstance().getDisplay());
+ GameClient.messageDialog("Login Successful.", GameClient.getInstance().getDisplay());
break;
case 1:
GameClient.messageDialog("Error: Player Limit Reached.", GameClient.getInstance().getDisplay());
break;
case 2:
GameClient.messageDialog("Database Error: Database cannot be reached.", GameClient.getInstance().getDisplay());
break;
case 3:
GameClient.messageDialog("Error: Invalid Username/Password", GameClient.getInstance().getDisplay());
break;
default:
GameClient.messageDialog("Error code: "+data.state+". What a Terrible Failure.", GameClient.getInstance().getDisplay());
break;
}
System.out.println(data.state);
m_game.getLoginScreen().setVisible(false);
m_game.getLoadingScreen().setVisible(false);
m_game.setPlayerId(0);//TODO: Save player id
m_game.getUi().setVisible(true);
m_game.getUi().getChat().setVisible(true);
m_game.getTimeService().setTime(data.hours,data.minutes);
} else if(object instanceof RegistrationData){
RegistrationData data = (RegistrationData)object;
System.out.println(data.state);
switch(data.state) {
case 0:
GameClient.messageDialog("Registration Successful.", GameClient.getInstance().getDisplay());
break;
case 1:
GameClient.messageDialog("Error: Username exists or is forbidden.", GameClient.getInstance().getDisplay());
break;
case 2:
GameClient.messageDialog("Error: Email already in use.", GameClient.getInstance().getDisplay());
break;
case 3:
GameClient.messageDialog("Error: Email is too long.", GameClient.getInstance().getDisplay());
break;
case 4:
GameClient.messageDialog("Error: Database cannot be reached.", GameClient.getInstance().getDisplay());
break;
default:
GameClient.messageDialog("Error code: "+data.state+". What a Terrible Failure.", GameClient.getInstance().getDisplay());
break;
}
m_game.getLoadingScreen().setVisible(false);
m_game.getLoginScreen().showLogin();
}
}
public void disconnected (Connection connection) {
EventQueue.invokeLater(new Runnable() {
public void run () {
}
});
}
});
client.connect(5000, host, NetworkProtocols.tcp_port);
}
// This holds per connection state.
static class PlayerConnection extends Connection {
public String name; //Default is IP
}
public Client getClient(){
return client;
}
}
| true | true | public TCPManager(String server,GameClient game) throws IOException {
this.m_game = game;
this.client = new Client();
this.host = server;
client.start();
NetworkProtocols.register(client);
//This allows us to get incoming classes and all.
client.addListener(new Listener(){
public void connected (Connection connection) {
}
public void received (Connection connection, Object object) {
if(object instanceof LoginData){
LoginData data = (LoginData)object;
switch(data.state) {
case 0:
GameClient.messageDialog("Registration Successful.", GameClient.getInstance().getDisplay());
break;
case 1:
GameClient.messageDialog("Error: Player Limit Reached.", GameClient.getInstance().getDisplay());
break;
case 2:
GameClient.messageDialog("Database Error: Database cannot be reached.", GameClient.getInstance().getDisplay());
break;
case 3:
GameClient.messageDialog("Error: Invalid Username/Password", GameClient.getInstance().getDisplay());
break;
default:
GameClient.messageDialog("Error code: "+data.state+". What a Terrible Failure.", GameClient.getInstance().getDisplay());
break;
}
System.out.println(data.state);
m_game.getLoginScreen().setVisible(false);
m_game.getLoadingScreen().setVisible(false);
m_game.setPlayerId(0);//TODO: Save player id
m_game.getUi().setVisible(true);
m_game.getUi().getChat().setVisible(true);
m_game.getTimeService().setTime(data.hours,data.minutes);
} else if(object instanceof RegistrationData){
RegistrationData data = (RegistrationData)object;
System.out.println(data.state);
switch(data.state) {
case 0:
GameClient.messageDialog("Registration Successful.", GameClient.getInstance().getDisplay());
break;
case 1:
GameClient.messageDialog("Error: Username exists or is forbidden.", GameClient.getInstance().getDisplay());
break;
case 2:
GameClient.messageDialog("Error: Email already in use.", GameClient.getInstance().getDisplay());
break;
case 3:
GameClient.messageDialog("Error: Email is too long.", GameClient.getInstance().getDisplay());
break;
case 4:
GameClient.messageDialog("Error: Database cannot be reached.", GameClient.getInstance().getDisplay());
break;
default:
GameClient.messageDialog("Error code: "+data.state+". What a Terrible Failure.", GameClient.getInstance().getDisplay());
break;
}
m_game.getLoadingScreen().setVisible(false);
m_game.getLoginScreen().showLogin();
}
}
public void disconnected (Connection connection) {
EventQueue.invokeLater(new Runnable() {
public void run () {
}
});
}
});
client.connect(5000, host, NetworkProtocols.tcp_port);
}
| public TCPManager(String server,GameClient game) throws IOException {
this.m_game = game;
this.client = new Client();
this.host = server;
client.start();
NetworkProtocols.register(client);
//This allows us to get incoming classes and all.
client.addListener(new Listener(){
public void connected (Connection connection) {
}
public void received (Connection connection, Object object) {
if(object instanceof LoginData){
LoginData data = (LoginData)object;
switch(data.state) {
case 0:
GameClient.messageDialog("Login Successful.", GameClient.getInstance().getDisplay());
break;
case 1:
GameClient.messageDialog("Error: Player Limit Reached.", GameClient.getInstance().getDisplay());
break;
case 2:
GameClient.messageDialog("Database Error: Database cannot be reached.", GameClient.getInstance().getDisplay());
break;
case 3:
GameClient.messageDialog("Error: Invalid Username/Password", GameClient.getInstance().getDisplay());
break;
default:
GameClient.messageDialog("Error code: "+data.state+". What a Terrible Failure.", GameClient.getInstance().getDisplay());
break;
}
System.out.println(data.state);
m_game.getLoginScreen().setVisible(false);
m_game.getLoadingScreen().setVisible(false);
m_game.setPlayerId(0);//TODO: Save player id
m_game.getUi().setVisible(true);
m_game.getUi().getChat().setVisible(true);
m_game.getTimeService().setTime(data.hours,data.minutes);
} else if(object instanceof RegistrationData){
RegistrationData data = (RegistrationData)object;
System.out.println(data.state);
switch(data.state) {
case 0:
GameClient.messageDialog("Registration Successful.", GameClient.getInstance().getDisplay());
break;
case 1:
GameClient.messageDialog("Error: Username exists or is forbidden.", GameClient.getInstance().getDisplay());
break;
case 2:
GameClient.messageDialog("Error: Email already in use.", GameClient.getInstance().getDisplay());
break;
case 3:
GameClient.messageDialog("Error: Email is too long.", GameClient.getInstance().getDisplay());
break;
case 4:
GameClient.messageDialog("Error: Database cannot be reached.", GameClient.getInstance().getDisplay());
break;
default:
GameClient.messageDialog("Error code: "+data.state+". What a Terrible Failure.", GameClient.getInstance().getDisplay());
break;
}
m_game.getLoadingScreen().setVisible(false);
m_game.getLoginScreen().showLogin();
}
}
public void disconnected (Connection connection) {
EventQueue.invokeLater(new Runnable() {
public void run () {
}
});
}
});
client.connect(5000, host, NetworkProtocols.tcp_port);
}
|
diff --git a/src/main/java/com/scheffield/ria/loading/SlowServingServlet.java b/src/main/java/com/scheffield/ria/loading/SlowServingServlet.java
index bb91273..f31468f 100644
--- a/src/main/java/com/scheffield/ria/loading/SlowServingServlet.java
+++ b/src/main/java/com/scheffield/ria/loading/SlowServingServlet.java
@@ -1,54 +1,54 @@
package com.scheffield.ria.loading;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
public class SlowServingServlet extends HttpServlet {
private static final String TIME_TO_WAIT_PARAM = "t";
private static final String RESOURCE_TO_LOAD = "r";
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
final Integer timeToWait = Integer.valueOf(req.getParameter(TIME_TO_WAIT_PARAM));
final String resource = req.getParameter(RESOURCE_TO_LOAD);
try {
- Thread.currentThread().wait(timeToWait * 1000);
+ Thread.sleep(timeToWait * 1000);
} catch (InterruptedException e) {
throw new ServletException(e);
}
final File file = new File(resource);
FileInputStream fileInputStream = null;
ServletOutputStream os = null;
try {
fileInputStream = new FileInputStream(file);
os = resp.getOutputStream();
IOUtils.copy(fileInputStream, os);
} finally {
IOUtils.closeQuietly(fileInputStream);
IOUtils.closeQuietly(os);
}
}
}
| true | true | protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
final Integer timeToWait = Integer.valueOf(req.getParameter(TIME_TO_WAIT_PARAM));
final String resource = req.getParameter(RESOURCE_TO_LOAD);
try {
Thread.currentThread().wait(timeToWait * 1000);
} catch (InterruptedException e) {
throw new ServletException(e);
}
final File file = new File(resource);
FileInputStream fileInputStream = null;
ServletOutputStream os = null;
try {
fileInputStream = new FileInputStream(file);
os = resp.getOutputStream();
IOUtils.copy(fileInputStream, os);
} finally {
IOUtils.closeQuietly(fileInputStream);
IOUtils.closeQuietly(os);
}
}
| protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
final Integer timeToWait = Integer.valueOf(req.getParameter(TIME_TO_WAIT_PARAM));
final String resource = req.getParameter(RESOURCE_TO_LOAD);
try {
Thread.sleep(timeToWait * 1000);
} catch (InterruptedException e) {
throw new ServletException(e);
}
final File file = new File(resource);
FileInputStream fileInputStream = null;
ServletOutputStream os = null;
try {
fileInputStream = new FileInputStream(file);
os = resp.getOutputStream();
IOUtils.copy(fileInputStream, os);
} finally {
IOUtils.closeQuietly(fileInputStream);
IOUtils.closeQuietly(os);
}
}
|
diff --git a/src/java/org/wings/plaf/css/msie/ScrollPaneLayoutCG.java b/src/java/org/wings/plaf/css/msie/ScrollPaneLayoutCG.java
index bb6e90e6..1755eeee 100644
--- a/src/java/org/wings/plaf/css/msie/ScrollPaneLayoutCG.java
+++ b/src/java/org/wings/plaf/css/msie/ScrollPaneLayoutCG.java
@@ -1,96 +1,92 @@
package org.wings.plaf.css.msie;
import org.wings.SComponent;
import org.wings.SConstants;
import org.wings.SScrollPaneLayout;
import org.wings.SDimension;
import org.wings.io.Device;
import org.wings.plaf.css.Utils;
import java.io.IOException;
import java.util.Map;
public class ScrollPaneLayoutCG extends org.wings.plaf.css.ScrollPaneLayoutCG {
private static final long serialVersionUID = 1L;
protected void writePaging(Device d, SScrollPaneLayout layout) throws IOException {
SDimension preferredSize = layout.getContainer().getPreferredSize();
- if (preferredSize == null) {
- super.write(d, layout);
- return;
- }
- String height = preferredSize.getHeight();
- if (height == null || "auto".equals(height)) {
- super.write(d, layout);
+ if (preferredSize == null || preferredSize.getHeight() == null ||
+ SDimension.AUTO.equals(preferredSize.getHeight())) {
+ super.writePaging(d, layout);
return;
}
// special implementation with expressions is only required, if the center component
// shall consume the remaining height
Map components = layout.getComponents();
SComponent north = (SComponent) components.get(SScrollPaneLayout.NORTH);
SComponent east = (SComponent) components.get(SScrollPaneLayout.EAST);
SComponent center = (SComponent) components.get(SScrollPaneLayout.VIEWPORT);
SComponent west = (SComponent) components.get(SScrollPaneLayout.WEST);
SComponent south = (SComponent) components.get(SScrollPaneLayout.SOUTH);
openLayouterBody(d, layout);
if (north != null) {
d.print("<tr>");
if (west != null) {
d.print("<td width=\"0%\"></td>");
}
d.print("<td width=\"100%\">");
writeComponent(d, north);
d.print("</td>");
if (east != null) {
d.print("<td width=\"0%\"></td>");
}
d.print("</tr>\n");
}
d.print("<tr yweight=\"100\">");
if (west != null) {
d.print("<td width=\"0%\">");
writeComponent(d, west);
d.print("</td>");
}
if (center != null) {
d.print("<td width=\"100%\"");
Utils.printTableCellAlignment(d, center, SConstants.LEFT_ALIGN, SConstants.TOP_ALIGN);
d.print(">");
writeComponent(d, center);
d.print("</td>");
}
if (east != null) {
d.print("<td width=\"0%\">");
writeComponent(d, east);
d.print("</td>");
}
d.print("</tr>\n");
if (south != null) {
d.print("<tr>");
if (west != null) {
d.print("<td width=\"0%\"></td>");
}
d.print("<td width=\"100%\">");
writeComponent(d, south);
d.print("</td>");
if (east != null) {
d.print("<td width=\"0%\"></td>");
}
d.print("</tr>\n");
}
closeLayouterBody(d, layout);
}
}
| true | true | protected void writePaging(Device d, SScrollPaneLayout layout) throws IOException {
SDimension preferredSize = layout.getContainer().getPreferredSize();
if (preferredSize == null) {
super.write(d, layout);
return;
}
String height = preferredSize.getHeight();
if (height == null || "auto".equals(height)) {
super.write(d, layout);
return;
}
// special implementation with expressions is only required, if the center component
// shall consume the remaining height
Map components = layout.getComponents();
SComponent north = (SComponent) components.get(SScrollPaneLayout.NORTH);
SComponent east = (SComponent) components.get(SScrollPaneLayout.EAST);
SComponent center = (SComponent) components.get(SScrollPaneLayout.VIEWPORT);
SComponent west = (SComponent) components.get(SScrollPaneLayout.WEST);
SComponent south = (SComponent) components.get(SScrollPaneLayout.SOUTH);
openLayouterBody(d, layout);
if (north != null) {
d.print("<tr>");
if (west != null) {
d.print("<td width=\"0%\"></td>");
}
d.print("<td width=\"100%\">");
writeComponent(d, north);
d.print("</td>");
if (east != null) {
d.print("<td width=\"0%\"></td>");
}
d.print("</tr>\n");
}
d.print("<tr yweight=\"100\">");
if (west != null) {
d.print("<td width=\"0%\">");
writeComponent(d, west);
d.print("</td>");
}
if (center != null) {
d.print("<td width=\"100%\"");
Utils.printTableCellAlignment(d, center, SConstants.LEFT_ALIGN, SConstants.TOP_ALIGN);
d.print(">");
writeComponent(d, center);
d.print("</td>");
}
if (east != null) {
d.print("<td width=\"0%\">");
writeComponent(d, east);
d.print("</td>");
}
d.print("</tr>\n");
if (south != null) {
d.print("<tr>");
if (west != null) {
d.print("<td width=\"0%\"></td>");
}
d.print("<td width=\"100%\">");
writeComponent(d, south);
d.print("</td>");
if (east != null) {
d.print("<td width=\"0%\"></td>");
}
d.print("</tr>\n");
}
closeLayouterBody(d, layout);
}
| protected void writePaging(Device d, SScrollPaneLayout layout) throws IOException {
SDimension preferredSize = layout.getContainer().getPreferredSize();
if (preferredSize == null || preferredSize.getHeight() == null ||
SDimension.AUTO.equals(preferredSize.getHeight())) {
super.writePaging(d, layout);
return;
}
// special implementation with expressions is only required, if the center component
// shall consume the remaining height
Map components = layout.getComponents();
SComponent north = (SComponent) components.get(SScrollPaneLayout.NORTH);
SComponent east = (SComponent) components.get(SScrollPaneLayout.EAST);
SComponent center = (SComponent) components.get(SScrollPaneLayout.VIEWPORT);
SComponent west = (SComponent) components.get(SScrollPaneLayout.WEST);
SComponent south = (SComponent) components.get(SScrollPaneLayout.SOUTH);
openLayouterBody(d, layout);
if (north != null) {
d.print("<tr>");
if (west != null) {
d.print("<td width=\"0%\"></td>");
}
d.print("<td width=\"100%\">");
writeComponent(d, north);
d.print("</td>");
if (east != null) {
d.print("<td width=\"0%\"></td>");
}
d.print("</tr>\n");
}
d.print("<tr yweight=\"100\">");
if (west != null) {
d.print("<td width=\"0%\">");
writeComponent(d, west);
d.print("</td>");
}
if (center != null) {
d.print("<td width=\"100%\"");
Utils.printTableCellAlignment(d, center, SConstants.LEFT_ALIGN, SConstants.TOP_ALIGN);
d.print(">");
writeComponent(d, center);
d.print("</td>");
}
if (east != null) {
d.print("<td width=\"0%\">");
writeComponent(d, east);
d.print("</td>");
}
d.print("</tr>\n");
if (south != null) {
d.print("<tr>");
if (west != null) {
d.print("<td width=\"0%\"></td>");
}
d.print("<td width=\"100%\">");
writeComponent(d, south);
d.print("</td>");
if (east != null) {
d.print("<td width=\"0%\"></td>");
}
d.print("</tr>\n");
}
closeLayouterBody(d, layout);
}
|
diff --git a/src/Tests/functionalTests/ComponentTest.java b/src/Tests/functionalTests/ComponentTest.java
index 8577265ae..c2c1b168c 100644
--- a/src/Tests/functionalTests/ComponentTest.java
+++ b/src/Tests/functionalTests/ComponentTest.java
@@ -1,77 +1,77 @@
/*
* ################################################################
*
* ProActive: The Java(TM) library for Parallel, Distributed,
* Concurrent computing with Security and Mobility
*
* Copyright (C) 1997-2007 INRIA/University of Nice-Sophia Antipolis
* Contact: [email protected]
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 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
*
* Initial developer(s): The ProActive Team
* http://www.inria.fr/oasis/ProActive/contacts.html
* Contributor(s):
*
* ################################################################
*/
package functionalTests;
import org.junit.BeforeClass;
import org.objectweb.proactive.core.config.ProActiveConfiguration;
import functionalTests.FunctionalTest;
/**
* @author Matthieu Morel
*
*/
public abstract class ComponentTest extends FunctionalTest {
/**
* @param name
*/
public ComponentTest() {
// super("[COMPONENTS] " + name);
}
/**
* @param name
* @param description
*/
public ComponentTest(String name, String description) {
// super("Components : " + name, description);
}
@BeforeClass
- public static void preConditions() throws Exception {
+ public static void componentPreConditions() throws Exception {
if (!"enable".equals(ProActiveConfiguration.getInstance()
.getProperty("proactive.future.ac"))) {
throw new Exception(
"The components framework needs the automatic continuations (system property 'proactive.future.ac' set to 'enable') to be operative");
}
//-Dfractal.provider=org.objectweb.proactive.core.component.Fractive
if (!"org.objectweb.proactive.core.component.Fractive".equals(
ProActiveConfiguration.getInstance()
.getProperty("fractal.provider"))) {
ProActiveConfiguration.getInstance()
.setProperty("fractal.provider",
"org.objectweb.proactive.core.component.Fractive");
}
}
}
| true | true | public static void preConditions() throws Exception {
if (!"enable".equals(ProActiveConfiguration.getInstance()
.getProperty("proactive.future.ac"))) {
throw new Exception(
"The components framework needs the automatic continuations (system property 'proactive.future.ac' set to 'enable') to be operative");
}
//-Dfractal.provider=org.objectweb.proactive.core.component.Fractive
if (!"org.objectweb.proactive.core.component.Fractive".equals(
ProActiveConfiguration.getInstance()
.getProperty("fractal.provider"))) {
ProActiveConfiguration.getInstance()
.setProperty("fractal.provider",
"org.objectweb.proactive.core.component.Fractive");
}
}
| public static void componentPreConditions() throws Exception {
if (!"enable".equals(ProActiveConfiguration.getInstance()
.getProperty("proactive.future.ac"))) {
throw new Exception(
"The components framework needs the automatic continuations (system property 'proactive.future.ac' set to 'enable') to be operative");
}
//-Dfractal.provider=org.objectweb.proactive.core.component.Fractive
if (!"org.objectweb.proactive.core.component.Fractive".equals(
ProActiveConfiguration.getInstance()
.getProperty("fractal.provider"))) {
ProActiveConfiguration.getInstance()
.setProperty("fractal.provider",
"org.objectweb.proactive.core.component.Fractive");
}
}
|
diff --git a/src/com/nolanlawson/keepscore/HistoryActivity.java b/src/com/nolanlawson/keepscore/HistoryActivity.java
index d4c674b..df915cd 100644
--- a/src/com/nolanlawson/keepscore/HistoryActivity.java
+++ b/src/com/nolanlawson/keepscore/HistoryActivity.java
@@ -1,76 +1,77 @@
package com.nolanlawson.keepscore;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.os.Bundle;
import android.widget.GridView;
import com.nolanlawson.keepscore.data.HistoryAdapter;
import com.nolanlawson.keepscore.data.HistoryItem;
import com.nolanlawson.keepscore.data.SeparatedListAdapter;
import com.nolanlawson.keepscore.db.Game;
import com.nolanlawson.keepscore.db.PlayerScore;
import com.nolanlawson.keepscore.helper.AdapterHelper;
import com.nolanlawson.keepscore.util.UtilLogger;
/**
* Activity for displaying the entire history of a game
* @author nolan
*
*/
public class HistoryActivity extends Activity {
private static final UtilLogger log = new UtilLogger(HistoryActivity.class);
public static final String EXTRA_GAME = "game";
private GridView gridView;
private SeparatedListAdapter adapter;
private Game game;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.history);
game = getIntent().getParcelableExtra(EXTRA_GAME);
log.d("intent is %s", getIntent());
log.d("game is %s", game);
createAdapter();
gridView = (GridView) findViewById(android.R.id.list);
gridView.setAdapter(adapter);
}
private void createAdapter() {
adapter = new SeparatedListAdapter(this);
List<String> sectionHeaders = new ArrayList<String>();
List<List<HistoryItem>> sections = new ArrayList<List<HistoryItem>>();
for (PlayerScore playerScore : game.getPlayerScores()) {
String header = playerScore.toDisplayName(this);
List<HistoryItem> section = HistoryItem.createFromPlayerScore(playerScore, this);
sectionHeaders.add(header);
sections.add(section);
}
// fit to the GridView; i.e. interleave so that everything shows up top-to-bottom
// rather than left-to-right
sections = AdapterHelper.createSectionsForTwoColumnGridView(sections);
- for (int i = 0; i < sectionHeaders.size(); i++) {
+ for (int i = 0; i < sections.size(); i++) {
HistoryAdapter subAdapter = new HistoryAdapter(this, sections.get(i));
- adapter.addSection(sectionHeaders.get(i), subAdapter);
+ String sectionHeader = i < sectionHeaders.size() ? sectionHeaders.get(i) : "";
+ adapter.addSection(sectionHeader, subAdapter);
}
}
}
| false | true | private void createAdapter() {
adapter = new SeparatedListAdapter(this);
List<String> sectionHeaders = new ArrayList<String>();
List<List<HistoryItem>> sections = new ArrayList<List<HistoryItem>>();
for (PlayerScore playerScore : game.getPlayerScores()) {
String header = playerScore.toDisplayName(this);
List<HistoryItem> section = HistoryItem.createFromPlayerScore(playerScore, this);
sectionHeaders.add(header);
sections.add(section);
}
// fit to the GridView; i.e. interleave so that everything shows up top-to-bottom
// rather than left-to-right
sections = AdapterHelper.createSectionsForTwoColumnGridView(sections);
for (int i = 0; i < sectionHeaders.size(); i++) {
HistoryAdapter subAdapter = new HistoryAdapter(this, sections.get(i));
adapter.addSection(sectionHeaders.get(i), subAdapter);
}
}
| private void createAdapter() {
adapter = new SeparatedListAdapter(this);
List<String> sectionHeaders = new ArrayList<String>();
List<List<HistoryItem>> sections = new ArrayList<List<HistoryItem>>();
for (PlayerScore playerScore : game.getPlayerScores()) {
String header = playerScore.toDisplayName(this);
List<HistoryItem> section = HistoryItem.createFromPlayerScore(playerScore, this);
sectionHeaders.add(header);
sections.add(section);
}
// fit to the GridView; i.e. interleave so that everything shows up top-to-bottom
// rather than left-to-right
sections = AdapterHelper.createSectionsForTwoColumnGridView(sections);
for (int i = 0; i < sections.size(); i++) {
HistoryAdapter subAdapter = new HistoryAdapter(this, sections.get(i));
String sectionHeader = i < sectionHeaders.size() ? sectionHeaders.get(i) : "";
adapter.addSection(sectionHeader, subAdapter);
}
}
|
diff --git a/org/python/core/PyString.java b/org/python/core/PyString.java
index 8d916996..0dec8549 100644
--- a/org/python/core/PyString.java
+++ b/org/python/core/PyString.java
@@ -1,499 +1,501 @@
package org.python.core;
public class PyString extends PySequence {
private String string;
private transient int cached_hashcode=0;
private transient boolean interned=false;
public static PyClass __class__;
public PyString(String new_string) {
super(__class__);
string = new_string;
}
public PyString(char c) {
this(String.valueOf(c));
}
public PyString __str__() {
return this;
}
public int __len__() {
return string.length();
}
public String toString() { return string; }
public String internedString() {
if (interned) {
return string;
} else {
string = string.intern();
interned = true;
return string;
}
}
// Do I need to do more for Unicode?
public PyString __repr__() {
char quote = '"';
if (string.indexOf('\'') == -1 || string.indexOf('"') != -1) quote = '\'';
StringBuffer buf = new StringBuffer(string.length()+5);
buf.append(quote);
for(int i=0; i<string.length(); i++) {
char c = string.charAt(i);
if (c == quote || c == '\\') {
buf.append('\\');
buf.append(c);
} else {
if (c < ' ' || c > 0177) {
buf.append('\\');
String s = Integer.toString(c, 8);
while (s.length() < 3) s = "0"+s;
buf.append(s);
} else {
buf.append(c);
}
}
}
buf.append(quote);
return new PyString(buf.toString());
}
public boolean equals(Object other) {
if (!interned) {
string = string.intern();
interned = true;
}
if (other instanceof PyString) {
PyString o = (PyString)other;
if (!o.interned) {
o.string = o.string.intern();
o.interned = true;
}
return string == o.string; //string.equals( ((PyString)other).string);
}
else return false;
}
public int __cmp__(PyObject other) {
if (!(other instanceof PyString)) return -2;
int c = string.compareTo(((PyString)other).string);
return c < 0 ? -1 : c > 0 ? 1 : 0;
}
public int hashCode() {
if (cached_hashcode == 0) cached_hashcode = string.hashCode();
return cached_hashcode;
}
private byte[] getBytes() {
byte[] buf = new byte[string.length()];
string.getBytes(0, string.length(), buf, 0);
return buf;
}
public Object __tojava__(Class c) {
//This is a hack to make almost all Java calls happy
if (c == String.class || c == Object.class) return string;
if (c == Character.TYPE)
if (string.length() == 1) return new Character(string.charAt(0));
if (c.isArray() && c.getComponentType() == Byte.TYPE) {
return getBytes();
}
if (c.isInstance(this)) return this;
return Py.NoConversion;
}
protected PyObject get(int i) {
return new PyString(string.substring(i,i+1));
}
protected PyObject getslice(int start, int stop, int step) {
if (step == 1) {
return new PyString(string.substring(start, stop));
} else {
int n = sliceLength(start, stop, step);
char new_chars[] = new char[n];
int j = 0;
for(int i=start; j<n; i+=step) new_chars[j++] = string.charAt(i);
return new PyString(new String(new_chars));
}
}
protected PyObject repeat(int count) {
int s = string.length();
char new_chars[] = new char[s*count];
for(int i=0; i<count; i++) {
string.getChars(0, s, new_chars, i*s);
}
return new PyString(new String(new_chars));
}
public PyObject __add__(PyObject generic_other) {
if (generic_other instanceof PyString) {
return new PyString(string.concat(((PyString)generic_other).string));
} else {
return null;
}
}
public PyObject __mod__(PyObject other) {
StringFormatter fmt = new StringFormatter(string);
return new PyString(fmt.format(other));
}
public PyInteger __int__() {
try {
return new PyInteger(Integer.valueOf(string).intValue());
} catch (NumberFormatException exc) {
throw Py.ValueError("invalid literal for __int__: "+string);
}
}
public PyLong __long__() {
try {
return new PyLong(new java.math.BigInteger(string));
} catch (NumberFormatException exc) {
throw Py.ValueError("invalid literal for __long__: "+string);
}
}
public PyFloat __float__() {
try {
return new PyFloat(Double.valueOf(string).doubleValue());
} catch (NumberFormatException exc) {
throw Py.ValueError("invalid literal for __float__: "+string);
}
}
}
final class StringFormatter{
int index;
String format;
StringBuffer buffer;
boolean negative;
int precision;
int argIndex;
PyObject args;
final char pop() {
try {
return format.charAt(index++);
} catch (StringIndexOutOfBoundsException e) {
throw Py.ValueError("incomplete format");
}
}
final char peek() {
return format.charAt(index);
}
final void push() {
index--;
}
public StringFormatter(String format) {
index = 0;
this.format = format;
buffer = new StringBuffer(format.length()+100);
}
PyObject getarg() {
PyObject ret = null;
switch(argIndex) {
// special index indicating a single item that has already been used
case -2:
break;
// special index indicating a single item that has not yet been used
case -1:
argIndex=-2;
return args;
default:
ret = args.__finditem__(argIndex++);
break;
}
if (ret == null)
throw Py.TypeError("not enough arguments for format string");
return ret;
}
int getNumber() {
char c = pop();
if (c == '*') {
PyObject o = getarg();
if (o instanceof PyInteger) return ((PyInteger)o).getValue();
throw Py.TypeError("* wants int");
} else {
if (Character.isDigit(c)) {
int numStart = index-1;
while (Character.isDigit(c = pop())) {;}
index -= 1;
return Integer.valueOf(format.substring(numStart, index)).intValue();
}
index -= 1;
return -1;
}
}
public String formatInteger(PyObject arg, int radix, boolean unsigned) {
return formatInteger(arg.__int__().getValue(), radix, unsigned);
}
public String formatInteger(long v, int radix, boolean unsigned) {
if (unsigned) {
if (v < 0) v = 0x100000000l + v;
} else {
if (v < 0) { negative = true; v = -v; }
}
String s = Long.toString(v, radix);
while (s.length() < precision) {
s = "0"+s;
}
return s;
}
public String formatFloatDecimal(PyObject arg, boolean truncate) {
return formatFloatDecimal(arg.__float__().getValue(), truncate);
}
public String formatFloatDecimal(double v, boolean truncate) {
java.text.NumberFormat format = java.text.NumberFormat.getInstance();
int prec = precision;
if (prec == -1) prec = 6;
if (v < 0) {
v = -v;
negative = true;
}
format.setMaximumFractionDigits(prec);
format.setMinimumFractionDigits(truncate ? 0 : prec);
format.setGroupingUsed(false);
//System.err.println("formatFloat: "+v+", "+prec);
String ret = format.format(v);
if (ret.indexOf('.') == -1) {
return ret+'.';
}
return ret;
}
public String formatFloatExponential(PyObject arg, char e, boolean truncate) {
StringBuffer buf = new StringBuffer();
double v = arg.__float__().getValue();
boolean isNegative = false;
if (v < 0) {
v = -v;
isNegative = true;
}
double power = 0.0;
if (v > 0) power = Math.floor(Math.log(v)/Math.log(10));
//System.err.println("formatExp: "+v+", "+power);
int savePrecision = precision;
if (truncate) precision = -1;
else precision = 3;
String exp = formatInteger((long)power, 10, false);
if (negative) { negative = false; exp = '-'+exp; }
else {
if (!truncate) exp = '+'+exp;
}
precision = savePrecision;
double base = v/Math.pow(10, power);
buf.append(formatFloatDecimal(base, truncate));
buf.append(e);
buf.append(exp);
negative = isNegative;
return buf.toString();
}
public String format(PyObject args) {
PyObject dict = null;
this.args = args;
if (args instanceof PyTuple) {
argIndex = 0;
} else {
// special index indicating a single item rather than a tuple
argIndex = -1;
if (args instanceof PyDictionary ||
args instanceof PyStringMap ||
args.__findattr__("__getitem__") != null) {
dict = args;
}
}
while (index < format.length()) {
boolean ljustFlag=false;
boolean signFlag=false;
boolean blankFlag=false;
boolean altFlag=false;
boolean zeroFlag=false;
int width = -1;
precision = -1;
char c = pop();
if (c != '%') {
buffer.append(c);
continue;
}
c = pop();
if (c == '(') {
//System.out.println("( found");
if (dict == null)
throw Py.TypeError("format requires a mapping");
int parens = 1;
int keyStart = index;
while (parens > 0) {
c = pop();
if (c == ')') parens--;
else if (c == '(') parens++;
}
this.args = dict.__getitem__(new PyString(format.substring(keyStart, index-1)));
this.argIndex = -1;
//System.out.println("args: "+args+", "+argIndex);
} else {
push();
}
while (true) {
switch(c = pop()) {
case '-': ljustFlag=true; continue;
case '+': signFlag=true; continue;
case ' ': blankFlag=true; continue;
case '#': altFlag=true; continue;
case '0': zeroFlag=true; continue;
}
break;
}
push();
width = getNumber();
c = pop();
if (c == '.') {
precision = getNumber();
if (precision == -1) precision = 0;
c = pop();
}
if (c == 'h' || c == 'l' || c == 'L') {
c = pop();
}
if (c == '%') {
buffer.append(c);
continue;
}
PyObject arg = getarg();
//System.out.println("args: "+args+", "+argIndex+", "+arg);
char fill = ' ';
String string=null;
negative = false;
if (zeroFlag) fill = '0';
else fill = ' ';
switch(c) {
case 's':
fill = ' ';
string = arg.__str__().toString();
if (precision >= 0 && string.length() > precision) {
string = string.substring(0, precision);
}
break;
case 'i':
case 'd':
string = formatInteger(arg, 10, false);
break;
case 'u':
string = formatInteger(arg, 10, true);
break;
case 'o':
string = formatInteger(arg, 8, true);
if (altFlag) { string = "0" + string; ; }
break;
case 'x':
string = formatInteger(arg, 16, true);
if (altFlag) { string = "0x" + string; }
break;
case 'X':
string = formatInteger(arg, 16, true);
//Do substitution of caps for lowercase here
if (altFlag) { string = "0X" + string; }
break;
case 'e':
case 'E':
string = formatFloatExponential(arg, c, false);
break;
case 'f':
string = formatFloatDecimal(arg, false);
break;
case 'g':
case 'G':
int prec = precision;
if (prec == -1) prec = 6;
double v = arg.__float__().getValue();
int digits = (int)Math.ceil(ExtraMath.log10(v));
if (digits > 0) {
if (digits <= prec) {
precision = prec-digits;
string = formatFloatDecimal(arg, true);
} else {
string = formatFloatExponential(arg, (char)(c-2), true);
}
} else {
string = formatFloatDecimal(arg, true);
}
break;
case 'c':
fill = ' ';
if (arg instanceof PyString) {
string = ((PyString)arg).toString();
if (string.length() != 1)
throw Py.TypeError("%c requires int or char");
break;
}
string = new Character((char)arg.__int__().getValue()).toString();
break;
default:
throw Py.ValueError("unsupported format character '"+c+"'");
}
String signString = "";
if (negative) {
signString = "-";
} else {
if (signFlag) {
signString = "+";
- }
+ } else if (blankFlag) {
+ signString = " ";
+ }
}
int length = string.length() + signString.length();
if (width < length) width = length;
if (ljustFlag && fill==' ') {
buffer.append(signString);
buffer.append(string);
while (width-- > length) buffer.append(fill);
} else {
if (fill != ' ') {
buffer.append(signString);
}
while (width-- > length) buffer.append(fill);
if (fill == ' ') {
buffer.append(signString);
}
buffer.append(string);
}
}
if (argIndex == -1 || (argIndex >= 0 && args.__finditem__(argIndex) != null)) {
throw Py.TypeError("not all arguments converted");
}
return buffer.toString();
}
}
| true | true | public String format(PyObject args) {
PyObject dict = null;
this.args = args;
if (args instanceof PyTuple) {
argIndex = 0;
} else {
// special index indicating a single item rather than a tuple
argIndex = -1;
if (args instanceof PyDictionary ||
args instanceof PyStringMap ||
args.__findattr__("__getitem__") != null) {
dict = args;
}
}
while (index < format.length()) {
boolean ljustFlag=false;
boolean signFlag=false;
boolean blankFlag=false;
boolean altFlag=false;
boolean zeroFlag=false;
int width = -1;
precision = -1;
char c = pop();
if (c != '%') {
buffer.append(c);
continue;
}
c = pop();
if (c == '(') {
//System.out.println("( found");
if (dict == null)
throw Py.TypeError("format requires a mapping");
int parens = 1;
int keyStart = index;
while (parens > 0) {
c = pop();
if (c == ')') parens--;
else if (c == '(') parens++;
}
this.args = dict.__getitem__(new PyString(format.substring(keyStart, index-1)));
this.argIndex = -1;
//System.out.println("args: "+args+", "+argIndex);
} else {
push();
}
while (true) {
switch(c = pop()) {
case '-': ljustFlag=true; continue;
case '+': signFlag=true; continue;
case ' ': blankFlag=true; continue;
case '#': altFlag=true; continue;
case '0': zeroFlag=true; continue;
}
break;
}
push();
width = getNumber();
c = pop();
if (c == '.') {
precision = getNumber();
if (precision == -1) precision = 0;
c = pop();
}
if (c == 'h' || c == 'l' || c == 'L') {
c = pop();
}
if (c == '%') {
buffer.append(c);
continue;
}
PyObject arg = getarg();
//System.out.println("args: "+args+", "+argIndex+", "+arg);
char fill = ' ';
String string=null;
negative = false;
if (zeroFlag) fill = '0';
else fill = ' ';
switch(c) {
case 's':
fill = ' ';
string = arg.__str__().toString();
if (precision >= 0 && string.length() > precision) {
string = string.substring(0, precision);
}
break;
case 'i':
case 'd':
string = formatInteger(arg, 10, false);
break;
case 'u':
string = formatInteger(arg, 10, true);
break;
case 'o':
string = formatInteger(arg, 8, true);
if (altFlag) { string = "0" + string; ; }
break;
case 'x':
string = formatInteger(arg, 16, true);
if (altFlag) { string = "0x" + string; }
break;
case 'X':
string = formatInteger(arg, 16, true);
//Do substitution of caps for lowercase here
if (altFlag) { string = "0X" + string; }
break;
case 'e':
case 'E':
string = formatFloatExponential(arg, c, false);
break;
case 'f':
string = formatFloatDecimal(arg, false);
break;
case 'g':
case 'G':
int prec = precision;
if (prec == -1) prec = 6;
double v = arg.__float__().getValue();
int digits = (int)Math.ceil(ExtraMath.log10(v));
if (digits > 0) {
if (digits <= prec) {
precision = prec-digits;
string = formatFloatDecimal(arg, true);
} else {
string = formatFloatExponential(arg, (char)(c-2), true);
}
} else {
string = formatFloatDecimal(arg, true);
}
break;
case 'c':
fill = ' ';
if (arg instanceof PyString) {
string = ((PyString)arg).toString();
if (string.length() != 1)
throw Py.TypeError("%c requires int or char");
break;
}
string = new Character((char)arg.__int__().getValue()).toString();
break;
default:
throw Py.ValueError("unsupported format character '"+c+"'");
}
String signString = "";
if (negative) {
signString = "-";
} else {
if (signFlag) {
signString = "+";
}
}
int length = string.length() + signString.length();
if (width < length) width = length;
if (ljustFlag && fill==' ') {
buffer.append(signString);
buffer.append(string);
while (width-- > length) buffer.append(fill);
} else {
if (fill != ' ') {
buffer.append(signString);
}
while (width-- > length) buffer.append(fill);
if (fill == ' ') {
buffer.append(signString);
}
buffer.append(string);
}
}
if (argIndex == -1 || (argIndex >= 0 && args.__finditem__(argIndex) != null)) {
throw Py.TypeError("not all arguments converted");
}
return buffer.toString();
}
| public String format(PyObject args) {
PyObject dict = null;
this.args = args;
if (args instanceof PyTuple) {
argIndex = 0;
} else {
// special index indicating a single item rather than a tuple
argIndex = -1;
if (args instanceof PyDictionary ||
args instanceof PyStringMap ||
args.__findattr__("__getitem__") != null) {
dict = args;
}
}
while (index < format.length()) {
boolean ljustFlag=false;
boolean signFlag=false;
boolean blankFlag=false;
boolean altFlag=false;
boolean zeroFlag=false;
int width = -1;
precision = -1;
char c = pop();
if (c != '%') {
buffer.append(c);
continue;
}
c = pop();
if (c == '(') {
//System.out.println("( found");
if (dict == null)
throw Py.TypeError("format requires a mapping");
int parens = 1;
int keyStart = index;
while (parens > 0) {
c = pop();
if (c == ')') parens--;
else if (c == '(') parens++;
}
this.args = dict.__getitem__(new PyString(format.substring(keyStart, index-1)));
this.argIndex = -1;
//System.out.println("args: "+args+", "+argIndex);
} else {
push();
}
while (true) {
switch(c = pop()) {
case '-': ljustFlag=true; continue;
case '+': signFlag=true; continue;
case ' ': blankFlag=true; continue;
case '#': altFlag=true; continue;
case '0': zeroFlag=true; continue;
}
break;
}
push();
width = getNumber();
c = pop();
if (c == '.') {
precision = getNumber();
if (precision == -1) precision = 0;
c = pop();
}
if (c == 'h' || c == 'l' || c == 'L') {
c = pop();
}
if (c == '%') {
buffer.append(c);
continue;
}
PyObject arg = getarg();
//System.out.println("args: "+args+", "+argIndex+", "+arg);
char fill = ' ';
String string=null;
negative = false;
if (zeroFlag) fill = '0';
else fill = ' ';
switch(c) {
case 's':
fill = ' ';
string = arg.__str__().toString();
if (precision >= 0 && string.length() > precision) {
string = string.substring(0, precision);
}
break;
case 'i':
case 'd':
string = formatInteger(arg, 10, false);
break;
case 'u':
string = formatInteger(arg, 10, true);
break;
case 'o':
string = formatInteger(arg, 8, true);
if (altFlag) { string = "0" + string; ; }
break;
case 'x':
string = formatInteger(arg, 16, true);
if (altFlag) { string = "0x" + string; }
break;
case 'X':
string = formatInteger(arg, 16, true);
//Do substitution of caps for lowercase here
if (altFlag) { string = "0X" + string; }
break;
case 'e':
case 'E':
string = formatFloatExponential(arg, c, false);
break;
case 'f':
string = formatFloatDecimal(arg, false);
break;
case 'g':
case 'G':
int prec = precision;
if (prec == -1) prec = 6;
double v = arg.__float__().getValue();
int digits = (int)Math.ceil(ExtraMath.log10(v));
if (digits > 0) {
if (digits <= prec) {
precision = prec-digits;
string = formatFloatDecimal(arg, true);
} else {
string = formatFloatExponential(arg, (char)(c-2), true);
}
} else {
string = formatFloatDecimal(arg, true);
}
break;
case 'c':
fill = ' ';
if (arg instanceof PyString) {
string = ((PyString)arg).toString();
if (string.length() != 1)
throw Py.TypeError("%c requires int or char");
break;
}
string = new Character((char)arg.__int__().getValue()).toString();
break;
default:
throw Py.ValueError("unsupported format character '"+c+"'");
}
String signString = "";
if (negative) {
signString = "-";
} else {
if (signFlag) {
signString = "+";
} else if (blankFlag) {
signString = " ";
}
}
int length = string.length() + signString.length();
if (width < length) width = length;
if (ljustFlag && fill==' ') {
buffer.append(signString);
buffer.append(string);
while (width-- > length) buffer.append(fill);
} else {
if (fill != ' ') {
buffer.append(signString);
}
while (width-- > length) buffer.append(fill);
if (fill == ' ') {
buffer.append(signString);
}
buffer.append(string);
}
}
if (argIndex == -1 || (argIndex >= 0 && args.__finditem__(argIndex) != null)) {
throw Py.TypeError("not all arguments converted");
}
return buffer.toString();
}
|
diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/partition/MinMaxPartitioner.java b/spring-batch-core/src/test/java/org/springframework/batch/core/partition/MinMaxPartitioner.java
index c8c12aaa5..d52f20508 100644
--- a/spring-batch-core/src/test/java/org/springframework/batch/core/partition/MinMaxPartitioner.java
+++ b/spring-batch-core/src/test/java/org/springframework/batch/core/partition/MinMaxPartitioner.java
@@ -1,45 +1,45 @@
/*
* Copyright 2006-2013 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.batch.core.partition;
import java.util.Map;
import org.springframework.batch.core.partition.support.SimplePartitioner;
import org.springframework.batch.item.ExecutionContext;
/**
* @author Dave Syer
*
*/
public class MinMaxPartitioner extends SimplePartitioner {
@Override
public Map<String, ExecutionContext> partition(int gridSize) {
Map<String, ExecutionContext> partition = super.partition(gridSize);
int total = 8; // The number of items in the ExampleItemReader
int range = total/gridSize;
int i = 0;
for (ExecutionContext context : partition.values()) {
int min = (i++)*range;
- int max = Math.min(total, (min+1)*range);
+ int max = Math.min(total, i * range);
context.putInt("min", min);
context.putInt("max", max);
}
return partition;
}
}
| true | true | public Map<String, ExecutionContext> partition(int gridSize) {
Map<String, ExecutionContext> partition = super.partition(gridSize);
int total = 8; // The number of items in the ExampleItemReader
int range = total/gridSize;
int i = 0;
for (ExecutionContext context : partition.values()) {
int min = (i++)*range;
int max = Math.min(total, (min+1)*range);
context.putInt("min", min);
context.putInt("max", max);
}
return partition;
}
| public Map<String, ExecutionContext> partition(int gridSize) {
Map<String, ExecutionContext> partition = super.partition(gridSize);
int total = 8; // The number of items in the ExampleItemReader
int range = total/gridSize;
int i = 0;
for (ExecutionContext context : partition.values()) {
int min = (i++)*range;
int max = Math.min(total, i * range);
context.putInt("min", min);
context.putInt("max", max);
}
return partition;
}
|
diff --git a/src/ProjectControl/src/org/cvut/wa2/projectcontrol/CreateTaskServlet.java b/src/ProjectControl/src/org/cvut/wa2/projectcontrol/CreateTaskServlet.java
index 9e20e02..f01c236 100644
--- a/src/ProjectControl/src/org/cvut/wa2/projectcontrol/CreateTaskServlet.java
+++ b/src/ProjectControl/src/org/cvut/wa2/projectcontrol/CreateTaskServlet.java
@@ -1,51 +1,51 @@
package org.cvut.wa2.projectcontrol;
import java.io.IOException;
import java.util.List;
import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.cvut.wa2.projectcontrol.DAO.PMF;
import org.cvut.wa2.projectcontrol.DAO.TeamDAO;
import org.cvut.wa2.projectcontrol.entities.CompositeTask;
import org.cvut.wa2.projectcontrol.entities.DocumentsToken;
import org.cvut.wa2.projectcontrol.entities.Team;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
public class CreateTaskServlet extends HttpServlet {
private static final long serialVersionUID = -258284310678221536L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
UserService userService = UserServiceFactory.getUserService();
RequestDispatcher disp = null;
if (userService.isUserLoggedIn()) {
String owner = userService.getCurrentUser().getEmail();
- disp = req.getRequestDispatcher("/CreatTask.jsp");
+ disp = req.getRequestDispatcher("/CreateTask.jsp");
List<Team> listOfTeams = TeamDAO.getTeams();
req.setAttribute("listOfTeams", listOfTeams);
req.setAttribute("owner", owner);
} else {
disp = req.getRequestDispatcher("/projectcontrol");
}
disp.forward(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
}
| true | true | protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
UserService userService = UserServiceFactory.getUserService();
RequestDispatcher disp = null;
if (userService.isUserLoggedIn()) {
String owner = userService.getCurrentUser().getEmail();
disp = req.getRequestDispatcher("/CreatTask.jsp");
List<Team> listOfTeams = TeamDAO.getTeams();
req.setAttribute("listOfTeams", listOfTeams);
req.setAttribute("owner", owner);
} else {
disp = req.getRequestDispatcher("/projectcontrol");
}
disp.forward(req, resp);
}
| protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
UserService userService = UserServiceFactory.getUserService();
RequestDispatcher disp = null;
if (userService.isUserLoggedIn()) {
String owner = userService.getCurrentUser().getEmail();
disp = req.getRequestDispatcher("/CreateTask.jsp");
List<Team> listOfTeams = TeamDAO.getTeams();
req.setAttribute("listOfTeams", listOfTeams);
req.setAttribute("owner", owner);
} else {
disp = req.getRequestDispatcher("/projectcontrol");
}
disp.forward(req, resp);
}
|
diff --git a/src/com/untamedears/ItemExchange/command/commands/CreateCommand.java b/src/com/untamedears/ItemExchange/command/commands/CreateCommand.java
index e27c1ac..2e3742e 100644
--- a/src/com/untamedears/ItemExchange/command/commands/CreateCommand.java
+++ b/src/com/untamedears/ItemExchange/command/commands/CreateCommand.java
@@ -1,111 +1,111 @@
package com.untamedears.ItemExchange.command.commands;
import static com.untamedears.citadel.Utility.getReinforcement;
import static com.untamedears.citadel.Utility.isReinforced;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import com.untamedears.ItemExchange.ItemExchangePlugin;
import com.untamedears.ItemExchange.command.PlayerCommand;
import com.untamedears.ItemExchange.exceptions.ExchangeRuleParseException;
import com.untamedears.ItemExchange.utility.ExchangeRule;
import com.untamedears.ItemExchange.utility.ExchangeRule.RuleType;
import com.untamedears.ItemExchange.utility.ItemExchange;
import com.untamedears.citadel.entity.PlayerReinforcement;
/*
* General command for creating either an entire ItemExchange or
* creating an exchange rule, given the context of the player when
* the command is issued.
*/
public class CreateCommand extends PlayerCommand {
public CreateCommand() {
super("Create Exchange");
setDescription("Automatically creates an exchange inside the chest the player is looking at");
setUsage("/iecreate");
setArgumentRange(0, 3);
setIdentifiers(new String[] { "iecreate", "iec" });
}
@Override
public boolean execute(CommandSender sender, String[] args) {
Player player = (Player) sender;
Block block = player.getLastTwoTargetBlocks(null, 20).get(1).getLocation().getBlock();
//If no input or ouptut is specified player attempt to set up ItemExchange at the block the player is looking at
//The player must have citadel access to the inventory block
if (args.length == 0) {
if (ItemExchangePlugin.ACCEPTABLE_BLOCKS.contains(block.getState().getType())) {
if ((!ItemExchangePlugin.CITADEL_ENABLED || ItemExchangePlugin.CITADEL_ENABLED && !isReinforced(block)) || (((PlayerReinforcement) getReinforcement(block)).isAccessible(player))) {
player.sendMessage(ItemExchange.createExchange(block.getLocation(), player));
}
else {
player.sendMessage(ChatColor.RED + "You do not have access to that block.");
}
}
else {
player.sendMessage(ChatColor.RED + "Block in view is not suitable for an Item Exchange.");
}
}
//Create a RuleBlock in the players inventory
else {
//Player must have space in their inventory for the RuleBlock
if (player.getInventory().firstEmpty() != -1) {
//If only an input/output is specified create the RuleBlock based on the item held in the players hand
if (args.length == 1) {
//Assign a ruleType
RuleType ruleType = null;
if (args[0].equalsIgnoreCase("input")) {
ruleType = ExchangeRule.RuleType.INPUT;
}
else if (args[0].equalsIgnoreCase("output")) {
- ruleType = ExchangeRule.RuleType.INPUT;
+ ruleType = ExchangeRule.RuleType.OUTPUT;
}
if (ruleType != null) {
ItemStack inHand = player.getItemInHand();
if(inHand == null || inHand.getType() == Material.AIR) {
player.sendMessage(ChatColor.RED + "You are not holding anything in your hand!");
return true;
}
if(ExchangeRule.isRuleBlock(inHand)) {
player.sendMessage(ChatColor.RED + "You cannot exchange rule blocks!");
return true;
}
//Creates the ExchangeRule, converts it to an ItemStack and places it in the player's inventory
player.getInventory().addItem(ExchangeRule.parseItemStack(inHand, ruleType).toItemStack());
player.sendMessage(ChatColor.GREEN + "Created Rule Block!");
}
else {
player.sendMessage(ChatColor.RED + "Please specify and input or output.");
}
}
//If additional arguments are specified create an exchange rule based upon the additional arguments and place it in the player's inventory
else if (args.length >= 2) {
try {
//Attemptes to create the ExchangeRule, converts it to an ItemStack and places it in the player's inventory
player.getInventory().addItem(ExchangeRule.parseCreateCommand(args).toItemStack());
player.sendMessage(ChatColor.GREEN + "Created Rule Block!");
}
catch (ExchangeRuleParseException e) {
player.sendMessage(ChatColor.RED + "Incorrect entry format.");
}
}
}
else {
player.sendMessage(ChatColor.RED + "Player inventory is full!");
}
}
return true;
}
}
| true | true | public boolean execute(CommandSender sender, String[] args) {
Player player = (Player) sender;
Block block = player.getLastTwoTargetBlocks(null, 20).get(1).getLocation().getBlock();
//If no input or ouptut is specified player attempt to set up ItemExchange at the block the player is looking at
//The player must have citadel access to the inventory block
if (args.length == 0) {
if (ItemExchangePlugin.ACCEPTABLE_BLOCKS.contains(block.getState().getType())) {
if ((!ItemExchangePlugin.CITADEL_ENABLED || ItemExchangePlugin.CITADEL_ENABLED && !isReinforced(block)) || (((PlayerReinforcement) getReinforcement(block)).isAccessible(player))) {
player.sendMessage(ItemExchange.createExchange(block.getLocation(), player));
}
else {
player.sendMessage(ChatColor.RED + "You do not have access to that block.");
}
}
else {
player.sendMessage(ChatColor.RED + "Block in view is not suitable for an Item Exchange.");
}
}
//Create a RuleBlock in the players inventory
else {
//Player must have space in their inventory for the RuleBlock
if (player.getInventory().firstEmpty() != -1) {
//If only an input/output is specified create the RuleBlock based on the item held in the players hand
if (args.length == 1) {
//Assign a ruleType
RuleType ruleType = null;
if (args[0].equalsIgnoreCase("input")) {
ruleType = ExchangeRule.RuleType.INPUT;
}
else if (args[0].equalsIgnoreCase("output")) {
ruleType = ExchangeRule.RuleType.INPUT;
}
if (ruleType != null) {
ItemStack inHand = player.getItemInHand();
if(inHand == null || inHand.getType() == Material.AIR) {
player.sendMessage(ChatColor.RED + "You are not holding anything in your hand!");
return true;
}
if(ExchangeRule.isRuleBlock(inHand)) {
player.sendMessage(ChatColor.RED + "You cannot exchange rule blocks!");
return true;
}
//Creates the ExchangeRule, converts it to an ItemStack and places it in the player's inventory
player.getInventory().addItem(ExchangeRule.parseItemStack(inHand, ruleType).toItemStack());
player.sendMessage(ChatColor.GREEN + "Created Rule Block!");
}
else {
player.sendMessage(ChatColor.RED + "Please specify and input or output.");
}
}
//If additional arguments are specified create an exchange rule based upon the additional arguments and place it in the player's inventory
else if (args.length >= 2) {
try {
//Attemptes to create the ExchangeRule, converts it to an ItemStack and places it in the player's inventory
player.getInventory().addItem(ExchangeRule.parseCreateCommand(args).toItemStack());
player.sendMessage(ChatColor.GREEN + "Created Rule Block!");
}
catch (ExchangeRuleParseException e) {
player.sendMessage(ChatColor.RED + "Incorrect entry format.");
}
}
}
else {
player.sendMessage(ChatColor.RED + "Player inventory is full!");
}
}
return true;
}
| public boolean execute(CommandSender sender, String[] args) {
Player player = (Player) sender;
Block block = player.getLastTwoTargetBlocks(null, 20).get(1).getLocation().getBlock();
//If no input or ouptut is specified player attempt to set up ItemExchange at the block the player is looking at
//The player must have citadel access to the inventory block
if (args.length == 0) {
if (ItemExchangePlugin.ACCEPTABLE_BLOCKS.contains(block.getState().getType())) {
if ((!ItemExchangePlugin.CITADEL_ENABLED || ItemExchangePlugin.CITADEL_ENABLED && !isReinforced(block)) || (((PlayerReinforcement) getReinforcement(block)).isAccessible(player))) {
player.sendMessage(ItemExchange.createExchange(block.getLocation(), player));
}
else {
player.sendMessage(ChatColor.RED + "You do not have access to that block.");
}
}
else {
player.sendMessage(ChatColor.RED + "Block in view is not suitable for an Item Exchange.");
}
}
//Create a RuleBlock in the players inventory
else {
//Player must have space in their inventory for the RuleBlock
if (player.getInventory().firstEmpty() != -1) {
//If only an input/output is specified create the RuleBlock based on the item held in the players hand
if (args.length == 1) {
//Assign a ruleType
RuleType ruleType = null;
if (args[0].equalsIgnoreCase("input")) {
ruleType = ExchangeRule.RuleType.INPUT;
}
else if (args[0].equalsIgnoreCase("output")) {
ruleType = ExchangeRule.RuleType.OUTPUT;
}
if (ruleType != null) {
ItemStack inHand = player.getItemInHand();
if(inHand == null || inHand.getType() == Material.AIR) {
player.sendMessage(ChatColor.RED + "You are not holding anything in your hand!");
return true;
}
if(ExchangeRule.isRuleBlock(inHand)) {
player.sendMessage(ChatColor.RED + "You cannot exchange rule blocks!");
return true;
}
//Creates the ExchangeRule, converts it to an ItemStack and places it in the player's inventory
player.getInventory().addItem(ExchangeRule.parseItemStack(inHand, ruleType).toItemStack());
player.sendMessage(ChatColor.GREEN + "Created Rule Block!");
}
else {
player.sendMessage(ChatColor.RED + "Please specify and input or output.");
}
}
//If additional arguments are specified create an exchange rule based upon the additional arguments and place it in the player's inventory
else if (args.length >= 2) {
try {
//Attemptes to create the ExchangeRule, converts it to an ItemStack and places it in the player's inventory
player.getInventory().addItem(ExchangeRule.parseCreateCommand(args).toItemStack());
player.sendMessage(ChatColor.GREEN + "Created Rule Block!");
}
catch (ExchangeRuleParseException e) {
player.sendMessage(ChatColor.RED + "Incorrect entry format.");
}
}
}
else {
player.sendMessage(ChatColor.RED + "Player inventory is full!");
}
}
return true;
}
|
diff --git a/src/com/android/bluetooth/map/BluetoothMapAppParams.java b/src/com/android/bluetooth/map/BluetoothMapAppParams.java
index ffdd2f1..554f422 100644
--- a/src/com/android/bluetooth/map/BluetoothMapAppParams.java
+++ b/src/com/android/bluetooth/map/BluetoothMapAppParams.java
@@ -1,798 +1,798 @@
/*
* Copyright (C) 2013 Samsung System LSI
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.bluetooth.map;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import android.util.Log;
/**
* This class encapsulates the appParams needed for MAP.
*/
public class BluetoothMapAppParams {
private static final String TAG = "BluetoothMapAppParams";
private static final int MAX_LIST_COUNT = 0x01;
private static final int MAX_LIST_COUNT_LEN = 0x02; //, 0x0000, 0xFFFF),
private static final int START_OFFSET = 0x02;
private static final int START_OFFSET_LEN = 0x02; //, 0x0000, 0xFFFF),
private static final int FILTER_MESSAGE_TYPE = 0x03;
private static final int FILTER_MESSAGE_TYPE_LEN = 0x01; //, 0x0000, 0x000f),
private static final int FILTER_PERIOD_BEGIN = 0x04;
private static final int FILTER_PERIOD_END = 0x05;
private static final int FILTER_READ_STATUS = 0x06;
private static final int FILTER_READ_STATUS_LEN = 0x01; //, 0x0000, 0x0002),
private static final int FILTER_RECIPIENT = 0x07;
private static final int FILTER_ORIGINATOR = 0x08;
private static final int FILTER_PRIORITY = 0x09;
private static final int FILTER_PRIORITY_LEN = 0x01; //, 0x0000, 0x0002),
private static final int ATTACHMENT = 0x0A;
private static final int ATTACHMENT_LEN = 0x01; //, 0x0000, 0x0001),
private static final int TRANSPARENT = 0x0B;
private static final int TRANSPARENT_LEN = 0x01; //, 0x0000, 0x0001),
private static final int RETRY = 0x0C;
private static final int RETRY_LEN = 0x01; //, 0x0000, 0x0001),
private static final int NEW_MESSAGE = 0x0D;
private static final int NEW_MESSAGE_LEN = 0x01; //, 0x0000, 0x0001),
private static final int NOTIFICATION_STATUS = 0x0E;
private static final int NOTIFICATION_STATUS_LEN = 0x01; //, 0x0000, 0xFFFF),
private static final int MAS_INSTANCE_ID = 0x0F;
private static final int MAS_INSTANCE_ID_LEN = 0x01; //, 0x0000, 0x00FF),
private static final int PARAMETER_MASK = 0x10;
private static final int PARAMETER_MASK_LEN = 0x04; //, 0x0000, 0x0000),
private static final int FOLDER_LISTING_SIZE = 0x11;
private static final int FOLDER_LISTING_SIZE_LEN = 0x02; //, 0x0000, 0xFFFF),
private static final int MESSAGE_LISTING_SIZE = 0x12;
private static final int MESSAGE_LISTING_SIZE_LEN = 0x02; //, 0x0000, 0xFFFF),
private static final int SUBJECT_LENGTH = 0x13;
private static final int SUBJECT_LENGTH_LEN = 0x01; //, 0x0000, 0x00FF),
private static final int CHARSET = 0x14;
private static final int CHARSET_LEN = 0x01; //, 0x0000, 0x0001),
private static final int FRACTION_REQUEST = 0x15;
private static final int FRACTION_REQUEST_LEN = 0x01; //, 0x0000, 0x0001),
private static final int FRACTION_DELIVER = 0x16;
private static final int FRACTION_DELIVER_LEN = 0x01; //, 0x0000, 0x0001),
private static final int STATUS_INDICATOR = 0x17;
private static final int STATUS_INDICATOR_LEN = 0x01; //, 0x0000, 0x0001),
private static final int STATUS_VALUE = 0x18;
private static final int STATUS_VALUE_LEN = 0x01; //, 0x0000, 0x0001),
private static final int MSE_TIME = 0x19;
public static final int INVALID_VALUE_PARAMETER = -1;
public static final int NOTIFICATION_STATUS_NO = 0;
public static final int NOTIFICATION_STATUS_YES = 1;
public static final int STATUS_INDICATOR_READ = 0;
public static final int STATUS_INDICATOR_DELETED = 1;
public static final int STATUS_VALUE_YES = 1;
public static final int STATUS_VALUE_NO = 0;
public static final int CHARSET_NATIVE = 0;
public static final int CHARSET_UTF8 = 1;
private int maxListCount = INVALID_VALUE_PARAMETER;
private int startOffset = INVALID_VALUE_PARAMETER;
private int filterMessageType = INVALID_VALUE_PARAMETER;
private long filterPeriodBegin = INVALID_VALUE_PARAMETER;
private long filterPeriodEnd = INVALID_VALUE_PARAMETER;
private int filterReadStatus = INVALID_VALUE_PARAMETER;
private String filterRecipient = null;
private String filterOriginator = null;
private int filterPriority = INVALID_VALUE_PARAMETER;
private int attachment = INVALID_VALUE_PARAMETER;
private int transparent = INVALID_VALUE_PARAMETER;
private int retry = INVALID_VALUE_PARAMETER;
private int newMessage = INVALID_VALUE_PARAMETER;
private int notificationStatus = INVALID_VALUE_PARAMETER;
private int masInstanceId = INVALID_VALUE_PARAMETER;
private long parameterMask = INVALID_VALUE_PARAMETER;
private int folderListingSize = INVALID_VALUE_PARAMETER;
private int messageListingSize = INVALID_VALUE_PARAMETER;
private int subjectLength = INVALID_VALUE_PARAMETER;
private int charset = INVALID_VALUE_PARAMETER;
private int fractionRequest = INVALID_VALUE_PARAMETER;
private int fractionDeliver = INVALID_VALUE_PARAMETER;
private int statusIndicator = INVALID_VALUE_PARAMETER;
private int statusValue = INVALID_VALUE_PARAMETER;
private long mseTime = INVALID_VALUE_PARAMETER;
/**
* Default constructor, used to build an application parameter object to be
* encoded. By default the member variables will be initialized to
* {@link INVALID_VALUE_PARAMETER} for values, and empty strings for String
* typed members.
*/
public BluetoothMapAppParams() {
}
/**
* Creates an application parameter object based on a application parameter
* OBEX header. The content of the {@link appParam} byte array will be
* parsed, and its content will be stored in the member variables.
* {@link INVALID_VALUE_PARAMETER} can be used to determine if a value is
* set or not, where strings will be empty, if {@link appParam} did not
* contain the parameter.
*
* @param appParams
* the byte array containing the application parameters OBEX
* header
* @throws IllegalArgumentException
* when a parameter does not respect the valid ranges specified
* in the MAP spec.
* @throws ParseException
* if a parameter string if formated incorrectly.
*/
public BluetoothMapAppParams(final byte[] appParams)
throws IllegalArgumentException, ParseException {
ParseParams(appParams);
}
/**
* Parse an application parameter OBEX header stored in a ByteArray.
*
* @param appParams
* the byte array containing the application parameters OBEX
* header
* @throws IllegalArgumentException
* when a parameter does not respect the valid ranges specified
* in the MAP spec.
* @throws ParseException
* if a parameter string if formated incorrectly.
*/
private void ParseParams(final byte[] appParams) throws ParseException,
IllegalArgumentException {
int i = 0;
int tagId, tagLength;
ByteBuffer appParamBuf = ByteBuffer.wrap(appParams);
appParamBuf.order(ByteOrder.BIG_ENDIAN);
while (i < appParams.length) {
tagId = appParams[i++] & 0xff; // Convert to unsigned to support values above 127
tagLength = appParams[i++] & 0xff; // Convert to unsigned to support values above 127
switch (tagId) {
case MAX_LIST_COUNT:
if (tagLength != MAX_LIST_COUNT_LEN) {
Log.w(TAG, "MAX_LIST_COUNT: Wrong length received: " + tagLength
+ " expected: " + MAX_LIST_COUNT_LEN);
break;
}
setMaxListCount(appParamBuf.getShort(i) & 0xffff); // Make it unsigned
break;
case START_OFFSET:
if (tagLength != START_OFFSET_LEN) {
Log.w(TAG, "START_OFFSET: Wrong length received: " + tagLength + " expected: "
+ START_OFFSET_LEN);
break;
}
setStartOffset(appParamBuf.getShort(i) & 0xffff); // Make it unsigned
break;
case FILTER_MESSAGE_TYPE:
if (tagLength != FILTER_MESSAGE_TYPE_LEN) {
Log.w(TAG, "FILTER_MESSAGE_TYPE: Wrong length received: " + tagLength + " expected: "
+ FILTER_MESSAGE_TYPE_LEN);
break;
}
setFilterMessageType(appParams[i] & 0x0f);
break;
case FILTER_PERIOD_BEGIN:
if(tagLength != 0) {
setFilterPeriodBegin(new String(appParams, i, tagLength));
}
break;
case FILTER_PERIOD_END:
if(tagLength != 0) {
setFilterPeriodEnd(new String(appParams, i, tagLength));
}
break;
case FILTER_READ_STATUS:
if (tagLength != FILTER_READ_STATUS_LEN) {
Log.w(TAG, "FILTER_READ_STATUS: Wrong length received: " + tagLength + " expected: "
+ FILTER_READ_STATUS_LEN);
break;
}
setFilterReadStatus(appParams[i] & 0x03); // Lower two bits
break;
case FILTER_RECIPIENT:
- setFilterRecipient(new String(appParams, i, tagLength));
+ setFilterRecipient(new String(appParams, i, tagLength - 1));
break;
case FILTER_ORIGINATOR:
- setFilterOriginator(new String(appParams, i, tagLength));
+ setFilterOriginator(new String(appParams, i, tagLength - 1));
break;
case FILTER_PRIORITY:
if (tagLength != FILTER_PRIORITY_LEN) {
Log.w(TAG, "FILTER_PRIORITY: Wrong length received: " + tagLength + " expected: "
+ FILTER_PRIORITY_LEN);
break;
}
setFilterPriority(appParams[i] & 0x03); // Lower two bits
break;
case ATTACHMENT:
if (tagLength != ATTACHMENT_LEN) {
Log.w(TAG, "ATTACHMENT: Wrong length received: " + tagLength + " expected: "
+ ATTACHMENT_LEN);
break;
}
setAttachment(appParams[i] & 0x01); // Lower bit
break;
case TRANSPARENT:
if (tagLength != TRANSPARENT_LEN) {
Log.w(TAG, "TRANSPARENT: Wrong length received: " + tagLength + " expected: "
+ TRANSPARENT_LEN);
break;
}
setTransparent(appParams[i] & 0x01); // Lower bit
break;
case RETRY:
if (tagLength != RETRY_LEN) {
Log.w(TAG, "RETRY: Wrong length received: " + tagLength + " expected: "
+ RETRY_LEN);
break;
}
setRetry(appParams[i] & 0x01); // Lower bit
break;
case NEW_MESSAGE:
if (tagLength != NEW_MESSAGE_LEN) {
Log.w(TAG, "NEW_MESSAGE: Wrong length received: " + tagLength + " expected: "
+ NEW_MESSAGE_LEN);
break;
}
setNewMessage(appParams[i] & 0x01); // Lower bit
break;
case NOTIFICATION_STATUS:
if (tagLength != NOTIFICATION_STATUS_LEN) {
Log.w(TAG, "NOTIFICATION_STATUS: Wrong length received: " + tagLength + " expected: "
+ NOTIFICATION_STATUS_LEN);
break;
}
setNotificationStatus(appParams[i] & 0x01); // Lower bit
break;
case MAS_INSTANCE_ID:
if (tagLength != MAS_INSTANCE_ID_LEN) {
Log.w(TAG, "MAS_INSTANCE_ID: Wrong length received: " + tagLength + " expected: "
+ MAS_INSTANCE_ID_LEN);
break;
}
setMasInstanceId(appParams[i] & 0xff);
break;
case PARAMETER_MASK:
if (tagLength != PARAMETER_MASK_LEN) {
Log.w(TAG, "PARAMETER_MASK: Wrong length received: " + tagLength + " expected: "
+ PARAMETER_MASK_LEN);
break;
}
setParameterMask(appParamBuf.getInt(i) & 0xffffffffL); // Make it unsigned
break;
case FOLDER_LISTING_SIZE:
if (tagLength != FOLDER_LISTING_SIZE_LEN) {
Log.w(TAG, "FOLDER_LISTING_SIZE: Wrong length received: " + tagLength + " expected: "
+ FOLDER_LISTING_SIZE_LEN);
break;
}
setFolderListingSize(appParamBuf.getShort(i) & 0xffff); // Make it unsigned
break;
case MESSAGE_LISTING_SIZE:
if (tagLength != MESSAGE_LISTING_SIZE_LEN) {
Log.w(TAG, "MESSAGE_LISTING_SIZE: Wrong length received: " + tagLength + " expected: "
+ MESSAGE_LISTING_SIZE_LEN);
break;
}
setMessageListingSize(appParamBuf.getShort(i) & 0xffff); // Make it unsigned
break;
case SUBJECT_LENGTH:
if (tagLength != SUBJECT_LENGTH_LEN) {
Log.w(TAG, "SUBJECT_LENGTH: Wrong length received: " + tagLength + " expected: "
+ SUBJECT_LENGTH_LEN);
break;
}
setSubjectLength(appParams[i] & 0xff);
break;
case CHARSET:
if (tagLength != CHARSET_LEN) {
Log.w(TAG, "CHARSET: Wrong length received: " + tagLength + " expected: "
+ CHARSET_LEN);
break;
}
setCharset(appParams[i] & 0x01); // Lower bit
break;
case FRACTION_REQUEST:
if (tagLength != FRACTION_REQUEST_LEN) {
Log.w(TAG, "FRACTION_REQUEST: Wrong length received: " + tagLength + " expected: "
+ FRACTION_REQUEST_LEN);
break;
}
setFractionRequest(appParams[i] & 0x01); // Lower bit
break;
case FRACTION_DELIVER:
if (tagLength != FRACTION_DELIVER_LEN) {
Log.w(TAG, "FRACTION_DELIVER: Wrong length received: " + tagLength + " expected: "
+ FRACTION_DELIVER_LEN);
break;
}
setFractionDeliver(appParams[i] & 0x01); // Lower bit
break;
case STATUS_INDICATOR:
if (tagLength != STATUS_INDICATOR_LEN) {
Log.w(TAG, "STATUS_INDICATOR: Wrong length received: " + tagLength + " expected: "
+ STATUS_INDICATOR_LEN);
break;
}
setStatusIndicator(appParams[i] & 0x01); // Lower bit
break;
case STATUS_VALUE:
if (tagLength != STATUS_VALUE_LEN) {
Log.w(TAG, "STATUS_VALUER: Wrong length received: " + tagLength + " expected: "
+ STATUS_VALUE_LEN);
break;
}
setStatusValue(appParams[i] & 0x01); // Lower bit
break;
case MSE_TIME:
setMseTime(new String(appParams, i, tagLength));
break;
default:
// Just skip unknown Tags, no need to report error
Log.w(TAG, "Unknown TagId received ( 0x" + Integer.toString(tagId, 16)
+ "), skipping...");
break;
}
i += tagLength; // Offset to next TagId
}
}
/**
* Get the approximate length needed to store the appParameters in a byte
* array.
*
* @return the length in bytes
* @throws UnsupportedEncodingException
* if the platform does not support UTF-8 encoding.
*/
private int getParamMaxLength() throws UnsupportedEncodingException {
int length = 0;
length += 25 * 2; // tagId + tagLength
length += 27; // fixed sizes
length += getFilterPeriodBegin() == INVALID_VALUE_PARAMETER ? 0 : 15;
length += getFilterPeriodEnd() == INVALID_VALUE_PARAMETER ? 0 : 15;
if (getFilterRecipient() != null)
length += getFilterRecipient().getBytes("UTF-8").length;
if (getFilterOriginator() != null)
length += getFilterOriginator().getBytes("UTF-8").length;
length += getMseTime() == INVALID_VALUE_PARAMETER ? 0 : 20;
return length;
}
/**
* Encode the application parameter object to a byte array.
*
* @return a byte Array representation of the application parameter object.
* @throws UnsupportedEncodingException
* if the platform does not support UTF-8 encoding.
*/
public byte[] EncodeParams() throws UnsupportedEncodingException {
ByteBuffer appParamBuf = ByteBuffer.allocate(getParamMaxLength());
appParamBuf.order(ByteOrder.BIG_ENDIAN);
byte[] retBuf;
if (getMaxListCount() != INVALID_VALUE_PARAMETER) {
appParamBuf.put((byte) MAX_LIST_COUNT);
appParamBuf.put((byte) MAX_LIST_COUNT_LEN);
appParamBuf.putShort((short) getMaxListCount());
}
if (getStartOffset() != INVALID_VALUE_PARAMETER) {
appParamBuf.put((byte) START_OFFSET);
appParamBuf.put((byte) START_OFFSET_LEN);
appParamBuf.putShort((short) getStartOffset());
}
if (getFilterMessageType() != INVALID_VALUE_PARAMETER) {
appParamBuf.put((byte) FILTER_MESSAGE_TYPE);
appParamBuf.put((byte) FILTER_MESSAGE_TYPE_LEN);
appParamBuf.put((byte) getFilterMessageType());
}
if (getFilterPeriodBegin() != INVALID_VALUE_PARAMETER) {
appParamBuf.put((byte) FILTER_PERIOD_BEGIN);
appParamBuf.put((byte) getFilterPeriodBeginString().getBytes("UTF-8").length);
appParamBuf.put(getFilterPeriodBeginString().getBytes("UTF-8"));
}
if (getFilterPeriodEnd() != INVALID_VALUE_PARAMETER) {
appParamBuf.put((byte) FILTER_PERIOD_END);
appParamBuf.put((byte) getFilterPeriodEndString().getBytes("UTF-8").length);
appParamBuf.put(getFilterPeriodEndString().getBytes("UTF-8"));
}
if (getFilterReadStatus() != INVALID_VALUE_PARAMETER) {
appParamBuf.put((byte) FILTER_READ_STATUS);
appParamBuf.put((byte) FILTER_READ_STATUS_LEN);
appParamBuf.put((byte) getFilterReadStatus());
}
if (getFilterRecipient() != null) {
appParamBuf.put((byte) FILTER_RECIPIENT);
appParamBuf.put((byte) getFilterRecipient().getBytes("UTF-8").length);
appParamBuf.put(getFilterRecipient().getBytes("UTF-8"));
}
if (getFilterOriginator() != null) {
appParamBuf.put((byte) FILTER_ORIGINATOR);
appParamBuf.put((byte) getFilterOriginator().getBytes("UTF-8").length);
appParamBuf.put(getFilterOriginator().getBytes("UTF-8"));
}
if (getFilterPriority() != INVALID_VALUE_PARAMETER) {
appParamBuf.put((byte) FILTER_PRIORITY);
appParamBuf.put((byte) FILTER_PRIORITY_LEN);
appParamBuf.put((byte) getFilterPriority());
}
if (getAttachment() != INVALID_VALUE_PARAMETER) {
appParamBuf.put((byte) ATTACHMENT);
appParamBuf.put((byte) ATTACHMENT_LEN);
appParamBuf.put((byte) getAttachment());
}
if (getTransparent() != INVALID_VALUE_PARAMETER) {
appParamBuf.put((byte) TRANSPARENT);
appParamBuf.put((byte) TRANSPARENT_LEN);
appParamBuf.put((byte) getTransparent());
}
if (getRetry() != INVALID_VALUE_PARAMETER) {
appParamBuf.put((byte) RETRY);
appParamBuf.put((byte) RETRY_LEN);
appParamBuf.put((byte) getRetry());
}
if (getNewMessage() != INVALID_VALUE_PARAMETER) {
appParamBuf.put((byte) NEW_MESSAGE);
appParamBuf.put((byte) NEW_MESSAGE_LEN);
appParamBuf.put((byte) getNewMessage());
}
if (getNotificationStatus() != INVALID_VALUE_PARAMETER) {
appParamBuf.put((byte) NOTIFICATION_STATUS);
appParamBuf.put((byte) NOTIFICATION_STATUS_LEN);
appParamBuf.putShort((short) getNotificationStatus());
}
if (getMasInstanceId() != INVALID_VALUE_PARAMETER) {
appParamBuf.put((byte) MAS_INSTANCE_ID);
appParamBuf.put((byte) MAS_INSTANCE_ID_LEN);
appParamBuf.put((byte) getMasInstanceId());
}
if (getParameterMask() != INVALID_VALUE_PARAMETER) {
appParamBuf.put((byte) PARAMETER_MASK);
appParamBuf.put((byte) PARAMETER_MASK_LEN);
appParamBuf.putInt((int) getParameterMask());
}
if (getFolderListingSize() != INVALID_VALUE_PARAMETER) {
appParamBuf.put((byte) FOLDER_LISTING_SIZE);
appParamBuf.put((byte) FOLDER_LISTING_SIZE_LEN);
appParamBuf.putShort((short) getFolderListingSize());
}
if (getMessageListingSize() != INVALID_VALUE_PARAMETER) {
appParamBuf.put((byte) MESSAGE_LISTING_SIZE);
appParamBuf.put((byte) MESSAGE_LISTING_SIZE_LEN);
appParamBuf.putShort((short) getMessageListingSize());
}
if (getSubjectLength() != INVALID_VALUE_PARAMETER) {
appParamBuf.put((byte) SUBJECT_LENGTH);
appParamBuf.put((byte) SUBJECT_LENGTH_LEN);
appParamBuf.put((byte) getSubjectLength());
}
if (getCharset() != INVALID_VALUE_PARAMETER) {
appParamBuf.put((byte) CHARSET);
appParamBuf.put((byte) CHARSET_LEN);
appParamBuf.put((byte) getCharset());
}
if (getFractionRequest() != INVALID_VALUE_PARAMETER) {
appParamBuf.put((byte) FRACTION_REQUEST);
appParamBuf.put((byte) FRACTION_REQUEST_LEN);
appParamBuf.put((byte) getFractionRequest());
}
if (getFractionDeliver() != INVALID_VALUE_PARAMETER) {
appParamBuf.put((byte) FRACTION_DELIVER);
appParamBuf.put((byte) FRACTION_DELIVER_LEN);
appParamBuf.put((byte) getFractionDeliver());
}
if (getStatusIndicator() != INVALID_VALUE_PARAMETER) {
appParamBuf.put((byte) STATUS_INDICATOR);
appParamBuf.put((byte) STATUS_INDICATOR_LEN);
appParamBuf.put((byte) getStatusIndicator());
}
if (getStatusValue() != INVALID_VALUE_PARAMETER) {
appParamBuf.put((byte) STATUS_VALUE);
appParamBuf.put((byte) STATUS_VALUE_LEN);
appParamBuf.put((byte) getStatusValue());
}
if (getMseTime() != INVALID_VALUE_PARAMETER) {
appParamBuf.put((byte) MSE_TIME);
appParamBuf.put((byte) getMseTimeString().getBytes("UTF-8").length);
appParamBuf.put(getMseTimeString().getBytes("UTF-8"));
}
// We need to reduce the length of the array to match the content
retBuf = Arrays.copyOfRange(appParamBuf.array(), appParamBuf.arrayOffset(),
appParamBuf.arrayOffset() + appParamBuf.position());
return retBuf;
}
public int getMaxListCount() {
return maxListCount;
}
public void setMaxListCount(int maxListCount) throws IllegalArgumentException {
if (maxListCount < 0 || maxListCount > 0xFFFF)
throw new IllegalArgumentException("Out of range, valid range is 0x0000 to 0xFFFF");
this.maxListCount = maxListCount;
}
public int getStartOffset() {
return startOffset;
}
public void setStartOffset(int startOffset) throws IllegalArgumentException {
if (startOffset < 0 || startOffset > 0xFFFF)
throw new IllegalArgumentException("Out of range, valid range is 0x0000 to 0xFFFF");
this.startOffset = startOffset;
}
public int getFilterMessageType() {
return filterMessageType;
}
public void setFilterMessageType(int filterMessageType) throws IllegalArgumentException {
if (filterMessageType < 0 || filterMessageType > 0x000F)
throw new IllegalArgumentException("Out of range, valid range is 0x0000 to 0x000F");
this.filterMessageType = filterMessageType;
}
public long getFilterPeriodBegin() {
return filterPeriodBegin;
}
public String getFilterPeriodBeginString() {
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
Date date = new Date(filterPeriodBegin);
return format.format(date); // Format to YYYYMMDDTHHMMSS local time
}
public void setFilterPeriodBegin(long filterPeriodBegin) {
this.filterPeriodBegin = filterPeriodBegin;
}
public void setFilterPeriodBegin(String filterPeriodBegin) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
Date date = format.parse(filterPeriodBegin);
this.filterPeriodBegin = date.getTime();
}
public long getFilterPeriodEnd() {
return filterPeriodEnd;
}
public String getFilterPeriodEndString() {
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
Date date = new Date(filterPeriodEnd);
return format.format(date); // Format to YYYYMMDDTHHMMSS local time
}
public void setFilterPeriodEnd(long filterPeriodEnd) {
this.filterPeriodEnd = filterPeriodEnd;
}
public void setFilterPeriodEnd(String filterPeriodEnd) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
Date date = format.parse(filterPeriodEnd);
this.filterPeriodEnd = date.getTime();
}
public int getFilterReadStatus() {
return filterReadStatus;
}
public void setFilterReadStatus(int filterReadStatus) throws IllegalArgumentException {
if (filterReadStatus < 0 || filterReadStatus > 0x0002)
throw new IllegalArgumentException("Out of range, valid range is 0x0000 to 0x0002");
this.filterReadStatus = filterReadStatus;
}
public String getFilterRecipient() {
return filterRecipient;
}
public void setFilterRecipient(String filterRecipient) {
this.filterRecipient = filterRecipient;
}
public String getFilterOriginator() {
return filterOriginator;
}
public void setFilterOriginator(String filterOriginator) {
this.filterOriginator = filterOriginator;
}
public int getFilterPriority() {
return filterPriority;
}
public void setFilterPriority(int filterPriority) throws IllegalArgumentException {
if (filterPriority < 0 || filterPriority > 0x0002)
throw new IllegalArgumentException("Out of range, valid range is 0x0000 to 0x0002");
this.filterPriority = filterPriority;
}
public int getAttachment() {
return attachment;
}
public void setAttachment(int attachment) throws IllegalArgumentException {
if (attachment < 0 || attachment > 0x0001)
throw new IllegalArgumentException("Out of range, valid range is 0x0000 to 0x0001");
this.attachment = attachment;
}
public int getTransparent() {
return transparent;
}
public void setTransparent(int transparent) throws IllegalArgumentException {
if (transparent < 0 || transparent > 0x0001)
throw new IllegalArgumentException("Out of range, valid range is 0x0000 to 0x0001");
this.transparent = transparent;
}
public int getRetry() {
return retry;
}
public void setRetry(int retry) throws IllegalArgumentException {
if (retry < 0 || retry > 0x0001)
throw new IllegalArgumentException("Out of range, valid range is 0x0000 to 0x0001");
this.retry = retry;
}
public int getNewMessage() {
return newMessage;
}
public void setNewMessage(int newMessage) throws IllegalArgumentException {
if (newMessage < 0 || newMessage > 0x0001)
throw new IllegalArgumentException("Out of range, valid range is 0x0000 to 0x0001");
this.newMessage = newMessage;
}
public int getNotificationStatus() {
return notificationStatus;
}
public void setNotificationStatus(int notificationStatus) throws IllegalArgumentException {
if (notificationStatus < 0 || notificationStatus > 0x0001)
throw new IllegalArgumentException("Out of range, valid range is 0x0000 to 0x0001");
this.notificationStatus = notificationStatus;
}
public int getMasInstanceId() {
return masInstanceId;
}
public void setMasInstanceId(int masInstanceId) {
if (masInstanceId < 0 || masInstanceId > 0x00FF)
throw new IllegalArgumentException("Out of range, valid range is 0x0000 to 0x00FF");
this.masInstanceId = masInstanceId;
}
public long getParameterMask() {
return parameterMask;
}
public void setParameterMask(long parameterMask) {
if (parameterMask < 0 || parameterMask > 0xFFFFFFFFL)
throw new IllegalArgumentException("Out of range, valid range is 0x0000 to 0xFFFFFFFF");
this.parameterMask = parameterMask;
}
public int getFolderListingSize() {
return folderListingSize;
}
public void setFolderListingSize(int folderListingSize) {
if (folderListingSize < 0 || folderListingSize > 0xFFFF)
throw new IllegalArgumentException("Out of range, valid range is 0x0000 to 0xFFFF");
this.folderListingSize = folderListingSize;
}
public int getMessageListingSize() {
return messageListingSize;
}
public void setMessageListingSize(int messageListingSize) {
if (messageListingSize < 0 || messageListingSize > 0xFFFF)
throw new IllegalArgumentException("Out of range, valid range is 0x0000 to 0xFFFF");
this.messageListingSize = messageListingSize;
}
public int getSubjectLength() {
return subjectLength;
}
public void setSubjectLength(int subjectLength) {
if (subjectLength < 0 || subjectLength > 0xFF)
throw new IllegalArgumentException("Out of range, valid range is 0x0000 to 0x00FF");
this.subjectLength = subjectLength;
}
public int getCharset() {
return charset;
}
public void setCharset(int charset) {
if (charset < 0 || charset > 0x1)
throw new IllegalArgumentException("Out of range: " + charset + ", valid range is 0x0000 to 0x0001");
this.charset = charset;
}
public int getFractionRequest() {
return fractionRequest;
}
public void setFractionRequest(int fractionRequest) {
if (fractionRequest < 0 || fractionRequest > 0x1)
throw new IllegalArgumentException("Out of range, valid range is 0x0000 to 0x0001");
this.fractionRequest = fractionRequest;
}
public int getFractionDeliver() {
return fractionDeliver;
}
public void setFractionDeliver(int fractionDeliver) {
if (fractionDeliver < 0 || fractionDeliver > 0x1)
throw new IllegalArgumentException("Out of range, valid range is 0x0000 to 0x0001");
this.fractionDeliver = fractionDeliver;
}
public int getStatusIndicator() {
return statusIndicator;
}
public void setStatusIndicator(int statusIndicator) {
if (statusIndicator < 0 || statusIndicator > 0x1)
throw new IllegalArgumentException("Out of range, valid range is 0x0000 to 0x0001");
this.statusIndicator = statusIndicator;
}
public int getStatusValue() {
return statusValue;
}
public void setStatusValue(int statusValue) {
if (statusValue < 0 || statusValue > 0x1)
throw new IllegalArgumentException("Out of range, valid range is 0x0000 to 0x0001");
this.statusValue = statusValue;
}
public long getMseTime() {
return mseTime;
}
public String getMseTimeString() {
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd'T'HHmmssZ");
Date date = new Date(getMseTime());
return format.format(date); // Format to YYYYMMDDTHHMMSS±hhmm UTC time ± offset
}
public void setMseTime(long mseTime) {
this.mseTime = mseTime;
}
public void setMseTime(String mseTime) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd'T'HHmmssZ");
Date date = format.parse(mseTime);
this.mseTime = date.getTime();
}
}
| false | true | private void ParseParams(final byte[] appParams) throws ParseException,
IllegalArgumentException {
int i = 0;
int tagId, tagLength;
ByteBuffer appParamBuf = ByteBuffer.wrap(appParams);
appParamBuf.order(ByteOrder.BIG_ENDIAN);
while (i < appParams.length) {
tagId = appParams[i++] & 0xff; // Convert to unsigned to support values above 127
tagLength = appParams[i++] & 0xff; // Convert to unsigned to support values above 127
switch (tagId) {
case MAX_LIST_COUNT:
if (tagLength != MAX_LIST_COUNT_LEN) {
Log.w(TAG, "MAX_LIST_COUNT: Wrong length received: " + tagLength
+ " expected: " + MAX_LIST_COUNT_LEN);
break;
}
setMaxListCount(appParamBuf.getShort(i) & 0xffff); // Make it unsigned
break;
case START_OFFSET:
if (tagLength != START_OFFSET_LEN) {
Log.w(TAG, "START_OFFSET: Wrong length received: " + tagLength + " expected: "
+ START_OFFSET_LEN);
break;
}
setStartOffset(appParamBuf.getShort(i) & 0xffff); // Make it unsigned
break;
case FILTER_MESSAGE_TYPE:
if (tagLength != FILTER_MESSAGE_TYPE_LEN) {
Log.w(TAG, "FILTER_MESSAGE_TYPE: Wrong length received: " + tagLength + " expected: "
+ FILTER_MESSAGE_TYPE_LEN);
break;
}
setFilterMessageType(appParams[i] & 0x0f);
break;
case FILTER_PERIOD_BEGIN:
if(tagLength != 0) {
setFilterPeriodBegin(new String(appParams, i, tagLength));
}
break;
case FILTER_PERIOD_END:
if(tagLength != 0) {
setFilterPeriodEnd(new String(appParams, i, tagLength));
}
break;
case FILTER_READ_STATUS:
if (tagLength != FILTER_READ_STATUS_LEN) {
Log.w(TAG, "FILTER_READ_STATUS: Wrong length received: " + tagLength + " expected: "
+ FILTER_READ_STATUS_LEN);
break;
}
setFilterReadStatus(appParams[i] & 0x03); // Lower two bits
break;
case FILTER_RECIPIENT:
setFilterRecipient(new String(appParams, i, tagLength));
break;
case FILTER_ORIGINATOR:
setFilterOriginator(new String(appParams, i, tagLength));
break;
case FILTER_PRIORITY:
if (tagLength != FILTER_PRIORITY_LEN) {
Log.w(TAG, "FILTER_PRIORITY: Wrong length received: " + tagLength + " expected: "
+ FILTER_PRIORITY_LEN);
break;
}
setFilterPriority(appParams[i] & 0x03); // Lower two bits
break;
case ATTACHMENT:
if (tagLength != ATTACHMENT_LEN) {
Log.w(TAG, "ATTACHMENT: Wrong length received: " + tagLength + " expected: "
+ ATTACHMENT_LEN);
break;
}
setAttachment(appParams[i] & 0x01); // Lower bit
break;
case TRANSPARENT:
if (tagLength != TRANSPARENT_LEN) {
Log.w(TAG, "TRANSPARENT: Wrong length received: " + tagLength + " expected: "
+ TRANSPARENT_LEN);
break;
}
setTransparent(appParams[i] & 0x01); // Lower bit
break;
case RETRY:
if (tagLength != RETRY_LEN) {
Log.w(TAG, "RETRY: Wrong length received: " + tagLength + " expected: "
+ RETRY_LEN);
break;
}
setRetry(appParams[i] & 0x01); // Lower bit
break;
case NEW_MESSAGE:
if (tagLength != NEW_MESSAGE_LEN) {
Log.w(TAG, "NEW_MESSAGE: Wrong length received: " + tagLength + " expected: "
+ NEW_MESSAGE_LEN);
break;
}
setNewMessage(appParams[i] & 0x01); // Lower bit
break;
case NOTIFICATION_STATUS:
if (tagLength != NOTIFICATION_STATUS_LEN) {
Log.w(TAG, "NOTIFICATION_STATUS: Wrong length received: " + tagLength + " expected: "
+ NOTIFICATION_STATUS_LEN);
break;
}
setNotificationStatus(appParams[i] & 0x01); // Lower bit
break;
case MAS_INSTANCE_ID:
if (tagLength != MAS_INSTANCE_ID_LEN) {
Log.w(TAG, "MAS_INSTANCE_ID: Wrong length received: " + tagLength + " expected: "
+ MAS_INSTANCE_ID_LEN);
break;
}
setMasInstanceId(appParams[i] & 0xff);
break;
case PARAMETER_MASK:
if (tagLength != PARAMETER_MASK_LEN) {
Log.w(TAG, "PARAMETER_MASK: Wrong length received: " + tagLength + " expected: "
+ PARAMETER_MASK_LEN);
break;
}
setParameterMask(appParamBuf.getInt(i) & 0xffffffffL); // Make it unsigned
break;
case FOLDER_LISTING_SIZE:
if (tagLength != FOLDER_LISTING_SIZE_LEN) {
Log.w(TAG, "FOLDER_LISTING_SIZE: Wrong length received: " + tagLength + " expected: "
+ FOLDER_LISTING_SIZE_LEN);
break;
}
setFolderListingSize(appParamBuf.getShort(i) & 0xffff); // Make it unsigned
break;
case MESSAGE_LISTING_SIZE:
if (tagLength != MESSAGE_LISTING_SIZE_LEN) {
Log.w(TAG, "MESSAGE_LISTING_SIZE: Wrong length received: " + tagLength + " expected: "
+ MESSAGE_LISTING_SIZE_LEN);
break;
}
setMessageListingSize(appParamBuf.getShort(i) & 0xffff); // Make it unsigned
break;
case SUBJECT_LENGTH:
if (tagLength != SUBJECT_LENGTH_LEN) {
Log.w(TAG, "SUBJECT_LENGTH: Wrong length received: " + tagLength + " expected: "
+ SUBJECT_LENGTH_LEN);
break;
}
setSubjectLength(appParams[i] & 0xff);
break;
case CHARSET:
if (tagLength != CHARSET_LEN) {
Log.w(TAG, "CHARSET: Wrong length received: " + tagLength + " expected: "
+ CHARSET_LEN);
break;
}
setCharset(appParams[i] & 0x01); // Lower bit
break;
case FRACTION_REQUEST:
if (tagLength != FRACTION_REQUEST_LEN) {
Log.w(TAG, "FRACTION_REQUEST: Wrong length received: " + tagLength + " expected: "
+ FRACTION_REQUEST_LEN);
break;
}
setFractionRequest(appParams[i] & 0x01); // Lower bit
break;
case FRACTION_DELIVER:
if (tagLength != FRACTION_DELIVER_LEN) {
Log.w(TAG, "FRACTION_DELIVER: Wrong length received: " + tagLength + " expected: "
+ FRACTION_DELIVER_LEN);
break;
}
setFractionDeliver(appParams[i] & 0x01); // Lower bit
break;
case STATUS_INDICATOR:
if (tagLength != STATUS_INDICATOR_LEN) {
Log.w(TAG, "STATUS_INDICATOR: Wrong length received: " + tagLength + " expected: "
+ STATUS_INDICATOR_LEN);
break;
}
setStatusIndicator(appParams[i] & 0x01); // Lower bit
break;
case STATUS_VALUE:
if (tagLength != STATUS_VALUE_LEN) {
Log.w(TAG, "STATUS_VALUER: Wrong length received: " + tagLength + " expected: "
+ STATUS_VALUE_LEN);
break;
}
setStatusValue(appParams[i] & 0x01); // Lower bit
break;
case MSE_TIME:
setMseTime(new String(appParams, i, tagLength));
break;
default:
// Just skip unknown Tags, no need to report error
Log.w(TAG, "Unknown TagId received ( 0x" + Integer.toString(tagId, 16)
+ "), skipping...");
break;
}
i += tagLength; // Offset to next TagId
}
}
| private void ParseParams(final byte[] appParams) throws ParseException,
IllegalArgumentException {
int i = 0;
int tagId, tagLength;
ByteBuffer appParamBuf = ByteBuffer.wrap(appParams);
appParamBuf.order(ByteOrder.BIG_ENDIAN);
while (i < appParams.length) {
tagId = appParams[i++] & 0xff; // Convert to unsigned to support values above 127
tagLength = appParams[i++] & 0xff; // Convert to unsigned to support values above 127
switch (tagId) {
case MAX_LIST_COUNT:
if (tagLength != MAX_LIST_COUNT_LEN) {
Log.w(TAG, "MAX_LIST_COUNT: Wrong length received: " + tagLength
+ " expected: " + MAX_LIST_COUNT_LEN);
break;
}
setMaxListCount(appParamBuf.getShort(i) & 0xffff); // Make it unsigned
break;
case START_OFFSET:
if (tagLength != START_OFFSET_LEN) {
Log.w(TAG, "START_OFFSET: Wrong length received: " + tagLength + " expected: "
+ START_OFFSET_LEN);
break;
}
setStartOffset(appParamBuf.getShort(i) & 0xffff); // Make it unsigned
break;
case FILTER_MESSAGE_TYPE:
if (tagLength != FILTER_MESSAGE_TYPE_LEN) {
Log.w(TAG, "FILTER_MESSAGE_TYPE: Wrong length received: " + tagLength + " expected: "
+ FILTER_MESSAGE_TYPE_LEN);
break;
}
setFilterMessageType(appParams[i] & 0x0f);
break;
case FILTER_PERIOD_BEGIN:
if(tagLength != 0) {
setFilterPeriodBegin(new String(appParams, i, tagLength));
}
break;
case FILTER_PERIOD_END:
if(tagLength != 0) {
setFilterPeriodEnd(new String(appParams, i, tagLength));
}
break;
case FILTER_READ_STATUS:
if (tagLength != FILTER_READ_STATUS_LEN) {
Log.w(TAG, "FILTER_READ_STATUS: Wrong length received: " + tagLength + " expected: "
+ FILTER_READ_STATUS_LEN);
break;
}
setFilterReadStatus(appParams[i] & 0x03); // Lower two bits
break;
case FILTER_RECIPIENT:
setFilterRecipient(new String(appParams, i, tagLength - 1));
break;
case FILTER_ORIGINATOR:
setFilterOriginator(new String(appParams, i, tagLength - 1));
break;
case FILTER_PRIORITY:
if (tagLength != FILTER_PRIORITY_LEN) {
Log.w(TAG, "FILTER_PRIORITY: Wrong length received: " + tagLength + " expected: "
+ FILTER_PRIORITY_LEN);
break;
}
setFilterPriority(appParams[i] & 0x03); // Lower two bits
break;
case ATTACHMENT:
if (tagLength != ATTACHMENT_LEN) {
Log.w(TAG, "ATTACHMENT: Wrong length received: " + tagLength + " expected: "
+ ATTACHMENT_LEN);
break;
}
setAttachment(appParams[i] & 0x01); // Lower bit
break;
case TRANSPARENT:
if (tagLength != TRANSPARENT_LEN) {
Log.w(TAG, "TRANSPARENT: Wrong length received: " + tagLength + " expected: "
+ TRANSPARENT_LEN);
break;
}
setTransparent(appParams[i] & 0x01); // Lower bit
break;
case RETRY:
if (tagLength != RETRY_LEN) {
Log.w(TAG, "RETRY: Wrong length received: " + tagLength + " expected: "
+ RETRY_LEN);
break;
}
setRetry(appParams[i] & 0x01); // Lower bit
break;
case NEW_MESSAGE:
if (tagLength != NEW_MESSAGE_LEN) {
Log.w(TAG, "NEW_MESSAGE: Wrong length received: " + tagLength + " expected: "
+ NEW_MESSAGE_LEN);
break;
}
setNewMessage(appParams[i] & 0x01); // Lower bit
break;
case NOTIFICATION_STATUS:
if (tagLength != NOTIFICATION_STATUS_LEN) {
Log.w(TAG, "NOTIFICATION_STATUS: Wrong length received: " + tagLength + " expected: "
+ NOTIFICATION_STATUS_LEN);
break;
}
setNotificationStatus(appParams[i] & 0x01); // Lower bit
break;
case MAS_INSTANCE_ID:
if (tagLength != MAS_INSTANCE_ID_LEN) {
Log.w(TAG, "MAS_INSTANCE_ID: Wrong length received: " + tagLength + " expected: "
+ MAS_INSTANCE_ID_LEN);
break;
}
setMasInstanceId(appParams[i] & 0xff);
break;
case PARAMETER_MASK:
if (tagLength != PARAMETER_MASK_LEN) {
Log.w(TAG, "PARAMETER_MASK: Wrong length received: " + tagLength + " expected: "
+ PARAMETER_MASK_LEN);
break;
}
setParameterMask(appParamBuf.getInt(i) & 0xffffffffL); // Make it unsigned
break;
case FOLDER_LISTING_SIZE:
if (tagLength != FOLDER_LISTING_SIZE_LEN) {
Log.w(TAG, "FOLDER_LISTING_SIZE: Wrong length received: " + tagLength + " expected: "
+ FOLDER_LISTING_SIZE_LEN);
break;
}
setFolderListingSize(appParamBuf.getShort(i) & 0xffff); // Make it unsigned
break;
case MESSAGE_LISTING_SIZE:
if (tagLength != MESSAGE_LISTING_SIZE_LEN) {
Log.w(TAG, "MESSAGE_LISTING_SIZE: Wrong length received: " + tagLength + " expected: "
+ MESSAGE_LISTING_SIZE_LEN);
break;
}
setMessageListingSize(appParamBuf.getShort(i) & 0xffff); // Make it unsigned
break;
case SUBJECT_LENGTH:
if (tagLength != SUBJECT_LENGTH_LEN) {
Log.w(TAG, "SUBJECT_LENGTH: Wrong length received: " + tagLength + " expected: "
+ SUBJECT_LENGTH_LEN);
break;
}
setSubjectLength(appParams[i] & 0xff);
break;
case CHARSET:
if (tagLength != CHARSET_LEN) {
Log.w(TAG, "CHARSET: Wrong length received: " + tagLength + " expected: "
+ CHARSET_LEN);
break;
}
setCharset(appParams[i] & 0x01); // Lower bit
break;
case FRACTION_REQUEST:
if (tagLength != FRACTION_REQUEST_LEN) {
Log.w(TAG, "FRACTION_REQUEST: Wrong length received: " + tagLength + " expected: "
+ FRACTION_REQUEST_LEN);
break;
}
setFractionRequest(appParams[i] & 0x01); // Lower bit
break;
case FRACTION_DELIVER:
if (tagLength != FRACTION_DELIVER_LEN) {
Log.w(TAG, "FRACTION_DELIVER: Wrong length received: " + tagLength + " expected: "
+ FRACTION_DELIVER_LEN);
break;
}
setFractionDeliver(appParams[i] & 0x01); // Lower bit
break;
case STATUS_INDICATOR:
if (tagLength != STATUS_INDICATOR_LEN) {
Log.w(TAG, "STATUS_INDICATOR: Wrong length received: " + tagLength + " expected: "
+ STATUS_INDICATOR_LEN);
break;
}
setStatusIndicator(appParams[i] & 0x01); // Lower bit
break;
case STATUS_VALUE:
if (tagLength != STATUS_VALUE_LEN) {
Log.w(TAG, "STATUS_VALUER: Wrong length received: " + tagLength + " expected: "
+ STATUS_VALUE_LEN);
break;
}
setStatusValue(appParams[i] & 0x01); // Lower bit
break;
case MSE_TIME:
setMseTime(new String(appParams, i, tagLength));
break;
default:
// Just skip unknown Tags, no need to report error
Log.w(TAG, "Unknown TagId received ( 0x" + Integer.toString(tagId, 16)
+ "), skipping...");
break;
}
i += tagLength; // Offset to next TagId
}
}
|
diff --git a/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/ui/actions/PartialNewSessionAction.java b/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/ui/actions/PartialNewSessionAction.java
index aa2c9bd87..29992ceaf 100644
--- a/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/ui/actions/PartialNewSessionAction.java
+++ b/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/ui/actions/PartialNewSessionAction.java
@@ -1,58 +1,58 @@
/*
* DPP - Serious Distributed Pair Programming
* (c) Freie Universitaet Berlin - Fachbereich Mathematik und Informatik - 2006
* (c) Riad Djemili - 2006
*
* 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 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 de.fu_berlin.inf.dpp.ui.actions;
import org.apache.log4j.Logger;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.window.Window;
import de.fu_berlin.inf.dpp.annotations.Component;
import de.fu_berlin.inf.dpp.ui.PartialProjectSelectionDialog;
import de.fu_berlin.inf.dpp.util.Util;
/**
* Start to share a project (a "session").
*
* This action is created by Eclipse!
*
* @author rdjemili
*/
@Component(module = "action")
public class PartialNewSessionAction extends GeneralNewSessionAction {
private static final Logger log = Logger
.getLogger(PartialNewSessionAction.class.getName());
/**
* @review runSafe OK
*/
public void run(IAction action) {
final PartialProjectSelectionDialog dialog = new PartialProjectSelectionDialog(
null, this.selectedProject);
if (dialog.open() == Window.OK) {
Util.runSafeSync(log, new Runnable() {
public void run() {
- runNewSession(dialog.getSelectedResources(), true);
+ runNewSession(dialog.getSelectedResources(), false);
}
});
}
}
}
| true | true | public void run(IAction action) {
final PartialProjectSelectionDialog dialog = new PartialProjectSelectionDialog(
null, this.selectedProject);
if (dialog.open() == Window.OK) {
Util.runSafeSync(log, new Runnable() {
public void run() {
runNewSession(dialog.getSelectedResources(), true);
}
});
}
}
| public void run(IAction action) {
final PartialProjectSelectionDialog dialog = new PartialProjectSelectionDialog(
null, this.selectedProject);
if (dialog.open() == Window.OK) {
Util.runSafeSync(log, new Runnable() {
public void run() {
runNewSession(dialog.getSelectedResources(), false);
}
});
}
}
|
diff --git a/org.openscada.ae/src/org/openscada/ae/MonitorStatusInformation.java b/org.openscada.ae/src/org/openscada/ae/MonitorStatusInformation.java
index 049637ef4..4f111466b 100644
--- a/org.openscada.ae/src/org/openscada/ae/MonitorStatusInformation.java
+++ b/org.openscada.ae/src/org/openscada/ae/MonitorStatusInformation.java
@@ -1,171 +1,171 @@
/*
* This file is part of the OpenSCADA project
* Copyright (C) 2006-2010 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.ae;
import java.io.Serializable;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.openscada.core.Variant;
import org.openscada.utils.lang.Immutable;
@Immutable
public class MonitorStatusInformation implements Serializable
{
private static final long serialVersionUID = 6138369511783020510L;
private final String id;
private final MonitorStatus status;
private final Date statusTimestamp;
private final Variant value;
private final String lastAknUser;
private final Date lastAknTimestamp;
private final Map<String, Variant> attributes;
public MonitorStatusInformation ( final String id, final MonitorStatus status, final Date statusTimestamp, final Variant value, final Date lastAknTimestamp, final String lastAknUser, final Map<String, Variant> attributes )
{
super ();
this.id = id;
this.status = status;
this.statusTimestamp = statusTimestamp;
this.value = value;
this.lastAknTimestamp = lastAknTimestamp;
this.lastAknUser = lastAknUser;
if ( attributes == null )
{
this.attributes = Collections.emptyMap ();
}
else
{
this.attributes = new HashMap<String, Variant> ( attributes );
}
if ( id == null )
{
- throw new NullPointerException ( "'status' must not be null" );
+ throw new NullPointerException ( "'id' must not be null" );
}
if ( status == null )
{
throw new NullPointerException ( "'status' must not be null" );
}
if ( statusTimestamp == null )
{
throw new NullPointerException ( "'statusTimestamp' must not be null" );
}
}
public String getId ()
{
return this.id;
}
public MonitorStatus getStatus ()
{
return this.status;
}
public Date getStatusTimestamp ()
{
return this.statusTimestamp;
}
public Variant getValue ()
{
return this.value;
}
public String getLastAknUser ()
{
return this.lastAknUser;
}
public Date getLastAknTimestamp ()
{
return this.lastAknTimestamp;
}
public Map<String, Variant> getAttributes ()
{
return Collections.unmodifiableMap ( this.attributes );
}
@Override
public int hashCode ()
{
final int prime = 31;
int result = 1;
result = prime * result + ( this.id == null ? 0 : this.id.hashCode () );
return result;
}
@Override
public boolean equals ( final Object obj )
{
if ( this == obj )
{
return true;
}
if ( obj == null )
{
return false;
}
if ( ! ( obj instanceof MonitorStatusInformation ) )
{
return false;
}
final MonitorStatusInformation other = (MonitorStatusInformation)obj;
if ( this.id == null )
{
if ( other.id != null )
{
return false;
}
}
else if ( !this.id.equals ( other.id ) )
{
return false;
}
return true;
}
@Override
public String toString ()
{
final StringBuilder sb = new StringBuilder ();
sb.append ( this.id + "(" );
sb.append ( "status=" + this.status );
sb.append ( ")" );
return sb.toString ();
}
}
| true | true | public MonitorStatusInformation ( final String id, final MonitorStatus status, final Date statusTimestamp, final Variant value, final Date lastAknTimestamp, final String lastAknUser, final Map<String, Variant> attributes )
{
super ();
this.id = id;
this.status = status;
this.statusTimestamp = statusTimestamp;
this.value = value;
this.lastAknTimestamp = lastAknTimestamp;
this.lastAknUser = lastAknUser;
if ( attributes == null )
{
this.attributes = Collections.emptyMap ();
}
else
{
this.attributes = new HashMap<String, Variant> ( attributes );
}
if ( id == null )
{
throw new NullPointerException ( "'status' must not be null" );
}
if ( status == null )
{
throw new NullPointerException ( "'status' must not be null" );
}
if ( statusTimestamp == null )
{
throw new NullPointerException ( "'statusTimestamp' must not be null" );
}
}
| public MonitorStatusInformation ( final String id, final MonitorStatus status, final Date statusTimestamp, final Variant value, final Date lastAknTimestamp, final String lastAknUser, final Map<String, Variant> attributes )
{
super ();
this.id = id;
this.status = status;
this.statusTimestamp = statusTimestamp;
this.value = value;
this.lastAknTimestamp = lastAknTimestamp;
this.lastAknUser = lastAknUser;
if ( attributes == null )
{
this.attributes = Collections.emptyMap ();
}
else
{
this.attributes = new HashMap<String, Variant> ( attributes );
}
if ( id == null )
{
throw new NullPointerException ( "'id' must not be null" );
}
if ( status == null )
{
throw new NullPointerException ( "'status' must not be null" );
}
if ( statusTimestamp == null )
{
throw new NullPointerException ( "'statusTimestamp' must not be null" );
}
}
|
diff --git a/bundles/org.eclipse.rap.ui/src/org/eclipse/ui/internal/UIPreferenceInitializer.java b/bundles/org.eclipse.rap.ui/src/org/eclipse/ui/internal/UIPreferenceInitializer.java
index a10f9f23d..9ac4022be 100755
--- a/bundles/org.eclipse.rap.ui/src/org/eclipse/ui/internal/UIPreferenceInitializer.java
+++ b/bundles/org.eclipse.rap.ui/src/org/eclipse/ui/internal/UIPreferenceInitializer.java
@@ -1,201 +1,202 @@
/*******************************************************************************
* Copyright (c) 2000, 2008 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
* Kiryl Kazakevich, Intel - bug 88359
* Tonny Madsen, RCP Company - bug 201055
*******************************************************************************/
package org.eclipse.ui.internal;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
import org.eclipse.core.runtime.preferences.DefaultScope;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import org.eclipse.core.runtime.preferences.IScopeContext;
import org.eclipse.core.runtime.preferences.InstanceScope;
import org.eclipse.core.runtime.preferences.IEclipsePreferences.NodeChangeEvent;
import org.eclipse.ui.IWorkbenchPreferenceConstants;
import org.osgi.service.prefs.BackingStoreException;
/**
* Implementation of the UI plugin's preference extension's customization
* element. This is needed in order to force the UI plugin's preferences to be
* initialized properly when running without
* org.eclipse.core.runtime.compatibility. For more details, see bug 58975 - New
* preference mechanism does not properly initialize defaults.
*
* @since 3.0
*/
public class UIPreferenceInitializer extends AbstractPreferenceInitializer {
public void initializeDefaultPreferences() {
IScopeContext context = new DefaultScope();
IEclipsePreferences node = context.getNode(UIPlugin.getDefault()
.getBundle().getSymbolicName());
node.put(IWorkbenchPreferenceConstants.OPEN_NEW_PERSPECTIVE,
IWorkbenchPreferenceConstants.OPEN_PERSPECTIVE_REPLACE);
// Deprecated but kept for backwards compatibility
// RAP [bm]: disabled
// node.put(IWorkbenchPreferenceConstants.PROJECT_OPEN_NEW_PERSPECTIVE,
// IWorkbenchPreferenceConstants.OPEN_PERSPECTIVE_REPLACE);
// node.put(IWorkbenchPreferenceConstants.SHIFT_OPEN_NEW_PERSPECTIVE,
// IWorkbenchPreferenceConstants.OPEN_PERSPECTIVE_REPLACE);
// node.put(IWorkbenchPreferenceConstants.ALTERNATE_OPEN_NEW_PERSPECTIVE,
// IWorkbenchPreferenceConstants.OPEN_PERSPECTIVE_REPLACE);
// Although there is no longer any item on the preference pages
// for setting the linking preference, since it is now a per-part
// setting, it remains as a preference to allow product overrides of the
// initial state of linking in the Navigator. By default, linking is
// off.
// node.putBoolean(IWorkbenchPreferenceConstants.LINK_NAVIGATOR_TO_EDITOR,
// false);
// RAPEND: [bm]
// Appearance / Presentation preferences
node.put(IWorkbenchPreferenceConstants.PRESENTATION_FACTORY_ID,
IWorkbenchConstants.DEFAULT_PRESENTATION_ID);
// RAP [bm]: no sense, disabled in IWPC
// node
// .putBoolean(
// IWorkbenchPreferenceConstants.SHOW_TRADITIONAL_STYLE_TABS,
// true);
// node.putBoolean(IWorkbenchPreferenceConstants.ENABLE_ANIMATIONS, true);
// node.putBoolean(IWorkbenchPreferenceConstants.USE_COLORED_LABELS, true);
// RAPEND: [bm]
node.put(IWorkbenchPreferenceConstants.DOCK_PERSPECTIVE_BAR,
IWorkbenchPreferenceConstants.TOP_RIGHT);
node.putBoolean(
IWorkbenchPreferenceConstants.SHOW_TEXT_ON_PERSPECTIVE_BAR,
true);
node.putBoolean(
IWorkbenchPreferenceConstants.SHOW_OTHER_IN_PERSPECTIVE_MENU,
true);
node.putBoolean(
IWorkbenchPreferenceConstants.SHOW_OPEN_ON_PERSPECTIVE_BAR,
true);
// the fast view bar should be on the bottom of a fresh workspace
node.put(IWorkbenchPreferenceConstants.INITIAL_FAST_VIEW_BAR_LOCATION,
IWorkbenchPreferenceConstants.BOTTOM);
// default to showing intro on startup
// RAP [bm]: no intro
// node.putBoolean(IWorkbenchPreferenceConstants.SHOW_INTRO, true);
// Default to the standard key configuration.
// RAP [bm]: Bindings
// node.put(IWorkbenchPreferenceConstants.KEY_CONFIGURATION_ID,
// IBindingService.DEFAULT_DEFAULT_ACTIVE_SCHEME_ID);
// RAPEND: [bm]
// Preference for showing system jobs in the jobs view
node.putBoolean(IWorkbenchPreferenceConstants.SHOW_SYSTEM_JOBS, false);
// The default minimum character width for editor tabs is undefined
// (i.e., -1)
node
.putInt(
IWorkbenchPreferenceConstants.EDITOR_MINIMUM_CHARACTERS,
-1);
// The default minimum character width for view tabs is 1
node.putInt(IWorkbenchPreferenceConstants.VIEW_MINIMUM_CHARACTERS, 1);
// Default for closing editors on exit.
node.putBoolean(IWorkbenchPreferenceConstants.CLOSE_EDITORS_ON_EXIT,
false);
// Default for using window working sets
node
.putBoolean(
IWorkbenchPreferenceConstants.USE_WINDOW_WORKING_SET_BY_DEFAULT,
false);
// Default for showing filter text widget that determines what is shown
// in a FilteredTree
node
.putBoolean(IWorkbenchPreferenceConstants.SHOW_FILTERED_TEXTS,
true);
// Default for enabling detached views
// RAP [bm]: no detached view
// node.putBoolean(IWorkbenchPreferenceConstants.ENABLE_DETACHED_VIEWS,
// true);
// Default for prompting for save when saveables are still held on to by other parts
node.putBoolean(IWorkbenchPreferenceConstants.PROMPT_WHEN_SAVEABLE_STILL_OPEN,
true);
// Default the min/max behaviour to the old (3.2) style
- node.putBoolean(IWorkbenchPreferenceConstants.ENABLE_NEW_MIN_MAX, true);
+ // RAP [bm]: disabled new min max story due to missing vertical toolbar
+ node.putBoolean(IWorkbenchPreferenceConstants.ENABLE_NEW_MIN_MAX, false);
// By default the Fast View Bar allows to select a new fast view from the view list
- node.putBoolean(IWorkbenchPreferenceConstants.DISABLE_NEW_FAST_VIEW, false);
+ node.putBoolean(IWorkbenchPreferenceConstants.DISABLE_NEW_FAST_VIEW, true);
// Default the sticky view close behaviour to the new style
node.putBoolean(IWorkbenchPreferenceConstants.ENABLE_32_STICKY_CLOSE_BEHAVIOR, false);
IEclipsePreferences rootNode = (IEclipsePreferences) Platform
.getPreferencesService().getRootNode()
.node(InstanceScope.SCOPE);
final String uiName = UIPlugin.getDefault().getBundle()
.getSymbolicName();
try {
if (rootNode.nodeExists(uiName)) {
((IEclipsePreferences) rootNode.node(uiName))
.addPreferenceChangeListener(PlatformUIPreferenceListener
.getSingleton());
}
} catch (BackingStoreException e) {
IStatus status = new Status(IStatus.ERROR, UIPlugin.getDefault()
.getBundle().getSymbolicName(), IStatus.ERROR, e
.getLocalizedMessage(), e);
UIPlugin.getDefault().getLog().log(status);
}
rootNode
.addNodeChangeListener(new IEclipsePreferences.INodeChangeListener() {
/*
* (non-Javadoc)
*
* @see org.eclipse.core.runtime.preferences.IEclipsePreferences.INodeChangeListener#added(org.eclipse.core.runtime.preferences.IEclipsePreferences.NodeChangeEvent)
*/
public void added(NodeChangeEvent event) {
if (!event.getChild().name().equals(uiName)) {
return;
}
((IEclipsePreferences) event.getChild())
.addPreferenceChangeListener(PlatformUIPreferenceListener
.getSingleton());
}
/*
* (non-Javadoc)
*
* @see org.eclipse.core.runtime.preferences.IEclipsePreferences.INodeChangeListener#removed(org.eclipse.core.runtime.preferences.IEclipsePreferences.NodeChangeEvent)
*/
public void removed(NodeChangeEvent event) {
// Nothing to do here
}
});
}
}
| false | true | public void initializeDefaultPreferences() {
IScopeContext context = new DefaultScope();
IEclipsePreferences node = context.getNode(UIPlugin.getDefault()
.getBundle().getSymbolicName());
node.put(IWorkbenchPreferenceConstants.OPEN_NEW_PERSPECTIVE,
IWorkbenchPreferenceConstants.OPEN_PERSPECTIVE_REPLACE);
// Deprecated but kept for backwards compatibility
// RAP [bm]: disabled
// node.put(IWorkbenchPreferenceConstants.PROJECT_OPEN_NEW_PERSPECTIVE,
// IWorkbenchPreferenceConstants.OPEN_PERSPECTIVE_REPLACE);
// node.put(IWorkbenchPreferenceConstants.SHIFT_OPEN_NEW_PERSPECTIVE,
// IWorkbenchPreferenceConstants.OPEN_PERSPECTIVE_REPLACE);
// node.put(IWorkbenchPreferenceConstants.ALTERNATE_OPEN_NEW_PERSPECTIVE,
// IWorkbenchPreferenceConstants.OPEN_PERSPECTIVE_REPLACE);
// Although there is no longer any item on the preference pages
// for setting the linking preference, since it is now a per-part
// setting, it remains as a preference to allow product overrides of the
// initial state of linking in the Navigator. By default, linking is
// off.
// node.putBoolean(IWorkbenchPreferenceConstants.LINK_NAVIGATOR_TO_EDITOR,
// false);
// RAPEND: [bm]
// Appearance / Presentation preferences
node.put(IWorkbenchPreferenceConstants.PRESENTATION_FACTORY_ID,
IWorkbenchConstants.DEFAULT_PRESENTATION_ID);
// RAP [bm]: no sense, disabled in IWPC
// node
// .putBoolean(
// IWorkbenchPreferenceConstants.SHOW_TRADITIONAL_STYLE_TABS,
// true);
// node.putBoolean(IWorkbenchPreferenceConstants.ENABLE_ANIMATIONS, true);
// node.putBoolean(IWorkbenchPreferenceConstants.USE_COLORED_LABELS, true);
// RAPEND: [bm]
node.put(IWorkbenchPreferenceConstants.DOCK_PERSPECTIVE_BAR,
IWorkbenchPreferenceConstants.TOP_RIGHT);
node.putBoolean(
IWorkbenchPreferenceConstants.SHOW_TEXT_ON_PERSPECTIVE_BAR,
true);
node.putBoolean(
IWorkbenchPreferenceConstants.SHOW_OTHER_IN_PERSPECTIVE_MENU,
true);
node.putBoolean(
IWorkbenchPreferenceConstants.SHOW_OPEN_ON_PERSPECTIVE_BAR,
true);
// the fast view bar should be on the bottom of a fresh workspace
node.put(IWorkbenchPreferenceConstants.INITIAL_FAST_VIEW_BAR_LOCATION,
IWorkbenchPreferenceConstants.BOTTOM);
// default to showing intro on startup
// RAP [bm]: no intro
// node.putBoolean(IWorkbenchPreferenceConstants.SHOW_INTRO, true);
// Default to the standard key configuration.
// RAP [bm]: Bindings
// node.put(IWorkbenchPreferenceConstants.KEY_CONFIGURATION_ID,
// IBindingService.DEFAULT_DEFAULT_ACTIVE_SCHEME_ID);
// RAPEND: [bm]
// Preference for showing system jobs in the jobs view
node.putBoolean(IWorkbenchPreferenceConstants.SHOW_SYSTEM_JOBS, false);
// The default minimum character width for editor tabs is undefined
// (i.e., -1)
node
.putInt(
IWorkbenchPreferenceConstants.EDITOR_MINIMUM_CHARACTERS,
-1);
// The default minimum character width for view tabs is 1
node.putInt(IWorkbenchPreferenceConstants.VIEW_MINIMUM_CHARACTERS, 1);
// Default for closing editors on exit.
node.putBoolean(IWorkbenchPreferenceConstants.CLOSE_EDITORS_ON_EXIT,
false);
// Default for using window working sets
node
.putBoolean(
IWorkbenchPreferenceConstants.USE_WINDOW_WORKING_SET_BY_DEFAULT,
false);
// Default for showing filter text widget that determines what is shown
// in a FilteredTree
node
.putBoolean(IWorkbenchPreferenceConstants.SHOW_FILTERED_TEXTS,
true);
// Default for enabling detached views
// RAP [bm]: no detached view
// node.putBoolean(IWorkbenchPreferenceConstants.ENABLE_DETACHED_VIEWS,
// true);
// Default for prompting for save when saveables are still held on to by other parts
node.putBoolean(IWorkbenchPreferenceConstants.PROMPT_WHEN_SAVEABLE_STILL_OPEN,
true);
// Default the min/max behaviour to the old (3.2) style
node.putBoolean(IWorkbenchPreferenceConstants.ENABLE_NEW_MIN_MAX, true);
// By default the Fast View Bar allows to select a new fast view from the view list
node.putBoolean(IWorkbenchPreferenceConstants.DISABLE_NEW_FAST_VIEW, false);
// Default the sticky view close behaviour to the new style
node.putBoolean(IWorkbenchPreferenceConstants.ENABLE_32_STICKY_CLOSE_BEHAVIOR, false);
IEclipsePreferences rootNode = (IEclipsePreferences) Platform
.getPreferencesService().getRootNode()
.node(InstanceScope.SCOPE);
final String uiName = UIPlugin.getDefault().getBundle()
.getSymbolicName();
try {
if (rootNode.nodeExists(uiName)) {
((IEclipsePreferences) rootNode.node(uiName))
.addPreferenceChangeListener(PlatformUIPreferenceListener
.getSingleton());
}
} catch (BackingStoreException e) {
IStatus status = new Status(IStatus.ERROR, UIPlugin.getDefault()
.getBundle().getSymbolicName(), IStatus.ERROR, e
.getLocalizedMessage(), e);
UIPlugin.getDefault().getLog().log(status);
}
rootNode
.addNodeChangeListener(new IEclipsePreferences.INodeChangeListener() {
/*
* (non-Javadoc)
*
* @see org.eclipse.core.runtime.preferences.IEclipsePreferences.INodeChangeListener#added(org.eclipse.core.runtime.preferences.IEclipsePreferences.NodeChangeEvent)
*/
public void added(NodeChangeEvent event) {
if (!event.getChild().name().equals(uiName)) {
return;
}
((IEclipsePreferences) event.getChild())
.addPreferenceChangeListener(PlatformUIPreferenceListener
.getSingleton());
}
/*
* (non-Javadoc)
*
* @see org.eclipse.core.runtime.preferences.IEclipsePreferences.INodeChangeListener#removed(org.eclipse.core.runtime.preferences.IEclipsePreferences.NodeChangeEvent)
*/
public void removed(NodeChangeEvent event) {
// Nothing to do here
}
});
}
| public void initializeDefaultPreferences() {
IScopeContext context = new DefaultScope();
IEclipsePreferences node = context.getNode(UIPlugin.getDefault()
.getBundle().getSymbolicName());
node.put(IWorkbenchPreferenceConstants.OPEN_NEW_PERSPECTIVE,
IWorkbenchPreferenceConstants.OPEN_PERSPECTIVE_REPLACE);
// Deprecated but kept for backwards compatibility
// RAP [bm]: disabled
// node.put(IWorkbenchPreferenceConstants.PROJECT_OPEN_NEW_PERSPECTIVE,
// IWorkbenchPreferenceConstants.OPEN_PERSPECTIVE_REPLACE);
// node.put(IWorkbenchPreferenceConstants.SHIFT_OPEN_NEW_PERSPECTIVE,
// IWorkbenchPreferenceConstants.OPEN_PERSPECTIVE_REPLACE);
// node.put(IWorkbenchPreferenceConstants.ALTERNATE_OPEN_NEW_PERSPECTIVE,
// IWorkbenchPreferenceConstants.OPEN_PERSPECTIVE_REPLACE);
// Although there is no longer any item on the preference pages
// for setting the linking preference, since it is now a per-part
// setting, it remains as a preference to allow product overrides of the
// initial state of linking in the Navigator. By default, linking is
// off.
// node.putBoolean(IWorkbenchPreferenceConstants.LINK_NAVIGATOR_TO_EDITOR,
// false);
// RAPEND: [bm]
// Appearance / Presentation preferences
node.put(IWorkbenchPreferenceConstants.PRESENTATION_FACTORY_ID,
IWorkbenchConstants.DEFAULT_PRESENTATION_ID);
// RAP [bm]: no sense, disabled in IWPC
// node
// .putBoolean(
// IWorkbenchPreferenceConstants.SHOW_TRADITIONAL_STYLE_TABS,
// true);
// node.putBoolean(IWorkbenchPreferenceConstants.ENABLE_ANIMATIONS, true);
// node.putBoolean(IWorkbenchPreferenceConstants.USE_COLORED_LABELS, true);
// RAPEND: [bm]
node.put(IWorkbenchPreferenceConstants.DOCK_PERSPECTIVE_BAR,
IWorkbenchPreferenceConstants.TOP_RIGHT);
node.putBoolean(
IWorkbenchPreferenceConstants.SHOW_TEXT_ON_PERSPECTIVE_BAR,
true);
node.putBoolean(
IWorkbenchPreferenceConstants.SHOW_OTHER_IN_PERSPECTIVE_MENU,
true);
node.putBoolean(
IWorkbenchPreferenceConstants.SHOW_OPEN_ON_PERSPECTIVE_BAR,
true);
// the fast view bar should be on the bottom of a fresh workspace
node.put(IWorkbenchPreferenceConstants.INITIAL_FAST_VIEW_BAR_LOCATION,
IWorkbenchPreferenceConstants.BOTTOM);
// default to showing intro on startup
// RAP [bm]: no intro
// node.putBoolean(IWorkbenchPreferenceConstants.SHOW_INTRO, true);
// Default to the standard key configuration.
// RAP [bm]: Bindings
// node.put(IWorkbenchPreferenceConstants.KEY_CONFIGURATION_ID,
// IBindingService.DEFAULT_DEFAULT_ACTIVE_SCHEME_ID);
// RAPEND: [bm]
// Preference for showing system jobs in the jobs view
node.putBoolean(IWorkbenchPreferenceConstants.SHOW_SYSTEM_JOBS, false);
// The default minimum character width for editor tabs is undefined
// (i.e., -1)
node
.putInt(
IWorkbenchPreferenceConstants.EDITOR_MINIMUM_CHARACTERS,
-1);
// The default minimum character width for view tabs is 1
node.putInt(IWorkbenchPreferenceConstants.VIEW_MINIMUM_CHARACTERS, 1);
// Default for closing editors on exit.
node.putBoolean(IWorkbenchPreferenceConstants.CLOSE_EDITORS_ON_EXIT,
false);
// Default for using window working sets
node
.putBoolean(
IWorkbenchPreferenceConstants.USE_WINDOW_WORKING_SET_BY_DEFAULT,
false);
// Default for showing filter text widget that determines what is shown
// in a FilteredTree
node
.putBoolean(IWorkbenchPreferenceConstants.SHOW_FILTERED_TEXTS,
true);
// Default for enabling detached views
// RAP [bm]: no detached view
// node.putBoolean(IWorkbenchPreferenceConstants.ENABLE_DETACHED_VIEWS,
// true);
// Default for prompting for save when saveables are still held on to by other parts
node.putBoolean(IWorkbenchPreferenceConstants.PROMPT_WHEN_SAVEABLE_STILL_OPEN,
true);
// Default the min/max behaviour to the old (3.2) style
// RAP [bm]: disabled new min max story due to missing vertical toolbar
node.putBoolean(IWorkbenchPreferenceConstants.ENABLE_NEW_MIN_MAX, false);
// By default the Fast View Bar allows to select a new fast view from the view list
node.putBoolean(IWorkbenchPreferenceConstants.DISABLE_NEW_FAST_VIEW, true);
// Default the sticky view close behaviour to the new style
node.putBoolean(IWorkbenchPreferenceConstants.ENABLE_32_STICKY_CLOSE_BEHAVIOR, false);
IEclipsePreferences rootNode = (IEclipsePreferences) Platform
.getPreferencesService().getRootNode()
.node(InstanceScope.SCOPE);
final String uiName = UIPlugin.getDefault().getBundle()
.getSymbolicName();
try {
if (rootNode.nodeExists(uiName)) {
((IEclipsePreferences) rootNode.node(uiName))
.addPreferenceChangeListener(PlatformUIPreferenceListener
.getSingleton());
}
} catch (BackingStoreException e) {
IStatus status = new Status(IStatus.ERROR, UIPlugin.getDefault()
.getBundle().getSymbolicName(), IStatus.ERROR, e
.getLocalizedMessage(), e);
UIPlugin.getDefault().getLog().log(status);
}
rootNode
.addNodeChangeListener(new IEclipsePreferences.INodeChangeListener() {
/*
* (non-Javadoc)
*
* @see org.eclipse.core.runtime.preferences.IEclipsePreferences.INodeChangeListener#added(org.eclipse.core.runtime.preferences.IEclipsePreferences.NodeChangeEvent)
*/
public void added(NodeChangeEvent event) {
if (!event.getChild().name().equals(uiName)) {
return;
}
((IEclipsePreferences) event.getChild())
.addPreferenceChangeListener(PlatformUIPreferenceListener
.getSingleton());
}
/*
* (non-Javadoc)
*
* @see org.eclipse.core.runtime.preferences.IEclipsePreferences.INodeChangeListener#removed(org.eclipse.core.runtime.preferences.IEclipsePreferences.NodeChangeEvent)
*/
public void removed(NodeChangeEvent event) {
// Nothing to do here
}
});
}
|
diff --git a/NCWITMOBILEAPP-Android/src/com/ncwitmobileapp/Login_Screen.java b/NCWITMOBILEAPP-Android/src/com/ncwitmobileapp/Login_Screen.java
index 2cece7c..1edb004 100644
--- a/NCWITMOBILEAPP-Android/src/com/ncwitmobileapp/Login_Screen.java
+++ b/NCWITMOBILEAPP-Android/src/com/ncwitmobileapp/Login_Screen.java
@@ -1,104 +1,104 @@
package com.ncwitmobileapp;
import com.ncwitmobileapp.R;
import com.ncwitmobileapp.client.MyRequestFactory;
import com.ncwitmobileapp.client.MyRequestFactory.HelloWorldRequest;
import com.google.gwt.core.client.GWT;
import com.google.web.bindery.requestfactory.shared.Receiver;
import com.google.web.bindery.requestfactory.shared.ServerFailure;
import android.R.color;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
public class Login_Screen extends Activity
{
private static final String TAG = "Techchicks";
/**
* The current context.
*/
private Context mContext = this;
@Override
public void onCreate(Bundle savedInstanceState)
{
- requestWindowFeature(Window.FEATURE_NO_TITLE);
+ requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.logins);
- final Button login = (Button)findViewById(R.id.login);
- login.setOnClickListener(new View.OnClickListener() {
+ final Button login = (Button)findViewById(R.id.login);
+ login.setOnClickListener(new View.OnClickListener() {
public void onClick(View lb) {
//communicate with App Engine
//goes to the Menu Page
//gets username and password from user(Editables)
String username;
String password;
EditText un=(EditText)findViewById(R.id.username);
EditText ps=(EditText)findViewById(R.id.password);
username=un.getText().toString();
password=ps.getText().toString();
login.setEnabled(false);
Log.i(TAG, "preparing request to send to server");
// Use an AsyncTask to avoid blocking the UI thread
new AsyncTask<Void, Void, String>() {
private String message;
@Override
protected String doInBackground(Void... arg0) {
MyRequestFactory requestFactory = Util.getRequestFactory(mContext,
MyRequestFactory.class);
final HelloWorldRequest request = requestFactory.helloWorldRequest();
Log.i(TAG, "Sending request to server");
request.getMessage().fire(new Receiver<String>() {
@Override
public void onFailure(ServerFailure error) {
message = "Failure: " + error.getMessage();
}
@Override
public void onSuccess(String result) {
message = result;
Log.i(TAG,"got back a hello world message");
}
});
return message;
}
}.execute();
}
- });
+ });
- Button register = (Button)findViewById(R.id.register);
- register.setOnClickListener(new View.OnClickListener() {
+ Button register = (Button)findViewById(R.id.register);
+ register.setOnClickListener(new View.OnClickListener() {
public void onClick(View lb) {
//goes to the Registration Page
}
});
- Button forgotpassword = (Button)findViewById(R.id.forgotpassword);
- forgotpassword.setOnClickListener(new View.OnClickListener() {
+ Button forgotpassword = (Button)findViewById(R.id.forgotpassword);
+ forgotpassword.setOnClickListener(new View.OnClickListener() {
public void onClick(View lb) {
//goes to the Forgot Password Page
}
});
- }
+ }
}
| false | true | public void onCreate(Bundle savedInstanceState)
{
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.logins);
final Button login = (Button)findViewById(R.id.login);
login.setOnClickListener(new View.OnClickListener() {
public void onClick(View lb) {
//communicate with App Engine
//goes to the Menu Page
//gets username and password from user(Editables)
String username;
String password;
EditText un=(EditText)findViewById(R.id.username);
EditText ps=(EditText)findViewById(R.id.password);
username=un.getText().toString();
password=ps.getText().toString();
login.setEnabled(false);
Log.i(TAG, "preparing request to send to server");
// Use an AsyncTask to avoid blocking the UI thread
new AsyncTask<Void, Void, String>() {
private String message;
@Override
protected String doInBackground(Void... arg0) {
MyRequestFactory requestFactory = Util.getRequestFactory(mContext,
MyRequestFactory.class);
final HelloWorldRequest request = requestFactory.helloWorldRequest();
Log.i(TAG, "Sending request to server");
request.getMessage().fire(new Receiver<String>() {
@Override
public void onFailure(ServerFailure error) {
message = "Failure: " + error.getMessage();
}
@Override
public void onSuccess(String result) {
message = result;
Log.i(TAG,"got back a hello world message");
}
});
return message;
}
}.execute();
}
});
Button register = (Button)findViewById(R.id.register);
register.setOnClickListener(new View.OnClickListener() {
public void onClick(View lb) {
//goes to the Registration Page
}
});
Button forgotpassword = (Button)findViewById(R.id.forgotpassword);
forgotpassword.setOnClickListener(new View.OnClickListener() {
public void onClick(View lb) {
//goes to the Forgot Password Page
}
});
}
| public void onCreate(Bundle savedInstanceState)
{
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.logins);
final Button login = (Button)findViewById(R.id.login);
login.setOnClickListener(new View.OnClickListener() {
public void onClick(View lb) {
//communicate with App Engine
//goes to the Menu Page
//gets username and password from user(Editables)
String username;
String password;
EditText un=(EditText)findViewById(R.id.username);
EditText ps=(EditText)findViewById(R.id.password);
username=un.getText().toString();
password=ps.getText().toString();
login.setEnabled(false);
Log.i(TAG, "preparing request to send to server");
// Use an AsyncTask to avoid blocking the UI thread
new AsyncTask<Void, Void, String>() {
private String message;
@Override
protected String doInBackground(Void... arg0) {
MyRequestFactory requestFactory = Util.getRequestFactory(mContext,
MyRequestFactory.class);
final HelloWorldRequest request = requestFactory.helloWorldRequest();
Log.i(TAG, "Sending request to server");
request.getMessage().fire(new Receiver<String>() {
@Override
public void onFailure(ServerFailure error) {
message = "Failure: " + error.getMessage();
}
@Override
public void onSuccess(String result) {
message = result;
Log.i(TAG,"got back a hello world message");
}
});
return message;
}
}.execute();
}
});
Button register = (Button)findViewById(R.id.register);
register.setOnClickListener(new View.OnClickListener() {
public void onClick(View lb) {
//goes to the Registration Page
}
});
Button forgotpassword = (Button)findViewById(R.id.forgotpassword);
forgotpassword.setOnClickListener(new View.OnClickListener() {
public void onClick(View lb) {
//goes to the Forgot Password Page
}
});
}
|
diff --git a/src/gui/GUI_Nest.java b/src/gui/GUI_Nest.java
index 48433c8..6d6f3a1 100644
--- a/src/gui/GUI_Nest.java
+++ b/src/gui/GUI_Nest.java
@@ -1,201 +1,202 @@
package gui;
import java.util.List;
import java.util.ArrayList;
import java.util.Random;
import state.*;
import agents.NestAgent;
import agents.Part;
public class GUI_Nest extends GUI_Component {
// Class-wide stuff
public static final int WIDTH = 25 * 5 + 20;
public static final int HEIGHT = 25 * 2 + 20;
// Member Variables
public GUI_Camera camera;
List<GUI_Part> partList;
String partHeld;
int posX, posY;
boolean clumped;
boolean badPart;
FactoryState state;
NestAgent agent;
AnimationEvent purge, unstable;
Random rand;
// Constructor
public GUI_Nest(int x, int y, FactoryState factoryState) {
partList = new ArrayList<GUI_Part>();
posX = x;
posY = y;
clumped = false;
this.state = factoryState;
myDrawing = new Drawing(posX, posY, "nest.png");
this.partHeld = "";
rand = new Random();
purge = new AnimationEvent();
purge.running = false;
unstable = new AnimationEvent();
unstable.running = false;
badPart = false;
}
// *** DoXXX API methods ***
public void doPutPartArrivedAtNest(Part p) {
//String partType = p.getPartName();
//GUI_Part newPart = new GUI_Part(p);
GUI_Part newPart = new GUI_Part(p);
// this.partHeld = newPart.getName();
if(badPart)
{
System.out.println("wat");
newPart.myDrawing.filename = "BadPart.png";
}
partList.add(newPart);
synchronized (state.guiPartList) {
state.guiPartList.add(newPart);
}
}
public void doSetClumped(boolean clumping) {
clumped = clumping;
}
public void doMakeBadParts() {
for (int i = 0; i < partList.size(); i++) {
GUI_Part part = partList.get(i);
part.myDrawing.filename = "BadPart.png";
}
partHeld = "BadPart";
badPart = true;
}
public void doSetUnstable(boolean stability) {
unstable.running = stability;
}
public void DoPurgeGuiNest() {
badPart = false;
purge.running = true;
purge.timer = 0;
}
// *** GUI friendly functions ***
public void removeGUIPart(GUI_Part p) {
if (partList.size() != 0)
{
partList.remove(0);
int capacity = 10;
agent.lane.msgRequestParts(partHeld,0,capacity-partList.size(), agent);
}
}
public void paintComponent() {
//Update drawing's x and y.
myDrawing.posX = posX;
myDrawing.posY = posY;
//Clear subDrawings...
myDrawing.subDrawings.clear();
//Then add them back
for(GUI_Part p : partList) {
p.paintComponent();
myDrawing.subDrawings.add(p.myDrawing);
}
}
public void setPartHeld(String partName) {
this.partHeld = partName;
}
public String getPartHeld() {
return this.partHeld;
}
public int getPosX() {
return this.posX;
}
public int getPosY() {
return this.posY;
}
public void setNestAgent(NestAgent n) {
this.agent = n;
}
public NestAgent getNestAgent() {
return this.agent;
}
public void setCamera(GUI_Camera c) {
this.camera = c;
}
public void updateGraphics() {
//TODO: Add animation for flushing parts, call DoneFlushedParts when done.
for (int i = 0; i < partList.size(); i++) {
GUI_Part part = partList.get(i);
// Set the x and y coordinates to have fish fill from the left side,
// column by column.
int x = (i / 2) * (clumped ? 15 : 25);
int y = (i % 2) * 25;
// Add 12 so that the parts are not on top of the nest
// borders.
x += 12;
y += 12;
//Deal with other effects
//purge animation
if(purge.running) {
x -= purge.timer;
if(x <= 0)
part.myDrawing.filename = "NOPIC";
}
//unstable animation
if (unstable.running) {
x += rand.nextGaussian();
y += rand.nextGaussian();
}
// Finally, add the nest's coordinates so that they are drawn over
// the nest.
x += posX;
y += posY;
part.setCoordinates(x, y);
}
if(purge.running) {
boolean allInvisible = true;
//If any of the parts are still visible, keep purge running
for(GUI_Part p : partList)
allInvisible &= p.myDrawing.filename.equals("NOPIC");
if(allInvisible) {
+ partList.clear();
purge.running = false;
agent.msgDoneFlushParts();
}
}
purge.timer = purge.running ? purge.timer + 1 : 0;
}
}
| true | true | public void updateGraphics() {
//TODO: Add animation for flushing parts, call DoneFlushedParts when done.
for (int i = 0; i < partList.size(); i++) {
GUI_Part part = partList.get(i);
// Set the x and y coordinates to have fish fill from the left side,
// column by column.
int x = (i / 2) * (clumped ? 15 : 25);
int y = (i % 2) * 25;
// Add 12 so that the parts are not on top of the nest
// borders.
x += 12;
y += 12;
//Deal with other effects
//purge animation
if(purge.running) {
x -= purge.timer;
if(x <= 0)
part.myDrawing.filename = "NOPIC";
}
//unstable animation
if (unstable.running) {
x += rand.nextGaussian();
y += rand.nextGaussian();
}
// Finally, add the nest's coordinates so that they are drawn over
// the nest.
x += posX;
y += posY;
part.setCoordinates(x, y);
}
if(purge.running) {
boolean allInvisible = true;
//If any of the parts are still visible, keep purge running
for(GUI_Part p : partList)
allInvisible &= p.myDrawing.filename.equals("NOPIC");
if(allInvisible) {
purge.running = false;
agent.msgDoneFlushParts();
}
}
purge.timer = purge.running ? purge.timer + 1 : 0;
}
| public void updateGraphics() {
//TODO: Add animation for flushing parts, call DoneFlushedParts when done.
for (int i = 0; i < partList.size(); i++) {
GUI_Part part = partList.get(i);
// Set the x and y coordinates to have fish fill from the left side,
// column by column.
int x = (i / 2) * (clumped ? 15 : 25);
int y = (i % 2) * 25;
// Add 12 so that the parts are not on top of the nest
// borders.
x += 12;
y += 12;
//Deal with other effects
//purge animation
if(purge.running) {
x -= purge.timer;
if(x <= 0)
part.myDrawing.filename = "NOPIC";
}
//unstable animation
if (unstable.running) {
x += rand.nextGaussian();
y += rand.nextGaussian();
}
// Finally, add the nest's coordinates so that they are drawn over
// the nest.
x += posX;
y += posY;
part.setCoordinates(x, y);
}
if(purge.running) {
boolean allInvisible = true;
//If any of the parts are still visible, keep purge running
for(GUI_Part p : partList)
allInvisible &= p.myDrawing.filename.equals("NOPIC");
if(allInvisible) {
partList.clear();
purge.running = false;
agent.msgDoneFlushParts();
}
}
purge.timer = purge.running ? purge.timer + 1 : 0;
}
|
diff --git a/src/main/java/org/iplantc/core/uidiskresource/client/sharing/views/DataSharingPermissionsPanel.java b/src/main/java/org/iplantc/core/uidiskresource/client/sharing/views/DataSharingPermissionsPanel.java
index d537965..c92368d 100644
--- a/src/main/java/org/iplantc/core/uidiskresource/client/sharing/views/DataSharingPermissionsPanel.java
+++ b/src/main/java/org/iplantc/core/uidiskresource/client/sharing/views/DataSharingPermissionsPanel.java
@@ -1,524 +1,525 @@
/**
*
*/
package org.iplantc.core.uidiskresource.client.sharing.views;
import java.util.ArrayList;
import java.util.List;
import org.iplantc.core.resources.client.IplantResources;
import org.iplantc.core.resources.client.messages.I18N;
import org.iplantc.core.uicommons.client.collaborators.events.UserSearchResultSelected;
import org.iplantc.core.uicommons.client.collaborators.events.UserSearchResultSelected.USER_SEARCH_EVENT_TAG;
import org.iplantc.core.uicommons.client.collaborators.models.Collaborator;
import org.iplantc.core.uicommons.client.collaborators.presenter.ManageCollaboratorsPresenter.MODE;
import org.iplantc.core.uicommons.client.collaborators.util.UserSearchField;
import org.iplantc.core.uicommons.client.collaborators.views.ManageCollaboratorsDailog;
import org.iplantc.core.uicommons.client.events.EventBus;
import org.iplantc.core.uicommons.client.models.UserInfo;
import org.iplantc.core.uidiskresource.client.models.DiskResource;
import org.iplantc.core.uidiskresource.client.models.DiskResourceAutoBeanFactory;
import org.iplantc.core.uidiskresource.client.models.Permissions;
import org.iplantc.core.uidiskresource.client.sharing.models.DataSharing;
import org.iplantc.core.uidiskresource.client.sharing.models.DataSharingKeyProvider;
import org.iplantc.core.uidiskresource.client.sharing.models.DataSharingProperties;
import org.iplantc.core.uidiskresource.client.sharing.views.DataSharingView.Presenter;
import com.google.gwt.core.shared.GWT;
import com.google.gwt.json.client.JSONBoolean;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.safecss.shared.SafeStyles;
import com.google.gwt.safecss.shared.SafeStylesUtils;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiTemplate;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Widget;
import com.google.web.bindery.autobean.shared.AutoBean;
import com.google.web.bindery.autobean.shared.AutoBeanCodex;
import com.sencha.gxt.cell.core.client.TextButtonCell;
import com.sencha.gxt.cell.core.client.form.ComboBoxCell.TriggerAction;
import com.sencha.gxt.core.client.ValueProvider;
import com.sencha.gxt.core.shared.FastMap;
import com.sencha.gxt.data.shared.ListStore;
import com.sencha.gxt.data.shared.StringLabelProvider;
import com.sencha.gxt.widget.core.client.box.AlertMessageBox;
import com.sencha.gxt.widget.core.client.button.TextButton;
import com.sencha.gxt.widget.core.client.container.VerticalLayoutContainer;
import com.sencha.gxt.widget.core.client.event.CompleteEditEvent;
import com.sencha.gxt.widget.core.client.event.CompleteEditEvent.CompleteEditHandler;
import com.sencha.gxt.widget.core.client.event.SelectEvent;
import com.sencha.gxt.widget.core.client.event.SelectEvent.SelectHandler;
import com.sencha.gxt.widget.core.client.form.SimpleComboBox;
import com.sencha.gxt.widget.core.client.grid.CellSelectionModel;
import com.sencha.gxt.widget.core.client.grid.ColumnConfig;
import com.sencha.gxt.widget.core.client.grid.ColumnModel;
import com.sencha.gxt.widget.core.client.grid.Grid;
import com.sencha.gxt.widget.core.client.grid.editing.GridEditing;
import com.sencha.gxt.widget.core.client.grid.editing.GridInlineEditing;
import com.sencha.gxt.widget.core.client.toolbar.FillToolItem;
import com.sencha.gxt.widget.core.client.toolbar.LabelToolItem;
import com.sencha.gxt.widget.core.client.toolbar.ToolBar;
/**
* @author sriram
*
*/
public class DataSharingPermissionsPanel implements IsWidget {
@UiField
Grid<DataSharing> grid;
@UiField
ToolBar toolbar;
@UiField(provided = true)
ListStore<DataSharing> listStore;
@UiField(provided = true)
ColumnModel<DataSharing> cm;
@UiField
VerticalLayoutContainer container;
private FastMap<List<DataSharing>> originalList;
private final FastMap<DiskResource> resources;
private final Presenter presenter;
private GridEditing<DataSharing> gridEditing;
private static final String ID_PERM_GROUP = "idPermGroup";
private SimpleComboBox<Object> permCombo;
private FastMap<List<DataSharing>> sharingMap;
private HorizontalPanel explainPanel;
final Widget widget;
private static MyUiBinder uiBinder = GWT.create(MyUiBinder.class);
@UiTemplate("DataSharingPermissionsView.ui.xml")
interface MyUiBinder extends UiBinder<Widget, DataSharingPermissionsPanel> {
}
public DataSharingPermissionsPanel(Presenter dataSharingPresenter, FastMap<DiskResource> resources) {
this.presenter = dataSharingPresenter;
this.resources = resources;
init();
widget = uiBinder.createAndBindUi(this);
initToolbar();
initGrid();
}
@Override
public Widget asWidget() {
return widget;
}
private void init() {
listStore = new ListStore<DataSharing>(new DataSharingKeyProvider());
cm = buildColumnModel();
buildPermissionsCombo();
EventBus.getInstance().addHandler(UserSearchResultSelected.TYPE,
new UserSearchResultSelected.UserSearchResultSelectedEventHandler() {
@Override
public void onUserSearchResultSelected(
UserSearchResultSelected userSearchResultSelected) {
if (userSearchResultSelected.getTag().equals(
UserSearchResultSelected.USER_SEARCH_EVENT_TAG.SHARING.toString())) {
addCollaborator(userSearchResultSelected.getCollaborator());
}
}
});
}
private void initGrid() {
grid.setSelectionModel(new CellSelectionModel<DataSharing>());
gridEditing = new GridInlineEditing<DataSharing>(grid);
gridEditing.addEditor(cm.getColumn(1), permCombo);
gridEditing.addCompleteEditHandler(new CompleteEditHandler<DataSharing>() {
@Override
public void onCompleteEdit(CompleteEditEvent<DataSharing> event) {
Object value = permCombo.getCurrentValue();
updatePermissions(value.toString(), grid.getSelectionModel().getSelectedItem()
.getUserName());
}
});
grid.getView().setAutoExpandColumn(cm.getColumn(0));
grid.getView().setEmptyText(I18N.DISPLAY.sharePrompt());
}
private void initToolbar() {
addExplainPanel();
toolbar.add(new UserSearchField(USER_SEARCH_EVENT_TAG.SHARING).asWidget());
toolbar.add(new FillToolItem());
toolbar.add(buildChooseCollabButton());
}
private TextButton buildChooseCollabButton() {
TextButton button = new TextButton();
button.setText(I18N.DISPLAY.chooseFromCollab());
button.addSelectHandler(new SelectHandler() {
@Override
public void onSelect(SelectEvent event) {
final ManageCollaboratorsDailog dialog = new ManageCollaboratorsDailog(MODE.SELECT);
dialog.setModal(true);
dialog.show();
dialog.addOkButtonSelectHandler(new SelectHandler() {
@Override
public void onSelect(SelectEvent event) {
List<Collaborator> selected = dialog.getSelectedCollaborators();
if (selected != null && selected.size() > 0) {
for (Collaborator c : selected) {
addCollaborator(c);
}
}
}
});
}
});
button.setToolTip(I18N.DISPLAY.chooseFromCollab());
button.setIcon(IplantResources.RESOURCES.share());
return button;
}
private SimpleComboBox<Object> buildPermissionsCombo() {
permCombo = new SimpleComboBox<Object>(new StringLabelProvider<Object>());
permCombo.setId(ID_PERM_GROUP);
permCombo.setForceSelection(true);
permCombo.add(DataSharing.READ);
permCombo.add(DataSharing.WRITE);
permCombo.add(DataSharing.OWN);
permCombo.setEditable(false);
permCombo.setTriggerAction(TriggerAction.ALL);
return permCombo;
}
private void addExplainPanel() {
explainPanel = new HorizontalPanel();
explainPanel.add(new LabelToolItem(I18N.DISPLAY.variablePermissionsNotice() + ":"));
TextButton explainBtn = new TextButton(I18N.DISPLAY.explain(), new SelectHandler() {
@Override
public void onSelect(SelectEvent event) {
ArrayList<DataSharing> shares = new ArrayList<DataSharing>();
for (String user : sharingMap.keySet()) {
shares.addAll(sharingMap.get(user));
}
ShareBreakDownDialog explainDlg = new ShareBreakDownDialog(shares);
explainDlg.setHeadingText(I18N.DISPLAY.whoHasAccess());
explainDlg.show();
}
});
explainPanel.add(explainBtn);
toolbar.add(explainPanel);
}
private void addCollaborator(Collaborator user) {
String userName = user.getUserName();
if (userName != null && userName.equalsIgnoreCase(UserInfo.getInstance().getUsername())) {
AlertMessageBox amb = new AlertMessageBox(I18N.DISPLAY.warning(),
I18N.DISPLAY.selfShareWarning());
amb.show();
return;
}
// Only add users not already displayed in the grid.
if (sharingMap.get(userName) == null) {
List<DataSharing> shareList = new ArrayList<DataSharing>();
DataSharing displayShare = null;
for (String path : resources.keySet()) {
DataSharing share = new DataSharing(user, presenter.getDefaultPermissions(), path);
shareList.add(share);
if (displayShare == null) {
displayShare = share.copy();
grid.getStore().add(displayShare);
}
}
sharingMap.put(userName, shareList);
}
}
private void removeModels(DataSharing model) {
ListStore<DataSharing> store = grid.getStore();
DataSharing sharing = store.findModel(model);
if (sharing != null) {
// Remove the shares from the sharingMap as well as the grid.
sharingMap.put(sharing.getUserName(), null);
store.remove(sharing);
}
}
public void loadSharingData(FastMap<List<DataSharing>> sharingMap) {
this.sharingMap = sharingMap;
originalList = new FastMap<List<DataSharing>>();
ListStore<DataSharing> store = grid.getStore();
store.clear();
explainPanel.setVisible(false);
for (String userName : sharingMap.keySet()) {
List<DataSharing> dataShares = sharingMap.get(userName);
if (dataShares != null && !dataShares.isEmpty()) {
List<DataSharing> newList = new ArrayList<DataSharing>();
for (DataSharing share : dataShares) {
DataSharing copyShare = share.copy();
newList.add(copyShare);
}
originalList.put(userName, newList);
// Add a dummy display share to the grid.
DataSharing displayShare = dataShares.get(0).copy();
if (hasVaryingPermissions(dataShares)) {
// Set the display permission to "varies" if this user's share list has varying
// permissions.
displayShare.setDisplayPermission(I18N.DISPLAY.varies());
explainPanel.setVisible(true);
}
store.add(displayShare);
}
}
}
private ColumnModel<DataSharing> buildColumnModel() {
List<ColumnConfig<DataSharing, ?>> configs = new ArrayList<ColumnConfig<DataSharing, ?>>();
DataSharingProperties props = GWT.create(DataSharingProperties.class);
ColumnConfig<DataSharing, String> name = new ColumnConfig<DataSharing, String>(
props.name());
name.setHeader(I18N.DISPLAY.name());
name.setWidth(220);
ColumnConfig<DataSharing, String> permission = new ColumnConfig<DataSharing, String>(
props.displayPermission());
permission.setHeader(I18N.DISPLAY.permissions());
- permission.setWidth(80);
+ permission.setWidth(150);
SafeStyles permTextStyles = SafeStylesUtils.fromTrustedString("color:#0098AA;cursor:pointer;");
permission.setColumnTextStyle(permTextStyles);
ColumnConfig<DataSharing, String> remove = new ColumnConfig<DataSharing, String>(
new ValueProvider<DataSharing, String>() {
@Override
public String getValue(DataSharing object) {
return "";
}
@Override
public void setValue(DataSharing object, String value) {
// do nothing
}
@Override
public String getPath() {
return "";
}
});
- SafeStyles textStyles = SafeStylesUtils.fromTrustedString("padding: 1px 3px;cursor:pointer;");
- remove.setColumnTextStyle(textStyles);
+ SafeStyles textStyles = SafeStylesUtils.fromTrustedString("padding-left: 10px;cursor:pointer;");
+ remove.setColumnStyle(textStyles);
+ remove.setWidth(50);
remove.setToolTip(I18N.DISPLAY.unshare());
TextButtonCell button = buildRemoveButtonCell();
remove.setCell(button);
configs.add(name);
configs.add(permission);
configs.add(remove);
return new ColumnModel<DataSharing>(configs);
}
private TextButtonCell buildRemoveButtonCell() {
TextButtonCell button = new TextButtonCell();
button.addSelectHandler(new SelectHandler() {
@Override
public void onSelect(SelectEvent event) {
removeModels(grid.getSelectionModel().getSelectedItem());
}
});
button.setIcon(IplantResources.RESOURCES.delete());
return button;
}
/**
*
*
* @return the sharing list
*/
public FastMap<List<DataSharing>> getSharingMap() {
FastMap<List<DataSharing>> sharingList = new FastMap<List<DataSharing>>();
for (DataSharing share : grid.getStore().getAll()) {
String userName = share.getUserName();
List<DataSharing> dataShares = sharingMap.get(userName);
List<DataSharing> updatedSharingList = getUpdatedSharingList(userName, dataShares);
if (updatedSharingList != null && updatedSharingList.size() > 0) {
sharingList.put(userName, updatedSharingList);
}
}
return sharingList;
}
/**
* check the list with original to see if things have changed. ignore unchanged records
*
* @param userName
* @param list
* @return
*/
private List<DataSharing> getUpdatedSharingList(String userName, List<DataSharing> list) {
List<DataSharing> updateList = new ArrayList<DataSharing>();
if (list != null && userName != null) {
List<DataSharing> fromOriginal = originalList.get(userName);
if (fromOriginal == null || fromOriginal.isEmpty()) {
updateList = list;
} else {
for (DataSharing s : list) {
if (!fromOriginal.contains(s)) {
updateList.add(s);
}
}
}
}
return updateList;
}
private void updatePermissions(String perm, String username) {
List<DataSharing> models = sharingMap.get(username);
if (models != null) {
boolean own = perm.equals(DataSharing.OWN);
boolean write = own || perm.equals(DataSharing.WRITE);
boolean read = true;
for (DataSharing share : models) {
if (own) {
share.setOwner(true);
} else if (write) {
share.setWritable(true);
} else {
share.setReadable(true);
}
}
if (resources.size() != models.size()) {
Collaborator user = models.get(0).getCollaborator();
DiskResourceAutoBeanFactory factory = GWT.create(DiskResourceAutoBeanFactory.class);
AutoBean<Permissions> autoBean = AutoBeanCodex.decode(factory, Permissions.class,
buildSharingPermissions(read, write, own));
for (String path : resources.keySet()) {
boolean shared = false;
for (DataSharing existingShare : models) {
if (path.equals(existingShare.getPath())) {
shared = true;
break;
}
}
if (!shared) {
models.add(new DataSharing(user, autoBean.as(), path));
}
}
}
checkExplainPanelVisibility();
}
}
/**
* Checks if the explainPanel should be hidden after permissions have been updated or removed.
*/
private void checkExplainPanelVisibility() {
if (explainPanel.isVisible()) {
boolean permsVary = false;
for (DataSharing dataShare : grid.getStore().getAll()) {
permsVary = hasVaryingPermissions(sharingMap.get(dataShare.getUserName()));
if (permsVary) {
// Stop checking after the first user is found with variable permissions.
break;
}
}
if (!permsVary) {
explainPanel.setVisible(false);
}
}
}
/**
* @param dataShares
* @return true if the given dataShares list has a different size than the resources list, or if not
* every permission in the given dataShares list is the same; false otherwise.
*/
private boolean hasVaryingPermissions(List<DataSharing> dataShares) {
if (dataShares == null || dataShares.size() != resources.size()) {
return true;
} else {
String displayPermission = dataShares.get(0).getDisplayPermission();
for (DataSharing share : dataShares) {
if (!displayPermission.equals(share.getDisplayPermission())) {
return true;
}
}
}
return false;
}
private String buildSharingPermissions(boolean read, boolean write, boolean own) {
JSONObject permission = new JSONObject();
permission.put("read", JSONBoolean.getInstance(read));
permission.put("write", JSONBoolean.getInstance(write));
permission.put("own", JSONBoolean.getInstance(own));
return permission.toString();
}
/**
* @return the unshareList
*/
public FastMap<List<DataSharing>> getUnshareList() {
// Prepare unshared list here
FastMap<List<DataSharing>> unshareList = new FastMap<List<DataSharing>>();
for (String userName : originalList.keySet()) {
if (sharingMap.get(userName) == null) {
// The username entry from the original list was removed from the sharingMap, which means
// it was unshared.
List<DataSharing> removeList = originalList.get(userName);
if (removeList != null && !removeList.isEmpty()) {
unshareList.put(userName, removeList);
}
}
}
return unshareList;
}
public void mask(String loadingMask) {
container.mask(I18N.DISPLAY.loadingMask());
}
public void unmask() {
container.unmask();
}
}
| false | true | private ColumnModel<DataSharing> buildColumnModel() {
List<ColumnConfig<DataSharing, ?>> configs = new ArrayList<ColumnConfig<DataSharing, ?>>();
DataSharingProperties props = GWT.create(DataSharingProperties.class);
ColumnConfig<DataSharing, String> name = new ColumnConfig<DataSharing, String>(
props.name());
name.setHeader(I18N.DISPLAY.name());
name.setWidth(220);
ColumnConfig<DataSharing, String> permission = new ColumnConfig<DataSharing, String>(
props.displayPermission());
permission.setHeader(I18N.DISPLAY.permissions());
permission.setWidth(80);
SafeStyles permTextStyles = SafeStylesUtils.fromTrustedString("color:#0098AA;cursor:pointer;");
permission.setColumnTextStyle(permTextStyles);
ColumnConfig<DataSharing, String> remove = new ColumnConfig<DataSharing, String>(
new ValueProvider<DataSharing, String>() {
@Override
public String getValue(DataSharing object) {
return "";
}
@Override
public void setValue(DataSharing object, String value) {
// do nothing
}
@Override
public String getPath() {
return "";
}
});
SafeStyles textStyles = SafeStylesUtils.fromTrustedString("padding: 1px 3px;cursor:pointer;");
remove.setColumnTextStyle(textStyles);
remove.setToolTip(I18N.DISPLAY.unshare());
TextButtonCell button = buildRemoveButtonCell();
remove.setCell(button);
configs.add(name);
configs.add(permission);
configs.add(remove);
return new ColumnModel<DataSharing>(configs);
}
| private ColumnModel<DataSharing> buildColumnModel() {
List<ColumnConfig<DataSharing, ?>> configs = new ArrayList<ColumnConfig<DataSharing, ?>>();
DataSharingProperties props = GWT.create(DataSharingProperties.class);
ColumnConfig<DataSharing, String> name = new ColumnConfig<DataSharing, String>(
props.name());
name.setHeader(I18N.DISPLAY.name());
name.setWidth(220);
ColumnConfig<DataSharing, String> permission = new ColumnConfig<DataSharing, String>(
props.displayPermission());
permission.setHeader(I18N.DISPLAY.permissions());
permission.setWidth(150);
SafeStyles permTextStyles = SafeStylesUtils.fromTrustedString("color:#0098AA;cursor:pointer;");
permission.setColumnTextStyle(permTextStyles);
ColumnConfig<DataSharing, String> remove = new ColumnConfig<DataSharing, String>(
new ValueProvider<DataSharing, String>() {
@Override
public String getValue(DataSharing object) {
return "";
}
@Override
public void setValue(DataSharing object, String value) {
// do nothing
}
@Override
public String getPath() {
return "";
}
});
SafeStyles textStyles = SafeStylesUtils.fromTrustedString("padding-left: 10px;cursor:pointer;");
remove.setColumnStyle(textStyles);
remove.setWidth(50);
remove.setToolTip(I18N.DISPLAY.unshare());
TextButtonCell button = buildRemoveButtonCell();
remove.setCell(button);
configs.add(name);
configs.add(permission);
configs.add(remove);
return new ColumnModel<DataSharing>(configs);
}
|
diff --git a/JsTestDriver/src/com/google/jstestdriver/ConfigurationParser.java b/JsTestDriver/src/com/google/jstestdriver/ConfigurationParser.java
index 7eabea2..0ac03ce 100644
--- a/JsTestDriver/src/com/google/jstestdriver/ConfigurationParser.java
+++ b/JsTestDriver/src/com/google/jstestdriver/ConfigurationParser.java
@@ -1,178 +1,178 @@
/*
* Copyright 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.jstestdriver;
import com.google.common.collect.Lists;
import org.apache.oro.io.GlobFilenameFilter;
import org.apache.oro.text.GlobCompiler;
import org.jvyaml.YAML;
import java.io.File;
import java.io.Reader;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* TODO: needs to give more feedback when something goes wrong...
*
* @author [email protected] (Jeremie Lenfant-Engelmann)
*/
public class ConfigurationParser {
private static final List<String> EMPTY_LIST = Lists.newArrayList();
private final Set<FileInfo> filesList = new LinkedHashSet<FileInfo>();
private final File basePath;
private final Reader configReader;
private final PathRewriter pathRewriter;
private String server = "";
private List<Plugin> plugins = new LinkedList<Plugin>();
private PathResolver pathResolver = new PathResolver();
public ConfigurationParser(File basePath, Reader configReader, PathRewriter pathRewriter) {
this.basePath = basePath;
this.configReader = configReader;
this.pathRewriter = pathRewriter;
}
@SuppressWarnings("unchecked")
public void parse() {
Map<Object, Object> data = (Map<Object, Object>) YAML.load(configReader);
Set<FileInfo> resolvedFilesLoad = new LinkedHashSet<FileInfo>();
Set<FileInfo> resolvedFilesExclude = new LinkedHashSet<FileInfo>();
if (data.containsKey("load")) {
resolvedFilesLoad.addAll(resolveFiles((List<String>) data.get("load"), false));
}
if (data.containsKey("exclude")) {
resolvedFilesExclude.addAll(resolveFiles((List<String>) data.get("exclude"), false));
}
if (data.containsKey("server")) {
this.server = (String) data.get("server");
}
if (data.containsKey("plugin")) {
for (Map<String, String> value: (List<Map<String, String>>) data.get("plugin")) {
plugins.add(new Plugin(value.get("name"), value.get("jar"), value.get("module"),
createArgsList(value.get("args"))));
}
}
if (data.containsKey("serve")) {
Set<FileInfo> resolvedServeFiles = resolveFiles((List<String>) data.get("serve"), true);
resolvedFilesLoad.addAll(resolvedServeFiles);
}
filesList.addAll(consolidatePatches(resolvedFilesLoad));
filesList.removeAll(resolvedFilesExclude);
}
private List<String> createArgsList(String args) {
if (args == null) {
return EMPTY_LIST;
}
List<String> argsList = Lists.newLinkedList();
String[] splittedArgs = args.split(",");
for (String arg : splittedArgs) {
argsList.add(arg.trim());
}
return argsList;
}
private Set<FileInfo> consolidatePatches(Set<FileInfo> resolvedFilesLoad) {
Set<FileInfo> consolidated = new LinkedHashSet<FileInfo>(resolvedFilesLoad.size());
FileInfo currentNonPatch = null;
for (FileInfo fileInfo : resolvedFilesLoad) {
if (fileInfo.isPatch()) {
if (currentNonPatch == null) {
throw new IllegalStateException("Patch " + fileInfo + " without a core file to patch");
}
currentNonPatch.addPatch(fileInfo);
} else {
consolidated.add(fileInfo);
currentNonPatch = fileInfo;
}
}
return consolidated;
}
private Set<FileInfo> resolveFiles(List<String> files, boolean serveOnly) {
if (files != null) {
Set<FileInfo> resolvedFiles = new LinkedHashSet<FileInfo>();
for (String f : files) {
f = pathRewriter.rewrite(f);
boolean isPatch = f.startsWith("patch");
if (isPatch) {
String[] tokens = f.split(" ", 2);
f = tokens[1].trim();
}
if (f.startsWith("http://") || f.startsWith("https://")) {
resolvedFiles.add(new FileInfo(f, -1, false, false, null));
} else {
- File file = basePath != null ? new File(basePath, f) : new File(f);
+ File file = basePath != null ? new File(basePath.getAbsoluteFile(), f) : new File(f);
File testFile = file.getAbsoluteFile();
File dir = testFile.getParentFile().getAbsoluteFile();
final String pattern = file.getName();
String[] filteredFiles = dir.list(new GlobFilenameFilter(pattern,
GlobCompiler.DEFAULT_MASK | GlobCompiler.CASE_INSENSITIVE_MASK));
if (filteredFiles == null || filteredFiles.length == 0) {
String error = "The patterns/paths " + f + " used in the configuration"
+ " file didn't match any file, the files patterns/paths need to be relative to"
+ " the configuration file.";
System.err.println(error);
throw new RuntimeException(error);
}
Arrays.sort(filteredFiles, String.CASE_INSENSITIVE_ORDER);
for (String filteredFile : filteredFiles) {
String resolvedFilePath =
pathResolver.resolvePath(dir.getAbsolutePath().replaceAll("\\\\", "/") + "/"
+ filteredFile.replaceAll("\\\\", "/"));
File resolvedFile = new File(resolvedFilePath);
resolvedFiles.add(new FileInfo(resolvedFilePath, resolvedFile.lastModified(), isPatch,
serveOnly, null));
}
}
}
return resolvedFiles;
}
return Collections.emptySet();
}
public Set<FileInfo> getFilesList() {
return filesList;
}
public String getServer() {
return server;
}
public List<Plugin> getPlugins() {
return plugins;
}
}
| true | true | private Set<FileInfo> resolveFiles(List<String> files, boolean serveOnly) {
if (files != null) {
Set<FileInfo> resolvedFiles = new LinkedHashSet<FileInfo>();
for (String f : files) {
f = pathRewriter.rewrite(f);
boolean isPatch = f.startsWith("patch");
if (isPatch) {
String[] tokens = f.split(" ", 2);
f = tokens[1].trim();
}
if (f.startsWith("http://") || f.startsWith("https://")) {
resolvedFiles.add(new FileInfo(f, -1, false, false, null));
} else {
File file = basePath != null ? new File(basePath, f) : new File(f);
File testFile = file.getAbsoluteFile();
File dir = testFile.getParentFile().getAbsoluteFile();
final String pattern = file.getName();
String[] filteredFiles = dir.list(new GlobFilenameFilter(pattern,
GlobCompiler.DEFAULT_MASK | GlobCompiler.CASE_INSENSITIVE_MASK));
if (filteredFiles == null || filteredFiles.length == 0) {
String error = "The patterns/paths " + f + " used in the configuration"
+ " file didn't match any file, the files patterns/paths need to be relative to"
+ " the configuration file.";
System.err.println(error);
throw new RuntimeException(error);
}
Arrays.sort(filteredFiles, String.CASE_INSENSITIVE_ORDER);
for (String filteredFile : filteredFiles) {
String resolvedFilePath =
pathResolver.resolvePath(dir.getAbsolutePath().replaceAll("\\\\", "/") + "/"
+ filteredFile.replaceAll("\\\\", "/"));
File resolvedFile = new File(resolvedFilePath);
resolvedFiles.add(new FileInfo(resolvedFilePath, resolvedFile.lastModified(), isPatch,
serveOnly, null));
}
}
}
return resolvedFiles;
}
return Collections.emptySet();
}
| private Set<FileInfo> resolveFiles(List<String> files, boolean serveOnly) {
if (files != null) {
Set<FileInfo> resolvedFiles = new LinkedHashSet<FileInfo>();
for (String f : files) {
f = pathRewriter.rewrite(f);
boolean isPatch = f.startsWith("patch");
if (isPatch) {
String[] tokens = f.split(" ", 2);
f = tokens[1].trim();
}
if (f.startsWith("http://") || f.startsWith("https://")) {
resolvedFiles.add(new FileInfo(f, -1, false, false, null));
} else {
File file = basePath != null ? new File(basePath.getAbsoluteFile(), f) : new File(f);
File testFile = file.getAbsoluteFile();
File dir = testFile.getParentFile().getAbsoluteFile();
final String pattern = file.getName();
String[] filteredFiles = dir.list(new GlobFilenameFilter(pattern,
GlobCompiler.DEFAULT_MASK | GlobCompiler.CASE_INSENSITIVE_MASK));
if (filteredFiles == null || filteredFiles.length == 0) {
String error = "The patterns/paths " + f + " used in the configuration"
+ " file didn't match any file, the files patterns/paths need to be relative to"
+ " the configuration file.";
System.err.println(error);
throw new RuntimeException(error);
}
Arrays.sort(filteredFiles, String.CASE_INSENSITIVE_ORDER);
for (String filteredFile : filteredFiles) {
String resolvedFilePath =
pathResolver.resolvePath(dir.getAbsolutePath().replaceAll("\\\\", "/") + "/"
+ filteredFile.replaceAll("\\\\", "/"));
File resolvedFile = new File(resolvedFilePath);
resolvedFiles.add(new FileInfo(resolvedFilePath, resolvedFile.lastModified(), isPatch,
serveOnly, null));
}
}
}
return resolvedFiles;
}
return Collections.emptySet();
}
|
diff --git a/CookieSlap/src/rageteam/cookieslap/main/CS.java b/CookieSlap/src/rageteam/cookieslap/main/CS.java
index df110f8..337649e 100644
--- a/CookieSlap/src/rageteam/cookieslap/main/CS.java
+++ b/CookieSlap/src/rageteam/cookieslap/main/CS.java
@@ -1,136 +1,137 @@
package rageteam.cookieslap.main;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scoreboard.DisplaySlot;
import org.bukkit.scoreboard.Objective;
import org.bukkit.scoreboard.Score;
import org.bukkit.scoreboard.Scoreboard;
import org.bukkit.scoreboard.ScoreboardManager;
import rageteam.cookieslap.commands.HelpCommand;
import rageteam.cookieslap.handlers.PlayerHandler;
import rageteam.cookieslap.handlers.ServerHandler;
import rageteam.cookieslap.managers.ArenasManager;
import rageteam.cookieslap.managers.ConfigManager;
import rageteam.cookieslap.managers.PlayerManager;
import rageteam.cookieslap.objects.GameState;
import rageteam.cookieslap.util.Chat;
import rageteam.cookieslap.util.Logger;
import rageteam.cookieslap.util.Misc;
public class CS extends JavaPlugin{
public GameState gameState = GameState.LOBBY;
public boolean canStart = false;
//Command Classes
public HelpCommand cmdHelp;
//Handler Classes
public ServerHandler serverHandler;
public PlayerHandler playerHandler;
//Manager Classes
public PlayerManager playerManager;
public ConfigManager cfgManager;
public ArenasManager arenasmanager;
//Util Classes
public Chat chat;
public Logger logger;
public Misc misc;
//Scoreboard
ScoreboardManager manager;
Scoreboard board;
Objective obj;
public int timeInSeconds = 240;
public int onlinePlayers = Bukkit.getServer().getOnlinePlayers().length;
public int highScore = 0;
public int arenaID = 0;
private void loadDependicies(){
this.chat = new Chat(this);
this.logger = new Logger(this);
this.misc = new Misc(this);
this.cmdHelp = new HelpCommand(this);
this.playerManager = new PlayerManager(this);
this.cfgManager = new ConfigManager(this);
this.arenasmanager = new ArenasManager(this);
this.playerHandler = new PlayerHandler(this);
this.serverHandler = new ServerHandler(this);
}
private void loadHandlers(){
getServer().getPluginManager().registerEvents(playerHandler, this);
getServer().getPluginManager().registerEvents(serverHandler, this);
}
private void registerCommands(){
getCommand("help").setExecutor(cmdHelp);
}
@Override
public void onEnable(){
loadDependicies();
loadHandlers();
registerCommands();
logger.log(false, "Loading CS Dependicies");
//ScoreBoard
manager = Bukkit.getScoreboardManager();
board = manager.getNewScoreboard();
obj = board.registerNewObjective("CookieSlap", "dummy");
obj.setDisplayName(ChatColor.GRAY + " /toggleboard " + ChatColor.WHITE + " to hide");
obj.setDisplaySlot(DisplaySlot.SIDEBAR);
final Score time = obj.getScore(Bukkit.getOfflinePlayer(ChatColor.LIGHT_PURPLE + "Time Left:" + ChatColor.RED));
getServer().getScheduler().scheduleSyncRepeatingTask(this, new Runnable(){
public void run(){
if(timeInSeconds != -1){
if(timeInSeconds != 0){
time.setScore(timeInSeconds);
+ timeInSeconds--;
} else if(timeInSeconds <= 10 && timeInSeconds > 0){
note();
}
}
}
}, 0L, 20L);
Score players = obj.getScore(Bukkit.getOfflinePlayer(ChatColor.DARK_AQUA + "Players:" + ChatColor.RED));
players.setScore(onlinePlayers);
Score arena = obj.getScore(Bukkit.getOfflinePlayer(ChatColor.GREEN + "Arena ID:" + ChatColor.RED));
arena.setScore(arenaID);
Score score = obj.getScore(Bukkit.getOfflinePlayer(ChatColor.YELLOW + "HighScore:" + ChatColor.RED));
score.setScore(highScore);
for(Player player : Bukkit.getOnlinePlayers()){
player.setScoreboard(board);
}
}
private void note() {
for(Player player : getServer().getOnlinePlayers()){
player.playSound(player.getLocation(), Sound.NOTE_PIANO, 10, 1);
}
}
@Override
public void onDisable(){
}
}
| true | true | public void onEnable(){
loadDependicies();
loadHandlers();
registerCommands();
logger.log(false, "Loading CS Dependicies");
//ScoreBoard
manager = Bukkit.getScoreboardManager();
board = manager.getNewScoreboard();
obj = board.registerNewObjective("CookieSlap", "dummy");
obj.setDisplayName(ChatColor.GRAY + " /toggleboard " + ChatColor.WHITE + " to hide");
obj.setDisplaySlot(DisplaySlot.SIDEBAR);
final Score time = obj.getScore(Bukkit.getOfflinePlayer(ChatColor.LIGHT_PURPLE + "Time Left:" + ChatColor.RED));
getServer().getScheduler().scheduleSyncRepeatingTask(this, new Runnable(){
public void run(){
if(timeInSeconds != -1){
if(timeInSeconds != 0){
time.setScore(timeInSeconds);
} else if(timeInSeconds <= 10 && timeInSeconds > 0){
note();
}
}
}
}, 0L, 20L);
Score players = obj.getScore(Bukkit.getOfflinePlayer(ChatColor.DARK_AQUA + "Players:" + ChatColor.RED));
players.setScore(onlinePlayers);
Score arena = obj.getScore(Bukkit.getOfflinePlayer(ChatColor.GREEN + "Arena ID:" + ChatColor.RED));
arena.setScore(arenaID);
Score score = obj.getScore(Bukkit.getOfflinePlayer(ChatColor.YELLOW + "HighScore:" + ChatColor.RED));
score.setScore(highScore);
for(Player player : Bukkit.getOnlinePlayers()){
player.setScoreboard(board);
}
}
| public void onEnable(){
loadDependicies();
loadHandlers();
registerCommands();
logger.log(false, "Loading CS Dependicies");
//ScoreBoard
manager = Bukkit.getScoreboardManager();
board = manager.getNewScoreboard();
obj = board.registerNewObjective("CookieSlap", "dummy");
obj.setDisplayName(ChatColor.GRAY + " /toggleboard " + ChatColor.WHITE + " to hide");
obj.setDisplaySlot(DisplaySlot.SIDEBAR);
final Score time = obj.getScore(Bukkit.getOfflinePlayer(ChatColor.LIGHT_PURPLE + "Time Left:" + ChatColor.RED));
getServer().getScheduler().scheduleSyncRepeatingTask(this, new Runnable(){
public void run(){
if(timeInSeconds != -1){
if(timeInSeconds != 0){
time.setScore(timeInSeconds);
timeInSeconds--;
} else if(timeInSeconds <= 10 && timeInSeconds > 0){
note();
}
}
}
}, 0L, 20L);
Score players = obj.getScore(Bukkit.getOfflinePlayer(ChatColor.DARK_AQUA + "Players:" + ChatColor.RED));
players.setScore(onlinePlayers);
Score arena = obj.getScore(Bukkit.getOfflinePlayer(ChatColor.GREEN + "Arena ID:" + ChatColor.RED));
arena.setScore(arenaID);
Score score = obj.getScore(Bukkit.getOfflinePlayer(ChatColor.YELLOW + "HighScore:" + ChatColor.RED));
score.setScore(highScore);
for(Player player : Bukkit.getOnlinePlayers()){
player.setScoreboard(board);
}
}
|
diff --git a/src/vue/terminal/secondaryFramed/SecondaryFrame.java b/src/vue/terminal/secondaryFramed/SecondaryFrame.java
index c1d9d06..0e4959f 100644
--- a/src/vue/terminal/secondaryFramed/SecondaryFrame.java
+++ b/src/vue/terminal/secondaryFramed/SecondaryFrame.java
@@ -1,79 +1,73 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package vue.terminal.secondaryFramed;
import controller.terminal.controller.TerminalController;
import java.awt.GraphicsConfiguration;
import java.awt.HeadlessException;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JFrame;
/**
*
* @author Valentin SEITZ
*/
public class SecondaryFrame extends JFrame {
public SecondaryFrame() throws HeadlessException {
this.initialize();
}
public SecondaryFrame(GraphicsConfiguration gc) {
super(gc);
this.initialize();
}
public SecondaryFrame(String string) throws HeadlessException {
super(string);
this.initialize();
}
public SecondaryFrame(String string, GraphicsConfiguration gc) {
super(string, gc);
this.initialize();
}
private void initialize() {
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.addWindowListener(new WindowListener() {
@Override
public void windowOpened(WindowEvent we) {
- throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void windowClosing(WindowEvent we) {
TerminalController.doCancel();
}
@Override
public void windowClosed(WindowEvent we) {
- throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void windowIconified(WindowEvent we) {
- throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void windowDeiconified(WindowEvent we) {
- throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void windowActivated(WindowEvent we) {
- throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void windowDeactivated(WindowEvent we) {
- throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
});
}
}
| false | true | private void initialize() {
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.addWindowListener(new WindowListener() {
@Override
public void windowOpened(WindowEvent we) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void windowClosing(WindowEvent we) {
TerminalController.doCancel();
}
@Override
public void windowClosed(WindowEvent we) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void windowIconified(WindowEvent we) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void windowDeiconified(WindowEvent we) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void windowActivated(WindowEvent we) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void windowDeactivated(WindowEvent we) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
});
}
| private void initialize() {
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.addWindowListener(new WindowListener() {
@Override
public void windowOpened(WindowEvent we) {
}
@Override
public void windowClosing(WindowEvent we) {
TerminalController.doCancel();
}
@Override
public void windowClosed(WindowEvent we) {
}
@Override
public void windowIconified(WindowEvent we) {
}
@Override
public void windowDeiconified(WindowEvent we) {
}
@Override
public void windowActivated(WindowEvent we) {
}
@Override
public void windowDeactivated(WindowEvent we) {
}
});
}
|
diff --git a/de.hswt.hrm.plant.ui/src/de/hswt/hrm/plant/ui/wizard/PlantWizard.java b/de.hswt.hrm.plant.ui/src/de/hswt/hrm/plant/ui/wizard/PlantWizard.java
index fa528194..2d66dc1b 100644
--- a/de.hswt.hrm.plant.ui/src/de/hswt/hrm/plant/ui/wizard/PlantWizard.java
+++ b/de.hswt.hrm.plant.ui/src/de/hswt/hrm/plant/ui/wizard/PlantWizard.java
@@ -1,129 +1,131 @@
package de.hswt.hrm.plant.ui.wizard;
import java.util.HashMap;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.swt.widgets.Text;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Optional;
import de.hswt.hrm.common.database.exception.DatabaseException;
import de.hswt.hrm.common.database.exception.SaveException;
import de.hswt.hrm.plant.model.Plant;
import de.hswt.hrm.plant.service.PlantService;
public class PlantWizard extends Wizard {
private static final Logger LOG = LoggerFactory.getLogger(PlantWizard.class);
private PlantWizardPageOne first;
private Optional<Plant> plant;
public PlantWizard(Optional<Plant> plant) {
this.plant = plant;
first = new PlantWizardPageOne("Erste Seite", plant);
if (plant.isPresent()) {
setWindowTitle("Anlage bearbeiten");
} else {
setWindowTitle("Neue Anlage erstellen");
}
}
@Override
public void addPages() {
addPage(first);
}
@Override
public boolean canFinish() {
return first.isPageComplete();
}
@Override
public boolean performFinish() {
if (plant.isPresent()) {
return editExistingPlant();
} else {
return insertNewPlant();
}
}
private boolean editExistingPlant() {
Plant p = this.plant.get();
try {
// Update plant from DB
p = PlantService.findById(p.getId());
// Set values to fields from WizardPage
p = setValues(plant);
// Update plant in DB
PlantService.update(p);
plant = Optional.of(p);
} catch (DatabaseException e) {
LOG.error("An error occured", e);
}
return true;
}
private boolean insertNewPlant() {
Plant p = setValues(Optional.<Plant>absent());
try {
plant = Optional.of(PlantService.insert(p));
} catch (SaveException e) {
LOG.error("Could not save Element: "+ plant +"into Database", e);
}
return true;
}
private Plant setValues(Optional<Plant> p) {
HashMap<String, Text> mandatoryWidgets = first.getMandatoryWidgets();
String description = mandatoryWidgets.get("description").getText();
//TODO place - mandatory?
//TODO nextInspection / inspectionIntervall?
String inspectionIntervall = mandatoryWidgets.get("inspectionIntervall").getText();
//TODO scheme
HashMap<String, Text> optionalWidgets = first.getOptionalWidgets();
String manufactor = optionalWidgets.get("manufactor").getText();
String constructionYear = optionalWidgets.get("constructionYear").getText();
String type = optionalWidgets.get("type").getText();
String airPerformance = optionalWidgets.get("airPerformance").getText();
String motorPower = optionalWidgets.get("motorPower").getText();
String ventilatorPerformance = optionalWidgets.get("ventilatorPerformance").getText();
String motorRPM = optionalWidgets.get("motorRPM").getText();
String current = optionalWidgets.get("current").getText();
String voltage = optionalWidgets.get("voltage").getText();
String note = optionalWidgets.get("note").getText();
Plant plant;
if (p.isPresent()) {
plant = p.get();
plant.setDescription(description);
//TODO place? nextInspection?
plant.setInspectionInterval(Integer.parseInt(inspectionIntervall));
//TODO scheme
} else {
plant = new Plant(Integer.parseInt(inspectionIntervall), description);
//TODO place? nextInspection?
//TODO scheme
}
plant.setManufactor(manufactor);
- plant.setConstructionYear(Integer.parseInt(constructionYear));
+ if (!constructionYear.equals("")) {
+ plant.setConstructionYear(Integer.parseInt(constructionYear));
+ }
plant.setType(type);
plant.setAirPerformance(airPerformance);
plant.setMotorPower(motorPower);
plant.setVentilatorPerformance(ventilatorPerformance);
plant.setMotorRpm(motorRPM);
plant.setCurrent(current);
plant.setVoltage(voltage);
plant.setNote(note);
return plant;
}
public Optional<Plant> getPlant() {
return plant;
}
}
| true | true | private Plant setValues(Optional<Plant> p) {
HashMap<String, Text> mandatoryWidgets = first.getMandatoryWidgets();
String description = mandatoryWidgets.get("description").getText();
//TODO place - mandatory?
//TODO nextInspection / inspectionIntervall?
String inspectionIntervall = mandatoryWidgets.get("inspectionIntervall").getText();
//TODO scheme
HashMap<String, Text> optionalWidgets = first.getOptionalWidgets();
String manufactor = optionalWidgets.get("manufactor").getText();
String constructionYear = optionalWidgets.get("constructionYear").getText();
String type = optionalWidgets.get("type").getText();
String airPerformance = optionalWidgets.get("airPerformance").getText();
String motorPower = optionalWidgets.get("motorPower").getText();
String ventilatorPerformance = optionalWidgets.get("ventilatorPerformance").getText();
String motorRPM = optionalWidgets.get("motorRPM").getText();
String current = optionalWidgets.get("current").getText();
String voltage = optionalWidgets.get("voltage").getText();
String note = optionalWidgets.get("note").getText();
Plant plant;
if (p.isPresent()) {
plant = p.get();
plant.setDescription(description);
//TODO place? nextInspection?
plant.setInspectionInterval(Integer.parseInt(inspectionIntervall));
//TODO scheme
} else {
plant = new Plant(Integer.parseInt(inspectionIntervall), description);
//TODO place? nextInspection?
//TODO scheme
}
plant.setManufactor(manufactor);
plant.setConstructionYear(Integer.parseInt(constructionYear));
plant.setType(type);
plant.setAirPerformance(airPerformance);
plant.setMotorPower(motorPower);
plant.setVentilatorPerformance(ventilatorPerformance);
plant.setMotorRpm(motorRPM);
plant.setCurrent(current);
plant.setVoltage(voltage);
plant.setNote(note);
return plant;
}
| private Plant setValues(Optional<Plant> p) {
HashMap<String, Text> mandatoryWidgets = first.getMandatoryWidgets();
String description = mandatoryWidgets.get("description").getText();
//TODO place - mandatory?
//TODO nextInspection / inspectionIntervall?
String inspectionIntervall = mandatoryWidgets.get("inspectionIntervall").getText();
//TODO scheme
HashMap<String, Text> optionalWidgets = first.getOptionalWidgets();
String manufactor = optionalWidgets.get("manufactor").getText();
String constructionYear = optionalWidgets.get("constructionYear").getText();
String type = optionalWidgets.get("type").getText();
String airPerformance = optionalWidgets.get("airPerformance").getText();
String motorPower = optionalWidgets.get("motorPower").getText();
String ventilatorPerformance = optionalWidgets.get("ventilatorPerformance").getText();
String motorRPM = optionalWidgets.get("motorRPM").getText();
String current = optionalWidgets.get("current").getText();
String voltage = optionalWidgets.get("voltage").getText();
String note = optionalWidgets.get("note").getText();
Plant plant;
if (p.isPresent()) {
plant = p.get();
plant.setDescription(description);
//TODO place? nextInspection?
plant.setInspectionInterval(Integer.parseInt(inspectionIntervall));
//TODO scheme
} else {
plant = new Plant(Integer.parseInt(inspectionIntervall), description);
//TODO place? nextInspection?
//TODO scheme
}
plant.setManufactor(manufactor);
if (!constructionYear.equals("")) {
plant.setConstructionYear(Integer.parseInt(constructionYear));
}
plant.setType(type);
plant.setAirPerformance(airPerformance);
plant.setMotorPower(motorPower);
plant.setVentilatorPerformance(ventilatorPerformance);
plant.setMotorRpm(motorRPM);
plant.setCurrent(current);
plant.setVoltage(voltage);
plant.setNote(note);
return plant;
}
|
diff --git a/app/FindReplace.java b/app/FindReplace.java
index 6cdfdff35..51fedc5d1 100644
--- a/app/FindReplace.java
+++ b/app/FindReplace.java
@@ -1,339 +1,336 @@
/* -*- mode: jde; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Part of the Processing project - http://processing.org
Copyright (c) 2004-06 Ben Fry and Casey Reas
Copyright (c) 2001-04 Massachusetts Institute of Technology
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 processing.app;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
* Find & Replace window for the Processing editor.
* <p/>
* One major annoyance in this is that the window is re-created each time
* that "Find" is called. This is because Mac OS X has a strange focus
* issue with windows that are re-shown with setVisible() or show().
* requestFocusInWindow() properly sets the focus to the find field,
* however, just a short moment later, the focus is set to null. Even
* trying to catch this scenario and request it again doesn't seem to work.
* Most likely this is some annoyance buried deep in one of Apple's docs,
* or in the doc for the focus stuff (I tend to think the former because
* Windows doesn't seem to be quite so beligerent). Filed as
* <A HREF="http://dev.processing.org/bugs/show_bug.cgi?id=244"> Bug 244</A>
* should anyone have clues about how to fix.
*/
public class FindReplace extends JFrame implements ActionListener {
static final int BIG = 13;
static final int SMALL = 6;
Editor editor;
JTextField findField;
JTextField replaceField;
static String findString;
static String replaceString;
JButton replaceButton;
JButton replaceAllButton;
JButton findButton;
JCheckBox ignoreCaseBox;
static boolean ignoreCase = true;
/// true when there's something selected in the editor
boolean found;
public FindReplace(Editor editor) {
super("Find");
setResizable(false);
this.editor = editor;
Container pain = getContentPane();
pain.setLayout(null);
JLabel findLabel = new JLabel("Find:");
Dimension d0 = findLabel.getPreferredSize();
JLabel replaceLabel = new JLabel("Replace with:");
Dimension d1 = replaceLabel.getPreferredSize();
pain.add(findLabel);
pain.add(replaceLabel);
pain.add(findField = new JTextField(20));
pain.add(replaceField = new JTextField(20));
Dimension d2 = findField.getPreferredSize();
if (findString != null) findField.setText(findString);
if (replaceString != null) replaceField.setText(replaceString);
//System.out.println("setting find str to " + findString);
//findField.requestFocusInWindow();
//pain.setDefault
/*
findField.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
System.out.println("Focus gained " + e.getOppositeComponent());
}
public void focusLost(FocusEvent e) {
System.out.println("Focus lost "); // + e.getOppositeComponent());
if (e.getOppositeComponent() == null) {
requestFocusInWindow();
}
}
});
*/
// +1 since it's better to tend downwards
int yoff = (1 + d2.height - d1.height) / 2;
findLabel.setBounds(BIG + (d1.width-d0.width) + yoff, BIG,
d1.width, d1.height);
replaceLabel.setBounds(BIG, BIG + d2.height + SMALL + yoff,
d1.width, d1.height);
//ignoreCase = true;
ignoreCaseBox = new JCheckBox("Ignore Case");
ignoreCaseBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ignoreCase = ignoreCaseBox.isSelected();
}
});
ignoreCaseBox.setSelected(ignoreCase);
pain.add(ignoreCaseBox);
//
JPanel buttons = new JPanel();
buttons.setLayout(new FlowLayout());
// ordering is different on mac versus pc
if (Base.isMacOS()) {
buttons.add(replaceButton = new JButton("Replace"));
buttons.add(replaceAllButton = new JButton("Replace All"));
buttons.add(findButton = new JButton("Find"));
} else {
buttons.add(findButton = new JButton("Find"));
buttons.add(replaceButton = new JButton("Replace"));
buttons.add(replaceAllButton = new JButton("Replace All"));
}
pain.add(buttons);
// to fix ugliness.. normally macosx java 1.3 puts an
// ugly white border around this object, so turn it off.
if (Base.isMacOS()) {
buttons.setBorder(null);
}
Dimension d3 = buttons.getPreferredSize();
//buttons.setBounds(BIG, BIG + d2.height*2 + SMALL + BIG,
buttons.setBounds(BIG, BIG + d2.height*3 + SMALL*2 + BIG,
d3.width, d3.height);
//
findField.setBounds(BIG + d1.width + SMALL, BIG,
d3.width - (d1.width + SMALL), d2.height);
replaceField.setBounds(BIG + d1.width + SMALL, BIG + d2.height + SMALL,
d3.width - (d1.width + SMALL), d2.height);
ignoreCaseBox.setBounds(BIG + d1.width + SMALL,
BIG + d2.height*2 + SMALL*2,
d3.width, d2.height);
//
replaceButton.addActionListener(this);
replaceAllButton.addActionListener(this);
findButton.addActionListener(this);
// you mustn't replace what you haven't found, my son
replaceButton.setEnabled(false);
// so that typing will go straight to this field
//findField.requestFocus();
// make the find button the blinky default
getRootPane().setDefaultButton(findButton);
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
int wide = d3.width + BIG*2;
Rectangle butt = buttons.getBounds(); // how big is your butt?
int high = butt.y + butt.height + BIG*2 + SMALL;
setBounds((screen.width - wide) / 2,
(screen.height - high) / 2, wide, high);
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
handleClose();
}
});
Base.registerWindowCloseKeys(getRootPane(), new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
//hide();
handleClose();
}
});
- /*
// hack to to get first field to focus properly on osx
- // though this still doesn't seem to work
addWindowListener(new WindowAdapter() {
public void windowActivated(WindowEvent e) {
//System.out.println("activating");
- //boolean ok = findField.requestFocusInWindow();
+ boolean ok = findField.requestFocusInWindow();
//System.out.println("got " + ok);
- //findField.selectAll();
+ findField.selectAll();
}
});
- */
}
public void handleClose() {
//System.out.println("handling close now");
findString = findField.getText();
replaceString = replaceField.getText();
// this object should eventually become dereferenced
hide();
}
/*
public void show() {
findField.requestFocusInWindow();
super.show();
//findField.selectAll();
//findField.requestFocus();
}
*/
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source == findButton) {
find(true);
} else if (source == replaceButton) {
replace();
} else if (source == replaceAllButton) {
replaceAll();
}
}
// look for the next instance of the find string
// to be found later than the current caret selection
// once found, select it (and go to that line)
public void find(boolean wrap) {
// in case search len is zero,
// otherwise replace all will go into an infinite loop
found = false;
String search = findField.getText();
//System.out.println("finding for " + search + " " + findString);
// this will catch "find next" being called when no search yet
if (search.length() == 0) return;
String text = editor.textarea.getText();
if (ignoreCase) {
search = search.toLowerCase();
text = text.toLowerCase();
}
//int selectionStart = editor.textarea.getSelectionStart();
int selectionEnd = editor.textarea.getSelectionEnd();
int nextIndex = text.indexOf(search, selectionEnd);
if (nextIndex == -1) {
if (wrap) {
// if wrapping, a second chance is ok, start from beginning
nextIndex = text.indexOf(search, 0);
}
if (nextIndex == -1) {
found = false;
replaceButton.setEnabled(false);
//Toolkit.getDefaultToolkit().beep();
return;
}
}
found = true;
replaceButton.setEnabled(true);
editor.textarea.select(nextIndex, nextIndex + search.length());
}
/**
* Replace the current selection with whatever's in the
* replacement text field.
*/
public void replace() {
if (!found) return; // don't replace if nothing found
// check to see if the document has wrapped around
// otherwise this will cause an infinite loop
String sel = editor.textarea.getSelectedText();
if (sel.equals(replaceField.getText())) {
found = false;
replaceButton.setEnabled(false);
return;
}
editor.textarea.setSelectedText(replaceField.getText());
//editor.setSketchModified(true);
//editor.sketch.setCurrentModified(true);
editor.sketch.setModified(true);
// don't allow a double replace
replaceButton.setEnabled(false);
}
/**
* Replace everything that matches by doing find and replace
* alternately until nothing more found.
*/
public void replaceAll() {
// move to the beginning
editor.textarea.select(0, 0);
do {
find(false);
replace();
} while (found);
}
}
| false | true | public FindReplace(Editor editor) {
super("Find");
setResizable(false);
this.editor = editor;
Container pain = getContentPane();
pain.setLayout(null);
JLabel findLabel = new JLabel("Find:");
Dimension d0 = findLabel.getPreferredSize();
JLabel replaceLabel = new JLabel("Replace with:");
Dimension d1 = replaceLabel.getPreferredSize();
pain.add(findLabel);
pain.add(replaceLabel);
pain.add(findField = new JTextField(20));
pain.add(replaceField = new JTextField(20));
Dimension d2 = findField.getPreferredSize();
if (findString != null) findField.setText(findString);
if (replaceString != null) replaceField.setText(replaceString);
//System.out.println("setting find str to " + findString);
//findField.requestFocusInWindow();
//pain.setDefault
/*
findField.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
System.out.println("Focus gained " + e.getOppositeComponent());
}
public void focusLost(FocusEvent e) {
System.out.println("Focus lost "); // + e.getOppositeComponent());
if (e.getOppositeComponent() == null) {
requestFocusInWindow();
}
}
});
*/
// +1 since it's better to tend downwards
int yoff = (1 + d2.height - d1.height) / 2;
findLabel.setBounds(BIG + (d1.width-d0.width) + yoff, BIG,
d1.width, d1.height);
replaceLabel.setBounds(BIG, BIG + d2.height + SMALL + yoff,
d1.width, d1.height);
//ignoreCase = true;
ignoreCaseBox = new JCheckBox("Ignore Case");
ignoreCaseBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ignoreCase = ignoreCaseBox.isSelected();
}
});
ignoreCaseBox.setSelected(ignoreCase);
pain.add(ignoreCaseBox);
//
JPanel buttons = new JPanel();
buttons.setLayout(new FlowLayout());
// ordering is different on mac versus pc
if (Base.isMacOS()) {
buttons.add(replaceButton = new JButton("Replace"));
buttons.add(replaceAllButton = new JButton("Replace All"));
buttons.add(findButton = new JButton("Find"));
} else {
buttons.add(findButton = new JButton("Find"));
buttons.add(replaceButton = new JButton("Replace"));
buttons.add(replaceAllButton = new JButton("Replace All"));
}
pain.add(buttons);
// to fix ugliness.. normally macosx java 1.3 puts an
// ugly white border around this object, so turn it off.
if (Base.isMacOS()) {
buttons.setBorder(null);
}
Dimension d3 = buttons.getPreferredSize();
//buttons.setBounds(BIG, BIG + d2.height*2 + SMALL + BIG,
buttons.setBounds(BIG, BIG + d2.height*3 + SMALL*2 + BIG,
d3.width, d3.height);
//
findField.setBounds(BIG + d1.width + SMALL, BIG,
d3.width - (d1.width + SMALL), d2.height);
replaceField.setBounds(BIG + d1.width + SMALL, BIG + d2.height + SMALL,
d3.width - (d1.width + SMALL), d2.height);
ignoreCaseBox.setBounds(BIG + d1.width + SMALL,
BIG + d2.height*2 + SMALL*2,
d3.width, d2.height);
//
replaceButton.addActionListener(this);
replaceAllButton.addActionListener(this);
findButton.addActionListener(this);
// you mustn't replace what you haven't found, my son
replaceButton.setEnabled(false);
// so that typing will go straight to this field
//findField.requestFocus();
// make the find button the blinky default
getRootPane().setDefaultButton(findButton);
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
int wide = d3.width + BIG*2;
Rectangle butt = buttons.getBounds(); // how big is your butt?
int high = butt.y + butt.height + BIG*2 + SMALL;
setBounds((screen.width - wide) / 2,
(screen.height - high) / 2, wide, high);
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
handleClose();
}
});
Base.registerWindowCloseKeys(getRootPane(), new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
//hide();
handleClose();
}
});
/*
// hack to to get first field to focus properly on osx
// though this still doesn't seem to work
addWindowListener(new WindowAdapter() {
public void windowActivated(WindowEvent e) {
//System.out.println("activating");
//boolean ok = findField.requestFocusInWindow();
//System.out.println("got " + ok);
//findField.selectAll();
}
});
*/
}
| public FindReplace(Editor editor) {
super("Find");
setResizable(false);
this.editor = editor;
Container pain = getContentPane();
pain.setLayout(null);
JLabel findLabel = new JLabel("Find:");
Dimension d0 = findLabel.getPreferredSize();
JLabel replaceLabel = new JLabel("Replace with:");
Dimension d1 = replaceLabel.getPreferredSize();
pain.add(findLabel);
pain.add(replaceLabel);
pain.add(findField = new JTextField(20));
pain.add(replaceField = new JTextField(20));
Dimension d2 = findField.getPreferredSize();
if (findString != null) findField.setText(findString);
if (replaceString != null) replaceField.setText(replaceString);
//System.out.println("setting find str to " + findString);
//findField.requestFocusInWindow();
//pain.setDefault
/*
findField.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
System.out.println("Focus gained " + e.getOppositeComponent());
}
public void focusLost(FocusEvent e) {
System.out.println("Focus lost "); // + e.getOppositeComponent());
if (e.getOppositeComponent() == null) {
requestFocusInWindow();
}
}
});
*/
// +1 since it's better to tend downwards
int yoff = (1 + d2.height - d1.height) / 2;
findLabel.setBounds(BIG + (d1.width-d0.width) + yoff, BIG,
d1.width, d1.height);
replaceLabel.setBounds(BIG, BIG + d2.height + SMALL + yoff,
d1.width, d1.height);
//ignoreCase = true;
ignoreCaseBox = new JCheckBox("Ignore Case");
ignoreCaseBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ignoreCase = ignoreCaseBox.isSelected();
}
});
ignoreCaseBox.setSelected(ignoreCase);
pain.add(ignoreCaseBox);
//
JPanel buttons = new JPanel();
buttons.setLayout(new FlowLayout());
// ordering is different on mac versus pc
if (Base.isMacOS()) {
buttons.add(replaceButton = new JButton("Replace"));
buttons.add(replaceAllButton = new JButton("Replace All"));
buttons.add(findButton = new JButton("Find"));
} else {
buttons.add(findButton = new JButton("Find"));
buttons.add(replaceButton = new JButton("Replace"));
buttons.add(replaceAllButton = new JButton("Replace All"));
}
pain.add(buttons);
// to fix ugliness.. normally macosx java 1.3 puts an
// ugly white border around this object, so turn it off.
if (Base.isMacOS()) {
buttons.setBorder(null);
}
Dimension d3 = buttons.getPreferredSize();
//buttons.setBounds(BIG, BIG + d2.height*2 + SMALL + BIG,
buttons.setBounds(BIG, BIG + d2.height*3 + SMALL*2 + BIG,
d3.width, d3.height);
//
findField.setBounds(BIG + d1.width + SMALL, BIG,
d3.width - (d1.width + SMALL), d2.height);
replaceField.setBounds(BIG + d1.width + SMALL, BIG + d2.height + SMALL,
d3.width - (d1.width + SMALL), d2.height);
ignoreCaseBox.setBounds(BIG + d1.width + SMALL,
BIG + d2.height*2 + SMALL*2,
d3.width, d2.height);
//
replaceButton.addActionListener(this);
replaceAllButton.addActionListener(this);
findButton.addActionListener(this);
// you mustn't replace what you haven't found, my son
replaceButton.setEnabled(false);
// so that typing will go straight to this field
//findField.requestFocus();
// make the find button the blinky default
getRootPane().setDefaultButton(findButton);
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
int wide = d3.width + BIG*2;
Rectangle butt = buttons.getBounds(); // how big is your butt?
int high = butt.y + butt.height + BIG*2 + SMALL;
setBounds((screen.width - wide) / 2,
(screen.height - high) / 2, wide, high);
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
handleClose();
}
});
Base.registerWindowCloseKeys(getRootPane(), new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
//hide();
handleClose();
}
});
// hack to to get first field to focus properly on osx
addWindowListener(new WindowAdapter() {
public void windowActivated(WindowEvent e) {
//System.out.println("activating");
boolean ok = findField.requestFocusInWindow();
//System.out.println("got " + ok);
findField.selectAll();
}
});
}
|
diff --git a/servers/media/core/server-impl/src/main/java/org/mobicents/media/server/impl/events/announcement/AudioPlayer.java b/servers/media/core/server-impl/src/main/java/org/mobicents/media/server/impl/events/announcement/AudioPlayer.java
index 26ae985e4..78d210947 100755
--- a/servers/media/core/server-impl/src/main/java/org/mobicents/media/server/impl/events/announcement/AudioPlayer.java
+++ b/servers/media/core/server-impl/src/main/java/org/mobicents/media/server/impl/events/announcement/AudioPlayer.java
@@ -1,261 +1,262 @@
/*
* BaseConnection.java
*
* Mobicents Media Gateway
*
* The source code contained in this file is in in the public domain.
* It can be used in any project or product without prior permission,
* license or royalty payments. There is NO WARRANTY OF ANY KIND,
* EXPRESS, IMPLIED OR STATUTORY, INCLUDING, WITHOUT LIMITATION,
* THE IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE,
* AND DATA ACCURACY. We do not warrant or make any representations
* regarding the use of the software or the results thereof, including
* but not limited to the correctness, accuracy, reliability or
* usefulness of the software.
*/
package org.mobicents.media.server.impl.events.announcement;
import java.io.IOException;
import java.net.URL;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.AudioFormat.Encoding;
import org.apache.log4j.Logger;
import org.mobicents.media.Buffer;
import org.mobicents.media.Format;
import org.mobicents.media.format.AudioFormat;
import org.mobicents.media.server.impl.AbstractSource;
import org.mobicents.media.server.impl.CachedBuffersPool;
import org.mobicents.media.server.impl.clock.Quartz;
import org.mobicents.media.server.impl.clock.Timer;
import org.mobicents.media.server.spi.events.pkg.Announcement;
import org.xiph.speex.spi.SpeexAudioFileReader;
/**
*
* @author Oleg Kulikov
*/
public class AudioPlayer extends AbstractSource implements Runnable {
private transient Logger logger = Logger.getLogger(AudioPlayer.class);
protected final static AudioFormat LINEAR = new AudioFormat(
AudioFormat.LINEAR, 8000, 16, 1,
AudioFormat.LITTLE_ENDIAN,
AudioFormat.SIGNED);
protected AudioFormat format = LINEAR;
protected final static Format[] formats = new Format[]{LINEAR};
private AudioInputStream stream = null;
private int packetSize;
private long seq = 0;
protected Timer timer;
private boolean started;
private String file;
private long time;
private int count = 0;
//protected int packetPeriod;
public AudioPlayer() {
super("AudioPlayer");
this.timer = new Timer();
timer.setListener(this);
}
public void setFile(String file) {
this.file = file;
}
public void start() {
this.start(file);
}
/**
* Starts playing audio from specified file.
*
*
* @param file the string url which points to a file to be played. *
*
* @throws java.net.MalformedURLException
* @throws java.io.IOException
* @throws javax.media.NoDataSourceException
* @throws javax.media.NoProcessorException
* @throws javax.media.CannotRealizeException
*/
public void start(String file) {
URL url = null;
try {
url = new URL(file);
} catch (IOException e) {
+ logger.error("IOException in file "+ file, e);
this.failed(e);
return;
}
//speex support
try {
synchronized (this) {
stream = AudioSystem.getAudioInputStream(url);
}
} catch (Exception e) {
logger.error("Error " + stream, e);
this.failed(e);
return;
}
if (stream == null) {
SpeexAudioFileReader speexAudioFileReader = new SpeexAudioFileReader();
try {
stream = speexAudioFileReader.getAudioInputStream(url);
} catch (Exception e) {
this.failed(e);
return;
}
}
AudioFormat fmt = new AudioFormat(getEncoding(stream.getFormat().getEncoding()), stream.getFormat().getFrameRate(), stream.getFormat().getFrameSize() * 8, stream.getFormat().getChannels());
packetSize = (int) ((fmt.getSampleRate() / 1000) * (fmt.getSampleSizeInBits() / 8) * Quartz.HEART_BEAT);
this.timer.start();
this.started = true;
//worker = new Thread(this);
//worker.setName("Audio Player");
//worker.setPriority(Thread.MAX_PRIORITY);
//worker.start();
this.started();
}
private String getEncoding(Encoding encoding) {
if (encoding == Encoding.ALAW) {
return "ALAW";
} else if (encoding == Encoding.ULAW) {
return "ULAW";
} else if (encoding == Encoding.PCM_SIGNED) {
return "LINEAR";
} else if (encoding == Encoding.PCM_UNSIGNED) {
return "LINEAR";
} else {
return null;
}
}
/**
* Terminates player.
*/
public void stop() {
timer.stop();
if (started) {
started = false;
this.stopped();
}
}
/**
* Called when player failed.
*/
protected void failed(Exception e) {
AnnEventImpl evt = new AnnEventImpl(Announcement.FAILED);
this.sendEvent(evt);
}
/**
* Called when player stopped.
*/
protected void stopped() {
AnnEventImpl evt = new AnnEventImpl(Announcement.COMPLETED);
this.sendEvent(evt);
}
/**
* Called when player started to transmitt audio.
*/
protected void started() {
AnnEventImpl evt = new AnnEventImpl(Announcement.STARTED);
this.sendEvent(evt);
}
/**
* Called when player reached end of audio stream.
*/
protected void endOfMedia() {
started = false;
AnnEventImpl evt = new AnnEventImpl(Announcement.COMPLETED);
this.sendEvent(evt);
}
private int readPacket(byte[] packet) throws IOException {
int offset = 0;
while (offset < packetSize) {
int len = stream.read(packet, offset, packetSize - offset);
if (len == -1) {
return -1;
}
offset += len;
}
return packetSize;
}
private void doProcess() {
byte[] packet = new byte[packetSize];
try {
//int len = stream.read(packet);
int len = readPacket(packet);
// long now = System.currentTimeMillis();
// if (now - time > 25) {
// System.out.println("Delay= " + (now - time));
// }
// time = now;
if (len == -1) {
timer.stop();
if (started) {
this.endOfMedia();
}
} else {
Buffer buffer = CachedBuffersPool.allocate();
buffer.setData(packet);
buffer.setDuration(Quartz.HEART_BEAT);
buffer.setLength(len);
buffer.setOffset(0);
buffer.setFormat(format);
buffer.setTimeStamp(seq * Quartz.HEART_BEAT);
buffer.setEOM(false);
buffer.setSequenceNumber(seq++);
if (sink != null) {
sink.receive(buffer);
}
}
} catch (Exception e) {
timer.stop();
started = false;
e.printStackTrace();
failed(e);
}
}
@SuppressWarnings("static-access")
public void run() {
/* while (started) {
if (count == 2) {
count = 0;
doProcess();
} else {
count++;
try {
Thread.currentThread().sleep(10);
} catch (InterruptedException e) {
started = false;
}
}
}
*/
doProcess();
}
public Format[] getFormats() {
return formats;
}
}
| true | true | public void start(String file) {
URL url = null;
try {
url = new URL(file);
} catch (IOException e) {
this.failed(e);
return;
}
//speex support
try {
synchronized (this) {
stream = AudioSystem.getAudioInputStream(url);
}
} catch (Exception e) {
logger.error("Error " + stream, e);
this.failed(e);
return;
}
if (stream == null) {
SpeexAudioFileReader speexAudioFileReader = new SpeexAudioFileReader();
try {
stream = speexAudioFileReader.getAudioInputStream(url);
} catch (Exception e) {
this.failed(e);
return;
}
}
AudioFormat fmt = new AudioFormat(getEncoding(stream.getFormat().getEncoding()), stream.getFormat().getFrameRate(), stream.getFormat().getFrameSize() * 8, stream.getFormat().getChannels());
packetSize = (int) ((fmt.getSampleRate() / 1000) * (fmt.getSampleSizeInBits() / 8) * Quartz.HEART_BEAT);
this.timer.start();
this.started = true;
//worker = new Thread(this);
//worker.setName("Audio Player");
//worker.setPriority(Thread.MAX_PRIORITY);
//worker.start();
this.started();
}
| public void start(String file) {
URL url = null;
try {
url = new URL(file);
} catch (IOException e) {
logger.error("IOException in file "+ file, e);
this.failed(e);
return;
}
//speex support
try {
synchronized (this) {
stream = AudioSystem.getAudioInputStream(url);
}
} catch (Exception e) {
logger.error("Error " + stream, e);
this.failed(e);
return;
}
if (stream == null) {
SpeexAudioFileReader speexAudioFileReader = new SpeexAudioFileReader();
try {
stream = speexAudioFileReader.getAudioInputStream(url);
} catch (Exception e) {
this.failed(e);
return;
}
}
AudioFormat fmt = new AudioFormat(getEncoding(stream.getFormat().getEncoding()), stream.getFormat().getFrameRate(), stream.getFormat().getFrameSize() * 8, stream.getFormat().getChannels());
packetSize = (int) ((fmt.getSampleRate() / 1000) * (fmt.getSampleSizeInBits() / 8) * Quartz.HEART_BEAT);
this.timer.start();
this.started = true;
//worker = new Thread(this);
//worker.setName("Audio Player");
//worker.setPriority(Thread.MAX_PRIORITY);
//worker.start();
this.started();
}
|
diff --git a/Sources/net/rujel/reusables/SessionedEditingContext.java b/Sources/net/rujel/reusables/SessionedEditingContext.java
index c763f8b..4c1ee01 100644
--- a/Sources/net/rujel/reusables/SessionedEditingContext.java
+++ b/Sources/net/rujel/reusables/SessionedEditingContext.java
@@ -1,165 +1,165 @@
// SessionedEditingContext.java
/*
* Copyright (c) 2008, Gennady & Michael Kushnir
* 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 RUJEL 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.rujel.reusables;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Logger;
import java.util.logging.Level;
import com.webobjects.eocontrol.*;
import com.webobjects.appserver.*;
import com.webobjects.foundation.NSMutableArray;
public class SessionedEditingContext extends EOEditingContext {
protected WOSession session;
protected static Logger logger = Logger.getLogger("rujel.reusables");
protected static final SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss SSS");
protected Counter failures = new Counter();
public SessionedEditingContext (WOSession ses){
super((ses.objectForKey("objectStore")!=null)?
(EOObjectStore)ses.objectForKey("objectStore"):
EOObjectStoreCoordinator.defaultCoordinator());
session = ses;
if(ses instanceof MultiECLockManager.Session)
((MultiECLockManager.Session)ses).ecLockManager().registerEditingContext(this);
}
public SessionedEditingContext (EOObjectStore parent,WOSession ses, boolean reg) {
super(parent);
if (ses == null) throw new
NullPointerException (
"You should define a session to instantiate SessionedEditingContext");
session = ses;
if(reg && ses instanceof MultiECLockManager.Session)
((MultiECLockManager.Session)ses).ecLockManager().registerEditingContext(this);
}
public SessionedEditingContext (EOObjectStore parent,WOSession ses) {
this(parent,ses,true);
}
public WOSession session() {
return session;
}
public void saveChanges() {
try {
super.saveChanges();
if(!SettingsReader.boolForKeyPath("ui.undoAfterSave", false))
undoManager().removeAllActionsWithTarget(this);
failures.nullify();
} catch (RuntimeException ex) {
failures.raise();
throw ex;
}
}
public int failuresCount () {
return failures.value();
}
protected void fin() {
if(session instanceof MultiECLockManager.Session)
((MultiECLockManager.Session)session).
ecLockManager().unregisterEditingContext(this);
if(_stackTraces.count() > 0)
logger.log(Level.WARNING,"disposing locked editing context (" +
_nameOfLockingThread + " : " + _stackTraces.count() + ')', new Object[]
{session, new Exception(), _stackTraces});
}
protected boolean inRevert = false;
public void revert() {
inRevert = true;
super.revert();
inRevert = false;
}
public void dispose() {
fin();
super.dispose();
}
public void finalize() throws Throwable {
fin();
super.finalize();
}
private String _nameOfLockingThread = null;
private NSMutableArray _stackTraces = new NSMutableArray();
public void lock() {
String nameOfCurrentThread = Thread.currentThread().getName();
Exception e = new Exception(df.format(new Date()));
String trace = WOLogFormatter.formatTrowable(e);
if (_stackTraces.count() == 0) {
_stackTraces.addObject(trace);
_nameOfLockingThread = nameOfCurrentThread;
} else {
if (nameOfCurrentThread.equals(_nameOfLockingThread)) {
_stackTraces.addObject(trace);
} else {
Level level = Level.INFO;
StackTraceElement stack[] = e.getStackTrace();
for (int i = 0; i < stack.length; i++) {
if(stack[i].getClassName().contains("NSNotificationCenter")) {
level = Level.FINER;
break;
}
}
logger.log(level,
"Attempting to lock editing context from " + nameOfCurrentThread
+ " that was previously locked in " + _nameOfLockingThread,
- new Object[] {session,stack,_stackTraces});
+ new Object[] {session,e,_stackTraces});
}
}
super.lock();
}
public void unlock() {
super.unlock();
if (_stackTraces.count() > 0)
_stackTraces.removeLastObject();
else
_stackTraces.count();
if (_stackTraces.count() == 0)
_nameOfLockingThread = null;
}
public void insertObject(EOEnterpriseObject object) {
super.insertObject(object);
if(!globalIDForObject(object).isTemporary())
logger.log((inRevert)?Level.FINER:Level.INFO,
"Inserting not new object",new Object[] {session,object, new Exception()});
}
}
| true | true | public void lock() {
String nameOfCurrentThread = Thread.currentThread().getName();
Exception e = new Exception(df.format(new Date()));
String trace = WOLogFormatter.formatTrowable(e);
if (_stackTraces.count() == 0) {
_stackTraces.addObject(trace);
_nameOfLockingThread = nameOfCurrentThread;
} else {
if (nameOfCurrentThread.equals(_nameOfLockingThread)) {
_stackTraces.addObject(trace);
} else {
Level level = Level.INFO;
StackTraceElement stack[] = e.getStackTrace();
for (int i = 0; i < stack.length; i++) {
if(stack[i].getClassName().contains("NSNotificationCenter")) {
level = Level.FINER;
break;
}
}
logger.log(level,
"Attempting to lock editing context from " + nameOfCurrentThread
+ " that was previously locked in " + _nameOfLockingThread,
new Object[] {session,stack,_stackTraces});
}
}
super.lock();
}
| public void lock() {
String nameOfCurrentThread = Thread.currentThread().getName();
Exception e = new Exception(df.format(new Date()));
String trace = WOLogFormatter.formatTrowable(e);
if (_stackTraces.count() == 0) {
_stackTraces.addObject(trace);
_nameOfLockingThread = nameOfCurrentThread;
} else {
if (nameOfCurrentThread.equals(_nameOfLockingThread)) {
_stackTraces.addObject(trace);
} else {
Level level = Level.INFO;
StackTraceElement stack[] = e.getStackTrace();
for (int i = 0; i < stack.length; i++) {
if(stack[i].getClassName().contains("NSNotificationCenter")) {
level = Level.FINER;
break;
}
}
logger.log(level,
"Attempting to lock editing context from " + nameOfCurrentThread
+ " that was previously locked in " + _nameOfLockingThread,
new Object[] {session,e,_stackTraces});
}
}
super.lock();
}
|
diff --git a/closure/closure-templates/java/src/com/google/template/soy/data/SoyData.java b/closure/closure-templates/java/src/com/google/template/soy/data/SoyData.java
index 35198e5fd..f90219485 100644
--- a/closure/closure-templates/java/src/com/google/template/soy/data/SoyData.java
+++ b/closure/closure-templates/java/src/com/google/template/soy/data/SoyData.java
@@ -1,171 +1,174 @@
/*
* Copyright 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.template.soy.data;
import com.google.template.soy.data.restricted.BooleanData;
import com.google.template.soy.data.restricted.FloatData;
import com.google.template.soy.data.restricted.IntegerData;
import com.google.template.soy.data.restricted.NullData;
import com.google.template.soy.data.restricted.StringData;
import java.util.List;
import java.util.Map;
/**
* Abstract base class for all nodes in a Soy data tree.
*
* @author Kai Huang
*/
public abstract class SoyData {
/**
* Creation function for creating a SoyData object out of any existing primitive, data object, or
* data structure.
*
* <p> Important: Avoid using this function if you know the type of the object at compile time.
* For example, if the object is a primitive, it can be passed directly to methods such as
* {@code SoyMapData.put()} or {@code SoyListData.add()}. If the object is a Map or an Iterable,
* you can directly create the equivalent SoyData object using the constructor of
* {@code SoyMapData} or {@code SoyListData}.
*
* <p> If the given object is already a SoyData object, then it is simply returned.
* Otherwise a new SoyData object will be created that is equivalent to the given primitive, data
* object, or data structure (even if the given object is null!).
*
* <p> Note that in order for the conversion process to succeed, the given data structure must
* correspond to a valid SoyData tree. Some requirements include:
* (a) all Maps within your data structure must have string keys that are identifiers,
* (b) all non-leaf nodes must be Maps or Lists,
* (c) all leaf nodes must be null, boolean, int, double, or String (corresponding to Soy
* primitive data types null, boolean, integer, float, string).
*
* @param obj The existing object or data structure to convert.
* @return A SoyData object or tree that corresponds to the given object.
* @throws SoyDataException If the given object cannot be converted to SoyData.
*/
public static SoyData createFromExistingData(Object obj) {
if (obj == null) {
return NullData.INSTANCE;
} else if (obj instanceof SoyData) {
return (SoyData) obj;
} else if (obj instanceof String) {
return new StringData((String) obj);
} else if (obj instanceof Boolean) {
return new BooleanData((Boolean) obj);
} else if (obj instanceof Integer) {
return new IntegerData((Integer) obj);
- } else if (obj instanceof Double) {
- return new FloatData((Double) obj);
} else if (obj instanceof Map) {
@SuppressWarnings("unchecked")
Map<String, ?> objCast = (Map<String, ?>) obj;
return new SoyMapData(objCast);
} else if (obj instanceof List) {
return new SoyListData((List<?>) obj);
+ } else if (obj instanceof Double) {
+ return new FloatData((Double) obj);
+ } else if (obj instanceof Float) {
+ // Automatically convert float to double.
+ return new FloatData((Float) obj);
} else {
throw new SoyDataException(
"Attempting to convert unrecognized object to Soy data (object type " +
obj.getClass().getSimpleName() + ").");
}
}
/**
* Converts this data object into a string (e.g. when used in a string context).
* @return The value of this data object if coerced into a string.
*/
@Override public abstract String toString();
/**
* Converts this data object into a boolean (e.g. when used in a boolean context). In other words,
* this method tells whether this object is truthy.
* @return The value of this data object if coerced into a boolean. I.e. true if this object is
* truthy, false if this object is falsy.
*/
public abstract boolean toBoolean();
/**
* Compares this data object against another for equality in the sense of the operator '==' for
* Soy expressions.
*
* @param other The other data object to compare against.
* @return True if the two objects are equal.
*/
@Override public abstract boolean equals(Object other);
/**
* Precondition: Only call this method if you know that this SoyData object is a boolean.
* This method gets the boolean value of this boolean object.
* @return The boolean value of this boolean object.
* @throws SoyDataException If this object is not actually a boolean.
*/
public boolean booleanValue() {
throw new SoyDataException("Non-boolean found when expecting boolean value.");
}
/**
* Precondition: Only call this method if you know that this SoyData object is an integer.
* This method gets the integer value of this integer object.
* @return The integer value of this integer object.
* @throws SoyDataException If this object is not actually an integer.
*/
public int integerValue() {
throw new SoyDataException("Non-integer found when expecting integer value.");
}
/**
* Precondition: Only call this method if you know that this SoyData object is a float.
* This method gets the float value of this float object.
* @return The float value of this float object.
* @throws SoyDataException If this object is not actually a float.
*/
public double floatValue() {
throw new SoyDataException("Non-float found when expecting float value.");
}
/**
* Precondition: Only call this method if you know that this SoyData object is a number.
* This method gets the float value of this number object (converting integer to float if
* necessary).
* @return The float value of this number object.
* @throws SoyDataException If this object is not actually a number.
*/
public double numberValue() {
throw new SoyDataException("Non-number found when expecting number value.");
}
/**
* Precondition: Only call this method if you know that this SoyData object is a string.
* This method gets the string value of this string object.
* @return The string value of this string object.
* @throws SoyDataException If this object is not actually a string.
*/
public String stringValue() {
throw new SoyDataException("Non-string found when expecting string value.");
}
}
| false | true | public static SoyData createFromExistingData(Object obj) {
if (obj == null) {
return NullData.INSTANCE;
} else if (obj instanceof SoyData) {
return (SoyData) obj;
} else if (obj instanceof String) {
return new StringData((String) obj);
} else if (obj instanceof Boolean) {
return new BooleanData((Boolean) obj);
} else if (obj instanceof Integer) {
return new IntegerData((Integer) obj);
} else if (obj instanceof Double) {
return new FloatData((Double) obj);
} else if (obj instanceof Map) {
@SuppressWarnings("unchecked")
Map<String, ?> objCast = (Map<String, ?>) obj;
return new SoyMapData(objCast);
} else if (obj instanceof List) {
return new SoyListData((List<?>) obj);
} else {
throw new SoyDataException(
"Attempting to convert unrecognized object to Soy data (object type " +
obj.getClass().getSimpleName() + ").");
}
}
| public static SoyData createFromExistingData(Object obj) {
if (obj == null) {
return NullData.INSTANCE;
} else if (obj instanceof SoyData) {
return (SoyData) obj;
} else if (obj instanceof String) {
return new StringData((String) obj);
} else if (obj instanceof Boolean) {
return new BooleanData((Boolean) obj);
} else if (obj instanceof Integer) {
return new IntegerData((Integer) obj);
} else if (obj instanceof Map) {
@SuppressWarnings("unchecked")
Map<String, ?> objCast = (Map<String, ?>) obj;
return new SoyMapData(objCast);
} else if (obj instanceof List) {
return new SoyListData((List<?>) obj);
} else if (obj instanceof Double) {
return new FloatData((Double) obj);
} else if (obj instanceof Float) {
// Automatically convert float to double.
return new FloatData((Float) obj);
} else {
throw new SoyDataException(
"Attempting to convert unrecognized object to Soy data (object type " +
obj.getClass().getSimpleName() + ").");
}
}
|
diff --git a/src/com/android/browser/BrowserActivity.java b/src/com/android/browser/BrowserActivity.java
index b46d0203..03bb9df1 100644
--- a/src/com/android/browser/BrowserActivity.java
+++ b/src/com/android/browser/BrowserActivity.java
@@ -1,4114 +1,4112 @@
/*
* Copyright (C) 2006 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.browser;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
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.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Picture;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.WebAddress;
import android.net.http.SslCertificate;
import android.net.http.SslError;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Debug;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.Process;
import android.os.ServiceManager;
import android.os.SystemClock;
import android.provider.Browser;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Intents.Insert;
import android.provider.Downloads;
import android.provider.MediaStore;
import android.speech.RecognizerResultsIntent;
import android.text.IClipboard;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.util.AttributeSet;
import android.util.Log;
import android.util.Patterns;
import android.view.ContextMenu;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.accessibility.AccessibilityManager;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.DownloadListener;
import android.webkit.HttpAuthHandler;
import android.webkit.PluginManager;
import android.webkit.SslErrorHandler;
import android.webkit.URLUtil;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebHistoryItem;
import android.webkit.WebIconDatabase;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerFuture;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.accounts.AccountManagerCallback;
import com.android.common.Search;
import com.android.common.speech.LoggingEvents;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class BrowserActivity extends Activity
implements View.OnCreateContextMenuListener, DownloadListener {
/* Define some aliases to make these debugging flags easier to refer to.
* This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
*/
private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
// These are single-character shortcuts for searching popular sources.
private static final int SHORTCUT_INVALID = 0;
private static final int SHORTCUT_GOOGLE_SEARCH = 1;
private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
@Override
public Void doInBackground(File... files) {
if (files != null) {
for (File f : files) {
if (!f.delete()) {
Log.e(LOGTAG, f.getPath() + " was not deleted");
}
}
}
return null;
}
}
/**
* This layout holds everything you see below the status bar, including the
* error console, the custom view container, and the webviews.
*/
private FrameLayout mBrowserFrameLayout;
private boolean mXLargeScreenSize;
@Override
public void onCreate(Bundle icicle) {
if (LOGV_ENABLED) {
Log.v(LOGTAG, this + " onStart");
}
super.onCreate(icicle);
// test the browser in OpenGL
// requestWindowFeature(Window.FEATURE_OPENGL);
// enable this to test the browser in 32bit
if (false) {
getWindow().setFormat(PixelFormat.RGBX_8888);
BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
}
if (AccessibilityManager.getInstance(this).isEnabled()) {
setDefaultKeyMode(DEFAULT_KEYS_DISABLE);
} else {
setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
}
mResolver = getContentResolver();
// If this was a web search request, pass it on to the default web
// search provider and finish this activity.
if (handleWebSearchIntent(getIntent())) {
finish();
return;
}
mSecLockIcon = Resources.getSystem().getDrawable(
android.R.drawable.ic_secure);
mMixLockIcon = Resources.getSystem().getDrawable(
android.R.drawable.ic_partial_secure);
FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
.findViewById(com.android.internal.R.id.content);
mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
.inflate(R.layout.custom_screen, null);
mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
R.id.main_content);
mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
.findViewById(R.id.error_console);
mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
.findViewById(R.id.fullscreen_custom_content);
frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
mTitleBar = new TitleBar(this);
mXLargeScreenSize = (getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK)
== Configuration.SCREENLAYOUT_SIZE_XLARGE;
if (mXLargeScreenSize) {
LinearLayout layout = (LinearLayout) mBrowserFrameLayout.
findViewById(R.id.vertical_layout);
layout.addView(mTitleBar, 0, new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
} else {
// mTitleBar will be always be shown in the fully loaded mode on
// phone
mTitleBar.setProgress(100);
// Fake title bar is not needed in xlarge layout
mFakeTitleBar = new TitleBar(this);
}
// Create the tab control and our initial tab
mTabControl = new TabControl(this);
// Open the icon database and retain all the bookmark urls for favicons
retainIconsOnStartup();
// Keep a settings instance handy.
mSettings = BrowserSettings.getInstance();
mSettings.setTabControl(mTabControl);
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
// Find out if the network is currently up.
ConnectivityManager cm = (ConnectivityManager) getSystemService(
Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null) {
mIsNetworkUp = info.isAvailable();
}
/* enables registration for changes in network status from
http stack */
mNetworkStateChangedFilter = new IntentFilter();
mNetworkStateChangedFilter.addAction(
ConnectivityManager.CONNECTIVITY_ACTION);
mNetworkStateIntentReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(
ConnectivityManager.CONNECTIVITY_ACTION)) {
NetworkInfo info = intent.getParcelableExtra(
ConnectivityManager.EXTRA_NETWORK_INFO);
String typeName = info.getTypeName();
String subtypeName = info.getSubtypeName();
sendNetworkType(typeName.toLowerCase(),
(subtypeName != null ? subtypeName.toLowerCase() : ""));
onNetworkToggle(info.isAvailable());
}
}
};
IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
filter.addDataScheme("package");
mPackageInstallationReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
final String packageName = intent.getData()
.getSchemeSpecificPart();
final boolean replacing = intent.getBooleanExtra(
Intent.EXTRA_REPLACING, false);
if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
// if it is replacing, refreshPlugins() when adding
return;
}
if (sGoogleApps.contains(packageName)) {
BrowserActivity.this.packageChanged(packageName,
Intent.ACTION_PACKAGE_ADDED.equals(action));
}
PackageManager pm = BrowserActivity.this.getPackageManager();
PackageInfo pkgInfo = null;
try {
pkgInfo = pm.getPackageInfo(packageName,
PackageManager.GET_PERMISSIONS);
} catch (PackageManager.NameNotFoundException e) {
return;
}
if (pkgInfo != null) {
String permissions[] = pkgInfo.requestedPermissions;
if (permissions == null) {
return;
}
boolean permissionOk = false;
for (String permit : permissions) {
if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
permissionOk = true;
break;
}
}
if (permissionOk) {
PluginManager.getInstance(BrowserActivity.this)
- .refreshPlugins(
- Intent.ACTION_PACKAGE_ADDED
- .equals(action));
+ .refreshPlugins(true);
}
}
}
};
registerReceiver(mPackageInstallationReceiver, filter);
if (!mTabControl.restoreState(icicle)) {
// clear up the thumbnail directory if we can't restore the state as
// none of the files in the directory are referenced any more.
new ClearThumbnails().execute(
mTabControl.getThumbnailDir().listFiles());
// there is no quit on Android. But if we can't restore the state,
// we can treat it as a new Browser, remove the old session cookies.
CookieManager.getInstance().removeSessionCookie();
final Intent intent = getIntent();
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 = getUrlDataFromIntent(intent);
String action = intent.getAction();
final Tab t = mTabControl.createNewTab(
(Intent.ACTION_VIEW.equals(action) &&
intent.getData() != null)
|| RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
.equals(action),
intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
mTabControl.setCurrentTab(t);
attachTabToContentView(t);
WebView webView = t.getWebView();
if (extra != null) {
int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
if (scale > 0 && scale <= 1000) {
webView.setInitialScale(scale);
}
}
if (urlData.isEmpty()) {
loadUrl(webView, mSettings.getHomePage());
} else {
loadUrlDataIn(t, urlData);
}
} else {
// TabControl.restoreState() will create a new tab even if
// restoring the state fails.
attachTabToContentView(mTabControl.getCurrentTab());
}
// Read JavaScript flags if it exists.
String jsFlags = mSettings.getJsFlags();
if (jsFlags.trim().length() != 0) {
mTabControl.getCurrentWebView().setJsFlags(jsFlags);
}
// Work out which packages are installed on the system.
getInstalledPackages();
// Start watching the default geolocation permissions
mSystemAllowGeolocationOrigins
= new SystemAllowGeolocationOrigins(getApplicationContext());
mSystemAllowGeolocationOrigins.start();
}
/**
* 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.
*/
/* package */ void showVoiceSearchResults(String result) {
ContentProviderClient client = mResolver.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);
}
@Override
protected void onNewIntent(Intent intent) {
Tab current = mTabControl.getCurrentTab();
// When a tab is closed on exit, the current tab index is set to -1.
// Reset before proceed as Browser requires the current tab to be set.
if (current == null) {
// Try to reset the tab in case the index was incorrect.
current = mTabControl.getTab(0);
if (current == null) {
// No tabs at all so just ignore this intent.
return;
}
mTabControl.setCurrentTab(current);
attachTabToContentView(current);
resetTitleAndIcon(current.getWebView());
}
final String action = intent.getAction();
final int flags = intent.getFlags();
if (Intent.ACTION_MAIN.equals(action) ||
(flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
// just resume the browser
return;
}
// In case the SearchDialog is open.
((SearchManager) getSystemService(Context.SEARCH_SERVICE))
.stopSearch();
boolean activateVoiceSearch = RecognizerResultsIntent
.ACTION_VOICE_SEARCH_RESULTS.equals(action);
if (Intent.ACTION_VIEW.equals(action)
|| Intent.ACTION_SEARCH.equals(action)
|| MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
|| Intent.ACTION_WEB_SEARCH.equals(action)
|| activateVoiceSearch) {
if (current.isInVoiceSearchMode()) {
String title = current.getVoiceDisplayTitle();
if (title != null && title.equals(intent.getStringExtra(
SearchManager.QUERY))) {
// The user submitted the same search as the last voice
// search, so do nothing.
return;
}
if (Intent.ACTION_SEARCH.equals(action)
&& current.voiceSearchSourceIsGoogle()) {
Intent logIntent = new Intent(
LoggingEvents.ACTION_LOG_EVENT);
logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
LoggingEvents.VoiceSearch.QUERY_UPDATED);
logIntent.putExtra(
LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
intent.getDataString());
sendBroadcast(logIntent);
// Note, onPageStarted will revert the voice title bar
// When http://b/issue?id=2379215 is fixed, we should update
// the title bar here.
}
}
// If this was a search request (e.g. search query directly typed into the address bar),
// pass it on to the default web search provider.
if (handleWebSearchIntent(intent)) {
return;
}
UrlData urlData = getUrlDataFromIntent(intent);
if (urlData.isEmpty()) {
urlData = new UrlData(mSettings.getHomePage());
}
final String appId = intent
.getStringExtra(Browser.EXTRA_APPLICATION_ID);
if ((Intent.ACTION_VIEW.equals(action)
// If a voice search has no appId, it means that it came
// from the browser. In that case, reuse the current tab.
|| (activateVoiceSearch && appId != null))
&& !getPackageName().equals(appId)
&& (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Tab appTab = mTabControl.getTabFromId(appId);
if (appTab != null) {
Log.i(LOGTAG, "Reusing tab for " + appId);
// Dismiss the subwindow if applicable.
dismissSubWindow(appTab);
// Since we might kill the WebView, remove it from the
// content view first.
removeTabFromContentView(appTab);
// Recreate the main WebView after destroying the old one.
// If the WebView has the same original url and is on that
// page, it can be reused.
boolean needsLoad =
mTabControl.recreateWebView(appTab, urlData);
if (current != appTab) {
switchToTab(mTabControl.getTabIndex(appTab));
if (needsLoad) {
loadUrlDataIn(appTab, urlData);
}
} else {
// If the tab was the current tab, we have to attach
// it to the view system again.
attachTabToContentView(appTab);
if (needsLoad) {
loadUrlDataIn(appTab, urlData);
}
}
return;
} else {
// No matching application tab, try to find a regular tab
// with a matching url.
appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
if (appTab != null) {
if (current != appTab) {
switchToTab(mTabControl.getTabIndex(appTab));
}
// Otherwise, we are already viewing the correct tab.
} else {
// if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
// will be opened in a new tab unless we have reached
// MAX_TABS. Then the url will be opened in the current
// tab. If a new tab is created, it will have "true" for
// exit on close.
openTabAndShow(urlData, true, appId);
}
}
} else {
if (!urlData.isEmpty()
&& urlData.mUrl.startsWith("about:debug")) {
if ("about:debug.dom".equals(urlData.mUrl)) {
current.getWebView().dumpDomTree(false);
} else if ("about:debug.dom.file".equals(urlData.mUrl)) {
current.getWebView().dumpDomTree(true);
} else if ("about:debug.render".equals(urlData.mUrl)) {
current.getWebView().dumpRenderTree(false);
} else if ("about:debug.render.file".equals(urlData.mUrl)) {
current.getWebView().dumpRenderTree(true);
} else if ("about:debug.display".equals(urlData.mUrl)) {
current.getWebView().dumpDisplayTree();
} else if (urlData.mUrl.startsWith("about:debug.drag")) {
int index = urlData.mUrl.codePointAt(16) - '0';
if (index <= 0 || index > 9) {
current.getWebView().setDragTracker(null);
} else {
current.getWebView().setDragTracker(new MeshTracker(index));
}
} else {
mSettings.toggleDebugSettings();
}
return;
}
// Get rid of the subwindow if it exists
dismissSubWindow(current);
// If the current Tab is being used as an application tab,
// remove the association, since the new Intent means that it is
// no longer associated with that application.
current.setAppId(null);
loadUrlDataIn(current, urlData);
}
}
}
private int parseUrlShortcut(String url) {
if (url == null) return SHORTCUT_INVALID;
// FIXME: quick search, need to be customized by setting
if (url.length() > 2 && url.charAt(1) == ' ') {
switch (url.charAt(0)) {
case 'g': return SHORTCUT_GOOGLE_SEARCH;
case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
case 'd': return SHORTCUT_DICTIONARY_SEARCH;
case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
}
}
return SHORTCUT_INVALID;
}
/**
* Launches the default web search activity with the query parameters if the given intent's data
* are identified as plain search terms and not URLs/shortcuts.
* @return true if the intent was handled and web search activity was launched, false if not.
*/
private boolean handleWebSearchIntent(Intent intent) {
if (intent == null) return false;
String url = null;
final String action = intent.getAction();
if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
action)) {
return false;
}
if (Intent.ACTION_VIEW.equals(action)) {
Uri data = intent.getData();
if (data != null) url = data.toString();
} else if (Intent.ACTION_SEARCH.equals(action)
|| MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
|| Intent.ACTION_WEB_SEARCH.equals(action)) {
url = intent.getStringExtra(SearchManager.QUERY);
}
return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
}
/**
* Launches the default web search activity with the query parameters if the given url string
* was identified as plain search terms and not URL/shortcut.
* @return true if the request was handled and web search activity was launched, false if not.
*/
private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
if (inUrl == null) return false;
// In general, we shouldn't modify URL from Intent.
// But currently, we get the user-typed URL from search box as well.
String url = fixUrl(inUrl).trim();
// URLs and site specific search shortcuts are handled by the regular flow of control, so
// return early.
if (Patterns.WEB_URL.matcher(url).matches()
|| ACCEPTED_URI_SCHEMA.matcher(url).matches()
|| parseUrlShortcut(url) != SHORTCUT_INVALID) {
return false;
}
final ContentResolver cr = mResolver;
final String newUrl = url;
new AsyncTask<Void, Void, Void>() {
protected Void doInBackground(Void... unused) {
Browser.updateVisitedHistory(cr, newUrl, false);
Browser.addSearchUrl(cr, newUrl);
return null;
}
}.execute();
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.putExtra(SearchManager.QUERY, url);
if (appData != null) {
intent.putExtra(SearchManager.APP_DATA, appData);
}
if (extraData != null) {
intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
}
intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
startActivity(intent);
return true;
}
private UrlData getUrlDataFromIntent(Intent intent) {
String url = "";
Map<String, String> headers = null;
if (intent != null) {
final String action = intent.getAction();
if (Intent.ACTION_VIEW.equals(action)) {
url = smartUrlFilter(intent.getData());
if (url != null && url.startsWith("content:")) {
/* Append mimetype so webview knows how to display */
String mimeType = intent.resolveType(getContentResolver());
if (mimeType != null) {
url += "?" + mimeType;
}
}
if (url != null && url.startsWith("http")) {
final Bundle pairs = intent
.getBundleExtra(Browser.EXTRA_HEADERS);
if (pairs != null && !pairs.isEmpty()) {
Iterator<String> iter = pairs.keySet().iterator();
headers = new HashMap<String, String>();
while (iter.hasNext()) {
String key = iter.next();
headers.put(key, pairs.getString(key));
}
}
}
} else if (Intent.ACTION_SEARCH.equals(action)
|| MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
|| Intent.ACTION_WEB_SEARCH.equals(action)) {
url = intent.getStringExtra(SearchManager.QUERY);
if (url != null) {
mLastEnteredUrl = url;
// In general, we shouldn't modify URL from Intent.
// But currently, we get the user-typed URL from search box as well.
url = fixUrl(url);
url = smartUrlFilter(url);
final ContentResolver cr = mResolver;
final String newUrl = url;
new AsyncTask<Void, Void, Void>() {
protected Void doInBackground(Void... unused) {
Browser.updateVisitedHistory(cr, newUrl, false);
return null;
}
}.execute();
String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
if (url.contains(searchSource)) {
String source = null;
final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
if (appData != null) {
source = appData.getString(Search.SOURCE);
}
if (TextUtils.isEmpty(source)) {
source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
}
url = url.replace(searchSource, "&source=android-"+source+"&");
}
}
}
}
return new UrlData(url, headers, intent);
}
/* package */ void showVoiceTitleBar(String title) {
mTitleBar.setInVoiceMode(true);
mTitleBar.setDisplayTitle(title);
if (!mXLargeScreenSize) {
mFakeTitleBar.setInVoiceMode(true);
mFakeTitleBar.setDisplayTitle(title);
}
}
/* package */ void revertVoiceTitleBar() {
mTitleBar.setInVoiceMode(false);
mTitleBar.setDisplayTitle(mUrl);
if (!mXLargeScreenSize) {
mFakeTitleBar.setInVoiceMode(false);
mFakeTitleBar.setDisplayTitle(mUrl);
}
}
/* package */ static String fixUrl(String inUrl) {
// FIXME: Converting the url to lower case
// duplicates functionality in smartUrlFilter().
// However, changing all current callers of fixUrl to
// call smartUrlFilter in addition may have unwanted
// consequences, and is deferred for now.
int colon = inUrl.indexOf(':');
boolean allLower = true;
for (int index = 0; index < colon; index++) {
char ch = inUrl.charAt(index);
if (!Character.isLetter(ch)) {
break;
}
allLower &= Character.isLowerCase(ch);
if (index == colon - 1 && !allLower) {
inUrl = inUrl.substring(0, colon).toLowerCase()
+ inUrl.substring(colon);
}
}
if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
return inUrl;
if (inUrl.startsWith("http:") ||
inUrl.startsWith("https:")) {
if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
inUrl = inUrl.replaceFirst("/", "//");
} else inUrl = inUrl.replaceFirst(":", "://");
}
return inUrl;
}
@Override
protected void onResume() {
super.onResume();
if (LOGV_ENABLED) {
Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
}
if (!mActivityInPause) {
Log.e(LOGTAG, "BrowserActivity is already resumed.");
return;
}
mTabControl.resumeCurrentTab();
mActivityInPause = false;
resumeWebViewTimers();
if (mWakeLock.isHeld()) {
mHandler.removeMessages(RELEASE_WAKELOCK);
mWakeLock.release();
}
registerReceiver(mNetworkStateIntentReceiver,
mNetworkStateChangedFilter);
WebView.enablePlatformNotifications();
}
/**
* Since the actual title bar is embedded in the WebView, and removing it
* would change its appearance, use a different TitleBar to show overlayed
* at the top of the screen, when the menu is open or the page is loading.
*/
private TitleBar mFakeTitleBar;
/**
* 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;
/**
* 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;
/**
* Whether or not the options menu is in its smaller, icon menu form. When
* true, we want the title bar overlay to be up. When false, we do not.
* Only meaningful if mOptionsMenuOpen is true.
*/
private boolean mIconView;
@Override
public boolean onMenuOpened(int featureId, Menu menu) {
if (Window.FEATURE_OPTIONS_PANEL == featureId) {
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 (mIconView) {
// Switching the menu to expanded view, so hide the
// title bar.
hideFakeTitleBar();
mIconView = false;
} else {
// Switching the menu back to icon view, so show the
// title bar once again.
showFakeTitleBar();
mIconView = true;
}
}
} else {
// The options menu is closed, so open it, and show the title
showFakeTitleBar();
mOptionsMenuOpen = true;
mConfigChanged = false;
mIconView = true;
}
}
return true;
}
private void showFakeTitleBar() {
if (mXLargeScreenSize) return;
if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
&& !mActivityInPause) {
WebView mainView = mTabControl.getCurrentWebView();
// if there is no current WebView, don't show the faked title bar;
if (mainView == null) {
return;
}
// Do not need to check for null, since the current tab will have
// at least a main WebView, or we would have returned above.
if (getTopWindow().getFindIsUp()) {
// Do not show the fake title bar, which would cover up the
// FindDialog.
return;
}
WindowManager manager
= (WindowManager) getSystemService(Context.WINDOW_SERVICE);
// Add the title bar to the window manager so it can receive touches
// while the menu is up
WindowManager.LayoutParams params
= new WindowManager.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_APPLICATION,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.TOP;
boolean atTop = mainView.getScrollY() == 0;
params.windowAnimations = atTop ? 0 : R.style.TitleBar;
manager.addView(mFakeTitleBar, params);
}
}
@Override
public void onOptionsMenuClosed(Menu menu) {
mOptionsMenuOpen = false;
if (!mInLoad) {
hideFakeTitleBar();
} else if (!mIconView) {
// The page is currently loading, and we are in expanded mode, so
// we were not showing the menu. Show it once again. It will be
// removed when the page finishes.
showFakeTitleBar();
}
}
private void hideFakeTitleBar() {
if (mXLargeScreenSize || mFakeTitleBar.getParent() == null) return;
WindowManager.LayoutParams params = (WindowManager.LayoutParams)
mFakeTitleBar.getLayoutParams();
WebView mainView = mTabControl.getCurrentWebView();
// Although we decided whether or not to animate based on the current
// scroll position, the scroll position may have changed since the
// fake title bar was displayed. Make sure it has the appropriate
// animation/lack thereof before removing.
params.windowAnimations = mainView != null && mainView.getScrollY() == 0
? 0 : R.style.TitleBar;
WindowManager manager
= (WindowManager) getSystemService(Context.WINDOW_SERVICE);
manager.updateViewLayout(mFakeTitleBar, params);
manager.removeView(mFakeTitleBar);
}
/**
* Special method for the fake title bar to call when displaying its context
* menu, since it is in its own Window, and its parent does not show a
* context menu.
*/
/* package */ void showTitleBarContextMenu() {
if (null == mTitleBar.getParent()) {
return;
}
openContextMenu(mTitleBar);
}
@Override
public void onContextMenuClosed(Menu menu) {
super.onContextMenuClosed(menu);
if (mInLoad) {
showFakeTitleBar();
}
}
/**
* onSaveInstanceState(Bundle map)
* onSaveInstanceState is called right before onStop(). The map contains
* the saved state.
*/
@Override
protected void onSaveInstanceState(Bundle outState) {
if (LOGV_ENABLED) {
Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
}
// the default implementation requires each view to have an id. As the
// browser handles the state itself and it doesn't use id for the views,
// don't call the default implementation. Otherwise it will trigger the
// warning like this, "couldn't save which view has focus because the
// focused view XXX has no id".
// Save all the tabs
mTabControl.saveState(outState);
}
@Override
protected void onPause() {
super.onPause();
if (mActivityInPause) {
Log.e(LOGTAG, "BrowserActivity is already paused.");
return;
}
mTabControl.pauseCurrentTab();
mActivityInPause = true;
if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
mWakeLock.acquire();
mHandler.sendMessageDelayed(mHandler
.obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
}
// FIXME: This removes the active tabs page and resets the menu to
// MAIN_MENU. A better solution might be to do this work in onNewIntent
// but then we would need to save it in onSaveInstanceState and restore
// it in onCreate/onRestoreInstanceState
if (mActiveTabsPage != null) {
removeActiveTabPage(true);
}
cancelStopToast();
// unregister network state listener
unregisterReceiver(mNetworkStateIntentReceiver);
WebView.disablePlatformNotifications();
}
@Override
protected void onDestroy() {
if (LOGV_ENABLED) {
Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
}
super.onDestroy();
if (mUploadMessage != null) {
mUploadMessage.onReceiveValue(null);
mUploadMessage = null;
}
if (mTabControl == null) return;
// Remove the fake title bar if it is there
hideFakeTitleBar();
// Remove the current tab and sub window
Tab t = mTabControl.getCurrentTab();
if (t != null) {
dismissSubWindow(t);
removeTabFromContentView(t);
}
// Destroy all the tabs
mTabControl.destroy();
WebIconDatabase.getInstance().close();
unregisterReceiver(mPackageInstallationReceiver);
// Stop watching the default geolocation permissions
mSystemAllowGeolocationOrigins.stop();
mSystemAllowGeolocationOrigins = null;
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
mConfigChanged = true;
super.onConfigurationChanged(newConfig);
if (mPageInfoDialog != null) {
mPageInfoDialog.dismiss();
showPageInfo(
mPageInfoView,
mPageInfoFromShowSSLCertificateOnError);
}
if (mSSLCertificateDialog != null) {
mSSLCertificateDialog.dismiss();
showSSLCertificate(
mSSLCertificateView);
}
if (mSSLCertificateOnErrorDialog != null) {
mSSLCertificateOnErrorDialog.dismiss();
showSSLCertificateOnError(
mSSLCertificateOnErrorView,
mSSLCertificateOnErrorHandler,
mSSLCertificateOnErrorError);
}
if (mHttpAuthenticationDialog != null) {
String title = ((TextView) mHttpAuthenticationDialog
.findViewById(com.android.internal.R.id.alertTitle)).getText()
.toString();
String name = ((TextView) mHttpAuthenticationDialog
.findViewById(R.id.username_edit)).getText().toString();
String password = ((TextView) mHttpAuthenticationDialog
.findViewById(R.id.password_edit)).getText().toString();
int focusId = mHttpAuthenticationDialog.getCurrentFocus()
.getId();
mHttpAuthenticationDialog.dismiss();
showHttpAuthentication(mHttpAuthHandler, null, null, title,
name, password, focusId);
}
}
@Override
public void onLowMemory() {
super.onLowMemory();
mTabControl.freeMemory();
}
private void resumeWebViewTimers() {
Tab tab = mTabControl.getCurrentTab();
if (tab == null) return; // monkey can trigger this
boolean inLoad = tab.inLoad();
if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
CookieSyncManager.getInstance().startSync();
WebView w = tab.getWebView();
if (w != null) {
w.resumeTimers();
}
}
}
private boolean pauseWebViewTimers() {
Tab tab = mTabControl.getCurrentTab();
boolean inLoad = tab.inLoad();
if (mActivityInPause && !inLoad) {
CookieSyncManager.getInstance().stopSync();
WebView w = mTabControl.getCurrentWebView();
if (w != null) {
w.pauseTimers();
}
return true;
} else {
return false;
}
}
// Open the icon database and retain all the icons for visited sites.
private void retainIconsOnStartup() {
final WebIconDatabase db = WebIconDatabase.getInstance();
db.open(getDir("icons", 0).getPath());
Cursor c = null;
try {
c = Browser.getAllBookmarks(mResolver);
if (c.moveToFirst()) {
int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
do {
String url = c.getString(urlIndex);
db.retainIconForPageUrl(url);
} while (c.moveToNext());
}
} catch (IllegalStateException e) {
Log.e(LOGTAG, "retainIconsOnStartup", e);
} finally {
if (c!= null) c.close();
}
}
// Helper method for getting the top window.
WebView getTopWindow() {
return mTabControl.getCurrentTopWebView();
}
TabControl getTabControl() {
return mTabControl;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.browser, menu);
mMenu = menu;
updateInLoadMenuItems();
return true;
}
/**
* 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() {
if (mMenu == null) {
return;
}
MenuItem src = mInLoad ?
mMenu.findItem(R.id.stop_menu_id):
mMenu.findItem(R.id.reload_menu_id);
MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
dest.setIcon(src.getIcon());
dest.setTitle(src.getTitle());
}
@Override
public boolean onContextItemSelected(MenuItem item) {
// chording is not an issue with context menus, but we use the same
// options selector, so set mCanChord to true so we can access them.
mCanChord = true;
int id = item.getItemId();
boolean result = true;
switch (id) {
// For the context menu from the title bar
case R.id.title_bar_copy_page_url:
Tab currentTab = mTabControl.getCurrentTab();
if (null == currentTab) {
result = false;
break;
}
WebView mainView = currentTab.getWebView();
if (null == mainView) {
result = false;
break;
}
copy(mainView.getUrl());
break;
// -- Browser context menu
case R.id.open_context_menu_id:
case R.id.bookmark_context_menu_id:
case R.id.save_link_context_menu_id:
case R.id.share_link_context_menu_id:
case R.id.copy_link_context_menu_id:
final WebView webView = getTopWindow();
if (null == webView) {
result = false;
break;
}
final HashMap hrefMap = new HashMap();
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);
}
mCanChord = false;
return result;
}
private Bundle createGoogleSearchSourceBundle(String source) {
Bundle bundle = new Bundle();
bundle.putString(Search.SOURCE, source);
return bundle;
}
/* package */ void editUrl() {
if (mOptionsMenuOpen) closeOptionsMenu();
String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
null, false);
}
/**
* Overriding this to insert a local information bundle
*/
@Override
public void startSearch(String initialQuery, boolean selectInitialQuery,
Bundle appSearchData, boolean globalSearch) {
if (appSearchData == null) {
appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
}
super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
}
/**
* Switch tabs. Called by the TitleBarSet when sliding the title bar
* results in changing tabs.
* @param index Index of the tab to change to, as defined by
* mTabControl.getTabIndex(Tab t).
* @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.
*/
/* package */ boolean switchToTab(int index) {
Tab tab = mTabControl.getTab(index);
Tab currentTab = mTabControl.getCurrentTab();
if (tab == null || tab == currentTab) {
return false;
}
if (currentTab != null) {
// currentTab may be null if it was just removed. In that case,
// we do not need to remove it
removeTabFromContentView(currentTab);
}
mTabControl.setCurrentTab(tab);
attachTabToContentView(tab);
resetTitleIconAndProgress();
updateLockIconToLatest();
return true;
}
/* package */ Tab openTabToHomePage() {
return openTabAndShow(mSettings.getHomePage(), false, null);
}
/* package */ void closeCurrentWindow() {
final Tab current = mTabControl.getCurrentTab();
if (mTabControl.getTabCount() == 1) {
// This is the last tab. Open a new one, with the home
// page and close the current one.
openTabToHomePage();
closeTab(current);
return;
}
final Tab parent = current.getParentTab();
int indexToShow = -1;
if (parent != null) {
indexToShow = mTabControl.getTabIndex(parent);
} else {
final int currentIndex = mTabControl.getCurrentIndex();
// Try to move to the tab to the right
indexToShow = currentIndex + 1;
if (indexToShow > mTabControl.getTabCount() - 1) {
// Try to move to the tab to the left
indexToShow = currentIndex - 1;
}
}
if (switchToTab(indexToShow)) {
// Close window
closeTab(current);
}
}
private ActiveTabsPage mActiveTabsPage;
/**
* Remove the active tabs page.
* @param needToAttach If true, the active tabs page did not attach a tab
* to the content view, so we need to do that here.
*/
/* package */ void removeActiveTabPage(boolean needToAttach) {
mContentView.removeView(mActiveTabsPage);
mTitleBar.setVisibility(View.VISIBLE);
mActiveTabsPage = null;
mMenuState = R.id.MAIN_MENU;
if (needToAttach) {
attachTabToContentView(mTabControl.getCurrentTab());
}
getTopWindow().requestFocus();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (!mCanChord) {
// The user has already fired a shortcut with this hold down of the
// menu key.
return false;
}
if (null == getTopWindow()) {
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;
}
switch (item.getItemId()) {
// -- Main menu
case R.id.new_tab_menu_id:
openTabToHomePage();
break;
case R.id.goto_menu_id:
editUrl();
break;
case R.id.bookmarks_menu_id:
bookmarksOrHistoryPicker(false);
break;
case R.id.active_tabs_menu_id:
mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
removeTabFromContentView(mTabControl.getCurrentTab());
mTitleBar.setVisibility(View.GONE);
hideFakeTitleBar();
mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
mActiveTabsPage.requestFocus();
mMenuState = EMPTY_MENU;
break;
case R.id.add_bookmark_menu_id:
Intent i = new Intent(BrowserActivity.this,
AddBookmarkPage.class);
WebView w = getTopWindow();
i.putExtra("url", w.getUrl());
i.putExtra("title", w.getTitle());
i.putExtra("touch_icon_url", w.getTouchIconUrl());
i.putExtra("thumbnail", createScreenshot(w));
startActivity(i);
break;
case R.id.stop_reload_menu_id:
if (mInLoad) {
stopLoading();
} else {
getTopWindow().reload();
}
break;
case R.id.back_menu_id:
getTopWindow().goBack();
break;
case R.id.forward_menu_id:
getTopWindow().goForward();
break;
case R.id.close_menu_id:
// Close the subwindow if it exists.
if (mTabControl.getCurrentSubWindow() != null) {
dismissSubWindow(mTabControl.getCurrentTab());
break;
}
closeCurrentWindow();
break;
case R.id.homepage_menu_id:
Tab current = mTabControl.getCurrentTab();
if (current != null) {
dismissSubWindow(current);
loadUrl(current.getWebView(), mSettings.getHomePage());
}
break;
case R.id.preferences_menu_id:
Intent intent = new Intent(this,
BrowserPreferencesPage.class);
intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
getTopWindow().getUrl());
startActivityForResult(intent, PREFERENCES_PAGE);
break;
case R.id.find_menu_id:
if (null == mFindDialog) {
mFindDialog = new FindDialog(this);
}
// Need to do something special for Tablet
Tab tab = mTabControl.getCurrentTab();
if (tab.getSubWebView() == null) {
// If the Find is being performed on the main webview,
// remove the embedded title bar.
WebView mainView = tab.getWebView();
if (mainView != null) {
mainView.setEmbeddedTitleBar(null);
}
}
hideFakeTitleBar();
tab.showFind(mFindDialog);
mMenuState = EMPTY_MENU;
break;
case R.id.select_text_id:
getTopWindow().emulateShiftHeld();
break;
case R.id.page_info_menu_id:
showPageInfo(mTabControl.getCurrentTab(), false);
break;
case R.id.classic_history_menu_id:
bookmarksOrHistoryPicker(true);
break;
case R.id.title_bar_share_page_url:
case R.id.share_page_menu_id:
Tab currentTab = mTabControl.getCurrentTab();
if (null == currentTab) {
mCanChord = false;
return false;
}
currentTab.populatePickerData();
sharePage(this, currentTab.getTitle(),
currentTab.getUrl(), currentTab.getFavicon(),
createScreenshot(currentTab.getWebView()));
break;
case R.id.dump_nav_menu_id:
getTopWindow().debugDump();
break;
case R.id.dump_counters_menu_id:
getTopWindow().dumpV8Counters();
break;
case R.id.zoom_in_menu_id:
getTopWindow().zoomIn();
break;
case R.id.zoom_out_menu_id:
getTopWindow().zoomOut();
break;
case R.id.view_downloads_menu_id:
viewDownloads(null);
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(id);
}
break;
}
}
}
break;
default:
if (!super.onOptionsItemSelected(item)) {
return false;
}
// Otherwise fall through.
}
mCanChord = false;
return true;
}
/*
* Remove the FindDialog.
*/
public void closeFind() {
Tab currentTab = mTabControl.getCurrentTab();
if (mFindDialog != null) {
currentTab.closeFind(mFindDialog);
mFindDialog.dismiss();
}
if (!mXLargeScreenSize) {
// If the Find was being performed in the main WebView, replace the
// embedded title bar.
if (currentTab.getSubWebView() == null) {
WebView mainView = currentTab.getWebView();
if (mainView != null) {
mainView.setEmbeddedTitleBar(mTitleBar);
}
}
}
mMenuState = R.id.MAIN_MENU;
if (mInLoad) {
// The title bar was hidden, because otherwise it would cover up the
// find dialog. Now that the dialog has been removed, show the fake
// title bar once again.
showFakeTitleBar();
}
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
// This happens when the user begins to hold down the menu key, so
// allow them to chord to get a shortcut.
mCanChord = true;
// 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.
super.onPrepareOptionsMenu(menu);
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);
}
final WebView w = getTopWindow();
boolean canGoBack = false;
boolean canGoForward = false;
boolean isHome = false;
if (w != null) {
canGoBack = w.canGoBack();
canGoForward = w.canGoForward();
isHome = mSettings.getHomePage().equals(w.getUrl());
}
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);
menu.findItem(R.id.forward_menu_id)
.setEnabled(canGoForward);
menu.findItem(R.id.new_tab_menu_id).setEnabled(
mTabControl.canCreateNewTab());
// decide whether to show the share link option
PackageManager pm = 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.isNavDump();
final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
nav.setVisible(isNavDump);
nav.setEnabled(isNavDump);
boolean showDebugSettings = mSettings.showDebugSettings();
final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
counter.setVisible(showDebugSettings);
counter.setEnabled(showDebugSettings);
break;
}
mCurrentMenuState = mMenuState;
return true;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
if (v instanceof TitleBar) {
return;
}
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 = getMenuInflater();
inflater.inflate(R.menu.browsercontext, menu);
// Show the correct menu group
final String extra = result.getExtra();
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);
// 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:
TextView titleView = (TextView) LayoutInflater.from(this)
.inflate(android.R.layout.browser_link_context_header,
null);
titleView.setText(extra);
menu.setHeaderView(titleView);
// 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.setVisible(showNewTab);
if (showNewTab) {
newTabItem.setOnMenuItemClickListener(
new MenuItem.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
final Tab parent = mTabControl.getCurrentTab();
final Tab newTab = openTab(extra);
if (newTab != parent) {
parent.addChildTab(newTab);
}
return true;
}
});
}
menu.findItem(R.id.bookmark_context_menu_id).setVisible(
Bookmarks.urlHasAcceptableScheme(extra));
PackageManager pm = 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_link_context_menu_id).setVisible(ri != null);
if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
break;
}
// otherwise fall through to handle image part
case WebView.HitTestResult.IMAGE_TYPE:
if (type == WebView.HitTestResult.IMAGE_TYPE) {
menu.setHeaderTitle(extra);
}
menu.findItem(R.id.view_image_context_menu_id).setIntent(
new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
menu.findItem(R.id.download_context_menu_id).
setOnMenuItemClickListener(new Download(extra));
menu.findItem(R.id.set_wallpaper_context_menu_id).
setOnMenuItemClickListener(new SetAsWallpaper(extra));
break;
default:
Log.w(LOGTAG, "We should not get here.");
break;
}
hideFakeTitleBar();
}
// Attach the given tab to the content view.
// this should only be called for the current tab.
private void attachTabToContentView(Tab t) {
// Attach the container that contains the main WebView and any other UI
// associated with the tab.
t.attachTabToContentView(mContentView);
if (mShouldShowErrorConsole) {
ErrorConsoleView errorConsole = t.getErrorConsole(true);
if (errorConsole.numberOfErrors() == 0) {
errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
} else {
errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
}
mErrorConsoleContainer.addView(errorConsole,
new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
}
if (!mXLargeScreenSize){
WebView view = t.getWebView();
view.setEmbeddedTitleBar(mTitleBar);
}
if (t.isInVoiceSearchMode()) {
showVoiceTitleBar(t.getVoiceDisplayTitle());
} else {
revertVoiceTitleBar();
}
// Request focus on the top window.
t.getTopWindow().requestFocus();
}
// Attach a sub window to the main WebView of the given tab.
void attachSubWindow(Tab t) {
t.attachSubWindow(mContentView);
getTopWindow().requestFocus();
}
// Remove the given tab from the content view.
private void removeTabFromContentView(Tab t) {
// Remove the container that contains the main WebView.
t.removeTabFromContentView(mContentView);
ErrorConsoleView errorConsole = t.getErrorConsole(false);
if (errorConsole != null) {
mErrorConsoleContainer.removeView(errorConsole);
}
if (!mXLargeScreenSize) {
WebView view = t.getWebView();
if (view != null) {
view.setEmbeddedTitleBar(null);
}
}
}
// Remove the sub window if it exists. Also called by TabControl when the
// user clicks the 'X' to dismiss a sub window.
/* package */ void dismissSubWindow(Tab t) {
t.removeSubWindow(mContentView);
// dismiss the subwindow. This will destroy the WebView.
t.dismissSubWindow();
getTopWindow().requestFocus();
}
// A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
// that accepts url as string.
private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
return openTabAndShow(new UrlData(url), closeOnExit, appId);
}
// This method does a ton of stuff. It will attempt to create a new tab
// if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
// url isn't null, it will load the given url.
/* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
String appId) {
final Tab currentTab = mTabControl.getCurrentTab();
if (mTabControl.canCreateNewTab()) {
final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
urlData.mUrl);
WebView webview = tab.getWebView();
// If the last tab was removed from the active tabs page, currentTab
// will be null.
if (currentTab != null) {
removeTabFromContentView(currentTab);
}
// We must set the new tab as the current tab to reflect the old
// animation behavior.
mTabControl.setCurrentTab(tab);
attachTabToContentView(tab);
if (!urlData.isEmpty()) {
loadUrlDataIn(tab, urlData);
}
return tab;
} else {
// Get rid of the subwindow if it exists
dismissSubWindow(currentTab);
if (!urlData.isEmpty()) {
// Load the given url.
loadUrlDataIn(currentTab, urlData);
}
return currentTab;
}
}
private Tab openTab(String url) {
if (mSettings.openInBackground()) {
Tab t = mTabControl.createNewTab();
if (t != null) {
WebView view = t.getWebView();
loadUrl(view, url);
}
return t;
} else {
return openTabAndShow(url, false, null);
}
}
private class Copy implements OnMenuItemClickListener {
private CharSequence mText;
public boolean onMenuItemClick(MenuItem item) {
copy(mText);
return true;
}
public Copy(CharSequence toCopy) {
mText = toCopy;
}
}
private class Download implements OnMenuItemClickListener {
private String mText;
public boolean onMenuItemClick(MenuItem item) {
onDownloadStartNoStream(mText, null, null, null, -1);
return true;
}
public Download(String toDownload) {
mText = toDownload;
}
}
private class SetAsWallpaper extends Thread implements
OnMenuItemClickListener, DialogInterface.OnCancelListener {
private URL mUrl;
private ProgressDialog mWallpaperProgress;
private boolean mCanceled = false;
public SetAsWallpaper(String url) {
try {
mUrl = new URL(url);
} catch (MalformedURLException e) {
mUrl = null;
}
}
public void onCancel(DialogInterface dialog) {
mCanceled = true;
}
public boolean onMenuItemClick(MenuItem item) {
if (mUrl != null) {
// The user may have tried to set a image with a large file size as their
// background so it may take a few moments to perform the operation. Display
// a progress spinner while it is working.
mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
mWallpaperProgress.setIndeterminate(true);
mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
mWallpaperProgress.setCancelable(true);
mWallpaperProgress.setOnCancelListener(this);
mWallpaperProgress.show();
start();
}
return true;
}
public void run() {
Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
try {
// TODO: This will cause the resource to be downloaded again, when we
// should in most cases be able to grab it from the cache. To fix this
// we should query WebCore to see if we can access a cached version and
// instead open an input stream on that. This pattern could also be used
// in the download manager where the same problem exists.
InputStream inputstream = mUrl.openStream();
if (inputstream != null) {
setWallpaper(inputstream);
}
} catch (IOException e) {
Log.e(LOGTAG, "Unable to set new wallpaper");
// Act as though the user canceled the operation so we try to
// restore the old wallpaper.
mCanceled = true;
}
if (mCanceled) {
// Restore the old wallpaper if the user cancelled whilst we were setting
// the new wallpaper.
int width = oldWallpaper.getIntrinsicWidth();
int height = oldWallpaper.getIntrinsicHeight();
Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bm);
oldWallpaper.setBounds(0, 0, width, height);
oldWallpaper.draw(canvas);
try {
setWallpaper(bm);
} catch (IOException e) {
Log.e(LOGTAG, "Unable to restore old wallpaper.");
}
mCanceled = false;
}
if (mWallpaperProgress.isShowing()) {
mWallpaperProgress.dismiss();
}
}
}
private void copy(CharSequence text) {
try {
IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
if (clip != null) {
clip.setClipboardText(text);
}
} catch (android.os.RemoteException e) {
Log.e(LOGTAG, "Copy failed", e);
}
}
/**
* Resets the browser title-view to whatever it must be
* (for example, if we had a loading error)
* When we have a new page, we call resetTitle, when we
* have to reset the titlebar to whatever it used to be
* (for example, if the user chose to stop loading), we
* call resetTitleAndRevertLockIcon.
*/
/* package */ void resetTitleAndRevertLockIcon() {
mTabControl.getCurrentTab().revertLockIcon();
updateLockIconToLatest();
resetTitleIconAndProgress();
}
/**
* Reset the title, favicon, and progress.
*/
private void resetTitleIconAndProgress() {
WebView current = mTabControl.getCurrentWebView();
if (current == null) {
return;
}
resetTitleAndIcon(current);
int progress = current.getProgress();
current.getWebChromeClient().onProgressChanged(current, progress);
}
// Reset the title and the icon based on the given item.
private void resetTitleAndIcon(WebView view) {
WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
if (item != null) {
setUrlTitle(item.getUrl(), item.getTitle());
setFavicon(item.getFavicon());
} else {
setUrlTitle(null, null);
setFavicon(null);
}
}
/**
* Sets a title composed of the URL and the title string.
* @param url The URL of the site being loaded.
* @param title The title of the site being loaded.
*/
void setUrlTitle(String url, String title) {
mUrl = url;
mTitle = title;
// If we are in voice search mode, the title has already been set.
if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
mTitleBar.setDisplayTitle(url);
if (!mXLargeScreenSize) {
mFakeTitleBar.setDisplayTitle(url);
}
}
/**
* @param url The URL to build a title version of the URL from.
* @return The title version of the URL or null if fails.
* The title version of the URL can be either the URL hostname,
* or the hostname with an "https://" prefix (for secure URLs),
* or an empty string if, for example, the URL in question is a
* file:// URL with no hostname.
*/
/* package */ static String buildTitleUrl(String url) {
String titleUrl = null;
if (url != null) {
try {
// parse the url string
URL urlObj = new URL(url);
if (urlObj != null) {
titleUrl = "";
String protocol = urlObj.getProtocol();
String host = urlObj.getHost();
if (host != null && 0 < host.length()) {
titleUrl = host;
if (protocol != null) {
// if a secure site, add an "https://" prefix!
if (protocol.equalsIgnoreCase("https")) {
titleUrl = protocol + "://" + host;
}
}
}
}
} catch (MalformedURLException e) {}
}
return titleUrl;
}
// Set the favicon in the title bar.
void setFavicon(Bitmap icon) {
mTitleBar.setFavicon(icon);
if (!mXLargeScreenSize) {
mFakeTitleBar.setFavicon(icon);
}
}
/**
* Close the tab, remove its associated title bar, and adjust mTabControl's
* current tab to a valid value.
*/
/* package */ void closeTab(Tab t) {
int currentIndex = mTabControl.getCurrentIndex();
int removeIndex = mTabControl.getTabIndex(t);
mTabControl.removeTab(t);
if (currentIndex >= removeIndex && currentIndex != 0) {
currentIndex--;
}
mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
resetTitleIconAndProgress();
}
/* package */ 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().
*/
moveTaskToBack(true);
return;
}
WebView w = current.getWebView();
if (w.canGoBack()) {
w.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.getParentTab();
if (parent != null) {
switchToTab(mTabControl.getTabIndex(parent));
// Now we close the other tab
closeTab(current);
} else {
if (current.closeOnExit()) {
// force the tab's inLoad() to be false as we are going to
// either finish the activity or remove the tab. This will
// ensure pauseWebViewTimers() taking action.
mTabControl.getCurrentTab().clearInLoad();
if (mTabControl.getTabCount() == 1) {
finish();
return;
}
// call pauseWebViewTimers() now, we won't be able to call
// it in onPause() as the WebView won't be valid.
// Temporarily change mActivityInPause to be true as
// pauseWebViewTimers() will do nothing if mActivityInPause
// is false.
boolean savedState = mActivityInPause;
if (savedState) {
Log.e(LOGTAG, "BrowserActivity is already paused "
+ "while handing goBackOnePageOrQuit.");
}
mActivityInPause = true;
pauseWebViewTimers();
mActivityInPause = savedState;
removeTabFromContentView(current);
mTabControl.removeTab(current);
}
/*
* 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().
*/
moveTaskToBack(true);
}
}
}
boolean isMenuDown() {
return mMenuIsDown;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Even if MENU is already held down, we need to call to super to open
// the IME on long press.
if (KeyEvent.KEYCODE_MENU == keyCode) {
mMenuIsDown = true;
return super.onKeyDown(keyCode, event);
}
// The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
// still down, we don't want to trigger the search. Pretend to consume
// the key and do nothing.
if (mMenuIsDown) return true;
switch(keyCode) {
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 (event.isShiftPressed()) {
getTopWindow().pageUp(false);
} else {
getTopWindow().pageDown(false);
}
return true;
case KeyEvent.KEYCODE_BACK:
if (event.getRepeatCount() == 0) {
event.startTracking();
return true;
} else if (mCustomView == null && mActiveTabsPage == null
&& event.isLongPress()) {
bookmarksOrHistoryPicker(true);
return true;
}
break;
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch(keyCode) {
case KeyEvent.KEYCODE_MENU:
mMenuIsDown = false;
break;
case KeyEvent.KEYCODE_BACK:
if (event.isTracking() && !event.isCanceled()) {
if (mCustomView != null) {
// if a custom view is showing, hide it
mTabControl.getCurrentWebView().getWebChromeClient()
.onHideCustomView();
} else if (mActiveTabsPage != null) {
// if tab page is showing, hide it
removeActiveTabPage(true);
} else {
WebView subwindow = mTabControl.getCurrentSubWindow();
if (subwindow != null) {
if (subwindow.canGoBack()) {
subwindow.goBack();
} else {
dismissSubWindow(mTabControl.getCurrentTab());
}
} else {
goBackOnePageOrQuit();
}
}
return true;
}
break;
}
return super.onKeyUp(keyCode, event);
}
/* package */ void stopLoading() {
mDidStopLoad = true;
resetTitleAndRevertLockIcon();
WebView w = getTopWindow();
w.stopLoading();
// FIXME: before refactor, it is using mWebViewClient. So I keep the
// same logic here. But for subwindow case, should we call into the main
// WebView's onPageFinished as we never call its onPageStarted and if
// the page finishes itself, we don't call onPageFinished.
mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
w.getUrl());
cancelStopToast();
mStopToast = Toast
.makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
mStopToast.show();
}
boolean didUserStopLoading() {
return mDidStopLoad;
}
private void cancelStopToast() {
if (mStopToast != null) {
mStopToast.cancel();
mStopToast = null;
}
}
// called by a UI or non-UI thread to post the message
public void postMessage(int what, int arg1, int arg2, Object obj,
long delayMillis) {
mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
obj), delayMillis);
}
// called by a UI or non-UI thread to remove the message
void removeMessages(int what, Object object) {
mHandler.removeMessages(what, object);
}
// 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 handler for handling javascript and saving passwords
private Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case FOCUS_NODE_HREF:
{
String url = (String) msg.getData().get("url");
String title = (String) msg.getData().get("title");
if (url == null || url.length() == 0) {
break;
}
HashMap focusNodeMap = (HashMap) msg.obj;
WebView view = (WebView) focusNodeMap.get("webview");
// Only apply the action if the top window did not change.
if (getTopWindow() != view) {
break;
}
switch (msg.arg1) {
case R.id.open_context_menu_id:
case R.id.view_image_context_menu_id:
loadUrlFromContext(getTopWindow(), url);
break;
case R.id.bookmark_context_menu_id:
Intent intent = new Intent(BrowserActivity.this,
AddBookmarkPage.class);
intent.putExtra("url", url);
intent.putExtra("title", title);
startActivity(intent);
break;
case R.id.share_link_context_menu_id:
sharePage(BrowserActivity.this, title, url, null,
null);
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:
onDownloadStartNoStream(url, null, null, null, -1);
break;
}
break;
}
case LOAD_URL:
loadUrlFromContext(getTopWindow(), (String) msg.obj);
break;
case STOP_LOAD:
stopLoading();
break;
case RELEASE_WAKELOCK:
if (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:
WebView view = (WebView) msg.obj;
if (view != null) {
updateScreenshot(view);
}
break;
}
}
};
/**
* 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}
*/
public 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 updateScreenshot(WebView view) {
// If this is a bookmarked site, add a screenshot to the database.
// FIXME: When should we update? Every time?
// FIXME: Would like to make sure there is actually something to
// draw, but the API for that (WebViewCore.pictureReady()) is not
// currently accessible here.
final Bitmap bm = createScreenshot(view);
if (bm == null) {
return;
}
final ContentResolver cr = getContentResolver();
final String url = view.getUrl();
final String originalUrl = view.getOriginalUrl();
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... unused) {
Cursor c = null;
try {
c = BrowserBookmarksAdapter.queryBookmarksForUrl(
cr, originalUrl, url, true);
if (c != null) {
if (c.moveToFirst()) {
ContentValues values = new ContentValues();
final ByteArrayOutputStream os
= new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, os);
values.put(Browser.BookmarkColumns.THUMBNAIL,
os.toByteArray());
do {
cr.update(ContentUris.withAppendedId(
Browser.BOOKMARKS_URI, c.getInt(0)),
values, null, null);
} while (c.moveToNext());
}
}
} catch (IllegalStateException e) {
// Ignore
} finally {
if (c != null) c.close();
}
return null;
}
}.execute();
}
/**
* Values for the size of the thumbnail created when taking a screenshot.
* Lazily initialized. Instead of using these directly, use
* getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
*/
private static int THUMBNAIL_WIDTH = 0;
private static int THUMBNAIL_HEIGHT = 0;
/**
* 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 int desired width for thumbnail screenshot.
*/
/* package */ static int getDesiredThumbnailWidth(Context context) {
if (THUMBNAIL_WIDTH == 0) {
float density = context.getResources().getDisplayMetrics().density;
THUMBNAIL_WIDTH = (int) (90 * density);
THUMBNAIL_HEIGHT = (int) (80 * density);
}
return THUMBNAIL_WIDTH;
}
/**
* 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 int desired height for thumbnail screenshot.
*/
/* package */ static int getDesiredThumbnailHeight(Context context) {
// To ensure that they are both initialized.
getDesiredThumbnailWidth(context);
return THUMBNAIL_HEIGHT;
}
private Bitmap createScreenshot(WebView view) {
Picture thumbnail = view.capturePicture();
if (thumbnail == null) {
return null;
}
Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
getDesiredThumbnailHeight(this), Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bm);
// May need to tweak these values to determine what is the
// best scale factor
int thumbnailWidth = thumbnail.getWidth();
int thumbnailHeight = thumbnail.getHeight();
float scaleFactorX = 1.0f;
float scaleFactorY = 1.0f;
if (thumbnailWidth > 0) {
scaleFactorX = (float) getDesiredThumbnailWidth(this) /
(float)thumbnailWidth;
} else {
return null;
}
if (view.getWidth() > view.getHeight() &&
thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
// If the device is in landscape and the page is shorter
// than the height of the view, stretch the thumbnail to fill the
// space.
scaleFactorY = (float) getDesiredThumbnailHeight(this) /
(float)thumbnailHeight;
} else {
// In the portrait case, this looks nice.
scaleFactorY = scaleFactorX;
}
canvas.scale(scaleFactorX, scaleFactorY);
thumbnail.draw(canvas);
return bm;
}
// -------------------------------------------------------------------------
// Helper function for WebViewClient.
//-------------------------------------------------------------------------
// Use in overrideUrlLoading
/* package */ final static String SCHEME_WTAI = "wtai://wp/";
/* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
/* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
/* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
// Keep this initial progress in sync with initialProgressValue (* 100)
// in ProgressTracker.cpp
private final static int INITIAL_PROGRESS = 10;
void onPageStarted(WebView view, String url, Bitmap favicon) {
// 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 (mActivityInPause) resumeWebViewTimers();
resetLockIcon(url);
setUrlTitle(url, null);
setFavicon(favicon);
// Show some progress so that the user knows the page is beginning to
// load
onProgressChanged(view, INITIAL_PROGRESS);
mDidStopLoad = false;
if (!mIsNetworkUp) createAndShowNetworkDialog();
if (view.getFindIsUp()) {
closeFind();
}
if (mSettings.isTracing()) {
String host;
try {
WebAddress uri = new WebAddress(url);
host = uri.mHost;
} catch (android.net.ParseException ex) {
host = "browser";
}
host = host.replace('.', '_');
host += ".trace";
mInTrace = true;
Debug.startMethodTracing(host, 20 * 1024 * 1024);
}
// Performance probe
if (false) {
mStart = SystemClock.uptimeMillis();
mProcessStart = Process.getElapsedCpuTime();
long[] sysCpu = new long[7];
if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
sysCpu, null)) {
mUserStart = sysCpu[0] + sysCpu[1];
mSystemStart = sysCpu[2];
mIdleStart = sysCpu[3];
mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
}
mUiStart = SystemClock.currentThreadTimeMillis();
}
}
void onPageFinished(WebView view, String url) {
// Reset the title and icon in case we stopped a provisional load.
resetTitleAndIcon(view);
// Update the lock icon image only once we are done loading
updateLockIconToLatest();
// pause the WebView timer and release the wake lock if it is finished
// while BrowserActivity is in pause state.
if (mActivityInPause && pauseWebViewTimers()) {
if (mWakeLock.isHeld()) {
mHandler.removeMessages(RELEASE_WAKELOCK);
mWakeLock.release();
}
}
// Performance probe
if (false) {
long[] sysCpu = new long[7];
if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
sysCpu, null)) {
String uiInfo = "UI thread used "
+ (SystemClock.currentThreadTimeMillis() - mUiStart)
+ " ms";
if (LOGD_ENABLED) {
Log.d(LOGTAG, uiInfo);
}
//The string that gets written to the log
String performanceString = "It took total "
+ (SystemClock.uptimeMillis() - mStart)
+ " ms clock time to load the page."
+ "\nbrowser process used "
+ (Process.getElapsedCpuTime() - mProcessStart)
+ " ms, user processes used "
+ (sysCpu[0] + sysCpu[1] - mUserStart) * 10
+ " ms, kernel used "
+ (sysCpu[2] - mSystemStart) * 10
+ " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
+ " ms and irq took "
+ (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
* 10 + " ms, " + uiInfo;
if (LOGD_ENABLED) {
Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
}
if (url != null) {
// strip the url to maintain consistency
String newUrl = new String(url);
if (newUrl.startsWith("http://www.")) {
newUrl = newUrl.substring(11);
} else if (newUrl.startsWith("http://")) {
newUrl = newUrl.substring(7);
} else if (newUrl.startsWith("https://www.")) {
newUrl = newUrl.substring(12);
} else if (newUrl.startsWith("https://")) {
newUrl = newUrl.substring(8);
}
if (LOGD_ENABLED) {
Log.d(LOGTAG, newUrl + " loaded");
}
}
}
}
if (mInTrace) {
mInTrace = false;
Debug.stopMethodTracing();
}
}
boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith(SCHEME_WTAI)) {
// wtai://wp/mc;number
// number=string(phone-number)
if (url.startsWith(SCHEME_WTAI_MC)) {
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse(WebView.SCHEME_TEL +
url.substring(SCHEME_WTAI_MC.length())));
startActivity(intent);
return true;
}
// wtai://wp/sd;dtmf
// dtmf=string(dialstring)
if (url.startsWith(SCHEME_WTAI_SD)) {
// TODO: only send when there is active voice connection
return false;
}
// wtai://wp/ap;number;name
// number=string(phone-number)
// name=string
if (url.startsWith(SCHEME_WTAI_AP)) {
// TODO
return false;
}
}
// The "about:" schemes are internal to the browser; don't want these to
// be dispatched to other apps.
if (url.startsWith("about:")) {
return false;
}
Intent intent;
// perform generic parsing of the URI to turn it into an Intent.
try {
intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
} catch (URISyntaxException ex) {
Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
return false;
}
// check whether the intent can be resolved. If not, we will see
// whether we can download it from the Market.
if (getPackageManager().resolveActivity(intent, 0) == null) {
String packagename = intent.getPackage();
if (packagename != null) {
intent = new Intent(Intent.ACTION_VIEW, Uri
.parse("market://search?q=pname:" + packagename));
intent.addCategory(Intent.CATEGORY_BROWSABLE);
startActivity(intent);
return true;
} else {
return false;
}
}
// sanitize the Intent, ensuring web pages can not bypass browser
// security (only access to BROWSABLE activities).
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.setComponent(null);
try {
if (startActivityIfNeeded(intent, -1)) {
return true;
}
} catch (ActivityNotFoundException ex) {
// ignore the error. If no application can handle the URL,
// eg about:blank, assume the browser can handle it.
}
if (mMenuIsDown) {
openTab(url);
closeOptionsMenu();
return true;
}
return false;
}
// -------------------------------------------------------------------------
// Helper function for WebChromeClient
// -------------------------------------------------------------------------
void onProgressChanged(WebView view, int newProgress) {
if (mXLargeScreenSize) {
mTitleBar.setProgress(newProgress);
} else {
// On the phone, the fake title bar will always cover up the
// regular title bar (or the regular one is offscreen), so only the
// fake title bar needs to change its progress
mFakeTitleBar.setProgress(newProgress);
}
if (newProgress == 100) {
// 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 (mInLoad) {
mInLoad = false;
updateInLoadMenuItems();
// If the options menu is open, leave the title bar
if (!mOptionsMenuOpen || !mIconView) {
hideFakeTitleBar();
}
}
} else {
if (!mInLoad) {
// onPageFinished may have already been called but a subframe is
// still loading and updating the progress. Reset mInLoad and
// update the menu items.
mInLoad = true;
updateInLoadMenuItems();
}
// When the page first begins to load, the Activity may still be
// paused, in which case showFakeTitleBar will do nothing. Call
// again as the page continues to load so that it will be shown.
// (Calling it will the fake title bar is already showing will also
// do nothing.
if (!mOptionsMenuOpen || mIconView) {
// This page has begun to load, so show the title bar
showFakeTitleBar();
}
}
}
void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
// if a view already exists then immediately terminate the new one
if (mCustomView != null) {
callback.onCustomViewHidden();
return;
}
// Add the custom view to its container.
mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
mCustomView = view;
mCustomViewCallback = callback;
// Save the menu state and set it to empty while the custom
// view is showing.
mOldMenuState = mMenuState;
mMenuState = EMPTY_MENU;
// Hide the content view.
mContentView.setVisibility(View.GONE);
// Finally show the custom view container.
setStatusBarVisibility(false);
mCustomViewContainer.setVisibility(View.VISIBLE);
mCustomViewContainer.bringToFront();
}
void onHideCustomView() {
if (mCustomView == null)
return;
// Hide the custom view.
mCustomView.setVisibility(View.GONE);
// Remove the custom view from its container.
mCustomViewContainer.removeView(mCustomView);
mCustomView = null;
// Reset the old menu state.
mMenuState = mOldMenuState;
mOldMenuState = EMPTY_MENU;
mCustomViewContainer.setVisibility(View.GONE);
mCustomViewCallback.onCustomViewHidden();
// Show the content view.
setStatusBarVisibility(true);
mContentView.setVisibility(View.VISIBLE);
}
Bitmap getDefaultVideoPoster() {
if (mDefaultVideoPoster == null) {
mDefaultVideoPoster = BitmapFactory.decodeResource(
getResources(), R.drawable.default_video_poster);
}
return mDefaultVideoPoster;
}
View getVideoLoadingProgressView() {
if (mVideoProgressView == null) {
LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
mVideoProgressView = inflater.inflate(
R.layout.video_loading_progress, null);
}
return mVideoProgressView;
}
/*
* The Object used to inform the WebView of the file to upload.
*/
private ValueCallback<Uri> mUploadMessage;
private String mCameraFilePath;
void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
final String imageMimeType = "image/*";
final String imageSourceKey = "source";
final String imageSourceValueCamera = "camera";
final String imageSourceValueGallery = "gallery";
// image source can be 'gallery' or 'camera'.
String imageSource = "";
// We add the camera intent if there was no accept type (or '*/*') or 'image/*'.
boolean addCameraIntent = true;
if (mUploadMessage != null) return;
mUploadMessage = uploadMsg;
// Parse the accept type.
String params[] = acceptType.split(";");
String mimeType = params[0];
for (String p : params) {
String[] keyValue = p.split("=");
if (keyValue.length == 2) {
// Process key=value parameters.
if (imageSourceKey.equals(keyValue[0])) {
imageSource = keyValue[1];
}
}
}
// This intent will display the standard OPENABLE file picker.
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
// Create an intent to add to the standard file picker that will
// capture an image from the camera. We'll combine this intent with
// the standard OPENABLE picker unless the web developer specifically
// requested the camera or gallery be opened by passing a parameter
// in the accept type.
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File externalDataDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM);
File cameraDataDir = new File(externalDataDir.getAbsolutePath() +
File.separator + "browser-photos");
cameraDataDir.mkdirs();
mCameraFilePath = cameraDataDir.getAbsolutePath() + File.separator +
System.currentTimeMillis() + ".jpg";
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mCameraFilePath)));
if (mimeType.equals(imageMimeType)) {
i.setType(imageMimeType);
if (imageSource.equals(imageSourceValueCamera)) {
// Specified 'image/*' and requested the camera, so go ahead and launch the camera
// directly.
BrowserActivity.this.startActivityForResult(cameraIntent, FILE_SELECTED);
return;
} else if (imageSource.equals(imageSourceValueGallery)) {
// Specified gallery as the source, so don't want to consider the camera.
addCameraIntent = false;
}
} else {
i.setType("*/*");
}
// Combine the chooser and the extra choices (like camera)
Intent chooser = new Intent(Intent.ACTION_CHOOSER);
chooser.putExtra(Intent.EXTRA_INTENT, i);
if (addCameraIntent) {
// Add the camera Intent
Intent[] choices = new Intent[1];
choices[0] = cameraIntent;
chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, choices);
}
chooser.putExtra(Intent.EXTRA_TITLE, getString(R.string.choose_upload));
BrowserActivity.this.startActivityForResult(chooser, FILE_SELECTED);
}
// -------------------------------------------------------------------------
// Implement functions for DownloadListener
// -------------------------------------------------------------------------
/**
* Notify the host application a download should be done, or that
* the data should be streamed if a streaming viewer is available.
* @param url The full url to the content that should be downloaded
* @param contentDisposition Content-disposition http header, if
* present.
* @param mimetype The mimetype of the content reported by the server
* @param contentLength The file size reported by the server
*/
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype, long contentLength) {
// if we're dealing wih A/V content that's not explicitly marked
// for download, check if it's streamable.
if (contentDisposition == null
|| !contentDisposition.regionMatches(
true, 0, "attachment", 0, 10)) {
// query the package manager to see if there's a registered handler
// that matches.
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(url), mimetype);
ResolveInfo info = getPackageManager().resolveActivity(intent,
PackageManager.MATCH_DEFAULT_ONLY);
if (info != null) {
ComponentName myName = getComponentName();
// If we resolved to ourselves, we don't want to attempt to
// load the url only to try and download it again.
if (!myName.getPackageName().equals(
info.activityInfo.packageName)
|| !myName.getClassName().equals(
info.activityInfo.name)) {
// someone (other than us) knows how to handle this mime
// type with this scheme, don't download.
try {
startActivity(intent);
return;
} catch (ActivityNotFoundException ex) {
if (LOGD_ENABLED) {
Log.d(LOGTAG, "activity not found for " + mimetype
+ " over " + Uri.parse(url).getScheme(),
ex);
}
// Best behavior is to fall back to a download in this
// case
}
}
}
}
onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
}
// This is to work around the fact that java.net.URI throws Exceptions
// instead of just encoding URL's properly
// Helper method for onDownloadStartNoStream
private static String encodePath(String path) {
char[] chars = path.toCharArray();
boolean needed = false;
for (char c : chars) {
if (c == '[' || c == ']') {
needed = true;
break;
}
}
if (needed == false) {
return path;
}
StringBuilder sb = new StringBuilder("");
for (char c : chars) {
if (c == '[' || c == ']') {
sb.append('%');
sb.append(Integer.toHexString(c));
} else {
sb.append(c);
}
}
return sb.toString();
}
/**
* Notify the host application a download should be done, even if there
* is a streaming viewer available for thise type.
* @param url The full url to the content that should be downloaded
* @param contentDisposition Content-disposition http header, if
* present.
* @param mimetype The mimetype of the content reported by the server
* @param contentLength The file size reported by the server
*/
/*package */ void onDownloadStartNoStream(String url, String userAgent,
String contentDisposition, String mimetype, long contentLength) {
String filename = URLUtil.guessFileName(url,
contentDisposition, mimetype);
// Check to see if we have an SDCard
String status = Environment.getExternalStorageState();
if (!status.equals(Environment.MEDIA_MOUNTED)) {
int title;
String msg;
// Check to see if the SDCard is busy, same as the music app
if (status.equals(Environment.MEDIA_SHARED)) {
msg = getString(R.string.download_sdcard_busy_dlg_msg);
title = R.string.download_sdcard_busy_dlg_title;
} else {
msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
title = R.string.download_no_sdcard_dlg_title;
}
new AlertDialog.Builder(this)
.setTitle(title)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(msg)
.setPositiveButton(R.string.ok, null)
.show();
return;
}
// java.net.URI is a lot stricter than KURL so we have to encode some
// extra characters. Fix for b 2538060 and b 1634719
WebAddress webAddress;
try {
webAddress = new WebAddress(url);
webAddress.mPath = encodePath(webAddress.mPath);
} catch (Exception e) {
// This only happens for very bad urls, we want to chatch the
// exception here
Log.e(LOGTAG, "Exception trying to parse url:" + url);
return;
}
// XXX: Have to use the old url since the cookies were stored using the
// old percent-encoded url.
String cookies = CookieManager.getInstance().getCookie(url);
ContentValues values = new ContentValues();
values.put(Downloads.Impl.COLUMN_URI, webAddress.toString());
values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
getPackageName());
values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
OpenDownloadReceiver.class.getCanonicalName());
values.put(Downloads.Impl.COLUMN_VISIBILITY,
Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
values.put(Downloads.Impl.COLUMN_DESCRIPTION, webAddress.mHost);
if (contentLength > 0) {
values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
}
if (mimetype == null) {
// We must have long pressed on a link or image to download it. We
// are not sure of the mimetype in this case, so do a head request
new FetchUrlMimeType(this).execute(values);
} else {
final Uri contentUri =
getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
}
Toast.makeText(this, R.string.download_pending, Toast.LENGTH_SHORT)
.show();
}
// -------------------------------------------------------------------------
/**
* Resets the lock icon. This method is called when we start a new load and
* know the url to be loaded.
*/
private void resetLockIcon(String url) {
// Save the lock-icon state (we revert to it if the load gets cancelled)
mTabControl.getCurrentTab().resetLockIcon(url);
updateLockIconImage(LOCK_ICON_UNSECURE);
}
/**
* Update the lock icon to correspond to our latest state.
*/
private void updateLockIconToLatest() {
updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
}
/**
* Updates the lock-icon image in the title-bar.
*/
private void updateLockIconImage(int lockIconType) {
Drawable d = null;
if (lockIconType == LOCK_ICON_SECURE) {
d = mSecLockIcon;
} else if (lockIconType == LOCK_ICON_MIXED) {
d = mMixLockIcon;
}
mTitleBar.setLock(d);
if (!mXLargeScreenSize) {
mFakeTitleBar.setLock(d);
}
}
/**
* Displays a page-info dialog.
* @param tab The tab to show info about
* @param fromShowSSLCertificateOnError The flag that indicates whether
* this dialog was opened from the SSL-certificate-on-error dialog or
* not. This is important, since we need to know whether to return to
* the parent dialog or simply dismiss.
*/
private void showPageInfo(final Tab tab,
final boolean fromShowSSLCertificateOnError) {
final LayoutInflater factory = LayoutInflater
.from(this);
final View pageInfoView = factory.inflate(R.layout.page_info, null);
final WebView view = tab.getWebView();
String url = null;
String title = null;
if (view == null) {
url = tab.getUrl();
title = tab.getTitle();
} else if (view == mTabControl.getCurrentWebView()) {
// Use the cached title and url if this is the current WebView
url = mUrl;
title = mTitle;
} else {
url = view.getUrl();
title = view.getTitle();
}
if (url == null) {
url = "";
}
if (title == null) {
title = "";
}
((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
mPageInfoView = tab;
mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
AlertDialog.Builder alertDialogBuilder =
new AlertDialog.Builder(this)
.setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
.setView(pageInfoView)
.setPositiveButton(
R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
mPageInfoDialog = null;
mPageInfoView = null;
// if we came here from the SSL error dialog
if (fromShowSSLCertificateOnError) {
// go back to the SSL error dialog
showSSLCertificateOnError(
mSSLCertificateOnErrorView,
mSSLCertificateOnErrorHandler,
mSSLCertificateOnErrorError);
}
}
})
.setOnCancelListener(
new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
mPageInfoDialog = null;
mPageInfoView = null;
// if we came here from the SSL error dialog
if (fromShowSSLCertificateOnError) {
// go back to the SSL error dialog
showSSLCertificateOnError(
mSSLCertificateOnErrorView,
mSSLCertificateOnErrorHandler,
mSSLCertificateOnErrorError);
}
}
});
// if we have a main top-level page SSL certificate set or a certificate
// error
if (fromShowSSLCertificateOnError ||
(view != null && view.getCertificate() != null)) {
// add a 'View Certificate' button
alertDialogBuilder.setNeutralButton(
R.string.view_certificate,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
mPageInfoDialog = null;
mPageInfoView = null;
// if we came here from the SSL error dialog
if (fromShowSSLCertificateOnError) {
// go back to the SSL error dialog
showSSLCertificateOnError(
mSSLCertificateOnErrorView,
mSSLCertificateOnErrorHandler,
mSSLCertificateOnErrorError);
} else {
// otherwise, display the top-most certificate from
// the chain
if (view.getCertificate() != null) {
showSSLCertificate(tab);
}
}
}
});
}
mPageInfoDialog = alertDialogBuilder.show();
}
/**
* Displays the main top-level page SSL certificate dialog
* (accessible from the Page-Info dialog).
* @param tab The tab to show certificate for.
*/
private void showSSLCertificate(final Tab tab) {
final View certificateView =
inflateCertificateView(tab.getWebView().getCertificate());
if (certificateView == null) {
return;
}
LayoutInflater factory = LayoutInflater.from(this);
final LinearLayout placeholder =
(LinearLayout)certificateView.findViewById(R.id.placeholder);
LinearLayout ll = (LinearLayout) factory.inflate(
R.layout.ssl_success, placeholder);
((TextView)ll.findViewById(R.id.success))
.setText(R.string.ssl_certificate_is_valid);
mSSLCertificateView = tab;
mSSLCertificateDialog =
new AlertDialog.Builder(this)
.setTitle(R.string.ssl_certificate).setIcon(
R.drawable.ic_dialog_browser_certificate_secure)
.setView(certificateView)
.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
mSSLCertificateDialog = null;
mSSLCertificateView = null;
showPageInfo(tab, false);
}
})
.setOnCancelListener(
new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
mSSLCertificateDialog = null;
mSSLCertificateView = null;
showPageInfo(tab, false);
}
})
.show();
}
/**
* Displays the SSL error certificate dialog.
* @param view The target web-view.
* @param handler The SSL error handler responsible for cancelling the
* connection that resulted in an SSL error or proceeding per user request.
* @param error The SSL error object.
*/
void showSSLCertificateOnError(
final WebView view, final SslErrorHandler handler, final SslError error) {
final View certificateView =
inflateCertificateView(error.getCertificate());
if (certificateView == null) {
return;
}
LayoutInflater factory = LayoutInflater.from(this);
final LinearLayout placeholder =
(LinearLayout)certificateView.findViewById(R.id.placeholder);
if (error.hasError(SslError.SSL_UNTRUSTED)) {
LinearLayout ll = (LinearLayout)factory
.inflate(R.layout.ssl_warning, placeholder);
((TextView)ll.findViewById(R.id.warning))
.setText(R.string.ssl_untrusted);
}
if (error.hasError(SslError.SSL_IDMISMATCH)) {
LinearLayout ll = (LinearLayout)factory
.inflate(R.layout.ssl_warning, placeholder);
((TextView)ll.findViewById(R.id.warning))
.setText(R.string.ssl_mismatch);
}
if (error.hasError(SslError.SSL_EXPIRED)) {
LinearLayout ll = (LinearLayout)factory
.inflate(R.layout.ssl_warning, placeholder);
((TextView)ll.findViewById(R.id.warning))
.setText(R.string.ssl_expired);
}
if (error.hasError(SslError.SSL_NOTYETVALID)) {
LinearLayout ll = (LinearLayout)factory
.inflate(R.layout.ssl_warning, placeholder);
((TextView)ll.findViewById(R.id.warning))
.setText(R.string.ssl_not_yet_valid);
}
mSSLCertificateOnErrorHandler = handler;
mSSLCertificateOnErrorView = view;
mSSLCertificateOnErrorError = error;
mSSLCertificateOnErrorDialog =
new AlertDialog.Builder(this)
.setTitle(R.string.ssl_certificate).setIcon(
R.drawable.ic_dialog_browser_certificate_partially_secure)
.setView(certificateView)
.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
mSSLCertificateOnErrorDialog = null;
mSSLCertificateOnErrorView = null;
mSSLCertificateOnErrorHandler = null;
mSSLCertificateOnErrorError = null;
view.getWebViewClient().onReceivedSslError(
view, handler, error);
}
})
.setNeutralButton(R.string.page_info_view,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
mSSLCertificateOnErrorDialog = null;
// do not clear the dialog state: we will
// need to show the dialog again once the
// user is done exploring the page-info details
showPageInfo(mTabControl.getTabFromView(view),
true);
}
})
.setOnCancelListener(
new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
mSSLCertificateOnErrorDialog = null;
mSSLCertificateOnErrorView = null;
mSSLCertificateOnErrorHandler = null;
mSSLCertificateOnErrorError = null;
view.getWebViewClient().onReceivedSslError(
view, handler, error);
}
})
.show();
}
/**
* Inflates the SSL certificate view (helper method).
* @param certificate The SSL certificate.
* @return The resultant certificate view with issued-to, issued-by,
* issued-on, expires-on, and possibly other fields set.
* If the input certificate is null, returns null.
*/
private View inflateCertificateView(SslCertificate certificate) {
if (certificate == null) {
return null;
}
LayoutInflater factory = LayoutInflater.from(this);
View certificateView = factory.inflate(
R.layout.ssl_certificate, null);
// issued to:
SslCertificate.DName issuedTo = certificate.getIssuedTo();
if (issuedTo != null) {
((TextView) certificateView.findViewById(R.id.to_common))
.setText(issuedTo.getCName());
((TextView) certificateView.findViewById(R.id.to_org))
.setText(issuedTo.getOName());
((TextView) certificateView.findViewById(R.id.to_org_unit))
.setText(issuedTo.getUName());
}
// issued by:
SslCertificate.DName issuedBy = certificate.getIssuedBy();
if (issuedBy != null) {
((TextView) certificateView.findViewById(R.id.by_common))
.setText(issuedBy.getCName());
((TextView) certificateView.findViewById(R.id.by_org))
.setText(issuedBy.getOName());
((TextView) certificateView.findViewById(R.id.by_org_unit))
.setText(issuedBy.getUName());
}
// issued on:
String issuedOn = formatCertificateDate(
certificate.getValidNotBeforeDate());
((TextView) certificateView.findViewById(R.id.issued_on))
.setText(issuedOn);
// expires on:
String expiresOn = formatCertificateDate(
certificate.getValidNotAfterDate());
((TextView) certificateView.findViewById(R.id.expires_on))
.setText(expiresOn);
return certificateView;
}
/**
* Formats the certificate date to a properly localized date string.
* @return Properly localized version of the certificate date string and
* the "" if it fails to localize.
*/
private String formatCertificateDate(Date certificateDate) {
if (certificateDate == null) {
return "";
}
String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
if (formattedDate == null) {
return "";
}
return formattedDate;
}
/**
* Displays an http-authentication dialog.
*/
void showHttpAuthentication(final HttpAuthHandler handler,
final String host, final String realm, final String title,
final String name, final String password, int focusId) {
LayoutInflater factory = LayoutInflater.from(this);
final View v = factory
.inflate(R.layout.http_authentication, null);
if (name != null) {
((EditText) v.findViewById(R.id.username_edit)).setText(name);
}
if (password != null) {
((EditText) v.findViewById(R.id.password_edit)).setText(password);
}
String titleText = title;
if (titleText == null) {
titleText = getText(R.string.sign_in_to).toString().replace(
"%s1", host).replace("%s2", realm);
}
mHttpAuthHandler = handler;
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle(titleText)
.setIcon(android.R.drawable.ic_dialog_alert)
.setView(v)
.setPositiveButton(R.string.action,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
String nm = ((EditText) v
.findViewById(R.id.username_edit))
.getText().toString();
String pw = ((EditText) v
.findViewById(R.id.password_edit))
.getText().toString();
BrowserActivity.this.setHttpAuthUsernamePassword
(host, realm, nm, pw);
handler.proceed(nm, pw);
mHttpAuthenticationDialog = null;
mHttpAuthHandler = null;
}})
.setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
handler.cancel();
BrowserActivity.this.resetTitleAndRevertLockIcon();
mHttpAuthenticationDialog = null;
mHttpAuthHandler = null;
}})
.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
handler.cancel();
BrowserActivity.this.resetTitleAndRevertLockIcon();
mHttpAuthenticationDialog = null;
mHttpAuthHandler = null;
}})
.create();
// Make the IME appear when the dialog is displayed if applicable.
dialog.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
dialog.show();
if (focusId != 0) {
dialog.findViewById(focusId).requestFocus();
} else {
v.findViewById(R.id.username_edit).requestFocus();
}
mHttpAuthenticationDialog = dialog;
}
public int getProgress() {
WebView w = mTabControl.getCurrentWebView();
if (w != null) {
return w.getProgress();
} else {
return 100;
}
}
/**
* Set HTTP authentication password.
*
* @param host The host for the password
* @param realm The realm for the password
* @param username The username for the password. If it is null, it means
* password can't be saved.
* @param password The password
*/
public void setHttpAuthUsernamePassword(String host, String realm,
String username,
String password) {
WebView w = getTopWindow();
if (w != null) {
w.setHttpAuthUsernamePassword(host, realm, username, password);
}
}
/**
* connectivity manager says net has come or gone... inform the user
* @param up true if net has come up, false if net has gone down
*/
public void onNetworkToggle(boolean up) {
if (up == mIsNetworkUp) {
return;
} else if (up) {
mIsNetworkUp = true;
if (mAlertDialog != null) {
mAlertDialog.cancel();
mAlertDialog = null;
}
} else {
mIsNetworkUp = false;
if (mInLoad) {
createAndShowNetworkDialog();
}
}
WebView w = mTabControl.getCurrentWebView();
if (w != null) {
w.setNetworkAvailable(up);
}
}
boolean isNetworkUp() {
return mIsNetworkUp;
}
// This method shows the network dialog alerting the user that the net is
// down. It will only show the dialog if mAlertDialog is null.
private void createAndShowNetworkDialog() {
if (mAlertDialog == null) {
mAlertDialog = new AlertDialog.Builder(this)
.setTitle(R.string.loadSuspendedTitle)
.setMessage(R.string.loadSuspended)
.setPositiveButton(R.string.ok, null)
.show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
if (getTopWindow() == null) return;
switch (requestCode) {
case COMBO_PAGE:
if (resultCode == RESULT_OK && intent != null) {
String data = intent.getAction();
Bundle extras = intent.getExtras();
if (extras != null && extras.getBoolean("new_window", false)) {
openTab(data);
} else {
final Tab currentTab =
mTabControl.getCurrentTab();
dismissSubWindow(currentTab);
if (data != null && data.length() != 0) {
loadUrl(getTopWindow(), data);
}
}
}
// Deliberately fall through to PREFERENCES_PAGE, since the
// same extra may be attached to the COMBO_PAGE
case PREFERENCES_PAGE:
if (resultCode == RESULT_OK && intent != null) {
String action = intent.getStringExtra(Intent.EXTRA_TEXT);
if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
mTabControl.removeParentChildRelationShips();
}
}
break;
// Choose a file from the file picker.
case FILE_SELECTED:
if (null == mUploadMessage) break;
Uri result = intent == null || resultCode != RESULT_OK ? null
: intent.getData();
// As we ask the camera to save the result of the user taking
// a picture, the camera application does not return anything other
// than RESULT_OK. So we need to check whether the file we expected
// was written to disk in the in the case that we
// did not get an intent returned but did get a RESULT_OK. If it was,
// we assume that this result has came back from the camera.
if (result == null && intent == null && resultCode == RESULT_OK) {
File cameraFile = new File(mCameraFilePath);
if (cameraFile.exists()) {
result = Uri.fromFile(cameraFile);
}
}
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
mCameraFilePath = null;
break;
default:
break;
}
getTopWindow().requestFocus();
}
/*
* 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.
*/
private void viewDownloads(Uri downloadRecord) {
Intent intent = new Intent(this,
BrowserDownloadPage.class);
intent.setData(downloadRecord);
startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
}
/**
* Open the Go page.
* @param startWithHistory If true, open starting on the history tab.
* Otherwise, start with the bookmarks tab.
*/
/* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
WebView current = mTabControl.getCurrentWebView();
if (current == null) {
return;
}
Intent intent = new Intent(this,
CombinedBookmarkHistoryActivity.class);
String title = current.getTitle();
String url = current.getUrl();
Bitmap thumbnail = createScreenshot(current);
// Just in case the user opens bookmarks before a page finishes loading
// so the current history item, and therefore the page, is null.
if (null == url) {
url = mLastEnteredUrl;
// This can happen.
if (null == url) {
url = mSettings.getHomePage();
}
}
// In case the web page has not yet received its associated title.
if (title == null) {
title = url;
}
intent.putExtra("title", title);
intent.putExtra("url", url);
intent.putExtra("thumbnail", thumbnail);
// Disable opening in a new window if we have maxed out the windows
intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
intent.putExtra("touch_icon_url", current.getTouchIconUrl());
if (startWithHistory) {
intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
CombinedBookmarkHistoryActivity.HISTORY_TAB);
}
startActivityForResult(intent, COMBO_PAGE);
}
// Called when loading from context menu or LOAD_URL message
private void loadUrlFromContext(WebView view, String url) {
// In case the user enters nothing.
if (url != null && url.length() != 0 && view != null) {
url = smartUrlFilter(url);
if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
loadUrl(view, 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.
*/
private void loadUrl(WebView view, String url) {
updateTitleBarForNewLoad(view, url);
view.loadUrl(url);
}
/**
* 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.
*/
private void loadUrlDataIn(Tab t, UrlData data) {
updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
data.loadIn(t);
}
/**
* If the WebView is the top window, update the title bar to reflect
* loading the new URL. i.e. set its text, clear the favicon (which
* will be set once the page begins loading), and set the progress to
* INITIAL_PROGRESS to show that the page has begun to load. Called
* by loadUrl and loadUrlDataIn.
* @param view The WebView that is starting a load.
* @param url The URL that is being loaded.
*/
private void updateTitleBarForNewLoad(WebView view, String url) {
if (view == getTopWindow()) {
setUrlTitle(url, null);
setFavicon(null);
onProgressChanged(view, INITIAL_PROGRESS);
}
}
private String smartUrlFilter(Uri inUri) {
if (inUri != null) {
return smartUrlFilter(inUri.toString());
}
return null;
}
protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
"(?i)" + // switch on case insensitive matching
"(" + // begin group for schema
"(?:http|https|file):\\/\\/" +
"|(?:inline|data|about|content|javascript):" +
")" +
"(.*)" );
/**
* Attempts to determine whether user input is a URL or search
* terms. Anything with a space is passed to search.
*
* Converts to lowercase any mistakenly uppercased schema (i.e.,
* "Http://" converts to "http://"
*
* @return Original or modified URL
*
*/
String smartUrlFilter(String url) {
String inUrl = url.trim();
boolean hasSpace = inUrl.indexOf(' ') != -1;
Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
if (matcher.matches()) {
// force scheme to lowercase
String scheme = matcher.group(1);
String lcScheme = scheme.toLowerCase();
if (!lcScheme.equals(scheme)) {
inUrl = lcScheme + matcher.group(2);
}
if (hasSpace) {
inUrl = inUrl.replace(" ", "%20");
}
return inUrl;
}
if (hasSpace) {
// FIXME: Is this the correct place to add to searches?
// what if someone else calls this function?
int shortcut = parseUrlShortcut(inUrl);
if (shortcut != SHORTCUT_INVALID) {
Browser.addSearchUrl(mResolver, inUrl);
String query = inUrl.substring(2);
switch (shortcut) {
case SHORTCUT_GOOGLE_SEARCH:
return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
case SHORTCUT_WIKIPEDIA_SEARCH:
return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
case SHORTCUT_DICTIONARY_SEARCH:
return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
// FIXME: we need location in this case
return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
}
}
} else {
if (Patterns.WEB_URL.matcher(inUrl).matches()) {
return URLUtil.guessUrl(inUrl);
}
}
Browser.addSearchUrl(mResolver, inUrl);
return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
}
/* package */ void setShouldShowErrorConsole(boolean flag) {
if (flag == mShouldShowErrorConsole) {
// Nothing to do.
return;
}
mShouldShowErrorConsole = flag;
ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
.getErrorConsole(true);
if (flag) {
// Setting the show state of the console will cause it's the layout to be inflated.
if (errorConsole.numberOfErrors() > 0) {
errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
} else {
errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
}
// Now we can add it to the main view.
mErrorConsoleContainer.addView(errorConsole,
new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
} else {
mErrorConsoleContainer.removeView(errorConsole);
}
}
boolean shouldShowErrorConsole() {
return mShouldShowErrorConsole;
}
private void setStatusBarVisibility(boolean visible) {
int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
private void sendNetworkType(String type, String subtype) {
WebView w = mTabControl.getCurrentWebView();
if (w != null) {
w.setNetworkType(type, subtype);
}
}
private void packageChanged(String packageName, boolean wasAdded) {
WebView w = mTabControl.getCurrentWebView();
if (w == null) {
return;
}
if (wasAdded) {
w.addPackageName(packageName);
} else {
w.removePackageName(packageName);
}
}
private void addPackageNames(Set<String> packageNames) {
WebView w = mTabControl.getCurrentWebView();
if (w == null) {
return;
}
w.addPackageNames(packageNames);
}
private void getInstalledPackages() {
AsyncTask<Void, Void, Set<String> > task =
new AsyncTask<Void, Void, Set<String> >() {
protected Set<String> doInBackground(Void... unused) {
Set<String> installedPackages = new HashSet<String>();
PackageManager pm = BrowserActivity.this.getPackageManager();
if (pm != null) {
List<PackageInfo> packages = pm.getInstalledPackages(0);
for (PackageInfo p : packages) {
if (BrowserActivity.this.sGoogleApps.contains(p.packageName)) {
installedPackages.add(p.packageName);
}
}
}
return installedPackages;
}
// Executes on the UI thread
protected void onPostExecute(Set<String> installedPackages) {
addPackageNames(installedPackages);
}
};
task.execute();
}
final static int LOCK_ICON_UNSECURE = 0;
final static int LOCK_ICON_SECURE = 1;
final static int LOCK_ICON_MIXED = 2;
private BrowserSettings mSettings;
private TabControl mTabControl;
private ContentResolver mResolver;
private FrameLayout mContentView;
private View mCustomView;
private FrameLayout mCustomViewContainer;
private WebChromeClient.CustomViewCallback mCustomViewCallback;
// 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 static final int EMPTY_MENU = -1;
private Menu mMenu;
private FindDialog mFindDialog;
// Used to prevent chording to result in firing two shortcuts immediately
// one after another. Fixes bug 1211714.
boolean mCanChord;
private boolean mInLoad;
private boolean mIsNetworkUp;
private boolean mDidStopLoad;
/* package */ boolean mActivityInPause = true;
private boolean mMenuIsDown;
private static boolean mInTrace;
// Performance probe
private static final int[] SYSTEM_CPU_FORMAT = new int[] {
Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
};
private long mStart;
private long mProcessStart;
private long mUserStart;
private long mSystemStart;
private long mIdleStart;
private long mIrqStart;
private long mUiStart;
private Drawable mMixLockIcon;
private Drawable mSecLockIcon;
/* hold a ref so we can auto-cancel if necessary */
private AlertDialog mAlertDialog;
// The up-to-date URL and title (these can be different from those stored
// in WebView, since it takes some time for the information in WebView to
// get updated)
private String mUrl;
private String mTitle;
// As PageInfo has different style for landscape / portrait, we have
// to re-open it when configuration changed
private AlertDialog mPageInfoDialog;
private Tab mPageInfoView;
// If the Page-Info dialog is launched from the SSL-certificate-on-error
// dialog, we should not just dismiss it, but should get back to the
// SSL-certificate-on-error dialog. This flag is used to store this state
private boolean mPageInfoFromShowSSLCertificateOnError;
// as SSLCertificateOnError has different style for landscape / portrait,
// we have to re-open it when configuration changed
private AlertDialog mSSLCertificateOnErrorDialog;
private WebView mSSLCertificateOnErrorView;
private SslErrorHandler mSSLCertificateOnErrorHandler;
private SslError mSSLCertificateOnErrorError;
// as SSLCertificate has different style for landscape / portrait, we
// have to re-open it when configuration changed
private AlertDialog mSSLCertificateDialog;
private Tab mSSLCertificateView;
// as HttpAuthentication has different style for landscape / portrait, we
// have to re-open it when configuration changed
private AlertDialog mHttpAuthenticationDialog;
private HttpAuthHandler mHttpAuthHandler;
/*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
/*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT,
Gravity.CENTER);
// Google search
final static String QuickSearch_G = "http://www.google.com/m?q=%s";
// Wikipedia search
final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
// Dictionary search
final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
// Google Mobile Local search
final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
final static String QUERY_PLACE_HOLDER = "%s";
// "source" parameter for Google search through search key
final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
// "source" parameter for Google search through goto menu
final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
// "source" parameter for Google search through simplily type
final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
// "source" parameter for Google search suggested by the browser
final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
// "source" parameter for Google search from unknown source
final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
private final static String LOGTAG = "browser";
private String mLastEnteredUrl;
private PowerManager.WakeLock mWakeLock;
private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
private Toast mStopToast;
private TitleBar mTitleBar;
private LinearLayout mErrorConsoleContainer = null;
private boolean mShouldShowErrorConsole = false;
// 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 };
// monitor platform changes
private IntentFilter mNetworkStateChangedFilter;
private BroadcastReceiver mNetworkStateIntentReceiver;
private BroadcastReceiver mPackageInstallationReceiver;
private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
// activity requestCode
final static int COMBO_PAGE = 1;
final static int DOWNLOAD_PAGE = 2;
final static int PREFERENCES_PAGE = 3;
final static int FILE_SELECTED = 4;
// the default <video> poster
private Bitmap mDefaultVideoPoster;
// the video progress view
private View mVideoProgressView;
// The Google packages we monitor for the navigator.isApplicationInstalled()
// API. Add as needed.
private static Set<String> sGoogleApps;
static {
sGoogleApps = new HashSet<String>();
sGoogleApps.add("com.google.android.youtube");
}
/**
* A UrlData class to abstract how the content will be set to WebView.
* This base class uses loadUrl to show the content.
*/
/* package */ static class UrlData {
final String mUrl;
final Map<String, String> mHeaders;
final Intent mVoiceIntent;
UrlData(String url) {
this.mUrl = url;
this.mHeaders = null;
this.mVoiceIntent = null;
}
UrlData(String url, Map<String, String> headers, Intent intent) {
this.mUrl = url;
this.mHeaders = headers;
if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
.equals(intent.getAction())) {
this.mVoiceIntent = intent;
} else {
this.mVoiceIntent = null;
}
}
boolean isEmpty() {
return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
}
/**
* Load this UrlData into the given Tab. Use loadUrlDataIn to update
* the title bar as well.
*/
public void loadIn(Tab t) {
if (mVoiceIntent != null) {
t.activateVoiceSearchMode(mVoiceIntent);
} else {
t.getWebView().loadUrl(mUrl, mHeaders);
}
}
};
/* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
}
| true | true | public void onCreate(Bundle icicle) {
if (LOGV_ENABLED) {
Log.v(LOGTAG, this + " onStart");
}
super.onCreate(icicle);
// test the browser in OpenGL
// requestWindowFeature(Window.FEATURE_OPENGL);
// enable this to test the browser in 32bit
if (false) {
getWindow().setFormat(PixelFormat.RGBX_8888);
BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
}
if (AccessibilityManager.getInstance(this).isEnabled()) {
setDefaultKeyMode(DEFAULT_KEYS_DISABLE);
} else {
setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
}
mResolver = getContentResolver();
// If this was a web search request, pass it on to the default web
// search provider and finish this activity.
if (handleWebSearchIntent(getIntent())) {
finish();
return;
}
mSecLockIcon = Resources.getSystem().getDrawable(
android.R.drawable.ic_secure);
mMixLockIcon = Resources.getSystem().getDrawable(
android.R.drawable.ic_partial_secure);
FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
.findViewById(com.android.internal.R.id.content);
mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
.inflate(R.layout.custom_screen, null);
mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
R.id.main_content);
mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
.findViewById(R.id.error_console);
mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
.findViewById(R.id.fullscreen_custom_content);
frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
mTitleBar = new TitleBar(this);
mXLargeScreenSize = (getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK)
== Configuration.SCREENLAYOUT_SIZE_XLARGE;
if (mXLargeScreenSize) {
LinearLayout layout = (LinearLayout) mBrowserFrameLayout.
findViewById(R.id.vertical_layout);
layout.addView(mTitleBar, 0, new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
} else {
// mTitleBar will be always be shown in the fully loaded mode on
// phone
mTitleBar.setProgress(100);
// Fake title bar is not needed in xlarge layout
mFakeTitleBar = new TitleBar(this);
}
// Create the tab control and our initial tab
mTabControl = new TabControl(this);
// Open the icon database and retain all the bookmark urls for favicons
retainIconsOnStartup();
// Keep a settings instance handy.
mSettings = BrowserSettings.getInstance();
mSettings.setTabControl(mTabControl);
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
// Find out if the network is currently up.
ConnectivityManager cm = (ConnectivityManager) getSystemService(
Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null) {
mIsNetworkUp = info.isAvailable();
}
/* enables registration for changes in network status from
http stack */
mNetworkStateChangedFilter = new IntentFilter();
mNetworkStateChangedFilter.addAction(
ConnectivityManager.CONNECTIVITY_ACTION);
mNetworkStateIntentReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(
ConnectivityManager.CONNECTIVITY_ACTION)) {
NetworkInfo info = intent.getParcelableExtra(
ConnectivityManager.EXTRA_NETWORK_INFO);
String typeName = info.getTypeName();
String subtypeName = info.getSubtypeName();
sendNetworkType(typeName.toLowerCase(),
(subtypeName != null ? subtypeName.toLowerCase() : ""));
onNetworkToggle(info.isAvailable());
}
}
};
IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
filter.addDataScheme("package");
mPackageInstallationReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
final String packageName = intent.getData()
.getSchemeSpecificPart();
final boolean replacing = intent.getBooleanExtra(
Intent.EXTRA_REPLACING, false);
if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
// if it is replacing, refreshPlugins() when adding
return;
}
if (sGoogleApps.contains(packageName)) {
BrowserActivity.this.packageChanged(packageName,
Intent.ACTION_PACKAGE_ADDED.equals(action));
}
PackageManager pm = BrowserActivity.this.getPackageManager();
PackageInfo pkgInfo = null;
try {
pkgInfo = pm.getPackageInfo(packageName,
PackageManager.GET_PERMISSIONS);
} catch (PackageManager.NameNotFoundException e) {
return;
}
if (pkgInfo != null) {
String permissions[] = pkgInfo.requestedPermissions;
if (permissions == null) {
return;
}
boolean permissionOk = false;
for (String permit : permissions) {
if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
permissionOk = true;
break;
}
}
if (permissionOk) {
PluginManager.getInstance(BrowserActivity.this)
.refreshPlugins(
Intent.ACTION_PACKAGE_ADDED
.equals(action));
}
}
}
};
registerReceiver(mPackageInstallationReceiver, filter);
if (!mTabControl.restoreState(icicle)) {
// clear up the thumbnail directory if we can't restore the state as
// none of the files in the directory are referenced any more.
new ClearThumbnails().execute(
mTabControl.getThumbnailDir().listFiles());
// there is no quit on Android. But if we can't restore the state,
// we can treat it as a new Browser, remove the old session cookies.
CookieManager.getInstance().removeSessionCookie();
final Intent intent = getIntent();
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 = getUrlDataFromIntent(intent);
String action = intent.getAction();
final Tab t = mTabControl.createNewTab(
(Intent.ACTION_VIEW.equals(action) &&
intent.getData() != null)
|| RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
.equals(action),
intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
mTabControl.setCurrentTab(t);
attachTabToContentView(t);
WebView webView = t.getWebView();
if (extra != null) {
int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
if (scale > 0 && scale <= 1000) {
webView.setInitialScale(scale);
}
}
if (urlData.isEmpty()) {
loadUrl(webView, mSettings.getHomePage());
} else {
loadUrlDataIn(t, urlData);
}
} else {
// TabControl.restoreState() will create a new tab even if
// restoring the state fails.
attachTabToContentView(mTabControl.getCurrentTab());
}
// Read JavaScript flags if it exists.
String jsFlags = mSettings.getJsFlags();
if (jsFlags.trim().length() != 0) {
mTabControl.getCurrentWebView().setJsFlags(jsFlags);
}
// Work out which packages are installed on the system.
getInstalledPackages();
// Start watching the default geolocation permissions
mSystemAllowGeolocationOrigins
= new SystemAllowGeolocationOrigins(getApplicationContext());
mSystemAllowGeolocationOrigins.start();
}
| public void onCreate(Bundle icicle) {
if (LOGV_ENABLED) {
Log.v(LOGTAG, this + " onStart");
}
super.onCreate(icicle);
// test the browser in OpenGL
// requestWindowFeature(Window.FEATURE_OPENGL);
// enable this to test the browser in 32bit
if (false) {
getWindow().setFormat(PixelFormat.RGBX_8888);
BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
}
if (AccessibilityManager.getInstance(this).isEnabled()) {
setDefaultKeyMode(DEFAULT_KEYS_DISABLE);
} else {
setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
}
mResolver = getContentResolver();
// If this was a web search request, pass it on to the default web
// search provider and finish this activity.
if (handleWebSearchIntent(getIntent())) {
finish();
return;
}
mSecLockIcon = Resources.getSystem().getDrawable(
android.R.drawable.ic_secure);
mMixLockIcon = Resources.getSystem().getDrawable(
android.R.drawable.ic_partial_secure);
FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
.findViewById(com.android.internal.R.id.content);
mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
.inflate(R.layout.custom_screen, null);
mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
R.id.main_content);
mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
.findViewById(R.id.error_console);
mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
.findViewById(R.id.fullscreen_custom_content);
frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
mTitleBar = new TitleBar(this);
mXLargeScreenSize = (getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK)
== Configuration.SCREENLAYOUT_SIZE_XLARGE;
if (mXLargeScreenSize) {
LinearLayout layout = (LinearLayout) mBrowserFrameLayout.
findViewById(R.id.vertical_layout);
layout.addView(mTitleBar, 0, new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
} else {
// mTitleBar will be always be shown in the fully loaded mode on
// phone
mTitleBar.setProgress(100);
// Fake title bar is not needed in xlarge layout
mFakeTitleBar = new TitleBar(this);
}
// Create the tab control and our initial tab
mTabControl = new TabControl(this);
// Open the icon database and retain all the bookmark urls for favicons
retainIconsOnStartup();
// Keep a settings instance handy.
mSettings = BrowserSettings.getInstance();
mSettings.setTabControl(mTabControl);
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
// Find out if the network is currently up.
ConnectivityManager cm = (ConnectivityManager) getSystemService(
Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null) {
mIsNetworkUp = info.isAvailable();
}
/* enables registration for changes in network status from
http stack */
mNetworkStateChangedFilter = new IntentFilter();
mNetworkStateChangedFilter.addAction(
ConnectivityManager.CONNECTIVITY_ACTION);
mNetworkStateIntentReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(
ConnectivityManager.CONNECTIVITY_ACTION)) {
NetworkInfo info = intent.getParcelableExtra(
ConnectivityManager.EXTRA_NETWORK_INFO);
String typeName = info.getTypeName();
String subtypeName = info.getSubtypeName();
sendNetworkType(typeName.toLowerCase(),
(subtypeName != null ? subtypeName.toLowerCase() : ""));
onNetworkToggle(info.isAvailable());
}
}
};
IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
filter.addDataScheme("package");
mPackageInstallationReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
final String packageName = intent.getData()
.getSchemeSpecificPart();
final boolean replacing = intent.getBooleanExtra(
Intent.EXTRA_REPLACING, false);
if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
// if it is replacing, refreshPlugins() when adding
return;
}
if (sGoogleApps.contains(packageName)) {
BrowserActivity.this.packageChanged(packageName,
Intent.ACTION_PACKAGE_ADDED.equals(action));
}
PackageManager pm = BrowserActivity.this.getPackageManager();
PackageInfo pkgInfo = null;
try {
pkgInfo = pm.getPackageInfo(packageName,
PackageManager.GET_PERMISSIONS);
} catch (PackageManager.NameNotFoundException e) {
return;
}
if (pkgInfo != null) {
String permissions[] = pkgInfo.requestedPermissions;
if (permissions == null) {
return;
}
boolean permissionOk = false;
for (String permit : permissions) {
if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
permissionOk = true;
break;
}
}
if (permissionOk) {
PluginManager.getInstance(BrowserActivity.this)
.refreshPlugins(true);
}
}
}
};
registerReceiver(mPackageInstallationReceiver, filter);
if (!mTabControl.restoreState(icicle)) {
// clear up the thumbnail directory if we can't restore the state as
// none of the files in the directory are referenced any more.
new ClearThumbnails().execute(
mTabControl.getThumbnailDir().listFiles());
// there is no quit on Android. But if we can't restore the state,
// we can treat it as a new Browser, remove the old session cookies.
CookieManager.getInstance().removeSessionCookie();
final Intent intent = getIntent();
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 = getUrlDataFromIntent(intent);
String action = intent.getAction();
final Tab t = mTabControl.createNewTab(
(Intent.ACTION_VIEW.equals(action) &&
intent.getData() != null)
|| RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
.equals(action),
intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
mTabControl.setCurrentTab(t);
attachTabToContentView(t);
WebView webView = t.getWebView();
if (extra != null) {
int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
if (scale > 0 && scale <= 1000) {
webView.setInitialScale(scale);
}
}
if (urlData.isEmpty()) {
loadUrl(webView, mSettings.getHomePage());
} else {
loadUrlDataIn(t, urlData);
}
} else {
// TabControl.restoreState() will create a new tab even if
// restoring the state fails.
attachTabToContentView(mTabControl.getCurrentTab());
}
// Read JavaScript flags if it exists.
String jsFlags = mSettings.getJsFlags();
if (jsFlags.trim().length() != 0) {
mTabControl.getCurrentWebView().setJsFlags(jsFlags);
}
// Work out which packages are installed on the system.
getInstalledPackages();
// Start watching the default geolocation permissions
mSystemAllowGeolocationOrigins
= new SystemAllowGeolocationOrigins(getApplicationContext());
mSystemAllowGeolocationOrigins.start();
}
|
diff --git a/web/src/main/java/org/fao/geonet/kernel/csw/services/GetRecords.java b/web/src/main/java/org/fao/geonet/kernel/csw/services/GetRecords.java
index 945890af5c..fe1f516cee 100644
--- a/web/src/main/java/org/fao/geonet/kernel/csw/services/GetRecords.java
+++ b/web/src/main/java/org/fao/geonet/kernel/csw/services/GetRecords.java
@@ -1,761 +1,771 @@
//=============================================================================
//=== Copyright (C) 2001-2007 Food and Agriculture Organization of the
//=== United Nations (FAO-UN), United Nations World Food Programme (WFP)
//=== and United Nations Environment Programme (UNEP)
//===
//=== 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 St, Fifth Floor, Boston, MA 02110-1301, USA
//===
//=== Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2,
//=== Rome - Italy. email: [email protected]
//==============================================================================
package org.fao.geonet.kernel.csw.services;
import jeeves.resources.dbms.Dbms;
import jeeves.server.context.ServiceContext;
import jeeves.utils.Log;
import jeeves.utils.Xml;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.search.Sort;
import org.fao.geonet.GeonetContext;
import org.fao.geonet.constants.Geonet;
import org.fao.geonet.csw.common.ConstraintLanguage;
import org.fao.geonet.csw.common.Csw;
import org.fao.geonet.csw.common.ElementSetName;
import org.fao.geonet.csw.common.OutputSchema;
import org.fao.geonet.csw.common.ResultType;
import org.fao.geonet.csw.common.exceptions.CatalogException;
import org.fao.geonet.csw.common.exceptions.InvalidParameterValueEx;
import org.fao.geonet.csw.common.exceptions.MissingParameterValueEx;
import org.fao.geonet.csw.common.exceptions.NoApplicableCodeEx;
import org.fao.geonet.kernel.csw.CatalogConfiguration;
import org.fao.geonet.kernel.csw.CatalogService;
import org.fao.geonet.kernel.csw.services.getrecords.FieldMapper;
import org.fao.geonet.kernel.csw.services.getrecords.SearchController;
import org.fao.geonet.kernel.search.LuceneConfig;
import org.fao.geonet.kernel.search.LuceneSearcher;
import org.fao.geonet.kernel.search.spatial.Pair;
import org.fao.geonet.util.ISODate;
import org.jdom.Attribute;
import org.jdom.Element;
import org.springframework.util.CollectionUtils;
import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.StringTokenizer;
/**
* See OGC 07-006 and OGC 07-045.
*/
public class GetRecords extends AbstractOperation implements CatalogService {
/**
* OGC 07-006 10.8.4.4.
*/
private static final String defaultOutputFormat = "application/xml";
//---------------------------------------------------------------------------
//---
//--- Constructor
//---
//---------------------------------------------------------------------------
private SearchController _searchController;
/**
* @param summaryConfig
* @param luceneConfig
*/
public GetRecords(File summaryConfig, LuceneConfig luceneConfig) {
_searchController = new SearchController(summaryConfig, luceneConfig);
}
/**
* @return
*/
public SearchController getSearchController() {
return _searchController;
};
//---------------------------------------------------------------------------
//---
//--- API methods
//---
//---------------------------------------------------------------------------
public String getName() { return "GetRecords"; }
/**
*
* @param request
* @param context
* @return
* @throws CatalogException
*/
public Element execute(Element request, ServiceContext context) throws CatalogException {
String timeStamp = new ISODate().toString();
//
// some validation checks (note: this is not an XSD validation)
//
// must be "CSW"
checkService(request);
// must be "2.0.2"
checkVersion(request);
// GeoNetwork only supports "application/xml"
String outputFormat = checkOutputFormat(request);
// one of ElementName XOR ElementSetName must be requested
checkElementNamesXORElementSetName(request);
// optional integer, value at least 1
int startPos = getStartPosition(request);
// optional integer, value at least 1
int maxRecords = getMaxRecords(request);
Element query = request.getChild("Query", Csw.NAMESPACE_CSW);
// one of "hits", "results", "validate" or the GN-specific (invalid) "results_with_summary".
ResultType resultType = ResultType.parse(request.getAttributeValue("resultType"));
// either Record or IsoRecord
OutputSchema outSchema = OutputSchema.parse(request.getAttributeValue("outputSchema"));
// GeoNetwork-specific parameter defining how to deal with ElementNames. See documentation in
// SearchController.applyElementNames() about these strategies.
String elementnameStrategy = getElementNameStrategy(query);
// value csw:Record or gmd:MD_Metadata
// heikki: this is actually a List (in OGC 07-006), but OGC 07-045 states:
// "Because for this application profile it is not possible that a query includes more than one typename, .."
// So: a single String should be OK
String typeName = checkTypenames(query);
// set of elementnames or null
Set<String> elemNames = getElementNames(query);
// If any element names are specified, it's an ad hoc query and overrides the element set name default. In that
// case, we set setName to FULL instead of SUMMARY so that we can retrieve a CSW:Record and trim out the
// elements that aren't in the elemNames set.
ElementSetName setName = ElementSetName.FULL;
//
// no ElementNames requested: use ElementSetName
//
if((elemNames == null)) {
setName = getElementSetName(query , ElementSetName.SUMMARY);
// elementsetname is FULL: use customized elementset if defined
if(setName.equals(ElementSetName.FULL)) {
GeonetContext gc = (GeonetContext) context.getHandlerContext(Geonet.CONTEXT_NAME);
List<Element> customElementSets;
+ Dbms dbms = null;
try {
- Dbms dbms = (Dbms) context.getResourceManager().open (Geonet.Res.MAIN_DB);
+ dbms = (Dbms) context.getResourceManager().open (Geonet.Res.MAIN_DB);
customElementSets = gc.getDataManager().getCustomElementSets(dbms);
// custom elementset defined
if(!CollectionUtils.isEmpty(customElementSets)) {
if(elemNames == null) {
elemNames = new HashSet<String>();
}
for(Element customElementSet : customElementSets) {
elemNames.add(customElementSet.getChildText("xpath"));
}
}
}
catch(Exception x) {
Log.warning(Geonet.CSW, "Failed to check for custom element sets; ignoring -- request will be handled with default FULL elementsetname. Message was: " + x.getMessage());
+ // an error here could make the dbms unusable so close it so that a new one can be used...
+ // should it be committed or aborted?
+ if(dbms != null) {
+ try {
+ context.getResourceManager().close(Geonet.Res.MAIN_DB, dbms);
+ } catch (Exception e) {
+ throw new RuntimeException("Unable to close database connection", e);
+ }
+ }
}
}
}
Element constr = query.getChild("Constraint", Csw.NAMESPACE_CSW);
Element filterExpr = getFilterExpression(constr);
String filterVersion = getFilterVersion(constr);
// Get max hits to be used for summary - CSW GeoNetwork extension
int maxHitsInSummary = 1000;
String sMaxRecordsInKeywordSummary = query.getAttributeValue("maxHitsInSummary");
if (sMaxRecordsInKeywordSummary != null) {
// TODO : it could be better to use service config parameter instead
// sMaxRecordsInKeywordSummary = config.getValue("maxHitsInSummary", "1000");
maxHitsInSummary = Integer.parseInt(sMaxRecordsInKeywordSummary);
}
Sort sort = getSortFields(request, context);
Element response;
if(resultType == ResultType.VALIDATE) {
//String schema = context.getAppPath() + Geonet.Path.VALIDATION + "csw/2.0.2/csw-2.0.2.xsd";
String schema = context.getAppPath() + Geonet.Path.VALIDATION + "csw202_apiso100/csw/2.0.2/CSW-discovery.xsd";
Log.debug(Geonet.CSW, "Validating request against " + schema);
try {
Xml.validate(schema, request);
}
catch (Exception e) {
throw new NoApplicableCodeEx("Request failed validation:" + e.toString());
}
response = new Element("Acknowledgement", Csw.NAMESPACE_CSW);
response.setAttribute("timeStamp",timeStamp);
Element echoedRequest = new Element("EchoedRequest", Csw.NAMESPACE_CSW);
echoedRequest.addContent(request);
response.addContent(echoedRequest);
}
else {
response = new Element(getName() +"Response", Csw.NAMESPACE_CSW);
Attribute schemaLocation = new Attribute("schemaLocation","http://www.opengis.net/cat/csw/2.0.2 http://schemas.opengis.net/csw/2.0.2/CSW-discovery.xsd",Csw.NAMESPACE_XSI);
response.setAttribute(schemaLocation);
Element status = new Element("SearchStatus", Csw.NAMESPACE_CSW);
status.setAttribute("timestamp",timeStamp);
response.addContent(status);
String cswServiceSpecificContraint = request.getChildText(Geonet.Elem.FILTER);
Pair<Element, Element> search = _searchController.search(context, startPos, maxRecords, resultType, outSchema,
setName, filterExpr, filterVersion, sort, elemNames, typeName, maxHitsInSummary, cswServiceSpecificContraint, elementnameStrategy);
// Only add GeoNetwork summary on results_with_summary option
if (resultType == ResultType.RESULTS_WITH_SUMMARY) {
response.addContent(search.one());
}
response.addContent(search.two());
}
return response;
}
/**
* TODO javadoc.
*
* @param params
* @return
* @throws CatalogException
*/
public Element adaptGetRequest(Map<String, String> params) throws CatalogException {
String service = params.get("service");
String version = params.get("version");
String resultType = params.get("resulttype");
String outputFormat = params.get("outputformat");
String outputSchema = params.get("outputschema");
String startPosition= params.get("startposition");
String maxRecords = params.get("maxrecords");
String hopCount = params.get("hopcount");
String distribSearch= params.get("distributedsearch");
String typeNames = params.get("typenames");
String elemSetName = params.get("elementsetname");
String elemName = params.get("elementname");
String constraint = params.get("constraint");
String constrLang = params.get("constraintlanguage");
String constrLangVer= params.get("constraint_language_version");
String sortby = params.get("sortby");
String elementnameStrategy = params.get("elementnamestrategy");
//--- build POST request
Element request = new Element(getName(), Csw.NAMESPACE_CSW);
setAttrib(request, "service", service);
setAttrib(request, "version", version);
setAttrib(request, "resultType", resultType);
setAttrib(request, "outputFormat", outputFormat);
setAttrib(request, "outputSchema", outputSchema);
setAttrib(request, "startPosition", startPosition);
setAttrib(request, "maxRecords", maxRecords);
if (distribSearch != null && distribSearch.equals("true")) {
Element ds = new Element("DistributedSearch", Csw.NAMESPACE_CSW);
ds.setText("TRUE");
if (hopCount != null) {
ds.setAttribute("hopCount", hopCount);
}
request.addContent(ds);
}
//--- build query element
Element query = new Element("Query", Csw.NAMESPACE_CSW);
request.addContent(query);
if(elementnameStrategy != null) {
setAttrib(query, "elementnamestrategy", elementnameStrategy);
}
if (typeNames != null) {
setAttrib(query, "typeNames", typeNames.replace(',',' '));
}
//--- these 2 are in mutual exclusion
addElement(query, "ElementSetName", elemSetName);
fill(query, "ElementName", elemName);
//--- handle constraint
ConstraintLanguage language = ConstraintLanguage.parse(constrLang);
if (constraint != null) {
Element constr = new Element("Constraint", Csw.NAMESPACE_CSW);
query.addContent(constr);
if (language == ConstraintLanguage.CQL) {
addElement(constr, "CqlText", constraint);
}
else {
try {
constr.addContent(Xml.loadString(constraint, false));
}
catch (Exception e) {
e.printStackTrace();
throw new NoApplicableCodeEx("Constraint is not a valid xml");
}
}
setAttrib(constr, "version", constrLangVer);
}
//--- handle sortby
if (sortby != null) {
Element sortBy = new Element("SortBy", Csw.NAMESPACE_OGC);
query.addContent(sortBy);
StringTokenizer st = new StringTokenizer(sortby, ",");
while (st.hasMoreTokens()) {
String sortInfo = st.nextToken();
String field = sortInfo.substring(0, sortInfo.length() -2);
boolean ascen = sortInfo.endsWith(":A");
Element sortProp = new Element("SortProperty", Csw.NAMESPACE_OGC);
sortBy.addContent(sortProp);
Element propName = new Element("PropertyName", Csw.NAMESPACE_OGC).setText(field);
Element sortOrder = new Element("SortOrder", Csw.NAMESPACE_OGC).setText(ascen ? "ASC" : "DESC");
sortProp.addContent(propName);
sortProp.addContent(sortOrder);
}
}
return request;
}
/**
* TODO javadoc.
*
* @param parameterName
* @return
* @throws CatalogException
*/
public Element retrieveValues(String parameterName) throws CatalogException {
Element listOfValues = null;
if (parameterName.equalsIgnoreCase("resultType")
|| parameterName.equalsIgnoreCase("outputFormat")
|| parameterName.equalsIgnoreCase("elementSetName")
|| parameterName.equalsIgnoreCase("outputSchema")
|| parameterName.equalsIgnoreCase("typenames"))
listOfValues = new Element("ListOfValues", Csw.NAMESPACE_CSW);
// Handle resultType parameter
if (parameterName.equalsIgnoreCase("resultType")) {
List<Element> values = new ArrayList<Element>();
ResultType[] resultType = ResultType.values();
for (ResultType aResultType : resultType) {
String value = aResultType.toString();
values.add(new Element("Value", Csw.NAMESPACE_CSW).setText(value));
}
if (listOfValues != null) {
listOfValues.addContent(values);
}
}
// Handle elementSetName parameter
if (parameterName.equalsIgnoreCase("elementSetName")) {
List<Element> values = new ArrayList<Element>();
ElementSetName[] esn = ElementSetName.values();
for (ElementSetName anEsn : esn) {
String value = anEsn.toString();
values.add(new Element("Value", Csw.NAMESPACE_CSW).setText(value));
}
if (listOfValues != null) {
listOfValues.addContent(values);
}
}
// Handle outputFormat parameter
if (parameterName.equalsIgnoreCase("outputformat")) {
Set<String> formats = CatalogConfiguration
.getGetRecordsOutputFormat();
List<Element> values = createValuesElement(formats);
if (listOfValues != null) {
listOfValues.addContent(values);
}
}
// Handle outputSchema parameter
if (parameterName.equalsIgnoreCase("outputSchema")) {
Set<String> namespacesUri = CatalogConfiguration
.getGetRecordsOutputSchema();
List<Element> values = createValuesElement(namespacesUri);
if (listOfValues != null) {
listOfValues.addContent(values);
}
}
// Handle typenames parameter
if (parameterName.equalsIgnoreCase("typenames")) {
Set<String> typenames = CatalogConfiguration
.getGetRecordsTypenames();
List<Element> values = createValuesElement(typenames);
if (listOfValues != null) {
listOfValues.addContent(values);
}
}
return listOfValues;
}
//---------------------------------------------------------------------------
//---
//--- Private methods
//---
//---------------------------------------------------------------------------
/**
* GeoNetwork only supports default value for outputFormat.
*
* OGC 07-006:
* The only value that is required to be supported is application/xml. Other supported values may include text/html
* and text/plain. Cardinality: Zero or one (Optional). Default value is application/xml.
*
* In the case where the output format is application/xml, the CSW shall generate an XML document that validates
* against a schema document that is specified in the output document via the xsi:schemaLocation attribute defined
* in XML.
*
* @param request GetRecords request
* @throws InvalidParameterValueEx hmm
*/
private String checkOutputFormat(Element request) throws InvalidParameterValueEx {
String format = request.getAttributeValue("outputFormat");
if (format != null && !format.equals(defaultOutputFormat)) {
throw new InvalidParameterValueEx("outputFormat", format);
}
else {
return defaultOutputFormat;
}
}
/**
* If the request contains a Query element, it must have attribute typeNames.
*
* The OGC 07-045 spec is more restrictive than OGC 07-006.
*
* OGC 07-006 10.8.4.8:
* The typeNames parameter is a list of one or more names of queryable entities in the catalogue's information model
* that may be constrained in the predicate of the query. In the case of XML realization of the OGC core metadata
* properties (Subclause 10.2.5), the element csw:Record is the only queryable entity. Other information models may
* include more than one queryable component. For example, queryable components for the XML realization of the ebRIM
* include rim:Service, rim:ExtrinsicObject and rim:Association. In such cases the application profile shall
* describe how multiple typeNames values should be processed.
* In addition, all or some of the these queryable entity names may be specified in the query to define which
* metadata record elements the query should present in the response to the GetRecords operation.
*
* OGC 07-045 8.2.2.1.1:
* Mandatory: Must support *one* of “csw:Record” or “gmd:MD_Metadata” in a query. Default value is “csw:Record”.
*
*
* So: if typeNames is not present or empty, or does not contain exactly one of the values specified in OGC 07-045,
* an exception is thrown.
*
* @param query query element
* @return typeName
* @throws MissingParameterValueEx if typeNames is missing
* @throws InvalidParameterValueEx if typeNames does not have one of the mandated values
*/
private String checkTypenames(Element query) throws MissingParameterValueEx, InvalidParameterValueEx {
Log.debug(Geonet.CSW_SEARCH, "checking typenames in query:\n" + Xml.getString(query));
Attribute typeNames = query.getAttribute("typeNames", query.getNamespace());
typeNames = query.getAttribute("typeNames");
if(typeNames != null) {
String typeNamesValue = typeNames.getValue();
if(StringUtils.isEmpty(typeNamesValue)) {
throw new MissingParameterValueEx("typeNames");
}
else if(!(typeNamesValue.equals("csw:Record") || typeNamesValue.equals("gmd:MD_Metadata"))) {
throw new InvalidParameterValueEx("typeNames", "invalid value");
}
else {
return typeNamesValue;
}
}
else {
throw new MissingParameterValueEx("typeNames");
}
}
/**
* GeoNetwork-specific parameter to control the behaviour when dealing with ElementNames. Supported values are
* 'csw202', 'relaxed' , 'context' and 'geonetwork26'. If the parameter is missing or does not have one of these
* values, the default value 'relaxed' is used. See documentation in SearchController.applyElementNames() about
* these strategies.
*
* @param query query element
* @return elementnames strategy
*/
private String getElementNameStrategy(Element query) {
Log.debug(Geonet.CSW_SEARCH, "getting elementnameStrategy from query:\n" + Xml.getString(query));
Attribute elementNameStrategyA = query.getAttribute("elementnameStrategy");
// default
String elementNameStrategy = "relaxed";
if(elementNameStrategyA != null) {
elementNameStrategy = elementNameStrategyA.getValue() ;
}
// empty or not one of the supported values
if(StringUtils.isNotEmpty(elementNameStrategy) &&
!(elementNameStrategy.equals("csw202") ||
elementNameStrategy.equals("relaxed") ||
elementNameStrategy.equals("context") ||
elementNameStrategy.equals("geonetwork26"))) {
// use default
elementNameStrategy = "relaxed";
}
Log.debug(Geonet.CSW_SEARCH, "elementNameStrategy: " + elementNameStrategy);
return elementNameStrategy;
}
/**
* Checks that not ElementName and ElementSetName are both present in the query, see OGC 07-006 section 10 8 4 9.
*
* @param request
* @throws InvalidParameterValueEx
*/
private void checkElementNamesXORElementSetName(Element request) throws InvalidParameterValueEx {
Element query = request.getChild("Query", Csw.NAMESPACE_CSW);
if(query != null) {
boolean elementNamePresent = !CollectionUtils.isEmpty(query.getChildren("ElementName", query.getNamespace()));
boolean elementSetNamePresent = !CollectionUtils.isEmpty(query.getChildren("ElementSetName", query.getNamespace()));
if(elementNamePresent && elementSetNamePresent) {
throw new InvalidParameterValueEx("ElementName and ElementSetName", "mutually exclusive");
}
}
}
/**
* OGC 07-006 and OGC 07-045:
* Non-zero, positive Integer. Optional. The default value is 1.
*
* @param request the request
* @return startPosition
* @throws InvalidParameterValueEx hmm
*/
private int getStartPosition(Element request) throws InvalidParameterValueEx {
String start = request.getAttributeValue("startPosition");
if(start == null) {
return 1;
}
try {
int value = Integer.parseInt(start);
if(value >= 1) {
return value;
}
else {
throw new InvalidParameterValueEx("startPosition", start);
}
}
catch (NumberFormatException x) {
throw new InvalidParameterValueEx("startPosition", start);
}
}
/**
* OGC 07-006 and OGC 07-045:
* PositiveInteger. Optional. The default value is 10.
*
* @param request the request
* @return maxRecords
* @throws InvalidParameterValueEx hmm
*/
private int getMaxRecords(Element request) throws InvalidParameterValueEx {
String max = request.getAttributeValue("maxRecords");
if(max == null) {
return 10;
}
try {
int value = Integer.parseInt(max);
if (value >= 1) {
return value;
}
else {
throw new InvalidParameterValueEx("maxRecords", max);
}
}
catch (NumberFormatException x) {
throw new InvalidParameterValueEx("maxRecords", max);
}
}
/**
* a return value >= 0 means that a distributed search was requested, otherwise the method returns -1.
*
* TODO unused method
*
* @param request
* @return
* @throws InvalidParameterValueEx
*/
private int getHopCount(Element request) throws InvalidParameterValueEx {
Element ds = request.getChild("DistributedSearch", Csw.NAMESPACE_CSW);
if (ds == null) {
return -1;
}
String hopCount = ds.getAttributeValue("hopCount");
if (hopCount == null) {
return 2;
}
try {
int value = Integer.parseInt(hopCount);
if (value >= 0) {
return value;
}
}
catch (NumberFormatException ignored) {
throw new InvalidParameterValueEx("hopCount", hopCount);
}
throw new InvalidParameterValueEx("hopCount", hopCount);
}
/**
* TODO javadoc.
*
* @param request
* @param context
* @return
*/
private Sort getSortFields(Element request, ServiceContext context) {
Element query = request.getChild("Query", Csw.NAMESPACE_CSW);
if (query == null) {
return null;
}
Element sortBy = query.getChild("SortBy", Csw.NAMESPACE_OGC);
if (sortBy == null) {
return null;
}
List list = sortBy.getChildren();
List<Pair<String, Boolean>> sortFields = new ArrayList<Pair<String, Boolean>>();
for (Object aList : list) {
Element el = (Element) aList;
String field = el.getChildText("PropertyName", Csw.NAMESPACE_OGC);
String order = el.getChildText("SortOrder", Csw.NAMESPACE_OGC);
// Map CSW search field to Lucene for sorting. And if not mapped assumes the field is a Lucene field.
String luceneField = FieldMapper.map(field);
if (luceneField != null) {
sortFields.add(Pair.read(luceneField, "DESC".equals(order)));
}
else {
sortFields.add(Pair.read(field, "DESC".equals(order)));
}
}
// we always want to keep the relevancy as part of the sorting mechanism
return LuceneSearcher.makeSort(sortFields, context.getLanguage(), false);
}
/**
* Returns the values of ElementNames in the query, or null if there are none.
*
* @param query the query
* @return set of elementname values
*/
private Set<String> getElementNames(Element query) {
Log.debug(Geonet.CSW, "GetRecords getElementNames");
Set<String> elementNames = null;
if (query != null) {
List<Element> elementList = query.getChildren("ElementName", query.getNamespace());
for(Element element : elementList) {
if(elementNames == null) {
elementNames = new HashSet<String>();
}
elementNames.add(element.getText());
}
}
// TODO in if(isDebugEnabled) condition. Jeeves LOG doesn't provide that useful function though.
if(elementNames != null) {
for(String elementName : elementNames) {
Log.debug(Geonet.CSW, "ElementName: " + elementName);
}
}
else {
Log.debug(Geonet.CSW, "No ElementNames found in request");
}
// TODO end if(isDebugEnabled)
return elementNames;
}
/**
* Retrieves the values of attribute typeNames. If typeNames contains csw:BriefRecord or csw:SummaryRecord, an
* exception is thrown.
*
* @param query the query
* @return list of typenames, or null if not found
* @throws InvalidParameterValueEx if a typename is illegal
*/
private Set<String> getTypeNames(Element query) throws InvalidParameterValueEx {
Set<String> typeNames = null;
String typeNames$ = query.getAttributeValue("typeNames");
if(typeNames$ != null) {
Scanner commaSeparatedScanner = new Scanner(typeNames$).useDelimiter(",");
while(commaSeparatedScanner.hasNext()) {
String typeName = commaSeparatedScanner.next().trim();
// These two are explicitly not allowed as search targets in CSW 2.0.2, so we throw an exception if the
// client asks for them
if (typeName.equals("csw:BriefRecord") || typeName.equals("csw:SummaryRecord")) {
throw new InvalidParameterValueEx("typeName", typeName);
}
if(typeNames == null) {
typeNames = new HashSet<String>();
}
typeNames.add(typeName);
}
}
// TODO in if(isDebugEnabled) condition. Jeeves LOG doesn't provide that useful function though.
if(typeNames != null) {
for(String typeName : typeNames) {
Log.debug(Geonet.CSW, "TypeName: " + typeName);
}
}
else {
Log.debug(Geonet.CSW, "No TypeNames found in request");
}
// TODO end if(isDebugEnabled)
return typeNames;
}
}
| false | true | public Element execute(Element request, ServiceContext context) throws CatalogException {
String timeStamp = new ISODate().toString();
//
// some validation checks (note: this is not an XSD validation)
//
// must be "CSW"
checkService(request);
// must be "2.0.2"
checkVersion(request);
// GeoNetwork only supports "application/xml"
String outputFormat = checkOutputFormat(request);
// one of ElementName XOR ElementSetName must be requested
checkElementNamesXORElementSetName(request);
// optional integer, value at least 1
int startPos = getStartPosition(request);
// optional integer, value at least 1
int maxRecords = getMaxRecords(request);
Element query = request.getChild("Query", Csw.NAMESPACE_CSW);
// one of "hits", "results", "validate" or the GN-specific (invalid) "results_with_summary".
ResultType resultType = ResultType.parse(request.getAttributeValue("resultType"));
// either Record or IsoRecord
OutputSchema outSchema = OutputSchema.parse(request.getAttributeValue("outputSchema"));
// GeoNetwork-specific parameter defining how to deal with ElementNames. See documentation in
// SearchController.applyElementNames() about these strategies.
String elementnameStrategy = getElementNameStrategy(query);
// value csw:Record or gmd:MD_Metadata
// heikki: this is actually a List (in OGC 07-006), but OGC 07-045 states:
// "Because for this application profile it is not possible that a query includes more than one typename, .."
// So: a single String should be OK
String typeName = checkTypenames(query);
// set of elementnames or null
Set<String> elemNames = getElementNames(query);
// If any element names are specified, it's an ad hoc query and overrides the element set name default. In that
// case, we set setName to FULL instead of SUMMARY so that we can retrieve a CSW:Record and trim out the
// elements that aren't in the elemNames set.
ElementSetName setName = ElementSetName.FULL;
//
// no ElementNames requested: use ElementSetName
//
if((elemNames == null)) {
setName = getElementSetName(query , ElementSetName.SUMMARY);
// elementsetname is FULL: use customized elementset if defined
if(setName.equals(ElementSetName.FULL)) {
GeonetContext gc = (GeonetContext) context.getHandlerContext(Geonet.CONTEXT_NAME);
List<Element> customElementSets;
try {
Dbms dbms = (Dbms) context.getResourceManager().open (Geonet.Res.MAIN_DB);
customElementSets = gc.getDataManager().getCustomElementSets(dbms);
// custom elementset defined
if(!CollectionUtils.isEmpty(customElementSets)) {
if(elemNames == null) {
elemNames = new HashSet<String>();
}
for(Element customElementSet : customElementSets) {
elemNames.add(customElementSet.getChildText("xpath"));
}
}
}
catch(Exception x) {
Log.warning(Geonet.CSW, "Failed to check for custom element sets; ignoring -- request will be handled with default FULL elementsetname. Message was: " + x.getMessage());
}
}
}
Element constr = query.getChild("Constraint", Csw.NAMESPACE_CSW);
Element filterExpr = getFilterExpression(constr);
String filterVersion = getFilterVersion(constr);
// Get max hits to be used for summary - CSW GeoNetwork extension
int maxHitsInSummary = 1000;
String sMaxRecordsInKeywordSummary = query.getAttributeValue("maxHitsInSummary");
if (sMaxRecordsInKeywordSummary != null) {
// TODO : it could be better to use service config parameter instead
// sMaxRecordsInKeywordSummary = config.getValue("maxHitsInSummary", "1000");
maxHitsInSummary = Integer.parseInt(sMaxRecordsInKeywordSummary);
}
Sort sort = getSortFields(request, context);
Element response;
if(resultType == ResultType.VALIDATE) {
//String schema = context.getAppPath() + Geonet.Path.VALIDATION + "csw/2.0.2/csw-2.0.2.xsd";
String schema = context.getAppPath() + Geonet.Path.VALIDATION + "csw202_apiso100/csw/2.0.2/CSW-discovery.xsd";
Log.debug(Geonet.CSW, "Validating request against " + schema);
try {
Xml.validate(schema, request);
}
catch (Exception e) {
throw new NoApplicableCodeEx("Request failed validation:" + e.toString());
}
response = new Element("Acknowledgement", Csw.NAMESPACE_CSW);
response.setAttribute("timeStamp",timeStamp);
Element echoedRequest = new Element("EchoedRequest", Csw.NAMESPACE_CSW);
echoedRequest.addContent(request);
response.addContent(echoedRequest);
}
else {
response = new Element(getName() +"Response", Csw.NAMESPACE_CSW);
Attribute schemaLocation = new Attribute("schemaLocation","http://www.opengis.net/cat/csw/2.0.2 http://schemas.opengis.net/csw/2.0.2/CSW-discovery.xsd",Csw.NAMESPACE_XSI);
response.setAttribute(schemaLocation);
Element status = new Element("SearchStatus", Csw.NAMESPACE_CSW);
status.setAttribute("timestamp",timeStamp);
response.addContent(status);
String cswServiceSpecificContraint = request.getChildText(Geonet.Elem.FILTER);
Pair<Element, Element> search = _searchController.search(context, startPos, maxRecords, resultType, outSchema,
setName, filterExpr, filterVersion, sort, elemNames, typeName, maxHitsInSummary, cswServiceSpecificContraint, elementnameStrategy);
// Only add GeoNetwork summary on results_with_summary option
if (resultType == ResultType.RESULTS_WITH_SUMMARY) {
response.addContent(search.one());
}
response.addContent(search.two());
}
return response;
}
| public Element execute(Element request, ServiceContext context) throws CatalogException {
String timeStamp = new ISODate().toString();
//
// some validation checks (note: this is not an XSD validation)
//
// must be "CSW"
checkService(request);
// must be "2.0.2"
checkVersion(request);
// GeoNetwork only supports "application/xml"
String outputFormat = checkOutputFormat(request);
// one of ElementName XOR ElementSetName must be requested
checkElementNamesXORElementSetName(request);
// optional integer, value at least 1
int startPos = getStartPosition(request);
// optional integer, value at least 1
int maxRecords = getMaxRecords(request);
Element query = request.getChild("Query", Csw.NAMESPACE_CSW);
// one of "hits", "results", "validate" or the GN-specific (invalid) "results_with_summary".
ResultType resultType = ResultType.parse(request.getAttributeValue("resultType"));
// either Record or IsoRecord
OutputSchema outSchema = OutputSchema.parse(request.getAttributeValue("outputSchema"));
// GeoNetwork-specific parameter defining how to deal with ElementNames. See documentation in
// SearchController.applyElementNames() about these strategies.
String elementnameStrategy = getElementNameStrategy(query);
// value csw:Record or gmd:MD_Metadata
// heikki: this is actually a List (in OGC 07-006), but OGC 07-045 states:
// "Because for this application profile it is not possible that a query includes more than one typename, .."
// So: a single String should be OK
String typeName = checkTypenames(query);
// set of elementnames or null
Set<String> elemNames = getElementNames(query);
// If any element names are specified, it's an ad hoc query and overrides the element set name default. In that
// case, we set setName to FULL instead of SUMMARY so that we can retrieve a CSW:Record and trim out the
// elements that aren't in the elemNames set.
ElementSetName setName = ElementSetName.FULL;
//
// no ElementNames requested: use ElementSetName
//
if((elemNames == null)) {
setName = getElementSetName(query , ElementSetName.SUMMARY);
// elementsetname is FULL: use customized elementset if defined
if(setName.equals(ElementSetName.FULL)) {
GeonetContext gc = (GeonetContext) context.getHandlerContext(Geonet.CONTEXT_NAME);
List<Element> customElementSets;
Dbms dbms = null;
try {
dbms = (Dbms) context.getResourceManager().open (Geonet.Res.MAIN_DB);
customElementSets = gc.getDataManager().getCustomElementSets(dbms);
// custom elementset defined
if(!CollectionUtils.isEmpty(customElementSets)) {
if(elemNames == null) {
elemNames = new HashSet<String>();
}
for(Element customElementSet : customElementSets) {
elemNames.add(customElementSet.getChildText("xpath"));
}
}
}
catch(Exception x) {
Log.warning(Geonet.CSW, "Failed to check for custom element sets; ignoring -- request will be handled with default FULL elementsetname. Message was: " + x.getMessage());
// an error here could make the dbms unusable so close it so that a new one can be used...
// should it be committed or aborted?
if(dbms != null) {
try {
context.getResourceManager().close(Geonet.Res.MAIN_DB, dbms);
} catch (Exception e) {
throw new RuntimeException("Unable to close database connection", e);
}
}
}
}
}
Element constr = query.getChild("Constraint", Csw.NAMESPACE_CSW);
Element filterExpr = getFilterExpression(constr);
String filterVersion = getFilterVersion(constr);
// Get max hits to be used for summary - CSW GeoNetwork extension
int maxHitsInSummary = 1000;
String sMaxRecordsInKeywordSummary = query.getAttributeValue("maxHitsInSummary");
if (sMaxRecordsInKeywordSummary != null) {
// TODO : it could be better to use service config parameter instead
// sMaxRecordsInKeywordSummary = config.getValue("maxHitsInSummary", "1000");
maxHitsInSummary = Integer.parseInt(sMaxRecordsInKeywordSummary);
}
Sort sort = getSortFields(request, context);
Element response;
if(resultType == ResultType.VALIDATE) {
//String schema = context.getAppPath() + Geonet.Path.VALIDATION + "csw/2.0.2/csw-2.0.2.xsd";
String schema = context.getAppPath() + Geonet.Path.VALIDATION + "csw202_apiso100/csw/2.0.2/CSW-discovery.xsd";
Log.debug(Geonet.CSW, "Validating request against " + schema);
try {
Xml.validate(schema, request);
}
catch (Exception e) {
throw new NoApplicableCodeEx("Request failed validation:" + e.toString());
}
response = new Element("Acknowledgement", Csw.NAMESPACE_CSW);
response.setAttribute("timeStamp",timeStamp);
Element echoedRequest = new Element("EchoedRequest", Csw.NAMESPACE_CSW);
echoedRequest.addContent(request);
response.addContent(echoedRequest);
}
else {
response = new Element(getName() +"Response", Csw.NAMESPACE_CSW);
Attribute schemaLocation = new Attribute("schemaLocation","http://www.opengis.net/cat/csw/2.0.2 http://schemas.opengis.net/csw/2.0.2/CSW-discovery.xsd",Csw.NAMESPACE_XSI);
response.setAttribute(schemaLocation);
Element status = new Element("SearchStatus", Csw.NAMESPACE_CSW);
status.setAttribute("timestamp",timeStamp);
response.addContent(status);
String cswServiceSpecificContraint = request.getChildText(Geonet.Elem.FILTER);
Pair<Element, Element> search = _searchController.search(context, startPos, maxRecords, resultType, outSchema,
setName, filterExpr, filterVersion, sort, elemNames, typeName, maxHitsInSummary, cswServiceSpecificContraint, elementnameStrategy);
// Only add GeoNetwork summary on results_with_summary option
if (resultType == ResultType.RESULTS_WITH_SUMMARY) {
response.addContent(search.one());
}
response.addContent(search.two());
}
return response;
}
|
diff --git a/org.knime.knip.imagej1/src/org/knime/knip/imagej1/IJMacroNodeFactory.java b/org.knime.knip.imagej1/src/org/knime/knip/imagej1/IJMacroNodeFactory.java
index 62bb8c1..7be8af0 100644
--- a/org.knime.knip.imagej1/src/org/knime/knip/imagej1/IJMacroNodeFactory.java
+++ b/org.knime.knip.imagej1/src/org/knime/knip/imagej1/IJMacroNodeFactory.java
@@ -1,394 +1,395 @@
/*
* ------------------------------------------------------------------------
*
* Copyright (C) 2003 - 2013
* University of Konstanz, Germany and
* KNIME GmbH, Konstanz, Germany
* Website: http://www.knime.org; Email: [email protected]
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License, Version 3, 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 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>.
*
* Additional permission under GNU GPL version 3 section 7:
*
* KNIME interoperates with ECLIPSE solely via ECLIPSE's plug-in APIs.
* Hence, KNIME and ECLIPSE are both independent programs and are not
* derived from each other. Should, however, the interpretation of the
* GNU GPL Version 3 ("License") under any applicable laws result in
* KNIME and ECLIPSE being a combined program, KNIME GMBH herewith grants
* you the additional permission to use and propagate KNIME together with
* ECLIPSE with only the license terms in place for ECLIPSE applying to
* ECLIPSE and the GNU GPL Version 3 applying for KNIME, provided the
* license terms of ECLIPSE themselves allow for the respective use and
* propagation of ECLIPSE together with KNIME.
*
* Additional permission relating to nodes for KNIME that extend the Node
* Extension (and in particular that are based on subclasses of NodeModel,
* NodeDialog, and NodeView) and that only interoperate with KNIME through
* standard APIs ("Nodes"):
* Nodes are deemed to be separate and independent programs and to not be
* covered works. Notwithstanding anything to the contrary in the
* License, the License does not apply to Nodes, you are not required to
* license Nodes under the License, and you are granted a license to
* prepare and propagate Nodes, in each case even if such Nodes are
* propagated with or for interoperation with KNIME. The owner of a Node
* may freely choose the license terms applicable to such Node, including
* when such Node is propagated with or for interoperation with KNIME.
* --------------------------------------------------------------------- *
*
*/
package org.knime.knip.imagej1;
import ij.measure.ResultsTable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import net.imglib2.Interval;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.img.ImgView;
import net.imglib2.meta.ImgPlus;
import net.imglib2.meta.ImgPlusMetadata;
import net.imglib2.meta.MetadataUtil;
import net.imglib2.ops.operation.SubsetOperations;
import net.imglib2.ops.operation.iterableinterval.unary.Inset;
import net.imglib2.type.numeric.RealType;
import org.knime.core.data.DataColumnSpec;
import org.knime.core.data.DataColumnSpecCreator;
import org.knime.core.data.DataRow;
import org.knime.core.data.DataTableSpec;
import org.knime.core.data.def.DefaultRow;
import org.knime.core.data.def.DoubleCell;
import org.knime.core.node.BufferedDataContainer;
import org.knime.core.node.BufferedDataTable;
import org.knime.core.node.ExecutionContext;
import org.knime.core.node.InvalidSettingsException;
import org.knime.core.node.NodeFactory;
import org.knime.core.node.NotConfigurableException;
import org.knime.core.node.defaultnodesettings.DialogComponent;
import org.knime.core.node.defaultnodesettings.SettingsModel;
import org.knime.core.node.defaultnodesettings.SettingsModelString;
import org.knime.core.node.port.PortObject;
import org.knime.core.node.port.PortObjectSpec;
import org.knime.core.node.port.PortType;
import org.knime.knip.base.data.img.ImgPlusCell;
import org.knime.knip.base.data.img.ImgPlusCellFactory;
import org.knime.knip.base.data.img.ImgPlusValue;
import org.knime.knip.base.exceptions.KNIPException;
import org.knime.knip.base.exceptions.KNIPRuntimeException;
import org.knime.knip.base.node.GenericValueToCellNodeFactory;
import org.knime.knip.base.node.ValueToCellNodeDialog;
import org.knime.knip.base.node.ValueToCellNodeModel;
import org.knime.knip.base.node.dialog.DialogComponentDimSelection;
import org.knime.knip.base.node.nodesettings.SettingsModelDimSelection;
import org.knime.knip.base.node.nodesettings.SettingsModelSerializableObjects;
import org.knime.knip.base.nodes.io.kernel.DialogComponentSerializableConfiguration;
import org.knime.knip.base.nodes.io.kernel.SerializableSetting;
import org.knime.knip.core.data.img.DefaultImgMetadata;
import org.knime.knip.imagej1.macro.AnalyzeParticlesIJMacro;
import org.knime.knip.imagej1.macro.CLAHEIJMacro;
import org.knime.knip.imagej1.macro.FindEdgesIJMacro;
import org.knime.knip.imagej1.macro.FindMaximaIJMacro;
import org.knime.knip.imagej1.macro.GaussianBlurIJMacro;
import org.knime.knip.imagej1.macro.PureCodeIJMacro;
import org.knime.knip.imagej1.macro.SharpenIJMacro;
import org.knime.knip.imagej1.macro.SubstractBackgroundIJMacro;
import org.knime.knip.imagej1.macro.WatershedIJMacro;
import org.knime.knip.imagej1.prefs.IJ1Preferences;
import org.knime.knip.imagej2.core.util.UntransformableIJTypeException;
/**
* {@link NodeFactory} to run {@link IJMacro}s
*
* @author <a href="mailto:[email protected]">Christian Dietz</a>
* @author <a href="mailto:[email protected]">Martin Horn</a>
* @author <a href="mailto:[email protected]">Michael Zinsmaier</a>
*
* @param <T>
*
*/
@SuppressWarnings("rawtypes")
public class IJMacroNodeFactory<T extends RealType<T>> extends
GenericValueToCellNodeFactory<ImgPlusValue, ValueToCellNodeModel<ImgPlusValue, ImgPlusCell>> {
private static SettingsModelSerializableObjects<SerializableSetting<String>> createMacroSelectionModel() {
return new SettingsModelSerializableObjects<SerializableSetting<String>>("kernels", new ImageJ1ObjectExt0());
}
private static SettingsModelDimSelection createDimSelectionModel() {
return new SettingsModelDimSelection("dim_selection", "X", "Y");
}
private static SettingsModelString createFlowVariableControllableCode() {
return new SettingsModelString("flow_variable_controlable_code", "");
}
/**
* {@inheritDoc}
*/
@Override
public ValueToCellNodeModel<ImgPlusValue, ImgPlusCell> createNodeModel() {
return new ValueToCellNodeModel<ImgPlusValue, ImgPlusCell>(new PortType[]{},
new PortType[]{BufferedDataTable.TYPE}) {
private final SettingsModelSerializableObjects<SerializableSetting<String>> m_macroSelection =
createMacroSelectionModel();
private final SettingsModelDimSelection m_dimSelection = createDimSelectionModel();
private final SettingsModelString m_flowVarCode = createFlowVariableControllableCode();
private IJMacro m_macro;
private ImgPlusCellFactory m_imgCellFactory;
private BufferedDataContainer m_resTableContainer;
private String m_currentRowKey;
private ExecutionContext m_exec;
/**
* {@inheritDoc}
*/
@Override
protected PortObjectSpec[] configure(final PortObjectSpec[] inSpecs) throws InvalidSettingsException {
final PortObjectSpec firstSpec = super.configure(inSpecs)[0];
return new PortObjectSpec[]{firstSpec, null};
}
/**
* {@inheritDoc}
*/
@Override
protected PortObject[] execute(final PortObject[] inObjects, final ExecutionContext exec) throws Exception {
final PortObject firstPort = super.execute(inObjects, exec)[0];
PortObject secondPort = null;
if (m_resTableContainer == null) {
m_resTableContainer = exec.createDataContainer(new DataTableSpec());
}
m_resTableContainer.close();
secondPort = m_resTableContainer.getTable();
return new PortObject[]{firstPort, secondPort};
}
@Override
protected void prepareExecute(final ExecutionContext exec) {
final List<SerializableSetting<String>> conf = m_macroSelection.getObjects();
String code = "";
if (m_flowVarCode.getStringValue().length() == 0) {
for (final SerializableSetting<String> fc : conf) {
code += fc.get();
}
} else {
setWarningMessage("IJ macro code controlled by a flow variable!");
code = m_flowVarCode.getStringValue();
m_flowVarCode.setStringValue("");
}
m_macro = new IJMacro(code);
m_imgCellFactory = new ImgPlusCellFactory(exec);
m_exec = exec;
m_resTableContainer = null;
System.setProperty("plugins.dir", IJ1Preferences.getIJ1PluginPath());
}
private DataTableSpec createResultTableSpec(final ResultsTable table) {
final String colHeadings = table.getColumnHeadings();
final StringTokenizer tk = new StringTokenizer(colHeadings, "\t");
final ArrayList<DataColumnSpec> colSpecs = new ArrayList<DataColumnSpec>(tk.countTokens());
while (tk.hasMoreTokens()) {
final String token = tk.nextToken().trim();
if (token.length() > 0) {
colSpecs.add(new DataColumnSpecCreator(token, DoubleCell.TYPE).createSpec());
}
}
return new DataTableSpec(colSpecs.toArray(new DataColumnSpec[colSpecs.size()]));
}
@SuppressWarnings("unchecked")
@Override
protected ImgPlusCell compute(final ImgPlusValue cellValue) throws Exception {
RealType<?> matchingType = null;
final ImgPlus img = cellValue.getImgPlus();
ImgPlus res = null;
final Interval[] intervals = m_dimSelection.getIntervals(img, img);
final int[] m_selectedDims = m_dimSelection.getSelectedDimIndices(img);
if (m_selectedDims.length < 2) {
throw new KNIPException(
"Selected dimensions do result in an Img with less than two dimensions for Img "
+ cellValue.getMetadata().getName() + ". MissingCell is created.");
}
final long[] min = new long[img.numDimensions()];
final Inset inset = new Inset(min);
for (final Interval interval : intervals) {
RandomAccessibleInterval subsetview = SubsetOperations.subsetview(img, interval);
ImgPlusMetadata meta =
MetadataUtil
.copyAndCleanImgPlusMetadata(interval, img,
new DefaultImgMetadata(subsetview.numDimensions()));
try {
matchingType =
m_macro.runOn(new ImgPlus<T>(new ImgView<T>(subsetview, img.factory()), meta),
matchingType);
} catch (UntransformableIJTypeException e) {
- throw new KNIPRuntimeException(e.getMessage());
+ throw new KNIPRuntimeException(e.getMessage(), e);
} catch (KNIPRuntimeException e) {
throw e;
} catch (Exception e) {
throw new KNIPRuntimeException(
- "The specified macro has thrown an error while execution. Make sure that the used plugins are available in the selected IJ1 plugin folder!");
+ "The specified macro has thrown an error while execution. Make sure that the used plugins are available in the selected IJ1 plugin folder! See KNIME Log for details!",
+ e);
}
interval.min(min);
if (res == null) {
final long[] dims = new long[img.numDimensions()];
img.dimensions(dims);
for (int i = 0; i < m_selectedDims.length; i++) {
dims[m_selectedDims[i]] = m_macro.resImgPlus().dimension(i);
}
res =
new ImgPlus(img.factory().create(dims,
m_macro.resImgPlus().firstElement().createVariable()),
img);
}
inset.compute(m_macro.resImgPlus(), res);
// fill result table if available
if (m_macro.resTable() != null) {
if (m_resTableContainer == null) {
final DataTableSpec spec = createResultTableSpec(m_macro.resTable());
if (spec != null) {
m_resTableContainer = m_exec.createDataContainer(spec);
} else {
m_resTableContainer = null;
}
}
if (m_resTableContainer != null) {
final int numCols = m_resTableContainer.getTableSpec().getNumColumns();
final int[] colIndices = new int[numCols];
for (int i = 0; i < colIndices.length; i++) {
colIndices[i] =
m_macro.resTable().getColumnIndex(m_resTableContainer.getTableSpec()
.getColumnSpec(i).getName());
}
for (int r = 0; r < m_macro.resTable().getCounter(); r++) {
final DoubleCell[] cells = new DoubleCell[numCols];
for (int c = 0; c < cells.length; c++) {
cells[c] = new DoubleCell(m_macro.resTable().getValueAsDouble(colIndices[c], r));
}
String rowKey;
if (intervals.length > 1) {
rowKey = m_currentRowKey + "#" + Arrays.toString(min) + "#" + r;
} else {
rowKey = m_currentRowKey + "#" + r;
}
m_resTableContainer.addRowToTable(new DefaultRow(rowKey, cells));
}
}
}
}
return m_imgCellFactory.createCell(res);
}
/**
* {@inheritDoc}
*/
@Override
protected void computeDataRow(final DataRow row) {
m_currentRowKey = row.getKey().toString();
}
@Override
protected void addSettingsModels(final List<SettingsModel> settingsModels) {
settingsModels.add(m_macroSelection);
settingsModels.add(m_dimSelection);
settingsModels.add(m_flowVarCode);
}
};
}
/**
* {@inheritDoc}
*/
@Override
protected ValueToCellNodeDialog<ImgPlusValue> createNodeDialog() {
return new ValueToCellNodeDialog<ImgPlusValue>() {
@SuppressWarnings("unchecked")
@Override
public void addDialogComponents() {
//TODO make macros a extension point
final Map<String, Class<?>> pool = new LinkedHashMap<String, Class<?>>();
pool.put("Enhance Local Constract (CLAHE)", CLAHEIJMacro.class);
pool.put("Pure Code", PureCodeIJMacro.class);
pool.put("Gaussian Blur", GaussianBlurIJMacro.class);
pool.put("Find Edges", FindEdgesIJMacro.class);
pool.put("Find Maxima", FindMaximaIJMacro.class);
pool.put("Analyze Particles", AnalyzeParticlesIJMacro.class);
pool.put("Sharpen", SharpenIJMacro.class);
pool.put("Watersched", WatershedIJMacro.class);
pool.put("Substract Background", SubstractBackgroundIJMacro.class);
addDialogComponent("Options", "Snippets", new DialogComponentSerializableConfiguration(
createMacroSelectionModel(), pool));
addDialogComponent("Options", "", new DialogComponentDimSelection(createDimSelectionModel(),
"Dimension Selection", 2, 3));
// hidden dialog component to be able to controll the imagej
// macro node by flow variables
addDialogComponent("Options", "Snippets", new DialogComponent(createFlowVariableControllableCode()) {
@Override
protected void validateSettingsBeforeSave() throws InvalidSettingsException {
}
@Override
protected void updateComponent() {
}
@Override
public void setToolTipText(final String text) {
}
@Override
protected void setEnabledComponents(final boolean enabled) {
}
@Override
protected void checkConfigurabilityBeforeLoad(final PortObjectSpec[] specs)
throws NotConfigurableException {
}
});
}
};
}
}
| false | true | public ValueToCellNodeModel<ImgPlusValue, ImgPlusCell> createNodeModel() {
return new ValueToCellNodeModel<ImgPlusValue, ImgPlusCell>(new PortType[]{},
new PortType[]{BufferedDataTable.TYPE}) {
private final SettingsModelSerializableObjects<SerializableSetting<String>> m_macroSelection =
createMacroSelectionModel();
private final SettingsModelDimSelection m_dimSelection = createDimSelectionModel();
private final SettingsModelString m_flowVarCode = createFlowVariableControllableCode();
private IJMacro m_macro;
private ImgPlusCellFactory m_imgCellFactory;
private BufferedDataContainer m_resTableContainer;
private String m_currentRowKey;
private ExecutionContext m_exec;
/**
* {@inheritDoc}
*/
@Override
protected PortObjectSpec[] configure(final PortObjectSpec[] inSpecs) throws InvalidSettingsException {
final PortObjectSpec firstSpec = super.configure(inSpecs)[0];
return new PortObjectSpec[]{firstSpec, null};
}
/**
* {@inheritDoc}
*/
@Override
protected PortObject[] execute(final PortObject[] inObjects, final ExecutionContext exec) throws Exception {
final PortObject firstPort = super.execute(inObjects, exec)[0];
PortObject secondPort = null;
if (m_resTableContainer == null) {
m_resTableContainer = exec.createDataContainer(new DataTableSpec());
}
m_resTableContainer.close();
secondPort = m_resTableContainer.getTable();
return new PortObject[]{firstPort, secondPort};
}
@Override
protected void prepareExecute(final ExecutionContext exec) {
final List<SerializableSetting<String>> conf = m_macroSelection.getObjects();
String code = "";
if (m_flowVarCode.getStringValue().length() == 0) {
for (final SerializableSetting<String> fc : conf) {
code += fc.get();
}
} else {
setWarningMessage("IJ macro code controlled by a flow variable!");
code = m_flowVarCode.getStringValue();
m_flowVarCode.setStringValue("");
}
m_macro = new IJMacro(code);
m_imgCellFactory = new ImgPlusCellFactory(exec);
m_exec = exec;
m_resTableContainer = null;
System.setProperty("plugins.dir", IJ1Preferences.getIJ1PluginPath());
}
private DataTableSpec createResultTableSpec(final ResultsTable table) {
final String colHeadings = table.getColumnHeadings();
final StringTokenizer tk = new StringTokenizer(colHeadings, "\t");
final ArrayList<DataColumnSpec> colSpecs = new ArrayList<DataColumnSpec>(tk.countTokens());
while (tk.hasMoreTokens()) {
final String token = tk.nextToken().trim();
if (token.length() > 0) {
colSpecs.add(new DataColumnSpecCreator(token, DoubleCell.TYPE).createSpec());
}
}
return new DataTableSpec(colSpecs.toArray(new DataColumnSpec[colSpecs.size()]));
}
@SuppressWarnings("unchecked")
@Override
protected ImgPlusCell compute(final ImgPlusValue cellValue) throws Exception {
RealType<?> matchingType = null;
final ImgPlus img = cellValue.getImgPlus();
ImgPlus res = null;
final Interval[] intervals = m_dimSelection.getIntervals(img, img);
final int[] m_selectedDims = m_dimSelection.getSelectedDimIndices(img);
if (m_selectedDims.length < 2) {
throw new KNIPException(
"Selected dimensions do result in an Img with less than two dimensions for Img "
+ cellValue.getMetadata().getName() + ". MissingCell is created.");
}
final long[] min = new long[img.numDimensions()];
final Inset inset = new Inset(min);
for (final Interval interval : intervals) {
RandomAccessibleInterval subsetview = SubsetOperations.subsetview(img, interval);
ImgPlusMetadata meta =
MetadataUtil
.copyAndCleanImgPlusMetadata(interval, img,
new DefaultImgMetadata(subsetview.numDimensions()));
try {
matchingType =
m_macro.runOn(new ImgPlus<T>(new ImgView<T>(subsetview, img.factory()), meta),
matchingType);
} catch (UntransformableIJTypeException e) {
throw new KNIPRuntimeException(e.getMessage());
} catch (KNIPRuntimeException e) {
throw e;
} catch (Exception e) {
throw new KNIPRuntimeException(
"The specified macro has thrown an error while execution. Make sure that the used plugins are available in the selected IJ1 plugin folder!");
}
interval.min(min);
if (res == null) {
final long[] dims = new long[img.numDimensions()];
img.dimensions(dims);
for (int i = 0; i < m_selectedDims.length; i++) {
dims[m_selectedDims[i]] = m_macro.resImgPlus().dimension(i);
}
res =
new ImgPlus(img.factory().create(dims,
m_macro.resImgPlus().firstElement().createVariable()),
img);
}
inset.compute(m_macro.resImgPlus(), res);
// fill result table if available
if (m_macro.resTable() != null) {
if (m_resTableContainer == null) {
final DataTableSpec spec = createResultTableSpec(m_macro.resTable());
if (spec != null) {
m_resTableContainer = m_exec.createDataContainer(spec);
} else {
m_resTableContainer = null;
}
}
if (m_resTableContainer != null) {
final int numCols = m_resTableContainer.getTableSpec().getNumColumns();
final int[] colIndices = new int[numCols];
for (int i = 0; i < colIndices.length; i++) {
colIndices[i] =
m_macro.resTable().getColumnIndex(m_resTableContainer.getTableSpec()
.getColumnSpec(i).getName());
}
for (int r = 0; r < m_macro.resTable().getCounter(); r++) {
final DoubleCell[] cells = new DoubleCell[numCols];
for (int c = 0; c < cells.length; c++) {
cells[c] = new DoubleCell(m_macro.resTable().getValueAsDouble(colIndices[c], r));
}
String rowKey;
if (intervals.length > 1) {
rowKey = m_currentRowKey + "#" + Arrays.toString(min) + "#" + r;
} else {
rowKey = m_currentRowKey + "#" + r;
}
m_resTableContainer.addRowToTable(new DefaultRow(rowKey, cells));
}
}
}
}
return m_imgCellFactory.createCell(res);
}
/**
* {@inheritDoc}
*/
@Override
protected void computeDataRow(final DataRow row) {
m_currentRowKey = row.getKey().toString();
}
@Override
protected void addSettingsModels(final List<SettingsModel> settingsModels) {
settingsModels.add(m_macroSelection);
settingsModels.add(m_dimSelection);
settingsModels.add(m_flowVarCode);
}
};
}
| public ValueToCellNodeModel<ImgPlusValue, ImgPlusCell> createNodeModel() {
return new ValueToCellNodeModel<ImgPlusValue, ImgPlusCell>(new PortType[]{},
new PortType[]{BufferedDataTable.TYPE}) {
private final SettingsModelSerializableObjects<SerializableSetting<String>> m_macroSelection =
createMacroSelectionModel();
private final SettingsModelDimSelection m_dimSelection = createDimSelectionModel();
private final SettingsModelString m_flowVarCode = createFlowVariableControllableCode();
private IJMacro m_macro;
private ImgPlusCellFactory m_imgCellFactory;
private BufferedDataContainer m_resTableContainer;
private String m_currentRowKey;
private ExecutionContext m_exec;
/**
* {@inheritDoc}
*/
@Override
protected PortObjectSpec[] configure(final PortObjectSpec[] inSpecs) throws InvalidSettingsException {
final PortObjectSpec firstSpec = super.configure(inSpecs)[0];
return new PortObjectSpec[]{firstSpec, null};
}
/**
* {@inheritDoc}
*/
@Override
protected PortObject[] execute(final PortObject[] inObjects, final ExecutionContext exec) throws Exception {
final PortObject firstPort = super.execute(inObjects, exec)[0];
PortObject secondPort = null;
if (m_resTableContainer == null) {
m_resTableContainer = exec.createDataContainer(new DataTableSpec());
}
m_resTableContainer.close();
secondPort = m_resTableContainer.getTable();
return new PortObject[]{firstPort, secondPort};
}
@Override
protected void prepareExecute(final ExecutionContext exec) {
final List<SerializableSetting<String>> conf = m_macroSelection.getObjects();
String code = "";
if (m_flowVarCode.getStringValue().length() == 0) {
for (final SerializableSetting<String> fc : conf) {
code += fc.get();
}
} else {
setWarningMessage("IJ macro code controlled by a flow variable!");
code = m_flowVarCode.getStringValue();
m_flowVarCode.setStringValue("");
}
m_macro = new IJMacro(code);
m_imgCellFactory = new ImgPlusCellFactory(exec);
m_exec = exec;
m_resTableContainer = null;
System.setProperty("plugins.dir", IJ1Preferences.getIJ1PluginPath());
}
private DataTableSpec createResultTableSpec(final ResultsTable table) {
final String colHeadings = table.getColumnHeadings();
final StringTokenizer tk = new StringTokenizer(colHeadings, "\t");
final ArrayList<DataColumnSpec> colSpecs = new ArrayList<DataColumnSpec>(tk.countTokens());
while (tk.hasMoreTokens()) {
final String token = tk.nextToken().trim();
if (token.length() > 0) {
colSpecs.add(new DataColumnSpecCreator(token, DoubleCell.TYPE).createSpec());
}
}
return new DataTableSpec(colSpecs.toArray(new DataColumnSpec[colSpecs.size()]));
}
@SuppressWarnings("unchecked")
@Override
protected ImgPlusCell compute(final ImgPlusValue cellValue) throws Exception {
RealType<?> matchingType = null;
final ImgPlus img = cellValue.getImgPlus();
ImgPlus res = null;
final Interval[] intervals = m_dimSelection.getIntervals(img, img);
final int[] m_selectedDims = m_dimSelection.getSelectedDimIndices(img);
if (m_selectedDims.length < 2) {
throw new KNIPException(
"Selected dimensions do result in an Img with less than two dimensions for Img "
+ cellValue.getMetadata().getName() + ". MissingCell is created.");
}
final long[] min = new long[img.numDimensions()];
final Inset inset = new Inset(min);
for (final Interval interval : intervals) {
RandomAccessibleInterval subsetview = SubsetOperations.subsetview(img, interval);
ImgPlusMetadata meta =
MetadataUtil
.copyAndCleanImgPlusMetadata(interval, img,
new DefaultImgMetadata(subsetview.numDimensions()));
try {
matchingType =
m_macro.runOn(new ImgPlus<T>(new ImgView<T>(subsetview, img.factory()), meta),
matchingType);
} catch (UntransformableIJTypeException e) {
throw new KNIPRuntimeException(e.getMessage(), e);
} catch (KNIPRuntimeException e) {
throw e;
} catch (Exception e) {
throw new KNIPRuntimeException(
"The specified macro has thrown an error while execution. Make sure that the used plugins are available in the selected IJ1 plugin folder! See KNIME Log for details!",
e);
}
interval.min(min);
if (res == null) {
final long[] dims = new long[img.numDimensions()];
img.dimensions(dims);
for (int i = 0; i < m_selectedDims.length; i++) {
dims[m_selectedDims[i]] = m_macro.resImgPlus().dimension(i);
}
res =
new ImgPlus(img.factory().create(dims,
m_macro.resImgPlus().firstElement().createVariable()),
img);
}
inset.compute(m_macro.resImgPlus(), res);
// fill result table if available
if (m_macro.resTable() != null) {
if (m_resTableContainer == null) {
final DataTableSpec spec = createResultTableSpec(m_macro.resTable());
if (spec != null) {
m_resTableContainer = m_exec.createDataContainer(spec);
} else {
m_resTableContainer = null;
}
}
if (m_resTableContainer != null) {
final int numCols = m_resTableContainer.getTableSpec().getNumColumns();
final int[] colIndices = new int[numCols];
for (int i = 0; i < colIndices.length; i++) {
colIndices[i] =
m_macro.resTable().getColumnIndex(m_resTableContainer.getTableSpec()
.getColumnSpec(i).getName());
}
for (int r = 0; r < m_macro.resTable().getCounter(); r++) {
final DoubleCell[] cells = new DoubleCell[numCols];
for (int c = 0; c < cells.length; c++) {
cells[c] = new DoubleCell(m_macro.resTable().getValueAsDouble(colIndices[c], r));
}
String rowKey;
if (intervals.length > 1) {
rowKey = m_currentRowKey + "#" + Arrays.toString(min) + "#" + r;
} else {
rowKey = m_currentRowKey + "#" + r;
}
m_resTableContainer.addRowToTable(new DefaultRow(rowKey, cells));
}
}
}
}
return m_imgCellFactory.createCell(res);
}
/**
* {@inheritDoc}
*/
@Override
protected void computeDataRow(final DataRow row) {
m_currentRowKey = row.getKey().toString();
}
@Override
protected void addSettingsModels(final List<SettingsModel> settingsModels) {
settingsModels.add(m_macroSelection);
settingsModels.add(m_dimSelection);
settingsModels.add(m_flowVarCode);
}
};
}
|
diff --git a/src/main/java/me/desht/dhutils/ExperienceManager.java b/src/main/java/me/desht/dhutils/ExperienceManager.java
index 6f28b9f..3303bfe 100644
--- a/src/main/java/me/desht/dhutils/ExperienceManager.java
+++ b/src/main/java/me/desht/dhutils/ExperienceManager.java
@@ -1,207 +1,212 @@
package me.desht.dhutils;
import java.util.Arrays;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
/**
* @author desht
*
* Adapted from ExperienceUtils code originally in ScrollingMenuSign.
*
* Credit to nisovin (http://forums.bukkit.org/threads/experienceutils-make-giving-taking-exp-a-bit-more-intuitive.54450/#post-1067480)
* for an implementation that avoids the problems of getTotalExperience(), which doesn't work properly after a player has enchanted something.
*/
public class ExperienceManager {
// this is to stop the lookup tables growing without control
private static int hardMaxLevel = 100000;
private static int xpRequiredForNextLevel[];
private static int xpTotalToReachLevel[];
private final String playerName;
static {
// 25 is an arbitrary value for the initial table size - the actual value isn't critically
// important since the tables are resized as needed.
initLookupTables(25);
}
public static int getHardMaxLevel() {
return hardMaxLevel;
}
public static void setHardMaxLevel(int hardMaxLevel) {
ExperienceManager.hardMaxLevel = hardMaxLevel;
}
/**
* Initialise the XP lookup tables. Basing this on observations noted in https://bukkit.atlassian.net/browse/BUKKIT-47
*
* 7 xp to get to level 1, 17 to level 2, 31 to level 3...
* At each level, the increment to get to the next level increases alternately by 3 and 4
*
* @param maxLevel The highest level handled by the lookup tables
*/
private static void initLookupTables(int maxLevel) {
xpRequiredForNextLevel = new int[maxLevel];
xpTotalToReachLevel = new int[maxLevel];
xpTotalToReachLevel[0] = 0;
// Code valid for MC 1.2 and earlier
// int incr = 7;
// for (int i = 1; i < xpTotalToReachLevel.length; i++) {
// xpRequiredForNextLevel[i - 1] = incr;
// xpTotalToReachLevel[i] = xpTotalToReachLevel[i - 1] + incr;
// incr += (i % 2 == 0) ? 4 : 3;
// }
// Valid for MC 1.3 and later
int incr = 17;
for (int i = 1; i < xpTotalToReachLevel.length; i++) {
xpRequiredForNextLevel[i - 1] = incr;
xpTotalToReachLevel[i] = xpTotalToReachLevel[i - 1] + incr;
- incr += (i >= 16) ? 3 : 0;
+ if (i >= 30) {
+ incr += 7;
+ } else if (i >= 16) {
+ incr += 3;
+ }
}
+ xpRequiredForNextLevel[xpRequiredForNextLevel.length - 1] = incr;
}
/**
* Calculate the level that the given XP quantity corresponds to, without using the lookup tables.
* This is needed if getLevelForExp() is called with an XP quantity beyond the range of the existing
* lookup tables.
*
* @param exp
* @return
*/
private static int calculateLevelForExp(int exp) {
int level = 0;
int curExp = 7; // level 1
int incr = 10;
while (curExp <= exp) {
curExp += incr;
level++;
incr += (level % 2 == 0) ? 3 : 4;
}
return level;
}
/**
* Create a new ExperienceManager for the given player.
*
* @param player The player for this ExperienceManager object
*/
public ExperienceManager(Player player) {
this.playerName = player.getName();
getPlayer(); // ensure it's a valid player name
}
/**
* Get the Player associated with this ExperienceManager.
*
* @return the Player object
* @throws IllegalStateException if the player is no longer online
*/
public Player getPlayer() {
Player p = Bukkit.getPlayer(playerName);
if (p == null) {
throw new IllegalStateException("Player " + playerName + " is not online");
}
return p;
}
/**
* Adjust the player's XP by the given amount in an intelligent fashion. Works around
* some of the non-intuitive behaviour of the basic Bukkit player.giveExp() method.
*
* @param amt Amount of XP, may be negative
*/
public void changeExp(int amt) {
setExp(getCurrentExp(), amt);
}
/**
* Set the player's experience
*
* @param amt Amount of XP, should not be negative
*/
public void setExp(int amt) {
setExp(0, amt);
}
private void setExp(int base, int amt) {
int xp = base + amt;
if (xp < 0) xp = 0;
Player player = getPlayer();
int curLvl = player.getLevel();
int newLvl = getLevelForExp(xp);
if (curLvl != newLvl) {
player.setLevel(newLvl);
}
float pct = ((float)(xp - getXpForLevel(newLvl)) / (float)xpRequiredForNextLevel[newLvl]);
player.setExp(pct);
}
/**
* Get the player's current XP total.
*
* @return the player's total XP
*/
public int getCurrentExp() {
Player player = getPlayer();
int lvl = player.getLevel();
int cur = getXpForLevel(lvl) + (int) Math.round(xpRequiredForNextLevel[lvl] * player.getExp());
return cur;
}
/**
* Checks if the player has the given amount of XP.
*
* @param amt The amount to check for.
* @return true if the player has enough XP, false otherwise
*/
public boolean hasExp(int amt) {
return getCurrentExp() >= amt;
}
/**
* Get the level that the given amount of XP falls within.
*
* @param exp The amount to check for.
* @return The level that a player with this amount total XP would be.
*/
public int getLevelForExp(int exp) {
if (exp <= 0) return 0;
if (exp > xpTotalToReachLevel[xpTotalToReachLevel.length - 1]) {
// need to extend the lookup tables
int newMax = calculateLevelForExp(exp) * 2;
if (newMax > hardMaxLevel) {
throw new IllegalArgumentException("Level for exp " + exp + " > hard max level " + hardMaxLevel);
}
initLookupTables(newMax);
}
int pos = Arrays.binarySearch(xpTotalToReachLevel, exp);
return pos < 0 ? -pos - 2 : pos;
}
/**
* Return the total XP needed to be the given level.
*
* @param level The level to check for.
* @return The amount of XP needed for the level.
*/
public int getXpForLevel(int level) {
if (level > hardMaxLevel) {
throw new IllegalArgumentException("Level " + level + " > hard max level " + hardMaxLevel);
}
if (level >= xpTotalToReachLevel.length) {
initLookupTables(level * 2);
}
return xpTotalToReachLevel[level];
}
}
| false | true | private static void initLookupTables(int maxLevel) {
xpRequiredForNextLevel = new int[maxLevel];
xpTotalToReachLevel = new int[maxLevel];
xpTotalToReachLevel[0] = 0;
// Code valid for MC 1.2 and earlier
// int incr = 7;
// for (int i = 1; i < xpTotalToReachLevel.length; i++) {
// xpRequiredForNextLevel[i - 1] = incr;
// xpTotalToReachLevel[i] = xpTotalToReachLevel[i - 1] + incr;
// incr += (i % 2 == 0) ? 4 : 3;
// }
// Valid for MC 1.3 and later
int incr = 17;
for (int i = 1; i < xpTotalToReachLevel.length; i++) {
xpRequiredForNextLevel[i - 1] = incr;
xpTotalToReachLevel[i] = xpTotalToReachLevel[i - 1] + incr;
incr += (i >= 16) ? 3 : 0;
}
}
| private static void initLookupTables(int maxLevel) {
xpRequiredForNextLevel = new int[maxLevel];
xpTotalToReachLevel = new int[maxLevel];
xpTotalToReachLevel[0] = 0;
// Code valid for MC 1.2 and earlier
// int incr = 7;
// for (int i = 1; i < xpTotalToReachLevel.length; i++) {
// xpRequiredForNextLevel[i - 1] = incr;
// xpTotalToReachLevel[i] = xpTotalToReachLevel[i - 1] + incr;
// incr += (i % 2 == 0) ? 4 : 3;
// }
// Valid for MC 1.3 and later
int incr = 17;
for (int i = 1; i < xpTotalToReachLevel.length; i++) {
xpRequiredForNextLevel[i - 1] = incr;
xpTotalToReachLevel[i] = xpTotalToReachLevel[i - 1] + incr;
if (i >= 30) {
incr += 7;
} else if (i >= 16) {
incr += 3;
}
}
xpRequiredForNextLevel[xpRequiredForNextLevel.length - 1] = incr;
}
|
diff --git a/src/org/newdawn/slick/GameContainer.java b/src/org/newdawn/slick/GameContainer.java
index cd4e799..63ddaf9 100644
--- a/src/org/newdawn/slick/GameContainer.java
+++ b/src/org/newdawn/slick/GameContainer.java
@@ -1,511 +1,511 @@
package org.newdawn.slick;
import java.util.Properties;
import org.lwjgl.Sys;
import org.lwjgl.input.Cursor;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.GL11;
import org.newdawn.slick.gui.GUIContext;
import org.newdawn.slick.openal.SoundStore;
import org.newdawn.slick.opengl.ImageData;
import org.newdawn.slick.util.Log;
import org.newdawn.slick.util.ResourceLoader;
/**
* A generic game container that handles the game loop, fps recording and
* managing the input system
*
* @author kevin
*/
public abstract class GameContainer implements GUIContext {
/** The time the last frame was rendered */
private long lastFrame;
/** The last time the FPS recorded */
private long lastFPS;
/** The last recorded FPS */
private int recordedFPS;
/** The current count of FPS */
private int fps;
/** True if we're currently running the game loop */
protected boolean running = true;
/** The width of the display */
protected int width;
/** The height of the display */
protected int height;
/** The game being managed */
protected Game game;
/** The default font to use in the graphics context */
private Font defaultFont;
/** The graphics context to be passed to the game */
private Graphics graphics;
/** The input system to pass to the game */
private Input input;
/** The FPS we want to lock to */
private int targetFPS = -1;
/** True if we should show the fps */
private boolean showFPS = true;
/** The minimum logic update interval */
private long minimumLogicInterval = 1;
/** The stored delta */
private long storedDelta;
/** The maximum logic update interval */
private long maximumLogicInterval = 0;
/** The last game started */
private Game lastGame;
/**
* Create a new game container wrapping a given game
*
* @param game The game to be wrapped
*/
protected GameContainer(Game game) {
this.game = game;
lastFrame = getTime();
getBuildVersion();
Log.checkVerboseLogSetting();
}
/**
* Renitialise the game and the context in which it's being rendered
*
* @throws SlickException Indicates a failure rerun initialisation routines
*/
public void reinit() throws SlickException {
}
/**
* Get the build number of slick
*
* @return The build number of slick
*/
public static int getBuildVersion() {
try {
Properties props = new Properties();
props.load(ResourceLoader.getResourceAsStream("version"));
int build = Integer.parseInt(props.getProperty("build"));
Log.info("Slick Build #"+build);
return build;
} catch (Exception e) {
Log.error("Unable to determine Slick build number");
return -1;
}
}
/**
* Get the default system font
*
* @return The default system font
*/
public Font getDefaultFont() {
return defaultFont;
}
/**
* Check if sound effects are enabled
*
* @return True if sound effects are enabled
*/
public boolean isSoundOn() {
return SoundStore.get().soundsOn();
}
/**
* Check if music is enabled
*
* @return True if music is enabled
*/
public boolean isMusicOn() {
return SoundStore.get().musicOn();
}
/**
* Indicate whether music should be enabled
*
* @param on True if music should be enabled
*/
public void setMusicOn(boolean on) {
SoundStore.get().setMusicOn(on);
}
/**
* Indicate whether sound effects should be enabled
*
* @param on True if sound effects should be enabled
*/
public void setSoundOn(boolean on) {
SoundStore.get().setSoundsOn(on);
}
/**
* Get the width of the standard screen resolution
*
* @return The screen width
*/
public abstract int getScreenWidth();
/**
* Get the height of the standard screen resolution
*
* @return The screen height
*/
public abstract int getScreenHeight();
/**
* Get the width of the game canvas
*
* @return The width of the game canvas
*/
public int getWidth() {
return width;
}
/**
* Get the height of the game canvas
*
* @return The height of the game canvas
*/
public int getHeight() {
return height;
}
/**
* Set the icon to be displayed if possible in this type of
* container
*
* @param ref The reference to the icon to be displayed
* @throws SlickException Indicates a failure to load the icon
*/
public abstract void setIcon(String ref) throws SlickException;
/**
* Set the icons to be used for this application. Note that the size of the icon
* defines how it will be used. Important ones to note
*
* Windows window icon must be 16x16
* Windows alt-tab icon must be 24x24 or 32x32 depending on Windows version (XP=32)
*
* @param refs The reference to the icon to be displayed
* @throws SlickException Indicates a failure to load the icon
*/
public abstract void setIcons(String[] refs) throws SlickException;
/**
* Get the accurate system time
*
* @return The system time in milliseconds
*/
public long getTime() {
return (Sys.getTime() * 1000) / Sys.getTimerResolution();
}
/**
* Sleep for a given period
*
* @param milliseconds The period to sleep for in milliseconds
*/
public void sleep(int milliseconds) {
long target = getTime()+milliseconds;
while (getTime() < target) {
Thread.yield();
}
}
/**
* Set the mouse cursor to be displayed - this is a hardware cursor and hence
* shouldn't have any impact on FPS.
*
* @param ref The location of the image to be loaded for the cursor
* @param hotSpotX The x coordinate of the hotspot within the cursor image
* @param hotSpotY The y coordinate of the hotspot within the cursor image
* @throws SlickException Indicates a failure to load the cursor image or create the hardware cursor
*/
public abstract void setMouseCursor(String ref, int hotSpotX, int hotSpotY) throws SlickException;
/**
* Set the mouse cursor to be displayed - this is a hardware cursor and hence
* shouldn't have any impact on FPS.
*
* @param data The image data from which the cursor can be construted
* @param hotSpotX The x coordinate of the hotspot within the cursor image
* @param hotSpotY The y coordinate of the hotspot within the cursor image
* @throws SlickException Indicates a failure to load the cursor image or create the hardware cursor
*/
public abstract void setMouseCursor(ImageData data, int hotSpotX, int hotSpotY) throws SlickException;
/**
* Set the mouse cursor to be displayed - this is a hardware cursor and hence
* shouldn't have any impact on FPS.
*
* @param cursor The cursor to use
* @param hotSpotX The x coordinate of the hotspot within the cursor image
* @param hotSpotY The y coordinate of the hotspot within the cursor image
* @throws SlickException Indicates a failure to load the cursor image or create the hardware cursor
*/
public abstract void setMouseCursor(Cursor cursor, int hotSpotX, int hotSpotY) throws SlickException;
/**
* Get the input system
*
* @return The input system available to this game container
*/
public Input getInput() {
return input;
}
/**
* Get the current recorded FPS (frames per second)
*
* @return The current FPS
*/
public int getFPS() {
return recordedFPS;
}
/**
* Indicate whether mouse cursor should be grabbed or not
*
* @param grabbed True if mouse cursor should be grabbed
*/
public abstract void setMouseGrabbed(boolean grabbed);
/**
* Retrieve the time taken to render the last frame, i.e. the change in time - delta.
*
* @return The time taken to render the last frame
*/
protected int getDelta() {
long time = getTime();
int delta = (int) (time - lastFrame);
lastFrame = time;
return delta;
}
/**
* Updated the FPS counter
*/
protected void updateFPS() {
if (getTime() - lastFPS > 1000) {
lastFPS = getTime();
recordedFPS = fps;
fps = 0;
}
fps++;
}
/**
* Set the minimum amount of time in milliseonds that has to
* pass before update() is called on the container game. This gives
* a way to limit logic updates compared to renders.
*
* @param interval The minimum interval between logic updates
*/
public void setMinimumLogicUpdateInterval(int interval) {
minimumLogicInterval = interval;
}
/**
* Set the maximum amount of time in milliseconds that can passed
* into the update method. Useful for collision detection without
* sweeping.
*
* @param interval The maximum interval between logic updates
*/
public void setMaximumLogicUpdateInterval(int interval) {
maximumLogicInterval = interval;
}
/**
* Update and render the game
*
* @param delta The change in time since last update and render
* @throws SlickException Indicates an internal fault to the game.
*/
protected void updateAndRender(int delta) throws SlickException {
storedDelta += delta;
input.poll(width, height);
SoundStore.get().poll(delta);
if (storedDelta >= minimumLogicInterval) {
try {
if (maximumLogicInterval != 0) {
long cycles = storedDelta / maximumLogicInterval;
for (int i=0;i<cycles;i++) {
game.update(this, (int) maximumLogicInterval);
}
game.update(this, (int) (delta % maximumLogicInterval));
} else {
game.update(this, (int) storedDelta);
}
storedDelta = 0;
} catch (Throwable e) {
Log.error(e);
throw new SlickException("Game.update() failure - check the game code.");
}
}
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT);
GL11.glLoadIdentity();
graphics.resetFont();
graphics.resetLineWidth();
graphics.setAntiAlias(false);
try {
game.render(this, graphics);
} catch (Throwable e) {
Log.error(e);
throw new SlickException("Game.render() failure - check the game code.");
}
graphics.resetTransform();
if (showFPS) {
defaultFont.drawString(10, 10, "FPS: "+recordedFPS);
}
if (targetFPS != -1) {
- Display.sync2(targetFPS);
+ Display.sync(targetFPS);
}
}
/**
* Initialise the GL context
*/
protected void initGL() {
Log.info("Starting display "+width+"x"+height);
String extensions = GL11.glGetString(GL11.GL_EXTENSIONS);
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glShadeModel(GL11.GL_SMOOTH);
GL11.glDisable(GL11.GL_DEPTH_TEST);
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
GL11.glClearDepth(1);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glViewport(0,0,width,height);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
if (input == null) {
input = new Input(height);
}
input.init(height);
input.removeListener(lastGame);
input.addListener(game);
lastGame = game;
}
/**
* Initialise the system components, OpenGL and OpenAL.
*
* @throws SlickException Indicates a failure to create a native handler
*/
protected void initSystem() throws SlickException {
initGL();
graphics = new Graphics(width, height);
defaultFont = graphics.getFont();
}
/**
* Enter the orthographic mode
*/
protected void enterOrtho() {
enterOrtho(width, height);
}
/**
* Indicate whether the container should show the FPS
*
* @param show True if the container should show the FPS
*/
public void setShowFPS(boolean show) {
showFPS = show;
}
/**
* Check if the FPS is currently showing
*
* @return True if the FPS is showing
*/
public boolean isShowingFPS() {
return showFPS;
}
/**
* Set the target fps we're hoping to get
*
* @param fps The target fps we're hoping to get
*/
public void setTargetFrameRate(int fps) {
targetFPS = fps;
}
/**
* Indicate whether the display should be synced to the
* vertical refresh (stops tearing)
*
* @param vsync True if we want to sync to vertical refresh
*/
public void setVSync(boolean vsync) {
Display.setVSyncEnabled(vsync);
}
/**
* True if the game is running
*
* @return True if the game is running
*/
protected boolean running() {
return running;
}
/**
* Inidcate we want verbose logging
*
* @param verbose True if we want verbose logging (INFO and DEBUG)
*/
public void setVerbose(boolean verbose) {
Log.setVerbose(verbose);
}
/**
* Cause the game to exit and shutdown cleanly
*/
public void exit() {
running = false;
}
/**
* Check if the game currently has focus
*
* @return True if the game currently has focus
*/
public abstract boolean hasFocus();
/**
* Enter the orthographic mode
*
* @param xsize The size of the panel being used
* @param ysize The size of the panel being used
*/
protected void enterOrtho(int xsize, int ysize) {
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glLoadIdentity();
GL11.glOrtho(0, width, height, 0, 1, -1);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glTranslatef((width-xsize)/2,
(height-ysize)/2,0);
}
}
| true | true | protected void updateAndRender(int delta) throws SlickException {
storedDelta += delta;
input.poll(width, height);
SoundStore.get().poll(delta);
if (storedDelta >= minimumLogicInterval) {
try {
if (maximumLogicInterval != 0) {
long cycles = storedDelta / maximumLogicInterval;
for (int i=0;i<cycles;i++) {
game.update(this, (int) maximumLogicInterval);
}
game.update(this, (int) (delta % maximumLogicInterval));
} else {
game.update(this, (int) storedDelta);
}
storedDelta = 0;
} catch (Throwable e) {
Log.error(e);
throw new SlickException("Game.update() failure - check the game code.");
}
}
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT);
GL11.glLoadIdentity();
graphics.resetFont();
graphics.resetLineWidth();
graphics.setAntiAlias(false);
try {
game.render(this, graphics);
} catch (Throwable e) {
Log.error(e);
throw new SlickException("Game.render() failure - check the game code.");
}
graphics.resetTransform();
if (showFPS) {
defaultFont.drawString(10, 10, "FPS: "+recordedFPS);
}
if (targetFPS != -1) {
Display.sync2(targetFPS);
}
}
| protected void updateAndRender(int delta) throws SlickException {
storedDelta += delta;
input.poll(width, height);
SoundStore.get().poll(delta);
if (storedDelta >= minimumLogicInterval) {
try {
if (maximumLogicInterval != 0) {
long cycles = storedDelta / maximumLogicInterval;
for (int i=0;i<cycles;i++) {
game.update(this, (int) maximumLogicInterval);
}
game.update(this, (int) (delta % maximumLogicInterval));
} else {
game.update(this, (int) storedDelta);
}
storedDelta = 0;
} catch (Throwable e) {
Log.error(e);
throw new SlickException("Game.update() failure - check the game code.");
}
}
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT);
GL11.glLoadIdentity();
graphics.resetFont();
graphics.resetLineWidth();
graphics.setAntiAlias(false);
try {
game.render(this, graphics);
} catch (Throwable e) {
Log.error(e);
throw new SlickException("Game.render() failure - check the game code.");
}
graphics.resetTransform();
if (showFPS) {
defaultFont.drawString(10, 10, "FPS: "+recordedFPS);
}
if (targetFPS != -1) {
Display.sync(targetFPS);
}
}
|
diff --git a/extensions/applib/src/org/eigenbase/applib/util/CreateTbFromSelectStmtUdp.java b/extensions/applib/src/org/eigenbase/applib/util/CreateTbFromSelectStmtUdp.java
index c77b12e62..598f575d4 100644
--- a/extensions/applib/src/org/eigenbase/applib/util/CreateTbFromSelectStmtUdp.java
+++ b/extensions/applib/src/org/eigenbase/applib/util/CreateTbFromSelectStmtUdp.java
@@ -1,178 +1,183 @@
/*
// $Id$
// Applib is a library of SQL-invocable routines for Eigenbase applications.
// Copyright (C) 2010 The Eigenbase Project
// Copyright (C) 2010 SQLstream, Inc.
// Copyright (C) 2010 DynamoBI Corporation
//
// 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.eigenbase.applib.util;
import java.sql.*;
import java.util.logging.*;
import net.sf.farrago.catalog.*;
import net.sf.farrago.runtime.*;
import net.sf.farrago.trace.*;
import org.eigenbase.applib.resource.*;
import org.eigenbase.sql.*;
/**
* [DDB-26] Create a UDP that creates a table from a generic cursor input, then
* optionally loads the table from the input cursor.<br>
*
* @author Ray Zhang
* @since Mar-18-2010
*/
public abstract class CreateTbFromSelectStmtUdp
{
//~ Static fields/initializers ---------------------------------------------
private static final Logger tracer =
FarragoTrace.getClassTracer(CreateTbFromSelectStmtUdp.class);
//~ Methods ----------------------------------------------------------------
/**
* @param sourceTbName
* @param targetSchemaName
* @param targetTableName
* @param additionalColsInfo
*
* @throws Exception
*/
public static void execute(
String targetSchemaName,
String targetTableName,
String selectStmt,
boolean shouldLoad)
throws Exception
{
FarragoRepos repos = FarragoUdrRuntime.getSession().getRepos();
String schema = targetSchemaName;
String table = targetTableName;
// validate the required input parameters.
if (((table == null) || (table.trim().length() == 0))) {
throw ApplibResource.instance().InputIsRequired.ex(
"targetTableName");
}
if (((selectStmt == null) || (selectStmt.trim().length() == 0))) {
throw ApplibResource.instance().InputIsRequired.ex("selectStmt");
}
ResultSet rs = null;
PreparedStatement ps = null;
Connection conn = null;
try {
// set up a jdbc connection
conn = DriverManager.getConnection("jdbc:default:connection");
// If schema is not specified, the udp will select the schema of the
// connection calling.
if (schema == null) {
schema =
FarragoUdrRuntime.getSession().getSessionVariables()
.schemaName;
+ // haven't called set schema before:
+ if (schema == null) {
+ throw ApplibResource.instance().InputIsRequired.ex(
+ "targetSchemaName");
+ }
}
// verify whehter the targe table is exsiting in specific schema.
ps = conn.prepareStatement(
"select count(1) from SYS_ROOT.DBA_TABLES where SCHEMA_NAME=? and TABLE_NAME=?");
ps.setString(1, schema);
ps.setString(2, table);
rs = ps.executeQuery();
int row_cnt = 0;
if (rs.next()) {
row_cnt = rs.getInt(1);
} else {
throw ApplibResource.instance().EmptyInput.ex();
}
if (row_cnt > 0) {
throw ApplibResource.instance().TableOrViewAlreadyExists.ex(
repos.getLocalizedObjectName(schema),
repos.getLocalizedObjectName(table));
}
// Create table structure based on select statement.
StringBuilder ddl = new StringBuilder();
ddl.append("create table ").append(
SqlDialect.EIGENBASE.quoteIdentifier(schema)).append(".")
.append(SqlDialect.EIGENBASE.quoteIdentifier(table)).append(" ( ");
ps = conn.prepareStatement(selectStmt);
ResultSetMetaData rsmd = ps.getMetaData();
int colNum = rsmd.getColumnCount();
int coltype;
for (int i = 1; i <= colNum; i++) {
ddl.append(
" " + rsmd.getColumnName(i) + " "
+ rsmd.getColumnTypeName(i));
coltype = rsmd.getColumnType(i);
if ((coltype == Types.VARBINARY)
|| (coltype == Types.BINARY)
|| (coltype == Types.CHAR)
|| (coltype == Types.VARCHAR))
{
// data type needs precision information
// VARBINARY, BINARY, CHAR, VARCHAR
ddl.append("(" + rsmd.getPrecision(i) + ")");
} else if (coltype == Types.DECIMAL) {
// DECIMAL needs precision and scale information
ddl.append(
"(" + rsmd.getPrecision(i) + ","
+ rsmd.getScale(i) + ")");
}
ddl.append(",");
}
ddl.deleteCharAt((ddl.length() - 1));
ddl.append(" )");
tracer.info("create table statement: " + ddl.toString());
ps = conn.prepareStatement(ddl.toString());
ps.execute();
// load data from source to target table if shouldLoad equals true
if (shouldLoad) {
StringBuilder insertstmt = new StringBuilder();
insertstmt.append(
"insert into "
+ SqlDialect.EIGENBASE.quoteIdentifier(schema)).append(".")
.append(SqlDialect.EIGENBASE.quoteIdentifier(table)).append(" ")
.append(selectStmt);
tracer.info("insert statement: " + insertstmt.toString());
ps = conn.prepareStatement(insertstmt.toString());
ps.execute();
}
} finally {
if (rs != null) {
rs.close();
}
if (ps != null) {
ps.close();
}
if (conn != null) {
conn.close();
}
}
}
}
// End CreateTbFromSelectStmtUdp.java
| true | true | public static void execute(
String targetSchemaName,
String targetTableName,
String selectStmt,
boolean shouldLoad)
throws Exception
{
FarragoRepos repos = FarragoUdrRuntime.getSession().getRepos();
String schema = targetSchemaName;
String table = targetTableName;
// validate the required input parameters.
if (((table == null) || (table.trim().length() == 0))) {
throw ApplibResource.instance().InputIsRequired.ex(
"targetTableName");
}
if (((selectStmt == null) || (selectStmt.trim().length() == 0))) {
throw ApplibResource.instance().InputIsRequired.ex("selectStmt");
}
ResultSet rs = null;
PreparedStatement ps = null;
Connection conn = null;
try {
// set up a jdbc connection
conn = DriverManager.getConnection("jdbc:default:connection");
// If schema is not specified, the udp will select the schema of the
// connection calling.
if (schema == null) {
schema =
FarragoUdrRuntime.getSession().getSessionVariables()
.schemaName;
}
// verify whehter the targe table is exsiting in specific schema.
ps = conn.prepareStatement(
"select count(1) from SYS_ROOT.DBA_TABLES where SCHEMA_NAME=? and TABLE_NAME=?");
ps.setString(1, schema);
ps.setString(2, table);
rs = ps.executeQuery();
int row_cnt = 0;
if (rs.next()) {
row_cnt = rs.getInt(1);
} else {
throw ApplibResource.instance().EmptyInput.ex();
}
if (row_cnt > 0) {
throw ApplibResource.instance().TableOrViewAlreadyExists.ex(
repos.getLocalizedObjectName(schema),
repos.getLocalizedObjectName(table));
}
// Create table structure based on select statement.
StringBuilder ddl = new StringBuilder();
ddl.append("create table ").append(
SqlDialect.EIGENBASE.quoteIdentifier(schema)).append(".")
.append(SqlDialect.EIGENBASE.quoteIdentifier(table)).append(" ( ");
ps = conn.prepareStatement(selectStmt);
ResultSetMetaData rsmd = ps.getMetaData();
int colNum = rsmd.getColumnCount();
int coltype;
for (int i = 1; i <= colNum; i++) {
ddl.append(
" " + rsmd.getColumnName(i) + " "
+ rsmd.getColumnTypeName(i));
coltype = rsmd.getColumnType(i);
if ((coltype == Types.VARBINARY)
|| (coltype == Types.BINARY)
|| (coltype == Types.CHAR)
|| (coltype == Types.VARCHAR))
{
// data type needs precision information
// VARBINARY, BINARY, CHAR, VARCHAR
ddl.append("(" + rsmd.getPrecision(i) + ")");
} else if (coltype == Types.DECIMAL) {
// DECIMAL needs precision and scale information
ddl.append(
"(" + rsmd.getPrecision(i) + ","
+ rsmd.getScale(i) + ")");
}
ddl.append(",");
}
ddl.deleteCharAt((ddl.length() - 1));
ddl.append(" )");
tracer.info("create table statement: " + ddl.toString());
ps = conn.prepareStatement(ddl.toString());
ps.execute();
// load data from source to target table if shouldLoad equals true
if (shouldLoad) {
StringBuilder insertstmt = new StringBuilder();
insertstmt.append(
"insert into "
+ SqlDialect.EIGENBASE.quoteIdentifier(schema)).append(".")
.append(SqlDialect.EIGENBASE.quoteIdentifier(table)).append(" ")
.append(selectStmt);
tracer.info("insert statement: " + insertstmt.toString());
ps = conn.prepareStatement(insertstmt.toString());
ps.execute();
}
} finally {
if (rs != null) {
rs.close();
}
if (ps != null) {
ps.close();
}
if (conn != null) {
conn.close();
}
}
}
| public static void execute(
String targetSchemaName,
String targetTableName,
String selectStmt,
boolean shouldLoad)
throws Exception
{
FarragoRepos repos = FarragoUdrRuntime.getSession().getRepos();
String schema = targetSchemaName;
String table = targetTableName;
// validate the required input parameters.
if (((table == null) || (table.trim().length() == 0))) {
throw ApplibResource.instance().InputIsRequired.ex(
"targetTableName");
}
if (((selectStmt == null) || (selectStmt.trim().length() == 0))) {
throw ApplibResource.instance().InputIsRequired.ex("selectStmt");
}
ResultSet rs = null;
PreparedStatement ps = null;
Connection conn = null;
try {
// set up a jdbc connection
conn = DriverManager.getConnection("jdbc:default:connection");
// If schema is not specified, the udp will select the schema of the
// connection calling.
if (schema == null) {
schema =
FarragoUdrRuntime.getSession().getSessionVariables()
.schemaName;
// haven't called set schema before:
if (schema == null) {
throw ApplibResource.instance().InputIsRequired.ex(
"targetSchemaName");
}
}
// verify whehter the targe table is exsiting in specific schema.
ps = conn.prepareStatement(
"select count(1) from SYS_ROOT.DBA_TABLES where SCHEMA_NAME=? and TABLE_NAME=?");
ps.setString(1, schema);
ps.setString(2, table);
rs = ps.executeQuery();
int row_cnt = 0;
if (rs.next()) {
row_cnt = rs.getInt(1);
} else {
throw ApplibResource.instance().EmptyInput.ex();
}
if (row_cnt > 0) {
throw ApplibResource.instance().TableOrViewAlreadyExists.ex(
repos.getLocalizedObjectName(schema),
repos.getLocalizedObjectName(table));
}
// Create table structure based on select statement.
StringBuilder ddl = new StringBuilder();
ddl.append("create table ").append(
SqlDialect.EIGENBASE.quoteIdentifier(schema)).append(".")
.append(SqlDialect.EIGENBASE.quoteIdentifier(table)).append(" ( ");
ps = conn.prepareStatement(selectStmt);
ResultSetMetaData rsmd = ps.getMetaData();
int colNum = rsmd.getColumnCount();
int coltype;
for (int i = 1; i <= colNum; i++) {
ddl.append(
" " + rsmd.getColumnName(i) + " "
+ rsmd.getColumnTypeName(i));
coltype = rsmd.getColumnType(i);
if ((coltype == Types.VARBINARY)
|| (coltype == Types.BINARY)
|| (coltype == Types.CHAR)
|| (coltype == Types.VARCHAR))
{
// data type needs precision information
// VARBINARY, BINARY, CHAR, VARCHAR
ddl.append("(" + rsmd.getPrecision(i) + ")");
} else if (coltype == Types.DECIMAL) {
// DECIMAL needs precision and scale information
ddl.append(
"(" + rsmd.getPrecision(i) + ","
+ rsmd.getScale(i) + ")");
}
ddl.append(",");
}
ddl.deleteCharAt((ddl.length() - 1));
ddl.append(" )");
tracer.info("create table statement: " + ddl.toString());
ps = conn.prepareStatement(ddl.toString());
ps.execute();
// load data from source to target table if shouldLoad equals true
if (shouldLoad) {
StringBuilder insertstmt = new StringBuilder();
insertstmt.append(
"insert into "
+ SqlDialect.EIGENBASE.quoteIdentifier(schema)).append(".")
.append(SqlDialect.EIGENBASE.quoteIdentifier(table)).append(" ")
.append(selectStmt);
tracer.info("insert statement: " + insertstmt.toString());
ps = conn.prepareStatement(insertstmt.toString());
ps.execute();
}
} finally {
if (rs != null) {
rs.close();
}
if (ps != null) {
ps.close();
}
if (conn != null) {
conn.close();
}
}
}
|
diff --git a/src/com/cs371m/austinrecycle/SplashScreenActivity.java b/src/com/cs371m/austinrecycle/SplashScreenActivity.java
index ec8a307..67c1de8 100644
--- a/src/com/cs371m/austinrecycle/SplashScreenActivity.java
+++ b/src/com/cs371m/austinrecycle/SplashScreenActivity.java
@@ -1,74 +1,74 @@
package com.cs371m.austinrecycle;
import android.net.ConnectivityManager;
import android.net.NetworkInfo.State;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
public class SplashScreenActivity extends Activity {
private final static String TAG = "SplashScreenActivity";
private static int TIME_OUT = 3000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
// Check if it is connecting to Internet
ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
- if(mobile.equals(State.DISCONNECTED) || mobile.equals(State.DISCONNECTING)
- || wifi.equals(State.DISCONNECTED) || wifi.equals(State.DISCONNECTING)) {
+ if(mobile.equals(State.DISCONNECTED) && mobile.equals(State.DISCONNECTING)
+ && wifi.equals(State.DISCONNECTED) && wifi.equals(State.DISCONNECTING)) {
AlertDialog.Builder connectionDialogBuilder = new AlertDialog.Builder(SplashScreenActivity.this);
connectionDialogBuilder.setTitle("Connection error");
connectionDialogBuilder.setMessage( "This app requires Internet connection.\n" +
"Please make sure you are connected to the Internet.");
connectionDialogBuilder.setNegativeButton("Try again", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Log.d(TAG, "Try again");
SplashScreenActivity.this.recreate();
}
});
connectionDialogBuilder.setPositiveButton("Go to Settings", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Log.d(TAG, "Settings");
startActivity(new Intent(Settings.ACTION_SETTINGS));
SplashScreenActivity.this.recreate();
}
});
AlertDialog connectionDialog = connectionDialogBuilder.create();
connectionDialog.show();
}
else {
Log.d(TAG, "Connected to internet");
Intent intent = new Intent(SplashScreenActivity.this, MainActivity.class);
SplashScreenActivity.this.startActivity(intent);
SplashScreenActivity.this.finish();
}
}
}, TIME_OUT);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.splash_screen, menu);
return true;
}
}
| true | true | protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
// Check if it is connecting to Internet
ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
if(mobile.equals(State.DISCONNECTED) || mobile.equals(State.DISCONNECTING)
|| wifi.equals(State.DISCONNECTED) || wifi.equals(State.DISCONNECTING)) {
AlertDialog.Builder connectionDialogBuilder = new AlertDialog.Builder(SplashScreenActivity.this);
connectionDialogBuilder.setTitle("Connection error");
connectionDialogBuilder.setMessage( "This app requires Internet connection.\n" +
"Please make sure you are connected to the Internet.");
connectionDialogBuilder.setNegativeButton("Try again", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Log.d(TAG, "Try again");
SplashScreenActivity.this.recreate();
}
});
connectionDialogBuilder.setPositiveButton("Go to Settings", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Log.d(TAG, "Settings");
startActivity(new Intent(Settings.ACTION_SETTINGS));
SplashScreenActivity.this.recreate();
}
});
AlertDialog connectionDialog = connectionDialogBuilder.create();
connectionDialog.show();
}
else {
Log.d(TAG, "Connected to internet");
Intent intent = new Intent(SplashScreenActivity.this, MainActivity.class);
SplashScreenActivity.this.startActivity(intent);
SplashScreenActivity.this.finish();
}
}
}, TIME_OUT);
}
| protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
// Check if it is connecting to Internet
ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
if(mobile.equals(State.DISCONNECTED) && mobile.equals(State.DISCONNECTING)
&& wifi.equals(State.DISCONNECTED) && wifi.equals(State.DISCONNECTING)) {
AlertDialog.Builder connectionDialogBuilder = new AlertDialog.Builder(SplashScreenActivity.this);
connectionDialogBuilder.setTitle("Connection error");
connectionDialogBuilder.setMessage( "This app requires Internet connection.\n" +
"Please make sure you are connected to the Internet.");
connectionDialogBuilder.setNegativeButton("Try again", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Log.d(TAG, "Try again");
SplashScreenActivity.this.recreate();
}
});
connectionDialogBuilder.setPositiveButton("Go to Settings", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Log.d(TAG, "Settings");
startActivity(new Intent(Settings.ACTION_SETTINGS));
SplashScreenActivity.this.recreate();
}
});
AlertDialog connectionDialog = connectionDialogBuilder.create();
connectionDialog.show();
}
else {
Log.d(TAG, "Connected to internet");
Intent intent = new Intent(SplashScreenActivity.this, MainActivity.class);
SplashScreenActivity.this.startActivity(intent);
SplashScreenActivity.this.finish();
}
}
}, TIME_OUT);
}
|
diff --git a/core/test/src/com/google/zxing/oned/CodaBarWriterTestCase.java b/core/test/src/com/google/zxing/oned/CodaBarWriterTestCase.java
index edc3e458..d621fb88 100644
--- a/core/test/src/com/google/zxing/oned/CodaBarWriterTestCase.java
+++ b/core/test/src/com/google/zxing/oned/CodaBarWriterTestCase.java
@@ -1,43 +1,43 @@
/*
* Copyright 2011 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.oned;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import org.junit.Assert;
import org.junit.Test;
/**
* @author [email protected] (Kazuki Nishiura)
*/
public final class CodaBarWriterTestCase extends Assert {
@Test
public void testEncode() throws WriterException {
// 1001001011 0 110101001 0 101011001 0 110101001 0 101001101 0 110010101 0 1101101011 0
// 1001001011
String resultStr = "0000000000" +
"1001001011011010100101010110010110101001010100110101100101010110110101101001001011"
+ "0000000000";
- BitMatrix result = new CodaBarWriter().encode("B515-3/N", BarcodeFormat.CODABAR, resultStr.length(), 0);
+ BitMatrix result = new CodaBarWriter().encode("B515-3/B", BarcodeFormat.CODABAR, resultStr.length(), 0);
for (int i = 0; i < resultStr.length(); i++) {
assertEquals("Element " + i, resultStr.charAt(i) == '1', result.get(i, 0));
}
}
}
| true | true | public void testEncode() throws WriterException {
// 1001001011 0 110101001 0 101011001 0 110101001 0 101001101 0 110010101 0 1101101011 0
// 1001001011
String resultStr = "0000000000" +
"1001001011011010100101010110010110101001010100110101100101010110110101101001001011"
+ "0000000000";
BitMatrix result = new CodaBarWriter().encode("B515-3/N", BarcodeFormat.CODABAR, resultStr.length(), 0);
for (int i = 0; i < resultStr.length(); i++) {
assertEquals("Element " + i, resultStr.charAt(i) == '1', result.get(i, 0));
}
}
| public void testEncode() throws WriterException {
// 1001001011 0 110101001 0 101011001 0 110101001 0 101001101 0 110010101 0 1101101011 0
// 1001001011
String resultStr = "0000000000" +
"1001001011011010100101010110010110101001010100110101100101010110110101101001001011"
+ "0000000000";
BitMatrix result = new CodaBarWriter().encode("B515-3/B", BarcodeFormat.CODABAR, resultStr.length(), 0);
for (int i = 0; i < resultStr.length(); i++) {
assertEquals("Element " + i, resultStr.charAt(i) == '1', result.get(i, 0));
}
}
|
diff --git a/src/somebody/is/madbro/handlers/chat/ChatSpamHandler.java b/src/somebody/is/madbro/handlers/chat/ChatSpamHandler.java
index dcb3730..885b950 100644
--- a/src/somebody/is/madbro/handlers/chat/ChatSpamHandler.java
+++ b/src/somebody/is/madbro/handlers/chat/ChatSpamHandler.java
@@ -1,95 +1,95 @@
package somebody.is.madbro.handlers.chat;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerChatEvent;
import somebody.is.madbro.AntiBot;
import somebody.is.madbro.datatrack.PlayerData;
import somebody.is.madbro.settings.Permissions;
import somebody.is.madbro.settings.Settings;
public class ChatSpamHandler {
public AntiBot antibot = null;
public ChatSpamHandler(AntiBot instance) {
antibot = instance;
// TODO Auto-generated constructor stub
}
public void handle(Player player, PlayerChatEvent event) {
try {
if (!Settings.enabled) {
return;
}
String pN = player.getName();
- if (Permissions.SPAM.getPermission(event.getPlayer())
+ if (Permissions.CHATSPAM.getPermission(event.getPlayer())
|| !Settings.enableAntiSpam) {
return;
}
if (antibot.getDataTrack().getBotTracker().autokick.contains(player
.getName())) {
player.kickPlayer(Settings.kickMsg);
event.setCancelled(true);
return;
}
if (antibot.getDataTrack().getBotTracker().autoipkick
.contains(player.getAddress().toString().split(":")[0])) {
player.kickPlayer(Settings.kickMsg);
event.setCancelled(true);
return;
}
if (antibot.getDataTrack().getChatTracker().spammyPlayers
.contains(pN)) {
event.setCancelled(true);
return;
}
if (!antibot.getDataTrack().getChatTracker().trackplayers
.containsKey(pN)) {
antibot.getDataTrack().getChatTracker().trackplayers.put(pN,
antibot.getDataTrack().getPlayer(pN, this));
} else {
try {
PlayerData pc = antibot.getDataTrack().getChatTracker().trackplayers
.get(pN);
long math = System.currentTimeMillis() - pc.lastChatMsg;
if (pc.amoumt > Settings.spamam && math < Settings.spamtime) {
antibot.getDataTrack().getChatTracker().chatspamblocked += 1;
if (Settings.notify) {
antibot.getServer().broadcastMessage(
Settings.prefix
+ "\247chas detected chat spam!");
}
if (!Settings.chatMute) {
antibot.getDataTrack().getChatTracker().trackplayers
.remove(pN);
player.kickPlayer(Settings.kickMsg);
event.setCancelled(true);
} else {
antibot.getDataTrack().getChatTracker().trackplayers
.remove(pN);
antibot.getDataTrack().getChatTracker().spammyPlayers
.add(pN);
event.setCancelled(true);
}
} else {
pc.trig();
}
} catch (Exception e) {
}
}
} catch (Exception e) {
// alright, it failed. Don't worry about it.
}
}
}
| true | true | public void handle(Player player, PlayerChatEvent event) {
try {
if (!Settings.enabled) {
return;
}
String pN = player.getName();
if (Permissions.SPAM.getPermission(event.getPlayer())
|| !Settings.enableAntiSpam) {
return;
}
if (antibot.getDataTrack().getBotTracker().autokick.contains(player
.getName())) {
player.kickPlayer(Settings.kickMsg);
event.setCancelled(true);
return;
}
if (antibot.getDataTrack().getBotTracker().autoipkick
.contains(player.getAddress().toString().split(":")[0])) {
player.kickPlayer(Settings.kickMsg);
event.setCancelled(true);
return;
}
if (antibot.getDataTrack().getChatTracker().spammyPlayers
.contains(pN)) {
event.setCancelled(true);
return;
}
if (!antibot.getDataTrack().getChatTracker().trackplayers
.containsKey(pN)) {
antibot.getDataTrack().getChatTracker().trackplayers.put(pN,
antibot.getDataTrack().getPlayer(pN, this));
} else {
try {
PlayerData pc = antibot.getDataTrack().getChatTracker().trackplayers
.get(pN);
long math = System.currentTimeMillis() - pc.lastChatMsg;
if (pc.amoumt > Settings.spamam && math < Settings.spamtime) {
antibot.getDataTrack().getChatTracker().chatspamblocked += 1;
if (Settings.notify) {
antibot.getServer().broadcastMessage(
Settings.prefix
+ "\247chas detected chat spam!");
}
if (!Settings.chatMute) {
antibot.getDataTrack().getChatTracker().trackplayers
.remove(pN);
player.kickPlayer(Settings.kickMsg);
event.setCancelled(true);
} else {
antibot.getDataTrack().getChatTracker().trackplayers
.remove(pN);
antibot.getDataTrack().getChatTracker().spammyPlayers
.add(pN);
event.setCancelled(true);
}
} else {
pc.trig();
}
} catch (Exception e) {
}
}
} catch (Exception e) {
// alright, it failed. Don't worry about it.
}
}
| public void handle(Player player, PlayerChatEvent event) {
try {
if (!Settings.enabled) {
return;
}
String pN = player.getName();
if (Permissions.CHATSPAM.getPermission(event.getPlayer())
|| !Settings.enableAntiSpam) {
return;
}
if (antibot.getDataTrack().getBotTracker().autokick.contains(player
.getName())) {
player.kickPlayer(Settings.kickMsg);
event.setCancelled(true);
return;
}
if (antibot.getDataTrack().getBotTracker().autoipkick
.contains(player.getAddress().toString().split(":")[0])) {
player.kickPlayer(Settings.kickMsg);
event.setCancelled(true);
return;
}
if (antibot.getDataTrack().getChatTracker().spammyPlayers
.contains(pN)) {
event.setCancelled(true);
return;
}
if (!antibot.getDataTrack().getChatTracker().trackplayers
.containsKey(pN)) {
antibot.getDataTrack().getChatTracker().trackplayers.put(pN,
antibot.getDataTrack().getPlayer(pN, this));
} else {
try {
PlayerData pc = antibot.getDataTrack().getChatTracker().trackplayers
.get(pN);
long math = System.currentTimeMillis() - pc.lastChatMsg;
if (pc.amoumt > Settings.spamam && math < Settings.spamtime) {
antibot.getDataTrack().getChatTracker().chatspamblocked += 1;
if (Settings.notify) {
antibot.getServer().broadcastMessage(
Settings.prefix
+ "\247chas detected chat spam!");
}
if (!Settings.chatMute) {
antibot.getDataTrack().getChatTracker().trackplayers
.remove(pN);
player.kickPlayer(Settings.kickMsg);
event.setCancelled(true);
} else {
antibot.getDataTrack().getChatTracker().trackplayers
.remove(pN);
antibot.getDataTrack().getChatTracker().spammyPlayers
.add(pN);
event.setCancelled(true);
}
} else {
pc.trig();
}
} catch (Exception e) {
}
}
} catch (Exception e) {
// alright, it failed. Don't worry about it.
}
}
|
diff --git a/MonacaFramework/src/mobi/monaca/framework/MonacaApplication.java b/MonacaFramework/src/mobi/monaca/framework/MonacaApplication.java
index 252d52d..d747337 100644
--- a/MonacaFramework/src/mobi/monaca/framework/MonacaApplication.java
+++ b/MonacaFramework/src/mobi/monaca/framework/MonacaApplication.java
@@ -1,291 +1,291 @@
package mobi.monaca.framework;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import mobi.monaca.framework.nativeui.UIContext;
import mobi.monaca.framework.nativeui.component.SpinnerDialog;
import mobi.monaca.framework.nativeui.menu.MenuRepresentation;
import mobi.monaca.framework.nativeui.menu.MenuRepresentationBuilder;
import mobi.monaca.framework.psedo.GCMIntentService;
import mobi.monaca.framework.task.GCMRegistrationIdSenderTask;
import mobi.monaca.framework.util.MyLog;
import mobi.monaca.utils.MonacaConst;
import mobi.monaca.utils.MonacaDevice;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.TargetApi;
import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
/** This class manage the application's global state and variable. */
public class MonacaApplication extends Application {
private static final String TAG = MonacaApplication.class.getSimpleName();
protected static List<MonacaPageActivity> pages = null;
protected static Map<String, MenuRepresentation> menuMap = null;
private SpinnerDialog monacaSpinnerDialog;
protected static InternalSettings settings = null;
protected AppJsonSetting appJsonSetting;
private BroadcastReceiver registeredReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String regId = intent.getStringExtra(GCMIntentService.KEY_REGID);
sendGCMRegisterIdToAppAPI(regId);
unregisterReceiver(this);
}
};
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
@Override
public void onCreate() {
MyLog.i(TAG, "onCreate()");
if (Build.VERSION.SDK_INT >= 12) {
CookieManager.setAcceptFileSchemeCookies(true);
}
CookieSyncManager.createInstance(this);
super.onCreate();
registerReceiver(registeredReceiver, new IntentFilter(GCMIntentService.ACTION_GCM_REGISTERED));
createMenuMap();
}
public void loadAppJsonSetting() {
JSONObject appJson = null;
try {
InputStream stream = getResources().getAssets().open("app.json");
byte[] buffer = new byte[stream.available()];
stream.read(buffer);
appJson = new JSONObject(new String(buffer, "UTF-8"));
} catch (IOException e) {
MyLog.e(TAG, e.getMessage());
} catch (JSONException e) {
MyLog.e(TAG, e.getMessage());
} catch (IllegalArgumentException e) {
MyLog.e(TAG, e.getMessage());
}catch (NullPointerException e) {
e.printStackTrace();
}
if (appJson == null) {
appJson = new JSONObject();
}
appJsonSetting = new AppJsonSetting(appJson);
boolean disableCookie = appJsonSetting.getDisableCookie();
CookieManager.getInstance().setAcceptCookie(!disableCookie);
if (!disableCookie) {
CookieSyncManager.getInstance().startSync();
- String assetUrl = "file:///android_asset/www/";
+ String assetUrl = appJsonSetting.shouldExtractAssets() || MonacaSplashActivity.usesLocalFileBootloader ? "file:///data/" : "file:///android_asset/www/";
//MyLog.d(TAG, projectUrl);
CookieManager.getInstance().setCookie(assetUrl, "MONACA_CLOUD_DEVICE_ID=" + MonacaDevice.getDeviceId(this));
CookieSyncManager.getInstance().sync();
CookieManager.getInstance().setCookie(assetUrl, "Domain=" + appJsonSetting.getMonacaCloudDomain());
CookieSyncManager.getInstance().sync();
CookieManager.getInstance().setCookie(assetUrl, "path=" + appJsonSetting.getMonacaCloudPath());
CookieSyncManager.getInstance().sync();
CookieManager.getInstance().setCookie(assetUrl, "secure");
CookieSyncManager.getInstance().sync();
}
}
public AppJsonSetting getAppJsonSetting() {
//if (appJsonSetting == null) {
// loadAppJsonSetting();
//}
return appJsonSetting;
}
protected void createMenuMap() {
menuMap = new MenuRepresentationBuilder(getApplicationContext()).buildFromAssets(this, "www/app.menu");
}
public void showMonacaSpinnerDialog(UIContext uiContext, JSONArray args) throws Exception {
// dismiss old one if any
if (monacaSpinnerDialog != null && monacaSpinnerDialog.isShowing()) {
monacaSpinnerDialog.dismiss();
}
try {
monacaSpinnerDialog = new SpinnerDialog(uiContext, args);
monacaSpinnerDialog.setCancelable(true);
monacaSpinnerDialog.setOnDismissListener(new OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
monacaSpinnerDialog = null;
}
});
monacaSpinnerDialog.show();
} catch (Exception e) {
Log.e("MONACA", e.getMessage());
throw e;
}
}
public void dismissMonacaSpinnerDialog() {
if (monacaSpinnerDialog != null && monacaSpinnerDialog.isShowing()) {
monacaSpinnerDialog.dismiss();
monacaSpinnerDialog = null;
}
}
public void hideMonacaSpinnerDialog(){
if (monacaSpinnerDialog != null && monacaSpinnerDialog.isShowing()) {
monacaSpinnerDialog.hide();
}
}
public void showMonacaSpinnerDialogIfAny(){
if (monacaSpinnerDialog != null) {
monacaSpinnerDialog.show();
}
}
public void updateSpinnerTitle(String title) {
if (monacaSpinnerDialog != null && monacaSpinnerDialog.isShowing()) {
monacaSpinnerDialog.updateTitleText(title);
}
}
public boolean allowAccess(String url) {
if (url.startsWith("file://")) {
Context context = this.getApplicationContext();
try {
url = new URI(url).normalize().toString();
} catch (Exception e) {
MyLog.e(TAG, e.getMessage());
return false;
}
if (url.startsWith("file:///android_asset/")) {
return true;
}
if (url.startsWith("file://" + context.getApplicationInfo().dataDir)) {
return !url.startsWith("file://" + context.getApplicationInfo().dataDir + "/shared_prefs/");
}
// allow access to SD card (some app need access to photos in SD
// card)
if (url.startsWith("file:///mnt/")) {
return true;
}
if (url.startsWith("file://" + Environment.getExternalStorageDirectory().getPath())) {
return true;
}
return false;
}
return true;
}
/** Add a MonacaPageActivity instance to the page list. */
public static void addPage(MonacaPageActivity page) {
if (pages == null) {
pages = new ArrayList<MonacaPageActivity>();
}
pages.add(page);
}
/** Remove a MonacaPageActivity instance from the page list. */
public static void removePage(MonacaPageActivity page) {
if (pages != null) {
pages.remove(page);
}
}
/** Get either MenuRepresentation or null from menu name. */
public static MenuRepresentation findMenuRepresentation(String name) {
if (menuMap != null) {
return menuMap.containsKey(name) ? menuMap.get(name) : null;
}
return null;
}
/** Get all MonacaPageActivity instances in this application. */
public static List<MonacaPageActivity> getPages() {
return pages != null ? pages : new ArrayList<MonacaPageActivity>();
}
/** Get Monaca's internal settings object */
public InternalSettings getInternalSettings() {
if (settings == null) {
try {
settings = new InternalSettings(this.getPackageManager().getApplicationInfo(this.getPackageName(), PackageManager.GET_META_DATA).metaData);
} catch (Exception e) {
MyLog.d(this.getClass().getSimpleName(), "InternalSettings initialization fail", e);
settings = new InternalSettings(new Bundle());
}
}
return settings;
}
@Override
public void onTerminate() {
MyLog.i(TAG, "onTerminate()");
pages = null;
menuMap = null;
super.onTerminate();
}
public String getPushProjectId() {
return appJsonSetting.getPushProjectId();
}
public void sendGCMRegisterIdToAppAPI(String regId) {
new GCMRegistrationIdSenderTask(this, MonacaConst.getPushRegistrationAPIUrl(this, getPushProjectId()), regId) {
@Override
protected void onSucceededRegistration(JSONObject resultJson) {
}
@Override
protected void onFailedRegistration(JSONObject resultJson) {
}
@Override
protected void onClosedTask() {
}
}.execute();
}
}
| true | true | public void loadAppJsonSetting() {
JSONObject appJson = null;
try {
InputStream stream = getResources().getAssets().open("app.json");
byte[] buffer = new byte[stream.available()];
stream.read(buffer);
appJson = new JSONObject(new String(buffer, "UTF-8"));
} catch (IOException e) {
MyLog.e(TAG, e.getMessage());
} catch (JSONException e) {
MyLog.e(TAG, e.getMessage());
} catch (IllegalArgumentException e) {
MyLog.e(TAG, e.getMessage());
}catch (NullPointerException e) {
e.printStackTrace();
}
if (appJson == null) {
appJson = new JSONObject();
}
appJsonSetting = new AppJsonSetting(appJson);
boolean disableCookie = appJsonSetting.getDisableCookie();
CookieManager.getInstance().setAcceptCookie(!disableCookie);
if (!disableCookie) {
CookieSyncManager.getInstance().startSync();
String assetUrl = "file:///android_asset/www/";
//MyLog.d(TAG, projectUrl);
CookieManager.getInstance().setCookie(assetUrl, "MONACA_CLOUD_DEVICE_ID=" + MonacaDevice.getDeviceId(this));
CookieSyncManager.getInstance().sync();
CookieManager.getInstance().setCookie(assetUrl, "Domain=" + appJsonSetting.getMonacaCloudDomain());
CookieSyncManager.getInstance().sync();
CookieManager.getInstance().setCookie(assetUrl, "path=" + appJsonSetting.getMonacaCloudPath());
CookieSyncManager.getInstance().sync();
CookieManager.getInstance().setCookie(assetUrl, "secure");
CookieSyncManager.getInstance().sync();
}
}
| public void loadAppJsonSetting() {
JSONObject appJson = null;
try {
InputStream stream = getResources().getAssets().open("app.json");
byte[] buffer = new byte[stream.available()];
stream.read(buffer);
appJson = new JSONObject(new String(buffer, "UTF-8"));
} catch (IOException e) {
MyLog.e(TAG, e.getMessage());
} catch (JSONException e) {
MyLog.e(TAG, e.getMessage());
} catch (IllegalArgumentException e) {
MyLog.e(TAG, e.getMessage());
}catch (NullPointerException e) {
e.printStackTrace();
}
if (appJson == null) {
appJson = new JSONObject();
}
appJsonSetting = new AppJsonSetting(appJson);
boolean disableCookie = appJsonSetting.getDisableCookie();
CookieManager.getInstance().setAcceptCookie(!disableCookie);
if (!disableCookie) {
CookieSyncManager.getInstance().startSync();
String assetUrl = appJsonSetting.shouldExtractAssets() || MonacaSplashActivity.usesLocalFileBootloader ? "file:///data/" : "file:///android_asset/www/";
//MyLog.d(TAG, projectUrl);
CookieManager.getInstance().setCookie(assetUrl, "MONACA_CLOUD_DEVICE_ID=" + MonacaDevice.getDeviceId(this));
CookieSyncManager.getInstance().sync();
CookieManager.getInstance().setCookie(assetUrl, "Domain=" + appJsonSetting.getMonacaCloudDomain());
CookieSyncManager.getInstance().sync();
CookieManager.getInstance().setCookie(assetUrl, "path=" + appJsonSetting.getMonacaCloudPath());
CookieSyncManager.getInstance().sync();
CookieManager.getInstance().setCookie(assetUrl, "secure");
CookieSyncManager.getInstance().sync();
}
}
|
diff --git a/src/main/java/net/aufdemrand/denizen/objects/dList.java b/src/main/java/net/aufdemrand/denizen/objects/dList.java
index 8cc040847..92552623d 100644
--- a/src/main/java/net/aufdemrand/denizen/objects/dList.java
+++ b/src/main/java/net/aufdemrand/denizen/objects/dList.java
@@ -1,398 +1,403 @@
package net.aufdemrand.denizen.objects;
import net.aufdemrand.denizen.flags.FlagManager;
import net.aufdemrand.denizen.tags.Attribute;
import net.aufdemrand.denizen.utilities.DenizenAPI;
import net.aufdemrand.denizen.utilities.debugging.dB;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Entity;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class dList extends ArrayList<String> implements dObject {
final static Pattern flag_by_id =
Pattern.compile("(fl\\[((?:p@|n@)(.+?))\\]@|fl@)(.+)",
Pattern.CASE_INSENSITIVE);
@ObjectFetcher("li, fl")
public static dList valueOf(String string) {
if (string == null) return null;
///////
// Match @object format
// Make sure string matches what this interpreter can accept.
Matcher m;
m = flag_by_id.matcher(string);
if (m.matches()) {
FlagManager flag_manager = DenizenAPI.getCurrentInstance().flagManager();
try {
// Global
if (m.group(1).equalsIgnoreCase("fl@")) {
if (FlagManager.serverHasFlag(m.group(4)))
return new dList(flag_manager.getGlobalFlag(m.group(4)));
} else if (m.group(2).toLowerCase().startsWith("p@")) {
if (FlagManager.playerHasFlag(dPlayer.valueOf(m.group(3)), m.group(4)))
return new dList(flag_manager.getPlayerFlag(m.group(3), m.group(4)));
} else if (m.group(2).toLowerCase().startsWith("n@")) {
if (FlagManager.npcHasFlag(dNPC.valueOf(m.group(3)), m.group(4)))
return new dList(flag_manager.getNPCFlag(Integer.valueOf(m.group(3)), m.group(4)));
}
} catch (Exception e) {
dB.echoDebug("Flag '" + m.group() + "' could not be found!");
return null;
}
}
// Use value of string, which will seperate values by the use of a pipe (|)
return new dList(string.replaceFirst("(?i)li@", ""));
}
public static boolean matches(String arg) {
Matcher m;
m = flag_by_id.matcher(arg);
if (m.matches()) return true;
if (arg.contains("|") || arg.toLowerCase().startsWith("li@")) {
dB.log(arg + " is a list.");
return true;
}
return false;
}
/////////////
// Constructors
//////////
public dList(ArrayList<? extends dObject> dObjectList) {
for (dObject obj : dObjectList)
add(obj.identify());
}
public dList(String items) {
addAll(Arrays.asList(items.split("\\|")));
}
public dList(List<String> items) {
addAll(items);
}
public dList(List<String> items, String prefix) {
for (String element : items) {
add(prefix + element);
}
}
public dList(FlagManager.Flag flag) {
this.flag = flag;
addAll(flag.values());
}
/////////////
// Instance Fields/Methods
//////////
private FlagManager.Flag flag = null;
//////////////////////////////
// DSCRIPT ARGUMENT METHODS
/////////////////////////
private String prefix = "List";
@Override
public String getPrefix() {
return prefix;
}
@Override
public dList setPrefix(String prefix) {
this.prefix = prefix;
return this;
}
@Override
public String debug() {
return "<G>" + prefix + "='<Y>" + identify() + "<G>' ";
}
@Override
public boolean isUnique() {
if (flag != null) return true;
else return false;
}
@Override
public String getType() {
return "List";
}
public String[] toArray() {
List<String> list = new ArrayList<String>();
for (String string : this) {
list.add(string);
}
return list.toArray(new String[list.size()]);
}
// Return a list that includes only elements belonging to a certain class
public List<dObject> filter(Class<? extends dObject> dClass) {
List<dObject> results = new ArrayList<dObject>();
for (String element : this) {
try {
if ((Boolean) dClass.getMethod("matches", String.class).invoke(null, element)) {
dObject object = (dObject) dClass.getMethod("valueOf", String.class).invoke(null, element);
// Only add the object if it is not null, thus filtering useless
// list items
if (object != null) {
results.add(object);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
if (results.size() > 0) return results;
else return null;
}
@Override
public String toString() {
return identify();
}
@Override
public String identify() {
if (flag != null)
return flag.toString();
if (isEmpty()) return "li@";
StringBuilder dScriptArg = new StringBuilder();
dScriptArg.append("li@");
for (String item : this)
dScriptArg.append(item + "|");
return dScriptArg.toString().substring(0, dScriptArg.length() - 1);
}
@Override
public String getAttribute(Attribute attribute) {
if (attribute == null) return null;
// <--
// <[email protected]_cslist> -> Element
// returns 'comma-separated' list of the contents of this dList.
// -->
if (attribute.startsWith("ascslist")
|| attribute.startsWith("as_cslist")) {
if (isEmpty()) return new Element("").getAttribute(attribute.fulfill(1));
StringBuilder dScriptArg = new StringBuilder();
for (String item : this)
dScriptArg.append(item + ", ");
return new Element(dScriptArg.toString().substring(0, dScriptArg.length() - 2))
.getAttribute(attribute.fulfill(1));
}
// <--
// <[email protected]> -> Element
// returns 'comma-separated' list of the contents of this dList.
// -->
if (attribute.startsWith("size"))
return new Element(size()).getAttribute(attribute.fulfill(1));
// <--
// <[email protected]_empty> -> Element
// returns 'comma-separated' list of the contents of this dList.
// -->
if (attribute.startsWith("is_empty"))
return new Element(isEmpty()).getAttribute(attribute.fulfill(1));
// <--
// <[email protected]_string> -> Element
// returns each item in the list as a single 'String'.
// -->
if (attribute.startsWith("asstring")
|| attribute.startsWith("as_string")) {
if (isEmpty()) return new Element("").getAttribute(attribute.fulfill(1));
StringBuilder dScriptArg = new StringBuilder();
for (String item : this)
dScriptArg.append(item + " ");
return new Element(dScriptArg.toString().substring(0, dScriptArg.length() - 1))
.getAttribute(attribute.fulfill(1));
}
// <--
// <[email protected][...|...]> -> dList
// returns a new dList excluding the items specified.
// -->
if (attribute.startsWith("exclude")) {
String[] exclusions = attribute.getContext(1).split("\\|");
// Create a new dList that will contain the exclusions
dList list = new dList(this);
// Iterate through
- for (String exclusion : exclusions)
- for (String value : list)
+ for (String exclusion : exclusions) {
+ for (int i = 0;i < list.size();i++) {
+ String value = list.get(i);
// If the value of the list equals the value of the exclusion,
// remove it.
- if (value.equalsIgnoreCase(exclusion))
+ if (value.equalsIgnoreCase(exclusion)) {
list.remove(value);
+ i--;
+ }
+ }
+ }
// Return the modified list
return list.getAttribute(attribute.fulfill(1));
}
// <--
// <[email protected][#]> -> Element
// returns an Element of the value specified by the supplied context.
// -->
if (attribute.startsWith("get")) {
if (isEmpty()) return "null";
int index = attribute.getIntContext(1);
if (index > size()) return "null";
String item;
if (index > 0) item = get(index - 1);
else item = get(0);
if (attribute.getAttribute(2).startsWith("as")) {
}
else
return new Element(item).getAttribute(attribute.fulfill(1));
}
if (attribute.startsWith("last")) {
return new Element(get(size() - 1)).getAttribute(attribute.fulfill(1));
}
if (attribute.startsWith("contains")) {
if (attribute.hasContext(1)) {
boolean state = false;
for (String element : this) {
if (element.equalsIgnoreCase(attribute.getContext(1))) {
state = true;
break;
}
}
return new Element(state).getAttribute(attribute.fulfill(1));
}
}
if (attribute.startsWith("prefix"))
return new Element(prefix)
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("debug.log")) {
dB.log(debug());
return new Element(Boolean.TRUE.toString())
.getAttribute(attribute.fulfill(2));
}
if (attribute.startsWith("debug.no_color")) {
return new Element(ChatColor.stripColor(debug()))
.getAttribute(attribute.fulfill(2));
}
if (attribute.startsWith("debug")) {
return new Element(debug())
.getAttribute(attribute.fulfill(1));
}
if (attribute.startsWith("identify")) {
return new Element(identify())
.getAttribute(attribute.fulfill(1));
}
if (attribute.startsWith("type")) {
return new Element(getType())
.getAttribute(attribute.fulfill(1));
}
// <--
// <[email protected]> -> Element
// gets a random item in the list and returns it as an Element.
// -->
if (attribute.startsWith("random")) {
return new Element(this.get(new Random().nextInt(this.size())))
.getAttribute(attribute.fulfill(1));
}
// FLAG Specific Attributes
// Note: is_expired attribute is handled in player/npc/server
// since expired flags return 'null'
// <--
// <fl@flag_name.is_expired> -> Element(boolean)
// returns true of the flag is expired or does not exist, false if it
// is not yet expired, or has no expiration.
// -->
// <--
// <fl@flag_name.expiration> -> Duration
// returns a Duration of the time remaining on the flag, if it
// has an expiration.
// -->
if (flag != null && attribute.startsWith("expiration")) {
return flag.expiration()
.getAttribute(attribute.fulfill(1));
}
// Need this attribute (for flags) since they return the last
// element of the list, unless '.as_list' is specified.
// <--
// <fl@flag_name.as_list> -> dList
// returns a dList containing the items in the flag
// -->
if (flag != null && (attribute.startsWith("as_list")
|| attribute.startsWith("aslist")))
return new dList(this).getAttribute(attribute.fulfill(1));
// If this is a flag, return the last element (this is how it has always worked...)
// Use as_list to return a list representation of the flag.
// If this is NOT a flag, but instead a normal dList, return an element
// with dList's identify() value.
return (flag != null
? new Element(flag.getLast().asString()).getAttribute(attribute.fulfill(0))
: new Element(identify()).getAttribute(attribute.fulfill(0)));
}
}
| false | true | public String getAttribute(Attribute attribute) {
if (attribute == null) return null;
// <--
// <[email protected]_cslist> -> Element
// returns 'comma-separated' list of the contents of this dList.
// -->
if (attribute.startsWith("ascslist")
|| attribute.startsWith("as_cslist")) {
if (isEmpty()) return new Element("").getAttribute(attribute.fulfill(1));
StringBuilder dScriptArg = new StringBuilder();
for (String item : this)
dScriptArg.append(item + ", ");
return new Element(dScriptArg.toString().substring(0, dScriptArg.length() - 2))
.getAttribute(attribute.fulfill(1));
}
// <--
// <[email protected]> -> Element
// returns 'comma-separated' list of the contents of this dList.
// -->
if (attribute.startsWith("size"))
return new Element(size()).getAttribute(attribute.fulfill(1));
// <--
// <[email protected]_empty> -> Element
// returns 'comma-separated' list of the contents of this dList.
// -->
if (attribute.startsWith("is_empty"))
return new Element(isEmpty()).getAttribute(attribute.fulfill(1));
// <--
// <[email protected]_string> -> Element
// returns each item in the list as a single 'String'.
// -->
if (attribute.startsWith("asstring")
|| attribute.startsWith("as_string")) {
if (isEmpty()) return new Element("").getAttribute(attribute.fulfill(1));
StringBuilder dScriptArg = new StringBuilder();
for (String item : this)
dScriptArg.append(item + " ");
return new Element(dScriptArg.toString().substring(0, dScriptArg.length() - 1))
.getAttribute(attribute.fulfill(1));
}
// <--
// <[email protected][...|...]> -> dList
// returns a new dList excluding the items specified.
// -->
if (attribute.startsWith("exclude")) {
String[] exclusions = attribute.getContext(1).split("\\|");
// Create a new dList that will contain the exclusions
dList list = new dList(this);
// Iterate through
for (String exclusion : exclusions)
for (String value : list)
// If the value of the list equals the value of the exclusion,
// remove it.
if (value.equalsIgnoreCase(exclusion))
list.remove(value);
// Return the modified list
return list.getAttribute(attribute.fulfill(1));
}
// <--
// <[email protected][#]> -> Element
// returns an Element of the value specified by the supplied context.
// -->
if (attribute.startsWith("get")) {
if (isEmpty()) return "null";
int index = attribute.getIntContext(1);
if (index > size()) return "null";
String item;
if (index > 0) item = get(index - 1);
else item = get(0);
if (attribute.getAttribute(2).startsWith("as")) {
}
else
return new Element(item).getAttribute(attribute.fulfill(1));
}
if (attribute.startsWith("last")) {
return new Element(get(size() - 1)).getAttribute(attribute.fulfill(1));
}
if (attribute.startsWith("contains")) {
if (attribute.hasContext(1)) {
boolean state = false;
for (String element : this) {
if (element.equalsIgnoreCase(attribute.getContext(1))) {
state = true;
break;
}
}
return new Element(state).getAttribute(attribute.fulfill(1));
}
}
if (attribute.startsWith("prefix"))
return new Element(prefix)
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("debug.log")) {
dB.log(debug());
return new Element(Boolean.TRUE.toString())
.getAttribute(attribute.fulfill(2));
}
if (attribute.startsWith("debug.no_color")) {
return new Element(ChatColor.stripColor(debug()))
.getAttribute(attribute.fulfill(2));
}
if (attribute.startsWith("debug")) {
return new Element(debug())
.getAttribute(attribute.fulfill(1));
}
if (attribute.startsWith("identify")) {
return new Element(identify())
.getAttribute(attribute.fulfill(1));
}
if (attribute.startsWith("type")) {
return new Element(getType())
.getAttribute(attribute.fulfill(1));
}
// <--
// <[email protected]> -> Element
// gets a random item in the list and returns it as an Element.
// -->
if (attribute.startsWith("random")) {
return new Element(this.get(new Random().nextInt(this.size())))
.getAttribute(attribute.fulfill(1));
}
// FLAG Specific Attributes
// Note: is_expired attribute is handled in player/npc/server
// since expired flags return 'null'
// <--
// <fl@flag_name.is_expired> -> Element(boolean)
// returns true of the flag is expired or does not exist, false if it
// is not yet expired, or has no expiration.
// -->
// <--
// <fl@flag_name.expiration> -> Duration
// returns a Duration of the time remaining on the flag, if it
// has an expiration.
// -->
if (flag != null && attribute.startsWith("expiration")) {
return flag.expiration()
.getAttribute(attribute.fulfill(1));
}
// Need this attribute (for flags) since they return the last
// element of the list, unless '.as_list' is specified.
// <--
// <fl@flag_name.as_list> -> dList
// returns a dList containing the items in the flag
// -->
if (flag != null && (attribute.startsWith("as_list")
|| attribute.startsWith("aslist")))
return new dList(this).getAttribute(attribute.fulfill(1));
// If this is a flag, return the last element (this is how it has always worked...)
// Use as_list to return a list representation of the flag.
// If this is NOT a flag, but instead a normal dList, return an element
// with dList's identify() value.
return (flag != null
? new Element(flag.getLast().asString()).getAttribute(attribute.fulfill(0))
: new Element(identify()).getAttribute(attribute.fulfill(0)));
}
| public String getAttribute(Attribute attribute) {
if (attribute == null) return null;
// <--
// <[email protected]_cslist> -> Element
// returns 'comma-separated' list of the contents of this dList.
// -->
if (attribute.startsWith("ascslist")
|| attribute.startsWith("as_cslist")) {
if (isEmpty()) return new Element("").getAttribute(attribute.fulfill(1));
StringBuilder dScriptArg = new StringBuilder();
for (String item : this)
dScriptArg.append(item + ", ");
return new Element(dScriptArg.toString().substring(0, dScriptArg.length() - 2))
.getAttribute(attribute.fulfill(1));
}
// <--
// <[email protected]> -> Element
// returns 'comma-separated' list of the contents of this dList.
// -->
if (attribute.startsWith("size"))
return new Element(size()).getAttribute(attribute.fulfill(1));
// <--
// <[email protected]_empty> -> Element
// returns 'comma-separated' list of the contents of this dList.
// -->
if (attribute.startsWith("is_empty"))
return new Element(isEmpty()).getAttribute(attribute.fulfill(1));
// <--
// <[email protected]_string> -> Element
// returns each item in the list as a single 'String'.
// -->
if (attribute.startsWith("asstring")
|| attribute.startsWith("as_string")) {
if (isEmpty()) return new Element("").getAttribute(attribute.fulfill(1));
StringBuilder dScriptArg = new StringBuilder();
for (String item : this)
dScriptArg.append(item + " ");
return new Element(dScriptArg.toString().substring(0, dScriptArg.length() - 1))
.getAttribute(attribute.fulfill(1));
}
// <--
// <[email protected][...|...]> -> dList
// returns a new dList excluding the items specified.
// -->
if (attribute.startsWith("exclude")) {
String[] exclusions = attribute.getContext(1).split("\\|");
// Create a new dList that will contain the exclusions
dList list = new dList(this);
// Iterate through
for (String exclusion : exclusions) {
for (int i = 0;i < list.size();i++) {
String value = list.get(i);
// If the value of the list equals the value of the exclusion,
// remove it.
if (value.equalsIgnoreCase(exclusion)) {
list.remove(value);
i--;
}
}
}
// Return the modified list
return list.getAttribute(attribute.fulfill(1));
}
// <--
// <[email protected][#]> -> Element
// returns an Element of the value specified by the supplied context.
// -->
if (attribute.startsWith("get")) {
if (isEmpty()) return "null";
int index = attribute.getIntContext(1);
if (index > size()) return "null";
String item;
if (index > 0) item = get(index - 1);
else item = get(0);
if (attribute.getAttribute(2).startsWith("as")) {
}
else
return new Element(item).getAttribute(attribute.fulfill(1));
}
if (attribute.startsWith("last")) {
return new Element(get(size() - 1)).getAttribute(attribute.fulfill(1));
}
if (attribute.startsWith("contains")) {
if (attribute.hasContext(1)) {
boolean state = false;
for (String element : this) {
if (element.equalsIgnoreCase(attribute.getContext(1))) {
state = true;
break;
}
}
return new Element(state).getAttribute(attribute.fulfill(1));
}
}
if (attribute.startsWith("prefix"))
return new Element(prefix)
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("debug.log")) {
dB.log(debug());
return new Element(Boolean.TRUE.toString())
.getAttribute(attribute.fulfill(2));
}
if (attribute.startsWith("debug.no_color")) {
return new Element(ChatColor.stripColor(debug()))
.getAttribute(attribute.fulfill(2));
}
if (attribute.startsWith("debug")) {
return new Element(debug())
.getAttribute(attribute.fulfill(1));
}
if (attribute.startsWith("identify")) {
return new Element(identify())
.getAttribute(attribute.fulfill(1));
}
if (attribute.startsWith("type")) {
return new Element(getType())
.getAttribute(attribute.fulfill(1));
}
// <--
// <[email protected]> -> Element
// gets a random item in the list and returns it as an Element.
// -->
if (attribute.startsWith("random")) {
return new Element(this.get(new Random().nextInt(this.size())))
.getAttribute(attribute.fulfill(1));
}
// FLAG Specific Attributes
// Note: is_expired attribute is handled in player/npc/server
// since expired flags return 'null'
// <--
// <fl@flag_name.is_expired> -> Element(boolean)
// returns true of the flag is expired or does not exist, false if it
// is not yet expired, or has no expiration.
// -->
// <--
// <fl@flag_name.expiration> -> Duration
// returns a Duration of the time remaining on the flag, if it
// has an expiration.
// -->
if (flag != null && attribute.startsWith("expiration")) {
return flag.expiration()
.getAttribute(attribute.fulfill(1));
}
// Need this attribute (for flags) since they return the last
// element of the list, unless '.as_list' is specified.
// <--
// <fl@flag_name.as_list> -> dList
// returns a dList containing the items in the flag
// -->
if (flag != null && (attribute.startsWith("as_list")
|| attribute.startsWith("aslist")))
return new dList(this).getAttribute(attribute.fulfill(1));
// If this is a flag, return the last element (this is how it has always worked...)
// Use as_list to return a list representation of the flag.
// If this is NOT a flag, but instead a normal dList, return an element
// with dList's identify() value.
return (flag != null
? new Element(flag.getLast().asString()).getAttribute(attribute.fulfill(0))
: new Element(identify()).getAttribute(attribute.fulfill(0)));
}
|
diff --git a/modules/activiti-engine/src/main/java/org/activiti/engine/delegate/event/BaseEntityEventListener.java b/modules/activiti-engine/src/main/java/org/activiti/engine/delegate/event/BaseEntityEventListener.java
index 4fd682d46..38167b69b 100644
--- a/modules/activiti-engine/src/main/java/org/activiti/engine/delegate/event/BaseEntityEventListener.java
+++ b/modules/activiti-engine/src/main/java/org/activiti/engine/delegate/event/BaseEntityEventListener.java
@@ -1,129 +1,129 @@
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.activiti.engine.delegate.event;
/**
* Base event listener that can be used when implementing an
* {@link ActivitiEventListener} to get notified when an entity is created,
* updated, deleted or if another entity-related event occurs.
*
* Override the <code>onXX(..)</code> methods to respond to entity changes
* accordingly.
*
* @author Frederik Heremans
*
*/
public class BaseEntityEventListener implements ActivitiEventListener {
protected boolean failOnException = false;
protected Class<?> entityClass;
/**
* Create a new BaseEntityEventListener, notified when an event that targets
* any type of entity is received. Returning true when
* {@link #isFailOnException()} is called.
*/
public BaseEntityEventListener() {
this(true, null);
}
/**
* Create a new BaseEntityEventListener.
*
* @param failOnException
* return value for {@link #isFailOnException()}.
*/
public BaseEntityEventListener(boolean failOnException) {
this(failOnException, null);
}
public BaseEntityEventListener(boolean failOnException, Class<?> entityClass) {
this.failOnException = failOnException;
this.entityClass = entityClass;
}
@Override
public final void onEvent(ActivitiEvent event) {
if(isValidEvent(event)) {
// Check if this event
if (event.getType() == ActivitiEventType.ENTITY_CREATED) {
onCreate(event);
- }if (event.getType() == ActivitiEventType.ENTITY_CREATED) {
+ }if (event.getType() == ActivitiEventType.ENTITY_INITIALIZED) {
onInitialized(event);
} else if (event.getType() == ActivitiEventType.ENTITY_DELETED) {
onDelete(event);
} else if (event.getType() == ActivitiEventType.ENTITY_UPDATED) {
onUpdate(event);
} else {
// Entity-specific event
onEntityEvent(event);
}
}
}
@Override
public boolean isFailOnException() {
return failOnException;
}
/**
* @return true, if the event is an {@link ActivitiEntityEvent} and (if needed) the entityClass
* set in this instance, is assignable from the entity class in the event.
*/
protected boolean isValidEvent(ActivitiEvent event) {
boolean valid = false;
if(event instanceof ActivitiEntityEvent) {
if(entityClass == null) {
valid = true;
} else {
valid = entityClass.isAssignableFrom(((ActivitiEntityEvent) event).getEntity().getClass());
}
}
return valid;
}
/**
* Called when an entity create event is received.
*/
protected void onCreate(ActivitiEvent event) {
// Default implementation is a NO-OP
}
/**
* Called when an entity initialized event is received.
*/
protected void onInitialized(ActivitiEvent event) {
// Default implementation is a NO-OP
}
/**
* Called when an entity delete event is received.
*/
protected void onDelete(ActivitiEvent event) {
// Default implementation is a NO-OP
}
/**
* Called when an entity update event is received.
*/
protected void onUpdate(ActivitiEvent event) {
// Default implementation is a NO-OP
}
/**
* Called when an event is received, which is not a create, an update or
* delete.
*/
protected void onEntityEvent(ActivitiEvent event) {
// Default implementation is a NO-OP
}
}
| true | true | public final void onEvent(ActivitiEvent event) {
if(isValidEvent(event)) {
// Check if this event
if (event.getType() == ActivitiEventType.ENTITY_CREATED) {
onCreate(event);
}if (event.getType() == ActivitiEventType.ENTITY_CREATED) {
onInitialized(event);
} else if (event.getType() == ActivitiEventType.ENTITY_DELETED) {
onDelete(event);
} else if (event.getType() == ActivitiEventType.ENTITY_UPDATED) {
onUpdate(event);
} else {
// Entity-specific event
onEntityEvent(event);
}
}
}
| public final void onEvent(ActivitiEvent event) {
if(isValidEvent(event)) {
// Check if this event
if (event.getType() == ActivitiEventType.ENTITY_CREATED) {
onCreate(event);
}if (event.getType() == ActivitiEventType.ENTITY_INITIALIZED) {
onInitialized(event);
} else if (event.getType() == ActivitiEventType.ENTITY_DELETED) {
onDelete(event);
} else if (event.getType() == ActivitiEventType.ENTITY_UPDATED) {
onUpdate(event);
} else {
// Entity-specific event
onEntityEvent(event);
}
}
}
|
diff --git a/src/main/java/net/oneandone/sushi/cli/Console.java b/src/main/java/net/oneandone/sushi/cli/Console.java
index c28b7356..fc49fda3 100644
--- a/src/main/java/net/oneandone/sushi/cli/Console.java
+++ b/src/main/java/net/oneandone/sushi/cli/Console.java
@@ -1,91 +1,92 @@
/**
* Copyright 1&1 Internet AG, https://github.com/1and1/
*
* 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 net.oneandone.sushi.cli;
import net.oneandone.sushi.fs.World;
import net.oneandone.sushi.io.InputLogStream;
import net.oneandone.sushi.io.MultiOutputStream;
import net.oneandone.sushi.io.MultiWriter;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Scanner;
/**
* Configurable replacement for System.out, System.err and System.in.
* TODO: name clash with java.world.Console in Java 6.
*/
public class Console {
public static Console create(World world) {
return new Console(world, new PrintWriter(System.out, true), new PrintWriter(System.err, true), System.in);
}
public static Console create(World world, final OutputStream log) {
return new Console(world,
new PrintWriter(MultiOutputStream.createTeeStream(System.out, log), true),
new PrintWriter(MultiOutputStream.createTeeStream(System.err, log), true),
new InputLogStream(System.in, log));
}
public final World world;
public final PrintWriter info;
public final PrintWriter verbose;
public final PrintWriter error;
public final Scanner input;
private final MultiWriter verboseSwitch;
public Console(World world, PrintWriter info, PrintWriter error, InputStream in) {
this.world = world;
this.info = info;
this.verboseSwitch = MultiWriter.createNullWriter();
this.verbose = new PrintWriter(verboseSwitch);
this.error = error;
this.input = new Scanner(in);
}
public boolean getVerbose() {
return verboseSwitch.dests().size() == 1;
}
public void setVerbose(boolean verbose) {
verboseSwitch.dests().clear();
if (verbose) {
verboseSwitch.dests().add(info);
}
}
public void pressReturn() {
readline("Press return to continue, ctrl-C to abort.\n");
}
public String readline(String message) {
return readline(message, "");
}
public String readline(String message, String dflt) {
String str;
info.print(message);
+ info.flush();
str = input.nextLine();
if (str.length() == 0) {
return dflt;
} else {
return str;
}
}
}
| true | true | public String readline(String message, String dflt) {
String str;
info.print(message);
str = input.nextLine();
if (str.length() == 0) {
return dflt;
} else {
return str;
}
}
| public String readline(String message, String dflt) {
String str;
info.print(message);
info.flush();
str = input.nextLine();
if (str.length() == 0) {
return dflt;
} else {
return str;
}
}
|
diff --git a/src/com.gluster.storage.management.gateway/src/com/gluster/storage/management/gateway/services/GlusterServerService.java b/src/com.gluster.storage.management.gateway/src/com/gluster/storage/management/gateway/services/GlusterServerService.java
index cbb8043f..48634c4d 100644
--- a/src/com.gluster.storage.management.gateway/src/com/gluster/storage/management/gateway/services/GlusterServerService.java
+++ b/src/com.gluster.storage.management.gateway/src/com/gluster/storage/management/gateway/services/GlusterServerService.java
@@ -1,171 +1,171 @@
/*******************************************************************************
* Copyright (c) 2011 Gluster, Inc. <http://www.gluster.com>
* This file is part of Gluster Management Console.
*
* Gluster Management Console is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Gluster Management Console is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License
* for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*******************************************************************************/
package com.gluster.storage.management.gateway.services;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.gluster.storage.management.core.constants.CoreConstants;
import com.gluster.storage.management.core.exceptions.ConnectionException;
import com.gluster.storage.management.core.exceptions.GlusterRuntimeException;
import com.gluster.storage.management.core.exceptions.GlusterValidationException;
import com.gluster.storage.management.core.model.Entity;
import com.gluster.storage.management.core.model.GlusterServer;
import com.gluster.storage.management.core.model.Server.SERVER_STATUS;
import com.gluster.storage.management.core.utils.GlusterCoreUtil;
import com.gluster.storage.management.gateway.data.ClusterInfo;
import com.gluster.storage.management.gateway.utils.GlusterUtil;
import com.gluster.storage.management.gateway.utils.ServerUtil;
/**
*
*/
@Component
public class GlusterServerService {
@Autowired
protected ServerUtil serverUtil;
@Autowired
private ClusterService clusterService;
@Autowired
private GlusterUtil glusterUtil;
public void fetchServerDetails(GlusterServer server) {
try {
server.setStatus(SERVER_STATUS.ONLINE);
serverUtil.fetchServerDetails(server);
} catch (ConnectionException e) {
server.setStatus(SERVER_STATUS.OFFLINE);
}
}
// TODO: Introduce logic to fetch records based on maxCount and previousServerName
public List<GlusterServer> getGlusterServers(String clusterName, boolean fetchDetails, Integer maxCount,
String previousServerName) {
List<GlusterServer> glusterServers;
GlusterServer onlineServer = clusterService.getOnlineServer(clusterName);
if (onlineServer == null) {
throw new GlusterRuntimeException("No online servers found in cluster [" + clusterName + "]");
}
try {
glusterServers = getGlusterServers(clusterName, onlineServer, fetchDetails, maxCount, previousServerName);
} catch (ConnectionException e) {
// online server has gone offline! try with a different one.
onlineServer = clusterService.getNewOnlineServer(clusterName);
if (onlineServer == null) {
throw new GlusterRuntimeException("No online servers found in cluster [" + clusterName + "]");
}
glusterServers = getGlusterServers(clusterName, onlineServer, fetchDetails, maxCount, previousServerName);
}
return glusterServers;
}
private List<GlusterServer> getGlusterServers(String clusterName, GlusterServer onlineServer, boolean fetchDetails,
Integer maxCount, String previousServerName) {
List<GlusterServer> glusterServers;
try {
glusterServers = glusterUtil.getGlusterServers(onlineServer);
- return GlusterCoreUtil.skipEntities(glusterServers, maxCount, previousServerName);
+ glusterServers = GlusterCoreUtil.skipEntities(glusterServers, maxCount, previousServerName);
} catch (ConnectionException e) {
// online server has gone offline! try with a different one.
onlineServer = clusterService.getNewOnlineServer(clusterName);
if (onlineServer == null) {
throw new GlusterRuntimeException("No online servers found in cluster [" + clusterName + "]");
}
glusterServers = glusterUtil.getGlusterServers(onlineServer);
}
if (fetchDetails) {
String errMsg = fetchDetailsOfServers(glusterServers, onlineServer);
if (!errMsg.isEmpty()) {
throw new GlusterRuntimeException("Couldn't fetch details for server(s): " + errMsg);
}
}
return glusterServers;
}
private String fetchDetailsOfServers(List<GlusterServer> glusterServers, GlusterServer onlineServer) {
String errMsg = "";
for (GlusterServer server : glusterServers) {
try {
fetchServerDetails(server);
} catch (Exception e) {
errMsg += CoreConstants.NEWLINE + server.getName() + " : [" + e.getMessage() + "]";
}
}
return errMsg;
}
public GlusterServer getGlusterServer(String clusterName, String serverName, Boolean fetchDetails) {
if (clusterName == null || clusterName.isEmpty()) {
throw new GlusterValidationException("Cluster name must not be empty!");
}
if (serverName == null || serverName.isEmpty()) {
throw new GlusterValidationException("Server name must not be empty!");
}
ClusterInfo cluster = clusterService.getCluster(clusterName);
if (cluster == null) {
throw new GlusterRuntimeException("Cluster [" + clusterName + "] not found!");
}
GlusterServer onlineServer = clusterService.getOnlineServer(clusterName);
if (onlineServer == null) {
throw new GlusterRuntimeException("No online servers found in cluster [" + clusterName + "]");
}
return getGlusterServer(clusterName, serverName, onlineServer, fetchDetails);
}
private GlusterServer getGlusterServer(String clusterName, String serverName, GlusterServer onlineServer,
Boolean fetchDetails) {
GlusterServer server = null;
try {
server = glusterUtil.getGlusterServer(onlineServer, serverName);
} catch (ConnectionException e) {
// online server has gone offline! try with a different one.
onlineServer = clusterService.getNewOnlineServer(clusterName);
if (onlineServer == null) {
throw new GlusterRuntimeException("No online servers found in cluster [" + clusterName + "]");
}
server = glusterUtil.getGlusterServer(onlineServer, serverName);
}
if (fetchDetails && server.isOnline()) {
fetchServerDetails(server);
}
return server;
}
public boolean isValidServer(String clusterName, String serverName) {
try {
GlusterServer server = getGlusterServer(clusterName, serverName, false);
return server != null;
} catch(Exception e) {
return false;
}
}
}
| true | true | private List<GlusterServer> getGlusterServers(String clusterName, GlusterServer onlineServer, boolean fetchDetails,
Integer maxCount, String previousServerName) {
List<GlusterServer> glusterServers;
try {
glusterServers = glusterUtil.getGlusterServers(onlineServer);
return GlusterCoreUtil.skipEntities(glusterServers, maxCount, previousServerName);
} catch (ConnectionException e) {
// online server has gone offline! try with a different one.
onlineServer = clusterService.getNewOnlineServer(clusterName);
if (onlineServer == null) {
throw new GlusterRuntimeException("No online servers found in cluster [" + clusterName + "]");
}
glusterServers = glusterUtil.getGlusterServers(onlineServer);
}
if (fetchDetails) {
String errMsg = fetchDetailsOfServers(glusterServers, onlineServer);
if (!errMsg.isEmpty()) {
throw new GlusterRuntimeException("Couldn't fetch details for server(s): " + errMsg);
}
}
return glusterServers;
}
| private List<GlusterServer> getGlusterServers(String clusterName, GlusterServer onlineServer, boolean fetchDetails,
Integer maxCount, String previousServerName) {
List<GlusterServer> glusterServers;
try {
glusterServers = glusterUtil.getGlusterServers(onlineServer);
glusterServers = GlusterCoreUtil.skipEntities(glusterServers, maxCount, previousServerName);
} catch (ConnectionException e) {
// online server has gone offline! try with a different one.
onlineServer = clusterService.getNewOnlineServer(clusterName);
if (onlineServer == null) {
throw new GlusterRuntimeException("No online servers found in cluster [" + clusterName + "]");
}
glusterServers = glusterUtil.getGlusterServers(onlineServer);
}
if (fetchDetails) {
String errMsg = fetchDetailsOfServers(glusterServers, onlineServer);
if (!errMsg.isEmpty()) {
throw new GlusterRuntimeException("Couldn't fetch details for server(s): " + errMsg);
}
}
return glusterServers;
}
|
diff --git a/ui/plugins/eu.esdihumboldt.hale.ui.common/src/eu/esdihumboldt/hale/ui/common/definition/selector/PropertyDefinitionDialog.java b/ui/plugins/eu.esdihumboldt.hale.ui.common/src/eu/esdihumboldt/hale/ui/common/definition/selector/PropertyDefinitionDialog.java
index 32d395d26..3f22334be 100644
--- a/ui/plugins/eu.esdihumboldt.hale.ui.common/src/eu/esdihumboldt/hale/ui/common/definition/selector/PropertyDefinitionDialog.java
+++ b/ui/plugins/eu.esdihumboldt.hale.ui.common/src/eu/esdihumboldt/hale/ui/common/definition/selector/PropertyDefinitionDialog.java
@@ -1,146 +1,146 @@
/*
* Copyright (c) 2012 Data Harmonisation Panel
*
* All rights reserved. This program and the accompanying materials are made
* available under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution. If not, see <http://www.gnu.org/licenses/>.
*
* Contributors:
* HUMBOLDT EU Integrated Project #030962
* Data Harmonisation Panel <http://www.dhpanel.eu>
*/
package eu.esdihumboldt.hale.ui.common.definition.selector;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreePath;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.dialogs.FilteredTree;
import eu.esdihumboldt.hale.common.align.model.ChildContext;
import eu.esdihumboldt.hale.common.align.model.EntityDefinition;
import eu.esdihumboldt.hale.common.align.model.impl.PropertyEntityDefinition;
import eu.esdihumboldt.hale.common.schema.SchemaSpaceID;
import eu.esdihumboldt.hale.common.schema.model.ChildDefinition;
import eu.esdihumboldt.hale.common.schema.model.PropertyDefinition;
import eu.esdihumboldt.hale.common.schema.model.TypeDefinition;
import eu.esdihumboldt.hale.ui.common.definition.viewer.DefinitionComparator;
import eu.esdihumboldt.hale.ui.common.definition.viewer.DefinitionLabelProvider;
import eu.esdihumboldt.hale.ui.common.definition.viewer.SchemaPatternFilter;
import eu.esdihumboldt.hale.ui.common.definition.viewer.TypePropertyContentProvider;
import eu.esdihumboldt.hale.ui.util.selector.AbstractViewerSelectionDialog;
import eu.esdihumboldt.hale.ui.util.viewer.tree.TreePathFilteredTree;
import eu.esdihumboldt.hale.ui.util.viewer.tree.TreePathProviderAdapter;
/**
* Dialog for selecting a {@link PropertyDefinition} with its complete property
* path (represented in an {@link EntityDefinition}).
*
* @author Simon Templer
*/
public class PropertyDefinitionDialog extends
AbstractViewerSelectionDialog<EntityDefinition, TreeViewer> {
private final TypeDefinition parentType;
private final SchemaSpaceID ssid;
/**
* Create a property entity dialog
*
* @param parentShell the parent shall
* @param ssid the schema space used for creating
* {@link PropertyEntityDefinition}, may be <code>null</code> if
* not needed
* @param parentType the parent type for the property to be selected
* @param title the dialog title
* @param initialSelection the entity definition to select initially (if
* possible), may be <code>null</code>
*/
public PropertyDefinitionDialog(Shell parentShell, SchemaSpaceID ssid,
TypeDefinition parentType, String title, EntityDefinition initialSelection) {
super(parentShell, title, initialSelection);
this.ssid = ssid;
this.parentType = parentType;
}
/**
* @see AbstractViewerSelectionDialog#createViewer(Composite)
*/
@Override
protected TreeViewer createViewer(Composite parent) {
// create viewer
SchemaPatternFilter patternFilter = new SchemaPatternFilter() {
@Override
protected boolean matches(Viewer viewer, Object element) {
boolean superMatches = super.matches(viewer, element);
if (!superMatches)
return false;
return acceptObject(viewer, getFilters(), ((TreePath) element).getLastSegment());
}
};
patternFilter.setUseEarlyReturnIfMatcherIsNull(false);
patternFilter.setIncludeLeadingWildcard(true);
FilteredTree tree = new TreePathFilteredTree(parent, SWT.SINGLE | SWT.H_SCROLL
| SWT.V_SCROLL | SWT.BORDER, patternFilter, true);
tree.getViewer().setComparator(new DefinitionComparator());
return tree.getViewer();
}
@Override
protected void setupViewer(TreeViewer viewer, EntityDefinition initialSelection) {
viewer.setLabelProvider(new DefinitionLabelProvider());
viewer.setContentProvider(new TreePathProviderAdapter(new TypePropertyContentProvider(
viewer)));
viewer.setInput(parentType);
if (initialSelection != null) {
viewer.setSelection(new StructuredSelection(initialSelection));
}
}
@Override
protected EntityDefinition getObjectFromSelection(ISelection selection) {
if (!selection.isEmpty() && selection instanceof IStructuredSelection) {
Object element = ((IStructuredSelection) selection).getFirstElement();
if (element instanceof EntityDefinition) {
return (EntityDefinition) element;
}
}
if (!selection.isEmpty() && selection instanceof ITreeSelection) {
// create property definition w/ default contexts
TreePath path = ((ITreeSelection) selection).getPaths()[0];
// get parent type
- TypeDefinition type = ((PropertyDefinition) path.getFirstSegment()).getParentType();
+ TypeDefinition type = ((ChildDefinition<?>) path.getFirstSegment()).getParentType();
// determine definition path
List<ChildContext> defPath = new ArrayList<ChildContext>();
for (int i = 0; i < path.getSegmentCount(); i++) {
defPath.add(new ChildContext((ChildDefinition<?>) path.getSegment(i)));
}
// TODO check if property entity definition is applicable?
return new PropertyEntityDefinition(type, defPath, ssid, null);
}
return null;
}
}
| true | true | protected EntityDefinition getObjectFromSelection(ISelection selection) {
if (!selection.isEmpty() && selection instanceof IStructuredSelection) {
Object element = ((IStructuredSelection) selection).getFirstElement();
if (element instanceof EntityDefinition) {
return (EntityDefinition) element;
}
}
if (!selection.isEmpty() && selection instanceof ITreeSelection) {
// create property definition w/ default contexts
TreePath path = ((ITreeSelection) selection).getPaths()[0];
// get parent type
TypeDefinition type = ((PropertyDefinition) path.getFirstSegment()).getParentType();
// determine definition path
List<ChildContext> defPath = new ArrayList<ChildContext>();
for (int i = 0; i < path.getSegmentCount(); i++) {
defPath.add(new ChildContext((ChildDefinition<?>) path.getSegment(i)));
}
// TODO check if property entity definition is applicable?
return new PropertyEntityDefinition(type, defPath, ssid, null);
}
return null;
}
| protected EntityDefinition getObjectFromSelection(ISelection selection) {
if (!selection.isEmpty() && selection instanceof IStructuredSelection) {
Object element = ((IStructuredSelection) selection).getFirstElement();
if (element instanceof EntityDefinition) {
return (EntityDefinition) element;
}
}
if (!selection.isEmpty() && selection instanceof ITreeSelection) {
// create property definition w/ default contexts
TreePath path = ((ITreeSelection) selection).getPaths()[0];
// get parent type
TypeDefinition type = ((ChildDefinition<?>) path.getFirstSegment()).getParentType();
// determine definition path
List<ChildContext> defPath = new ArrayList<ChildContext>();
for (int i = 0; i < path.getSegmentCount(); i++) {
defPath.add(new ChildContext((ChildDefinition<?>) path.getSegment(i)));
}
// TODO check if property entity definition is applicable?
return new PropertyEntityDefinition(type, defPath, ssid, null);
}
return null;
}
|
diff --git a/src/dloader/PageProcessor.java b/src/dloader/PageProcessor.java
index 9a23358..981bc9f 100644
--- a/src/dloader/PageProcessor.java
+++ b/src/dloader/PageProcessor.java
@@ -1,396 +1,396 @@
package dloader;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import dloader.PageJob.JobStatusEnum;
import dloader.page.*;
import dloader.page.AbstractPage.ProblemsReadingDocumentException;
/**
* This class handles multiple PageJob objects and general algorithm of the program
* @author A.Cerbic
*/
public class PageProcessor {
/**
* Dynamically growing list of PageJob objects;
*/
static final List<PageJob> jobQ;
/**
* Holds reference to a cache, if one is present (null otherwise)
*/
static XMLCache cache;
/**
* Holds reference to a logger, if one is present (null otherwise)
*/
static Logger logger;
/**
* true if PageProcessor reads and writes to cache.
* false if only writes (when cache is not null)
*/
static boolean isReadingCache;
/**
* priorities system to select next job from the Q
*/
static final
Map<PageJob.JobStatusEnum, Integer> priorities;
/**
* value for the top priority
*/
static final
int PRIORITIES_MIN = 0;
/**
* minimum priority value for job statuses that don't get executed
*/
static final
int PRIORITIES_NOWORK = 100;
/**
* minimum value for "heavy"-duty priorities (involving long operations)
*/
static final
int PRIORITIES_HEAVY = 4;
static {
priorities = new Hashtable<>();
jobQ = Collections.synchronizedList(new LinkedList<PageJob>());
}
static public
List<PageJob> getJobQ() {
return jobQ;
}
static private
void initPriorities(boolean structured) {
priorities.clear();
if (structured) {
/**
* structured job order for console application
* (1st finish THIS item then touch next)
*/
priorities.put(JobStatusEnum.RECON_PAGE, 0);
priorities.put(JobStatusEnum.DOWNLOAD_PAGE, 1);
priorities.put(JobStatusEnum.ADD_CHILDREN_JOBS, 2);
priorities.put(JobStatusEnum.PRESAVE_CHECK, 3);
priorities.put(JobStatusEnum.SAVE_RESULTS, 4);
priorities.put(JobStatusEnum.PAGE_DONE, 100);
priorities.put(JobStatusEnum.PAGE_FAILED, 100);
} else {
/**
* fast-preview job order for GUI application
*/
priorities.put(JobStatusEnum.ADD_CHILDREN_JOBS, 0);
priorities.put(JobStatusEnum.RECON_PAGE, 1);
priorities.put(JobStatusEnum.PRESAVE_CHECK, 2);
priorities.put(JobStatusEnum.DOWNLOAD_PAGE, 3);
priorities.put(JobStatusEnum.SAVE_RESULTS, 4);
priorities.put(JobStatusEnum.PAGE_DONE, 100);
priorities.put(JobStatusEnum.PAGE_FAILED, 100);
}
}
/**
* Called for root page; this page will be added to Q and always downloaded;
* @param saveTo - master directory in which this page results will be saved
* @param baseURL - the initial page
* @param isReadingCache - whether PageProcessor is allowed to read from cache
*/
static public synchronized
void initPageProcessor(
String saveTo, String baseURL,
Logger l,
boolean isReadingCache, String cacheFilename,
boolean isStructuredJobPriorities) {
if ((saveTo != null) && (baseURL != null))
addJob (saveTo, detectPage(baseURL), JobStatusEnum.DOWNLOAD_PAGE);
logger = l;
PageProcessor.isReadingCache = isReadingCache;
try {
PageProcessor.cache = new XMLCache(cacheFilename);
} catch (IllegalArgumentException e) {
if (logger != null) logger.log(Level.WARNING, "", e);
PageProcessor.isReadingCache = false;
// and follow with cache set to null
}
initPriorities(isStructuredJobPriorities);
}
static void saveCache () throws IOException {
cache.saveCache();
}
/**
* adds job to the shared queue
* @param j - the job
*/
static void addJob (PageJob j) {
assert (j != null);
getJobQ().add(0,j);
}
/**
* creates new job and adds it to the shared queue
* @param saveTo - directory in which this page results will be saved
* @param page - the page bound to this job
* @param status - status of a job
*/
static void addJob (String saveTo, AbstractPage page, JobStatusEnum status) {
assert (saveTo != null);
assert (page != null);
synchronized (getJobQ()) {
PageJob job = getJobForPage(page);
if (job == null)
job = new PageJob(saveTo,page,status);
else if (!job.saveTo.equals(saveTo)) {
// this weird situation normally should not happen, but who knows...
logger.log(Level.SEVERE, "Adding a job with same page and different 'saveTo': " + job.page.getTitle());
getJobQ().remove(job);
job = new PageJob(saveTo,page,status); // restart job with new location
} else {
// Hmmm... this EXACT page item is already in a Q.
logger.log(Level.SEVERE, "Adding a job with same page and same 'saveTo': " + job.page.getTitle());
synchronized (job) { job.status = status;}
}
getJobQ().add(0,job);
}
}
/**
* Detects page type by its URL address (String)
* @param baseURL - String representation of URL
* @return new PageParser descendant fitting for the page
* @throws IllegalArgumentException - when baseURL is bad or null
*/
static final public
AbstractPage detectPage(String baseURL) throws IllegalArgumentException {
URL u;
try {
u = new URL(baseURL);
} catch (MalformedURLException e) {
throw new IllegalArgumentException(e);
}
if (baseURL.contains("/track/"))
return new Track(baseURL, null);
if (baseURL.contains("/album/"))
return new Album(baseURL, null);
if (u.getPath().isEmpty() || u.getPath().equals("/"))
return new Discography(baseURL, null);
throw new IllegalArgumentException();
}
/**
* Processes all jobs in a Q and all jobs they generate
*/
static public
void acquireData() {
PageJob lastJob = null;
do {
lastJob = doSingleJob(false);
} while ( lastJob != null );
}
/**
* Get one job from the Q and do it (job may re-add itself and new jobs into the Q)
* @return PageJob that was done (in its new status)
* or null if no jobs are available;
*/
static public
PageJob doSingleJob(boolean lightWeight) {
PageJob job = null;
synchronized (getJobQ()) {
job = getNextJob(lightWeight);
if (job == null) return null;
getJobQ().remove(job);
}
synchronized (job) {
try {
processOnePage(job); // will re-add this job in a new status
} catch (ProblemsReadingDocumentException|IOException e) {
synchronized (job) {
if (job.status == JobStatusEnum.DOWNLOAD_PAGE ||
job.status == JobStatusEnum.SAVE_RESULTS) {
if ( --job.retryCount <= 0) {
if (logger != null)
logger.log(Level.WARNING, "[Failed] " + job.toString(), e);
job.status = JobStatusEnum.PAGE_FAILED;
}
addJob(job);
}
}
}
}
return job;
}
/**
* picks next job to process with the respect to priority, task profile and synchronization
* @return the job for this PageProcessor or null if there are no jobs fitting profile
*/
static
public PageJob getNextJob(boolean lightWeight) {
Integer priority = PRIORITIES_NOWORK; PageJob nextJob = null;
synchronized (getJobQ()) {
for (PageJob job: getJobQ()) {
if (priorities.get(job.status) < priority) {
priority = priorities.get(job.status);
nextJob = job;
if (priority == PRIORITIES_MIN) return nextJob; // cancel search for top priority found;
}
}
}
if (lightWeight && priority >= PRIORITIES_HEAVY)
return null;
else return nextJob;
}
/**
* logs results of acquiring metadata (from cache or web)
* @param job - the job to report about
*/
static void logInfoSurvey(PageJob job) {
AbstractPage page = job.page;
if (logger == null) return;
String method = "failed";
String log_message = null;
synchronized (job) {
if (job.isReadFromWeb) method = "web";
else if (job.isReadFromCache) method = "cache";
int childPagesNum = page.childPages.size();
log_message = String.format("%s (%s): <%s>%s%n",
page.getClass().getSimpleName(),
method,
page.url.toString(),
(childPagesNum > 0)?
String.format(" [%s] children", childPagesNum): "");
while (page.parent != null) {
log_message = "\t"+log_message;
page = page.parent;
}
}
logger.info(log_message);
}
/**
* logs results of saving page's data to disk
* @param job - the job that was saved, contains saveResultsReport field
*/
static void logDataSave(PageJob job) {
if (logger == null) return;
String result = job.saveResultsReport;
AbstractPage page = job.page;
if (result == null || result.isEmpty()) return;
String log_message = String.format("%s \"%s\" %s%n",
page.getClass().getSimpleName(),
page.getTitle().toString(),
result
);
while (page.parent != null) {
log_message = "\t"+log_message;
page = page.parent;
}
logger.info(log_message);
}
/**
* Gets one page job, does one operation on it (may fail)
* and puts job (and/or possibly new jobs) into a queue for further processing
*/
static
void processOnePage(PageJob job) throws ProblemsReadingDocumentException, IOException {
AbstractPage page = job.page;
switch (job.status) {
case RECON_PAGE:
if ((isReadingCache && job.isReadFromCache) || job.isReadFromWeb)
// this page (and its children is already processed - stop refresh here)
break;
if (isReadingCache && cache != null)
- job.isReadFromCache = page.loadFromCache(cache.doc);
+// job.isReadFromCache = page.loadFromCache(cache.doc);
if (job.isReadFromCache) {
job.status = JobStatusEnum.ADD_CHILDREN_JOBS;
logInfoSurvey(job);
}
else job.status = JobStatusEnum.DOWNLOAD_PAGE;
addJob(job);
break;
case DOWNLOAD_PAGE:
synchronized (page) {
page.downloadPage();
job.isReadFromWeb = true;
StatisticGatherer.totalPageDownloadFinished.incrementAndGet();
if (cache != null)
page.saveToCache(cache.doc);
}
job.status = JobStatusEnum.ADD_CHILDREN_JOBS;
logInfoSurvey(job);
addJob (job);
break;
case ADD_CHILDREN_JOBS:
for (AbstractPage child: page.childPages) {
String childrenSaveTo = page.getChildrenSaveTo(job.saveTo);
addJob(childrenSaveTo, child, JobStatusEnum.RECON_PAGE);
}
job.retryCount = PageJob.MAX_RETRIES; // reset retries for next faulty operation
job.status = JobStatusEnum.PRESAVE_CHECK;
addJob(job);
break;
case PRESAVE_CHECK:
if (job.page.isSavingNotRequired(job.saveTo)) {
logDataSave(job);
job.status = JobStatusEnum.PAGE_DONE;
addJob(job);
} else {
job.status = JobStatusEnum.SAVE_RESULTS;
addJob(job);
}
break;
case SAVE_RESULTS:
job.saveResultsReport = page.saveResult(job.saveTo);
logDataSave(job);
job.status = JobStatusEnum.PAGE_DONE;
addJob(job);
break;
}
}
/**
* Return the PageJob object for specific page (1-to-1 relationship)
* only this snapshot of job q is scanned! So, jobs that are temporary removed from q
* (or not added yet) can fall off the grid.
* @param page - the page to look for
* @return PageJob object for that page or null if not found or null argument
*/
public static
PageJob getJobForPage(AbstractPage page) {
if (page == null) return null;
synchronized (getJobQ()) {
// XXX: ??? Change == to URL equals compare?
for (PageJob element: getJobQ())
if (element.page == page)
return element;
}
return null;
}
}
| true | true | void processOnePage(PageJob job) throws ProblemsReadingDocumentException, IOException {
AbstractPage page = job.page;
switch (job.status) {
case RECON_PAGE:
if ((isReadingCache && job.isReadFromCache) || job.isReadFromWeb)
// this page (and its children is already processed - stop refresh here)
break;
if (isReadingCache && cache != null)
job.isReadFromCache = page.loadFromCache(cache.doc);
if (job.isReadFromCache) {
job.status = JobStatusEnum.ADD_CHILDREN_JOBS;
logInfoSurvey(job);
}
else job.status = JobStatusEnum.DOWNLOAD_PAGE;
addJob(job);
break;
case DOWNLOAD_PAGE:
synchronized (page) {
page.downloadPage();
job.isReadFromWeb = true;
StatisticGatherer.totalPageDownloadFinished.incrementAndGet();
if (cache != null)
page.saveToCache(cache.doc);
}
job.status = JobStatusEnum.ADD_CHILDREN_JOBS;
logInfoSurvey(job);
addJob (job);
break;
case ADD_CHILDREN_JOBS:
for (AbstractPage child: page.childPages) {
String childrenSaveTo = page.getChildrenSaveTo(job.saveTo);
addJob(childrenSaveTo, child, JobStatusEnum.RECON_PAGE);
}
job.retryCount = PageJob.MAX_RETRIES; // reset retries for next faulty operation
job.status = JobStatusEnum.PRESAVE_CHECK;
addJob(job);
break;
case PRESAVE_CHECK:
if (job.page.isSavingNotRequired(job.saveTo)) {
logDataSave(job);
job.status = JobStatusEnum.PAGE_DONE;
addJob(job);
} else {
job.status = JobStatusEnum.SAVE_RESULTS;
addJob(job);
}
break;
case SAVE_RESULTS:
job.saveResultsReport = page.saveResult(job.saveTo);
logDataSave(job);
job.status = JobStatusEnum.PAGE_DONE;
addJob(job);
break;
}
}
| void processOnePage(PageJob job) throws ProblemsReadingDocumentException, IOException {
AbstractPage page = job.page;
switch (job.status) {
case RECON_PAGE:
if ((isReadingCache && job.isReadFromCache) || job.isReadFromWeb)
// this page (and its children is already processed - stop refresh here)
break;
if (isReadingCache && cache != null)
// job.isReadFromCache = page.loadFromCache(cache.doc);
if (job.isReadFromCache) {
job.status = JobStatusEnum.ADD_CHILDREN_JOBS;
logInfoSurvey(job);
}
else job.status = JobStatusEnum.DOWNLOAD_PAGE;
addJob(job);
break;
case DOWNLOAD_PAGE:
synchronized (page) {
page.downloadPage();
job.isReadFromWeb = true;
StatisticGatherer.totalPageDownloadFinished.incrementAndGet();
if (cache != null)
page.saveToCache(cache.doc);
}
job.status = JobStatusEnum.ADD_CHILDREN_JOBS;
logInfoSurvey(job);
addJob (job);
break;
case ADD_CHILDREN_JOBS:
for (AbstractPage child: page.childPages) {
String childrenSaveTo = page.getChildrenSaveTo(job.saveTo);
addJob(childrenSaveTo, child, JobStatusEnum.RECON_PAGE);
}
job.retryCount = PageJob.MAX_RETRIES; // reset retries for next faulty operation
job.status = JobStatusEnum.PRESAVE_CHECK;
addJob(job);
break;
case PRESAVE_CHECK:
if (job.page.isSavingNotRequired(job.saveTo)) {
logDataSave(job);
job.status = JobStatusEnum.PAGE_DONE;
addJob(job);
} else {
job.status = JobStatusEnum.SAVE_RESULTS;
addJob(job);
}
break;
case SAVE_RESULTS:
job.saveResultsReport = page.saveResult(job.saveTo);
logDataSave(job);
job.status = JobStatusEnum.PAGE_DONE;
addJob(job);
break;
}
}
|
diff --git a/test/src/com/redhat/ceylon/compiler/java/test/misc/MiscTest.java b/test/src/com/redhat/ceylon/compiler/java/test/misc/MiscTest.java
index 4f3fa1268..ee8864ddc 100755
--- a/test/src/com/redhat/ceylon/compiler/java/test/misc/MiscTest.java
+++ b/test/src/com/redhat/ceylon/compiler/java/test/misc/MiscTest.java
@@ -1,272 +1,272 @@
/*
* Copyright Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the authors tag. All rights reserved.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License version 2.
*
* This particular file is subject to the "Classpath" exception as provided in the
* LICENSE file that accompanied this code.
*
* This program is distributed in the hope that it will be useful, but WITHOUT A
* 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 distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package com.redhat.ceylon.compiler.java.test.misc;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import javax.tools.JavaFileObject;
import junit.framework.Assert;
import org.junit.Ignore;
import org.junit.Test;
import com.redhat.ceylon.cmr.api.JDKUtils;
import com.redhat.ceylon.compiler.java.test.CompilerTest;
import com.redhat.ceylon.compiler.java.tools.CeyloncFileManager;
import com.redhat.ceylon.compiler.java.tools.CeyloncTaskImpl;
import com.redhat.ceylon.compiler.java.tools.CeyloncTool;
public class MiscTest extends CompilerTest {
@Test
public void testDefaultedModel() throws Exception{
compile("defaultedmodel/DefineDefaulted.ceylon");
compile("defaultedmodel/UseDefaulted.ceylon");
}
@Test
public void testHelloWorld(){
compareWithJavaSource("helloworld/helloworld");
}
@Test
public void runHelloWorld() throws Exception{
compileAndRun("com.redhat.ceylon.compiler.java.test.misc.helloworld.helloworld", "helloworld/helloworld.ceylon");
}
@Test
public void testCompileTwoDepdendantClasses() throws Exception{
compile("twoclasses/Two.ceylon");
compile("twoclasses/One.ceylon");
}
@Test
public void testCompileTwoClasses() throws Exception{
compileAndRun("com.redhat.ceylon.compiler.java.test.misc.twoclasses.main", "twoclasses/One.ceylon", "twoclasses/Two.ceylon", "twoclasses/main.ceylon");
}
@Test
public void testEqualsHashOverriding(){
compareWithJavaSource("equalshashoverriding/EqualsHashOverriding");
}
@Test
public void compileRuntime(){
cleanCars("build/classes-runtime");
java.util.List<File> sourceFiles = new ArrayList<File>();
String ceylonSourcePath = "../ceylon.language/src";
String javaSourcePath = "../ceylon.language/runtime";
String[] ceylonPackages = {"ceylon.language", "ceylon.language.descriptor"};
HashSet exceptions = new HashSet();
for (String ex : new String[] {
// Native files
"Array", "Boolean", "Callable", "Character", "className",
"Exception", "flatten", "Float", "identityHash", "Integer", "internalFirst", "internalSort",
- "Keys", "language", "process",
+ "Keys", "language", "process", "integerRangeByIterable",
"SequenceBuilder", "SequenceAppender", "String", "StringBuilder", "unflatten",
// Problem files
"LazySet"
}) {
exceptions.add(ex);
}
String[] extras = new String[]{
"array", "arrayOfSize", "copyArray", "false", "infinity",
- "parseFloat", "parseInteger", "string", "true"
+ "parseFloat", "parseInteger", "string", "true", "integerRangeByIterable"
};
for(String pkg : ceylonPackages){
File pkgDir = new File(ceylonSourcePath, pkg.replaceAll("\\.", "/"));
File javaPkgDir = new File(javaSourcePath, pkg.replaceAll("\\.", "/"));
File[] files = pkgDir.listFiles();
if (files != null) {
for(File src : files) {
if(src.isFile() && src.getName().toLowerCase().endsWith(".ceylon")) {
String baseName = src.getName().substring(0, src.getName().length() - 7);
if (!exceptions.contains(baseName)) {
sourceFiles.add(src);
} else {
addJavaSourceFile(baseName, sourceFiles, javaPkgDir);
}
}
}
}
}
// add extra files that are in Java
File javaPkgDir = new File(javaSourcePath, "ceylon/language");
for(String extra : extras)
addJavaSourceFile(extra, sourceFiles, javaPkgDir);
String[] javaPackages = {"ceylon.language.descriptor", "com/redhat/ceylon/compiler/java", "com/redhat/ceylon/compiler/java/language", "com/redhat/ceylon/compiler/java/metadata"};
for(String pkg : javaPackages){
File pkgDir = new File(javaSourcePath, pkg.replaceAll("\\.", "/"));
File[] files = pkgDir.listFiles();
if (files != null) {
for(File src : files) {
if(src.isFile() && src.getName().toLowerCase().endsWith(".java")) {
sourceFiles.add(src);
}
}
}
}
CeyloncTool compiler;
try {
compiler = new CeyloncTool();
} catch (VerifyError e) {
System.err.println("ERROR: Cannot run tests! Did you maybe forget to configure the -Xbootclasspath/p: parameter?");
throw e;
}
CeyloncFileManager fileManager = (CeyloncFileManager)compiler.getStandardFileManager(null, null, null);
Iterable<? extends JavaFileObject> compilationUnits1 =
fileManager.getJavaFileObjectsFromFiles(sourceFiles);
String compilerSourcePath = ceylonSourcePath + File.pathSeparator + javaSourcePath;
CeyloncTaskImpl task = (CeyloncTaskImpl) compiler.getTask(null, fileManager, null,
Arrays.asList("-sourcepath", compilerSourcePath, "-d", "build/classes-runtime", "-Xbootstrapceylon"/*, "-verbose", "-Xceylonallowduplicates"*/),
null, compilationUnits1);
Boolean result = task.call();
Assert.assertEquals("Compilation failed", Boolean.TRUE, result);
}
private void addJavaSourceFile(String baseName, List<File> sourceFiles, File javaPkgDir) {
if (Character.isLowerCase(baseName.charAt(0))) {
sourceFiles.add(new File(javaPkgDir, baseName + "_.java"));
} else {
sourceFiles.add(new File(javaPkgDir, baseName + ".java"));
File impl = new File(javaPkgDir, baseName + "$impl.java");
if (impl.exists()) {
sourceFiles.add(impl);
}
}
}
@Test
public void compileSDK(){
String[] modules = {
"collection",
"dbc",
"file",
"interop.java",
"io",
"json",
"math",
"net",
"process",
};
String sourceDir = "../ceylon-sdk/source";
// don't run this if the SDK is not checked out
File sdkFile = new File(sourceDir);
if(!sdkFile.exists())
return;
java.util.List<String> moduleNames = new ArrayList<String>(modules.length);
for(String module : modules){
moduleNames.add("ceylon." + module);
}
CeyloncTool compiler;
try {
compiler = new CeyloncTool();
} catch (VerifyError e) {
System.err.println("ERROR: Cannot run tests! Did you maybe forget to configure the -Xbootclasspath/p: parameter?");
throw e;
}
CeyloncFileManager fileManager = (CeyloncFileManager)compiler.getStandardFileManager(null, null, null);
CeyloncTaskImpl task = (CeyloncTaskImpl) compiler.getTask(null, fileManager, null,
Arrays.asList("-sourcepath", sourceDir, "-d", "build/classes-sdk"),
moduleNames, null);
Boolean result = task.call();
Assert.assertEquals("Compilation failed", Boolean.TRUE, result);
}
//
// Java keyword avoidance
// Note class names and generic type arguments are not a problem because
// in Ceylon they must begin with an upper case latter, but the Java
// keywords are all lowercase
@Test
public void testKeywordVariable(){
compareWithJavaSource("keyword/Variable");
}
@Test
public void testKeywordAttribute(){
compareWithJavaSource("keyword/Attribute");
}
@Test
public void testKeywordMethod(){
compareWithJavaSource("keyword/Method");
}
@Test
public void testKeywordParameter(){
compareWithJavaSource("keyword/Parameter");
}
@Test
public void testJDKModules(){
Assert.assertTrue(JDKUtils.isJDKModule("java.base"));
Assert.assertTrue(JDKUtils.isJDKModule("java.desktop"));
Assert.assertTrue(JDKUtils.isJDKModule("java.compiler")); // last one
Assert.assertFalse(JDKUtils.isJDKModule("java.stef"));
}
@Test
public void testJDKPackages(){
Assert.assertTrue(JDKUtils.isJDKAnyPackage("java.awt"));
Assert.assertTrue(JDKUtils.isJDKAnyPackage("java.lang"));
Assert.assertTrue(JDKUtils.isJDKAnyPackage("java.util"));
Assert.assertTrue(JDKUtils.isJDKAnyPackage("javax.swing"));
Assert.assertTrue(JDKUtils.isJDKAnyPackage("org.w3c.dom"));
Assert.assertTrue(JDKUtils.isJDKAnyPackage("org.xml.sax.helpers"));// last one
Assert.assertFalse(JDKUtils.isJDKAnyPackage("fr.epardaud"));
}
@Test
public void testOracleJDKModules(){
Assert.assertTrue(JDKUtils.isOracleJDKModule("oracle.jdk.base"));
Assert.assertTrue(JDKUtils.isOracleJDKModule("oracle.jdk.desktop"));
Assert.assertTrue(JDKUtils.isOracleJDKModule("oracle.jdk.httpserver"));
Assert.assertTrue(JDKUtils.isOracleJDKModule("oracle.jdk.tools.base")); // last one
Assert.assertFalse(JDKUtils.isOracleJDKModule("oracle.jdk.stef"));
Assert.assertFalse(JDKUtils.isOracleJDKModule("jdk.base"));
}
@Test
public void testOracleJDKPackages(){
Assert.assertTrue(JDKUtils.isOracleJDKAnyPackage("com.oracle.net"));
Assert.assertTrue(JDKUtils.isOracleJDKAnyPackage("com.sun.awt"));
Assert.assertTrue(JDKUtils.isOracleJDKAnyPackage("com.sun.imageio.plugins.bmp"));
Assert.assertTrue(JDKUtils.isOracleJDKAnyPackage("com.sun.java.swing.plaf.gtk"));
Assert.assertTrue(JDKUtils.isOracleJDKAnyPackage("com.sun.nio.sctp"));
Assert.assertTrue(JDKUtils.isOracleJDKAnyPackage("sun.nio"));
Assert.assertTrue(JDKUtils.isOracleJDKAnyPackage("sunw.util"));// last one
Assert.assertFalse(JDKUtils.isOracleJDKAnyPackage("fr.epardaud"));
}
}
| false | true | public void compileRuntime(){
cleanCars("build/classes-runtime");
java.util.List<File> sourceFiles = new ArrayList<File>();
String ceylonSourcePath = "../ceylon.language/src";
String javaSourcePath = "../ceylon.language/runtime";
String[] ceylonPackages = {"ceylon.language", "ceylon.language.descriptor"};
HashSet exceptions = new HashSet();
for (String ex : new String[] {
// Native files
"Array", "Boolean", "Callable", "Character", "className",
"Exception", "flatten", "Float", "identityHash", "Integer", "internalFirst", "internalSort",
"Keys", "language", "process",
"SequenceBuilder", "SequenceAppender", "String", "StringBuilder", "unflatten",
// Problem files
"LazySet"
}) {
exceptions.add(ex);
}
String[] extras = new String[]{
"array", "arrayOfSize", "copyArray", "false", "infinity",
"parseFloat", "parseInteger", "string", "true"
};
for(String pkg : ceylonPackages){
File pkgDir = new File(ceylonSourcePath, pkg.replaceAll("\\.", "/"));
File javaPkgDir = new File(javaSourcePath, pkg.replaceAll("\\.", "/"));
File[] files = pkgDir.listFiles();
if (files != null) {
for(File src : files) {
if(src.isFile() && src.getName().toLowerCase().endsWith(".ceylon")) {
String baseName = src.getName().substring(0, src.getName().length() - 7);
if (!exceptions.contains(baseName)) {
sourceFiles.add(src);
} else {
addJavaSourceFile(baseName, sourceFiles, javaPkgDir);
}
}
}
}
}
// add extra files that are in Java
File javaPkgDir = new File(javaSourcePath, "ceylon/language");
for(String extra : extras)
addJavaSourceFile(extra, sourceFiles, javaPkgDir);
String[] javaPackages = {"ceylon.language.descriptor", "com/redhat/ceylon/compiler/java", "com/redhat/ceylon/compiler/java/language", "com/redhat/ceylon/compiler/java/metadata"};
for(String pkg : javaPackages){
File pkgDir = new File(javaSourcePath, pkg.replaceAll("\\.", "/"));
File[] files = pkgDir.listFiles();
if (files != null) {
for(File src : files) {
if(src.isFile() && src.getName().toLowerCase().endsWith(".java")) {
sourceFiles.add(src);
}
}
}
}
CeyloncTool compiler;
try {
compiler = new CeyloncTool();
} catch (VerifyError e) {
System.err.println("ERROR: Cannot run tests! Did you maybe forget to configure the -Xbootclasspath/p: parameter?");
throw e;
}
CeyloncFileManager fileManager = (CeyloncFileManager)compiler.getStandardFileManager(null, null, null);
Iterable<? extends JavaFileObject> compilationUnits1 =
fileManager.getJavaFileObjectsFromFiles(sourceFiles);
String compilerSourcePath = ceylonSourcePath + File.pathSeparator + javaSourcePath;
CeyloncTaskImpl task = (CeyloncTaskImpl) compiler.getTask(null, fileManager, null,
Arrays.asList("-sourcepath", compilerSourcePath, "-d", "build/classes-runtime", "-Xbootstrapceylon"/*, "-verbose", "-Xceylonallowduplicates"*/),
null, compilationUnits1);
Boolean result = task.call();
Assert.assertEquals("Compilation failed", Boolean.TRUE, result);
}
| public void compileRuntime(){
cleanCars("build/classes-runtime");
java.util.List<File> sourceFiles = new ArrayList<File>();
String ceylonSourcePath = "../ceylon.language/src";
String javaSourcePath = "../ceylon.language/runtime";
String[] ceylonPackages = {"ceylon.language", "ceylon.language.descriptor"};
HashSet exceptions = new HashSet();
for (String ex : new String[] {
// Native files
"Array", "Boolean", "Callable", "Character", "className",
"Exception", "flatten", "Float", "identityHash", "Integer", "internalFirst", "internalSort",
"Keys", "language", "process", "integerRangeByIterable",
"SequenceBuilder", "SequenceAppender", "String", "StringBuilder", "unflatten",
// Problem files
"LazySet"
}) {
exceptions.add(ex);
}
String[] extras = new String[]{
"array", "arrayOfSize", "copyArray", "false", "infinity",
"parseFloat", "parseInteger", "string", "true", "integerRangeByIterable"
};
for(String pkg : ceylonPackages){
File pkgDir = new File(ceylonSourcePath, pkg.replaceAll("\\.", "/"));
File javaPkgDir = new File(javaSourcePath, pkg.replaceAll("\\.", "/"));
File[] files = pkgDir.listFiles();
if (files != null) {
for(File src : files) {
if(src.isFile() && src.getName().toLowerCase().endsWith(".ceylon")) {
String baseName = src.getName().substring(0, src.getName().length() - 7);
if (!exceptions.contains(baseName)) {
sourceFiles.add(src);
} else {
addJavaSourceFile(baseName, sourceFiles, javaPkgDir);
}
}
}
}
}
// add extra files that are in Java
File javaPkgDir = new File(javaSourcePath, "ceylon/language");
for(String extra : extras)
addJavaSourceFile(extra, sourceFiles, javaPkgDir);
String[] javaPackages = {"ceylon.language.descriptor", "com/redhat/ceylon/compiler/java", "com/redhat/ceylon/compiler/java/language", "com/redhat/ceylon/compiler/java/metadata"};
for(String pkg : javaPackages){
File pkgDir = new File(javaSourcePath, pkg.replaceAll("\\.", "/"));
File[] files = pkgDir.listFiles();
if (files != null) {
for(File src : files) {
if(src.isFile() && src.getName().toLowerCase().endsWith(".java")) {
sourceFiles.add(src);
}
}
}
}
CeyloncTool compiler;
try {
compiler = new CeyloncTool();
} catch (VerifyError e) {
System.err.println("ERROR: Cannot run tests! Did you maybe forget to configure the -Xbootclasspath/p: parameter?");
throw e;
}
CeyloncFileManager fileManager = (CeyloncFileManager)compiler.getStandardFileManager(null, null, null);
Iterable<? extends JavaFileObject> compilationUnits1 =
fileManager.getJavaFileObjectsFromFiles(sourceFiles);
String compilerSourcePath = ceylonSourcePath + File.pathSeparator + javaSourcePath;
CeyloncTaskImpl task = (CeyloncTaskImpl) compiler.getTask(null, fileManager, null,
Arrays.asList("-sourcepath", compilerSourcePath, "-d", "build/classes-runtime", "-Xbootstrapceylon"/*, "-verbose", "-Xceylonallowduplicates"*/),
null, compilationUnits1);
Boolean result = task.call();
Assert.assertEquals("Compilation failed", Boolean.TRUE, result);
}
|
diff --git a/disambiguation-author/src/main/java/pl/edu/icm/coansys/disambiguation/author/pig/extractor/EXTRACT_SNAME_DOCUMENT_METADATA.java b/disambiguation-author/src/main/java/pl/edu/icm/coansys/disambiguation/author/pig/extractor/EXTRACT_SNAME_DOCUMENT_METADATA.java
index 60885149..10addd8c 100644
--- a/disambiguation-author/src/main/java/pl/edu/icm/coansys/disambiguation/author/pig/extractor/EXTRACT_SNAME_DOCUMENT_METADATA.java
+++ b/disambiguation-author/src/main/java/pl/edu/icm/coansys/disambiguation/author/pig/extractor/EXTRACT_SNAME_DOCUMENT_METADATA.java
@@ -1,90 +1,90 @@
/*
* (C) 2010-2012 ICM UW. All rights reserved.
*/
package pl.edu.icm.coansys.disambiguation.author.pig.extractor;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import org.apache.pig.EvalFunc;
import org.apache.pig.data.DataBag;
import org.apache.pig.data.DataByteArray;
import org.apache.pig.data.DataType;
import org.apache.pig.data.DefaultDataBag;
import org.apache.pig.data.Tuple;
import org.apache.pig.data.TupleFactory;
import org.apache.pig.impl.logicalLayer.FrontendException;
import org.apache.pig.impl.logicalLayer.schema.Schema;
import pl.edu.icm.coansys.disambiguation.author.auxil.StackTraceExtractor;
import pl.edu.icm.coansys.models.DocumentProtos.Author;
import pl.edu.icm.coansys.models.DocumentProtos.DocumentWrapper;
/**
*
* @author pdendek
*/
public class EXTRACT_SNAME_DOCUMENT_METADATA extends EvalFunc<DataBag>{
@Override
public Schema outputSchema(Schema p_input){
try{
return Schema.generateNestedSchema(DataType.BAG);
}catch(FrontendException e){
throw new IllegalStateException(e);
}
}
public DataBag exec(Tuple input) throws IOException {
if (input == null || input.size() == 0)
return null;
try{
DataByteArray dba = null;
try{
- dba = (DataByteArray) input.get(1);
+ dba = (DataByteArray) input.get(0);
}catch(Exception e){
- System.out.println("Trying to cast Object ("+input.getType(1)
+ System.out.println("Trying to cast Object ("+input.getType(0)
+") to DataByteArray");
System.out.println("Failure!");
e.printStackTrace();
throw e;
}
DocumentWrapper dm = null;
try{
dm = DocumentWrapper.parseFrom(dba.get());
}catch(Exception e){
System.out.println("Trying to read ByteArray to DocumentMetadata");
System.out.println("Failure!");
e.printStackTrace();
throw e;
}
DataBag ret = new DefaultDataBag();
DataByteArray metadata =
new DataByteArray(dm.getDocumentMetadata().toByteArray());
List <Author> authors =
dm.getDocumentMetadata().getBasicMetadata().getAuthorList();
for ( int i = 0; i < authors.size(); i++ ){
String sname = authors.get(i).getSurname();
Object[] to = new Object[]{sname, metadata, i};
Tuple t = TupleFactory.getInstance().newTuple(Arrays.asList(to));
ret.add(t);
}
return ret;
}catch(Exception e){
// Throwing an exception will cause the task to fail.
throw new IOException("Caught exception processing input row:\n"
+ StackTraceExtractor.getStackTrace(e));
}
}
}
| false | true | public DataBag exec(Tuple input) throws IOException {
if (input == null || input.size() == 0)
return null;
try{
DataByteArray dba = null;
try{
dba = (DataByteArray) input.get(1);
}catch(Exception e){
System.out.println("Trying to cast Object ("+input.getType(1)
+") to DataByteArray");
System.out.println("Failure!");
e.printStackTrace();
throw e;
}
DocumentWrapper dm = null;
try{
dm = DocumentWrapper.parseFrom(dba.get());
}catch(Exception e){
System.out.println("Trying to read ByteArray to DocumentMetadata");
System.out.println("Failure!");
e.printStackTrace();
throw e;
}
DataBag ret = new DefaultDataBag();
DataByteArray metadata =
new DataByteArray(dm.getDocumentMetadata().toByteArray());
List <Author> authors =
dm.getDocumentMetadata().getBasicMetadata().getAuthorList();
for ( int i = 0; i < authors.size(); i++ ){
String sname = authors.get(i).getSurname();
Object[] to = new Object[]{sname, metadata, i};
Tuple t = TupleFactory.getInstance().newTuple(Arrays.asList(to));
ret.add(t);
}
return ret;
}catch(Exception e){
// Throwing an exception will cause the task to fail.
throw new IOException("Caught exception processing input row:\n"
+ StackTraceExtractor.getStackTrace(e));
}
}
| public DataBag exec(Tuple input) throws IOException {
if (input == null || input.size() == 0)
return null;
try{
DataByteArray dba = null;
try{
dba = (DataByteArray) input.get(0);
}catch(Exception e){
System.out.println("Trying to cast Object ("+input.getType(0)
+") to DataByteArray");
System.out.println("Failure!");
e.printStackTrace();
throw e;
}
DocumentWrapper dm = null;
try{
dm = DocumentWrapper.parseFrom(dba.get());
}catch(Exception e){
System.out.println("Trying to read ByteArray to DocumentMetadata");
System.out.println("Failure!");
e.printStackTrace();
throw e;
}
DataBag ret = new DefaultDataBag();
DataByteArray metadata =
new DataByteArray(dm.getDocumentMetadata().toByteArray());
List <Author> authors =
dm.getDocumentMetadata().getBasicMetadata().getAuthorList();
for ( int i = 0; i < authors.size(); i++ ){
String sname = authors.get(i).getSurname();
Object[] to = new Object[]{sname, metadata, i};
Tuple t = TupleFactory.getInstance().newTuple(Arrays.asList(to));
ret.add(t);
}
return ret;
}catch(Exception e){
// Throwing an exception will cause the task to fail.
throw new IOException("Caught exception processing input row:\n"
+ StackTraceExtractor.getStackTrace(e));
}
}
|
diff --git a/h2/src/main/org/h2/store/PageStore.java b/h2/src/main/org/h2/store/PageStore.java
index 0d93b16d4..b4431bc2f 100644
--- a/h2/src/main/org/h2/store/PageStore.java
+++ b/h2/src/main/org/h2/store/PageStore.java
@@ -1,1590 +1,1590 @@
/*
* Copyright 2004-2010 H2 Group. Multiple-Licensed under the H2 License,
* Version 1.0, and under the Eclipse Public License, Version 1.0
* (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.store;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.zip.CRC32;
import org.h2.command.ddl.CreateTableData;
import org.h2.constant.ErrorCode;
import org.h2.constant.SysProperties;
import org.h2.engine.Constants;
import org.h2.engine.Database;
import org.h2.engine.Session;
import org.h2.index.Cursor;
import org.h2.index.Index;
import org.h2.index.IndexType;
import org.h2.index.MultiVersionIndex;
import org.h2.index.PageBtreeIndex;
import org.h2.index.PageBtreeLeaf;
import org.h2.index.PageBtreeNode;
import org.h2.index.PageDataIndex;
import org.h2.index.PageDataLeaf;
import org.h2.index.PageDataNode;
import org.h2.index.PageDataOverflow;
import org.h2.index.PageDelegateIndex;
import org.h2.index.PageIndex;
import org.h2.message.DbException;
import org.h2.message.Trace;
import org.h2.result.Row;
import org.h2.result.SearchRow;
import org.h2.schema.Schema;
import org.h2.table.Column;
import org.h2.table.IndexColumn;
import org.h2.table.Table;
import org.h2.table.TableData;
import org.h2.util.Cache;
import org.h2.util.CacheLRU;
import org.h2.util.CacheObject;
import org.h2.util.CacheWriter;
import org.h2.util.IOUtils;
import org.h2.util.IntArray;
import org.h2.util.IntIntHashMap;
import org.h2.util.New;
import org.h2.util.StatementBuilder;
import org.h2.util.StringUtils;
import org.h2.value.CompareMode;
import org.h2.value.Value;
import org.h2.value.ValueInt;
import org.h2.value.ValueString;
/**
* This class represents a file that is organized as a number of pages. Page 0
* contains a static file header, and pages 1 and 2 both contain the variable
* file header (page 2 is a copy of page 1 and is only read if the checksum of
* page 1 is invalid). The format of page 0 is:
* <ul>
* <li>0-47: file header (3 time "-- H2 0.5/B -- \n")</li>
* <li>48-51: page size in bytes (512 - 32768, must be a power of 2)</li>
* <li>52: write version (read-only if larger than 1)</li>
* <li>53: read version (opening fails if larger than 1)</li>
* </ul>
* The format of page 1 and 2 is:
* <ul>
* <li>CRC32 of the remaining data: int (0-3)</li>
* <li>write counter (incremented on each write): long (4-11)</li>
* <li>log trunk key: int (12-15)</li>
* <li>log trunk page (0 for none): int (16-19)</li>
* <li>log data page (0 for none): int (20-23)</li>
* </ul>
* Page 3 contains the first free list page.
* Page 4 contains the meta table root page.
*/
public class PageStore implements CacheWriter {
// TODO test running out of disk space (using a special file system)
// TODO test with recovery being the default method
// TODO test reservedPages does not grow unbound
// TODO utf-x: test if it's faster
// TODO corrupt pages should be freed once in a while
// TODO node row counts are incorrect (not splitting row counts)
// TODO after opening the database, delay writing until required
// TODO optimization: try to avoid allocating a byte array per page
// TODO optimization: check if calling Data.getValueLen slows things down
// TODO order pages so that searching for a key only seeks forward
// TODO optimization: update: only log the key and changed values
// TODO index creation: use less space (ordered, split at insertion point)
// TODO detect circles in linked lists
// (input stream, free list, extend pages...)
// at runtime and recovery
// synchronized correctly (on the index?)
// TODO remove trace or use isDebugEnabled
// TODO recover tool: support syntax to delete a row with a key
// TODO don't store default values (store a special value)
// TODO split files (1 GB max size)
// TODO add a setting (that can be changed at runtime) to call fsync
// and delay on each commit
// TODO check for file size (exception if not exact size expected)
// TODO online backup using bsdiff
// TODO when removing DiskFile:
// remove CacheObject.blockCount
// remove Record.getMemorySize
// simplify InDoubtTransaction
// remove parameter in Record.write(DataPage buff)
// remove Record.getByteCount
// remove Database.objectIds
// remove TableData.checkRowCount
// remove Row.setPos
// remove database URL option RECOVER=1 option
// remove old database URL options and documentation
/**
* The smallest possible page size.
*/
public static final int PAGE_SIZE_MIN = 64;
/**
* The biggest possible page size.
*/
public static final int PAGE_SIZE_MAX = 32768;
private static final int PAGE_ID_FREE_LIST_ROOT = 3;
private static final int PAGE_ID_META_ROOT = 4;
private static final int MIN_PAGE_COUNT = 6;
private static final int INCREMENT_PAGES = 128;
private static final int READ_VERSION = 3;
private static final int WRITE_VERSION = 3;
private static final int META_TYPE_SCAN_INDEX = 0;
private static final int META_TYPE_BTREE_INDEX = 1;
private static final int META_TABLE_ID = -1;
private static final SearchRow[] EMPTY_SEARCH_ROW = new SearchRow[0];
private Database database;
private final Trace trace;
private String fileName;
private FileStore file;
private String accessMode;
private int pageSize;
private int pageSizeShift;
private long writeCountBase, writeCount, readCount;
private int logKey, logFirstTrunkPage, logFirstDataPage;
private Cache cache;
private int freeListPagesPerList;
private boolean recoveryRunning;
/**
* The file size in bytes.
*/
private long fileLength;
/**
* Number of pages (including free pages).
*/
private int pageCount;
private PageLog log;
private Schema metaSchema;
private TableData metaTable;
private PageDataIndex metaIndex;
private IntIntHashMap metaRootPageId = new IntIntHashMap();
private HashMap<Integer, PageIndex> metaObjects = New.hashMap();
/**
* The map of reserved pages, to ensure index head pages
* are not used for regular data during recovery. The key is the page id,
* and the value the latest transaction position where this page is used.
*/
private HashMap<Integer, Integer> reservedPages;
private boolean isNew;
// TODO reduce DEFAULT_MAX_LOG_SIZE, and don't divide here
private long maxLogSize = Constants.DEFAULT_MAX_LOG_SIZE / 10;
private Session systemSession;
private BitSet freed = new BitSet();
private ArrayList<PageFreeList> freeLists = New.arrayList();
/**
* The change count is something like a "micro-transaction-id".
* It is used to ensure that changed pages are not written to the file
* before the the current operation is not finished. This is only a problem
* when using a very small cache size. The value starts at 1 so that
* pages with change count 0 can be evicted from the cache.
*/
private int changeCount = 1;
private Data emptyPage;
/**
* Create a new page store object.
*
* @param database the database
* @param fileName the file name
* @param accessMode the access mode
* @param cacheSizeDefault the default cache size
*/
public PageStore(Database database, String fileName, String accessMode, int cacheSizeDefault) {
this.fileName = fileName;
this.accessMode = accessMode;
this.database = database;
trace = database.getTrace(Trace.PAGE_STORE);
// int test;
// trace.setLevel(TraceSystem.DEBUG);
String cacheType = database.getCacheType();
this.cache = CacheLRU.getCache(this, cacheType, cacheSizeDefault);
systemSession = new Session(database, null, 0);
}
/**
* Copy the next page to the output stream.
*
* @param pageId the page to copy
* @param out the output stream
* @return the new position, or -1 if there is no more data to copy
*/
public int copyDirect(int pageId, OutputStream out) throws IOException {
synchronized (database) {
byte[] buffer = new byte[pageSize];
if (pageId >= pageCount) {
return -1;
}
file.seek((long) pageId << pageSizeShift);
file.readFullyDirect(buffer, 0, pageSize);
readCount++;
out.write(buffer, 0, pageSize);
return pageId + 1;
}
}
/**
* Open the file and read the header.
*/
public void open() {
try {
metaRootPageId.put(META_TABLE_ID, PAGE_ID_META_ROOT);
if (IOUtils.exists(fileName)) {
if (IOUtils.length(fileName) < MIN_PAGE_COUNT * PAGE_SIZE_MIN) {
// the database was not fully created
openNew();
} else {
openExisting();
}
} else {
openNew();
}
} catch (DbException e) {
close();
throw e;
}
}
private void openNew() {
setPageSize(SysProperties.PAGE_SIZE);
freeListPagesPerList = PageFreeList.getPagesAddressed(pageSize);
file = database.openFile(fileName, accessMode, false);
recoveryRunning = true;
writeStaticHeader();
writeVariableHeader();
log = new PageLog(this);
increaseFileSize(MIN_PAGE_COUNT);
openMetaIndex();
logFirstTrunkPage = allocatePage();
log.openForWriting(logFirstTrunkPage, false);
isNew = true;
recoveryRunning = false;
increaseFileSize(INCREMENT_PAGES);
}
private void openExisting() {
file = database.openFile(fileName, accessMode, true);
readStaticHeader();
freeListPagesPerList = PageFreeList.getPagesAddressed(pageSize);
fileLength = file.length();
pageCount = (int) (fileLength / pageSize);
if (pageCount < MIN_PAGE_COUNT) {
close();
openNew();
return;
}
readVariableHeader();
log = new PageLog(this);
log.openForReading(logKey, logFirstTrunkPage, logFirstDataPage);
recover();
if (!database.isReadOnly()) {
recoveryRunning = true;
log.free();
logFirstTrunkPage = allocatePage();
log.openForWriting(logFirstTrunkPage, false);
recoveryRunning = false;
checkpoint();
}
}
private void writeIndexRowCounts() {
for (PageIndex index: metaObjects.values()) {
index.writeRowCount();
}
}
private void writeBack() {
ArrayList<CacheObject> list = cache.getAllChanged();
Collections.sort(list);
for (CacheObject rec : list) {
writeBack(rec);
}
}
/**
* Flush all pending changes to disk, and switch the new transaction log.
*/
public void checkpoint() {
trace.debug("checkpoint");
if (log == null || database.isReadOnly()) {
// the file was never fully opened
return;
}
synchronized (database) {
database.checkPowerOff();
writeIndexRowCounts();
writeBack();
log.checkpoint();
switchLog();
// write back the free list
writeBack();
byte[] empty = new byte[pageSize];
for (int i = PAGE_ID_FREE_LIST_ROOT; i < pageCount; i++) {
if (isUsed(i)) {
freed.clear(i);
} else if (!freed.get(i)) {
if (trace.isDebugEnabled()) {
trace.debug("free " + i);
}
freed.set(i);
file.seek((long) i << pageSizeShift);
file.write(empty, 0, pageSize);
writeCount++;
}
}
}
}
/**
* Shrink the file so there are no empty pages at the end.
*
* @param fully if the database should be fully compressed
*/
public void compact(boolean fully) {
if (!SysProperties.PAGE_STORE_TRIM) {
return;
}
// find the last used page
int lastUsed = -1;
for (int i = getFreeListId(pageCount); i >= 0; i--) {
lastUsed = getFreeList(i).getLastUsed();
if (lastUsed != -1) {
break;
}
}
// open a new log at the very end
// (to be truncated later)
writeBack();
recoveryRunning = true;
try {
log.free();
logFirstTrunkPage = lastUsed + 1;
allocatePage(logFirstTrunkPage);
log.openForWriting(logFirstTrunkPage, true);
} finally {
recoveryRunning = false;
}
long start = System.currentTimeMillis();
int maxCompactTime = SysProperties.MAX_COMPACT_TIME;
int maxMove = SysProperties.MAX_COMPACT_COUNT;
if (fully) {
maxCompactTime = Integer.MAX_VALUE;
maxMove = Integer.MAX_VALUE;
}
for (int x = lastUsed, j = 0; x > MIN_PAGE_COUNT && j < maxMove; x--, j++) {
compact(x);
long now = System.currentTimeMillis();
if (now > start + maxCompactTime) {
break;
}
}
writeIndexRowCounts();
writeBack();
// truncate the log
recoveryRunning = true;
try {
log.free();
setLogFirstPage(0, 0, 0);
} finally {
recoveryRunning = false;
}
writeBack();
for (int i = getFreeListId(pageCount); i >= 0; i--) {
lastUsed = getFreeList(i).getLastUsed();
if (lastUsed != -1) {
break;
}
}
int newPageCount = lastUsed + 1;
if (newPageCount < pageCount) {
freed.set(newPageCount, pageCount, false);
}
pageCount = newPageCount;
// the easiest way to remove superfluous entries
freeLists.clear();
trace.debug("pageCount:" + pageCount);
long newLength = (long) pageCount << pageSizeShift;
if (file.length() != newLength) {
file.setLength(newLength);
writeCount++;
}
}
private void compact(int full) {
int free = -1;
for (int i = 0; i < pageCount; i++) {
free = getFreeList(i).getFirstFree();
if (free != -1) {
break;
}
}
if (free == -1 || free >= full) {
return;
}
Page f = (Page) cache.get(free);
if (f != null) {
DbException.throwInternalError("not free: " + f);
}
if (isUsed(full)) {
Page p = getPage(full);
if (p != null) {
trace.debug("move " + p.getPos() + " to " + free);
long logSection = log.getLogSectionId(), logPos = log.getLogPos();
try {
p.moveTo(systemSession, free);
} finally {
changeCount++;
}
if (log.getLogSectionId() == logSection || log.getLogPos() != logPos) {
commit(systemSession);
}
} else {
freePage(full);
}
}
}
/**
* Read a page from the store.
*
* @param pageId the page id
* @return the page
*/
public Page getPage(int pageId) {
synchronized (database) {
Page p = (Page) cache.find(pageId);
if (p != null) {
return p;
}
}
Data data = createData();
readPage(pageId, data);
int type = data.readByte();
if (type == Page.TYPE_EMPTY) {
return null;
}
data.readShortInt();
data.readInt();
if (!checksumTest(data.getBytes(), pageId, pageSize)) {
throw DbException.get(ErrorCode.FILE_CORRUPTED_1, "wrong checksum");
}
Page p;
switch (type & ~Page.FLAG_LAST) {
case Page.TYPE_FREE_LIST:
p = PageFreeList.read(this, data, pageId);
break;
case Page.TYPE_DATA_LEAF: {
int indexId = data.readVarInt();
PageDataIndex index = (PageDataIndex) metaObjects.get(indexId);
if (index == null) {
throw DbException.get(ErrorCode.FILE_CORRUPTED_1, "index not found " + indexId);
}
p = PageDataLeaf.read(index, data, pageId);
break;
}
case Page.TYPE_DATA_NODE: {
int indexId = data.readVarInt();
PageDataIndex index = (PageDataIndex) metaObjects.get(indexId);
if (index == null) {
throw DbException.get(ErrorCode.FILE_CORRUPTED_1, "index not found " + indexId);
}
p = PageDataNode.read(index, data, pageId);
break;
}
case Page.TYPE_DATA_OVERFLOW: {
p = PageDataOverflow.read(this, data, pageId);
break;
}
case Page.TYPE_BTREE_LEAF: {
int indexId = data.readVarInt();
PageBtreeIndex index = (PageBtreeIndex) metaObjects.get(indexId);
if (index == null) {
throw DbException.get(ErrorCode.FILE_CORRUPTED_1, "index not found " + indexId);
}
p = PageBtreeLeaf.read(index, data, pageId);
break;
}
case Page.TYPE_BTREE_NODE: {
int indexId = data.readVarInt();
PageBtreeIndex index = (PageBtreeIndex) metaObjects.get(indexId);
if (index == null) {
throw DbException.get(ErrorCode.FILE_CORRUPTED_1, "index not found " + indexId);
}
p = PageBtreeNode.read(index, data, pageId);
break;
}
case Page.TYPE_STREAM_TRUNK:
p = PageStreamTrunk.read(this, data, pageId);
break;
case Page.TYPE_STREAM_DATA:
p = PageStreamData.read(this, data, pageId);
break;
default:
throw DbException.get(ErrorCode.FILE_CORRUPTED_1, "page=" + pageId + " type=" + type);
}
cache.put(p);
return p;
}
private void switchLog() {
trace.debug("switchLog");
Session[] sessions = database.getSessions(true);
int firstUncommittedSection = log.getLogSectionId();
for (int i = 0; i < sessions.length; i++) {
Session session = sessions[i];
int firstUncommitted = session.getFirstUncommittedLog();
if (firstUncommitted != Session.LOG_WRITTEN) {
if (firstUncommitted < firstUncommittedSection) {
firstUncommittedSection = firstUncommitted;
}
}
}
log.removeUntil(firstUncommittedSection);
}
private void readStaticHeader() {
file.seek(FileStore.HEADER_LENGTH);
Data page = Data.create(database, new byte[PAGE_SIZE_MIN - FileStore.HEADER_LENGTH]);
file.readFully(page.getBytes(), 0, PAGE_SIZE_MIN - FileStore.HEADER_LENGTH);
readCount++;
setPageSize(page.readInt());
int writeVersion = page.readByte();
int readVersion = page.readByte();
if (readVersion > READ_VERSION) {
throw DbException.get(ErrorCode.FILE_VERSION_ERROR_1, fileName);
}
if (writeVersion > WRITE_VERSION) {
close();
database.setReadOnly(true);
accessMode = "r";
file = database.openFile(fileName, accessMode, true);
}
}
private void readVariableHeader() {
Data page = createData();
for (int i = 1;; i++) {
if (i == 3) {
throw DbException.get(ErrorCode.FILE_CORRUPTED_1, fileName);
}
page.reset();
readPage(i, page);
CRC32 crc = new CRC32();
crc.update(page.getBytes(), 4, pageSize - 4);
int expected = (int) crc.getValue();
int got = page.readInt();
if (expected == got) {
writeCountBase = page.readLong();
logKey = page.readInt();
logFirstTrunkPage = page.readInt();
logFirstDataPage = page.readInt();
break;
}
}
}
/**
* Set the page size. The size must be a power of two. This method must be
* called before opening.
*
* @param size the page size
*/
private void setPageSize(int size) {
if (size < PAGE_SIZE_MIN || size > PAGE_SIZE_MAX) {
throw DbException.get(ErrorCode.FILE_CORRUPTED_1, fileName);
}
boolean good = false;
int shift = 0;
for (int i = 1; i <= size;) {
if (size == i) {
good = true;
break;
}
shift++;
i += i;
}
if (!good) {
throw DbException.get(ErrorCode.FILE_CORRUPTED_1, fileName);
}
pageSize = size;
emptyPage = createData();
pageSizeShift = shift;
}
private void writeStaticHeader() {
Data page = Data.create(database, new byte[pageSize - FileStore.HEADER_LENGTH]);
page.writeInt(pageSize);
page.writeByte((byte) WRITE_VERSION);
page.writeByte((byte) READ_VERSION);
file.seek(FileStore.HEADER_LENGTH);
file.write(page.getBytes(), 0, pageSize - FileStore.HEADER_LENGTH);
writeCount++;
}
/**
* Set the trunk page and data page id of the log.
*
* @param logKey the log key of the trunk page
* @param trunkPageId the trunk page id
* @param dataPageId the data page id
*/
void setLogFirstPage(int logKey, int trunkPageId, int dataPageId) {
if (trace.isDebugEnabled()) {
trace.debug("setLogFirstPage key: " + logKey + " trunk: " + trunkPageId + " data: " + dataPageId);
}
this.logKey = logKey;
this.logFirstTrunkPage = trunkPageId;
this.logFirstDataPage = dataPageId;
writeVariableHeader();
}
private void writeVariableHeader() {
Data page = createData();
page.writeInt(0);
page.writeLong(getWriteCountTotal());
page.writeInt(logKey);
page.writeInt(logFirstTrunkPage);
page.writeInt(logFirstDataPage);
CRC32 crc = new CRC32();
crc.update(page.getBytes(), 4, pageSize - 4);
page.setInt(0, (int) crc.getValue());
file.seek(pageSize);
file.write(page.getBytes(), 0, pageSize);
file.seek(pageSize + pageSize);
file.write(page.getBytes(), 0, pageSize);
// don't increment the write counter, because it was just written
}
/**
* Close the file without further writing.
*/
public void close() {
trace.debug("close");
if (log != null) {
log.close();
log = null;
}
if (file != null) {
try {
file.close();
} finally {
file = null;
}
}
}
public void flushLog() {
if (file != null) {
synchronized (database) {
log.flush();
}
}
}
/**
* Flush the transaction log and sync the file.
*/
public void sync() {
if (file != null) {
synchronized (database) {
log.flush();
file.sync();
}
}
}
public Trace getTrace() {
return trace;
}
public void writeBack(CacheObject obj) {
synchronized (database) {
Page record = (Page) obj;
if (trace.isDebugEnabled()) {
trace.debug("writeBack " + record);
}
record.write();
record.setChanged(false);
}
}
/**
* Write an undo log entry if required.
*
* @param page the page
* @param old the old data (if known) or null
*/
public void logUndo(Page page, Data old) {
synchronized (database) {
if (trace.isDebugEnabled()) {
// if (!record.isChanged()) {
// trace.debug("logUndo " + record.toString());
// }
}
checkOpen();
database.checkWritingAllowed();
if (!recoveryRunning) {
int pos = page.getPos();
if (!log.getUndo(pos)) {
if (old == null) {
old = readPage(pos);
}
log.addUndo(pos, old);
}
}
}
}
/**
* Update a page.
*
* @param page the page
*/
public void update(Page page) {
synchronized (database) {
if (trace.isDebugEnabled()) {
if (!page.isChanged()) {
trace.debug("updateRecord " + page.toString());
}
}
checkOpen();
database.checkWritingAllowed();
page.setChanged(true);
int pos = page.getPos();
if (SysProperties.CHECK && !recoveryRunning) {
// ensure the undo entry is already written
log.addUndo(pos, null);
}
allocatePage(pos);
cache.update(pos, page);
}
}
private int getFreeListId(int pageId) {
return (pageId - PAGE_ID_FREE_LIST_ROOT) / freeListPagesPerList;
}
private PageFreeList getFreeListForPage(int pageId) {
return getFreeList(getFreeListId(pageId));
}
private PageFreeList getFreeList(int i) {
PageFreeList list = null;
if (i < freeLists.size()) {
list = freeLists.get(i);
if (list != null) {
return list;
}
}
int p = PAGE_ID_FREE_LIST_ROOT + i * freeListPagesPerList;
while (p >= pageCount) {
increaseFileSize(INCREMENT_PAGES);
}
if (p < pageCount) {
list = (PageFreeList) getPage(p);
}
if (list == null) {
list = PageFreeList.create(this, p);
cache.put(list);
}
while (freeLists.size() <= i) {
freeLists.add(null);
}
freeLists.set(i, list);
return list;
}
private void freePage(int pageId) {
PageFreeList list = getFreeListForPage(pageId);
list.free(pageId);
}
/**
* Set the bit of an already allocated page.
*
* @param pageId the page to allocate
*/
void allocatePage(int pageId) {
PageFreeList list = getFreeListForPage(pageId);
list.allocate(pageId);
}
private boolean isUsed(int pageId) {
return getFreeListForPage(pageId).isUsed(pageId);
}
/**
* Allocate a number of pages.
*
* @param list the list where to add the allocated pages
* @param pagesToAllocate the number of pages to allocate
* @param exclude the exclude list
* @param after all allocated pages are higher than this page
*/
void allocatePages(IntArray list, int pagesToAllocate, BitSet exclude, int after) {
for (int i = 0; i < pagesToAllocate; i++) {
int page = allocatePage(exclude, after);
after = page;
list.add(page);
}
}
/**
* Allocate a page.
*
* @return the page id
*/
public int allocatePage() {
int pos = allocatePage(null, 0);
if (!recoveryRunning) {
log.addUndo(pos, emptyPage);
}
return pos;
}
private int allocatePage(BitSet exclude, int first) {
int page;
synchronized (database) {
// TODO could remember the first possible free list page
for (int i = 0;; i++) {
PageFreeList list = getFreeList(i);
page = list.allocate(exclude, first);
if (page >= 0) {
break;
}
}
if (page >= pageCount) {
increaseFileSize(INCREMENT_PAGES);
}
if (trace.isDebugEnabled()) {
// trace.debug("allocatePage " + pos);
}
return page;
}
}
private void increaseFileSize(int increment) {
for (int i = pageCount; i < pageCount + increment; i++) {
freed.set(i);
}
pageCount += increment;
long newLength = (long) pageCount << pageSizeShift;
file.setLength(newLength);
writeCount++;
fileLength = newLength;
}
/**
* Add a page to the free list. The undo log entry must have been written.
*
* @param pageId the page id
*/
public void free(int pageId) {
free(pageId, true);
}
/**
* Add a page to the free list.
*
* @param pageId the page id
* @param undo if the undo record must have been written
*/
void free(int pageId, boolean undo) {
if (trace.isDebugEnabled()) {
// trace.debug("freePage " + pageId);
}
synchronized (database) {
cache.remove(pageId);
if (SysProperties.CHECK && !recoveryRunning && undo) {
// ensure the undo entry is already written
log.addUndo(pageId, null);
}
freePage(pageId);
if (recoveryRunning) {
writePage(pageId, createData());
}
}
}
/**
* Create a data object.
*
* @return the data page.
*/
public Data createData() {
return Data.create(database, new byte[pageSize]);
}
/**
* Read a page.
*
* @param pos the page id
* @return the page
*/
public Data readPage(int pos) {
Data page = createData();
readPage(pos, page);
return page;
}
/**
* Read a page.
*
* @param pos the page id
* @param page the page
*/
void readPage(int pos, Data page) {
synchronized (database) {
if (pos < 0 || pos >= pageCount) {
throw DbException.get(ErrorCode.FILE_CORRUPTED_1, pos + " of " + pageCount);
}
file.seek((long) pos << pageSizeShift);
file.readFully(page.getBytes(), 0, pageSize);
readCount++;
}
}
/**
* Get the page size.
*
* @return the page size
*/
public int getPageSize() {
return pageSize;
}
/**
* Get the number of pages (including free pages).
*
* @return the page count
*/
public int getPageCount() {
return pageCount;
}
/**
* Write a page.
*
* @param pageId the page id
* @param data the data
*/
public void writePage(int pageId, Data data) {
if (pageId <= 0) {
DbException.throwInternalError("write to page " + pageId);
}
byte[] bytes = data.getBytes();
if (SysProperties.CHECK) {
boolean shouldBeFreeList = (pageId - PAGE_ID_FREE_LIST_ROOT) % freeListPagesPerList == 0;
boolean isFreeList = bytes[0] == Page.TYPE_FREE_LIST;
if (bytes[0] != 0 && shouldBeFreeList != isFreeList) {
throw DbException.throwInternalError();
}
}
checksumSet(bytes, pageId);
synchronized (database) {
file.seek((long) pageId << pageSizeShift);
file.write(bytes, 0, pageSize);
writeCount++;
}
}
/**
* Remove a page from the cache.
*
* @param pageId the page id
*/
public void removeRecord(int pageId) {
synchronized (database) {
cache.remove(pageId);
}
}
Database getDatabase() {
return database;
}
/**
* Run recovery.
*/
private void recover() {
trace.debug("log recover");
recoveryRunning = true;
log.recover(PageLog.RECOVERY_STAGE_UNDO);
if (reservedPages != null) {
for (int r : reservedPages.keySet()) {
if (trace.isDebugEnabled()) {
trace.debug("reserve " + r);
}
allocatePage(r);
}
}
log.recover(PageLog.RECOVERY_STAGE_ALLOCATE);
openMetaIndex();
readMetaData();
log.recover(PageLog.RECOVERY_STAGE_REDO);
boolean setReadOnly = false;
if (!database.isReadOnly()) {
if (log.getInDoubtTransactions().size() == 0) {
log.recoverEnd();
switchLog();
} else {
setReadOnly = true;
}
}
PageDataIndex systemTable = (PageDataIndex) metaObjects.get(0);
isNew = systemTable == null;
for (Iterator<PageIndex> it = metaObjects.values().iterator(); it.hasNext();) {
Index openIndex = it.next();
if (openIndex.getTable().isTemporary()) {
openIndex.truncate(systemSession);
openIndex.remove(systemSession);
removeMetaIndex(openIndex, systemSession);
it.remove();
} else {
openIndex.close(systemSession);
}
}
allocatePage(PAGE_ID_META_ROOT);
writeIndexRowCounts();
recoveryRunning = false;
reservedPages = null;
writeBack();
// clear the cache because it contains pages with closed indexes
cache.clear();
freeLists.clear();
metaObjects.clear();
metaObjects.put(-1, metaIndex);
if (setReadOnly) {
database.setReadOnly(true);
}
trace.debug("log recover done");
}
/**
* A record is added to a table, or removed from a table.
*
* @param session the session
* @param tableId the table id
* @param row the row to add
* @param add true if the row is added, false if it is removed
*/
public void logAddOrRemoveRow(Session session, int tableId, Row row, boolean add) {
synchronized (database) {
if (!recoveryRunning) {
log.logAddOrRemoveRow(session, tableId, row, add);
}
}
}
/**
* Mark a committed transaction.
*
* @param session the session
*/
public void commit(Session session) {
synchronized (database) {
checkOpen();
log.commit(session.getId());
if (log.getSize() > maxLogSize) {
checkpoint();
}
}
}
/**
* Prepare a transaction.
*
* @param session the session
* @param transaction the name of the transaction
*/
public void prepareCommit(Session session, String transaction) {
synchronized (database) {
log.prepareCommit(session, transaction);
}
}
/**
* Check whether this is a new database.
*
* @return true if it is
*/
public boolean isNew() {
return isNew;
}
/**
* Reserve the page if this is a index root page entry.
*
* @param logPos the redo log position
* @param tableId the table id
* @param row the row
*/
void allocateIfIndexRoot(int logPos, int tableId, Row row) {
if (tableId == META_TABLE_ID) {
int rootPageId = row.getValue(3).getInt();
if (reservedPages == null) {
reservedPages = New.hashMap();
}
reservedPages.put(rootPageId, logPos);
}
}
/**
* Redo a delete in a table.
*
* @param logPos the redo log position
* @param tableId the object id of the table
* @param key the key of the row to delete
*/
void redoDelete(int logPos, int tableId, long key) {
Index index = metaObjects.get(tableId);
PageDataIndex scan = (PageDataIndex) index;
Row row = scan.getRow(key);
redo(logPos, tableId, row, false);
}
/**
* Redo a change in a table.
*
* @param logPos the redo log position
* @param tableId the object id of the table
* @param row the row
* @param add true if the record is added, false if deleted
*/
void redo(int logPos, int tableId, Row row, boolean add) {
if (tableId == META_TABLE_ID) {
if (add) {
addMeta(row, systemSession, true);
} else {
removeMeta(logPos, row);
}
}
Index index = metaObjects.get(tableId);
if (index == null) {
throw DbException.throwInternalError("Table not found: " + tableId + " " + row + " " + add);
}
Table table = index.getTable();
if (add) {
table.addRow(systemSession, row);
} else {
table.removeRow(systemSession, row);
}
}
/**
* Redo a truncate.
*
* @param tableId the object id of the table
*/
void redoTruncate(int tableId) {
Index index = metaObjects.get(tableId);
Table table = index.getTable();
table.truncate(systemSession);
}
private void openMetaIndex() {
CreateTableData data = new CreateTableData();
ArrayList<Column> cols = data.columns;
cols.add(new Column("ID", Value.INT));
cols.add(new Column("TYPE", Value.INT));
cols.add(new Column("PARENT", Value.INT));
cols.add(new Column("HEAD", Value.INT));
cols.add(new Column("OPTIONS", Value.STRING));
cols.add(new Column("COLUMNS", Value.STRING));
metaSchema = new Schema(database, 0, "", null, true);
data.schema = metaSchema;
data.tableName = "PAGE_INDEX";
data.id = META_TABLE_ID;
data.temporary = false;
data.persistData = true;
data.persistIndexes = true;
data.create = false;
data.session = systemSession;
metaTable = new TableData(data);
metaIndex = (PageDataIndex) metaTable.getScanIndex(
systemSession);
metaObjects.clear();
metaObjects.put(-1, metaIndex);
}
private void readMetaData() {
Cursor cursor = metaIndex.find(systemSession, null, null);
while (cursor.next()) {
Row row = cursor.get();
addMeta(row, systemSession, false);
}
}
private void removeMeta(int logPos, Row row) {
int id = row.getValue(0).getInt();
PageIndex index = metaObjects.get(id);
int rootPageId = index.getRootPageId();
index.getTable().removeIndex(index);
if (index instanceof PageBtreeIndex) {
if (index.isTemporary()) {
systemSession.removeLocalTempTableIndex(index);
} else {
index.getSchema().remove(index);
}
} else if (index instanceof PageDelegateIndex) {
index.getSchema().remove(index);
}
index.remove(systemSession);
metaObjects.remove(id);
if (reservedPages != null && reservedPages.containsKey(rootPageId)) {
// re-allocate the page if it is used later on again
int latestPos = reservedPages.get(rootPageId);
if (latestPos > logPos) {
allocatePage(rootPageId);
}
}
}
private void addMeta(Row row, Session session, boolean redo) {
int id = row.getValue(0).getInt();
int type = row.getValue(1).getInt();
int parent = row.getValue(2).getInt();
int rootPageId = row.getValue(3).getInt();
String options = row.getValue(4).getString();
String columnList = row.getValue(5).getString();
String[] columns = StringUtils.arraySplit(columnList, ',', false);
String[] ops = StringUtils.arraySplit(options, ',', false);
Index meta;
if (trace.isDebugEnabled()) {
trace.debug("addMeta id=" + id + " type=" + type + " parent=" + parent + " columns=" + columnList);
}
if (redo && rootPageId != 0) {
// ensure the page is empty, but not used by regular data
writePage(rootPageId, createData());
allocatePage(rootPageId);
}
metaRootPageId.put(id, rootPageId);
if (type == META_TYPE_SCAN_INDEX) {
CreateTableData data = new CreateTableData();
for (int i = 0; i < columns.length; i++) {
Column col = new Column("C" + i, Value.INT);
data.columns.add(col);
}
data.schema = metaSchema;
data.tableName = "T" + id;
data.id = id;
data.temporary = ops[2].equals("temp");
data.persistData = true;
data.persistIndexes = true;
data.create = false;
data.session = session;
TableData table = new TableData(data);
CompareMode mode = CompareMode.getInstance(ops[0], Integer.parseInt(ops[1]));
table.setCompareMode(mode);
meta = table.getScanIndex(session);
} else {
Index p = metaObjects.get(parent);
if (p == null) {
- throw DbException.throwInternalError("parent not found:" + parent);
+ throw DbException.get(ErrorCode.FILE_CORRUPTED_1, "Table not found:" + parent + " for " + row + " meta:" + metaObjects);
}
TableData table = (TableData) p.getTable();
Column[] tableCols = table.getColumns();
IndexColumn[] cols = new IndexColumn[columns.length];
for (int i = 0; i < columns.length; i++) {
String c = columns[i];
IndexColumn ic = new IndexColumn();
int idx = c.indexOf('/');
if (idx >= 0) {
String s = c.substring(idx + 1);
ic.sortType = Integer.parseInt(s);
c = c.substring(0, idx);
}
Column column = tableCols[Integer.parseInt(c)];
ic.column = column;
cols[i] = ic;
}
IndexType indexType;
if (ops[3].equals("d")) {
indexType = IndexType.createPrimaryKey(true, false);
Column[] tableColumns = table.getColumns();
for (int i = 0; i < cols.length; i++) {
tableColumns[cols[i].column.getColumnId()].setNullable(false);
}
} else {
indexType = IndexType.createNonUnique(true);
}
meta = table.addIndex(session, "I" + id, id, cols, indexType, false, null);
}
PageIndex index;
if (meta instanceof MultiVersionIndex) {
index = (PageIndex) ((MultiVersionIndex) meta).getBaseIndex();
} else {
index = (PageIndex) meta;
}
metaObjects.put(id, index);
}
/**
* Add an index to the in-memory index map.
*
* @param index the index
*/
public void addIndex(PageIndex index) {
metaObjects.put(index.getId(), index);
}
/**
* Add the meta data of an index.
*
* @param index the index to add
* @param session the session
*/
public void addMeta(PageIndex index, Session session) {
int type = index instanceof PageDataIndex ? META_TYPE_SCAN_INDEX : META_TYPE_BTREE_INDEX;
IndexColumn[] columns = index.getIndexColumns();
StatementBuilder buff = new StatementBuilder();
for (IndexColumn col : columns) {
buff.appendExceptFirst(",");
int id = col.column.getColumnId();
buff.append(id);
int sortType = col.sortType;
if (sortType != 0) {
buff.append('/');
buff.append(sortType);
}
}
String columnList = buff.toString();
Table table = index.getTable();
CompareMode mode = table.getCompareMode();
String options = mode.getName()+ "," + mode.getStrength() + ",";
if (table.isTemporary()) {
options += "temp";
}
options += ",";
if (index instanceof PageDelegateIndex) {
options += "d";
}
Row row = metaTable.getTemplateRow();
row.setValue(0, ValueInt.get(index.getId()));
row.setValue(1, ValueInt.get(type));
row.setValue(2, ValueInt.get(table.getId()));
row.setValue(3, ValueInt.get(index.getRootPageId()));
row.setValue(4, ValueString.get(options));
row.setValue(5, ValueString.get(columnList));
row.setKey(index.getId() + 1);
metaIndex.add(session, row);
}
/**
* Remove the meta data of an index.
*
* @param index the index to remove
* @param session the session
*/
public void removeMeta(Index index, Session session) {
if (!recoveryRunning) {
removeMetaIndex(index, session);
metaObjects.remove(index.getId());
}
}
private void removeMetaIndex(Index index, Session session) {
int key = index.getId() + 1;
Row row = metaIndex.getRow(session, key);
if (row.getKey() != key) {
DbException.throwInternalError();
}
metaIndex.remove(session, row);
}
/**
* Set the maximum transaction log size in megabytes.
*
* @param maxSize the new maximum log size
*/
public void setMaxLogSize(long maxSize) {
this.maxLogSize = maxSize;
}
/**
* Commit or rollback a prepared transaction after opening a database with
* in-doubt transactions.
*
* @param sessionId the session id
* @param pageId the page where the transaction was prepared
* @param commit if the transaction should be committed
*/
public void setInDoubtTransactionState(int sessionId, int pageId, boolean commit) {
boolean old = database.isReadOnly();
try {
database.setReadOnly(false);
log.setInDoubtTransactionState(sessionId, pageId, commit);
} finally {
database.setReadOnly(old);
}
}
/**
* Get the list of in-doubt transaction.
*
* @return the list
*/
public ArrayList<InDoubtTransaction> getInDoubtTransactions() {
return log.getInDoubtTransactions();
}
/**
* Check whether the recovery process is currently running.
*
* @return true if it is
*/
public boolean isRecoveryRunning() {
return this.recoveryRunning;
}
private void checkOpen() {
if (file == null) {
throw DbException.get(ErrorCode.DATABASE_IS_CLOSED);
}
}
/**
* Create an array of SearchRow with the given size.
*
* @param entryCount the number of elements
* @return the array
*/
public static SearchRow[] newSearchRows(int entryCount) {
if (entryCount == 0) {
return EMPTY_SEARCH_ROW;
}
return new SearchRow[entryCount];
}
/**
* Get the file write count since the database was created.
*
* @return the write count
*/
public long getWriteCountTotal() {
return writeCount + writeCountBase;
}
/**
* Get the file write count since the database was opened.
*
* @return the write count
*/
public long getWriteCount() {
return writeCount;
}
/**
* Get the file read count since the database was opened.
*
* @return the read count
*/
public long getReadCount() {
return readCount;
}
/**
* A table is truncated.
*
* @param session the session
* @param tableId the table id
*/
public void logTruncate(Session session, int tableId) {
synchronized (database) {
if (!recoveryRunning) {
log.logTruncate(session, tableId);
}
}
}
/**
* Get the root page of an index.
*
* @param indexId the index id
* @return the root page
*/
public int getRootPageId(int indexId) {
return metaRootPageId.get(indexId);
}
public Cache getCache() {
return cache;
}
private void checksumSet(byte[] d, int pageId) {
int ps = pageSize;
int type = d[0];
if (type == Page.TYPE_EMPTY) {
return;
}
int s1 = 255 + (type & 255), s2 = 255 + s1;
s2 += s1 += d[6] & 255;
s2 += s1 += d[(ps >> 1) - 1] & 255;
s2 += s1 += d[ps >> 1] & 255;
s2 += s1 += d[ps - 2] & 255;
s2 += s1 += d[ps - 1] & 255;
d[1] = (byte) (((s1 & 255) + (s1 >> 8)) ^ pageId);
d[2] = (byte) (((s2 & 255) + (s2 >> 8)) ^ (pageId >> 8));
}
/**
* Check if the stored checksum is correct
* @param d the data
* @param pageId the page id
* @param pageSize the page size
* @return true if it is correct
*/
public static boolean checksumTest(byte[] d, int pageId, int pageSize) {
int ps = pageSize;
int s1 = 255 + (d[0] & 255), s2 = 255 + s1;
s2 += s1 += d[6] & 255;
s2 += s1 += d[(ps >> 1) - 1] & 255;
s2 += s1 += d[ps >> 1] & 255;
s2 += s1 += d[ps - 2] & 255;
s2 += s1 += d[ps - 1] & 255;
if (d[1] != (byte) (((s1 & 255) + (s1 >> 8)) ^ pageId)
|| d[2] != (byte) (((s2 & 255) + (s2 >> 8)) ^ (pageId >> 8))) {
return false;
}
return true;
}
/**
* Increment the change count. To be done after the operation has finished.
*/
public void incrementChangeCount() {
changeCount++;
}
/**
* Get the current change count. The first value is 1
*
* @return the change count
*/
public int getChangeCount() {
return changeCount;
}
}
| true | true | private void addMeta(Row row, Session session, boolean redo) {
int id = row.getValue(0).getInt();
int type = row.getValue(1).getInt();
int parent = row.getValue(2).getInt();
int rootPageId = row.getValue(3).getInt();
String options = row.getValue(4).getString();
String columnList = row.getValue(5).getString();
String[] columns = StringUtils.arraySplit(columnList, ',', false);
String[] ops = StringUtils.arraySplit(options, ',', false);
Index meta;
if (trace.isDebugEnabled()) {
trace.debug("addMeta id=" + id + " type=" + type + " parent=" + parent + " columns=" + columnList);
}
if (redo && rootPageId != 0) {
// ensure the page is empty, but not used by regular data
writePage(rootPageId, createData());
allocatePage(rootPageId);
}
metaRootPageId.put(id, rootPageId);
if (type == META_TYPE_SCAN_INDEX) {
CreateTableData data = new CreateTableData();
for (int i = 0; i < columns.length; i++) {
Column col = new Column("C" + i, Value.INT);
data.columns.add(col);
}
data.schema = metaSchema;
data.tableName = "T" + id;
data.id = id;
data.temporary = ops[2].equals("temp");
data.persistData = true;
data.persistIndexes = true;
data.create = false;
data.session = session;
TableData table = new TableData(data);
CompareMode mode = CompareMode.getInstance(ops[0], Integer.parseInt(ops[1]));
table.setCompareMode(mode);
meta = table.getScanIndex(session);
} else {
Index p = metaObjects.get(parent);
if (p == null) {
throw DbException.throwInternalError("parent not found:" + parent);
}
TableData table = (TableData) p.getTable();
Column[] tableCols = table.getColumns();
IndexColumn[] cols = new IndexColumn[columns.length];
for (int i = 0; i < columns.length; i++) {
String c = columns[i];
IndexColumn ic = new IndexColumn();
int idx = c.indexOf('/');
if (idx >= 0) {
String s = c.substring(idx + 1);
ic.sortType = Integer.parseInt(s);
c = c.substring(0, idx);
}
Column column = tableCols[Integer.parseInt(c)];
ic.column = column;
cols[i] = ic;
}
IndexType indexType;
if (ops[3].equals("d")) {
indexType = IndexType.createPrimaryKey(true, false);
Column[] tableColumns = table.getColumns();
for (int i = 0; i < cols.length; i++) {
tableColumns[cols[i].column.getColumnId()].setNullable(false);
}
} else {
indexType = IndexType.createNonUnique(true);
}
meta = table.addIndex(session, "I" + id, id, cols, indexType, false, null);
}
PageIndex index;
if (meta instanceof MultiVersionIndex) {
index = (PageIndex) ((MultiVersionIndex) meta).getBaseIndex();
} else {
index = (PageIndex) meta;
}
metaObjects.put(id, index);
}
| private void addMeta(Row row, Session session, boolean redo) {
int id = row.getValue(0).getInt();
int type = row.getValue(1).getInt();
int parent = row.getValue(2).getInt();
int rootPageId = row.getValue(3).getInt();
String options = row.getValue(4).getString();
String columnList = row.getValue(5).getString();
String[] columns = StringUtils.arraySplit(columnList, ',', false);
String[] ops = StringUtils.arraySplit(options, ',', false);
Index meta;
if (trace.isDebugEnabled()) {
trace.debug("addMeta id=" + id + " type=" + type + " parent=" + parent + " columns=" + columnList);
}
if (redo && rootPageId != 0) {
// ensure the page is empty, but not used by regular data
writePage(rootPageId, createData());
allocatePage(rootPageId);
}
metaRootPageId.put(id, rootPageId);
if (type == META_TYPE_SCAN_INDEX) {
CreateTableData data = new CreateTableData();
for (int i = 0; i < columns.length; i++) {
Column col = new Column("C" + i, Value.INT);
data.columns.add(col);
}
data.schema = metaSchema;
data.tableName = "T" + id;
data.id = id;
data.temporary = ops[2].equals("temp");
data.persistData = true;
data.persistIndexes = true;
data.create = false;
data.session = session;
TableData table = new TableData(data);
CompareMode mode = CompareMode.getInstance(ops[0], Integer.parseInt(ops[1]));
table.setCompareMode(mode);
meta = table.getScanIndex(session);
} else {
Index p = metaObjects.get(parent);
if (p == null) {
throw DbException.get(ErrorCode.FILE_CORRUPTED_1, "Table not found:" + parent + " for " + row + " meta:" + metaObjects);
}
TableData table = (TableData) p.getTable();
Column[] tableCols = table.getColumns();
IndexColumn[] cols = new IndexColumn[columns.length];
for (int i = 0; i < columns.length; i++) {
String c = columns[i];
IndexColumn ic = new IndexColumn();
int idx = c.indexOf('/');
if (idx >= 0) {
String s = c.substring(idx + 1);
ic.sortType = Integer.parseInt(s);
c = c.substring(0, idx);
}
Column column = tableCols[Integer.parseInt(c)];
ic.column = column;
cols[i] = ic;
}
IndexType indexType;
if (ops[3].equals("d")) {
indexType = IndexType.createPrimaryKey(true, false);
Column[] tableColumns = table.getColumns();
for (int i = 0; i < cols.length; i++) {
tableColumns[cols[i].column.getColumnId()].setNullable(false);
}
} else {
indexType = IndexType.createNonUnique(true);
}
meta = table.addIndex(session, "I" + id, id, cols, indexType, false, null);
}
PageIndex index;
if (meta instanceof MultiVersionIndex) {
index = (PageIndex) ((MultiVersionIndex) meta).getBaseIndex();
} else {
index = (PageIndex) meta;
}
metaObjects.put(id, index);
}
|
diff --git a/app/models/domain/Statistiques.java b/app/models/domain/Statistiques.java
index a03cd5c..bb58f99 100644
--- a/app/models/domain/Statistiques.java
+++ b/app/models/domain/Statistiques.java
@@ -1,175 +1,164 @@
package models.domain;
import com.google.code.morphia.annotations.Entity;
import com.google.common.base.Function;
import com.google.common.collect.ComparisonChain;
import play.modules.morphia.Model;
import javax.annotation.Nullable;
import java.util.Date;
/**
* .
*
* @author fsznajderman
* date : 05/05/12
*/
@Entity
public class Statistiques extends Model {
private String bestNamePost;
private String bestTitlePost;
private String bestGoogleID;
private String plusOneMatrix;
private String sharedMatrix;
private String titleMatrix;
private Long sumPlusOne;
private Long sumShared;
private Date statisticDate;
private boolean current = false;
public String getBestNamePost() {
return bestNamePost;
}
public void setBestNamePost(String bestNamePost) {
this.bestNamePost = bestNamePost;
}
public String getBestTitlePost() {
return bestTitlePost;
}
public void setBestTitlePost(String bestTitlePost) {
this.bestTitlePost = bestTitlePost;
}
public String getPlusOneMatrix() {
return plusOneMatrix;
}
public void setPlusOneMatrix(String plusOneMatrix) {
this.plusOneMatrix = plusOneMatrix;
}
public String getSharedMatrix() {
return sharedMatrix;
}
public void setSharedMatrix(String sharedMatrix) {
this.sharedMatrix = sharedMatrix;
}
public Date getStatisticDate() {
return statisticDate;
}
public void setStatisticDate(Date statisticDate) {
this.statisticDate = statisticDate;
}
public Long getSumPlusOne() {
return sumPlusOne;
}
public void setSumPlusOne(Long sumPlusOne) {
this.sumPlusOne = sumPlusOne;
}
public Long getSumShared() {
return sumShared;
}
public void setSumShared(Long sumShared) {
this.sumShared = sumShared;
}
public String getTitleMatrix() {
return titleMatrix;
}
public void setTitleMatrix(String titleMatrix) {
this.titleMatrix = titleMatrix;
}
public String getBestGoogleID() {
return bestGoogleID;
}
public void setBestGoogleID(String bestGoogleID) {
this.bestGoogleID = bestGoogleID;
}
public boolean isCurrent() {
return current;
}
public void setCurrent(boolean current) {
this.current = current;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("Statistiques");
sb.append("{bestNamePost='").append(bestNamePost).append('\'');
sb.append(", bestTitlePost='").append(bestTitlePost).append('\'');
sb.append(", plusOneMatrix='").append(plusOneMatrix).append('\'');
sb.append(", sharedMatrix='").append(sharedMatrix).append('\'');
sb.append(", titleMatrix='").append(titleMatrix).append('\'');
sb.append(", sumPlusOne=").append(sumPlusOne);
sb.append(", sumShared=").append(sumShared);
sb.append(", statisticDate=").append(statisticDate);
sb.append('}');
return sb.toString();
}
@Override
public boolean equals(Object o) {
if (this == o){ return true;}
if (o == null || getClass() != o.getClass()){ return false; }
Statistiques that = (Statistiques) o;
- return ComparisonChain.start().compare(this.getBestGoogleID(), that.getBestGoogleID())
+ return ComparisonChain.start()
.compare(bestNamePost, that.bestNamePost)
.compare(bestTitlePost, that.bestTitlePost)
.compare(plusOneMatrix, that.plusOneMatrix)
.compare(sharedMatrix, that.sharedMatrix)
.compare(sumPlusOne, that.sumPlusOne)
.compare(this.sumShared, that.sumShared)
- .compare(this.titleMatrix, that.titleMatrix).result() == 0;
+ .result() == 0;
- /*if (bestGoogleID != null ? !bestGoogleID.equals(that.bestGoogleID) : that.bestGoogleID != null) return false;
- if (bestNamePost != null ? !bestNamePost.equals(that.bestNamePost) : that.bestNamePost != null) return false;
- if (bestTitlePost != null ? !bestTitlePost.equals(that.bestTitlePost) : that.bestTitlePost != null)
- return false;
- if (plusOneMatrix != null ? !plusOneMatrix.equals(that.plusOneMatrix) : that.plusOneMatrix != null)
- return false;
- if (sharedMatrix != null ? !sharedMatrix.equals(that.sharedMatrix) : that.sharedMatrix != null) return false;
- if (sumPlusOne != null ? !sumPlusOne.equals(that.sumPlusOne) : that.sumPlusOne != null) return false;
- if (sumShared != null ? !sumShared.equals(that.sumShared) : that.sumShared != null) return false;
- if (titleMatrix != null ? !titleMatrix.equals(that.titleMatrix) : that.titleMatrix != null) return false; */
- /*return true; */
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (bestNamePost != null ? bestNamePost.hashCode() : 0);
result = 31 * result + (bestTitlePost != null ? bestTitlePost.hashCode() : 0);
result = 31 * result + (bestGoogleID != null ? bestGoogleID.hashCode() : 0);
result = 31 * result + (plusOneMatrix != null ? plusOneMatrix.hashCode() : 0);
result = 31 * result + (sharedMatrix != null ? sharedMatrix.hashCode() : 0);
result = 31 * result + (titleMatrix != null ? titleMatrix.hashCode() : 0);
result = 31 * result + (sumPlusOne != null ? sumPlusOne.hashCode() : 0);
result = 31 * result + (sumShared != null ? sumShared.hashCode() : 0);
return result;
}
}
| false | true | public boolean equals(Object o) {
if (this == o){ return true;}
if (o == null || getClass() != o.getClass()){ return false; }
Statistiques that = (Statistiques) o;
return ComparisonChain.start().compare(this.getBestGoogleID(), that.getBestGoogleID())
.compare(bestNamePost, that.bestNamePost)
.compare(bestTitlePost, that.bestTitlePost)
.compare(plusOneMatrix, that.plusOneMatrix)
.compare(sharedMatrix, that.sharedMatrix)
.compare(sumPlusOne, that.sumPlusOne)
.compare(this.sumShared, that.sumShared)
.compare(this.titleMatrix, that.titleMatrix).result() == 0;
/*if (bestGoogleID != null ? !bestGoogleID.equals(that.bestGoogleID) : that.bestGoogleID != null) return false;
if (bestNamePost != null ? !bestNamePost.equals(that.bestNamePost) : that.bestNamePost != null) return false;
if (bestTitlePost != null ? !bestTitlePost.equals(that.bestTitlePost) : that.bestTitlePost != null)
return false;
if (plusOneMatrix != null ? !plusOneMatrix.equals(that.plusOneMatrix) : that.plusOneMatrix != null)
return false;
if (sharedMatrix != null ? !sharedMatrix.equals(that.sharedMatrix) : that.sharedMatrix != null) return false;
if (sumPlusOne != null ? !sumPlusOne.equals(that.sumPlusOne) : that.sumPlusOne != null) return false;
if (sumShared != null ? !sumShared.equals(that.sumShared) : that.sumShared != null) return false;
if (titleMatrix != null ? !titleMatrix.equals(that.titleMatrix) : that.titleMatrix != null) return false; */
/*return true; */
}
| public boolean equals(Object o) {
if (this == o){ return true;}
if (o == null || getClass() != o.getClass()){ return false; }
Statistiques that = (Statistiques) o;
return ComparisonChain.start()
.compare(bestNamePost, that.bestNamePost)
.compare(bestTitlePost, that.bestTitlePost)
.compare(plusOneMatrix, that.plusOneMatrix)
.compare(sharedMatrix, that.sharedMatrix)
.compare(sumPlusOne, that.sumPlusOne)
.compare(this.sumShared, that.sumShared)
.result() == 0;
}
|
diff --git a/plugins/org.eclipse.dltk.ruby.basicdebugger/src/org/eclipse/dltk/ruby/basicdebugger/RubyBasicDebuggerRunner.java b/plugins/org.eclipse.dltk.ruby.basicdebugger/src/org/eclipse/dltk/ruby/basicdebugger/RubyBasicDebuggerRunner.java
index a325dbd0..c4fb3a2d 100644
--- a/plugins/org.eclipse.dltk.ruby.basicdebugger/src/org/eclipse/dltk/ruby/basicdebugger/RubyBasicDebuggerRunner.java
+++ b/plugins/org.eclipse.dltk.ruby.basicdebugger/src/org/eclipse/dltk/ruby/basicdebugger/RubyBasicDebuggerRunner.java
@@ -1,138 +1,139 @@
/*******************************************************************************
* Copyright (c) 2005, 2007 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
*
*******************************************************************************/
package org.eclipse.dltk.ruby.basicdebugger;
import java.io.IOException;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.dltk.core.PreferencesLookupDelegate;
import org.eclipse.dltk.core.environment.IDeployment;
import org.eclipse.dltk.core.environment.IEnvironment;
import org.eclipse.dltk.core.environment.IExecutionEnvironment;
import org.eclipse.dltk.launching.DebuggingEngineRunner;
import org.eclipse.dltk.launching.IInterpreterInstall;
import org.eclipse.dltk.launching.InterpreterConfig;
import org.eclipse.dltk.launching.debug.DbgpInterpreterConfig;
import org.eclipse.dltk.ruby.debug.RubyDebugPlugin;
import org.eclipse.dltk.ruby.internal.launching.JRubyInstallType;
public class RubyBasicDebuggerRunner extends DebuggingEngineRunner {
public static final String ENGINE_ID = "org.eclipse.dltk.ruby.basicdebugger"; //$NON-NLS-1$
private static final String RUBY_HOST_VAR = "DBGP_RUBY_HOST"; //$NON-NLS-1$
private static final String RUBY_PORT_VAR = "DBGP_RUBY_PORT"; //$NON-NLS-1$
private static final String RUBY_KEY_VAR = "DBGP_RUBY_KEY"; //$NON-NLS-1$
private static final String RUBY_LOG_VAR = "DBGP_RUBY_LOG"; //$NON-NLS-1$
private static final String DEBUGGER_SCRIPT = "BasicRunner.rb"; //$NON-NLS-1$
protected IPath deploy(IDeployment deployment) throws CoreException {
try {
IPath deploymentPath = RubyBasicDebuggerPlugin.getDefault()
.deployDebuggerSource(deployment);
return deployment.getFile(deploymentPath).getPath();
} catch (IOException e) {
abort(
Messages.RubyBasicDebuggerRunner_unableToDeployDebuggerSource,
e);
}
return null;
}
public RubyBasicDebuggerRunner(IInterpreterInstall install) {
super(install);
}
protected InterpreterConfig addEngineConfig(InterpreterConfig config,
PreferencesLookupDelegate delegate) throws CoreException {
IEnvironment env = getInstall().getEnvironment();
IExecutionEnvironment exeEnv = (IExecutionEnvironment) env
.getAdapter(IExecutionEnvironment.class);
IDeployment deployment = exeEnv.createDeployment();
// Get debugger source location
final IPath sourceLocation = deploy(deployment);
final IPath scriptFile = sourceLocation.append(DEBUGGER_SCRIPT);
// Creating new config
InterpreterConfig newConfig = (InterpreterConfig) config.clone();
if (getInstall().getInterpreterInstallType() instanceof JRubyInstallType) {
newConfig.addEnvVar("JAVA_OPTS", "-Djruby.jit.enabled=false"); //$NON-NLS-1$ //$NON-NLS-2$
newConfig.addInterpreterArg("-X-C"); //$NON-NLS-1$
}
newConfig.addInterpreterArg("-r"); //$NON-NLS-1$
newConfig.addInterpreterArg(env.convertPathToString(scriptFile)); //$NON-NLS-1$
newConfig.addInterpreterArg("-I"); //$NON-NLS-1$
newConfig.addInterpreterArg(env.convertPathToString(sourceLocation)); //$NON-NLS-1$
// Environment
final DbgpInterpreterConfig dbgpConfig = new DbgpInterpreterConfig(
config);
String sessionId = dbgpConfig.getSessionId();
newConfig.addEnvVar(RUBY_HOST_VAR, dbgpConfig.getHost());
newConfig.addEnvVar(RUBY_PORT_VAR, Integer.toString(dbgpConfig
.getPort()));
newConfig.addEnvVar(RUBY_KEY_VAR, sessionId);
- if (isLoggingEnabled(delegate)) {
- newConfig.addEnvVar(RUBY_LOG_VAR, getLogFileName(delegate,
- sessionId));
+ String logFileName = getLogFileName(delegate,
+ sessionId);
+ if (logFileName != null) {
+ newConfig.addEnvVar(RUBY_LOG_VAR, logFileName);
}
return newConfig;
}
protected String getDebuggingEngineId() {
return ENGINE_ID;
}
/*
* @see org.eclipse.dltk.launching.DebuggingEngineRunner#getDebugPreferenceQualifier()
*/
protected String getDebugPreferenceQualifier() {
return RubyDebugPlugin.PLUGIN_ID;
}
/*
* @see org.eclipse.dltk.launching.DebuggingEngineRunner#getDebuggingEnginePreferenceQualifier()
*/
protected String getDebuggingEnginePreferenceQualifier() {
return RubyBasicDebuggerPlugin.PLUGIN_ID;
}
/*
* @see org.eclipse.dltk.launching.DebuggingEngineRunner#getLoggingEnabledPreferenceKey()
*/
protected String getLoggingEnabledPreferenceKey() {
return RubyBasicDebuggerConstants.ENABLE_LOGGING;
}
/*
* @see org.eclipse.dltk.launching.DebuggingEngineRunner#getLogFileNamePreferenceKey()
*/
protected String getLogFileNamePreferenceKey() {
return RubyBasicDebuggerConstants.LOG_FILE_NAME;
}
/*
* @see org.eclipse.dltk.launching.DebuggingEngineRunner#getLogFilePathPreferenceKey()
*/
protected String getLogFilePathPreferenceKey() {
return RubyBasicDebuggerConstants.LOG_FILE_PATH;
}
}
| true | true | protected InterpreterConfig addEngineConfig(InterpreterConfig config,
PreferencesLookupDelegate delegate) throws CoreException {
IEnvironment env = getInstall().getEnvironment();
IExecutionEnvironment exeEnv = (IExecutionEnvironment) env
.getAdapter(IExecutionEnvironment.class);
IDeployment deployment = exeEnv.createDeployment();
// Get debugger source location
final IPath sourceLocation = deploy(deployment);
final IPath scriptFile = sourceLocation.append(DEBUGGER_SCRIPT);
// Creating new config
InterpreterConfig newConfig = (InterpreterConfig) config.clone();
if (getInstall().getInterpreterInstallType() instanceof JRubyInstallType) {
newConfig.addEnvVar("JAVA_OPTS", "-Djruby.jit.enabled=false"); //$NON-NLS-1$ //$NON-NLS-2$
newConfig.addInterpreterArg("-X-C"); //$NON-NLS-1$
}
newConfig.addInterpreterArg("-r"); //$NON-NLS-1$
newConfig.addInterpreterArg(env.convertPathToString(scriptFile)); //$NON-NLS-1$
newConfig.addInterpreterArg("-I"); //$NON-NLS-1$
newConfig.addInterpreterArg(env.convertPathToString(sourceLocation)); //$NON-NLS-1$
// Environment
final DbgpInterpreterConfig dbgpConfig = new DbgpInterpreterConfig(
config);
String sessionId = dbgpConfig.getSessionId();
newConfig.addEnvVar(RUBY_HOST_VAR, dbgpConfig.getHost());
newConfig.addEnvVar(RUBY_PORT_VAR, Integer.toString(dbgpConfig
.getPort()));
newConfig.addEnvVar(RUBY_KEY_VAR, sessionId);
if (isLoggingEnabled(delegate)) {
newConfig.addEnvVar(RUBY_LOG_VAR, getLogFileName(delegate,
sessionId));
}
return newConfig;
}
| protected InterpreterConfig addEngineConfig(InterpreterConfig config,
PreferencesLookupDelegate delegate) throws CoreException {
IEnvironment env = getInstall().getEnvironment();
IExecutionEnvironment exeEnv = (IExecutionEnvironment) env
.getAdapter(IExecutionEnvironment.class);
IDeployment deployment = exeEnv.createDeployment();
// Get debugger source location
final IPath sourceLocation = deploy(deployment);
final IPath scriptFile = sourceLocation.append(DEBUGGER_SCRIPT);
// Creating new config
InterpreterConfig newConfig = (InterpreterConfig) config.clone();
if (getInstall().getInterpreterInstallType() instanceof JRubyInstallType) {
newConfig.addEnvVar("JAVA_OPTS", "-Djruby.jit.enabled=false"); //$NON-NLS-1$ //$NON-NLS-2$
newConfig.addInterpreterArg("-X-C"); //$NON-NLS-1$
}
newConfig.addInterpreterArg("-r"); //$NON-NLS-1$
newConfig.addInterpreterArg(env.convertPathToString(scriptFile)); //$NON-NLS-1$
newConfig.addInterpreterArg("-I"); //$NON-NLS-1$
newConfig.addInterpreterArg(env.convertPathToString(sourceLocation)); //$NON-NLS-1$
// Environment
final DbgpInterpreterConfig dbgpConfig = new DbgpInterpreterConfig(
config);
String sessionId = dbgpConfig.getSessionId();
newConfig.addEnvVar(RUBY_HOST_VAR, dbgpConfig.getHost());
newConfig.addEnvVar(RUBY_PORT_VAR, Integer.toString(dbgpConfig
.getPort()));
newConfig.addEnvVar(RUBY_KEY_VAR, sessionId);
String logFileName = getLogFileName(delegate,
sessionId);
if (logFileName != null) {
newConfig.addEnvVar(RUBY_LOG_VAR, logFileName);
}
return newConfig;
}
|
diff --git a/src/org/SdkYoungHeads/DoIKnowYou/AddNewGroupActivity.java b/src/org/SdkYoungHeads/DoIKnowYou/AddNewGroupActivity.java
index a5e8bd5..f0dbc06 100644
--- a/src/org/SdkYoungHeads/DoIKnowYou/AddNewGroupActivity.java
+++ b/src/org/SdkYoungHeads/DoIKnowYou/AddNewGroupActivity.java
@@ -1,162 +1,161 @@
package org.SdkYoungHeads.DoIKnowYou;
import org.SdkYoungHeads.DoIKnowYou.ListOfGroupsActivity.MyGroupAdapter;
import android.app.Activity;
import android.content.Context;
import java.io.IOException;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
public class AddNewGroupActivity extends Activity {
protected Group group;
protected ListView personList;
SelectedPersonsAdapter adapter;
public void onCreate(Bundle savedInstanceState) {
group = new Group();
super.onCreate(savedInstanceState);
setContentView(R.layout.addnewgroup);
- adapter.notifyDataSetInvalidated();
// Person[] p = ((Application)getApplication()).selectedPersons;
//
// if(p == null) {
// p = new Person[1];
// p[0] = new Person();
// p[0].setName("No record");
// }
// personList = (ListView) this.findViewById(R.id.list_of_groups);
// adapter = new SelectedPersonsAdapter(this.getBaseContext(), p);
// Button addPerson = (Button) findViewById(R.id.addPersonToGroupBtn);
// addPerson.setOnClickListener(new View.OnClickListener() {
// public void onClick(View view) {
// Intent myIntent = new Intent(view.getContext(), SelectPersonsActivity.class);
// startActivityForResult(myIntent, 0);
// }
//
// });
final TextView name = (TextView)findViewById(R.id.groupNameEdit);
Button addGroup = (Button) findViewById(R.id.createGroupBtn);
addGroup.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
group.setName(name.getText().toString());
GroupContainer gc = ((Application)getApplication()).getDatabase();
if (gc.getGroupByName(name.getText().toString()) != null) {
Builder builder = new AlertDialog.Builder(AddNewGroupActivity.this);
builder.setMessage(R.string.group_already_exists).
setPositiveButton(R.string.okay, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.show();
return;
}
gc.addGroup(group);
try {
gc.save(getBaseContext());
finish();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
// setAdapter();
}
// protected void setAdapter() {
//
// Person[] p = ((Application)getApplication()).selectedPersons;
//
// if(p == null || p.length == 0) {
// p = new Person[1];
// p[0] = new Person();
// p[0].setName("No record");
// }
// ((Application)getApplication()).selectedPersons = null;
// Log.d("????? >>>>>>", ">>>>>>>>>>>>>>>>>>>>>>>>" + p.length);
//
// personList.clearChoices();
// adapter.setData(p);
// personList.setAdapter(adapter);
//
//// personList.invalidate();
//// adapter.notifyDataSetChanged();
//
// }
class SelectedPersonsAdapter extends ArrayAdapter<Person> {
protected Context context;
protected Person[] persons;
public SelectedPersonsAdapter(Context context, Person[] persons) {
super(AddNewGroupActivity.this, R.layout.group_row, persons);
this.context = context;
this.persons = persons;
}
public void setData(Person[] p) {
this.persons = p;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.group_row, parent, false);
// ImageView groupIcon = (ImageView) rowView.findViewById(R.id.group_icon);
// ImageView groupArrow = (ImageView) rowView.findViewById(R.id.group_arrow);
TextView personName = (TextView) rowView.findViewById(R.id.person_name);
personName.setText(persons[position].getName());
// Change the icon for Windows and iPhone
// String s = values[position];
// if (s.startsWith("iPhone")) {
// imageView.setImageResource(R.drawable.no);
// } else {
// imageView.setImageResource(R.drawable.ok);
// }
return rowView;
}
}
}
| true | true | public void onCreate(Bundle savedInstanceState) {
group = new Group();
super.onCreate(savedInstanceState);
setContentView(R.layout.addnewgroup);
adapter.notifyDataSetInvalidated();
// Person[] p = ((Application)getApplication()).selectedPersons;
//
// if(p == null) {
// p = new Person[1];
// p[0] = new Person();
// p[0].setName("No record");
// }
// personList = (ListView) this.findViewById(R.id.list_of_groups);
// adapter = new SelectedPersonsAdapter(this.getBaseContext(), p);
// Button addPerson = (Button) findViewById(R.id.addPersonToGroupBtn);
// addPerson.setOnClickListener(new View.OnClickListener() {
// public void onClick(View view) {
// Intent myIntent = new Intent(view.getContext(), SelectPersonsActivity.class);
// startActivityForResult(myIntent, 0);
// }
//
// });
final TextView name = (TextView)findViewById(R.id.groupNameEdit);
Button addGroup = (Button) findViewById(R.id.createGroupBtn);
addGroup.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
group.setName(name.getText().toString());
GroupContainer gc = ((Application)getApplication()).getDatabase();
if (gc.getGroupByName(name.getText().toString()) != null) {
Builder builder = new AlertDialog.Builder(AddNewGroupActivity.this);
builder.setMessage(R.string.group_already_exists).
setPositiveButton(R.string.okay, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.show();
return;
}
gc.addGroup(group);
try {
gc.save(getBaseContext());
finish();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
| public void onCreate(Bundle savedInstanceState) {
group = new Group();
super.onCreate(savedInstanceState);
setContentView(R.layout.addnewgroup);
// Person[] p = ((Application)getApplication()).selectedPersons;
//
// if(p == null) {
// p = new Person[1];
// p[0] = new Person();
// p[0].setName("No record");
// }
// personList = (ListView) this.findViewById(R.id.list_of_groups);
// adapter = new SelectedPersonsAdapter(this.getBaseContext(), p);
// Button addPerson = (Button) findViewById(R.id.addPersonToGroupBtn);
// addPerson.setOnClickListener(new View.OnClickListener() {
// public void onClick(View view) {
// Intent myIntent = new Intent(view.getContext(), SelectPersonsActivity.class);
// startActivityForResult(myIntent, 0);
// }
//
// });
final TextView name = (TextView)findViewById(R.id.groupNameEdit);
Button addGroup = (Button) findViewById(R.id.createGroupBtn);
addGroup.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
group.setName(name.getText().toString());
GroupContainer gc = ((Application)getApplication()).getDatabase();
if (gc.getGroupByName(name.getText().toString()) != null) {
Builder builder = new AlertDialog.Builder(AddNewGroupActivity.this);
builder.setMessage(R.string.group_already_exists).
setPositiveButton(R.string.okay, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.show();
return;
}
gc.addGroup(group);
try {
gc.save(getBaseContext());
finish();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
|
diff --git a/src/org/processmining/plugins/xpdl/exporting/XpdlExportNet.java b/src/org/processmining/plugins/xpdl/exporting/XpdlExportNet.java
index 8b3162a..c86bddf 100644
--- a/src/org/processmining/plugins/xpdl/exporting/XpdlExportNet.java
+++ b/src/org/processmining/plugins/xpdl/exporting/XpdlExportNet.java
@@ -1,79 +1,79 @@
package org.processmining.plugins.xpdl.exporting;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import org.processmining.contexts.cli.CLIPluginContext;
import org.processmining.contexts.uitopia.UIPluginContext;
import org.processmining.contexts.uitopia.annotations.UIExportPlugin;
import org.processmining.framework.plugin.annotations.Plugin;
import org.processmining.framework.plugin.annotations.PluginVariant;
import org.processmining.models.graphbased.directed.bpmn.BPMNDiagramExt;
import org.processmining.plugins.xpdl.Xpdl;
import org.processmining.plugins.xpdl.converter.BPMN2XPDLConversionExt;
@Plugin(name = "XPDL export Bussines Notation with Artifact", returnLabels = {}, returnTypes = {}, parameterLabels = { "XPDL open",
"File" }, userAccessible = true)
@UIExportPlugin(description = "xpdl files", extension = "xpdl")
public class XpdlExportNet {
@PluginVariant(requiredParameterLabels = { 0, 1 }, variantLabel = "Export File")
public void exportXPDLtoFile(UIPluginContext context, Xpdl net, File file) throws IOException {
String text = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n" + net.exportElement();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
bw.write(text);
bw.close();
}
@PluginVariant(requiredParameterLabels = { 0, 1 }, variantLabel = "Export File")
public void exportXPDLtoFile(UIPluginContext context, BPMNDiagramExt brnet, File file) throws IOException {
/*Xpdl net = brnet.getXpdltraslate();
String text = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n" + net.exportElement();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
bw.write(text);
bw.close();*/
BPMN2XPDLConversionExt xpdlConversion = new BPMN2XPDLConversionExt(brnet);
Xpdl xpdl = xpdlConversion.fills_layout(context);
String text = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + xpdl.exportElement();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
bw.write(text);
bw.close();
}
@PluginVariant(requiredParameterLabels = { 0, 1 }, variantLabel = "Export File")
public void exportXPDLtoFile(CLIPluginContext context, BPMNDiagramExt brnet, File file) throws IOException {
/*Xpdl net = brnet.getXpdltraslate();
String text = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n" + net.exportElement();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
bw.write(text);
bw.close();*/
BPMN2XPDLConversionExt xpdlConversion = new BPMN2XPDLConversionExt(brnet);
- //Xpdl xpdl = xpdlConversion.fills_nolayout();
- Xpdl xpdl = xpdlConversion.fills_layout(context);
+ Xpdl xpdl = xpdlConversion.fills_nolayout();
+ //Xpdl xpdl = xpdlConversion.fills_layout(context);
String text = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + xpdl.exportElement();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
bw.write(text);
bw.close();
}
}
| true | true | public void exportXPDLtoFile(CLIPluginContext context, BPMNDiagramExt brnet, File file) throws IOException {
/*Xpdl net = brnet.getXpdltraslate();
String text = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n" + net.exportElement();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
bw.write(text);
bw.close();*/
BPMN2XPDLConversionExt xpdlConversion = new BPMN2XPDLConversionExt(brnet);
//Xpdl xpdl = xpdlConversion.fills_nolayout();
Xpdl xpdl = xpdlConversion.fills_layout(context);
String text = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + xpdl.exportElement();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
bw.write(text);
bw.close();
}
| public void exportXPDLtoFile(CLIPluginContext context, BPMNDiagramExt brnet, File file) throws IOException {
/*Xpdl net = brnet.getXpdltraslate();
String text = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n" + net.exportElement();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
bw.write(text);
bw.close();*/
BPMN2XPDLConversionExt xpdlConversion = new BPMN2XPDLConversionExt(brnet);
Xpdl xpdl = xpdlConversion.fills_nolayout();
//Xpdl xpdl = xpdlConversion.fills_layout(context);
String text = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + xpdl.exportElement();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
bw.write(text);
bw.close();
}
|
diff --git a/src/com/partyrock/music/MP3.java b/src/com/partyrock/music/MP3.java
index 127e21a..078fcea 100644
--- a/src/com/partyrock/music/MP3.java
+++ b/src/com/partyrock/music/MP3.java
@@ -1,188 +1,187 @@
package com.partyrock.music;
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.*;
public class MP3 extends Sound {
private File file;
private boolean isPaused;
private boolean isPlaying;
private AudioFileFormat fileFormat;
private Thread MP3Thread;
private SourceDataLine line;
private AudioInputStream din;
private MP3Player myMP3Player;
private double startTime = 0;
/**
* Constructs an MP3 from a given file.
* @param file The file
*/
public MP3(File file) {
super();
this.file = file;
isPaused = false;
if (!file.exists()) {
System.err.println("MP3 constructed for non-existent file");
return;
}
try {
fileFormat = AudioSystem.getAudioFileFormat(file);
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public class MP3Player implements Runnable {
private double startTime;
boolean paused;
public MP3Player(double var) {
this.startTime = var;
paused = false;
}
public void run() {
din = null;
try {
AudioInputStream in = AudioSystem.getAudioInputStream(file);
AudioFormat baseFormat = in.getFormat();
AudioFormat decodedFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, baseFormat.getSampleRate(), 16, baseFormat.getChannels(), baseFormat.getChannels() * 2, baseFormat.getSampleRate(), false);
din = AudioSystem.getAudioInputStream(decodedFormat, in);
- DataLine.Info info = new DataLine.Info(SourceDataLine.class, decodedFormat);
line = AudioSystem.getSourceDataLine(decodedFormat, null);
if (line != null) {
line.open(decodedFormat);
byte[] data = new byte[4096];
// Start
line.start();
isPlaying = true;
// Skip first startTime seconds
int bytesToSkip = (int) (startTime
* (Integer) fileFormat.properties().get("mp3.bitrate.nominal.bps") / 8);
din.skip(bytesToSkip);
int nBytesRead;
while ((data != null) && (din != null) && (nBytesRead = din.read(data, 0, data.length)) != -1
&& isPlaying) {
// Skip first startTime seconds
if (isPaused == true) {
while (isPaused) {
Thread.sleep(100);
}
}
line.write(data, 0, nBytesRead);
// System.out.println(line.getMicrosecondPosition());
}
isPlaying = false;
// Stop
if (line != null && din != null) {
line.drain();
line.stop();
line.close();
din.close();
}
}
} catch (Exception e) {
System.out.println("Error!");
e.printStackTrace();
} finally {
if (din != null) {
try {
din.close();
} catch (IOException e) {
}
}
}
}
}
@Override
public void play(double startTime) {
this.startTime = startTime;
myMP3Player = new MP3Player(startTime);
MP3Thread = new Thread(myMP3Player);
MP3Thread.start();
}
public void playthread(double startTime) {
}
@Override
public double getDuration() {
// TODO Auto-generated method stub
Long microseconds = (Long) fileFormat.properties().get("duration");
double milliseconds = (int) (microseconds / 1000);
double seconds = (milliseconds / 1000);
return seconds;
}
@Override
public void pause() {
// TODO Auto-generated method stub
isPaused = true;
// MP3Thread.suspend();
myMP3Player.paused = true;
}
public void unpause() {
// TODO Auto-generated method stub
isPaused = false;
myMP3Player.paused = false;
// MP3Thread.resume();
}
@Override
public double getCurrentTime() {
// TODO Auto-generated method stub
System.out.println(line.getMicrosecondPosition());
return startTime + (line.getMicrosecondPosition() / 1000);
}
/**
* Returns the file associated with this MP3
* @return The mp3 file
*/
public File getFile() {
return file;
}
public void stop() {
isPlaying = false;
pause();
MP3Thread = null;
myMP3Player = null;
isPaused = false;
isPlaying = false;
// fileFormat = null;
MP3Thread = null;
line = null;
din = null;
myMP3Player = null;
startTime = 0;
// Stop
// line.drain();
// line.stop();
// line.close();
}
}
| true | true | public void run() {
din = null;
try {
AudioInputStream in = AudioSystem.getAudioInputStream(file);
AudioFormat baseFormat = in.getFormat();
AudioFormat decodedFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, baseFormat.getSampleRate(), 16, baseFormat.getChannels(), baseFormat.getChannels() * 2, baseFormat.getSampleRate(), false);
din = AudioSystem.getAudioInputStream(decodedFormat, in);
DataLine.Info info = new DataLine.Info(SourceDataLine.class, decodedFormat);
line = AudioSystem.getSourceDataLine(decodedFormat, null);
if (line != null) {
line.open(decodedFormat);
byte[] data = new byte[4096];
// Start
line.start();
isPlaying = true;
// Skip first startTime seconds
int bytesToSkip = (int) (startTime
* (Integer) fileFormat.properties().get("mp3.bitrate.nominal.bps") / 8);
din.skip(bytesToSkip);
int nBytesRead;
while ((data != null) && (din != null) && (nBytesRead = din.read(data, 0, data.length)) != -1
&& isPlaying) {
// Skip first startTime seconds
if (isPaused == true) {
while (isPaused) {
Thread.sleep(100);
}
}
line.write(data, 0, nBytesRead);
// System.out.println(line.getMicrosecondPosition());
}
isPlaying = false;
// Stop
if (line != null && din != null) {
line.drain();
line.stop();
line.close();
din.close();
}
}
} catch (Exception e) {
System.out.println("Error!");
e.printStackTrace();
} finally {
if (din != null) {
try {
din.close();
} catch (IOException e) {
}
}
}
}
| public void run() {
din = null;
try {
AudioInputStream in = AudioSystem.getAudioInputStream(file);
AudioFormat baseFormat = in.getFormat();
AudioFormat decodedFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, baseFormat.getSampleRate(), 16, baseFormat.getChannels(), baseFormat.getChannels() * 2, baseFormat.getSampleRate(), false);
din = AudioSystem.getAudioInputStream(decodedFormat, in);
line = AudioSystem.getSourceDataLine(decodedFormat, null);
if (line != null) {
line.open(decodedFormat);
byte[] data = new byte[4096];
// Start
line.start();
isPlaying = true;
// Skip first startTime seconds
int bytesToSkip = (int) (startTime
* (Integer) fileFormat.properties().get("mp3.bitrate.nominal.bps") / 8);
din.skip(bytesToSkip);
int nBytesRead;
while ((data != null) && (din != null) && (nBytesRead = din.read(data, 0, data.length)) != -1
&& isPlaying) {
// Skip first startTime seconds
if (isPaused == true) {
while (isPaused) {
Thread.sleep(100);
}
}
line.write(data, 0, nBytesRead);
// System.out.println(line.getMicrosecondPosition());
}
isPlaying = false;
// Stop
if (line != null && din != null) {
line.drain();
line.stop();
line.close();
din.close();
}
}
} catch (Exception e) {
System.out.println("Error!");
e.printStackTrace();
} finally {
if (din != null) {
try {
din.close();
} catch (IOException e) {
}
}
}
}
|
diff --git a/nuxeo-runtime-test/src/test/java/org/nuxeo/runtime/ResourceServiceTest.java b/nuxeo-runtime-test/src/test/java/org/nuxeo/runtime/ResourceServiceTest.java
index 38927acb..2c66baa8 100644
--- a/nuxeo-runtime-test/src/test/java/org/nuxeo/runtime/ResourceServiceTest.java
+++ b/nuxeo-runtime-test/src/test/java/org/nuxeo/runtime/ResourceServiceTest.java
@@ -1,56 +1,56 @@
/*
* (C) Copyright 2006-2011 Nuxeo SA (http://nuxeo.com/) and contributors.
*
* 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.
*
* Contributors:
* Nuxeo - initial API and implementation
*
* $Id$
*/
package org.nuxeo.runtime;
import java.io.InputStream;
import java.net.URL;
import org.nuxeo.common.utils.FileUtils;
import org.nuxeo.runtime.api.Framework;
import org.nuxeo.runtime.services.resource.ResourceService;
import org.nuxeo.runtime.test.NXRuntimeTestCase;
/**
* @author <a href="mailto:[email protected]">Bogdan Stefanescu</a>
*
*/
public class ResourceServiceTest extends NXRuntimeTestCase {
@Override
public void setUp() throws Exception {
super.setUp();
deployContrib("org.nuxeo.runtime.test.tests", "ResourcesContrib.xml");
}
public void testContributions() throws Exception {
ResourceService rs = Framework.getLocalService(ResourceService.class);
URL url = rs.getResource("myres");
InputStream in = url.openStream();
try {
- assertEquals("test resource", FileUtils.read(in));
+ assertEquals("test resource", FileUtils.read(in).trim());
} finally {
in.close();
}
}
}
| true | true | public void testContributions() throws Exception {
ResourceService rs = Framework.getLocalService(ResourceService.class);
URL url = rs.getResource("myres");
InputStream in = url.openStream();
try {
assertEquals("test resource", FileUtils.read(in));
} finally {
in.close();
}
}
| public void testContributions() throws Exception {
ResourceService rs = Framework.getLocalService(ResourceService.class);
URL url = rs.getResource("myres");
InputStream in = url.openStream();
try {
assertEquals("test resource", FileUtils.read(in).trim());
} finally {
in.close();
}
}
|
diff --git a/SolarPanelApp/src/com/example/calendar/BasicCalendar.java b/SolarPanelApp/src/com/example/calendar/BasicCalendar.java
index 2056798..ec1e7d9 100644
--- a/SolarPanelApp/src/com/example/calendar/BasicCalendar.java
+++ b/SolarPanelApp/src/com/example/calendar/BasicCalendar.java
@@ -1,56 +1,56 @@
package com.example.calendar;
import java.util.Collection;
import java.util.Calendar;
import java.util.Map;
import java.util.TreeMap;
import com.example.solarpanelmanager.api.responses.Event;
public class BasicCalendar {
private Map<String, Event> calendar = new TreeMap<String, Event>();
private static final long DAY_MILLIS = 24 * 60 * 60 * 1000;
public BasicCalendar(Collection<Event> events) {
for (Event e : events)
addEvent(e);
}
public boolean addEvent(Event event) {
for (Event e : calendar.values()) {
if (isOverlap(event, e))
return false;
}
calendar.put(eventToKey(event), event);
return true;
}
public void removeEvent(Event event) {
calendar.remove(eventToKey(event));
}
public Map<String, Event> getCalendar() {
return calendar;
}
private static String eventToKey(Event e) {
Calendar day = Calendar.getInstance();
day.setTimeInMillis(e.getFirstTime());
return day.get(Calendar.HOUR) + ":" + day.get(Calendar.MINUTE);
}
private static boolean isOverlap(Event e1, Event e2) {
Calendar newDay = Calendar.getInstance();
newDay.setTimeInMillis(e1.getFirstTime());
- long newStart = (newDay.get(Calendar.HOUR) * 60 * 60 * 1000 + newDay.get(Calendar.MINUTE) * 60 * 1000) % DAY_MILLIS;
+ long newStart = newDay.getTimeInMillis() % DAY_MILLIS;
long newEnd = (newStart + e1.getDuration()) % DAY_MILLIS;
Calendar oldDay = Calendar.getInstance();
oldDay.setTimeInMillis(e2.getFirstTime());
- long oldStart = (oldDay.get(Calendar.HOUR) * 60 * 60 * 1000 + oldDay.get(Calendar.MINUTE) * 60 * 1000) % DAY_MILLIS;
+ long oldStart = oldDay.getTimeInMillis() % DAY_MILLIS;
long oldEnd = (oldStart + e2.getDuration()) % DAY_MILLIS;
return (newStart >= oldStart && newStart < oldEnd) || (newEnd <= oldEnd && newEnd > oldStart);
}
}
| false | true | private static boolean isOverlap(Event e1, Event e2) {
Calendar newDay = Calendar.getInstance();
newDay.setTimeInMillis(e1.getFirstTime());
long newStart = (newDay.get(Calendar.HOUR) * 60 * 60 * 1000 + newDay.get(Calendar.MINUTE) * 60 * 1000) % DAY_MILLIS;
long newEnd = (newStart + e1.getDuration()) % DAY_MILLIS;
Calendar oldDay = Calendar.getInstance();
oldDay.setTimeInMillis(e2.getFirstTime());
long oldStart = (oldDay.get(Calendar.HOUR) * 60 * 60 * 1000 + oldDay.get(Calendar.MINUTE) * 60 * 1000) % DAY_MILLIS;
long oldEnd = (oldStart + e2.getDuration()) % DAY_MILLIS;
return (newStart >= oldStart && newStart < oldEnd) || (newEnd <= oldEnd && newEnd > oldStart);
}
| private static boolean isOverlap(Event e1, Event e2) {
Calendar newDay = Calendar.getInstance();
newDay.setTimeInMillis(e1.getFirstTime());
long newStart = newDay.getTimeInMillis() % DAY_MILLIS;
long newEnd = (newStart + e1.getDuration()) % DAY_MILLIS;
Calendar oldDay = Calendar.getInstance();
oldDay.setTimeInMillis(e2.getFirstTime());
long oldStart = oldDay.getTimeInMillis() % DAY_MILLIS;
long oldEnd = (oldStart + e2.getDuration()) % DAY_MILLIS;
return (newStart >= oldStart && newStart < oldEnd) || (newEnd <= oldEnd && newEnd > oldStart);
}
|
diff --git a/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/PackageHtmlCheck.java b/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/PackageHtmlCheck.java
index c6a3428ea..11b97d8dc 100644
--- a/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/PackageHtmlCheck.java
+++ b/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/PackageHtmlCheck.java
@@ -1,68 +1,70 @@
////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2002 Oliver Burn
//
// 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
////////////////////////////////////////////////////////////////////////////////
package com.puppycrawl.tools.checkstyle.checks;
import java.io.File;
import java.util.Iterator;
import java.util.Set;
import com.puppycrawl.tools.checkstyle.api.MessageDispatcher;
import com.puppycrawl.tools.checkstyle.api.LocalizedMessage;
import com.puppycrawl.tools.checkstyle.api.AbstractFileSetCheck;
/**
* <p>
* Checks that all packages have a package documentation.
* </p>
* <p>
* An example of how to configure the check is:
* </p>
* <pre>
* <module name="PackageHtml"/>
* </pre>
* @author lkuehne
*/
public class PackageHtmlCheck extends AbstractFileSetCheck
{
/**
* Checks that each java file in the fileset has a package.html sibling
* and fires errors for the missing files.
* @param aFiles a set of files
*/
public void process(File[] aFiles)
{
Set directories = getParentDirs(aFiles);
for (Iterator it = directories.iterator(); it.hasNext();) {
File dir = (File) it.next();
File packageHtml = new File(dir, "package.html");
MessageDispatcher dispatcher = getMessageDispatcher();
final String path = packageHtml.getPath();
dispatcher.fireFileStarted(path);
if (!packageHtml.exists()) {
LocalizedMessage[] errors = new LocalizedMessage[1];
- final String bundle =
- this.getClass().getPackage().getName() + ".messages";
+ final String className = getClass().getName();
+ final int pkgEndIndex = className.lastIndexOf('.');
+ final String pkgName = className.substring(0, pkgEndIndex);
+ final String bundle = pkgName + ".messages";
errors[0] = new LocalizedMessage(
0, bundle, "javadoc.packageHtml", null);
getMessageDispatcher().fireErrors(path, errors);
}
dispatcher.fireFileFinished(path);
}
}
}
| true | true | public void process(File[] aFiles)
{
Set directories = getParentDirs(aFiles);
for (Iterator it = directories.iterator(); it.hasNext();) {
File dir = (File) it.next();
File packageHtml = new File(dir, "package.html");
MessageDispatcher dispatcher = getMessageDispatcher();
final String path = packageHtml.getPath();
dispatcher.fireFileStarted(path);
if (!packageHtml.exists()) {
LocalizedMessage[] errors = new LocalizedMessage[1];
final String bundle =
this.getClass().getPackage().getName() + ".messages";
errors[0] = new LocalizedMessage(
0, bundle, "javadoc.packageHtml", null);
getMessageDispatcher().fireErrors(path, errors);
}
dispatcher.fireFileFinished(path);
}
}
| public void process(File[] aFiles)
{
Set directories = getParentDirs(aFiles);
for (Iterator it = directories.iterator(); it.hasNext();) {
File dir = (File) it.next();
File packageHtml = new File(dir, "package.html");
MessageDispatcher dispatcher = getMessageDispatcher();
final String path = packageHtml.getPath();
dispatcher.fireFileStarted(path);
if (!packageHtml.exists()) {
LocalizedMessage[] errors = new LocalizedMessage[1];
final String className = getClass().getName();
final int pkgEndIndex = className.lastIndexOf('.');
final String pkgName = className.substring(0, pkgEndIndex);
final String bundle = pkgName + ".messages";
errors[0] = new LocalizedMessage(
0, bundle, "javadoc.packageHtml", null);
getMessageDispatcher().fireErrors(path, errors);
}
dispatcher.fireFileFinished(path);
}
}
|
diff --git a/src/za/jamie/androidffmpegcmdline/ffmpeg/FfmpegJob.java b/src/za/jamie/androidffmpegcmdline/ffmpeg/FfmpegJob.java
index 2d289f7..8b8f811 100644
--- a/src/za/jamie/androidffmpegcmdline/ffmpeg/FfmpegJob.java
+++ b/src/za/jamie/androidffmpegcmdline/ffmpeg/FfmpegJob.java
@@ -1,173 +1,173 @@
package za.jamie.androidffmpegcmdline.ffmpeg;
import java.util.LinkedList;
import java.util.List;
import android.text.TextUtils;
public class FfmpegJob {
public String inputPath;
public String inputFormat;
public String inputVideoCodec;
public String inputAudioCodec;
public String videoCodec;
public int videoBitrate;
public int videoWidth = -1;
public int videoHeight = -1;
public float videoFramerate = -1;
public String videoBitStreamFilter;
public String audioCodec;
public int audioBitrate;
public int audioSampleRate;
public int audioChannels;
public int audioVolume;
public String audioBitStreamFilter;
public String audioFilter;
public String videoFilter;
public long startTime = -1;
public long duration = -1;
public String outputPath;
public String format;
public boolean disableVideo;
public boolean disableAudio;
private final String mFfmpegPath;
public FfmpegJob(String ffmpegPath) {
mFfmpegPath = ffmpegPath;
}
public ProcessRunnable create() {
if (inputPath == null || outputPath == null) {
throw new IllegalStateException("Need an input and output filepath!");
}
final List<String> cmd = new LinkedList<String>();
cmd.add(mFfmpegPath);
cmd.add("-y");
- if (TextUtils.isEmpty(inputFormat)) {
+ if (!TextUtils.isEmpty(inputFormat)) {
cmd.add(FFMPEGArg.ARG_FORMAT);
cmd.add(inputFormat);
}
- if (TextUtils.isEmpty(inputVideoCodec)) {
+ if (!TextUtils.isEmpty(inputVideoCodec)) {
cmd.add(FFMPEGArg.ARG_VIDEOCODEC);
cmd.add(inputVideoCodec);
}
- if (TextUtils.isEmpty(inputAudioCodec)) {
+ if (!TextUtils.isEmpty(inputAudioCodec)) {
cmd.add(FFMPEGArg.ARG_AUDIOCODEC);
cmd.add(inputAudioCodec);
}
cmd.add("-i");
cmd.add(inputPath);
if (disableVideo) {
cmd.add(FFMPEGArg.ARG_DISABLE_VIDEO);
} else {
if (videoBitrate > 0) {
cmd.add(FFMPEGArg.ARG_BITRATE_VIDEO);
cmd.add(videoBitrate + "k");
}
if (videoWidth > 0 && videoHeight > 0) {
cmd.add(FFMPEGArg.ARG_SIZE);
cmd.add(videoWidth + "x" + videoHeight);
}
if (videoFramerate > -1) {
cmd.add(FFMPEGArg.ARG_FRAMERATE);
cmd.add(String.valueOf(videoFramerate));
}
- if (TextUtils.isEmpty(videoCodec)) {
+ if (!TextUtils.isEmpty(videoCodec)) {
cmd.add(FFMPEGArg.ARG_VIDEOCODEC);
cmd.add(videoCodec);
}
- if (TextUtils.isEmpty(videoBitStreamFilter)) {
+ if (!TextUtils.isEmpty(videoBitStreamFilter)) {
cmd.add(FFMPEGArg.ARG_VIDEOBITSTREAMFILTER);
cmd.add(videoBitStreamFilter);
}
- if (TextUtils.isEmpty(videoFilter)) {
+ if (!TextUtils.isEmpty(videoFilter)) {
cmd.add(FFMPEGArg.ARG_VIDEOFILTER);
cmd.add(videoFilter);
}
}
if (disableAudio) {
cmd.add(FFMPEGArg.ARG_DISABLE_AUDIO);
} else {
- if (TextUtils.isEmpty(audioCodec)) {
+ if (!TextUtils.isEmpty(audioCodec)) {
cmd.add(FFMPEGArg.ARG_AUDIOCODEC);
cmd.add(audioCodec);
}
- if (TextUtils.isEmpty(audioBitStreamFilter)) {
+ if (!TextUtils.isEmpty(audioBitStreamFilter)) {
cmd.add(FFMPEGArg.ARG_AUDIOBITSTREAMFILTER);
cmd.add(audioBitStreamFilter);
}
- if (TextUtils.isEmpty(audioFilter)) {
+ if (!TextUtils.isEmpty(audioFilter)) {
cmd.add(FFMPEGArg.ARG_AUDIOFILTER);
cmd.add(audioFilter);
}
if (audioChannels > 0) {
cmd.add(FFMPEGArg.ARG_CHANNELS_AUDIO);
cmd.add(String.valueOf(audioChannels));
}
if (audioVolume > 0) {
cmd.add(FFMPEGArg.ARG_VOLUME_AUDIO);
cmd.add(String.valueOf(audioVolume));
}
if (audioBitrate > 0) {
cmd.add(FFMPEGArg.ARG_BITRATE_AUDIO);
cmd.add(audioBitrate + "k");
}
}
- if (TextUtils.isEmpty(format)) {
+ if (!TextUtils.isEmpty(format)) {
cmd.add("-f");
cmd.add(format);
}
cmd.add(outputPath);
final ProcessBuilder pb = new ProcessBuilder(cmd);
return new ProcessRunnable(pb);
}
public class FFMPEGArg {
String key;
String value;
public static final String ARG_VIDEOCODEC = "-vcodec";
public static final String ARG_AUDIOCODEC = "-acodec";
public static final String ARG_VIDEOBITSTREAMFILTER = "-vbsf";
public static final String ARG_AUDIOBITSTREAMFILTER = "-absf";
public static final String ARG_VIDEOFILTER = "-vf";
public static final String ARG_AUDIOFILTER = "-af";
public static final String ARG_VERBOSITY = "-v";
public static final String ARG_FILE_INPUT = "-i";
public static final String ARG_SIZE = "-s";
public static final String ARG_FRAMERATE = "-r";
public static final String ARG_FORMAT = "-f";
public static final String ARG_BITRATE_VIDEO = "-b:v";
public static final String ARG_BITRATE_AUDIO = "-b:a";
public static final String ARG_CHANNELS_AUDIO = "-ac";
public static final String ARG_FREQ_AUDIO = "-ar";
public static final String ARG_VOLUME_AUDIO = "-vol";
public static final String ARG_STARTTIME = "-ss";
public static final String ARG_DURATION = "-t";
public static final String ARG_DISABLE_AUDIO = "-an";
public static final String ARG_DISABLE_VIDEO = "-vn";
}
}
| false | true | public ProcessRunnable create() {
if (inputPath == null || outputPath == null) {
throw new IllegalStateException("Need an input and output filepath!");
}
final List<String> cmd = new LinkedList<String>();
cmd.add(mFfmpegPath);
cmd.add("-y");
if (TextUtils.isEmpty(inputFormat)) {
cmd.add(FFMPEGArg.ARG_FORMAT);
cmd.add(inputFormat);
}
if (TextUtils.isEmpty(inputVideoCodec)) {
cmd.add(FFMPEGArg.ARG_VIDEOCODEC);
cmd.add(inputVideoCodec);
}
if (TextUtils.isEmpty(inputAudioCodec)) {
cmd.add(FFMPEGArg.ARG_AUDIOCODEC);
cmd.add(inputAudioCodec);
}
cmd.add("-i");
cmd.add(inputPath);
if (disableVideo) {
cmd.add(FFMPEGArg.ARG_DISABLE_VIDEO);
} else {
if (videoBitrate > 0) {
cmd.add(FFMPEGArg.ARG_BITRATE_VIDEO);
cmd.add(videoBitrate + "k");
}
if (videoWidth > 0 && videoHeight > 0) {
cmd.add(FFMPEGArg.ARG_SIZE);
cmd.add(videoWidth + "x" + videoHeight);
}
if (videoFramerate > -1) {
cmd.add(FFMPEGArg.ARG_FRAMERATE);
cmd.add(String.valueOf(videoFramerate));
}
if (TextUtils.isEmpty(videoCodec)) {
cmd.add(FFMPEGArg.ARG_VIDEOCODEC);
cmd.add(videoCodec);
}
if (TextUtils.isEmpty(videoBitStreamFilter)) {
cmd.add(FFMPEGArg.ARG_VIDEOBITSTREAMFILTER);
cmd.add(videoBitStreamFilter);
}
if (TextUtils.isEmpty(videoFilter)) {
cmd.add(FFMPEGArg.ARG_VIDEOFILTER);
cmd.add(videoFilter);
}
}
if (disableAudio) {
cmd.add(FFMPEGArg.ARG_DISABLE_AUDIO);
} else {
if (TextUtils.isEmpty(audioCodec)) {
cmd.add(FFMPEGArg.ARG_AUDIOCODEC);
cmd.add(audioCodec);
}
if (TextUtils.isEmpty(audioBitStreamFilter)) {
cmd.add(FFMPEGArg.ARG_AUDIOBITSTREAMFILTER);
cmd.add(audioBitStreamFilter);
}
if (TextUtils.isEmpty(audioFilter)) {
cmd.add(FFMPEGArg.ARG_AUDIOFILTER);
cmd.add(audioFilter);
}
if (audioChannels > 0) {
cmd.add(FFMPEGArg.ARG_CHANNELS_AUDIO);
cmd.add(String.valueOf(audioChannels));
}
if (audioVolume > 0) {
cmd.add(FFMPEGArg.ARG_VOLUME_AUDIO);
cmd.add(String.valueOf(audioVolume));
}
if (audioBitrate > 0) {
cmd.add(FFMPEGArg.ARG_BITRATE_AUDIO);
cmd.add(audioBitrate + "k");
}
}
if (TextUtils.isEmpty(format)) {
cmd.add("-f");
cmd.add(format);
}
cmd.add(outputPath);
final ProcessBuilder pb = new ProcessBuilder(cmd);
return new ProcessRunnable(pb);
}
| public ProcessRunnable create() {
if (inputPath == null || outputPath == null) {
throw new IllegalStateException("Need an input and output filepath!");
}
final List<String> cmd = new LinkedList<String>();
cmd.add(mFfmpegPath);
cmd.add("-y");
if (!TextUtils.isEmpty(inputFormat)) {
cmd.add(FFMPEGArg.ARG_FORMAT);
cmd.add(inputFormat);
}
if (!TextUtils.isEmpty(inputVideoCodec)) {
cmd.add(FFMPEGArg.ARG_VIDEOCODEC);
cmd.add(inputVideoCodec);
}
if (!TextUtils.isEmpty(inputAudioCodec)) {
cmd.add(FFMPEGArg.ARG_AUDIOCODEC);
cmd.add(inputAudioCodec);
}
cmd.add("-i");
cmd.add(inputPath);
if (disableVideo) {
cmd.add(FFMPEGArg.ARG_DISABLE_VIDEO);
} else {
if (videoBitrate > 0) {
cmd.add(FFMPEGArg.ARG_BITRATE_VIDEO);
cmd.add(videoBitrate + "k");
}
if (videoWidth > 0 && videoHeight > 0) {
cmd.add(FFMPEGArg.ARG_SIZE);
cmd.add(videoWidth + "x" + videoHeight);
}
if (videoFramerate > -1) {
cmd.add(FFMPEGArg.ARG_FRAMERATE);
cmd.add(String.valueOf(videoFramerate));
}
if (!TextUtils.isEmpty(videoCodec)) {
cmd.add(FFMPEGArg.ARG_VIDEOCODEC);
cmd.add(videoCodec);
}
if (!TextUtils.isEmpty(videoBitStreamFilter)) {
cmd.add(FFMPEGArg.ARG_VIDEOBITSTREAMFILTER);
cmd.add(videoBitStreamFilter);
}
if (!TextUtils.isEmpty(videoFilter)) {
cmd.add(FFMPEGArg.ARG_VIDEOFILTER);
cmd.add(videoFilter);
}
}
if (disableAudio) {
cmd.add(FFMPEGArg.ARG_DISABLE_AUDIO);
} else {
if (!TextUtils.isEmpty(audioCodec)) {
cmd.add(FFMPEGArg.ARG_AUDIOCODEC);
cmd.add(audioCodec);
}
if (!TextUtils.isEmpty(audioBitStreamFilter)) {
cmd.add(FFMPEGArg.ARG_AUDIOBITSTREAMFILTER);
cmd.add(audioBitStreamFilter);
}
if (!TextUtils.isEmpty(audioFilter)) {
cmd.add(FFMPEGArg.ARG_AUDIOFILTER);
cmd.add(audioFilter);
}
if (audioChannels > 0) {
cmd.add(FFMPEGArg.ARG_CHANNELS_AUDIO);
cmd.add(String.valueOf(audioChannels));
}
if (audioVolume > 0) {
cmd.add(FFMPEGArg.ARG_VOLUME_AUDIO);
cmd.add(String.valueOf(audioVolume));
}
if (audioBitrate > 0) {
cmd.add(FFMPEGArg.ARG_BITRATE_AUDIO);
cmd.add(audioBitrate + "k");
}
}
if (!TextUtils.isEmpty(format)) {
cmd.add("-f");
cmd.add(format);
}
cmd.add(outputPath);
final ProcessBuilder pb = new ProcessBuilder(cmd);
return new ProcessRunnable(pb);
}
|
diff --git a/openejb/examples/webapps/rest-example/src/test/java/org/superbiz/rest/dao/UserServiceTest.java b/openejb/examples/webapps/rest-example/src/test/java/org/superbiz/rest/dao/UserServiceTest.java
index ed7fbf4b4..3fdb376b5 100644
--- a/openejb/examples/webapps/rest-example/src/test/java/org/superbiz/rest/dao/UserServiceTest.java
+++ b/openejb/examples/webapps/rest-example/src/test/java/org/superbiz/rest/dao/UserServiceTest.java
@@ -1,89 +1,89 @@
package org.superbiz.rest.dao;
import org.apache.commons.io.FileUtils;
import org.apache.cxf.jaxrs.client.JAXRSClientFactory;
import org.apache.tomee.embedded.EmbeddedTomEEContainer;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.superbiz.rest.model.User;
import javax.ejb.embeddable.EJBContainer;
import javax.naming.NamingException;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNotNull;
/**
* @author rmannibucau
*/
public class UserServiceTest {
private static EJBContainer container;
private static File webApp;
@BeforeClass public static void start() throws IOException {
webApp = createWebApp();
Properties p = new Properties();
p.setProperty(EJBContainer.APP_NAME, "test");
p.setProperty(EJBContainer.PROVIDER, "tomee-embedded"); // need web feature
p.setProperty(EJBContainer.MODULES, webApp.getAbsolutePath());
p.setProperty(EmbeddedTomEEContainer.TOMEE_EJBCONTAINER_HTTP_PORT, "-1"); // random port
container = EJBContainer.createEJBContainer(p);
}
@AfterClass public static void stop() {
if (container != null) {
container.close();
}
if (webApp != null) {
try {
FileUtils.forceDelete(webApp);
} catch (IOException e) {
FileUtils.deleteQuietly(webApp);
}
}
}
@Test public void create() throws NamingException {
- UserDAO dao = (UserDAO) container.getContext().lookup("java:global/" + webApp.getName() + "/UserDAO");
+ UserDAO dao = (UserDAO) container.getContext().lookup("java:global/rest-example/UserDAO");
User user = dao.create("foo", "dummy", "[email protected]");
assertNotNull(dao.find(user.getId()));
String uri = "http://127.0.0.1:" + System.getProperty(EmbeddedTomEEContainer.TOMEE_EJBCONTAINER_HTTP_PORT) + "/" + webApp.getName();
UserServiceClientAPI client = JAXRSClientFactory.create(uri, UserServiceClientAPI.class);
User retrievedUser = client.show(user.getId());
assertNotNull(retrievedUser);
assertEquals("foo", retrievedUser.getFullname());
assertEquals("dummy", retrievedUser.getPassword());
assertEquals("[email protected]", retrievedUser.getEmail());
}
private static File createWebApp() throws IOException {
File file = new File(System.getProperty("java.io.tmpdir") + "/tomee-" + Math.random());
if (!file.mkdirs() && !file.exists()) {
throw new RuntimeException("can't create " + file.getAbsolutePath());
}
FileUtils.copyDirectory(new File("target/classes"), new File(file, "WEB-INF/classes"));
return file;
}
/**
* a simple copy of the unique method i want to use from my service.
* It allows to use cxf proxy to call remotely our rest service.
* Any other way to do it is good.
*/
@Path("/api/user")
@Produces({ "text/xml", "application/json" })
public static interface UserServiceClientAPI {
@Path("/show/{id}") @GET User show(@PathParam("id") long id);
}
}
| true | true | @Test public void create() throws NamingException {
UserDAO dao = (UserDAO) container.getContext().lookup("java:global/" + webApp.getName() + "/UserDAO");
User user = dao.create("foo", "dummy", "[email protected]");
assertNotNull(dao.find(user.getId()));
String uri = "http://127.0.0.1:" + System.getProperty(EmbeddedTomEEContainer.TOMEE_EJBCONTAINER_HTTP_PORT) + "/" + webApp.getName();
UserServiceClientAPI client = JAXRSClientFactory.create(uri, UserServiceClientAPI.class);
User retrievedUser = client.show(user.getId());
assertNotNull(retrievedUser);
assertEquals("foo", retrievedUser.getFullname());
assertEquals("dummy", retrievedUser.getPassword());
assertEquals("[email protected]", retrievedUser.getEmail());
}
| @Test public void create() throws NamingException {
UserDAO dao = (UserDAO) container.getContext().lookup("java:global/rest-example/UserDAO");
User user = dao.create("foo", "dummy", "[email protected]");
assertNotNull(dao.find(user.getId()));
String uri = "http://127.0.0.1:" + System.getProperty(EmbeddedTomEEContainer.TOMEE_EJBCONTAINER_HTTP_PORT) + "/" + webApp.getName();
UserServiceClientAPI client = JAXRSClientFactory.create(uri, UserServiceClientAPI.class);
User retrievedUser = client.show(user.getId());
assertNotNull(retrievedUser);
assertEquals("foo", retrievedUser.getFullname());
assertEquals("dummy", retrievedUser.getPassword());
assertEquals("[email protected]", retrievedUser.getEmail());
}
|
diff --git a/src/main/java/org/cytoscape/fluxviz/internal/logic/Context.java b/src/main/java/org/cytoscape/fluxviz/internal/logic/Context.java
index 37c2ded..68f36e9 100644
--- a/src/main/java/org/cytoscape/fluxviz/internal/logic/Context.java
+++ b/src/main/java/org/cytoscape/fluxviz/internal/logic/Context.java
@@ -1,44 +1,45 @@
package org.cytoscape.fluxviz.internal.logic;
import java.util.ArrayList;
import java.util.List;
import org.cytoscape.model.CyNetwork;
public class Context {
private List<CyNetwork> activeNetworks;
private Evaluator evaluator = null;
int sleepTime;
public int getSleepTime() {
return sleepTime;
}
public void setSleepTime(int sleepTime) {
this.sleepTime = sleepTime;
}
public Evaluator getEvaluator() {
return evaluator;
}
public void setEvaluator(Evaluator evaluator) {
this.evaluator = evaluator;
}
public Context()
{
activeNetworks = new ArrayList<CyNetwork>();
+ sleepTime = 1;
}
public boolean containsNetwork(CyNetwork network)
{
return activeNetworks.contains(network);
}
public void addNetwork(CyNetwork network)
{
activeNetworks.add(network);
}
}
| true | true | public Context()
{
activeNetworks = new ArrayList<CyNetwork>();
}
| public Context()
{
activeNetworks = new ArrayList<CyNetwork>();
sleepTime = 1;
}
|
diff --git a/src/java/com/stackframe/sarariman/WeeknightTask.java b/src/java/com/stackframe/sarariman/WeeknightTask.java
index cad16b2..3f96a9c 100644
--- a/src/java/com/stackframe/sarariman/WeeknightTask.java
+++ b/src/java/com/stackframe/sarariman/WeeknightTask.java
@@ -1,61 +1,61 @@
/*
* Copyright (C) 2009-2010 StackFrame, LLC
* This code is licensed under GPLv2.
*/
package com.stackframe.sarariman;
import java.sql.Date;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author mcculley
*/
public class WeeknightTask extends TimerTask {
private final Sarariman sarariman;
private final Directory directory;
private final EmailDispatcher emailDispatcher;
private final Logger logger = Logger.getLogger(getClass().getName());
public WeeknightTask(Sarariman sarariman, Directory directory, EmailDispatcher emailDispatcher) {
this.sarariman = sarariman;
this.directory = directory;
this.emailDispatcher = emailDispatcher;
}
public void run() {
Calendar today = Calendar.getInstance();
int dayOfWeek = today.get(Calendar.DAY_OF_WEEK);
- if (dayOfWeek == Calendar.SATURDAY && dayOfWeek == Calendar.SUNDAY) {
+ if (dayOfWeek == Calendar.SATURDAY || dayOfWeek == Calendar.SUNDAY) {
return;
}
java.util.Date todayDate = today.getTime();
Date week = new Date(DateUtils.weekStart(todayDate).getTime());
for (Employee employee : directory.getByUserName().values()) {
Timesheet timesheet = new Timesheet(sarariman, employee.getNumber(), week);
try {
if (!timesheet.isSubmitted()) {
if (dayOfWeek == Calendar.FRIDAY) {
emailDispatcher.send(employee.getEmail(), EmailDispatcher.addresses(sarariman.getApprovers()),
"timesheet", "Please submit your timesheet for the week of " + week + ".");
} else {
double hoursRecorded = timesheet.getHours(new Date(todayDate.getTime()));
if (hoursRecorded == 0.0 && employee.isFulltime()) {
emailDispatcher.send(employee.getEmail(), EmailDispatcher.addresses(sarariman.getApprovers()),
"timesheet", "Please record your time if you worked today.");
}
}
}
} catch (SQLException se) {
logger.log(Level.SEVERE, "could not get hours for " + today, se);
}
}
}
}
| true | true | public void run() {
Calendar today = Calendar.getInstance();
int dayOfWeek = today.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek == Calendar.SATURDAY && dayOfWeek == Calendar.SUNDAY) {
return;
}
java.util.Date todayDate = today.getTime();
Date week = new Date(DateUtils.weekStart(todayDate).getTime());
for (Employee employee : directory.getByUserName().values()) {
Timesheet timesheet = new Timesheet(sarariman, employee.getNumber(), week);
try {
if (!timesheet.isSubmitted()) {
if (dayOfWeek == Calendar.FRIDAY) {
emailDispatcher.send(employee.getEmail(), EmailDispatcher.addresses(sarariman.getApprovers()),
"timesheet", "Please submit your timesheet for the week of " + week + ".");
} else {
double hoursRecorded = timesheet.getHours(new Date(todayDate.getTime()));
if (hoursRecorded == 0.0 && employee.isFulltime()) {
emailDispatcher.send(employee.getEmail(), EmailDispatcher.addresses(sarariman.getApprovers()),
"timesheet", "Please record your time if you worked today.");
}
}
}
} catch (SQLException se) {
logger.log(Level.SEVERE, "could not get hours for " + today, se);
}
}
}
| public void run() {
Calendar today = Calendar.getInstance();
int dayOfWeek = today.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek == Calendar.SATURDAY || dayOfWeek == Calendar.SUNDAY) {
return;
}
java.util.Date todayDate = today.getTime();
Date week = new Date(DateUtils.weekStart(todayDate).getTime());
for (Employee employee : directory.getByUserName().values()) {
Timesheet timesheet = new Timesheet(sarariman, employee.getNumber(), week);
try {
if (!timesheet.isSubmitted()) {
if (dayOfWeek == Calendar.FRIDAY) {
emailDispatcher.send(employee.getEmail(), EmailDispatcher.addresses(sarariman.getApprovers()),
"timesheet", "Please submit your timesheet for the week of " + week + ".");
} else {
double hoursRecorded = timesheet.getHours(new Date(todayDate.getTime()));
if (hoursRecorded == 0.0 && employee.isFulltime()) {
emailDispatcher.send(employee.getEmail(), EmailDispatcher.addresses(sarariman.getApprovers()),
"timesheet", "Please record your time if you worked today.");
}
}
}
} catch (SQLException se) {
logger.log(Level.SEVERE, "could not get hours for " + today, se);
}
}
}
|
diff --git a/src/com/redhat/contentspec/client/commands/CreateCommand.java b/src/com/redhat/contentspec/client/commands/CreateCommand.java
index 3d26a79..a5813ed 100644
--- a/src/com/redhat/contentspec/client/commands/CreateCommand.java
+++ b/src/com/redhat/contentspec/client/commands/CreateCommand.java
@@ -1,247 +1,247 @@
package com.redhat.contentspec.client.commands;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
import com.redhat.contentspec.client.config.ContentSpecConfiguration;
import com.redhat.contentspec.client.constants.Constants;
import com.redhat.contentspec.client.converter.FileConverter;
import com.redhat.contentspec.client.utils.ClientUtilities;
import com.redhat.contentspec.processor.ContentSpecParser;
import com.redhat.contentspec.processor.ContentSpecProcessor;
import com.redhat.contentspec.rest.RESTManager;
import com.redhat.contentspec.rest.RESTReader;
import com.redhat.contentspec.utils.StringUtilities;
import com.redhat.contentspec.utils.logging.ErrorLoggerManager;
import com.redhat.ecs.commonutils.FileUtilities;
import com.redhat.topicindex.rest.entities.TopicV1;
import com.redhat.topicindex.rest.entities.UserV1;
@Parameters(commandDescription = "Create a new Content Specification on the server")
public class CreateCommand extends BaseCommandImpl {
@Parameter(converter = FileConverter.class, metaVar = "[FILE]")
private List<File> files = new ArrayList<File>();
@Parameter(names = {Constants.PERMISSIVE_LONG_PARAM, Constants.PERMISSIVE_SHORT_PARAM}, description = "Turn on permissive processing.")
private Boolean permissive = false;
@Parameter(names = Constants.EXEC_TIME_LONG_PARAM, description = "Show the execution time of the command.", hidden = true)
private Boolean executionTime = false;
@Parameter(names = Constants.NO_CREATE_CSPROCESSOR_CFG_LONG_PARAM, description = "Don't create the csprocessor.cfg and other files.")
private Boolean createCsprocessorCfg = true;
@Parameter(names = {Constants.FORCE_LONG_PARAM, Constants.FORCE_SHORT_PARAM}, description = "Force the Content Specification directories to be created.")
private Boolean force = false;
private ContentSpecProcessor csp = null;
public CreateCommand(JCommander parser) {
super(parser);
}
public List<File> getFiles() {
return files;
}
public void setFiles(List<File> files) {
this.files = files;
}
public Boolean getPermissive() {
return permissive;
}
public void setPermissive(Boolean permissive) {
this.permissive = permissive;
}
public Boolean getExecutionTime() {
return executionTime;
}
public void setExecutionTime(Boolean executionTime) {
this.executionTime = executionTime;
}
public Boolean getCreateCsprocessorCfg() {
return createCsprocessorCfg;
}
public void setCreateCsprocessorCfg(Boolean createCsprocessorCfg) {
this.createCsprocessorCfg = createCsprocessorCfg;
}
public Boolean getForce() {
return force;
}
public void setForce(Boolean force) {
this.force = force;
}
public boolean isValid() {
// We should have only one file
if (files.size() != 1) return false;
// Check that the file exists
File file = files.get(0);
if (file.isDirectory()) return false;
if (!file.exists()) return false;
if (!file.isFile()) return false;
return true;
}
@Override
public void process(ContentSpecConfiguration cspConfig, RESTManager restManager, ErrorLoggerManager elm, UserV1 user) {
if (!isValid()) {
printError(Constants.ERROR_NO_FILE_MSG, true);
shutdown(Constants.EXIT_FAILURE);
}
long startTime = System.currentTimeMillis();
boolean success = false;
// Read in the file contents
String contentSpec = FileUtilities.readFileContents(files.get(0));
if (contentSpec == null || contentSpec.equals("")) {
printError(Constants.ERROR_EMPTY_FILE_MSG, false);
shutdown(Constants.EXIT_FAILURE);
}
// Good point to check for a shutdown
if (isAppShuttingDown()) {
shutdown.set(true);
return;
}
// Parse the spec to get the title
ContentSpecParser parser = new ContentSpecParser(elm, restManager);
try {
parser.parse(contentSpec);
} catch (Exception e) {
printError(Constants.ERROR_INTERNAL_ERROR, false);
shutdown(Constants.EXIT_INTERNAL_SERVER_ERROR);
}
// Check that the output directory doesn't already exist
File directory = new File(cspConfig.getRootOutputDirectory() + StringUtilities.escapeTitle(parser.getContentSpec().getTitle()));
- if (directory.exists() && !force) {
+ if (directory.exists() && !force && directory.isDirectory()) {
printError(String.format(Constants.ERROR_CONTENT_SPEC_EXISTS_MSG, directory.getAbsolutePath()), false);
shutdown(Constants.EXIT_FAILURE);
// If it exists and force is enabled delete the directory contents
- } else if (directory.exists()) {
+ } else if (directory.exists() && directory.isDirectory()) {
ClientUtilities.deleteDir(directory);
}
// Good point to check for a shutdown
if (isAppShuttingDown()) {
shutdown.set(true);
return;
}
csp = new ContentSpecProcessor(restManager, elm, permissive);
Integer revision = null;
try {
success = csp.processContentSpec(contentSpec, user, ContentSpecParser.ParsingMode.NEW);
if (success) {
revision = restManager.getReader().getLatestCSRevById(csp.getContentSpec().getId());
}
} catch (Exception e) {
printError(Constants.ERROR_INTERNAL_ERROR, false);
shutdown(Constants.EXIT_INTERNAL_SERVER_ERROR);
}
// Print the logs
long elapsedTime = System.currentTimeMillis() - startTime;
JCommander.getConsole().println(elm.generateLogs());
if (success) {
JCommander.getConsole().println(String.format(Constants.SUCCESSFUL_PUSH_MSG, csp.getContentSpec().getId(), revision));
}
if (executionTime) {
JCommander.getConsole().println(String.format(Constants.EXEC_TIME_MSG, elapsedTime));
}
// Good point to check for a shutdown
// It doesn't matter if the directory and files aren't created just so long as the spec finished saving
if (isAppShuttingDown()) {
shutdown.set(true);
return;
}
if (success && createCsprocessorCfg) {
boolean error = false;
// Save the csprocessor.cfg and post spec to file if the create was successful
String escapedTitle = StringUtilities.escapeTitle(csp.getContentSpec().getTitle());
TopicV1 contentSpecTopic = restManager.getReader().getContentSpecById(csp.getContentSpec().getId(), null);
File outputSpec = new File(cspConfig.getRootOutputDirectory() + escapedTitle + File.separator + escapedTitle + "-post." + Constants.FILENAME_EXTENSION);
File outputConfig = new File(cspConfig.getRootOutputDirectory() + escapedTitle + File.separator + "csprocessor.cfg");
String config = ClientUtilities.generateCsprocessorCfg(contentSpecTopic, cspConfig.getServerUrl());
// Create the directory
if (outputConfig.getParentFile() != null)
outputConfig.getParentFile().mkdirs();
// Save the csprocessor.cfg
try {
FileOutputStream fos = new FileOutputStream(outputConfig);
fos.write(config.getBytes());
fos.flush();
fos.close();
JCommander.getConsole().println(String.format(Constants.OUTPUT_SAVED_MSG, outputConfig.getAbsolutePath()));
} catch (IOException e) {
printError(String.format(Constants.ERROR_FAILED_SAVING_FILE, outputConfig.getAbsolutePath()), false);
error = true;
}
// Save the Post Processed spec
try {
FileOutputStream fos = new FileOutputStream(outputSpec);
fos.write(contentSpecTopic.getXml().getBytes());
fos.flush();
fos.close();
JCommander.getConsole().println(String.format(Constants.OUTPUT_SAVED_MSG, outputSpec.getAbsolutePath()));
} catch (IOException e) {
printError(String.format(Constants.ERROR_FAILED_SAVING_FILE, outputSpec.getAbsolutePath()), false);
error = false;
}
if (error) {
shutdown(Constants.EXIT_FAILURE);
}
}
}
@Override
public void printError(String errorMsg, boolean displayHelp) {
printError(errorMsg, displayHelp, Constants.CREATE_COMMAND_NAME);
}
@Override
public void printHelp() {
printHelp(Constants.CREATE_COMMAND_NAME);
}
@Override
public UserV1 authenticate(RESTReader reader) {
return authenticate(getUsername(), reader);
}
@Override
public void shutdown() {
super.shutdown();
if (csp != null) {
csp.shutdown();
}
}
}
| false | true | public void process(ContentSpecConfiguration cspConfig, RESTManager restManager, ErrorLoggerManager elm, UserV1 user) {
if (!isValid()) {
printError(Constants.ERROR_NO_FILE_MSG, true);
shutdown(Constants.EXIT_FAILURE);
}
long startTime = System.currentTimeMillis();
boolean success = false;
// Read in the file contents
String contentSpec = FileUtilities.readFileContents(files.get(0));
if (contentSpec == null || contentSpec.equals("")) {
printError(Constants.ERROR_EMPTY_FILE_MSG, false);
shutdown(Constants.EXIT_FAILURE);
}
// Good point to check for a shutdown
if (isAppShuttingDown()) {
shutdown.set(true);
return;
}
// Parse the spec to get the title
ContentSpecParser parser = new ContentSpecParser(elm, restManager);
try {
parser.parse(contentSpec);
} catch (Exception e) {
printError(Constants.ERROR_INTERNAL_ERROR, false);
shutdown(Constants.EXIT_INTERNAL_SERVER_ERROR);
}
// Check that the output directory doesn't already exist
File directory = new File(cspConfig.getRootOutputDirectory() + StringUtilities.escapeTitle(parser.getContentSpec().getTitle()));
if (directory.exists() && !force) {
printError(String.format(Constants.ERROR_CONTENT_SPEC_EXISTS_MSG, directory.getAbsolutePath()), false);
shutdown(Constants.EXIT_FAILURE);
// If it exists and force is enabled delete the directory contents
} else if (directory.exists()) {
ClientUtilities.deleteDir(directory);
}
// Good point to check for a shutdown
if (isAppShuttingDown()) {
shutdown.set(true);
return;
}
csp = new ContentSpecProcessor(restManager, elm, permissive);
Integer revision = null;
try {
success = csp.processContentSpec(contentSpec, user, ContentSpecParser.ParsingMode.NEW);
if (success) {
revision = restManager.getReader().getLatestCSRevById(csp.getContentSpec().getId());
}
} catch (Exception e) {
printError(Constants.ERROR_INTERNAL_ERROR, false);
shutdown(Constants.EXIT_INTERNAL_SERVER_ERROR);
}
// Print the logs
long elapsedTime = System.currentTimeMillis() - startTime;
JCommander.getConsole().println(elm.generateLogs());
if (success) {
JCommander.getConsole().println(String.format(Constants.SUCCESSFUL_PUSH_MSG, csp.getContentSpec().getId(), revision));
}
if (executionTime) {
JCommander.getConsole().println(String.format(Constants.EXEC_TIME_MSG, elapsedTime));
}
// Good point to check for a shutdown
// It doesn't matter if the directory and files aren't created just so long as the spec finished saving
if (isAppShuttingDown()) {
shutdown.set(true);
return;
}
if (success && createCsprocessorCfg) {
boolean error = false;
// Save the csprocessor.cfg and post spec to file if the create was successful
String escapedTitle = StringUtilities.escapeTitle(csp.getContentSpec().getTitle());
TopicV1 contentSpecTopic = restManager.getReader().getContentSpecById(csp.getContentSpec().getId(), null);
File outputSpec = new File(cspConfig.getRootOutputDirectory() + escapedTitle + File.separator + escapedTitle + "-post." + Constants.FILENAME_EXTENSION);
File outputConfig = new File(cspConfig.getRootOutputDirectory() + escapedTitle + File.separator + "csprocessor.cfg");
String config = ClientUtilities.generateCsprocessorCfg(contentSpecTopic, cspConfig.getServerUrl());
// Create the directory
if (outputConfig.getParentFile() != null)
outputConfig.getParentFile().mkdirs();
// Save the csprocessor.cfg
try {
FileOutputStream fos = new FileOutputStream(outputConfig);
fos.write(config.getBytes());
fos.flush();
fos.close();
JCommander.getConsole().println(String.format(Constants.OUTPUT_SAVED_MSG, outputConfig.getAbsolutePath()));
} catch (IOException e) {
printError(String.format(Constants.ERROR_FAILED_SAVING_FILE, outputConfig.getAbsolutePath()), false);
error = true;
}
// Save the Post Processed spec
try {
FileOutputStream fos = new FileOutputStream(outputSpec);
fos.write(contentSpecTopic.getXml().getBytes());
fos.flush();
fos.close();
JCommander.getConsole().println(String.format(Constants.OUTPUT_SAVED_MSG, outputSpec.getAbsolutePath()));
} catch (IOException e) {
printError(String.format(Constants.ERROR_FAILED_SAVING_FILE, outputSpec.getAbsolutePath()), false);
error = false;
}
if (error) {
shutdown(Constants.EXIT_FAILURE);
}
}
}
| public void process(ContentSpecConfiguration cspConfig, RESTManager restManager, ErrorLoggerManager elm, UserV1 user) {
if (!isValid()) {
printError(Constants.ERROR_NO_FILE_MSG, true);
shutdown(Constants.EXIT_FAILURE);
}
long startTime = System.currentTimeMillis();
boolean success = false;
// Read in the file contents
String contentSpec = FileUtilities.readFileContents(files.get(0));
if (contentSpec == null || contentSpec.equals("")) {
printError(Constants.ERROR_EMPTY_FILE_MSG, false);
shutdown(Constants.EXIT_FAILURE);
}
// Good point to check for a shutdown
if (isAppShuttingDown()) {
shutdown.set(true);
return;
}
// Parse the spec to get the title
ContentSpecParser parser = new ContentSpecParser(elm, restManager);
try {
parser.parse(contentSpec);
} catch (Exception e) {
printError(Constants.ERROR_INTERNAL_ERROR, false);
shutdown(Constants.EXIT_INTERNAL_SERVER_ERROR);
}
// Check that the output directory doesn't already exist
File directory = new File(cspConfig.getRootOutputDirectory() + StringUtilities.escapeTitle(parser.getContentSpec().getTitle()));
if (directory.exists() && !force && directory.isDirectory()) {
printError(String.format(Constants.ERROR_CONTENT_SPEC_EXISTS_MSG, directory.getAbsolutePath()), false);
shutdown(Constants.EXIT_FAILURE);
// If it exists and force is enabled delete the directory contents
} else if (directory.exists() && directory.isDirectory()) {
ClientUtilities.deleteDir(directory);
}
// Good point to check for a shutdown
if (isAppShuttingDown()) {
shutdown.set(true);
return;
}
csp = new ContentSpecProcessor(restManager, elm, permissive);
Integer revision = null;
try {
success = csp.processContentSpec(contentSpec, user, ContentSpecParser.ParsingMode.NEW);
if (success) {
revision = restManager.getReader().getLatestCSRevById(csp.getContentSpec().getId());
}
} catch (Exception e) {
printError(Constants.ERROR_INTERNAL_ERROR, false);
shutdown(Constants.EXIT_INTERNAL_SERVER_ERROR);
}
// Print the logs
long elapsedTime = System.currentTimeMillis() - startTime;
JCommander.getConsole().println(elm.generateLogs());
if (success) {
JCommander.getConsole().println(String.format(Constants.SUCCESSFUL_PUSH_MSG, csp.getContentSpec().getId(), revision));
}
if (executionTime) {
JCommander.getConsole().println(String.format(Constants.EXEC_TIME_MSG, elapsedTime));
}
// Good point to check for a shutdown
// It doesn't matter if the directory and files aren't created just so long as the spec finished saving
if (isAppShuttingDown()) {
shutdown.set(true);
return;
}
if (success && createCsprocessorCfg) {
boolean error = false;
// Save the csprocessor.cfg and post spec to file if the create was successful
String escapedTitle = StringUtilities.escapeTitle(csp.getContentSpec().getTitle());
TopicV1 contentSpecTopic = restManager.getReader().getContentSpecById(csp.getContentSpec().getId(), null);
File outputSpec = new File(cspConfig.getRootOutputDirectory() + escapedTitle + File.separator + escapedTitle + "-post." + Constants.FILENAME_EXTENSION);
File outputConfig = new File(cspConfig.getRootOutputDirectory() + escapedTitle + File.separator + "csprocessor.cfg");
String config = ClientUtilities.generateCsprocessorCfg(contentSpecTopic, cspConfig.getServerUrl());
// Create the directory
if (outputConfig.getParentFile() != null)
outputConfig.getParentFile().mkdirs();
// Save the csprocessor.cfg
try {
FileOutputStream fos = new FileOutputStream(outputConfig);
fos.write(config.getBytes());
fos.flush();
fos.close();
JCommander.getConsole().println(String.format(Constants.OUTPUT_SAVED_MSG, outputConfig.getAbsolutePath()));
} catch (IOException e) {
printError(String.format(Constants.ERROR_FAILED_SAVING_FILE, outputConfig.getAbsolutePath()), false);
error = true;
}
// Save the Post Processed spec
try {
FileOutputStream fos = new FileOutputStream(outputSpec);
fos.write(contentSpecTopic.getXml().getBytes());
fos.flush();
fos.close();
JCommander.getConsole().println(String.format(Constants.OUTPUT_SAVED_MSG, outputSpec.getAbsolutePath()));
} catch (IOException e) {
printError(String.format(Constants.ERROR_FAILED_SAVING_FILE, outputSpec.getAbsolutePath()), false);
error = false;
}
if (error) {
shutdown(Constants.EXIT_FAILURE);
}
}
}
|
diff --git a/core/org.eclipse.ptp.remote.remotetools.core/src/org/eclipse/ptp/remote/remotetools/RemoteToolsConnection.java b/core/org.eclipse.ptp.remote.remotetools.core/src/org/eclipse/ptp/remote/remotetools/RemoteToolsConnection.java
index 34899e9da..cece3c7df 100644
--- a/core/org.eclipse.ptp.remote.remotetools.core/src/org/eclipse/ptp/remote/remotetools/RemoteToolsConnection.java
+++ b/core/org.eclipse.ptp.remote.remotetools.core/src/org/eclipse/ptp/remote/remotetools/RemoteToolsConnection.java
@@ -1,245 +1,238 @@
/*******************************************************************************
* Copyright (c) 2007 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.ptp.remote.remotetools;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.ptp.remote.IRemoteConnection;
import org.eclipse.ptp.remote.exception.AddressInUseException;
import org.eclipse.ptp.remote.exception.RemoteConnectionException;
import org.eclipse.ptp.remote.exception.UnableToForwardPortException;
import org.eclipse.ptp.remote.remotetools.environment.core.PTPTargetControl;
import org.eclipse.ptp.remotetools.core.IRemoteExecutionManager;
import org.eclipse.ptp.remotetools.environment.control.ITargetStatus;
import org.eclipse.ptp.remotetools.exception.CancelException;
import org.eclipse.ptp.remotetools.exception.LocalPortBoundException;
import org.eclipse.ptp.remotetools.exception.PortForwardingException;
public class RemoteToolsConnection implements IRemoteConnection {
private String connName;
private String address;
private String userName;
private PTPTargetControl control;
public RemoteToolsConnection(String name, String address, String userName, PTPTargetControl control) {
this.control = control;
this.connName = name;
this.address = address;
this.userName = userName;
}
/* (non-Javadoc)
* @see org.eclipse.ptp.remote.IRemoteConnection#close()
*/
public synchronized void close(IProgressMonitor monitor) {
if (monitor == null) {
monitor = new NullProgressMonitor();
}
monitor.beginTask("Closing connection...", 1);
try {
control.kill(monitor);
} catch (CoreException e) {
}
monitor.done();
}
/**
* Create a new execution manager. Required because script execution
* closes channel after execution.
*
* @return execution manager
* @throws org.eclipse.ptp.remotetools.exception.RemoteConnectionException
*/
public IRemoteExecutionManager createExecutionManager() throws org.eclipse.ptp.remotetools.exception.RemoteConnectionException {
return control.createExecutionManager();
}
/* (non-Javadoc)
* @see org.eclipse.ptp.remote.IRemoteConnection#forwardLocalPort(int, java.lang.String, int)
*/
public void forwardLocalPort(int localPort, String fwdAddress, int fwdPort)
throws RemoteConnectionException {
if (!isOpen()) {
throw new RemoteConnectionException("Connection is not open");
}
try {
control.getExecutionManager().createTunnel(localPort, fwdAddress, fwdPort);
} catch (LocalPortBoundException e) {
throw new AddressInUseException(e.getMessage());
} catch (org.eclipse.ptp.remotetools.exception.RemoteConnectionException e) {
throw new RemoteConnectionException(e.getMessage());
} catch (CancelException e) {
throw new RemoteConnectionException(e.getMessage());
}
}
/* (non-Javadoc)
* @see org.eclipse.ptp.remote.IRemoteConnection#forwardLocalPort(java.lang.String, int, org.eclipse.core.runtime.IProgressMonitor)
*/
public int forwardLocalPort(String fwdAddress, int fwdPort,
IProgressMonitor monitor) throws RemoteConnectionException {
if (!isOpen()) {
throw new RemoteConnectionException("Connection is not open");
}
return 0;
}
/* (non-Javadoc)
* @see org.eclipse.ptp.remote.IRemoteConnection#forwardRemotePort(int, java.lang.String, int)
*/
public void forwardRemotePort(int remotePort, String fwdAddress, int fwdPort)
throws RemoteConnectionException {
if (!isOpen()) {
throw new RemoteConnectionException("Connection is not open");
}
try {
control.getExecutionManager().getPortForwardingTools().forwardRemotePort(remotePort, fwdAddress, fwdPort);
} catch (org.eclipse.ptp.remotetools.exception.RemoteConnectionException e) {
throw new RemoteConnectionException(e.getMessage());
} catch (CancelException e) {
throw new RemoteConnectionException(e.getMessage());
} catch (PortForwardingException e) {
throw new AddressInUseException(e.getMessage());
}
}
/* (non-Javadoc)
* @see org.eclipse.ptp.remote.IRemoteConnection#forwardRemotePort(java.lang.String, int, org.eclipse.core.runtime.IProgressMonitor)
*/
public int forwardRemotePort(String fwdAddress, int fwdPort,
IProgressMonitor monitor) throws RemoteConnectionException {
if (monitor == null) {
monitor = new NullProgressMonitor();
}
monitor.beginTask("Setting up remote forwarding", 10);
/*
* Start with a different port number, in case we're doing this all on localhost.
*/
int remotePort = fwdPort + 1;
/*
* Try to find a free port on the remote machine. This take a while, so
* allow it to be canceled. If we've tried all ports (which could take a
* very long while) then bail out.
*/
while (!monitor.isCanceled()) {
try {
forwardRemotePort(remotePort, fwdAddress, fwdPort);
} catch (AddressInUseException e) {
if (++remotePort == fwdPort) {
throw new UnableToForwardPortException("Could not allocate remote port");
}
monitor.worked(1);
}
monitor.done();
return remotePort;
}
monitor.done();
return -1;
}
/* (non-Javadoc)
* @see org.eclipse.ptp.remote.IRemoteConnection#getAddress()
*/
public String getAddress() {
return address;
}
/* (non-Javadoc)
* @see org.eclipse.ptp.remote.IRemoteConnection#getName()
*/
public String getName() {
return connName;
}
public String getUsername() {
return userName;
}
/* (non-Javadoc)
* @see org.eclipse.ptp.remote.IRemoteConnection#isOpen()
*/
public synchronized boolean isOpen() {
return control.query() == ITargetStatus.RESUMED;
}
/* (non-Javadoc)
* @see org.eclipse.ptp.remote.IRemoteConnection#open()
*/
public void open(IProgressMonitor monitor) throws RemoteConnectionException {
if (monitor == null) {
monitor = new NullProgressMonitor();
}
monitor.beginTask("Opening connection...", 2);
if (control.query() == ITargetStatus.STOPPED) {
Job job = new Job("Start the Environment") {
protected IStatus run(IProgressMonitor monitor) {
IStatus status = null;
try {
if (control.create(monitor)) {
status = Status.OK_STATUS;
}
} catch (CoreException e) {
status = e.getStatus();
}
return status;
}
};
job.setUser(true);
job.schedule();
monitor.worked(1);
/*
* Wait for the job to finish
*/
while (!monitor.isCanceled() && control.query() != ITargetStatus.RESUMED) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
}
- if (monitor.isCanceled()) {
- try {
- control.kill(null);
- } catch (CoreException e) {
- }
- throw new RemoteConnectionException("Remote connection canceled");
- }
}
monitor.done();
}
/* (non-Javadoc)
* @see org.eclipse.ptp.remote.IRemoteConnection#setAddress(java.lang.String)
*/
public void setAddress(String address) {
this.address = address;
}
/* (non-Javadoc)
* @see org.eclipse.ptp.remote.IRemoteConnection#setUsername(java.lang.String)
*/
public void setUsername(String userName) {
this.userName = userName;
}
/* (non-Javadoc)
* @see org.eclipse.ptp.remote.IRemoteConnection#supportsTCPPortForwarding()
*/
public boolean supportsTCPPortForwarding() {
return true;
}
}
| true | true | public void open(IProgressMonitor monitor) throws RemoteConnectionException {
if (monitor == null) {
monitor = new NullProgressMonitor();
}
monitor.beginTask("Opening connection...", 2);
if (control.query() == ITargetStatus.STOPPED) {
Job job = new Job("Start the Environment") {
protected IStatus run(IProgressMonitor monitor) {
IStatus status = null;
try {
if (control.create(monitor)) {
status = Status.OK_STATUS;
}
} catch (CoreException e) {
status = e.getStatus();
}
return status;
}
};
job.setUser(true);
job.schedule();
monitor.worked(1);
/*
* Wait for the job to finish
*/
while (!monitor.isCanceled() && control.query() != ITargetStatus.RESUMED) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
}
if (monitor.isCanceled()) {
try {
control.kill(null);
} catch (CoreException e) {
}
throw new RemoteConnectionException("Remote connection canceled");
}
}
monitor.done();
}
| public void open(IProgressMonitor monitor) throws RemoteConnectionException {
if (monitor == null) {
monitor = new NullProgressMonitor();
}
monitor.beginTask("Opening connection...", 2);
if (control.query() == ITargetStatus.STOPPED) {
Job job = new Job("Start the Environment") {
protected IStatus run(IProgressMonitor monitor) {
IStatus status = null;
try {
if (control.create(monitor)) {
status = Status.OK_STATUS;
}
} catch (CoreException e) {
status = e.getStatus();
}
return status;
}
};
job.setUser(true);
job.schedule();
monitor.worked(1);
/*
* Wait for the job to finish
*/
while (!monitor.isCanceled() && control.query() != ITargetStatus.RESUMED) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
}
}
monitor.done();
}
|
diff --git a/src/ru/study/core/GeneticAlgCore.java b/src/ru/study/core/GeneticAlgCore.java
index 4122d48..1b10c46 100644
--- a/src/ru/study/core/GeneticAlgCore.java
+++ b/src/ru/study/core/GeneticAlgCore.java
@@ -1,104 +1,108 @@
package ru.study.core;
import ru.study.utils.MathExpressionParser;
import ru.study.utils.Pair;
import java.util.*;
/**
* Created with IntelliJ IDEA.
* User: markdev
* Date: 10/7/13
* Time: 9:53 PM
* To change this template use File | Settings | File Templates.
*/
public class GeneticAlgCore {
private MathExpressionParser MEP;
public GeneticAlgCore(MathExpressionParser MEP) {
this.MEP = MEP;
}
public ArrayList<Person> initialPersons(int from, int to) {
int bitSize = Integer.toBinaryString(to).length() - 1;
- int generationSize = 4; //размер одного поколения
+ int generationSize = (int) Math.sqrt(to - from); //размер одного поколения
+ if (generationSize < 2) {
+ generationSize = 2;
+ }
+ System.out.println("generationSize = "+generationSize);
//Берем рандомные generationSize особи
ArrayList<Person> randomp = new ArrayList<Person>();
int rouletteSize = 0; //подсчитываем общий размер рулетки
for (int i = 0; i < generationSize; i++) {
Person p = new Person(randomNum(from, to), bitSize, MEP);
rouletteSize = rouletteSize + p.getAdaptation();
randomp.add(p);
}
//формируем список интервалов
double[][] intervals = new double[generationSize][2];
double prevInterval = 0;
for (int i = 0; i < generationSize; i++) {
intervals[i][0] = prevInterval;
double newInterval = prevInterval + (double) (randomp.get(i).getAdaptation()) / (double) rouletteSize;
intervals[i][1] = newInterval;
prevInterval = newInterval;
}
//Отбираем особей которые попадут в начальный пул - метод рулетки
ArrayList<Person> initialPool = new ArrayList<Person>();
for (int i = 0; i < generationSize; i++) {
initialPool.add(randomp.get(intervalId(intervals)));
}
return initialPool;
}
private int randomNum(int from, int to) {
Random r = new Random();
return r.nextInt(to) + from;
}
public int intervalId(double[][] intervals) {
double r = Math.random();
for (int i = 0; i < intervals.length; i++) {
double from = intervals[i][0];
double to = intervals[i][1];
if (r >= from && r <= to) {
return i;
}
}
return intervals.length - 1;
}
//HashSet не допускает дублирования, так что если его длина = 1 то
//значит что все элементы списка - одинаковые - а значит можно заканчивать
public boolean isBestPersonFound(ArrayList<Person> personsPool) {
return new HashSet<Person>(personsPool).size() == 1;
}
//Попарно скрещивает
public ArrayList<Person> crossing(ArrayList<Person> personsPool) {
ArrayList<Person> crossed = new ArrayList<Person>();
for (int i = 1; i < personsPool.size(); i++) {
Person p1 = personsPool.get(i - 1);
Person p2 = personsPool.get(i);
Pair<Person, Person> crossing = Person.crossing(new Pair<Person, Person>(p1, p2));
crossed.add(crossing.getFirst());
crossed.add(crossing.getSecond());
}
personsPool.addAll(crossed);
return personsPool;
}
public ArrayList<Person> getBestPersons(ArrayList<Person> personsPool) {
//Сортируем и берем первую половину
Collections.sort(personsPool, new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
if (o1.getAdaptation() < o2.getAdaptation()) {
return 1;
} else if (o1.getAdaptation() == o2.getAdaptation()) {
return 0;
} else if (o1.getAdaptation() > o2.getAdaptation()) {
return -1;
}
return 0;
}
});
return new ArrayList<Person>(personsPool.subList(0, personsPool.size() / 2));
}
}
| true | true | public ArrayList<Person> initialPersons(int from, int to) {
int bitSize = Integer.toBinaryString(to).length() - 1;
int generationSize = 4; //размер одного поколения
//Берем рандомные generationSize особи
ArrayList<Person> randomp = new ArrayList<Person>();
int rouletteSize = 0; //подсчитываем общий размер рулетки
for (int i = 0; i < generationSize; i++) {
Person p = new Person(randomNum(from, to), bitSize, MEP);
rouletteSize = rouletteSize + p.getAdaptation();
randomp.add(p);
}
//формируем список интервалов
double[][] intervals = new double[generationSize][2];
double prevInterval = 0;
for (int i = 0; i < generationSize; i++) {
intervals[i][0] = prevInterval;
double newInterval = prevInterval + (double) (randomp.get(i).getAdaptation()) / (double) rouletteSize;
intervals[i][1] = newInterval;
prevInterval = newInterval;
}
//Отбираем особей которые попадут в начальный пул - метод рулетки
ArrayList<Person> initialPool = new ArrayList<Person>();
for (int i = 0; i < generationSize; i++) {
initialPool.add(randomp.get(intervalId(intervals)));
}
return initialPool;
}
| public ArrayList<Person> initialPersons(int from, int to) {
int bitSize = Integer.toBinaryString(to).length() - 1;
int generationSize = (int) Math.sqrt(to - from); //размер одного поколения
if (generationSize < 2) {
generationSize = 2;
}
System.out.println("generationSize = "+generationSize);
//Берем рандомные generationSize особи
ArrayList<Person> randomp = new ArrayList<Person>();
int rouletteSize = 0; //подсчитываем общий размер рулетки
for (int i = 0; i < generationSize; i++) {
Person p = new Person(randomNum(from, to), bitSize, MEP);
rouletteSize = rouletteSize + p.getAdaptation();
randomp.add(p);
}
//формируем список интервалов
double[][] intervals = new double[generationSize][2];
double prevInterval = 0;
for (int i = 0; i < generationSize; i++) {
intervals[i][0] = prevInterval;
double newInterval = prevInterval + (double) (randomp.get(i).getAdaptation()) / (double) rouletteSize;
intervals[i][1] = newInterval;
prevInterval = newInterval;
}
//Отбираем особей которые попадут в начальный пул - метод рулетки
ArrayList<Person> initialPool = new ArrayList<Person>();
for (int i = 0; i < generationSize; i++) {
initialPool.add(randomp.get(intervalId(intervals)));
}
return initialPool;
}
|
diff --git a/src/com/android/phone/Use2GOnlyCheckBoxPreference.java b/src/com/android/phone/Use2GOnlyCheckBoxPreference.java
index 1fa83a76..f3a3a956 100644
--- a/src/com/android/phone/Use2GOnlyCheckBoxPreference.java
+++ b/src/com/android/phone/Use2GOnlyCheckBoxPreference.java
@@ -1,112 +1,116 @@
/*
* 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.phone;
import android.content.Context;
import android.os.AsyncResult;
import android.os.Handler;
import android.os.Message;
import android.preference.CheckBoxPreference;
import android.util.AttributeSet;
import android.util.Log;
import com.android.internal.telephony.Phone;
public class Use2GOnlyCheckBoxPreference extends CheckBoxPreference {
private static final String LOG_TAG = "Use2GOnlyCheckBoxPreference";
private static final boolean DBG = true;
private Phone mPhone;
private MyHandler mHandler;
public Use2GOnlyCheckBoxPreference(Context context) {
this(context, null);
}
public Use2GOnlyCheckBoxPreference(Context context, AttributeSet attrs) {
this(context, attrs,com.android.internal.R.attr.checkBoxPreferenceStyle);
}
public Use2GOnlyCheckBoxPreference(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mPhone = PhoneApp.getPhone();
mHandler = new MyHandler();
mPhone.getPreferredNetworkType(
mHandler.obtainMessage(MyHandler.MESSAGE_GET_PREFERRED_NETWORK_TYPE));
}
@Override
protected void onClick() {
super.onClick();
int networkType = isChecked() ? Phone.NT_MODE_GSM_ONLY : Phone.NT_MODE_WCDMA_PREF;
Log.i(LOG_TAG, "set preferred network type="+networkType);
android.provider.Settings.Secure.putInt(mPhone.getContext().getContentResolver(),
android.provider.Settings.Secure.PREFERRED_NETWORK_MODE, networkType);
mPhone.setPreferredNetworkType(networkType, mHandler
.obtainMessage(MyHandler.MESSAGE_SET_PREFERRED_NETWORK_TYPE));
}
private class MyHandler extends Handler {
private static final int MESSAGE_GET_PREFERRED_NETWORK_TYPE = 0;
private static final int MESSAGE_SET_PREFERRED_NETWORK_TYPE = 1;
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_GET_PREFERRED_NETWORK_TYPE:
handleGetPreferredNetworkTypeResponse(msg);
break;
case MESSAGE_SET_PREFERRED_NETWORK_TYPE:
handleSetPreferredNetworkTypeResponse(msg);
break;
}
}
private void handleGetPreferredNetworkTypeResponse(Message msg) {
AsyncResult ar = (AsyncResult) msg.obj;
if (ar.exception == null) {
int type = ((int[])ar.result)[0];
+ if (type != Phone.NT_MODE_GSM_ONLY) {
+ // Allow only NT_MODE_GSM_ONLY or NT_MODE_WCDMA_PREF
+ type = Phone.NT_MODE_WCDMA_PREF;
+ }
Log.i(LOG_TAG, "get preferred network type="+type);
setChecked(type == Phone.NT_MODE_GSM_ONLY);
android.provider.Settings.Secure.putInt(mPhone.getContext().getContentResolver(),
android.provider.Settings.Secure.PREFERRED_NETWORK_MODE, type);
} else {
// Weird state, disable the setting
Log.i(LOG_TAG, "get preferred network type, exception="+ar.exception);
setEnabled(false);
}
}
private void handleSetPreferredNetworkTypeResponse(Message msg) {
AsyncResult ar = (AsyncResult) msg.obj;
if (ar.exception != null) {
// Yikes, error, disable the setting
setEnabled(false);
// Set UI to current state
Log.i(LOG_TAG, "set preferred network type, exception=" + ar.exception);
mPhone.getPreferredNetworkType(obtainMessage(MESSAGE_GET_PREFERRED_NETWORK_TYPE));
} else {
Log.i(LOG_TAG, "set preferred network type done");
}
}
}
}
| true | true | private void handleGetPreferredNetworkTypeResponse(Message msg) {
AsyncResult ar = (AsyncResult) msg.obj;
if (ar.exception == null) {
int type = ((int[])ar.result)[0];
Log.i(LOG_TAG, "get preferred network type="+type);
setChecked(type == Phone.NT_MODE_GSM_ONLY);
android.provider.Settings.Secure.putInt(mPhone.getContext().getContentResolver(),
android.provider.Settings.Secure.PREFERRED_NETWORK_MODE, type);
} else {
// Weird state, disable the setting
Log.i(LOG_TAG, "get preferred network type, exception="+ar.exception);
setEnabled(false);
}
}
| private void handleGetPreferredNetworkTypeResponse(Message msg) {
AsyncResult ar = (AsyncResult) msg.obj;
if (ar.exception == null) {
int type = ((int[])ar.result)[0];
if (type != Phone.NT_MODE_GSM_ONLY) {
// Allow only NT_MODE_GSM_ONLY or NT_MODE_WCDMA_PREF
type = Phone.NT_MODE_WCDMA_PREF;
}
Log.i(LOG_TAG, "get preferred network type="+type);
setChecked(type == Phone.NT_MODE_GSM_ONLY);
android.provider.Settings.Secure.putInt(mPhone.getContext().getContentResolver(),
android.provider.Settings.Secure.PREFERRED_NETWORK_MODE, type);
} else {
// Weird state, disable the setting
Log.i(LOG_TAG, "get preferred network type, exception="+ar.exception);
setEnabled(false);
}
}
|
diff --git a/boundbox-library/src/test/java/org/boundbox/writer/BoundBoxWriterTest.java b/boundbox-library/src/test/java/org/boundbox/writer/BoundBoxWriterTest.java
index b38ed4b..278fa06 100644
--- a/boundbox-library/src/test/java/org/boundbox/writer/BoundBoxWriterTest.java
+++ b/boundbox-library/src/test/java/org/boundbox/writer/BoundBoxWriterTest.java
@@ -1,1137 +1,1157 @@
package org.boundbox.writer;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import javax.annotation.processing.Processor;
import javax.tools.JavaCompiler;
import javax.tools.JavaCompiler.CompilationTask;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import lombok.Getter;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.boundbox.FakeFieldInfo;
import org.boundbox.FakeInnerClassInfo;
import org.boundbox.FakeMethodInfo;
import org.boundbox.model.ClassInfo;
import org.boundbox.model.FieldInfo;
import org.boundbox.model.InnerClassInfo;
import org.boundbox.model.MethodInfo;
import org.easymock.Capture;
import org.easymock.EasyMock;
import org.easymock.IAnswer;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
//https://today.java.net/pub/a/today/2008/04/10/source-code-analysis-using-java-6-compiler-apis.html#invoking-the-compiler-from-code-the-java-compiler-api
//http://stackoverflow.com/a/7989365/693752
//TODO compile in memory ? Not sure, it's cool to debug
public class BoundBoxWriterTest {
@Getter
private BoundboxWriter writer;
private File sandBoxDir;
private FileWriter sandboxWriter;
private DocumentationGenerator mockDocumentationGenerator;
@Before
public void setup() throws IOException {
writer = new BoundboxWriter();
sandBoxDir = new File("target/sandbox");
if (sandBoxDir.exists()) {
FileUtils.deleteDirectory(sandBoxDir);
}
sandBoxDir.mkdirs();
mockDocumentationGenerator = EasyMock.createMock(DocumentationGenerator.class);
}
@After
public void tearDown() throws IOException {
if (sandBoxDir.exists()) {
//FileUtils.deleteDirectory(sandBoxDir);
}
closeSandboxWriter();
}
private void closeSandboxWriter() throws IOException {
if (sandboxWriter != null) {
sandboxWriter.close();
sandboxWriter = null;
}
}
// ----------------------------------
// JAVADOC
// ----------------------------------
//TODO this test tests the documentation generator, put these in its test class
//TODO replace by a mock of documentation generator here
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void testProcess_class_without_javadoc() throws Exception {
// given
String classUnderTestName = "TestClassWithNothing";
ClassInfo classInfo = new ClassInfo(classUnderTestName);
classInfo.setListFieldInfos(Collections.<FieldInfo>emptyList());
classInfo.setListConstructorInfos(Collections.<MethodInfo>emptyList());
classInfo.setListMethodInfos(Collections.<MethodInfo>emptyList());
classInfo.setListImports(new HashSet<String>());
final Capture<ClassInfo> captured = new Capture<ClassInfo>();
EasyMock.expect(mockDocumentationGenerator.generateJavadocForBoundBoxClass(EasyMock.capture(captured))).andReturn(StringUtils.EMPTY);
EasyMock.expectLastCall().andAnswer(new IAnswer() {
public Object answer() {
//used to debug the call
System.out.println(captured.getValue());
assertTrue(false);
return null;
}
});
final Capture<ClassInfo> captured2 = new Capture<ClassInfo>();
EasyMock.expect(mockDocumentationGenerator.generateJavadocForBoundBoxConstructor(EasyMock.capture(captured2))).andReturn(StringUtils.EMPTY);
EasyMock.expectLastCall().andAnswer(new IAnswer() {
public Object answer() {
//used to debug the call
System.out.println(captured2.getValue());
assertTrue(false);
return null;
}
});
EasyMock.replay(mockDocumentationGenerator);
writer.setWritingJavadoc(false);
Writer out = createWriterInSandbox(writer.getNamingGenerator().createBoundBoxName(classInfo));
// when
writer.setJavadocGenerator(mockDocumentationGenerator);
writer.writeBoundBox(classInfo, out);
// then
//tested by the capture.
}
@Test
public void testProcess_class_with_javadoc() throws Exception {
// given
String classUnderTestName = "TestClassWithNothing";
ClassInfo classInfo = new ClassInfo(classUnderTestName);
classInfo.setListFieldInfos(Collections.<FieldInfo>emptyList());
classInfo.setListConstructorInfos(Collections.<MethodInfo>emptyList());
classInfo.setListMethodInfos(Collections.<MethodInfo>emptyList());
classInfo.setListImports(new HashSet<String>());
EasyMock.expect(mockDocumentationGenerator.generateJavadocForBoundBoxClass(EasyMock.anyObject(ClassInfo.class))).andReturn(StringUtils.EMPTY);
EasyMock.expectLastCall().atLeastOnce();
EasyMock.expect(mockDocumentationGenerator.generateJavadocForBoundBoxConstructor(EasyMock.anyObject(ClassInfo.class))).andReturn(StringUtils.EMPTY);
EasyMock.expectLastCall().atLeastOnce();
EasyMock.replay(mockDocumentationGenerator);
Writer out = createWriterInSandbox(writer.getNamingGenerator().createBoundBoxName(classInfo));
writer.setWritingJavadoc(true);
// when
writer.setJavadocGenerator(mockDocumentationGenerator);
writer.writeBoundBox(classInfo, out);
// then
EasyMock.verify(mockDocumentationGenerator);
}
// ----------------------------------
// FIELDS
// ----------------------------------
@Test
public void testProcess_class_with_single_field() throws Exception {
// given
String classUnderTestName = "TestClassWithSingleField";
List<String> neededClasses = new ArrayList<String>();
ClassInfo classInfo = new ClassInfo(classUnderTestName);
FakeFieldInfo fakeFieldInfo = new FakeFieldInfo("foo", "java.lang.String");
List<FieldInfo> listFieldInfos = new ArrayList<FieldInfo>();
listFieldInfos.add(fakeFieldInfo);
classInfo.setListFieldInfos(listFieldInfos);
classInfo.setListImports(new HashSet<String>());
Writer out = createWriterInSandbox(writer.getNamingGenerator().createBoundBoxName(classInfo));
// when
writer.writeBoundBox(classInfo, out);
closeSandboxWriter();
// then
CompilationTask task = createCompileTask(writer.getNamingGenerator().createBoundBoxName(classInfo), neededClasses);
boolean result = task.call();
assertTrue(result);
Class<?> clazz = loadBoundBoxClass(writer.getNamingGenerator().createBoundBoxName(classInfo));;
Method method = clazz.getDeclaredMethod("boundBox_getFoo");
assertNotNull(method);
Method method2 = clazz.getDeclaredMethod("boundBox_setFoo", String.class);
assertNotNull(method2);
}
@Test
public void testProcess_class_with_many_fields() throws Exception {
// given
String classUnderTestName = "TestClassWithManyFields";
List<String> neededClasses = new ArrayList<String>();
ClassInfo classInfo = new ClassInfo(classUnderTestName);
FakeFieldInfo fakeFieldInfo = new FakeFieldInfo("foo", "java.lang.String");
FakeFieldInfo fakeFieldInfo2 = new FakeFieldInfo("a", "int");
FakeFieldInfo fakeFieldInfo3 = new FakeFieldInfo("array1", "double[]");
FakeFieldInfo fakeFieldInfo4 = new FakeFieldInfo("array2", "float[][]");
List<FieldInfo> listFieldInfos = new ArrayList<FieldInfo>();
listFieldInfos.add(fakeFieldInfo);
listFieldInfos.add(fakeFieldInfo2);
listFieldInfos.add(fakeFieldInfo3);
listFieldInfos.add(fakeFieldInfo4);
classInfo.setListFieldInfos(listFieldInfos);
classInfo.setListImports(new HashSet<String>());
Writer out = createWriterInSandbox(writer.getNamingGenerator().createBoundBoxName(classInfo));
// when
writer.writeBoundBox(classInfo, out);
closeSandboxWriter();
// then
CompilationTask task = createCompileTask(writer.getNamingGenerator().createBoundBoxName(classInfo), neededClasses);
boolean result = task.call();
assertTrue(result);
Class<?> clazz = loadBoundBoxClass(writer.getNamingGenerator().createBoundBoxName(classInfo));;
Method method = clazz.getDeclaredMethod("boundBox_getFoo");
assertNotNull(method);
Method method2 = clazz.getDeclaredMethod("boundBox_setFoo", String.class);
assertNotNull(method2);
}
// ----------------------------------
// STATIC FIELDS
// ----------------------------------
@Test
public void testProcess_class_with_static_field() throws Exception {
// given
String classUnderTestName = "TestClassWithStaticField";
List<String> neededClasses = new ArrayList<String>();
ClassInfo classInfo = new ClassInfo(classUnderTestName);
FakeFieldInfo fakeFieldInfo = new FakeFieldInfo("foo", "java.lang.String");
fakeFieldInfo.setStaticField(true);
FakeFieldInfo fakeFieldInfo2 = new FakeFieldInfo("a", "int");
fakeFieldInfo2.setStaticField(true);
List<FieldInfo> listFieldInfos = new ArrayList<FieldInfo>();
listFieldInfos.add(fakeFieldInfo);
listFieldInfos.add(fakeFieldInfo2);
classInfo.setListFieldInfos(listFieldInfos);
classInfo.setListImports(new HashSet<String>());
Writer out = createWriterInSandbox(writer.getNamingGenerator().createBoundBoxName(classInfo));
// when
writer.writeBoundBox(classInfo, out);
closeSandboxWriter();
// then
CompilationTask task = createCompileTask(writer.getNamingGenerator().createBoundBoxName(classInfo), neededClasses);
boolean result = task.call();
assertTrue(result);
Class<?> clazz = loadBoundBoxClass(writer.getNamingGenerator().createBoundBoxName(classInfo));;
Method method = clazz.getDeclaredMethod("boundBox_getFoo");
assertNotNull(method);
assertTrue((method.getModifiers() & Modifier.STATIC) != 0);
Method method2 = clazz.getDeclaredMethod("boundBox_setFoo", String.class);
assertNotNull(method2);
assertTrue((method2.getModifiers() & Modifier.STATIC) != 0);
Method method3 = clazz.getDeclaredMethod("boundBox_getA");
assertNotNull(method3);
assertTrue((method3.getModifiers() & Modifier.STATIC) != 0);
Method method4 = clazz.getDeclaredMethod("boundBox_setA", int.class);
assertNotNull(method4);
assertTrue((method4.getModifiers() & Modifier.STATIC) != 0);
}
// ----------------------------------
// STATIC INITIALIZER
// ----------------------------------
//those blocks are not accessible via reflection
// ----------------------------------
// CONSTRUCTORS
// ----------------------------------
@Test
public void testProcess_class_with_single_constructor() throws Exception {
// given
String classUnderTestName = "TestClassWithSingleConstructor";
List<String> neededClasses = new ArrayList<String>();
ClassInfo classInfo = new ClassInfo(classUnderTestName);
FakeMethodInfo fakeMethodInfo = new FakeMethodInfo("<init>", "void", new ArrayList<FieldInfo>(), null);
List<MethodInfo> listConstructorInfos = new ArrayList<MethodInfo>();
listConstructorInfos.add(fakeMethodInfo);
classInfo.setListConstructorInfos(listConstructorInfos);
classInfo.setListImports(new HashSet<String>());
Writer out = createWriterInSandbox(writer.getNamingGenerator().createBoundBoxName(classInfo));
// when
writer.writeBoundBox(classInfo, out);
closeSandboxWriter();
// then
CompilationTask task = createCompileTask(writer.getNamingGenerator().createBoundBoxName(classInfo), neededClasses);
boolean result = task.call();
assertTrue(result);
Class<?> clazz = loadBoundBoxClass(writer.getNamingGenerator().createBoundBoxName(classInfo));;
Method method = clazz.getDeclaredMethod("boundBox_new");
assertNotNull(method);
assertTrue((method.getModifiers() & Modifier.STATIC) != 0);
}
@Test
public void testProcess_class_with_many_constructors() throws Exception {
// given
String classUnderTestName = "TestClassWithManyConstructors";
List<String> neededClasses = new ArrayList<String>();
ClassInfo classInfo = new ClassInfo(classUnderTestName);
List<MethodInfo> listConstructorInfos = new ArrayList<MethodInfo>();
listConstructorInfos.add(new FakeMethodInfo("<init>", "void", new ArrayList<FieldInfo>(), null));
FakeFieldInfo fieldInfo = new FakeFieldInfo("a", "int");
listConstructorInfos.add(new FakeMethodInfo("<init>", "void", Arrays.<FieldInfo>asList(fieldInfo), null));
FakeFieldInfo fieldInfo2 = new FakeFieldInfo("a", Object.class.getName());
listConstructorInfos.add(new FakeMethodInfo("<init>", "void", Arrays.<FieldInfo>asList(fieldInfo2), null));
FakeFieldInfo fieldInfo3 = new FakeFieldInfo("b", Object.class.getName());
listConstructorInfos.add(new FakeMethodInfo("<init>", "void", Arrays.<FieldInfo>asList(fieldInfo, fieldInfo3), null));
FakeFieldInfo fieldInfo4 = new FakeFieldInfo("c", Object.class.getName());
listConstructorInfos.add(new FakeMethodInfo("<init>", "void",
Arrays.<FieldInfo>asList(fieldInfo, fieldInfo3, fieldInfo4), Arrays.asList("java.io.IOException",
"java.lang.RuntimeException")));
classInfo.setListConstructorInfos(listConstructorInfos);
classInfo.setListImports(new HashSet<String>());
Writer out = createWriterInSandbox(writer.getNamingGenerator().createBoundBoxName(classInfo));
// when
writer.writeBoundBox(classInfo, out);
closeSandboxWriter();
// then
CompilationTask task = createCompileTask(writer.getNamingGenerator().createBoundBoxName(classInfo), neededClasses);
boolean result = task.call();
assertTrue(result);
Class<?> clazz = loadBoundBoxClass(writer.getNamingGenerator().createBoundBoxName(classInfo));;
Method declaredMethod1 = clazz.getDeclaredMethod("boundBox_new");
assertNotNull(declaredMethod1);
assertTrue((declaredMethod1.getModifiers() & Modifier.STATIC) != 0);
Method declaredMethod2 = clazz.getDeclaredMethod("boundBox_new", int.class);
assertNotNull(declaredMethod2);
assertTrue((declaredMethod2.getModifiers() & Modifier.STATIC) != 0);
Method declaredMethod3 = clazz.getDeclaredMethod("boundBox_new", Object.class);
assertNotNull(declaredMethod3);
assertTrue((declaredMethod3.getModifiers() & Modifier.STATIC) != 0);
Method declaredMethod4 = clazz.getDeclaredMethod("boundBox_new", int.class, Object.class);
assertNotNull(declaredMethod4);
assertTrue((declaredMethod4.getModifiers() & Modifier.STATIC) != 0);
Method declaredMethod5 = clazz.getDeclaredMethod("boundBox_new", int.class, Object.class, Object.class);
assertNotNull(declaredMethod5);
assertTrue((declaredMethod5.getModifiers() & Modifier.STATIC) != 0);
boolean containsIOException = false;
boolean containsRuntimeException = false;
for (Class<?> exceptionClass : declaredMethod5.getExceptionTypes()) {
if (exceptionClass.equals(IOException.class)) {
containsIOException = true;
}
if (exceptionClass.equals(RuntimeException.class)) {
containsRuntimeException = true;
}
}
assertTrue(containsIOException);
assertTrue(containsRuntimeException);
}
// ----------------------------------
// METHODS
// ----------------------------------
@Test
public void testProcess_class_with_single_method() throws Exception {
// given
String classUnderTestName = "TestClassWithSingleMethod";
List<String> neededClasses = new ArrayList<String>();
ClassInfo classInfo = new ClassInfo(classUnderTestName);
FakeMethodInfo fakeMethodInfo = new FakeMethodInfo("foo", "void", new ArrayList<FieldInfo>(), null);
List<MethodInfo> listMethodInfos = new ArrayList<MethodInfo>();
listMethodInfos.add(fakeMethodInfo);
classInfo.setListMethodInfos(listMethodInfos);
classInfo.setListImports(new HashSet<String>());
Writer out = createWriterInSandbox(writer.getNamingGenerator().createBoundBoxName(classInfo));
// when
writer.writeBoundBox(classInfo, out);
closeSandboxWriter();
// then
CompilationTask task = createCompileTask(writer.getNamingGenerator().createBoundBoxName(classInfo), neededClasses);
boolean result = task.call();
assertTrue(result);
Class<?> clazz = loadBoundBoxClass(writer.getNamingGenerator().createBoundBoxName(classInfo));;
Method method = clazz.getDeclaredMethod("foo");
assertNotNull(method);
}
@Test
public void testProcess_class_with_many_methods() throws Exception {
// given
String classUnderTestName = "TestClassWithManyMethods";
List<String> neededClasses = new ArrayList<String>();
ClassInfo classInfo = new ClassInfo(classUnderTestName);
List<MethodInfo> listConstructorInfos = new ArrayList<MethodInfo>();
listConstructorInfos.add(new FakeMethodInfo("simple", "void", new ArrayList<FieldInfo>(), null));
FakeFieldInfo fieldInfo = new FakeFieldInfo("a", "int");
listConstructorInfos.add(new FakeMethodInfo("withPrimitiveArgument", "void", Arrays.<FieldInfo>asList(fieldInfo), null));
FakeFieldInfo fieldInfo2 = new FakeFieldInfo("a", Object.class.getName());
listConstructorInfos.add(new FakeMethodInfo("withObjectArgument", "void", Arrays.<FieldInfo>asList(fieldInfo2), null));
FakeFieldInfo fieldInfo3 = new FakeFieldInfo("b", Object.class.getName());
listConstructorInfos.add(new FakeMethodInfo("withManyArguments", "void", Arrays.<FieldInfo>asList(fieldInfo, fieldInfo3),
null));
+ listConstructorInfos.add(new FakeMethodInfo("withPrimitiveCharReturnType", "char", Arrays.<FieldInfo>asList(), null));
listConstructorInfos.add(new FakeMethodInfo("withPrimitiveIntReturnType", "int", Arrays.<FieldInfo>asList(), null));
+ listConstructorInfos.add(new FakeMethodInfo("withPrimitiveByteReturnType", "byte", Arrays.<FieldInfo>asList(), null));
+ listConstructorInfos.add(new FakeMethodInfo("withPrimitiveShortReturnType", "short", Arrays.<FieldInfo>asList(), null));
+ listConstructorInfos.add(new FakeMethodInfo("withPrimitiveLongReturnType", "long", Arrays.<FieldInfo>asList(), null));
listConstructorInfos.add(new FakeMethodInfo("withPrimitiveDoubleReturnType", "double", Arrays.<FieldInfo>asList(), null));
+ listConstructorInfos.add(new FakeMethodInfo("withPrimitiveFloatReturnType", "float", Arrays.<FieldInfo>asList(), null));
listConstructorInfos
.add(new FakeMethodInfo("withPrimitiveBooleanReturnType", "boolean", Arrays.<FieldInfo>asList(), null));
listConstructorInfos.add(new FakeMethodInfo("withSingleThrownType", "void", Arrays.<FieldInfo>asList(), Arrays
.asList("java.io.IOException")));
listConstructorInfos.add(new FakeMethodInfo("withManyThrownType", "void", Arrays.<FieldInfo>asList(), Arrays.asList(
"java.io.IOException", "java.lang.RuntimeException")));
classInfo.setListConstructorInfos(listConstructorInfos);
classInfo.setListImports(new HashSet<String>());
Writer out = createWriterInSandbox(writer.getNamingGenerator().createBoundBoxName(classInfo));
// when
writer.writeBoundBox(classInfo, out);
closeSandboxWriter();
// then
CompilationTask task = createCompileTask(writer.getNamingGenerator().createBoundBoxName(classInfo), neededClasses);
boolean result = task.call();
assertTrue(result);
Class<?> clazz = loadBoundBoxClass(writer.getNamingGenerator().createBoundBoxName(classInfo));;
assertNotNull(clazz.getDeclaredMethod("simple"));
assertNotNull(clazz.getDeclaredMethod("withPrimitiveArgument", int.class));
assertNotNull(clazz.getDeclaredMethod("withObjectArgument", Object.class));
assertNotNull(clazz.getDeclaredMethod("withManyArguments", int.class, Object.class));
- Method declaredMethod = clazz.getDeclaredMethod("withPrimitiveIntReturnType");
- assertNotNull(declaredMethod);
- assertTrue(int.class.equals(declaredMethod.getReturnType()));
- Method declaredMethod2 = clazz.getDeclaredMethod("withPrimitiveDoubleReturnType");
- assertNotNull(declaredMethod2);
- assertTrue(double.class.equals(declaredMethod2.getReturnType()));
+ Method declaredMethodChar = clazz.getDeclaredMethod("withPrimitiveCharReturnType");
+ assertNotNull(declaredMethodChar);
+ assertTrue(char.class.equals(declaredMethodChar.getReturnType()));
+ Method declaredMethodInt = clazz.getDeclaredMethod("withPrimitiveIntReturnType");
+ assertNotNull(declaredMethodInt);
+ assertTrue(int.class.equals(declaredMethodInt.getReturnType()));
+ Method declaredMethodLong = clazz.getDeclaredMethod("withPrimitiveLongReturnType");
+ assertNotNull(declaredMethodLong);
+ assertTrue(long.class.equals(declaredMethodLong.getReturnType()));
+ Method declaredMethodByte = clazz.getDeclaredMethod("withPrimitiveByteReturnType");
+ assertNotNull(declaredMethodByte);
+ assertTrue(byte.class.equals(declaredMethodByte.getReturnType()));
+ Method declaredMethodShort = clazz.getDeclaredMethod("withPrimitiveShortReturnType");
+ assertNotNull(declaredMethodShort);
+ assertTrue(short.class.equals(declaredMethodShort.getReturnType()));
+ Method declaredMethodDouble = clazz.getDeclaredMethod("withPrimitiveDoubleReturnType");
+ assertNotNull(declaredMethodDouble);
+ assertTrue(double.class.equals(declaredMethodDouble.getReturnType()));
+ Method declaredMethodFloat = clazz.getDeclaredMethod("withPrimitiveFloatReturnType");
+ assertNotNull(declaredMethodFloat);
+ assertTrue(float.class.equals(declaredMethodFloat.getReturnType()));
Method declaredMethod3 = clazz.getDeclaredMethod("withPrimitiveBooleanReturnType");
assertNotNull(declaredMethod3);
assertTrue(boolean.class.equals(declaredMethod3.getReturnType()));
Method declaredMethod4 = clazz.getDeclaredMethod("withSingleThrownType");
assertNotNull(declaredMethod4);
boolean containsIOException = false;
for (Class<?> exceptionClass : declaredMethod4.getExceptionTypes()) {
if (exceptionClass.equals(IOException.class)) {
containsIOException = true;
}
}
assertTrue(containsIOException);
Method declaredMethod5 = clazz.getDeclaredMethod("withManyThrownType");
assertNotNull(declaredMethod5);
containsIOException = false;
boolean containsRuntimeException = false;
for (Class<?> exceptionClass : declaredMethod5.getExceptionTypes()) {
if (exceptionClass.equals(IOException.class)) {
containsIOException = true;
}
if (exceptionClass.equals(RuntimeException.class)) {
containsRuntimeException = true;
}
}
assertTrue(containsIOException);
assertTrue(containsRuntimeException);
}
// ----------------------------------
// STATIC METHODS
// ----------------------------------
@Test
public void testProcess_class_with_static_method() throws Exception {
// given
String classUnderTestName = "TestClassWithStaticMethod";
List<String> neededClasses = new ArrayList<String>();
ClassInfo classInfo = new ClassInfo(classUnderTestName);
FakeMethodInfo fakeMethodInfo = new FakeMethodInfo("foo", "void", new ArrayList<FieldInfo>(), null);
fakeMethodInfo.setStaticMethod(true);
List<MethodInfo> listMethodInfos = new ArrayList<MethodInfo>();
listMethodInfos.add(fakeMethodInfo);
classInfo.setListMethodInfos(listMethodInfos);
classInfo.setListImports(new HashSet<String>());
Writer out = createWriterInSandbox(writer.getNamingGenerator().createBoundBoxName(classInfo));
// when
writer.writeBoundBox(classInfo, out);
closeSandboxWriter();
// then
CompilationTask task = createCompileTask(writer.getNamingGenerator().createBoundBoxName(classInfo), neededClasses);
boolean result = task.call();
assertTrue(result);
Class<?> clazz = loadBoundBoxClass(writer.getNamingGenerator().createBoundBoxName(classInfo));;
Method method = clazz.getDeclaredMethod("foo");
assertNotNull(method);
assertTrue((method.getModifiers() & Modifier.STATIC) != 0);
}
// ----------------------------------
// INHERITANCE OF FIELDS
// ----------------------------------
@Test
public void testProcess_class_with_inherited_field() throws Exception {
// given
String classUnderTestName = "TestClassWithInheritedField";
List<String> neededClasses = new ArrayList<String>();
neededClasses.add("TestClassWithSingleField");
ClassInfo classInfo = new ClassInfo(classUnderTestName);
FakeFieldInfo fakeFieldInfo = new FakeFieldInfo("foo", "java.lang.String");
fakeFieldInfo.setInheritanceLevel(1);
List<FieldInfo> listFieldInfos = new ArrayList<FieldInfo>();
listFieldInfos.add(fakeFieldInfo);
classInfo.setListFieldInfos(listFieldInfos);
classInfo.setListSuperClassNames(Arrays.asList("TestClassWithInheritedField", "TestClassWithSingleField"));
classInfo.setListImports(new HashSet<String>());
Writer out = createWriterInSandbox(writer.getNamingGenerator().createBoundBoxName(classInfo));
// when
writer.writeBoundBox(classInfo, out);
closeSandboxWriter();
// then
CompilationTask task = createCompileTask(writer.getNamingGenerator().createBoundBoxName(classInfo), neededClasses);
boolean result = task.call();
assertTrue(result);
Class<?> clazz = loadBoundBoxClass(writer.getNamingGenerator().createBoundBoxName(classInfo));;
Method method = clazz.getDeclaredMethod("boundBox_super_TestClassWithSingleField_getFoo");
assertNotNull(method);
Method method2 = clazz.getDeclaredMethod("boundBox_super_TestClassWithSingleField_setFoo", String.class);
assertNotNull(method2);
}
@Test
public void testProcess_class_with_inherited_and_hidingfield() throws Exception {
// given
String classUnderTestName = "TestClassWithInheritedAndHidingField";
List<String> neededClasses = new ArrayList<String>();
neededClasses.add("TestClassWithSingleField");
ClassInfo classInfo = new ClassInfo(classUnderTestName);
List<FieldInfo> listFieldInfos = new ArrayList<FieldInfo>();
FakeFieldInfo fakeFieldInfo = new FakeFieldInfo("foo", "java.lang.String");
fakeFieldInfo.setInheritanceLevel(0);
listFieldInfos.add(fakeFieldInfo);
FakeFieldInfo fakeFieldInfo2 = new FakeFieldInfo("foo", "java.lang.String");
fakeFieldInfo2.setInheritanceLevel(1);
listFieldInfos.add(fakeFieldInfo2);
classInfo.setListFieldInfos(listFieldInfos);
classInfo.setListSuperClassNames(Arrays.asList("TestClassWithInheritedField", "TestClassWithSingleField"));
classInfo.setListImports(new HashSet<String>());
Writer out = createWriterInSandbox(writer.getNamingGenerator().createBoundBoxName(classInfo));
// when
writer.writeBoundBox(classInfo, out);
closeSandboxWriter();
// then
CompilationTask task = createCompileTask(writer.getNamingGenerator().createBoundBoxName(classInfo), neededClasses);
boolean result = task.call();
assertTrue(result);
Class<?> clazz = loadBoundBoxClass(writer.getNamingGenerator().createBoundBoxName(classInfo));;
assertNotNull(clazz.getDeclaredMethod("boundBox_getFoo"));
assertNotNull(clazz.getDeclaredMethod("boundBox_setFoo", String.class));
assertNotNull(clazz.getDeclaredMethod("boundBox_super_TestClassWithSingleField_getFoo"));
assertNotNull(clazz.getDeclaredMethod("boundBox_super_TestClassWithSingleField_setFoo", String.class));
}
// ----------------------------------
// INHERITANCE OF METHODS
// ----------------------------------
@Test
public void testProcess_class_with_inherited_method() throws Exception {
// given
String classUnderTestName = "TestClassWithInheritedMethod";
List<String> neededClasses = new ArrayList<String>();
neededClasses.add("TestClassWithSingleMethod");
ClassInfo classInfo = new ClassInfo(classUnderTestName);
FakeMethodInfo fakeMethodInfo = new FakeMethodInfo("foo", "void", new ArrayList<FieldInfo>(), null);
List<MethodInfo> listMethodInfos = new ArrayList<MethodInfo>();
listMethodInfos.add(fakeMethodInfo);
classInfo.setListMethodInfos(listMethodInfos);
classInfo.setListSuperClassNames(Arrays.asList("TestClassWithInheritedMethod", "TestClassWithSingleMethod"));
classInfo.setListImports(new HashSet<String>());
Writer out = createWriterInSandbox(writer.getNamingGenerator().createBoundBoxName(classInfo));
// when
writer.writeBoundBox(classInfo, out);
closeSandboxWriter();
// then
CompilationTask task = createCompileTask(writer.getNamingGenerator().createBoundBoxName(classInfo), neededClasses);
boolean result = task.call();
assertTrue(result);
Class<?> clazz = loadBoundBoxClass(writer.getNamingGenerator().createBoundBoxName(classInfo));;
Method method = clazz.getDeclaredMethod("foo");
assertNotNull(method);
Method method2 = null;
try {
method2 = clazz.getDeclaredMethod("boundbox_TestClassWithSingleMethod_foo");
assertFalse(true);
} catch (Exception ex) {
assertNull(method2);
}
}
@Test
public void testProcess_class_with_overriding_method() throws Exception {
// given
String classUnderTestName = "TestClassWithOverridingMethod";
List<String> neededClasses = new ArrayList<String>();
neededClasses.add("TestClassWithSingleMethod");
ClassInfo classInfo = new ClassInfo(classUnderTestName);
List<MethodInfo> listMethodInfos = new ArrayList<MethodInfo>();
FakeMethodInfo fakeMethodInfo = new FakeMethodInfo("foo", "void", new ArrayList<FieldInfo>(), null);
listMethodInfos.add(fakeMethodInfo);
FakeMethodInfo fakeMethodInfo2 = new FakeMethodInfo("foo", "void", new ArrayList<FieldInfo>(), null);
fakeMethodInfo2.setInheritanceLevel(1);
fakeMethodInfo2.setOverriden(true);
listMethodInfos.add(fakeMethodInfo2);
classInfo.setListMethodInfos(listMethodInfos);
classInfo.setListSuperClassNames(Arrays.asList("TestClassWithInheritedMethod", "TestClassWithSingleMethod"));
classInfo.setListImports(new HashSet<String>());
Writer out = createWriterInSandbox(writer.getNamingGenerator().createBoundBoxName(classInfo));
// when
writer.writeBoundBox(classInfo, out);
closeSandboxWriter();
// then
CompilationTask task = createCompileTask(writer.getNamingGenerator().createBoundBoxName(classInfo), neededClasses);
boolean result = task.call();
assertTrue(result);
Class<?> clazz = loadBoundBoxClass(writer.getNamingGenerator().createBoundBoxName(classInfo));;
Method method = clazz.getDeclaredMethod("foo");
assertNotNull(method);
Method method2 = clazz.getDeclaredMethod("boundBox_super_TestClassWithSingleMethod_foo");
assertNotNull(method2);
}
@Test
public void testProcess_class_with_inherited_overriding_method() throws Exception {
// given
String classUnderTestName = "TestClassWithInheritedOverridingMethod";
List<String> neededClasses = new ArrayList<String>();
neededClasses.add("TestClassWithOverridingMethod");
neededClasses.add("TestClassWithSingleMethod");
ClassInfo classInfo = new ClassInfo(classUnderTestName);
List<MethodInfo> listMethodInfos = new ArrayList<MethodInfo>();
FakeMethodInfo fakeMethodInfo = new FakeMethodInfo("foo", "void", new ArrayList<FieldInfo>(), null);
listMethodInfos.add(fakeMethodInfo);
FakeMethodInfo fakeMethodInfo2 = new FakeMethodInfo("foo", "void", new ArrayList<FieldInfo>(), null);
fakeMethodInfo2.setInheritanceLevel(2);
listMethodInfos.add(fakeMethodInfo2);
classInfo.setListMethodInfos(listMethodInfos);
classInfo.setListSuperClassNames(Arrays.asList("TestClassWithInheritedOverridingMethod", "TestClassWithInheritedMethod",
"TestClassWithSingleMethod"));
classInfo.setListImports(new HashSet<String>());
Writer out = createWriterInSandbox(writer.getNamingGenerator().createBoundBoxName(classInfo));
// when
writer.writeBoundBox(classInfo, out);
closeSandboxWriter();
// then
CompilationTask task = createCompileTask(writer.getNamingGenerator().createBoundBoxName(classInfo), neededClasses);
boolean result = task.call();
assertTrue(result);
Class<?> clazz = loadBoundBoxClass(writer.getNamingGenerator().createBoundBoxName(classInfo));;
Method method = clazz.getDeclaredMethod("foo");
assertNotNull(method);
Method method2 = clazz.getDeclaredMethod("boundBox_super_TestClassWithSingleMethod_foo");
assertNotNull(method2);
}
// ----------------------------------
// GENERICS
// ----------------------------------
// part of TDD for https://github.com/stephanenicolas/boundbox/issues/1
// proposed by Flavien Laurent
@Test
public void testProcess_class_with_generics_parameters_have_raw_types() throws Exception {
// given
String classUnderTestName = "TestClassWithGenerics";
List<String> neededClasses = new ArrayList<String>();
ClassInfo classInfo = new ClassInfo(classUnderTestName);
ArrayList<FieldInfo> listParameters = new ArrayList<FieldInfo>();
FieldInfo fakeParameterInfo = new FakeFieldInfo("strings", "java.util.List");
listParameters.add(fakeParameterInfo );
FakeMethodInfo fakeMethodInfo = new FakeMethodInfo("doIt", "void", listParameters, null);
List<MethodInfo> listMethodInfos = new ArrayList<MethodInfo>();
listMethodInfos.add(fakeMethodInfo);
classInfo.setListMethodInfos(listMethodInfos);
classInfo.setListImports(new HashSet<String>());
Writer out = createWriterInSandbox(writer.getNamingGenerator().createBoundBoxName(classInfo));
// when
writer.writeBoundBox(classInfo, out);
closeSandboxWriter();
// then
CompilationTask task = createCompileTask(writer.getNamingGenerator().createBoundBoxName(classInfo), neededClasses);
boolean result = task.call();
assertTrue(result);
Class<?> clazz = loadBoundBoxClass(writer.getNamingGenerator().createBoundBoxName(classInfo));;
Method method = clazz.getDeclaredMethod("doIt", List.class);
assertNotNull(method);
}
// part of TDD for https://github.com/stephanenicolas/boundbox/issues/1
// proposed by Flavien Laurent
@Test
public void testProcess_class_with_generics_parameters_have_generic_types() throws Exception {
// given
String classUnderTestName = "TestClassWithGenerics";
List<String> neededClasses = new ArrayList<String>();
ClassInfo classInfo = new ClassInfo(classUnderTestName);
ArrayList<FieldInfo> listParameters = new ArrayList<FieldInfo>();
FieldInfo fakeParameterInfo = new FakeFieldInfo("strings", "java.util.List<String>");
listParameters.add(fakeParameterInfo );
FakeMethodInfo fakeMethodInfo = new FakeMethodInfo("doIt", "void", listParameters, null);
List<MethodInfo> listMethodInfos = new ArrayList<MethodInfo>();
listMethodInfos.add(fakeMethodInfo);
classInfo.setListMethodInfos(listMethodInfos);
classInfo.setListImports(new HashSet<String>());
Writer out = createWriterInSandbox(writer.getNamingGenerator().createBoundBoxName(classInfo));
// when
writer.writeBoundBox(classInfo, out);
closeSandboxWriter();
// then
CompilationTask task = createCompileTask(writer.getNamingGenerator().createBoundBoxName(classInfo), neededClasses);
boolean result = task.call();
assertTrue(result);
Class<?> clazz = loadBoundBoxClass(writer.getNamingGenerator().createBoundBoxName(classInfo));;
Method method = clazz.getDeclaredMethod("doIt", List.class);
assertNotNull(method);
}
// ----------------------------------
// INNER CLASSES
// ----------------------------------
@Test
public void testProcess_class_with_static_inner_class() throws Exception {
// given
String classUnderTestName = "TestClassWithStaticInnerClass";
List<String> neededClasses = new ArrayList<String>();
ClassInfo classInfo = new ClassInfo(classUnderTestName);
FakeFieldInfo fakeFieldInfo = new FakeFieldInfo("a", "int");
List<FieldInfo> listFieldInfos = new ArrayList<FieldInfo>();
listFieldInfos.add(fakeFieldInfo);
FakeMethodInfo fakeMethodInfo = new FakeMethodInfo("foo", "void", new ArrayList<FieldInfo>(), null);
List<MethodInfo> listMethodInfos = new ArrayList<MethodInfo>();
listMethodInfos.add(fakeMethodInfo);
FakeInnerClassInfo fakeInnerClassInfo = new FakeInnerClassInfo("InnerClass");
fakeInnerClassInfo.setStaticInnerClass(true);
classInfo.setListFieldInfos(listFieldInfos);
classInfo.setListMethodInfos(listMethodInfos);
classInfo.setListInnerClassInfo(Arrays.<InnerClassInfo>asList(fakeInnerClassInfo));
classInfo.setListImports(new HashSet<String>());
Writer out = createWriterInSandbox(writer.getNamingGenerator().createBoundBoxName(classInfo));
// when
writer.writeBoundBox(classInfo, out);
closeSandboxWriter();
// then
CompilationTask task = createCompileTask(writer.getNamingGenerator().createBoundBoxName(classInfo), neededClasses);
boolean result = task.call();
assertTrue(result);
Class<?> clazz = loadBoundBoxClass(writer.getNamingGenerator().createBoundBoxName(classInfo));;
Method method = clazz.getDeclaredMethod("boundBox_getA");
assertNotNull(method);
Method method2 = clazz.getDeclaredMethod("boundBox_setA", int.class);
assertNotNull(method2);
Method method3 = clazz.getDeclaredMethod("foo");
assertNotNull(method3);
Class<?> class1 = clazz.getDeclaredClasses()[0];
assertNotNull(class1);
assertEquals("BoundBoxOfInnerClass",class1.getSimpleName());
}
// ----------------------------------
// INNER CLASSES
// ----------------------------------
@Test
public void testProcess_class_with_static_inner_class_with_constructor() throws Exception {
// given
String classUnderTestName = "TestClassWithStaticInnerClassWithConstructor";
List<String> neededClasses = new ArrayList<String>();
ClassInfo classInfo = new ClassInfo(classUnderTestName);
FakeMethodInfo fakeInnerClassConstructorInfo = new FakeMethodInfo("<init>", "void", new ArrayList<FieldInfo>(), null);
List<MethodInfo> listInnerClassConstructorInfos = new ArrayList<MethodInfo>();
listInnerClassConstructorInfos.add(fakeInnerClassConstructorInfo);
FakeInnerClassInfo fakeInnerClassInfo = new FakeInnerClassInfo("InnerClass");
fakeInnerClassInfo.setStaticInnerClass(true);
fakeInnerClassInfo.setListConstructorInfos(listInnerClassConstructorInfos);
classInfo.setListInnerClassInfo(Arrays.<InnerClassInfo>asList(fakeInnerClassInfo));
classInfo.setListImports(new HashSet<String>());
Writer out = createWriterInSandbox(writer.getNamingGenerator().createBoundBoxName(classInfo));
// when
writer.writeBoundBox(classInfo, out);
closeSandboxWriter();
// then
CompilationTask task = createCompileTask(writer.getNamingGenerator().createBoundBoxName(classInfo), neededClasses);
boolean result = task.call();
assertTrue(result);
Class<?> clazz = loadBoundBoxClass(writer.getNamingGenerator().createBoundBoxName(classInfo));;
Class<?> innerClass = clazz.getDeclaredClasses()[0];
assertNotNull(innerClass);
assertEquals("BoundBoxOfInnerClass",innerClass.getSimpleName());
Method innerClassConstructor = clazz.getDeclaredMethod("boundBox_new_InnerClass");
assertNotNull(innerClassConstructor);
}
@Test
public void testProcess_class_with_static_inner_class_with_many_constructors() throws Exception {
// given
String classUnderTestName = "TestClassWithStaticInnerClassWithConstructor";
List<String> neededClasses = new ArrayList<String>();
ClassInfo classInfo = new ClassInfo(classUnderTestName);
List<MethodInfo> listInnerClassConstructorInfos = new ArrayList<MethodInfo>();
FakeMethodInfo fakeInnerClassConstructorInfo = new FakeMethodInfo("<init>", "void", new ArrayList<FieldInfo>(), null);
listInnerClassConstructorInfos.add(fakeInnerClassConstructorInfo);
FieldInfo paramInt = new FakeFieldInfo("a", int.class.getName());
FakeMethodInfo fakeInnerClassConstructorInfo2 = new FakeMethodInfo("<init>", "void", Arrays.asList(paramInt), null);
listInnerClassConstructorInfos.add(fakeInnerClassConstructorInfo2);
FieldInfo paramObject = new FakeFieldInfo("a", Object.class.getName());
FakeMethodInfo fakeInnerClassConstructorInfo3 = new FakeMethodInfo("<init>", "void", Arrays.asList(paramObject), null);
listInnerClassConstructorInfos.add(fakeInnerClassConstructorInfo3);
FakeInnerClassInfo fakeInnerClassInfo = new FakeInnerClassInfo("InnerClass");
fakeInnerClassInfo.setStaticInnerClass(true);
fakeInnerClassInfo.setListConstructorInfos(listInnerClassConstructorInfos);
classInfo.setListInnerClassInfo(Arrays.<InnerClassInfo>asList(fakeInnerClassInfo));
classInfo.setListImports(new HashSet<String>());
Writer out = createWriterInSandbox(writer.getNamingGenerator().createBoundBoxName(classInfo));
// when
writer.writeBoundBox(classInfo, out);
closeSandboxWriter();
// then
CompilationTask task = createCompileTask(writer.getNamingGenerator().createBoundBoxName(classInfo), neededClasses);
boolean result = task.call();
assertTrue(result);
Class<?> clazz = loadBoundBoxClass(writer.getNamingGenerator().createBoundBoxName(classInfo));;
Class<?> innerClass = clazz.getDeclaredClasses()[0];
assertNotNull(innerClass);
assertEquals("BoundBoxOfInnerClass",innerClass.getSimpleName());
Method innerClassConstructor = clazz.getDeclaredMethod("boundBox_new_InnerClass");
assertNotNull(innerClassConstructor);
Method innerClassConstructor2 = clazz.getDeclaredMethod("boundBox_new_InnerClass", int.class);
assertNotNull(innerClassConstructor2);
Method innerClassConstructor3 = clazz.getDeclaredMethod("boundBox_new_InnerClass", Object.class);
assertNotNull(innerClassConstructor3);
}
@Test
public void testProcess_class_with_static_inner_class_with_many_fields_and_methods() throws Exception {
// given
String classUnderTestName = "TestClassWithStaticInnerClassWithManyFieldsAndMethods";
List<String> neededClasses = new ArrayList<String>();
ClassInfo classInfo = new ClassInfo(classUnderTestName);
List<MethodInfo> listInnerClassConstructorInfos = new ArrayList<MethodInfo>();
FakeMethodInfo fakeInnerClassConstructorInfo = new FakeMethodInfo("<init>", "void", new ArrayList<FieldInfo>(), null);
listInnerClassConstructorInfos.add(fakeInnerClassConstructorInfo);
List<FieldInfo> listInnerClassFieldInfos = new ArrayList<FieldInfo>();
FieldInfo fakeInnerClassFieldInfo = new FakeFieldInfo("a", int.class.getName());
listInnerClassFieldInfos.add(fakeInnerClassFieldInfo);
FieldInfo fakeInnerClassFieldInfo2 = new FakeFieldInfo("b", Object.class.getName());
listInnerClassFieldInfos.add(fakeInnerClassFieldInfo2);
List<MethodInfo> listInnerClassMethodInfos = new ArrayList<MethodInfo>();
FakeMethodInfo fakeInnerClassMethodInfo = new FakeMethodInfo("foo", "void", new ArrayList<FieldInfo>(), null);
listInnerClassMethodInfos.add(fakeInnerClassMethodInfo);
FakeMethodInfo fakeInnerClassMethodInfo2 = new FakeMethodInfo("bar", "void", Arrays.asList(fakeInnerClassFieldInfo), null);
listInnerClassMethodInfos.add(fakeInnerClassMethodInfo2);
FakeInnerClassInfo fakeInnerClassInfo = new FakeInnerClassInfo("InnerClass");
fakeInnerClassInfo.setStaticInnerClass(true);
fakeInnerClassInfo.setListConstructorInfos(listInnerClassConstructorInfos);
fakeInnerClassInfo.setListFieldInfos(listInnerClassFieldInfos);
fakeInnerClassInfo.setListMethodInfos(listInnerClassMethodInfos);
classInfo.setListInnerClassInfo(Arrays.<InnerClassInfo>asList(fakeInnerClassInfo));
classInfo.setListImports(new HashSet<String>());
Writer out = createWriterInSandbox(writer.getNamingGenerator().createBoundBoxName(classInfo));
// when
writer.writeBoundBox(classInfo, out);
closeSandboxWriter();
// then
CompilationTask task = createCompileTask(writer.getNamingGenerator().createBoundBoxName(classInfo), neededClasses);
boolean result = task.call();
assertTrue(result);
Class<?> clazz = loadBoundBoxClass(writer.getNamingGenerator().createBoundBoxName(classInfo));;
Class<?> innerClass = clazz.getDeclaredClasses()[0];
assertNotNull(innerClass);
assertEquals("BoundBoxOfInnerClass",innerClass.getSimpleName());
Method innerClassConstructor = clazz.getDeclaredMethod("boundBox_new_InnerClass");
assertNotNull(innerClassConstructor);
Method innerClassMethod = innerClass.getDeclaredMethod("foo");
assertNotNull(innerClassMethod);
Method innerClassMethod2 = innerClass.getDeclaredMethod("bar", int.class);
assertNotNull(innerClassMethod2);
}
// ----------------------------------
// PREFIXES
// ----------------------------------
@Test
public void testProcess_class_with_prefixes() throws Exception {
// given
String classUnderTestName = "TestClassWithSingleField";
List<String> neededClasses = new ArrayList<String>();
ClassInfo classInfo = new ClassInfo(classUnderTestName);
FakeFieldInfo fakeFieldInfo = new FakeFieldInfo("foo", "java.lang.String");
List<FieldInfo> listFieldInfos = new ArrayList<FieldInfo>();
listFieldInfos.add(fakeFieldInfo);
classInfo.setListFieldInfos(listFieldInfos);
classInfo.setListImports(new HashSet<String>());
String[] prefixes = {"BB",""};
writer.setPrefixes(prefixes);
Writer out = createWriterInSandbox(writer.getNamingGenerator().createBoundBoxName(classInfo));
// when
writer.writeBoundBox(classInfo, out);
closeSandboxWriter();
// then
CompilationTask task = createCompileTask(writer.getNamingGenerator().createBoundBoxName(classInfo), neededClasses);
boolean result = task.call();
assertTrue(result);
Class<?> clazz = loadBoundBoxClass("BBTestClassWithSingleField");
Method method = clazz.getDeclaredMethod("_getFoo");
assertNotNull(method);
Method method2 = clazz.getDeclaredMethod("_setFoo", String.class);
assertNotNull(method2);
}
// ----------------------------------
// PRIVATE METHODS
// ----------------------------------
private Class<?> loadBoundBoxClass(String className) throws ClassNotFoundException {
return new CustomClassLoader().loadClass(className);
}
private CompilationTask createCompileTask(String className, List<String> neededClasses) throws URISyntaxException {
String[] writtenSourceFileNames = new String[] { classNameToJavaFile(className) };
List<String> neededJavaFiles = new ArrayList<String>();
for (String neededClass : neededClasses) {
neededJavaFiles.add(classNameToJavaFile(neededClass));
}
String[] testSourceFileNames = neededJavaFiles.toArray(new String[0]);
CompilationTask task = processAnnotations(writtenSourceFileNames, testSourceFileNames);
return task;
}
private FileWriter createWriterInSandbox(String className) throws IOException {
sandboxWriter = new FileWriter(new File(sandBoxDir, classNameToJavaFile(className)));
return sandboxWriter;
}
private String classNameToJavaFile(String className) {
return className.replaceAll("\\.", "/").concat(".java");
}
private CompilationTask processAnnotations(String[] writtenSourceFileNames, String[] testSourceFileNames)
throws URISyntaxException {
// Get an instance of java compiler
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
// Get a new instance of the standard file manager implementation
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
// Get the list of java file objects, in this case we have only
// one file, TestClass.java
// http://stackoverflow.com/a/676102/693752
List<File> listSourceFiles = new ArrayList<File>();
for (String sourceFileName : writtenSourceFileNames) {
listSourceFiles.add(new File(sandBoxDir, sourceFileName));
}
for (String sourceFileName : testSourceFileNames) {
listSourceFiles.add(new File(ClassLoader.getSystemResource(sourceFileName).toURI()));
}
Iterable<? extends JavaFileObject> compilationUnits1 = fileManager.getJavaFileObjectsFromFiles(listSourceFiles);
Iterable<String> options = Arrays.asList("-d", sandBoxDir.getAbsolutePath());
// Create the compilation task
CompilationTask task = compiler.getTask(null, fileManager, null, options, null, compilationUnits1);
task.setProcessors(new LinkedList<Processor>());
return task;
}
// ----------------------------------
// INNER CLASS
// ----------------------------------
private final class CustomClassLoader extends ClassLoader {
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
File classFile = new File(sandBoxDir, name + ".class");
if (!classFile.exists()) {
return super.loadClass(name);
} else {
try {
byte[] bytes = FileUtils.readFileToByteArray(classFile);
return defineClass(name, bytes, 0, bytes.length);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
}
}
| false | true | public void testProcess_class_with_many_methods() throws Exception {
// given
String classUnderTestName = "TestClassWithManyMethods";
List<String> neededClasses = new ArrayList<String>();
ClassInfo classInfo = new ClassInfo(classUnderTestName);
List<MethodInfo> listConstructorInfos = new ArrayList<MethodInfo>();
listConstructorInfos.add(new FakeMethodInfo("simple", "void", new ArrayList<FieldInfo>(), null));
FakeFieldInfo fieldInfo = new FakeFieldInfo("a", "int");
listConstructorInfos.add(new FakeMethodInfo("withPrimitiveArgument", "void", Arrays.<FieldInfo>asList(fieldInfo), null));
FakeFieldInfo fieldInfo2 = new FakeFieldInfo("a", Object.class.getName());
listConstructorInfos.add(new FakeMethodInfo("withObjectArgument", "void", Arrays.<FieldInfo>asList(fieldInfo2), null));
FakeFieldInfo fieldInfo3 = new FakeFieldInfo("b", Object.class.getName());
listConstructorInfos.add(new FakeMethodInfo("withManyArguments", "void", Arrays.<FieldInfo>asList(fieldInfo, fieldInfo3),
null));
listConstructorInfos.add(new FakeMethodInfo("withPrimitiveIntReturnType", "int", Arrays.<FieldInfo>asList(), null));
listConstructorInfos.add(new FakeMethodInfo("withPrimitiveDoubleReturnType", "double", Arrays.<FieldInfo>asList(), null));
listConstructorInfos
.add(new FakeMethodInfo("withPrimitiveBooleanReturnType", "boolean", Arrays.<FieldInfo>asList(), null));
listConstructorInfos.add(new FakeMethodInfo("withSingleThrownType", "void", Arrays.<FieldInfo>asList(), Arrays
.asList("java.io.IOException")));
listConstructorInfos.add(new FakeMethodInfo("withManyThrownType", "void", Arrays.<FieldInfo>asList(), Arrays.asList(
"java.io.IOException", "java.lang.RuntimeException")));
classInfo.setListConstructorInfos(listConstructorInfos);
classInfo.setListImports(new HashSet<String>());
Writer out = createWriterInSandbox(writer.getNamingGenerator().createBoundBoxName(classInfo));
// when
writer.writeBoundBox(classInfo, out);
closeSandboxWriter();
// then
CompilationTask task = createCompileTask(writer.getNamingGenerator().createBoundBoxName(classInfo), neededClasses);
boolean result = task.call();
assertTrue(result);
Class<?> clazz = loadBoundBoxClass(writer.getNamingGenerator().createBoundBoxName(classInfo));;
assertNotNull(clazz.getDeclaredMethod("simple"));
assertNotNull(clazz.getDeclaredMethod("withPrimitiveArgument", int.class));
assertNotNull(clazz.getDeclaredMethod("withObjectArgument", Object.class));
assertNotNull(clazz.getDeclaredMethod("withManyArguments", int.class, Object.class));
Method declaredMethod = clazz.getDeclaredMethod("withPrimitiveIntReturnType");
assertNotNull(declaredMethod);
assertTrue(int.class.equals(declaredMethod.getReturnType()));
Method declaredMethod2 = clazz.getDeclaredMethod("withPrimitiveDoubleReturnType");
assertNotNull(declaredMethod2);
assertTrue(double.class.equals(declaredMethod2.getReturnType()));
Method declaredMethod3 = clazz.getDeclaredMethod("withPrimitiveBooleanReturnType");
assertNotNull(declaredMethod3);
assertTrue(boolean.class.equals(declaredMethod3.getReturnType()));
Method declaredMethod4 = clazz.getDeclaredMethod("withSingleThrownType");
assertNotNull(declaredMethod4);
boolean containsIOException = false;
for (Class<?> exceptionClass : declaredMethod4.getExceptionTypes()) {
if (exceptionClass.equals(IOException.class)) {
containsIOException = true;
}
}
assertTrue(containsIOException);
Method declaredMethod5 = clazz.getDeclaredMethod("withManyThrownType");
assertNotNull(declaredMethod5);
containsIOException = false;
boolean containsRuntimeException = false;
for (Class<?> exceptionClass : declaredMethod5.getExceptionTypes()) {
if (exceptionClass.equals(IOException.class)) {
containsIOException = true;
}
if (exceptionClass.equals(RuntimeException.class)) {
containsRuntimeException = true;
}
}
assertTrue(containsIOException);
assertTrue(containsRuntimeException);
}
| public void testProcess_class_with_many_methods() throws Exception {
// given
String classUnderTestName = "TestClassWithManyMethods";
List<String> neededClasses = new ArrayList<String>();
ClassInfo classInfo = new ClassInfo(classUnderTestName);
List<MethodInfo> listConstructorInfos = new ArrayList<MethodInfo>();
listConstructorInfos.add(new FakeMethodInfo("simple", "void", new ArrayList<FieldInfo>(), null));
FakeFieldInfo fieldInfo = new FakeFieldInfo("a", "int");
listConstructorInfos.add(new FakeMethodInfo("withPrimitiveArgument", "void", Arrays.<FieldInfo>asList(fieldInfo), null));
FakeFieldInfo fieldInfo2 = new FakeFieldInfo("a", Object.class.getName());
listConstructorInfos.add(new FakeMethodInfo("withObjectArgument", "void", Arrays.<FieldInfo>asList(fieldInfo2), null));
FakeFieldInfo fieldInfo3 = new FakeFieldInfo("b", Object.class.getName());
listConstructorInfos.add(new FakeMethodInfo("withManyArguments", "void", Arrays.<FieldInfo>asList(fieldInfo, fieldInfo3),
null));
listConstructorInfos.add(new FakeMethodInfo("withPrimitiveCharReturnType", "char", Arrays.<FieldInfo>asList(), null));
listConstructorInfos.add(new FakeMethodInfo("withPrimitiveIntReturnType", "int", Arrays.<FieldInfo>asList(), null));
listConstructorInfos.add(new FakeMethodInfo("withPrimitiveByteReturnType", "byte", Arrays.<FieldInfo>asList(), null));
listConstructorInfos.add(new FakeMethodInfo("withPrimitiveShortReturnType", "short", Arrays.<FieldInfo>asList(), null));
listConstructorInfos.add(new FakeMethodInfo("withPrimitiveLongReturnType", "long", Arrays.<FieldInfo>asList(), null));
listConstructorInfos.add(new FakeMethodInfo("withPrimitiveDoubleReturnType", "double", Arrays.<FieldInfo>asList(), null));
listConstructorInfos.add(new FakeMethodInfo("withPrimitiveFloatReturnType", "float", Arrays.<FieldInfo>asList(), null));
listConstructorInfos
.add(new FakeMethodInfo("withPrimitiveBooleanReturnType", "boolean", Arrays.<FieldInfo>asList(), null));
listConstructorInfos.add(new FakeMethodInfo("withSingleThrownType", "void", Arrays.<FieldInfo>asList(), Arrays
.asList("java.io.IOException")));
listConstructorInfos.add(new FakeMethodInfo("withManyThrownType", "void", Arrays.<FieldInfo>asList(), Arrays.asList(
"java.io.IOException", "java.lang.RuntimeException")));
classInfo.setListConstructorInfos(listConstructorInfos);
classInfo.setListImports(new HashSet<String>());
Writer out = createWriterInSandbox(writer.getNamingGenerator().createBoundBoxName(classInfo));
// when
writer.writeBoundBox(classInfo, out);
closeSandboxWriter();
// then
CompilationTask task = createCompileTask(writer.getNamingGenerator().createBoundBoxName(classInfo), neededClasses);
boolean result = task.call();
assertTrue(result);
Class<?> clazz = loadBoundBoxClass(writer.getNamingGenerator().createBoundBoxName(classInfo));;
assertNotNull(clazz.getDeclaredMethod("simple"));
assertNotNull(clazz.getDeclaredMethod("withPrimitiveArgument", int.class));
assertNotNull(clazz.getDeclaredMethod("withObjectArgument", Object.class));
assertNotNull(clazz.getDeclaredMethod("withManyArguments", int.class, Object.class));
Method declaredMethodChar = clazz.getDeclaredMethod("withPrimitiveCharReturnType");
assertNotNull(declaredMethodChar);
assertTrue(char.class.equals(declaredMethodChar.getReturnType()));
Method declaredMethodInt = clazz.getDeclaredMethod("withPrimitiveIntReturnType");
assertNotNull(declaredMethodInt);
assertTrue(int.class.equals(declaredMethodInt.getReturnType()));
Method declaredMethodLong = clazz.getDeclaredMethod("withPrimitiveLongReturnType");
assertNotNull(declaredMethodLong);
assertTrue(long.class.equals(declaredMethodLong.getReturnType()));
Method declaredMethodByte = clazz.getDeclaredMethod("withPrimitiveByteReturnType");
assertNotNull(declaredMethodByte);
assertTrue(byte.class.equals(declaredMethodByte.getReturnType()));
Method declaredMethodShort = clazz.getDeclaredMethod("withPrimitiveShortReturnType");
assertNotNull(declaredMethodShort);
assertTrue(short.class.equals(declaredMethodShort.getReturnType()));
Method declaredMethodDouble = clazz.getDeclaredMethod("withPrimitiveDoubleReturnType");
assertNotNull(declaredMethodDouble);
assertTrue(double.class.equals(declaredMethodDouble.getReturnType()));
Method declaredMethodFloat = clazz.getDeclaredMethod("withPrimitiveFloatReturnType");
assertNotNull(declaredMethodFloat);
assertTrue(float.class.equals(declaredMethodFloat.getReturnType()));
Method declaredMethod3 = clazz.getDeclaredMethod("withPrimitiveBooleanReturnType");
assertNotNull(declaredMethod3);
assertTrue(boolean.class.equals(declaredMethod3.getReturnType()));
Method declaredMethod4 = clazz.getDeclaredMethod("withSingleThrownType");
assertNotNull(declaredMethod4);
boolean containsIOException = false;
for (Class<?> exceptionClass : declaredMethod4.getExceptionTypes()) {
if (exceptionClass.equals(IOException.class)) {
containsIOException = true;
}
}
assertTrue(containsIOException);
Method declaredMethod5 = clazz.getDeclaredMethod("withManyThrownType");
assertNotNull(declaredMethod5);
containsIOException = false;
boolean containsRuntimeException = false;
for (Class<?> exceptionClass : declaredMethod5.getExceptionTypes()) {
if (exceptionClass.equals(IOException.class)) {
containsIOException = true;
}
if (exceptionClass.equals(RuntimeException.class)) {
containsRuntimeException = true;
}
}
assertTrue(containsIOException);
assertTrue(containsRuntimeException);
}
|
diff --git a/grails-app/services/org/chai/kevin/value/ExpressionService.java b/grails-app/services/org/chai/kevin/value/ExpressionService.java
index 7527f2ed..1e68b1ae 100644
--- a/grails-app/services/org/chai/kevin/value/ExpressionService.java
+++ b/grails-app/services/org/chai/kevin/value/ExpressionService.java
@@ -1,256 +1,256 @@
package org.chai.kevin.value;
/*
* Copyright (c) 2011, Clinton Health Access Initiative.
*
* 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 <organization> 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 <COPYRIGHT HOLDER> 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.
*/
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.chai.kevin.JaqlService;
import org.chai.kevin.LocationService;
import org.chai.kevin.data.Calculation;
import org.chai.kevin.data.Data;
import org.chai.kevin.data.DataElement;
import org.chai.kevin.data.DataService;
import org.chai.kevin.data.NormalizedDataElement;
import org.chai.kevin.data.RawDataElement;
import org.chai.kevin.data.Type;
import org.chai.kevin.location.CalculationEntity;
import org.chai.kevin.location.DataLocationEntity;
import org.chai.kevin.location.DataEntityType;
import org.hisp.dhis.period.Period;
import org.springframework.transaction.annotation.Transactional;
import com.ibm.jaql.json.type.JsonValue;
public class ExpressionService {
private static final Log log = LogFactory.getLog(ExpressionService.class);
private static final Log expressionLog = LogFactory.getLog("ExpressionLog");
private DataService dataService;
private LocationService locationService;
private ValueService valueService;
private JaqlService jaqlService;
public static class StatusValuePair {
public Status status = null;
public Value value = null;
}
@Transactional(readOnly=true)
public <T extends CalculationPartialValue> List<T> calculatePartialValues(Calculation<T> calculation, CalculationEntity entity, Period period) {
if (log.isDebugEnabled()) log.debug("calculateValue(calculation="+calculation+",period="+period+",entity="+entity+")");
List<T> result = new ArrayList<T>();
for (String expression : calculation.getPartialExpressions()) {
result.addAll(calculatePartialValues(calculation, expression, entity, period));
}
return result;
}
private <T extends CalculationPartialValue> Set<T> calculatePartialValues(Calculation<T> calculation, String expression, CalculationEntity entity, Period period) {
if (log.isDebugEnabled()) log.debug("calculateValue(expression="+expression+",period="+period+",entity="+entity+")");
Set<T> result = new HashSet<T>();
for (DataEntityType type : locationService.listTypes()) {
Set<DataEntityType> collectForType = new HashSet<DataEntityType>();
collectForType.add(type);
List<DataLocationEntity> facilities = entity.collectDataLocationEntities(null, collectForType);
if (!facilities.isEmpty()) {
Map<DataLocationEntity, StatusValuePair> values = new HashMap<DataLocationEntity, StatusValuePair>();
for (DataLocationEntity facility : facilities) {
StatusValuePair statusValuePair = getExpressionStatusValuePair(expression, Calculation.TYPE, period, facility, DataElement.class);
values.put(facility, statusValuePair);
}
result.add(calculation.getCalculationPartialValue(expression, values, entity, period, type));
}
}
return result;
}
@Transactional(readOnly=true)
public NormalizedDataElementValue calculateValue(NormalizedDataElement normalizedDataElement, DataLocationEntity facility, Period period) {
if (log.isDebugEnabled()) log.debug("calculateValue(normalizedDataElement="+normalizedDataElement+",period="+period+",facility="+facility+")");
String expression = normalizedDataElement.getExpression(period, facility.getType().getCode());
StatusValuePair statusValuePair = getExpressionStatusValuePair(expression, normalizedDataElement.getType(), period, facility, RawDataElement.class);
NormalizedDataElementValue expressionValue = new NormalizedDataElementValue(statusValuePair.value, statusValuePair.status, facility, normalizedDataElement, period);
if (log.isDebugEnabled()) log.debug("getValue()="+expressionValue);
return expressionValue;
}
// location has to be a facility
private <T extends DataElement<S>, S extends DataValue> StatusValuePair getExpressionStatusValuePair(String expression, Type type, Period period, DataLocationEntity facility, Class<T> clazz) {
StatusValuePair statusValuePair = new StatusValuePair();
if (expression == null) {
statusValuePair.status = Status.DOES_NOT_APPLY;
statusValuePair.value = Value.NULL_INSTANCE();
}
else {
Map<String, T> datas = getDataInExpression(expression, clazz);
if (hasNullValues(datas.values())) {
statusValuePair.value = Value.NULL_INSTANCE();
statusValuePair.status = Status.MISSING_DATA_ELEMENT;
}
else {
Map<String, Value> valueMap = new HashMap<String, Value>();
Map<String, Type> typeMap = new HashMap<String, Type>();
for (Entry<String, T> entry : datas.entrySet()) {
DataValue dataValue = valueService.getDataElementValue(entry.getValue(), facility, period);
valueMap.put(entry.getValue().getId().toString(), dataValue==null?null:dataValue.getValue());
typeMap.put(entry.getValue().getId().toString(), entry.getValue().getType());
}
if (hasNullValues(valueMap.values())) {
statusValuePair.value = Value.NULL_INSTANCE();
statusValuePair.status = Status.MISSING_VALUE;
}
else {
try {
statusValuePair.value = jaqlService.evaluate(expression, type, valueMap, typeMap);
statusValuePair.status = Status.VALID;
} catch (IllegalArgumentException e) {
- expressionLog.error("expression={"+expression+"}, type={"+type+"}, period={"+period+"}, facility={"+facility+"}, valueMap={"+valueMap+"}, typeMap={"+typeMap+"}");
+ expressionLog.error("expression={"+expression+"}, type={"+type+"}, period={"+period+"}, facility={"+facility+"}, valueMap={"+valueMap+"}, typeMap={"+typeMap+"}", e);
log.warn("there was an error evaluating expression: "+expression, e);
statusValuePair.value = Value.NULL_INSTANCE();
statusValuePair.status = Status.ERROR;
}
}
}
}
return statusValuePair;
}
// TODO do this for validation rules
@Transactional(readOnly=true)
public <T extends Data<?>> boolean expressionIsValid(String formula, Class<T> allowedClazz) {
if (formula.contains("\n")) return false;
Map<String, T> variables = getDataInExpression(formula, allowedClazz);
if (hasNullValues(variables.values())) return false;
Map<String, String> jaqlVariables = new HashMap<String, String>();
for (Entry<String, T> variable : variables.entrySet()) {
Type type = variable.getValue().getType();
jaqlVariables.put(variable.getKey(), type.getJaqlValue(type.getPlaceHolderValue()));
}
try {
jaqlService.getJsonValue(formula, jaqlVariables);
} catch (IllegalArgumentException e) {
return false;
}
return true;
}
@Transactional(readOnly=true)
public <T extends Data<?>> Map<String, T> getDataInExpression(String expression, Class<T> clazz) {
if (log.isDebugEnabled()) log.debug("getDataInExpression(expression="+expression+", clazz="+clazz+")");
Map<String, T> dataInExpression = new HashMap<String, T>();
Set<String> placeholders = getVariables(expression);
for (String placeholder : placeholders) {
T data = null;
try {
data = dataService.getData(Long.parseLong(placeholder.replace("$", "")), clazz);
}
catch (NumberFormatException e) {
log.error("wrong format for dataelement: "+placeholder);
}
dataInExpression.put(placeholder, data);
}
if (log.isDebugEnabled()) log.debug("getDataInExpression()="+dataInExpression);
return dataInExpression;
}
public static Set<String> getVariables(String expression) {
Set<String> placeholders = null;
if ( expression != null ) {
placeholders = new HashSet<String>();
final Matcher matcher = Pattern.compile("\\$\\d+").matcher( expression );
while (matcher.find()) {
String match = matcher.group();
placeholders.add(match);
}
}
return placeholders;
}
public static String convertStringExpression(String expression, Map<String, String> mapping) {
String result = expression;
for (Entry<String, String> entry : mapping.entrySet()) {
// TODO validate key
if (!Pattern.matches("\\$\\d+", entry.getKey())) throw new IllegalArgumentException("key does not match expression pattern: "+entry);
result = result.replaceAll("\\"+entry.getKey()+"(\\z|\\D|$)", entry.getValue().replace("$", "\\$")+"$1");
}
return result;
}
private static <T extends Object> boolean hasNullValues(Collection<T> values) {
for (Object object : values) {
if (object == null) return true;
}
return false;
}
public void setDataService(DataService dataService) {
this.dataService = dataService;
}
public void setValueService(ValueService valueService) {
this.valueService = valueService;
}
public void setLocationService(LocationService locationService) {
this.locationService = locationService;
}
public void setJaqlService(JaqlService jaqlService) {
this.jaqlService = jaqlService;
}
}
| true | true | private <T extends DataElement<S>, S extends DataValue> StatusValuePair getExpressionStatusValuePair(String expression, Type type, Period period, DataLocationEntity facility, Class<T> clazz) {
StatusValuePair statusValuePair = new StatusValuePair();
if (expression == null) {
statusValuePair.status = Status.DOES_NOT_APPLY;
statusValuePair.value = Value.NULL_INSTANCE();
}
else {
Map<String, T> datas = getDataInExpression(expression, clazz);
if (hasNullValues(datas.values())) {
statusValuePair.value = Value.NULL_INSTANCE();
statusValuePair.status = Status.MISSING_DATA_ELEMENT;
}
else {
Map<String, Value> valueMap = new HashMap<String, Value>();
Map<String, Type> typeMap = new HashMap<String, Type>();
for (Entry<String, T> entry : datas.entrySet()) {
DataValue dataValue = valueService.getDataElementValue(entry.getValue(), facility, period);
valueMap.put(entry.getValue().getId().toString(), dataValue==null?null:dataValue.getValue());
typeMap.put(entry.getValue().getId().toString(), entry.getValue().getType());
}
if (hasNullValues(valueMap.values())) {
statusValuePair.value = Value.NULL_INSTANCE();
statusValuePair.status = Status.MISSING_VALUE;
}
else {
try {
statusValuePair.value = jaqlService.evaluate(expression, type, valueMap, typeMap);
statusValuePair.status = Status.VALID;
} catch (IllegalArgumentException e) {
expressionLog.error("expression={"+expression+"}, type={"+type+"}, period={"+period+"}, facility={"+facility+"}, valueMap={"+valueMap+"}, typeMap={"+typeMap+"}");
log.warn("there was an error evaluating expression: "+expression, e);
statusValuePair.value = Value.NULL_INSTANCE();
statusValuePair.status = Status.ERROR;
}
}
}
}
return statusValuePair;
}
| private <T extends DataElement<S>, S extends DataValue> StatusValuePair getExpressionStatusValuePair(String expression, Type type, Period period, DataLocationEntity facility, Class<T> clazz) {
StatusValuePair statusValuePair = new StatusValuePair();
if (expression == null) {
statusValuePair.status = Status.DOES_NOT_APPLY;
statusValuePair.value = Value.NULL_INSTANCE();
}
else {
Map<String, T> datas = getDataInExpression(expression, clazz);
if (hasNullValues(datas.values())) {
statusValuePair.value = Value.NULL_INSTANCE();
statusValuePair.status = Status.MISSING_DATA_ELEMENT;
}
else {
Map<String, Value> valueMap = new HashMap<String, Value>();
Map<String, Type> typeMap = new HashMap<String, Type>();
for (Entry<String, T> entry : datas.entrySet()) {
DataValue dataValue = valueService.getDataElementValue(entry.getValue(), facility, period);
valueMap.put(entry.getValue().getId().toString(), dataValue==null?null:dataValue.getValue());
typeMap.put(entry.getValue().getId().toString(), entry.getValue().getType());
}
if (hasNullValues(valueMap.values())) {
statusValuePair.value = Value.NULL_INSTANCE();
statusValuePair.status = Status.MISSING_VALUE;
}
else {
try {
statusValuePair.value = jaqlService.evaluate(expression, type, valueMap, typeMap);
statusValuePair.status = Status.VALID;
} catch (IllegalArgumentException e) {
expressionLog.error("expression={"+expression+"}, type={"+type+"}, period={"+period+"}, facility={"+facility+"}, valueMap={"+valueMap+"}, typeMap={"+typeMap+"}", e);
log.warn("there was an error evaluating expression: "+expression, e);
statusValuePair.value = Value.NULL_INSTANCE();
statusValuePair.status = Status.ERROR;
}
}
}
}
return statusValuePair;
}
|
diff --git a/core/cc.warlock.rcp/src/cc/warlock/rcp/ui/WarlockProgressBar.java b/core/cc.warlock.rcp/src/cc/warlock/rcp/ui/WarlockProgressBar.java
index c09925d5..164b61b1 100644
--- a/core/cc.warlock.rcp/src/cc/warlock/rcp/ui/WarlockProgressBar.java
+++ b/core/cc.warlock.rcp/src/cc/warlock/rcp/ui/WarlockProgressBar.java
@@ -1,203 +1,203 @@
/*
* Created on Jan 15, 2005
*/
package cc.warlock.rcp.ui;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;
/**
* @author Marshall
*
* This is a custom progress bar that mimics the L&F of StormFront's status bars.
* It's sort of a dirty hack, but it suffices for now. It needs to handle being in a LayoutManager better...
*/
public class WarlockProgressBar extends Canvas
{
protected Font progressFont;
protected String label;
protected Color foreground, background, borderColor;
protected int min, max, selection;
protected int width, height;
protected int borderWidth;
protected boolean showText;
public WarlockProgressBar (Composite composite, int style)
{
super(composite, style);
// defaults
width = 100; height = 15;
showText = true;
Font textFont = JFaceResources.getDefaultFont();
FontData textData = textFont.getFontData()[0];
int minHeight = 8;
progressFont = new Font(getShell().getDisplay(),
- textData.name, (int)Math.max(minHeight,textData.height), textData.style);
+ textData.getName(), (int)Math.max(minHeight,textData.getHeight()), textData.getStyle());
foreground = new Color(getShell().getDisplay(), 255, 255, 255);
background = new Color(getShell().getDisplay(), 0, 0, 0);
borderColor = new Color(getShell().getDisplay(), 25, 25, 25);
borderWidth = 1;
addPaintListener(new PaintListener() {
public void paintControl(PaintEvent e) {
if (label != null) {
Rectangle bounds = getBounds();
e.gc.setFont (progressFont);
Point extent = e.gc.textExtent(label);
int totalPixels = 0;
for (int i = 0; i < label.length(); i++)
{
totalPixels += e.gc.getCharWidth(label.charAt(i));
totalPixels += e.gc.getAdvanceWidth(label.charAt(i));
}
int left = (int) Math.floor(((bounds.width - (borderWidth * 2)) - extent.x) / 2.0);
int top = (int) Math.floor(((bounds.height - (borderWidth * 2)) - e.gc.getFontMetrics().getHeight()) / 2.0);
int barWidth = 0;
int fullBarWidth = (bounds.width - (borderWidth*2));
int fullBarHeight = (bounds.height - (borderWidth*2));
if (max > min)
{
double decimal = (selection / ((double)(max - min)));
barWidth = (int) Math.floor(decimal * fullBarWidth - 1);
}
Color gradientColor = getGradientColor(25, true);
e.gc.setBackground(gradientColor);
e.gc.setForeground(background);
e.gc.fillGradientRectangle(borderWidth, borderWidth, barWidth, fullBarHeight, false);
e.gc.setBackground(borderColor);
e.gc.fillRectangle(borderWidth + barWidth, borderWidth, fullBarWidth, fullBarHeight);
e.gc.setForeground(borderColor);
e.gc.setLineWidth(borderWidth);
e.gc.drawRectangle(0, 0, bounds.width, bounds.height);
if (showText)
{
e.gc.setForeground(foreground);
e.gc.drawText (label, left, top, true);
}
}
}
});
}
private Color getGradientColor (int factor, boolean lighter)
{
int red = 0;
int green = 0;
int blue = 0;
if (lighter)
{
red = background.getRed() < (255 - factor) ? background.getRed() + factor : 255;
green = background.getGreen() < (255 - factor) ? background.getGreen() + factor : 255;
blue = background.getBlue() < (255 - factor) ? background.getBlue() + factor : 255;
}
else {
red = background.getRed() > factor ? background.getRed() - factor : 0;
green = background.getRed() > factor ? background.getRed() - factor : 0;
blue = background.getRed() > factor ? background.getRed() - factor : 0;
}
return new Color(getShell().getDisplay(), red, green, blue);
}
public void setSize(int width, int height) {
this.width = width;
this.height = height;
}
public Point computeSize(int wHint, int hHint, boolean changed) {
return new Point (width, height);
}
public void setForeground (Color color)
{
foreground = color;
redraw();
}
public void setBackground (Color color)
{
background = color;
redraw();
}
public void setLabel (String label)
{
this.label = label;
redraw();
}
public void setMinimum (int min)
{
this.min = min;
}
public void setMaximum (int max)
{
this.max = max;
}
public int getSelection ()
{
return selection;
}
public void setSelection (int selection)
{
this.selection = selection;
redraw();
}
public void setShowText (boolean showText)
{
this.showText = showText;
redraw();
}
public void dispose() {
background.dispose();
foreground.dispose();
progressFont.dispose();
super.dispose();
}
public Color getBorderColor() {
return borderColor;
}
public void setBorderColor(Color borderColor) {
this.borderColor = borderColor;
}
public int getBorderWidth() {
return borderWidth;
}
public void setBorderWidth(int borderWidth) {
this.borderWidth = borderWidth;
}
}
| true | true | public WarlockProgressBar (Composite composite, int style)
{
super(composite, style);
// defaults
width = 100; height = 15;
showText = true;
Font textFont = JFaceResources.getDefaultFont();
FontData textData = textFont.getFontData()[0];
int minHeight = 8;
progressFont = new Font(getShell().getDisplay(),
textData.name, (int)Math.max(minHeight,textData.height), textData.style);
foreground = new Color(getShell().getDisplay(), 255, 255, 255);
background = new Color(getShell().getDisplay(), 0, 0, 0);
borderColor = new Color(getShell().getDisplay(), 25, 25, 25);
borderWidth = 1;
addPaintListener(new PaintListener() {
public void paintControl(PaintEvent e) {
if (label != null) {
Rectangle bounds = getBounds();
e.gc.setFont (progressFont);
Point extent = e.gc.textExtent(label);
int totalPixels = 0;
for (int i = 0; i < label.length(); i++)
{
totalPixels += e.gc.getCharWidth(label.charAt(i));
totalPixels += e.gc.getAdvanceWidth(label.charAt(i));
}
int left = (int) Math.floor(((bounds.width - (borderWidth * 2)) - extent.x) / 2.0);
int top = (int) Math.floor(((bounds.height - (borderWidth * 2)) - e.gc.getFontMetrics().getHeight()) / 2.0);
int barWidth = 0;
int fullBarWidth = (bounds.width - (borderWidth*2));
int fullBarHeight = (bounds.height - (borderWidth*2));
if (max > min)
{
double decimal = (selection / ((double)(max - min)));
barWidth = (int) Math.floor(decimal * fullBarWidth - 1);
}
Color gradientColor = getGradientColor(25, true);
e.gc.setBackground(gradientColor);
e.gc.setForeground(background);
e.gc.fillGradientRectangle(borderWidth, borderWidth, barWidth, fullBarHeight, false);
e.gc.setBackground(borderColor);
e.gc.fillRectangle(borderWidth + barWidth, borderWidth, fullBarWidth, fullBarHeight);
e.gc.setForeground(borderColor);
e.gc.setLineWidth(borderWidth);
e.gc.drawRectangle(0, 0, bounds.width, bounds.height);
if (showText)
{
e.gc.setForeground(foreground);
e.gc.drawText (label, left, top, true);
}
}
}
});
}
| public WarlockProgressBar (Composite composite, int style)
{
super(composite, style);
// defaults
width = 100; height = 15;
showText = true;
Font textFont = JFaceResources.getDefaultFont();
FontData textData = textFont.getFontData()[0];
int minHeight = 8;
progressFont = new Font(getShell().getDisplay(),
textData.getName(), (int)Math.max(minHeight,textData.getHeight()), textData.getStyle());
foreground = new Color(getShell().getDisplay(), 255, 255, 255);
background = new Color(getShell().getDisplay(), 0, 0, 0);
borderColor = new Color(getShell().getDisplay(), 25, 25, 25);
borderWidth = 1;
addPaintListener(new PaintListener() {
public void paintControl(PaintEvent e) {
if (label != null) {
Rectangle bounds = getBounds();
e.gc.setFont (progressFont);
Point extent = e.gc.textExtent(label);
int totalPixels = 0;
for (int i = 0; i < label.length(); i++)
{
totalPixels += e.gc.getCharWidth(label.charAt(i));
totalPixels += e.gc.getAdvanceWidth(label.charAt(i));
}
int left = (int) Math.floor(((bounds.width - (borderWidth * 2)) - extent.x) / 2.0);
int top = (int) Math.floor(((bounds.height - (borderWidth * 2)) - e.gc.getFontMetrics().getHeight()) / 2.0);
int barWidth = 0;
int fullBarWidth = (bounds.width - (borderWidth*2));
int fullBarHeight = (bounds.height - (borderWidth*2));
if (max > min)
{
double decimal = (selection / ((double)(max - min)));
barWidth = (int) Math.floor(decimal * fullBarWidth - 1);
}
Color gradientColor = getGradientColor(25, true);
e.gc.setBackground(gradientColor);
e.gc.setForeground(background);
e.gc.fillGradientRectangle(borderWidth, borderWidth, barWidth, fullBarHeight, false);
e.gc.setBackground(borderColor);
e.gc.fillRectangle(borderWidth + barWidth, borderWidth, fullBarWidth, fullBarHeight);
e.gc.setForeground(borderColor);
e.gc.setLineWidth(borderWidth);
e.gc.drawRectangle(0, 0, bounds.width, bounds.height);
if (showText)
{
e.gc.setForeground(foreground);
e.gc.drawText (label, left, top, true);
}
}
}
});
}
|
diff --git a/grails/src/web/org/codehaus/groovy/grails/web/pages/GroovyPageWritable.java b/grails/src/web/org/codehaus/groovy/grails/web/pages/GroovyPageWritable.java
index ce31a4d95..97f023241 100644
--- a/grails/src/web/org/codehaus/groovy/grails/web/pages/GroovyPageWritable.java
+++ b/grails/src/web/org/codehaus/groovy/grails/web/pages/GroovyPageWritable.java
@@ -1,311 +1,316 @@
/* Copyright 2004-2005 Graeme Rocher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.codehaus.groovy.grails.web.pages;
import grails.util.GrailsUtil;
import groovy.lang.Binding;
import groovy.lang.GroovyObject;
import groovy.lang.Writable;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.groovy.grails.commons.GrailsApplication;
import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes;
import org.codehaus.groovy.grails.web.servlet.WrappedResponseHolder;
import org.codehaus.groovy.grails.web.servlet.mvc.GrailsWebRequest;
import org.codehaus.groovy.runtime.InvokerHelper;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.request.RequestContextHolder;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
/**
* An instance of groovy.lang.Writable that writes itself to the specified
* writer, typically the response writer
*
* @author Graeme Rocher
* @since 0.5
*
* <p/>
* Created: Feb 23, 2007
* Time: 11:36:44 AM
*/
class GroovyPageWritable implements Writable {
private static final Log LOG = LogFactory.getLog(GroovyPageWritable.class);
private HttpServletResponse response;
private HttpServletRequest request;
private GroovyPageMetaInfo metaInfo;
private boolean showSource;
private ServletContext context;
private Map additionalBinding = new HashMap();
private static final String GROOVY_SOURCE_CONTENT_TYPE = "text/plain";
public GroovyPageWritable(GroovyPageMetaInfo metaInfo) {
GrailsWebRequest webRequest = (GrailsWebRequest) RequestContextHolder.currentRequestAttributes();
this.request = webRequest.getCurrentRequest();
HttpServletResponse wrapped = WrappedResponseHolder.getWrappedResponse();
this.response = wrapped != null ? wrapped : webRequest.getCurrentResponse();
this.context = webRequest.getServletContext();
this.showSource = request.getParameter("showSource") != null && GrailsUtil.isDevelopmentEnv();
this.metaInfo = metaInfo;
}
/**
* This sets any additional variables that need to be placed in the Binding of the GSP page.
*
* @param binding The additional variables
*/
public void setBinding(Map binding) {
if(binding != null)
this.additionalBinding = binding;
}
/**
* Set to true if the generated source should be output instead
* @param showSource True if source output should be output
*/
public void setShowSource(boolean showSource) {
this.showSource = showSource;
}
/**
* Writes the template to the specified Writer
*
* @param out The Writer to write to, normally the HttpServletResponse
* @return Returns the passed Writer
* @throws IOException
*/
public Writer writeTo(Writer out) throws IOException {
if (showSource) {
// Set it to TEXT
response.setContentType(GROOVY_SOURCE_CONTENT_TYPE); // must come before response.getOutputStream()
writeGroovySourceToResponse(metaInfo, out);
} else {
// Set it to HTML by default
if(metaInfo.getCompilationException()!=null) {
throw metaInfo.getCompilationException();
}
boolean contentTypeAlreadySet = response.isCommitted() || response.getContentType() != null;
if(LOG.isDebugEnabled() && !contentTypeAlreadySet) {
LOG.debug("Writing response to ["+response.getClass()+"] with content type: " + metaInfo.getContentType());
}
if(!contentTypeAlreadySet) {
response.setContentType(metaInfo.getContentType()); // must come before response.getWriter()
}
// Set up the script context
Binding binding = (Binding)request.getAttribute(GrailsApplicationAttributes.PAGE_SCOPE);
Binding oldBinding = null;
if(binding == null) {
binding = createBinding();
formulateBinding(request, response, binding, out);
}
else {
// if the Binding already exists then we're a template being included/rendered as part of a larger template
// in this case we need our own Binding and the old Binding needs to be restored after rendering
oldBinding = binding;
binding = createBinding();
formulateBinding(request, response, binding, out);
}
GroovyPage page = (GroovyPage) InvokerHelper.createScript(metaInfo.getPageClass(), binding);
page.setJspTags(metaInfo.getJspTags());
page.setJspTagLibraryResolver(metaInfo.getJspTagLibraryResolver());
page.setGspTagLibraryLookup(metaInfo.getTagLibraryLookup());
page.run();
request.setAttribute(GrailsApplicationAttributes.PAGE_SCOPE, oldBinding);
}
return out;
}
protected void copyBinding(Binding binding, Binding oldBinding, Writer out) throws IOException {
formulateBindingFromWebRequest(binding, request, response, out, (GroovyObject) request.getAttribute(GrailsApplicationAttributes.CONTROLLER));
binding.getVariables().putAll(oldBinding.getVariables());
for (Object o : additionalBinding.keySet()) {
String key = (String) o;
if (!GroovyPage.isReservedName(key)) {
binding.setVariable(key, additionalBinding.get(key));
}
else {
LOG.debug("Variable [" + key + "] cannot be placed within the GSP model, the name used is a reserved name.");
}
}
}
private Binding createBinding() {
Binding binding = new Binding();
request.setAttribute(GrailsApplicationAttributes.PAGE_SCOPE, binding);
binding.setVariable(GroovyPage.PAGE_SCOPE, binding);
return binding;
}
/**
* Copy all of input to output.
* @param in The input stream to writeInputStreamToResponse from
* @param out The output to write to
* @throws IOException When an error occurs writing to the response Writer
*/
protected void writeInputStreamToResponse(InputStream in, Writer out) throws IOException {
try {
in.reset();
Reader reader = new InputStreamReader(in, "UTF-8");
char[] buf = new char[8192];
for (;;) {
int read = reader.read(buf);
if (read <= 0) break;
out.write(buf, 0, read);
}
} finally {
out.close();
in.close();
}
}
/**
* Writes the Groovy source code attached to the given info object
* to the response, prefixing each line with its line number. The
* line numbers make it easier to match line numbers in exceptions
* to the generated source.
* @param info The meta info for the GSP page that we want to write
* the generated source for.
* @param out The writer to send the source to.
* @throws IOException If there is either a problem with the input
* stream for the Groovy source, or the writer.
*/
protected void writeGroovySourceToResponse(GroovyPageMetaInfo info, Writer out) throws IOException {
InputStream in = info.getGroovySource();
try {
- in.reset();
+ try {
+ in.reset();
+ }
+ catch (IOException e) {
+ // ignore
+ }
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
int lineNum = 1;
int maxPaddingSize = 3;
// Prepare the buffer containing the whitespace padding.
// The padding is used to right-align the line numbers.
StringBuffer paddingBuffer = new StringBuffer(maxPaddingSize);
for (int i = 0; i < maxPaddingSize; i++) {
paddingBuffer.append(' ');
}
// Set the initial padding.
String padding = paddingBuffer.toString();
// Read the Groovy source line by line and write it to the
// response, prefixing each line with the line number.
for (String line = reader.readLine(); line != null; line = reader.readLine(), lineNum++) {
// Get the current line number as a string.
String numberText = String.valueOf(lineNum);
// Decrease the padding if the current line number has
// more digits than the previous one.
if (padding.length() + numberText.length() > 4) {
paddingBuffer.deleteCharAt(padding.length() - 1);
padding = paddingBuffer.toString();
}
// Write out this line.
out.write(padding);
out.write(numberText);
out.write(": ");
out.write(line);
out.write('\n');
}
}
finally {
out.close();
in.close();
}
}
/**
* Prepare Bindings before instantiating page.
* @param request The HttpServletRequest instance
* @param response The HttpServletResponse instance
* @param out The response out
* @throws java.io.IOException Thrown when an IO error occurs creating the binding
*/
protected void formulateBinding(HttpServletRequest request, HttpServletResponse response, Binding binding, Writer out)
throws IOException {
formulateBindingFromWebRequest(binding, request, response, out, (GroovyObject) request.getAttribute(GrailsApplicationAttributes.CONTROLLER));
populateViewModel(request, binding);
}
protected void populateViewModel(HttpServletRequest request, Binding binding) {
// Go through request attributes and add them to the binding as the model
for (Enumeration attributeEnum = request.getAttributeNames(); attributeEnum.hasMoreElements();) {
String key = (String) attributeEnum.nextElement();
if(!GroovyPage.isReservedName(key)) {
if(!binding.getVariables().containsKey(key)) {
binding.setVariable( key, request.getAttribute(key) );
}
}
else {
LOG.debug("Variable [" + key + "] cannot be placed within the GSP model, the name used is a reserved name.");
}
}
for (Object o : additionalBinding.keySet()) {
String key = (String) o;
if (!GroovyPage.isReservedName(key)) {
binding.setVariable(key, additionalBinding.get(key));
}
else {
LOG.debug("Variable [" + key + "] cannot be placed within the GSP model, the name used is a reserved name.");
}
}
}
private void formulateBindingFromWebRequest(Binding binding, HttpServletRequest request, HttpServletResponse response, Writer out, GroovyObject controller) {
// if there is no controller in the request configure using existing attributes, creating objects where necessary
GrailsWebRequest webRequest = (GrailsWebRequest)request.getAttribute(GrailsApplicationAttributes.WEB_REQUEST);
binding.setVariable(GroovyPage.WEB_REQUEST, webRequest);
binding.setVariable(GroovyPage.REQUEST, request);
binding.setVariable(GroovyPage.RESPONSE, response);
binding.setVariable(GroovyPage.FLASH, webRequest.getFlashScope());
binding.setVariable(GroovyPage.SERVLET_CONTEXT, context);
ApplicationContext appCtx = webRequest.getAttributes().getApplicationContext();
binding.setVariable(GroovyPage.APPLICATION_CONTEXT, appCtx);
if(appCtx!=null)
binding.setVariable(GrailsApplication.APPLICATION_ID, webRequest.getAttributes().getGrailsApplication());
binding.setVariable(GroovyPage.SESSION, webRequest.getSession());
binding.setVariable(GroovyPage.PARAMS, webRequest.getParams());
binding.setVariable(GroovyPage.ACTION_NAME, webRequest.getActionName());
binding.setVariable(GroovyPage.CONTROLLER_NAME, webRequest.getControllerName());
if(controller!= null) {
binding.setVariable(GrailsApplicationAttributes.CONTROLLER, controller);
binding.setVariable(GroovyPage.PLUGIN_CONTEXT_PATH, controller.getProperty(GroovyPage.PLUGIN_CONTEXT_PATH));
}
binding.setVariable(GroovyPage.OUT, out);
}
}
| true | true | protected void writeGroovySourceToResponse(GroovyPageMetaInfo info, Writer out) throws IOException {
InputStream in = info.getGroovySource();
try {
in.reset();
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
int lineNum = 1;
int maxPaddingSize = 3;
// Prepare the buffer containing the whitespace padding.
// The padding is used to right-align the line numbers.
StringBuffer paddingBuffer = new StringBuffer(maxPaddingSize);
for (int i = 0; i < maxPaddingSize; i++) {
paddingBuffer.append(' ');
}
// Set the initial padding.
String padding = paddingBuffer.toString();
// Read the Groovy source line by line and write it to the
// response, prefixing each line with the line number.
for (String line = reader.readLine(); line != null; line = reader.readLine(), lineNum++) {
// Get the current line number as a string.
String numberText = String.valueOf(lineNum);
// Decrease the padding if the current line number has
// more digits than the previous one.
if (padding.length() + numberText.length() > 4) {
paddingBuffer.deleteCharAt(padding.length() - 1);
padding = paddingBuffer.toString();
}
// Write out this line.
out.write(padding);
out.write(numberText);
out.write(": ");
out.write(line);
out.write('\n');
}
}
finally {
out.close();
in.close();
}
}
| protected void writeGroovySourceToResponse(GroovyPageMetaInfo info, Writer out) throws IOException {
InputStream in = info.getGroovySource();
try {
try {
in.reset();
}
catch (IOException e) {
// ignore
}
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
int lineNum = 1;
int maxPaddingSize = 3;
// Prepare the buffer containing the whitespace padding.
// The padding is used to right-align the line numbers.
StringBuffer paddingBuffer = new StringBuffer(maxPaddingSize);
for (int i = 0; i < maxPaddingSize; i++) {
paddingBuffer.append(' ');
}
// Set the initial padding.
String padding = paddingBuffer.toString();
// Read the Groovy source line by line and write it to the
// response, prefixing each line with the line number.
for (String line = reader.readLine(); line != null; line = reader.readLine(), lineNum++) {
// Get the current line number as a string.
String numberText = String.valueOf(lineNum);
// Decrease the padding if the current line number has
// more digits than the previous one.
if (padding.length() + numberText.length() > 4) {
paddingBuffer.deleteCharAt(padding.length() - 1);
padding = paddingBuffer.toString();
}
// Write out this line.
out.write(padding);
out.write(numberText);
out.write(": ");
out.write(line);
out.write('\n');
}
}
finally {
out.close();
in.close();
}
}
|
diff --git a/wicketstuff-minis/src/main/java/org/wicketstuff/minis/prototipbehaviour/PrototipSettings.java b/wicketstuff-minis/src/main/java/org/wicketstuff/minis/prototipbehaviour/PrototipSettings.java
index dd0442f6d..1446791e0 100644
--- a/wicketstuff-minis/src/main/java/org/wicketstuff/minis/prototipbehaviour/PrototipSettings.java
+++ b/wicketstuff-minis/src/main/java/org/wicketstuff/minis/prototipbehaviour/PrototipSettings.java
@@ -1,593 +1,593 @@
/*
* 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.wicketstuff.minis.prototipbehaviour;
import java.io.Serializable;
/**
* This is a class for creating settings to be used with the prototip lib (the optional third argument)
*
* in all cases you do not need to worry about enclosing your strings in ' '
*
* There is logic in place so that if you enter false or true (ie the boolean), or a number
* it will not enclose your string in '', where as any other string it will
*
* see http://www.nickstakenburg.com/projects/prototip/ for a better description of the options that prototip uses
*
* @author Richard Wilkinson
*
*/
public class PrototipSettings implements Serializable
{
private static final long serialVersionUID = 1L;
private String className;
private String closeButton;
private String duration;
private String delay;
private String effect;
private String hideAfter;
private String hideOn;
private String hook;
private String offset_x;
private String offset_y;
private String showOn;
private String target;
private String title;
private String viewpoint;
private String extraOptions;
private String fixed;
/**
* Generates the correct Javascript code to add as the third parameter to a prototip tooltip
*
* any title passed in here will override any title which is set in this object eg:
*
* PrototipBehaviour title > PrototipSettings title
*
* @return Javascript String
*/
public String getOptionsString(String title)
{
StringBuilder options = new StringBuilder();
if(className != null)
{
options.append("className").append(": ").append(className);
}
if(closeButton != null)
{
if(options.length() > 0) options.append(", ");
options.append("closeButton").append(":").append(closeButton);
}
if(duration != null)
{
if(options.length() > 0) options.append(", ");
options.append("duration").append(":").append(duration);
}
if(delay != null)
{
if(options.length() > 0) options.append(", ");
options.append("delay").append(":").append(delay);
}
if(effect != null)
{
if(options.length() > 0) options.append(", ");
options.append("effect").append(": ").append(effect);;
}
if(hideAfter != null)
{
if(options.length() > 0) options.append(", ");
options.append("hideAfter").append(":").append(hideAfter);
}
if(hideOn != null)
{
if(options.length() > 0) options.append(", ");
options.append("hideOn").append(":").append(hideOn);
}
if(hook != null)
{
if(options.length() > 0) options.append(", ");
options.append("hook").append(":").append(hook);
}
if(offset_x != null && offset_y != null)
{
if(options.length() > 0) options.append(", ");
options.append("offset").append(": { x:").append(offset_x).append(", y: ").append(offset_y).append("}");
}
if(showOn != null)
{
if(options.length() > 0) options.append(", ");
options.append("showOn").append(": ").append(showOn);
}
if(target != null)
{
if(options.length() > 0) options.append(", ");
options.append("target").append(": ").append(target);
}
if(title != null)
{
if(options.length() > 0) options.append(", ");
options.append("title").append(": '").append(title).append("'");
}
else if(this.title != null)
{
if(options.length() > 0) options.append(", ");
options.append("title").append(": ").append(this.title);
}
if(viewpoint != null)
{
if(options.length() > 0) options.append(", ");
options.append("viewpoint").append(":").append(viewpoint);
}
if(fixed != null)
{
if(options.length() > 0) options.append(", ");
options.append("fixed").append(":").append(fixed);
}
if(extraOptions != null)
{
if(options.length() > 0) options.append(", ");
- options.append("extraOptions").append(":").append(extraOptions);
+ options.append(extraOptions);
}
if(options.length() > 0)
{
options.insert(0, "{ ");
options.append(" }");
}
return options.toString();
}
/**
* @return the className
*/
public String getClassName() {
return className;
}
/**
* you do not need to include the ' '
*
* @param className the className to set
* @return this
*/
public PrototipSettings setClassName(String className) {
this.className = "'" + className + "'";
return this;
}
/**
* @return the closeButton
*/
public String getCloseButton() {
return closeButton;
}
/**
* either false or true
*
* @param closeButton the closeButton to set
* @return this
*/
public PrototipSettings setCloseButton(String closeButton) {
this.closeButton = closeButton;
return this;
}
/**
* @return the duration
*/
public String getDuration() {
return duration;
}
/**
* duration of the effect, if used
* eg 0.3
*
* @param duration the duration to set
* @return this
*/
public PrototipSettings setDuration(String duration) {
this.duration = duration;
return this;
}
/**
* @return the fixed
*/
public String getFixed() {
return fixed;
}
/**
* eg false or true
*
* @param fixed the fixed to set
* @return this
*/
public PrototipSettings setFixed(String fixed) {
this.fixed = fixed;
return this;
}
/**
* @return the delay
*/
public String getDelay() {
return delay;
}
/**
* seconds before tooltip appears
* eg 0.2
*
* @param delay the delay to set
* @return this
*/
public PrototipSettings setDelay(String delay) {
this.delay = delay;
return this;
}
/**
* @return the effect
*/
public String getEffect() {
return effect;
}
/**
* you do not need to include the ' '
*
* false, appear or blind, or others if they get enabled
*
* @param effect the effect to set
* @return this
*/
public PrototipSettings setEffect(String effect)
{
if(!effect.equals("false"))
{
effect = "'" + effect + "'";
}
this.effect = effect;
return this;
}
/**
* @return the hideAfter
*/
public String getHideAfter() {
return hideAfter;
}
/**
* false or a number eg 1.5
*
* @param hideAfter the hideAfter to set
* @return this
*/
public PrototipSettings setHideAfter(String hideAfter) {
this.hideAfter = hideAfter;
return this;
}
/**
* @return the hideOn
*/
public String getHideOn() {
return hideOn;
}
/**
* any event eg mouseout or false
*
* @param hideOn the hideOn to set
* @return this
*/
public PrototipSettings setHideOn(String hideOn) {
if(!hideOn.equals("false"))
{
hideOn = "'" + hideOn + "'";
}
this.hideOn = hideOn;
return this;
}
/**
* eg:
* { element: 'element|target|tip|closeButton|.close',
* event: 'click|mouseover|mousemove' }
*
* @param element
* @param event
* @return this
*/
public PrototipSettings setHideOn(String element, String event) {
this.hideOn = new StringBuilder("{ ").append("element: '").append(element).append("', event: '")
.append(event).append("' }").toString();
return this;
}
/**
* @return the hook
*/
public String getHook() {
return hook;
}
/**
* @param hook the hook to set
* @return this
*/
public PrototipSettings setHookFalse() {
this.hook = "false";
return this;
}
/**
* Set the hook, where you want
*
* eg:
*
* { target: 'topLeft|topRight|bottomLeft|bottomRight|
* topMiddle|bottomMiddle|leftMiddle|rightMiddle',
* tip: 'topLeft|topRight|bottomLeft|bottomRight|
* topMiddle|bottomMiddle|leftMiddle|rightMiddle' }
*
* for false use setHookFalse()
*
* @param target
* @param tip
* @return this
*/
public PrototipSettings setHook(String target, String tip) {
this.hook = new StringBuilder("{ ").append("target: '").append(target).append("', tip: '")
.append(tip).append("' }").toString();
return this;
}
/**
* @return the offset_x
*/
public String getOffset_x() {
return offset_x;
}
/**
* @param offset_x the offset_x to set
* @return this
*/
public PrototipSettings setOffset_x(String offset_x) {
this.offset_x = offset_x;
return this;
}
/**
* @return the offset_y
*/
public String getOffset_y() {
return offset_y;
}
/**
* @param offset_y the offset_y to set
* @return this
*/
public PrototipSettings setOffset_y(String offset_y) {
this.offset_y = offset_y;
return this;
}
/**
* Set both x and y offsets
* @param offset_x
* @param offset_y
* @return this
*/
public PrototipSettings setOffset(String offset_x, String offset_y)
{
this.offset_x = offset_x;
this.offset_y = offset_y;
return this;
}
/**
* @return the showOn
*/
public String getShowOn() {
return showOn;
}
/**
* @param showOn the showOn to set
* @return this
*/
public PrototipSettings setShowOn(String showOn) {
this.showOn = "'" + showOn + "'";
return this;
}
/**
* @return the target
*/
public String getTarget() {
return target;
}
/**
* @param target the target to set
* @return this
*/
public PrototipSettings setTarget(String target) {
this.target = "'" + target + "'";
return this;
}
/**
* @return the title
*/
public String getTitle() {
return title;
}
/**
* @param title the title to set
*/
public PrototipSettings setTitle(String title) {
if(!title.equals("false"))
{
title = "'" + title + "'";
}
this.title = title;
return this;
}
/**
* @return the viewpoint
*/
public String getViewpoint() {
return viewpoint;
}
/**
* @param viewpoint the viewpoint to set
* @return this
*/
public PrototipSettings setViewpoint(String viewpoint) {
this.viewpoint = viewpoint;
return this;
}
/**
* @return the extraOptions
*/
public String getExtraOptions() {
return extraOptions;
}
/**
* Futureproofing - this allows you at add any string as an option (note you will need to take care of ' and { } yourself
*
* @param extraOptions the extraOptions to set
* @return this
*/
public PrototipSettings setExtraOptions(String extraOptions) {
this.extraOptions = extraOptions;
return this;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((className == null) ? 0 : className.hashCode());
result = prime * result
+ ((closeButton == null) ? 0 : closeButton.hashCode());
result = prime * result + ((delay == null) ? 0 : delay.hashCode());
result = prime * result
+ ((duration == null) ? 0 : duration.hashCode());
result = prime * result + ((effect == null) ? 0 : effect.hashCode());
result = prime * result
+ ((extraOptions == null) ? 0 : extraOptions.hashCode());
result = prime * result + ((fixed == null) ? 0 : fixed.hashCode());
result = prime * result
+ ((hideAfter == null) ? 0 : hideAfter.hashCode());
result = prime * result + ((hideOn == null) ? 0 : hideOn.hashCode());
result = prime * result + ((hook == null) ? 0 : hook.hashCode());
result = prime * result
+ ((offset_x == null) ? 0 : offset_x.hashCode());
result = prime * result
+ ((offset_y == null) ? 0 : offset_y.hashCode());
result = prime * result + ((showOn == null) ? 0 : showOn.hashCode());
result = prime * result + ((target == null) ? 0 : target.hashCode());
result = prime * result + ((title == null) ? 0 : title.hashCode());
result = prime * result
+ ((viewpoint == null) ? 0 : viewpoint.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final PrototipSettings other = (PrototipSettings) obj;
if (className == null) {
if (other.className != null)
return false;
} else if (!className.equals(other.className))
return false;
if (closeButton == null) {
if (other.closeButton != null)
return false;
} else if (!closeButton.equals(other.closeButton))
return false;
if (delay == null) {
if (other.delay != null)
return false;
} else if (!delay.equals(other.delay))
return false;
if (duration == null) {
if (other.duration != null)
return false;
} else if (!duration.equals(other.duration))
return false;
if (effect == null) {
if (other.effect != null)
return false;
} else if (!effect.equals(other.effect))
return false;
if (extraOptions == null) {
if (other.extraOptions != null)
return false;
} else if (!extraOptions.equals(other.extraOptions))
return false;
if (fixed == null) {
if (other.fixed != null)
return false;
} else if (!fixed.equals(other.fixed))
return false;
if (hideAfter == null) {
if (other.hideAfter != null)
return false;
} else if (!hideAfter.equals(other.hideAfter))
return false;
if (hideOn == null) {
if (other.hideOn != null)
return false;
} else if (!hideOn.equals(other.hideOn))
return false;
if (hook == null) {
if (other.hook != null)
return false;
} else if (!hook.equals(other.hook))
return false;
if (offset_x == null) {
if (other.offset_x != null)
return false;
} else if (!offset_x.equals(other.offset_x))
return false;
if (offset_y == null) {
if (other.offset_y != null)
return false;
} else if (!offset_y.equals(other.offset_y))
return false;
if (showOn == null) {
if (other.showOn != null)
return false;
} else if (!showOn.equals(other.showOn))
return false;
if (target == null) {
if (other.target != null)
return false;
} else if (!target.equals(other.target))
return false;
if (title == null) {
if (other.title != null)
return false;
} else if (!title.equals(other.title))
return false;
if (viewpoint == null) {
if (other.viewpoint != null)
return false;
} else if (!viewpoint.equals(other.viewpoint))
return false;
return true;
}
}
| true | true | public String getOptionsString(String title)
{
StringBuilder options = new StringBuilder();
if(className != null)
{
options.append("className").append(": ").append(className);
}
if(closeButton != null)
{
if(options.length() > 0) options.append(", ");
options.append("closeButton").append(":").append(closeButton);
}
if(duration != null)
{
if(options.length() > 0) options.append(", ");
options.append("duration").append(":").append(duration);
}
if(delay != null)
{
if(options.length() > 0) options.append(", ");
options.append("delay").append(":").append(delay);
}
if(effect != null)
{
if(options.length() > 0) options.append(", ");
options.append("effect").append(": ").append(effect);;
}
if(hideAfter != null)
{
if(options.length() > 0) options.append(", ");
options.append("hideAfter").append(":").append(hideAfter);
}
if(hideOn != null)
{
if(options.length() > 0) options.append(", ");
options.append("hideOn").append(":").append(hideOn);
}
if(hook != null)
{
if(options.length() > 0) options.append(", ");
options.append("hook").append(":").append(hook);
}
if(offset_x != null && offset_y != null)
{
if(options.length() > 0) options.append(", ");
options.append("offset").append(": { x:").append(offset_x).append(", y: ").append(offset_y).append("}");
}
if(showOn != null)
{
if(options.length() > 0) options.append(", ");
options.append("showOn").append(": ").append(showOn);
}
if(target != null)
{
if(options.length() > 0) options.append(", ");
options.append("target").append(": ").append(target);
}
if(title != null)
{
if(options.length() > 0) options.append(", ");
options.append("title").append(": '").append(title).append("'");
}
else if(this.title != null)
{
if(options.length() > 0) options.append(", ");
options.append("title").append(": ").append(this.title);
}
if(viewpoint != null)
{
if(options.length() > 0) options.append(", ");
options.append("viewpoint").append(":").append(viewpoint);
}
if(fixed != null)
{
if(options.length() > 0) options.append(", ");
options.append("fixed").append(":").append(fixed);
}
if(extraOptions != null)
{
if(options.length() > 0) options.append(", ");
options.append("extraOptions").append(":").append(extraOptions);
}
if(options.length() > 0)
{
options.insert(0, "{ ");
options.append(" }");
}
return options.toString();
}
| public String getOptionsString(String title)
{
StringBuilder options = new StringBuilder();
if(className != null)
{
options.append("className").append(": ").append(className);
}
if(closeButton != null)
{
if(options.length() > 0) options.append(", ");
options.append("closeButton").append(":").append(closeButton);
}
if(duration != null)
{
if(options.length() > 0) options.append(", ");
options.append("duration").append(":").append(duration);
}
if(delay != null)
{
if(options.length() > 0) options.append(", ");
options.append("delay").append(":").append(delay);
}
if(effect != null)
{
if(options.length() > 0) options.append(", ");
options.append("effect").append(": ").append(effect);;
}
if(hideAfter != null)
{
if(options.length() > 0) options.append(", ");
options.append("hideAfter").append(":").append(hideAfter);
}
if(hideOn != null)
{
if(options.length() > 0) options.append(", ");
options.append("hideOn").append(":").append(hideOn);
}
if(hook != null)
{
if(options.length() > 0) options.append(", ");
options.append("hook").append(":").append(hook);
}
if(offset_x != null && offset_y != null)
{
if(options.length() > 0) options.append(", ");
options.append("offset").append(": { x:").append(offset_x).append(", y: ").append(offset_y).append("}");
}
if(showOn != null)
{
if(options.length() > 0) options.append(", ");
options.append("showOn").append(": ").append(showOn);
}
if(target != null)
{
if(options.length() > 0) options.append(", ");
options.append("target").append(": ").append(target);
}
if(title != null)
{
if(options.length() > 0) options.append(", ");
options.append("title").append(": '").append(title).append("'");
}
else if(this.title != null)
{
if(options.length() > 0) options.append(", ");
options.append("title").append(": ").append(this.title);
}
if(viewpoint != null)
{
if(options.length() > 0) options.append(", ");
options.append("viewpoint").append(":").append(viewpoint);
}
if(fixed != null)
{
if(options.length() > 0) options.append(", ");
options.append("fixed").append(":").append(fixed);
}
if(extraOptions != null)
{
if(options.length() > 0) options.append(", ");
options.append(extraOptions);
}
if(options.length() > 0)
{
options.insert(0, "{ ");
options.append(" }");
}
return options.toString();
}
|
diff --git a/src/main/java/com/impetus/kundera/ycsb/benchmark/MongoDbClient.java b/src/main/java/com/impetus/kundera/ycsb/benchmark/MongoDbClient.java
index 41b460c..93fb59e 100755
--- a/src/main/java/com/impetus/kundera/ycsb/benchmark/MongoDbClient.java
+++ b/src/main/java/com/impetus/kundera/ycsb/benchmark/MongoDbClient.java
@@ -1,385 +1,385 @@
/**
* MongoDB client binding for YCSB.
*
* Submitted by Yen Pai on 5/11/2010.
*
* https://gist.github.com/000a66b8db2caf42467b#file_mongo_db.java
*
*/
package com.impetus.kundera.ycsb.benchmark;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;
import java.util.Map;
import java.util.Vector;
import com.mongodb.BasicDBObject;
import com.mongodb.DBAddress;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.WriteConcern;
import com.mongodb.WriteResult;
import com.yahoo.ycsb.DB;
import com.yahoo.ycsb.DBException;
import com.yahoo.ycsb.ByteIterator;
import com.yahoo.ycsb.StringByteIterator;
/**
* MongoDB client for YCSB framework.
*
* Properties to set:
*
* mongodb.url=mongodb://localhost:27017 mongodb.database=ycsb
* mongodb.writeConcern=normal
*
* @author ypai
*
*/
public class MongoDbClient extends DB
{
private static Mongo mongo;
private WriteConcern writeConcern;
private String database;
private static com.mongodb.DB db = null;
// private DBCollection collection;
@Override
/**
* Initialize any state for this DB.
* Called once per DB instance; there is one DB instance per client thread.
*/
public void init() throws DBException
{
// initialize MongoDb driver
Properties props = getProperties();
String host = props.getProperty("hosts");
;
String port = props.getProperty("port");
String url = "mongodb://" + host + ":" + port;
// String url = props.getProperty("mongodb.url",
// "mongodb://192.168.145.168:27017");
database = props.getProperty("schema", "kundera");
String writeConcernType = props.getProperty("mongodb.writeConcern", "safe").toLowerCase();
if ("none".equals(writeConcernType))
{
writeConcern = WriteConcern.NONE;
}
else if ("safe".equals(writeConcernType))
{
writeConcern = WriteConcern.SAFE;
}
else if ("normal".equals(writeConcernType))
{
writeConcern = WriteConcern.NORMAL;
}
else if ("fsync_safe".equals(writeConcernType))
{
writeConcern = WriteConcern.FSYNC_SAFE;
}
else if ("replicas_safe".equals(writeConcernType))
{
writeConcern = WriteConcern.REPLICAS_SAFE;
}
else
{
System.err.println("ERROR: Invalid writeConcern: '" + writeConcernType + "'. "
+ "Must be [ none | safe | normal | fsync_safe | replicas_safe ]");
System.exit(1);
}
- synchronized (mongo)
+ synchronized (host)
{
if (mongo == null)
{
try
{
// strip out prefix since Java driver doesn't currently
// support
// standard connection format URL yet
// http://www.mongodb.org/display/DOCS/Connections
if (url.startsWith("mongodb://"))
{
url = url.substring(10);
}
// need to append db to url.
url += "/" + database;
// System.out.println("new database url = " + url);
mongo = new Mongo(new DBAddress(url));
mongo.getMongoOptions().setConnectionsPerHost(100);
// System.out.println("mongo connection created with " +
// url);
}
catch (Exception e1)
{
System.err.println("Could not initialize MongoDB connection pool for Loader: " + e1.toString());
e1.printStackTrace();
return;
}
db = mongo.getDB(database);
}
}
}
@Override
/**
* Cleanup any state for this DB.
* Called once per DB instance; there is one DB instance per client thread.
*/
public void cleanup() throws DBException
{
/* try
{
mongo.close();
}
catch (Exception e1)
{
System.err.println("Could not close MongoDB connection pool: " + e1.toString());
e1.printStackTrace();
return;
}*/
}
@Override
/**
* Delete a record from the database.
*
* @param table The name of the table
* @param key The record key of the record to delete.
* @return Zero on success, a non-zero error code on error. See this class's description for a discussion of error codes.
*/
public int delete(String table, String key)
{
com.mongodb.DB db = null;
try
{
db = mongo.getDB(database);
db.requestStart();
DBCollection collection = db.getCollection(table);
DBObject q = new BasicDBObject().append("_id", key);
WriteResult res = collection.remove(q, writeConcern);
return res.getN() == 1 ? 0 : 1;
}
catch (Exception e)
{
System.err.println(e.toString());
return 1;
}
finally
{
if (db != null)
{
db.requestDone();
}
}
}
@Override
/**
* Insert a record in the database. Any field/value pairs in the specified values HashMap will be written into the record with the specified
* record key.
*
* @param table The name of the table
* @param key The record key of the record to insert.
* @param values A HashMap of field/value pairs to insert in the record
* @return Zero on success, a non-zero error code on error. See this class's description for a discussion of error codes.
*/
public int insert(String table, String key, HashMap<String, ByteIterator> values)
{
try
{
// db.requestStart();
DBCollection collection = db.getCollection("kundera");
DBObject r = new BasicDBObject();
r.put("_id", key);
for (String k : values.keySet())
{
r.put(k, getString(key, "kk"));
}
// WriteResult res = collection.insert(r, writeConcern);
// return res.getError() == null ? 0 : 1;
collection.insert(r);
return 0;
}
catch (Exception e)
{
e.printStackTrace();
return 1;
}
}
@Override
@SuppressWarnings("unchecked")
/**
* Read a record from the database. Each field/value pair from the result will be stored in a HashMap.
*
* @param table The name of the table
* @param key The record key of the record to read.
* @param fields The list of fields to read, or null for all of them
* @param result A HashMap of field/value pairs for the result
* @return Zero on success, a non-zero error code on error or "not found".
*/
public int read(String table, String key, Set<String> fields, HashMap<String, ByteIterator> result)
{
// com.mongodb.DB db = null;
try
{
// db = mongo.getDB(database);
//
// db.requestStart();
//
// DBCollection collection = db.getCollection(table);
DBObject q = new BasicDBObject().append("_id", key);
DBObject fieldsToReturn = new BasicDBObject();
boolean returnAllFields = fields == null;
DBObject queryResult = null;
DBCollection collection = db.getCollection("kundera");
if (!returnAllFields)
{
Iterator<String> iter = fields.iterator();
while (iter.hasNext())
{
fieldsToReturn.put(iter.next(), 1);
}
queryResult = collection.findOne(q, fieldsToReturn);
}
else
{
queryResult = collection.findOne(q);
}
if (queryResult != null)
{
result.putAll(queryResult.toMap());
}
return queryResult != null ? 0 : 1;
}
catch (Exception e)
{
System.err.println(e.toString());
return 1;
}
/*
* finally { if (db != null) { db.requestDone(); } }
*/
}
@Override
/**
* Update a record in the database. Any field/value pairs in the specified values HashMap will be written into the record with the specified
* record key, overwriting any existing values with the same field name.
*
* @param table The name of the table
* @param key The record key of the record to write.
* @param values A HashMap of field/value pairs to update in the record
* @return Zero on success, a non-zero error code on error. See this class's description for a discussion of error codes.
*/
public int update(String table, String key, HashMap<String, ByteIterator> values)
{
com.mongodb.DB db = null;
try
{
db = mongo.getDB(database);
db.requestStart();
DBCollection collection = db.getCollection(table);
DBObject q = new BasicDBObject().append("_id", key);
DBObject u = new BasicDBObject();
DBObject fieldsToSet = new BasicDBObject();
Iterator<String> keys = values.keySet().iterator();
while (keys.hasNext())
{
String tmpKey = keys.next();
fieldsToSet.put(tmpKey, values.get(tmpKey).toArray());
}
u.put("$set", fieldsToSet);
WriteResult res = collection.update(q, u, false, false, writeConcern);
return res.getN() == 1 ? 0 : 1;
}
catch (Exception e)
{
System.err.println(e.toString());
return 1;
}
finally
{
if (db != null)
{
db.requestDone();
}
}
}
@Override
@SuppressWarnings("unchecked")
/**
* Perform a range scan for a set of records in the database. Each field/value pair from the result will be stored in a HashMap.
*
* @param table The name of the table
* @param startkey The record key of the first record to read.
* @param recordcount The number of records to read
* @param fields The list of fields to read, or null for all of them
* @param result A Vector of HashMaps, where each HashMap is a set field/value pairs for one record
* @return Zero on success, a non-zero error code on error. See this class's description for a discussion of error codes.
*/
public int scan(String table, String startkey, int recordcount, Set<String> fields,
Vector<HashMap<String, ByteIterator>> result)
{
com.mongodb.DB db = null;
try
{
db = mongo.getDB(database);
db.requestStart();
DBCollection collection = db.getCollection(table);
// { "_id":{"$gte":startKey, "$lte":{"appId":key+"\uFFFF"}} }
DBObject scanRange = new BasicDBObject().append("$gte", startkey);
DBObject q = new BasicDBObject().append("_id", scanRange);
DBCursor cursor = collection.find(q).limit(recordcount);
while (cursor.hasNext())
{
// toMap() returns a Map, but result.add() expects a
// Map<String,String>. Hence, the suppress warnings.
result.add(StringByteIterator.getByteIteratorMap((Map<String, String>) cursor.next().toMap()));
}
return 0;
}
catch (Exception e)
{
System.err.println(e.toString());
return 1;
}
finally
{
if (db != null)
{
db.requestDone();
}
}
}
private String getString(String key, String value)
{
StringBuilder builder = new StringBuilder(key);
builder.append(value);
return builder.toString();
}
}
| true | true | public void init() throws DBException
{
// initialize MongoDb driver
Properties props = getProperties();
String host = props.getProperty("hosts");
;
String port = props.getProperty("port");
String url = "mongodb://" + host + ":" + port;
// String url = props.getProperty("mongodb.url",
// "mongodb://192.168.145.168:27017");
database = props.getProperty("schema", "kundera");
String writeConcernType = props.getProperty("mongodb.writeConcern", "safe").toLowerCase();
if ("none".equals(writeConcernType))
{
writeConcern = WriteConcern.NONE;
}
else if ("safe".equals(writeConcernType))
{
writeConcern = WriteConcern.SAFE;
}
else if ("normal".equals(writeConcernType))
{
writeConcern = WriteConcern.NORMAL;
}
else if ("fsync_safe".equals(writeConcernType))
{
writeConcern = WriteConcern.FSYNC_SAFE;
}
else if ("replicas_safe".equals(writeConcernType))
{
writeConcern = WriteConcern.REPLICAS_SAFE;
}
else
{
System.err.println("ERROR: Invalid writeConcern: '" + writeConcernType + "'. "
+ "Must be [ none | safe | normal | fsync_safe | replicas_safe ]");
System.exit(1);
}
synchronized (mongo)
{
if (mongo == null)
{
try
{
// strip out prefix since Java driver doesn't currently
// support
// standard connection format URL yet
// http://www.mongodb.org/display/DOCS/Connections
if (url.startsWith("mongodb://"))
{
url = url.substring(10);
}
// need to append db to url.
url += "/" + database;
// System.out.println("new database url = " + url);
mongo = new Mongo(new DBAddress(url));
mongo.getMongoOptions().setConnectionsPerHost(100);
// System.out.println("mongo connection created with " +
// url);
}
catch (Exception e1)
{
System.err.println("Could not initialize MongoDB connection pool for Loader: " + e1.toString());
e1.printStackTrace();
return;
}
db = mongo.getDB(database);
}
}
}
| public void init() throws DBException
{
// initialize MongoDb driver
Properties props = getProperties();
String host = props.getProperty("hosts");
;
String port = props.getProperty("port");
String url = "mongodb://" + host + ":" + port;
// String url = props.getProperty("mongodb.url",
// "mongodb://192.168.145.168:27017");
database = props.getProperty("schema", "kundera");
String writeConcernType = props.getProperty("mongodb.writeConcern", "safe").toLowerCase();
if ("none".equals(writeConcernType))
{
writeConcern = WriteConcern.NONE;
}
else if ("safe".equals(writeConcernType))
{
writeConcern = WriteConcern.SAFE;
}
else if ("normal".equals(writeConcernType))
{
writeConcern = WriteConcern.NORMAL;
}
else if ("fsync_safe".equals(writeConcernType))
{
writeConcern = WriteConcern.FSYNC_SAFE;
}
else if ("replicas_safe".equals(writeConcernType))
{
writeConcern = WriteConcern.REPLICAS_SAFE;
}
else
{
System.err.println("ERROR: Invalid writeConcern: '" + writeConcernType + "'. "
+ "Must be [ none | safe | normal | fsync_safe | replicas_safe ]");
System.exit(1);
}
synchronized (host)
{
if (mongo == null)
{
try
{
// strip out prefix since Java driver doesn't currently
// support
// standard connection format URL yet
// http://www.mongodb.org/display/DOCS/Connections
if (url.startsWith("mongodb://"))
{
url = url.substring(10);
}
// need to append db to url.
url += "/" + database;
// System.out.println("new database url = " + url);
mongo = new Mongo(new DBAddress(url));
mongo.getMongoOptions().setConnectionsPerHost(100);
// System.out.println("mongo connection created with " +
// url);
}
catch (Exception e1)
{
System.err.println("Could not initialize MongoDB connection pool for Loader: " + e1.toString());
e1.printStackTrace();
return;
}
db = mongo.getDB(database);
}
}
}
|
diff --git a/src/main/java/Sirius/server/search/builtin/GeoSearch.java b/src/main/java/Sirius/server/search/builtin/GeoSearch.java
index f05886c5..f2c347a0 100644
--- a/src/main/java/Sirius/server/search/builtin/GeoSearch.java
+++ b/src/main/java/Sirius/server/search/builtin/GeoSearch.java
@@ -1,139 +1,139 @@
/***************************************************
*
* cismet GmbH, Saarbruecken, Germany
*
* ... and it just works.
*
****************************************************/
/*
* Copyright (C) 2010 thorsten
*
* 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 Sirius.server.search.builtin;
import Sirius.server.middleware.interfaces.domainserver.MetaService;
import Sirius.server.middleware.types.MetaObjectNode;
import Sirius.server.middleware.types.Node;
import Sirius.server.search.CidsServerSearch;
import com.vividsolutions.jts.geom.Geometry;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
/**
* DOCUMENT ME!
*
* @author thorsten
* @version $Revision$, $Date$
*/
public class GeoSearch extends CidsServerSearch {
//~ Instance fields --------------------------------------------------------
Geometry searchGeometry = null;
//~ Constructors -----------------------------------------------------------
/**
* Creates a new GeoSearch object.
*
* @param searchGeometry DOCUMENT ME!
*/
public GeoSearch(final Geometry searchGeometry) {
this.searchGeometry = searchGeometry;
}
//~ Methods ----------------------------------------------------------------
@Override
public Collection performServerSearch() {
final ArrayList<Node> aln = new ArrayList<Node>();
try {
getLog().info("geosearch started");
final String sql = "WITH recursive derived_index(ocid,oid,acid,aid,depth) AS "
+ "( "
+ "SELECT class_id,object_id,cast (NULL AS int), cast (NULL AS int),0 "
+ "FROM GEOSUCHE WHERE class_id IN"
+ "( "
+ "WITH recursive derived_child(father,child,depth) AS ( "
+ "SELECT father,father,0 FROM cs_class_hierarchy WHERE father in <cidsClassesInStatement> "
+ "UNION ALL "
+ "SELECT ch.father,ch.child,dc.depth+1 FROM derived_child dc,cs_class_hierarchy ch WHERE ch.father=dc.child) "
+ "SELECT DISTINCT father FROM derived_child LIMIT 100 "
+ ") "
+ "AND geo_field && GeometryFromText('SRID=<cidsSearchGeometrySRID>;<cidsSearchGeometryWKT>') AND intersects(geo_field,GeometryFromText('SRID=<cidsSearchGeometrySRID>;<cidsSearchGeometryWKT>')) "
+ "UNION ALL "
- + "SELECT aam.class_id,aam.object_id, aam.attr_class_id, aam.attr_object_id,di.depth+1 FROM cs_all_attr_mapping aam,derived_index di WHERE aam.attr_class_id=di.ocid AND aam.attr_object_id=di.oid"
+ + "SELECT aam.class_id,aam.object_id, aam.attr_class_id, aam.attr_object_id,di.depth+1 FROM cs_attr_object aam,derived_index di WHERE aam.attr_class_id=di.ocid AND aam.attr_object_id=di.oid"
+ ") "
+ "SELECT DISTINCT ocid,oid FROM derived_index WHERE ocid in <cidsClassesInStatement> LIMIT 1000 ";
// Deppensuche sequentiell
final HashSet keyset = new HashSet(getActiveLoaclServers().keySet());
final String cidsSearchGeometryWKT = searchGeometry.toText();
final String sridString = Integer.toString(searchGeometry.getSRID());
if ((cidsSearchGeometryWKT == null) || (cidsSearchGeometryWKT.trim().length() == 0)
|| (sridString == null)
|| (sridString.trim().length() == 0)) {
// TODO: Notify user?
getLog().error(
"Search geometry or srid is not given. Can't perform a search without those information.");
return aln;
}
for (final Object key : keyset) {
final MetaService ms = (MetaService)getActiveLoaclServers().get(key);
final String classesInStatement = getClassesInSnippetsPerDomain().get((String)key);
if (getLog().isDebugEnabled()) {
getLog().debug("cidsClassesInStatement=" + classesInStatement);
}
if (getLog().isDebugEnabled()) {
getLog().debug("cidsSearchGeometryWKT=" + cidsSearchGeometryWKT);
}
if (getLog().isDebugEnabled()) {
getLog().debug("cidsSearchGeometrySRID=" + sridString);
}
if ((classesInStatement == null) || (classesInStatement.trim().length() == 0)) {
getLog().warn("There are no search classes defined for domain '" + key
+ "'. This domain will be skipped.");
continue;
}
final String sqlStatement = sql.replaceAll("<cidsClassesInStatement>", classesInStatement)
.replaceAll("<cidsSearchGeometryWKT>", cidsSearchGeometryWKT)
.replaceAll("<cidsSearchGeometrySRID>", sridString);
getLog().info("geosearch: " + sqlStatement);
final ArrayList<ArrayList> result = ms.performCustomSearch(sqlStatement);
for (final ArrayList al : result) {
final int cid = (Integer)al.get(0);
final int oid = (Integer)al.get(1);
final MetaObjectNode mon = new MetaObjectNode((String)key, oid, cid);
aln.add(mon);
}
}
} catch (Exception e) {
getLog().error("Problem during GEOSEARCH", e);
}
return aln;
}
}
| true | true | public Collection performServerSearch() {
final ArrayList<Node> aln = new ArrayList<Node>();
try {
getLog().info("geosearch started");
final String sql = "WITH recursive derived_index(ocid,oid,acid,aid,depth) AS "
+ "( "
+ "SELECT class_id,object_id,cast (NULL AS int), cast (NULL AS int),0 "
+ "FROM GEOSUCHE WHERE class_id IN"
+ "( "
+ "WITH recursive derived_child(father,child,depth) AS ( "
+ "SELECT father,father,0 FROM cs_class_hierarchy WHERE father in <cidsClassesInStatement> "
+ "UNION ALL "
+ "SELECT ch.father,ch.child,dc.depth+1 FROM derived_child dc,cs_class_hierarchy ch WHERE ch.father=dc.child) "
+ "SELECT DISTINCT father FROM derived_child LIMIT 100 "
+ ") "
+ "AND geo_field && GeometryFromText('SRID=<cidsSearchGeometrySRID>;<cidsSearchGeometryWKT>') AND intersects(geo_field,GeometryFromText('SRID=<cidsSearchGeometrySRID>;<cidsSearchGeometryWKT>')) "
+ "UNION ALL "
+ "SELECT aam.class_id,aam.object_id, aam.attr_class_id, aam.attr_object_id,di.depth+1 FROM cs_all_attr_mapping aam,derived_index di WHERE aam.attr_class_id=di.ocid AND aam.attr_object_id=di.oid"
+ ") "
+ "SELECT DISTINCT ocid,oid FROM derived_index WHERE ocid in <cidsClassesInStatement> LIMIT 1000 ";
// Deppensuche sequentiell
final HashSet keyset = new HashSet(getActiveLoaclServers().keySet());
final String cidsSearchGeometryWKT = searchGeometry.toText();
final String sridString = Integer.toString(searchGeometry.getSRID());
if ((cidsSearchGeometryWKT == null) || (cidsSearchGeometryWKT.trim().length() == 0)
|| (sridString == null)
|| (sridString.trim().length() == 0)) {
// TODO: Notify user?
getLog().error(
"Search geometry or srid is not given. Can't perform a search without those information.");
return aln;
}
for (final Object key : keyset) {
final MetaService ms = (MetaService)getActiveLoaclServers().get(key);
final String classesInStatement = getClassesInSnippetsPerDomain().get((String)key);
if (getLog().isDebugEnabled()) {
getLog().debug("cidsClassesInStatement=" + classesInStatement);
}
if (getLog().isDebugEnabled()) {
getLog().debug("cidsSearchGeometryWKT=" + cidsSearchGeometryWKT);
}
if (getLog().isDebugEnabled()) {
getLog().debug("cidsSearchGeometrySRID=" + sridString);
}
if ((classesInStatement == null) || (classesInStatement.trim().length() == 0)) {
getLog().warn("There are no search classes defined for domain '" + key
+ "'. This domain will be skipped.");
continue;
}
final String sqlStatement = sql.replaceAll("<cidsClassesInStatement>", classesInStatement)
.replaceAll("<cidsSearchGeometryWKT>", cidsSearchGeometryWKT)
.replaceAll("<cidsSearchGeometrySRID>", sridString);
getLog().info("geosearch: " + sqlStatement);
final ArrayList<ArrayList> result = ms.performCustomSearch(sqlStatement);
for (final ArrayList al : result) {
final int cid = (Integer)al.get(0);
final int oid = (Integer)al.get(1);
final MetaObjectNode mon = new MetaObjectNode((String)key, oid, cid);
aln.add(mon);
}
}
} catch (Exception e) {
getLog().error("Problem during GEOSEARCH", e);
}
return aln;
}
| public Collection performServerSearch() {
final ArrayList<Node> aln = new ArrayList<Node>();
try {
getLog().info("geosearch started");
final String sql = "WITH recursive derived_index(ocid,oid,acid,aid,depth) AS "
+ "( "
+ "SELECT class_id,object_id,cast (NULL AS int), cast (NULL AS int),0 "
+ "FROM GEOSUCHE WHERE class_id IN"
+ "( "
+ "WITH recursive derived_child(father,child,depth) AS ( "
+ "SELECT father,father,0 FROM cs_class_hierarchy WHERE father in <cidsClassesInStatement> "
+ "UNION ALL "
+ "SELECT ch.father,ch.child,dc.depth+1 FROM derived_child dc,cs_class_hierarchy ch WHERE ch.father=dc.child) "
+ "SELECT DISTINCT father FROM derived_child LIMIT 100 "
+ ") "
+ "AND geo_field && GeometryFromText('SRID=<cidsSearchGeometrySRID>;<cidsSearchGeometryWKT>') AND intersects(geo_field,GeometryFromText('SRID=<cidsSearchGeometrySRID>;<cidsSearchGeometryWKT>')) "
+ "UNION ALL "
+ "SELECT aam.class_id,aam.object_id, aam.attr_class_id, aam.attr_object_id,di.depth+1 FROM cs_attr_object aam,derived_index di WHERE aam.attr_class_id=di.ocid AND aam.attr_object_id=di.oid"
+ ") "
+ "SELECT DISTINCT ocid,oid FROM derived_index WHERE ocid in <cidsClassesInStatement> LIMIT 1000 ";
// Deppensuche sequentiell
final HashSet keyset = new HashSet(getActiveLoaclServers().keySet());
final String cidsSearchGeometryWKT = searchGeometry.toText();
final String sridString = Integer.toString(searchGeometry.getSRID());
if ((cidsSearchGeometryWKT == null) || (cidsSearchGeometryWKT.trim().length() == 0)
|| (sridString == null)
|| (sridString.trim().length() == 0)) {
// TODO: Notify user?
getLog().error(
"Search geometry or srid is not given. Can't perform a search without those information.");
return aln;
}
for (final Object key : keyset) {
final MetaService ms = (MetaService)getActiveLoaclServers().get(key);
final String classesInStatement = getClassesInSnippetsPerDomain().get((String)key);
if (getLog().isDebugEnabled()) {
getLog().debug("cidsClassesInStatement=" + classesInStatement);
}
if (getLog().isDebugEnabled()) {
getLog().debug("cidsSearchGeometryWKT=" + cidsSearchGeometryWKT);
}
if (getLog().isDebugEnabled()) {
getLog().debug("cidsSearchGeometrySRID=" + sridString);
}
if ((classesInStatement == null) || (classesInStatement.trim().length() == 0)) {
getLog().warn("There are no search classes defined for domain '" + key
+ "'. This domain will be skipped.");
continue;
}
final String sqlStatement = sql.replaceAll("<cidsClassesInStatement>", classesInStatement)
.replaceAll("<cidsSearchGeometryWKT>", cidsSearchGeometryWKT)
.replaceAll("<cidsSearchGeometrySRID>", sridString);
getLog().info("geosearch: " + sqlStatement);
final ArrayList<ArrayList> result = ms.performCustomSearch(sqlStatement);
for (final ArrayList al : result) {
final int cid = (Integer)al.get(0);
final int oid = (Integer)al.get(1);
final MetaObjectNode mon = new MetaObjectNode((String)key, oid, cid);
aln.add(mon);
}
}
} catch (Exception e) {
getLog().error("Problem during GEOSEARCH", e);
}
return aln;
}
|
diff --git a/components/bio-formats/src/loci/formats/in/MIASReader.java b/components/bio-formats/src/loci/formats/in/MIASReader.java
index 1c60d20a1..50eafb6f1 100644
--- a/components/bio-formats/src/loci/formats/in/MIASReader.java
+++ b/components/bio-formats/src/loci/formats/in/MIASReader.java
@@ -1,608 +1,610 @@
//
// MIASReader.java
//
/*
OME Bio-Formats package for reading and converting biological file formats.
Copyright (C) 2005-@year@ UW-Madison LOCI and Glencoe Software, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 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 loci.formats.in;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.Vector;
import loci.common.DataTools;
import loci.common.Location;
import loci.common.RandomAccessInputStream;
import loci.common.Region;
import loci.formats.CoreMetadata;
import loci.formats.FilePattern;
import loci.formats.FormatException;
import loci.formats.FormatReader;
import loci.formats.FormatTools;
import loci.formats.MetadataTools;
import loci.formats.TiffTools;
import loci.formats.in.MinimalTiffReader;
import loci.formats.meta.FilterMetadata;
import loci.formats.meta.MetadataStore;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;
/**
* MIASReader is the file format reader for Maia Scientific MIAS-2 datasets.
*
* <dl><dt><b>Source code:</b></dt>
* <dd><a href="https://skyking.microscopy.wisc.edu/trac/java/browser/trunk/components/bio-formats/src/loci/formats/in/MIASReader.java">Trac</a>,
* <a href="https://skyking.microscopy.wisc.edu/svn/java/trunk/components/bio-formats/src/loci/formats/in/MIASReader.java">SVN</a></dd></dl>
*
* @author Melissa Linkert melissa at glencoesoftware.com
*/
public class MIASReader extends FormatReader {
// -- Fields --
/** TIFF files - indexed by plate, well, and file. */
private String[][][] tiffs;
/** Delegate reader. */
private MinimalTiffReader reader;
/** Path to file containing analysis results for all plates. */
private String resultFile = null;
/** Other files that contain analysis results. */
private Vector<String> analysisFiles = null;
private int[][] wellNumber;
private int tileRows, tileCols;
// -- Constructor --
/** Constructs a new MIAS reader. */
public MIASReader() {
super("MIAS", new String[] {"tif", "tiff"});
suffixSufficient = false;
blockCheckLen = 1048576;
}
// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#isThisType(String, boolean) */
public boolean isThisType(String filename, boolean open) {
Location baseFile = new Location(filename).getAbsoluteFile();
Location wellDir = baseFile.getParentFile();
Location experiment = wellDir.getParentFile().getParentFile();
return wellDir != null && experiment != null &&
wellDir.getName().startsWith("Well") && super.isThisType(filename, open);
}
/* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */
public boolean isThisType(RandomAccessInputStream stream) throws IOException {
if (!FormatTools.validStream(stream, blockCheckLen, false)) return false;
Hashtable ifd = TiffTools.getFirstIFD(stream);
if (ifd == null) return false;
Object s = TiffTools.getIFDValue(ifd, TiffTools.SOFTWARE);
if (s == null) return false;
String software = null;
if (s instanceof String[]) software = ((String[]) s)[0];
else software = s.toString();
return software.startsWith("eaZYX");
}
/* @see loci.formats.IFormatReader#fileGroupOption(String) */
public int fileGroupOption(String id) throws FormatException, IOException {
return FormatTools.MUST_GROUP;
}
/* @see loci.formats.IFormatReader#get8BitLookupTable() */
public byte[][] get8BitLookupTable() throws FormatException, IOException {
FormatTools.assertId(currentId, true, 1);
return reader == null ? null : reader.get8BitLookupTable();
}
/* @see loci.formats.IFormatReader#get16BitLookupTable() */
public short[][] get16BitLookupTable() throws FormatException, IOException {
FormatTools.assertId(currentId, true, 1);
return reader == null ? null : reader.get16BitLookupTable();
}
/* @see loci.formats.IFormatReader#openThumbImage(int) */
public BufferedImage openThumbImage(int no)
throws FormatException, IOException
{
FormatTools.assertId(currentId, true, 1);
FormatTools.checkPlaneNumber(this, no);
// TODO : thumbnails take a long time to read
int well = getWellNumber(getSeries());
int plate = getPlateNumber(getSeries());
reader.setId(tiffs[well][plate][no * tileRows * tileCols]);
return reader.openThumbImage(0);
}
/**
* @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int)
*/
public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h)
throws FormatException, IOException
{
FormatTools.assertId(currentId, true, 1);
FormatTools.checkPlaneNumber(this, no);
FormatTools.checkBufferSize(this, buf.length, w, h);
int well = getWellNumber(getSeries());
int plate = getPlateNumber(getSeries());
if (tileRows == 1 && tileCols == 1) {
reader.setId(tiffs[plate][well][no]);
reader.openBytes(0, buf, x, y, w, h);
return buf;
}
int bpp = FormatTools.getBytesPerPixel(getPixelType());
int outputRowLen = w * bpp;
int tileWidth = getSizeX() / tileCols;
int tileHeight = getSizeY() / tileRows;
Region image = new Region(x, y, w, h);
int outputRow = 0, outputCol = 0;
Region intersection = null;
byte[] tileBuf = null;
for (int row=0; row<tileRows; row++) {
for (int col=0; col<tileCols; col++) {
Region tile =
new Region(col * tileWidth, row * tileHeight, tileWidth, tileHeight);
if (!tile.intersects(image)) continue;
intersection = tile.intersection(image);
intersection.x %= tileWidth;
intersection.y %= tileHeight;
reader.setId(tiffs[plate][well][(no*tileRows + row) * tileCols + col]);
tileBuf = reader.openBytes(0, intersection.x, intersection.y,
intersection.width, intersection.height);
int rowLen = tileBuf.length / intersection.height;
// copy tile into output image
int outputOffset = outputRow * outputRowLen + outputCol;
for (int trow=0; trow<intersection.height; trow++) {
System.arraycopy(tileBuf, trow * rowLen, buf, outputOffset, rowLen);
outputOffset += outputRowLen;
}
outputCol += rowLen;
}
if (intersection != null) {
outputRow += intersection.height;
outputCol = 0;
}
}
return buf;
}
/* @see loci.formats.IFormatReader#getUsedFiles(boolean) */
public String[] getUsedFiles(boolean noPixels) {
FormatTools.assertId(currentId, true, 1);
Vector<String> files = new Vector<String>();
if (!noPixels) {
for (String[][] plates : tiffs) {
for (String[] wells : plates) {
for (String file : wells) {
files.add(file);
}
}
}
}
if (resultFile != null) files.add(resultFile);
for (String file : analysisFiles) {
if (!file.endsWith(".tif") || !noPixels) {
files.add(file);
}
}
return files.toArray(new String[0]);
}
// -- IFormatHandler API methods --
/* @see loci.formats.IFormatHandler#close(boolean) */
public void close(boolean fileOnly) throws IOException {
super.close(fileOnly);
if (reader != null) reader.close(fileOnly);
if (!fileOnly) {
reader = null;
tiffs = null;
tileRows = tileCols = 0;
resultFile = null;
analysisFiles = null;
wellNumber = null;
}
}
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
protected void initFile(String id) throws FormatException, IOException {
debug("MIASReader.initFile(" + id + ")");
super.initFile(id);
// TODO : initFile currently accepts a constituent TIFF file.
// Consider allowing the top level experiment directory to be passed in
reader = new MinimalTiffReader();
analysisFiles = new Vector<String>();
// MIAS is a high content screening format which supports multiple plates,
// wells and fields.
// Most of the metadata comes from the directory hierarchy, as very little
// metadata is present in the actual files.
//
// The directory hierarchy is:
//
// <experiment name> top level experiment directory
// Batchresults analysis results for experiment
// <plate number>_<plate barcode> one directory for each plate
// results analysis results for plate
// Well<xxxx> one directory for each well
// mode<x>_z<xxx>_t<xxx>_im<x>_<x>.tif
//
// Each TIFF file contains a single grayscale plane. The "mode" block
// refers to the channel number; the "z" and "t" blocks refer to the
// Z section and timepoint, respectively. The "im<x>_<x>" block gives
// the row and column coordinates of the image within a mosaic.
//
// We are initially given one of these TIFF files; from there, we need
// to find the top level experiment directory and work our way down to
// determine how many plates and wells are present.
status("Building list of TIFF files");
Location baseFile = new Location(id).getAbsoluteFile();
Location experiment =
baseFile.getParentFile().getParentFile().getParentFile();
String experimentName = experiment.getName();
Vector<String> plateDirs = new Vector<String>();
String[] directories = experiment.list();
Arrays.sort(directories);
for (String dir : directories) {
if (dir.equals("Batchresults")) {
Location f = new Location(experiment.getAbsolutePath(), dir);
String[] results = f.list();
for (String result : results) {
Location file = new Location(f.getAbsolutePath(), result);
analysisFiles.add(file.getAbsolutePath());
if (result.startsWith("NEO_Results")) {
resultFile = file.getAbsolutePath();
}
}
}
else plateDirs.add(dir);
}
String[] plateDirectories = plateDirs.toArray(new String[0]);
tiffs = new String[plateDirectories.length][][];
int[][] zCount = new int[plateDirectories.length][];
int[][] cCount = new int[plateDirectories.length][];
int[][] tCount = new int[plateDirectories.length][];
String[][] order = new String[plateDirectories.length][];
wellNumber = new int[plateDirectories.length][];
for (int i=0; i<plateDirectories.length; i++) {
String plate = plateDirectories[i];
Location plateDir = new Location(experiment.getAbsolutePath(), plate);
String[] list = plateDir.list();
Arrays.sort(list);
Vector<String> wellDirectories = new Vector<String>();
for (String dir : list) {
Location f = new Location(plateDir.getAbsolutePath(), dir);
if (f.getName().startsWith("Well")) {
wellDirectories.add(f.getAbsolutePath());
}
else if (f.getName().equals("results")) {
String[] resultsList = f.list();
for (String result : resultsList) {
// exclude proprietary program state files
if (!result.endsWith(".sav") && !result.endsWith(".dsv")) {
Location r = new Location(f.getAbsolutePath(), result);
analysisFiles.add(r.getAbsolutePath());
}
}
}
}
tiffs[i] = new String[wellDirectories.size()][];
zCount[i] = new int[wellDirectories.size()];
cCount[i] = new int[wellDirectories.size()];
tCount[i] = new int[wellDirectories.size()];
order[i] = new String[wellDirectories.size()];
wellNumber[i] = new int[wellDirectories.size()];
for (int j=0; j<wellDirectories.size(); j++) {
Location well = new Location(wellDirectories.get(j));
String wellName = well.getName().replaceAll("Well", "");
wellNumber[i][j] = Integer.parseInt(wellName) - 1;
String wellPath = well.getAbsolutePath();
String[] tiffFiles = well.list();
FilePattern fp = new FilePattern(tiffFiles[0], wellPath);
String[] blocks = fp.getPrefixes();
BigInteger[] firstNumber = fp.getFirst();
BigInteger[] lastNumber = fp.getLast();
BigInteger[] step = fp.getStep();
order[i][j] = "";
for (int block=0; block<blocks.length; block++) {
blocks[block] = blocks[block].toLowerCase();
blocks[block] =
blocks[block].substring(blocks[block].lastIndexOf("_") + 1);
if (blocks[block].equals("z")) {
BigInteger tmp = lastNumber[block].subtract(firstNumber[block]);
tmp = tmp.add(BigInteger.ONE);
tmp = tmp.divide(step[block]);
zCount[i][j] = tmp.intValue();
order[i][j] += "Z";
}
else if (blocks[block].equals("t")) {
BigInteger tmp = lastNumber[block].subtract(firstNumber[block]);
tmp = tmp.add(BigInteger.ONE);
tmp = tmp.divide(step[block]);
tCount[i][j] = tmp.intValue();
order[i][j] += "T";
}
else if (blocks[block].equals("mode")) {
BigInteger tmp = lastNumber[block].subtract(firstNumber[block]);
tmp = tmp.add(BigInteger.ONE);
tmp = tmp.divide(step[block]);
cCount[i][j] = tmp.intValue();
order[i][j] += "C";
}
else if (blocks[block].equals("im")) {
BigInteger tmp = lastNumber[block].subtract(firstNumber[block]);
tmp = tmp.add(BigInteger.ONE);
tmp = tmp.divide(step[block]);
tileRows = tmp.intValue();
}
else if (blocks[block].equals("")) {
BigInteger tmp = lastNumber[block].subtract(firstNumber[block]);
tmp = tmp.add(BigInteger.ONE);
tmp = tmp.divide(step[block]);
tileCols = tmp.intValue();
}
else {
throw new FormatException("Unsupported block '" + blocks[block]);
}
}
order[i][j] += "YX";
order[i][j] = new StringBuffer(order[i][j]).reverse().toString();
Arrays.sort(tiffFiles);
tiffs[i][j] = new String[tiffFiles.length];
for (int k=0; k<tiffFiles.length; k++) {
tiffs[i][j][k] =
new Location(wellPath, tiffFiles[k]).getAbsolutePath();
}
}
}
// Populate core metadata
status("Populating core metadata");
int nSeries = 0;
for (int i=0; i<tiffs.length; i++) {
nSeries += tiffs[i].length;
}
core = new CoreMetadata[nSeries];
for (int i=0; i<core.length; i++) {
core[i] = new CoreMetadata();
int plate = getPlateNumber(i);
int well = getWellNumber(i);
core[i].sizeZ = zCount[plate][well];
core[i].sizeC = cCount[plate][well];
core[i].sizeT = tCount[plate][well];
if (core[i].sizeZ == 0) core[i].sizeZ = 1;
if (core[i].sizeC == 0) core[i].sizeC = 1;
if (core[i].sizeT == 0) core[i].sizeT = 1;
reader.setId(tiffs[plate][well][0]);
core[i].sizeX = reader.getSizeX() * tileCols;
core[i].sizeY = reader.getSizeY() * tileRows;
core[i].pixelType = reader.getPixelType();
core[i].sizeC *= reader.getSizeC();
core[i].rgb = reader.isRGB();
core[i].littleEndian = reader.isLittleEndian();
core[i].interleaved = reader.isInterleaved();
core[i].indexed = reader.isIndexed();
core[i].falseColor = reader.isFalseColor();
core[i].dimensionOrder = order[plate][well];
if (core[i].dimensionOrder.indexOf("Z") == -1) {
core[i].dimensionOrder += "Z";
}
if (core[i].dimensionOrder.indexOf("C") == -1) {
core[i].dimensionOrder += "C";
}
if (core[i].dimensionOrder.indexOf("T") == -1) {
core[i].dimensionOrder += "T";
}
core[i].imageCount = core[i].sizeZ * core[i].sizeT * cCount[plate][well];
}
// Populate metadata hashtable
status("Populating metadata hashtable");
int wellCols = 1;
if (resultFile != null) {
RandomAccessInputStream s = new RandomAccessInputStream(resultFile);
String colNames = null;
Vector<String> rows = new Vector<String>();
boolean doKeyValue = true;
int nStarLines = 0;
String analysisResults = s.readString((int) s.length());
String[] lines = analysisResults.split("\n");
for (String line : lines) {
line = line.trim();
if (line.length() == 0) continue;
if (line.startsWith("******") && line.endsWith("******")) nStarLines++;
if (doKeyValue) {
String[] n = line.split("\t");
if (n[0].endsWith(":")) n[0] = n[0].substring(0, n[0].length() - 1);
if (n.length >= 2) addMeta(n[0], n[1]);
}
else {
if (colNames == null) colNames = line;
else rows.add(line);
}
if (nStarLines == 2) doKeyValue = false;
}
String[] cols = colNames.split("\t");
for (String row : rows) {
String[] d = row.split("\t");
for (int col=3; col<cols.length; col++) {
addMeta("Plate " + d[0] + ", Well " + d[2] + " " + cols[col], d[col]);
if (cols[col].equals("AreaCode")) {
String wellID = d[col];
wellID = wellID.replaceAll("\\D", "");
wellCols = Integer.parseInt(wellID);
}
}
}
}
// Populate MetadataStore
status("Populating MetadataStore");
MetadataStore store =
new FilterMetadata(getMetadataStore(), isMetadataFiltered());
MetadataTools.populatePixels(store, this);
store.setExperimentID("Experiment:" + experimentName, 0);
store.setExperimentType("Other", 0);
// populate SPW metadata
for (int plate=0; plate<tiffs.length; plate++) {
store.setPlateColumnNamingConvention("1", plate);
store.setPlateRowNamingConvention("A", plate);
String plateDir = plateDirectories[plate];
plateDir = plateDir.substring(plateDir.lastIndexOf(File.separator) + 1);
plateDir = plateDir.substring(plateDir.indexOf("-") + 1);
+ store.setPlateName(plateDir, plate);
store.setPlateExternalIdentifier(plateDir, plate);
for (int well=0; well<tiffs[plate].length; well++) {
int wellIndex = wellNumber[plate][well];
store.setWellColumn(wellIndex % wellCols, plate, wellIndex);
store.setWellRow(wellIndex / wellCols, plate, wellIndex);
int imageNumber = getSeriesNumber(plate, well);
store.setWellSampleImageRef("Image:" + imageNumber, plate,
wellIndex, 0);
store.setWellSampleIndex(new Integer(imageNumber), plate, wellIndex, 0);
}
}
// populate Image/Pixels metadata
for (int s=0; s<getSeriesCount(); s++) {
int plate = getPlateNumber(s);
int well = getWellNumber(s);
well = wellNumber[plate][well];
store.setImageExperimentRef("Experiment:" + experimentName, s);
char wellRow = (char) ('A' + (well / wellCols));
int wellCol = (well % wellCols) + 1;
+ store.setImageID("Image:" + s, s);
store.setImageName("Plate #" + plate + ", Well " + wellRow + wellCol, s);
MetadataTools.setDefaultCreationDate(store, id, s);
}
}
// -- Helper methods --
/** Retrieve the series corresponding to the given plate and well. */
private int getSeriesNumber(int plate, int well) {
int series = 0;
for (int i=0; i<plate; i++) {
series += tiffs[i].length;
}
return series + well;
}
/** Retrieve the well to which this series belongs. */
private int getWellNumber(int series) {
return getPlateAndWell(series)[1];
}
/** Retrieve the plate to which this series belongs. */
private int getPlateNumber(int series) {
return getPlateAndWell(series)[0];
}
/** Retrieve a two element array containing the plate and well indices. */
private int[] getPlateAndWell(int series) {
// NB: Don't use FormatTools.rasterToPosition(...), because each plate
// could have a different number of wells.
int wellNumber = series;
int plateNumber = 0;
while (wellNumber >= tiffs[plateNumber].length) {
wellNumber -= tiffs[plateNumber].length;
plateNumber++;
}
return new int[] {plateNumber, wellNumber};
}
}
| false | true | protected void initFile(String id) throws FormatException, IOException {
debug("MIASReader.initFile(" + id + ")");
super.initFile(id);
// TODO : initFile currently accepts a constituent TIFF file.
// Consider allowing the top level experiment directory to be passed in
reader = new MinimalTiffReader();
analysisFiles = new Vector<String>();
// MIAS is a high content screening format which supports multiple plates,
// wells and fields.
// Most of the metadata comes from the directory hierarchy, as very little
// metadata is present in the actual files.
//
// The directory hierarchy is:
//
// <experiment name> top level experiment directory
// Batchresults analysis results for experiment
// <plate number>_<plate barcode> one directory for each plate
// results analysis results for plate
// Well<xxxx> one directory for each well
// mode<x>_z<xxx>_t<xxx>_im<x>_<x>.tif
//
// Each TIFF file contains a single grayscale plane. The "mode" block
// refers to the channel number; the "z" and "t" blocks refer to the
// Z section and timepoint, respectively. The "im<x>_<x>" block gives
// the row and column coordinates of the image within a mosaic.
//
// We are initially given one of these TIFF files; from there, we need
// to find the top level experiment directory and work our way down to
// determine how many plates and wells are present.
status("Building list of TIFF files");
Location baseFile = new Location(id).getAbsoluteFile();
Location experiment =
baseFile.getParentFile().getParentFile().getParentFile();
String experimentName = experiment.getName();
Vector<String> plateDirs = new Vector<String>();
String[] directories = experiment.list();
Arrays.sort(directories);
for (String dir : directories) {
if (dir.equals("Batchresults")) {
Location f = new Location(experiment.getAbsolutePath(), dir);
String[] results = f.list();
for (String result : results) {
Location file = new Location(f.getAbsolutePath(), result);
analysisFiles.add(file.getAbsolutePath());
if (result.startsWith("NEO_Results")) {
resultFile = file.getAbsolutePath();
}
}
}
else plateDirs.add(dir);
}
String[] plateDirectories = plateDirs.toArray(new String[0]);
tiffs = new String[plateDirectories.length][][];
int[][] zCount = new int[plateDirectories.length][];
int[][] cCount = new int[plateDirectories.length][];
int[][] tCount = new int[plateDirectories.length][];
String[][] order = new String[plateDirectories.length][];
wellNumber = new int[plateDirectories.length][];
for (int i=0; i<plateDirectories.length; i++) {
String plate = plateDirectories[i];
Location plateDir = new Location(experiment.getAbsolutePath(), plate);
String[] list = plateDir.list();
Arrays.sort(list);
Vector<String> wellDirectories = new Vector<String>();
for (String dir : list) {
Location f = new Location(plateDir.getAbsolutePath(), dir);
if (f.getName().startsWith("Well")) {
wellDirectories.add(f.getAbsolutePath());
}
else if (f.getName().equals("results")) {
String[] resultsList = f.list();
for (String result : resultsList) {
// exclude proprietary program state files
if (!result.endsWith(".sav") && !result.endsWith(".dsv")) {
Location r = new Location(f.getAbsolutePath(), result);
analysisFiles.add(r.getAbsolutePath());
}
}
}
}
tiffs[i] = new String[wellDirectories.size()][];
zCount[i] = new int[wellDirectories.size()];
cCount[i] = new int[wellDirectories.size()];
tCount[i] = new int[wellDirectories.size()];
order[i] = new String[wellDirectories.size()];
wellNumber[i] = new int[wellDirectories.size()];
for (int j=0; j<wellDirectories.size(); j++) {
Location well = new Location(wellDirectories.get(j));
String wellName = well.getName().replaceAll("Well", "");
wellNumber[i][j] = Integer.parseInt(wellName) - 1;
String wellPath = well.getAbsolutePath();
String[] tiffFiles = well.list();
FilePattern fp = new FilePattern(tiffFiles[0], wellPath);
String[] blocks = fp.getPrefixes();
BigInteger[] firstNumber = fp.getFirst();
BigInteger[] lastNumber = fp.getLast();
BigInteger[] step = fp.getStep();
order[i][j] = "";
for (int block=0; block<blocks.length; block++) {
blocks[block] = blocks[block].toLowerCase();
blocks[block] =
blocks[block].substring(blocks[block].lastIndexOf("_") + 1);
if (blocks[block].equals("z")) {
BigInteger tmp = lastNumber[block].subtract(firstNumber[block]);
tmp = tmp.add(BigInteger.ONE);
tmp = tmp.divide(step[block]);
zCount[i][j] = tmp.intValue();
order[i][j] += "Z";
}
else if (blocks[block].equals("t")) {
BigInteger tmp = lastNumber[block].subtract(firstNumber[block]);
tmp = tmp.add(BigInteger.ONE);
tmp = tmp.divide(step[block]);
tCount[i][j] = tmp.intValue();
order[i][j] += "T";
}
else if (blocks[block].equals("mode")) {
BigInteger tmp = lastNumber[block].subtract(firstNumber[block]);
tmp = tmp.add(BigInteger.ONE);
tmp = tmp.divide(step[block]);
cCount[i][j] = tmp.intValue();
order[i][j] += "C";
}
else if (blocks[block].equals("im")) {
BigInteger tmp = lastNumber[block].subtract(firstNumber[block]);
tmp = tmp.add(BigInteger.ONE);
tmp = tmp.divide(step[block]);
tileRows = tmp.intValue();
}
else if (blocks[block].equals("")) {
BigInteger tmp = lastNumber[block].subtract(firstNumber[block]);
tmp = tmp.add(BigInteger.ONE);
tmp = tmp.divide(step[block]);
tileCols = tmp.intValue();
}
else {
throw new FormatException("Unsupported block '" + blocks[block]);
}
}
order[i][j] += "YX";
order[i][j] = new StringBuffer(order[i][j]).reverse().toString();
Arrays.sort(tiffFiles);
tiffs[i][j] = new String[tiffFiles.length];
for (int k=0; k<tiffFiles.length; k++) {
tiffs[i][j][k] =
new Location(wellPath, tiffFiles[k]).getAbsolutePath();
}
}
}
// Populate core metadata
status("Populating core metadata");
int nSeries = 0;
for (int i=0; i<tiffs.length; i++) {
nSeries += tiffs[i].length;
}
core = new CoreMetadata[nSeries];
for (int i=0; i<core.length; i++) {
core[i] = new CoreMetadata();
int plate = getPlateNumber(i);
int well = getWellNumber(i);
core[i].sizeZ = zCount[plate][well];
core[i].sizeC = cCount[plate][well];
core[i].sizeT = tCount[plate][well];
if (core[i].sizeZ == 0) core[i].sizeZ = 1;
if (core[i].sizeC == 0) core[i].sizeC = 1;
if (core[i].sizeT == 0) core[i].sizeT = 1;
reader.setId(tiffs[plate][well][0]);
core[i].sizeX = reader.getSizeX() * tileCols;
core[i].sizeY = reader.getSizeY() * tileRows;
core[i].pixelType = reader.getPixelType();
core[i].sizeC *= reader.getSizeC();
core[i].rgb = reader.isRGB();
core[i].littleEndian = reader.isLittleEndian();
core[i].interleaved = reader.isInterleaved();
core[i].indexed = reader.isIndexed();
core[i].falseColor = reader.isFalseColor();
core[i].dimensionOrder = order[plate][well];
if (core[i].dimensionOrder.indexOf("Z") == -1) {
core[i].dimensionOrder += "Z";
}
if (core[i].dimensionOrder.indexOf("C") == -1) {
core[i].dimensionOrder += "C";
}
if (core[i].dimensionOrder.indexOf("T") == -1) {
core[i].dimensionOrder += "T";
}
core[i].imageCount = core[i].sizeZ * core[i].sizeT * cCount[plate][well];
}
// Populate metadata hashtable
status("Populating metadata hashtable");
int wellCols = 1;
if (resultFile != null) {
RandomAccessInputStream s = new RandomAccessInputStream(resultFile);
String colNames = null;
Vector<String> rows = new Vector<String>();
boolean doKeyValue = true;
int nStarLines = 0;
String analysisResults = s.readString((int) s.length());
String[] lines = analysisResults.split("\n");
for (String line : lines) {
line = line.trim();
if (line.length() == 0) continue;
if (line.startsWith("******") && line.endsWith("******")) nStarLines++;
if (doKeyValue) {
String[] n = line.split("\t");
if (n[0].endsWith(":")) n[0] = n[0].substring(0, n[0].length() - 1);
if (n.length >= 2) addMeta(n[0], n[1]);
}
else {
if (colNames == null) colNames = line;
else rows.add(line);
}
if (nStarLines == 2) doKeyValue = false;
}
String[] cols = colNames.split("\t");
for (String row : rows) {
String[] d = row.split("\t");
for (int col=3; col<cols.length; col++) {
addMeta("Plate " + d[0] + ", Well " + d[2] + " " + cols[col], d[col]);
if (cols[col].equals("AreaCode")) {
String wellID = d[col];
wellID = wellID.replaceAll("\\D", "");
wellCols = Integer.parseInt(wellID);
}
}
}
}
// Populate MetadataStore
status("Populating MetadataStore");
MetadataStore store =
new FilterMetadata(getMetadataStore(), isMetadataFiltered());
MetadataTools.populatePixels(store, this);
store.setExperimentID("Experiment:" + experimentName, 0);
store.setExperimentType("Other", 0);
// populate SPW metadata
for (int plate=0; plate<tiffs.length; plate++) {
store.setPlateColumnNamingConvention("1", plate);
store.setPlateRowNamingConvention("A", plate);
String plateDir = plateDirectories[plate];
plateDir = plateDir.substring(plateDir.lastIndexOf(File.separator) + 1);
plateDir = plateDir.substring(plateDir.indexOf("-") + 1);
store.setPlateExternalIdentifier(plateDir, plate);
for (int well=0; well<tiffs[plate].length; well++) {
int wellIndex = wellNumber[plate][well];
store.setWellColumn(wellIndex % wellCols, plate, wellIndex);
store.setWellRow(wellIndex / wellCols, plate, wellIndex);
int imageNumber = getSeriesNumber(plate, well);
store.setWellSampleImageRef("Image:" + imageNumber, plate,
wellIndex, 0);
store.setWellSampleIndex(new Integer(imageNumber), plate, wellIndex, 0);
}
}
// populate Image/Pixels metadata
for (int s=0; s<getSeriesCount(); s++) {
int plate = getPlateNumber(s);
int well = getWellNumber(s);
well = wellNumber[plate][well];
store.setImageExperimentRef("Experiment:" + experimentName, s);
char wellRow = (char) ('A' + (well / wellCols));
int wellCol = (well % wellCols) + 1;
store.setImageName("Plate #" + plate + ", Well " + wellRow + wellCol, s);
MetadataTools.setDefaultCreationDate(store, id, s);
}
}
| protected void initFile(String id) throws FormatException, IOException {
debug("MIASReader.initFile(" + id + ")");
super.initFile(id);
// TODO : initFile currently accepts a constituent TIFF file.
// Consider allowing the top level experiment directory to be passed in
reader = new MinimalTiffReader();
analysisFiles = new Vector<String>();
// MIAS is a high content screening format which supports multiple plates,
// wells and fields.
// Most of the metadata comes from the directory hierarchy, as very little
// metadata is present in the actual files.
//
// The directory hierarchy is:
//
// <experiment name> top level experiment directory
// Batchresults analysis results for experiment
// <plate number>_<plate barcode> one directory for each plate
// results analysis results for plate
// Well<xxxx> one directory for each well
// mode<x>_z<xxx>_t<xxx>_im<x>_<x>.tif
//
// Each TIFF file contains a single grayscale plane. The "mode" block
// refers to the channel number; the "z" and "t" blocks refer to the
// Z section and timepoint, respectively. The "im<x>_<x>" block gives
// the row and column coordinates of the image within a mosaic.
//
// We are initially given one of these TIFF files; from there, we need
// to find the top level experiment directory and work our way down to
// determine how many plates and wells are present.
status("Building list of TIFF files");
Location baseFile = new Location(id).getAbsoluteFile();
Location experiment =
baseFile.getParentFile().getParentFile().getParentFile();
String experimentName = experiment.getName();
Vector<String> plateDirs = new Vector<String>();
String[] directories = experiment.list();
Arrays.sort(directories);
for (String dir : directories) {
if (dir.equals("Batchresults")) {
Location f = new Location(experiment.getAbsolutePath(), dir);
String[] results = f.list();
for (String result : results) {
Location file = new Location(f.getAbsolutePath(), result);
analysisFiles.add(file.getAbsolutePath());
if (result.startsWith("NEO_Results")) {
resultFile = file.getAbsolutePath();
}
}
}
else plateDirs.add(dir);
}
String[] plateDirectories = plateDirs.toArray(new String[0]);
tiffs = new String[plateDirectories.length][][];
int[][] zCount = new int[plateDirectories.length][];
int[][] cCount = new int[plateDirectories.length][];
int[][] tCount = new int[plateDirectories.length][];
String[][] order = new String[plateDirectories.length][];
wellNumber = new int[plateDirectories.length][];
for (int i=0; i<plateDirectories.length; i++) {
String plate = plateDirectories[i];
Location plateDir = new Location(experiment.getAbsolutePath(), plate);
String[] list = plateDir.list();
Arrays.sort(list);
Vector<String> wellDirectories = new Vector<String>();
for (String dir : list) {
Location f = new Location(plateDir.getAbsolutePath(), dir);
if (f.getName().startsWith("Well")) {
wellDirectories.add(f.getAbsolutePath());
}
else if (f.getName().equals("results")) {
String[] resultsList = f.list();
for (String result : resultsList) {
// exclude proprietary program state files
if (!result.endsWith(".sav") && !result.endsWith(".dsv")) {
Location r = new Location(f.getAbsolutePath(), result);
analysisFiles.add(r.getAbsolutePath());
}
}
}
}
tiffs[i] = new String[wellDirectories.size()][];
zCount[i] = new int[wellDirectories.size()];
cCount[i] = new int[wellDirectories.size()];
tCount[i] = new int[wellDirectories.size()];
order[i] = new String[wellDirectories.size()];
wellNumber[i] = new int[wellDirectories.size()];
for (int j=0; j<wellDirectories.size(); j++) {
Location well = new Location(wellDirectories.get(j));
String wellName = well.getName().replaceAll("Well", "");
wellNumber[i][j] = Integer.parseInt(wellName) - 1;
String wellPath = well.getAbsolutePath();
String[] tiffFiles = well.list();
FilePattern fp = new FilePattern(tiffFiles[0], wellPath);
String[] blocks = fp.getPrefixes();
BigInteger[] firstNumber = fp.getFirst();
BigInteger[] lastNumber = fp.getLast();
BigInteger[] step = fp.getStep();
order[i][j] = "";
for (int block=0; block<blocks.length; block++) {
blocks[block] = blocks[block].toLowerCase();
blocks[block] =
blocks[block].substring(blocks[block].lastIndexOf("_") + 1);
if (blocks[block].equals("z")) {
BigInteger tmp = lastNumber[block].subtract(firstNumber[block]);
tmp = tmp.add(BigInteger.ONE);
tmp = tmp.divide(step[block]);
zCount[i][j] = tmp.intValue();
order[i][j] += "Z";
}
else if (blocks[block].equals("t")) {
BigInteger tmp = lastNumber[block].subtract(firstNumber[block]);
tmp = tmp.add(BigInteger.ONE);
tmp = tmp.divide(step[block]);
tCount[i][j] = tmp.intValue();
order[i][j] += "T";
}
else if (blocks[block].equals("mode")) {
BigInteger tmp = lastNumber[block].subtract(firstNumber[block]);
tmp = tmp.add(BigInteger.ONE);
tmp = tmp.divide(step[block]);
cCount[i][j] = tmp.intValue();
order[i][j] += "C";
}
else if (blocks[block].equals("im")) {
BigInteger tmp = lastNumber[block].subtract(firstNumber[block]);
tmp = tmp.add(BigInteger.ONE);
tmp = tmp.divide(step[block]);
tileRows = tmp.intValue();
}
else if (blocks[block].equals("")) {
BigInteger tmp = lastNumber[block].subtract(firstNumber[block]);
tmp = tmp.add(BigInteger.ONE);
tmp = tmp.divide(step[block]);
tileCols = tmp.intValue();
}
else {
throw new FormatException("Unsupported block '" + blocks[block]);
}
}
order[i][j] += "YX";
order[i][j] = new StringBuffer(order[i][j]).reverse().toString();
Arrays.sort(tiffFiles);
tiffs[i][j] = new String[tiffFiles.length];
for (int k=0; k<tiffFiles.length; k++) {
tiffs[i][j][k] =
new Location(wellPath, tiffFiles[k]).getAbsolutePath();
}
}
}
// Populate core metadata
status("Populating core metadata");
int nSeries = 0;
for (int i=0; i<tiffs.length; i++) {
nSeries += tiffs[i].length;
}
core = new CoreMetadata[nSeries];
for (int i=0; i<core.length; i++) {
core[i] = new CoreMetadata();
int plate = getPlateNumber(i);
int well = getWellNumber(i);
core[i].sizeZ = zCount[plate][well];
core[i].sizeC = cCount[plate][well];
core[i].sizeT = tCount[plate][well];
if (core[i].sizeZ == 0) core[i].sizeZ = 1;
if (core[i].sizeC == 0) core[i].sizeC = 1;
if (core[i].sizeT == 0) core[i].sizeT = 1;
reader.setId(tiffs[plate][well][0]);
core[i].sizeX = reader.getSizeX() * tileCols;
core[i].sizeY = reader.getSizeY() * tileRows;
core[i].pixelType = reader.getPixelType();
core[i].sizeC *= reader.getSizeC();
core[i].rgb = reader.isRGB();
core[i].littleEndian = reader.isLittleEndian();
core[i].interleaved = reader.isInterleaved();
core[i].indexed = reader.isIndexed();
core[i].falseColor = reader.isFalseColor();
core[i].dimensionOrder = order[plate][well];
if (core[i].dimensionOrder.indexOf("Z") == -1) {
core[i].dimensionOrder += "Z";
}
if (core[i].dimensionOrder.indexOf("C") == -1) {
core[i].dimensionOrder += "C";
}
if (core[i].dimensionOrder.indexOf("T") == -1) {
core[i].dimensionOrder += "T";
}
core[i].imageCount = core[i].sizeZ * core[i].sizeT * cCount[plate][well];
}
// Populate metadata hashtable
status("Populating metadata hashtable");
int wellCols = 1;
if (resultFile != null) {
RandomAccessInputStream s = new RandomAccessInputStream(resultFile);
String colNames = null;
Vector<String> rows = new Vector<String>();
boolean doKeyValue = true;
int nStarLines = 0;
String analysisResults = s.readString((int) s.length());
String[] lines = analysisResults.split("\n");
for (String line : lines) {
line = line.trim();
if (line.length() == 0) continue;
if (line.startsWith("******") && line.endsWith("******")) nStarLines++;
if (doKeyValue) {
String[] n = line.split("\t");
if (n[0].endsWith(":")) n[0] = n[0].substring(0, n[0].length() - 1);
if (n.length >= 2) addMeta(n[0], n[1]);
}
else {
if (colNames == null) colNames = line;
else rows.add(line);
}
if (nStarLines == 2) doKeyValue = false;
}
String[] cols = colNames.split("\t");
for (String row : rows) {
String[] d = row.split("\t");
for (int col=3; col<cols.length; col++) {
addMeta("Plate " + d[0] + ", Well " + d[2] + " " + cols[col], d[col]);
if (cols[col].equals("AreaCode")) {
String wellID = d[col];
wellID = wellID.replaceAll("\\D", "");
wellCols = Integer.parseInt(wellID);
}
}
}
}
// Populate MetadataStore
status("Populating MetadataStore");
MetadataStore store =
new FilterMetadata(getMetadataStore(), isMetadataFiltered());
MetadataTools.populatePixels(store, this);
store.setExperimentID("Experiment:" + experimentName, 0);
store.setExperimentType("Other", 0);
// populate SPW metadata
for (int plate=0; plate<tiffs.length; plate++) {
store.setPlateColumnNamingConvention("1", plate);
store.setPlateRowNamingConvention("A", plate);
String plateDir = plateDirectories[plate];
plateDir = plateDir.substring(plateDir.lastIndexOf(File.separator) + 1);
plateDir = plateDir.substring(plateDir.indexOf("-") + 1);
store.setPlateName(plateDir, plate);
store.setPlateExternalIdentifier(plateDir, plate);
for (int well=0; well<tiffs[plate].length; well++) {
int wellIndex = wellNumber[plate][well];
store.setWellColumn(wellIndex % wellCols, plate, wellIndex);
store.setWellRow(wellIndex / wellCols, plate, wellIndex);
int imageNumber = getSeriesNumber(plate, well);
store.setWellSampleImageRef("Image:" + imageNumber, plate,
wellIndex, 0);
store.setWellSampleIndex(new Integer(imageNumber), plate, wellIndex, 0);
}
}
// populate Image/Pixels metadata
for (int s=0; s<getSeriesCount(); s++) {
int plate = getPlateNumber(s);
int well = getWellNumber(s);
well = wellNumber[plate][well];
store.setImageExperimentRef("Experiment:" + experimentName, s);
char wellRow = (char) ('A' + (well / wellCols));
int wellCol = (well % wellCols) + 1;
store.setImageID("Image:" + s, s);
store.setImageName("Plate #" + plate + ", Well " + wellRow + wellCol, s);
MetadataTools.setDefaultCreationDate(store, id, s);
}
}
|
diff --git a/src/com/abhirama/gameengine/tests/stresstest/CustomGameServerHandler.java b/src/com/abhirama/gameengine/tests/stresstest/CustomGameServerHandler.java
index 87ab3fb..c2f06fc 100644
--- a/src/com/abhirama/gameengine/tests/stresstest/CustomGameServerHandler.java
+++ b/src/com/abhirama/gameengine/tests/stresstest/CustomGameServerHandler.java
@@ -1,48 +1,48 @@
/**
* Created by IntelliJ IDEA.
* User: abhat
* This software is provided under the "DO WHAT THE HECK YOU WANT TO DO WITH THIS LICENSE"
*/
package com.abhirama.gameengine.tests.stresstest;
import com.abhirama.gameengine.Player;
import com.abhirama.gameengine.Room;
import com.abhirama.http.GameServerHandler;
import com.abhirama.utils.Util;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public class CustomGameServerHandler extends GameServerHandler {
@Override
public Map gameLogic(Map data) {
//Simulate a memcache fetch
try {
TimeUnit.MILLISECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
Room room = Room.getRoom(Util.getRandomInt(1, 1000));
System.out.println("Executing hit room event:" + room.getPlayers().size());
List<Player> players = room.getPlayers();
TestPlayer player0 = (TestPlayer)players.get(Util.getRandomInt(0, 9));
TestPlayer player1 = (TestPlayer)players.get(Util.getRandomInt(0, 9));
player1.setHealth(90);
- //Simulate a memcache fetch
+ //Simulate a memcache set
try {
TimeUnit.MILLISECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
this.addToOp("I am inside custom game server handler" + this.requestParameters.toString());
return null;
}
}
| true | true | public Map gameLogic(Map data) {
//Simulate a memcache fetch
try {
TimeUnit.MILLISECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
Room room = Room.getRoom(Util.getRandomInt(1, 1000));
System.out.println("Executing hit room event:" + room.getPlayers().size());
List<Player> players = room.getPlayers();
TestPlayer player0 = (TestPlayer)players.get(Util.getRandomInt(0, 9));
TestPlayer player1 = (TestPlayer)players.get(Util.getRandomInt(0, 9));
player1.setHealth(90);
//Simulate a memcache fetch
try {
TimeUnit.MILLISECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
this.addToOp("I am inside custom game server handler" + this.requestParameters.toString());
return null;
}
| public Map gameLogic(Map data) {
//Simulate a memcache fetch
try {
TimeUnit.MILLISECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
Room room = Room.getRoom(Util.getRandomInt(1, 1000));
System.out.println("Executing hit room event:" + room.getPlayers().size());
List<Player> players = room.getPlayers();
TestPlayer player0 = (TestPlayer)players.get(Util.getRandomInt(0, 9));
TestPlayer player1 = (TestPlayer)players.get(Util.getRandomInt(0, 9));
player1.setHealth(90);
//Simulate a memcache set
try {
TimeUnit.MILLISECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
this.addToOp("I am inside custom game server handler" + this.requestParameters.toString());
return null;
}
|
diff --git a/debug/org.eclipse.ptp.debug.sdm.core/src/org/eclipse/ptp/debug/sdm/core/SDMRunner.java b/debug/org.eclipse.ptp.debug.sdm.core/src/org/eclipse/ptp/debug/sdm/core/SDMRunner.java
index bb5eb6d5f..e3910780c 100644
--- a/debug/org.eclipse.ptp.debug.sdm.core/src/org/eclipse/ptp/debug/sdm/core/SDMRunner.java
+++ b/debug/org.eclipse.ptp.debug.sdm.core/src/org/eclipse/ptp/debug/sdm/core/SDMRunner.java
@@ -1,226 +1,228 @@
package org.eclipse.ptp.debug.sdm.core;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.osgi.util.NLS;
import org.eclipse.ptp.core.elementcontrols.IResourceManagerControl;
import org.eclipse.ptp.core.elements.IPJob;
import org.eclipse.ptp.debug.core.PTPDebugCorePlugin;
import org.eclipse.ptp.debug.sdm.core.messages.Messages;
import org.eclipse.ptp.debug.sdm.core.utils.DebugUtil;
import org.eclipse.ptp.remote.core.IRemoteConnection;
import org.eclipse.ptp.remote.core.IRemoteConnectionManager;
import org.eclipse.ptp.remote.core.IRemoteFileManager;
import org.eclipse.ptp.remote.core.IRemoteProcess;
import org.eclipse.ptp.remote.core.IRemoteProcessBuilder;
import org.eclipse.ptp.remote.core.IRemoteServices;
import org.eclipse.ptp.remote.core.PTPRemoteCorePlugin;
import org.eclipse.ptp.rmsystem.IResourceManagerConfiguration;
public class SDMRunner extends Job {
public enum SDMMasterState {
UNKNOWN, STARTING, RUNNING, FINISHED, ERROR
};
private List<String> command;
private String workDir = null;
private SDMMasterState sdmState = SDMMasterState.STARTING;
private IPJob ipJob = null;
private IResourceManagerControl rmControl = null;
private IRemoteProcess sdmProcess;
public SDMRunner(IResourceManagerControl rmControl) {
super(Messages.SDMRunner_0);
this.setPriority(Job.LONG);
this.setSystem(true);
this.rmControl = rmControl;
DebugUtil.trace(DebugUtil.SDM_MASTER_TRACING_MORE, Messages.SDMRunner_4);
}
public void setCommand(List<String> command) {
DebugUtil.trace(DebugUtil.SDM_MASTER_TRACING_MORE, Messages.SDMRunner_5, command.toString());
this.command = command;
}
public void setWorkDir(String workDir) {
DebugUtil.trace(DebugUtil.SDM_MASTER_TRACING_MORE, Messages.SDMRunner_6, workDir);
this.workDir = workDir;
}
public synchronized SDMMasterState getSdmState() {
return sdmState;
}
protected synchronized void setSdmState(SDMMasterState sdmState) {
DebugUtil.trace(DebugUtil.SDM_MASTER_TRACING_MORE, Messages.SDMRunner_7, sdmState.toString());
this.sdmState = sdmState;
this.notifyAll();
}
public void setJob(IPJob ipJob) {
DebugUtil.trace(DebugUtil.SDM_MASTER_TRACING_MORE, Messages.SDMRunner_8, ipJob.getID());
this.ipJob = ipJob;
}
@Override
protected IStatus run(IProgressMonitor monitor) {
assert command != null;
assert sdmProcess == null;
DebugUtil.trace(DebugUtil.SDM_MASTER_TRACING, Messages.SDMRunner_9);
/*
* Catch all try...catch
*/
try {
if (monitor.isCanceled()) {
throw new InterruptedException();
}
/*
* Prepare remote connection.
*/
IResourceManagerConfiguration configuration = rmControl.getConfiguration();
IRemoteServices remoteServices = PTPRemoteCorePlugin.getDefault().getRemoteServices(
configuration.getRemoteServicesId(), monitor);
IRemoteConnectionManager connectionManager = remoteServices.getConnectionManager();
IRemoteConnection connection = connectionManager.getConnection(configuration.getConnectionName());
IRemoteFileManager fileManager = remoteServices.getFileManager(connection);
IRemoteProcessBuilder sdmProcessBuilder = remoteServices.getProcessBuilder(connection, command);
if (workDir != null) {
sdmProcessBuilder.directory(fileManager.getResource(workDir));
}
/*
* Wait some time to assure that SDM servers and front end have
* started.
*/
DebugUtil.trace(DebugUtil.SDM_MASTER_TRACING, Messages.SDMRunner_10);
if (monitor.isCanceled()) {
throw new InterruptedException();
}
synchronized (this) {
wait(3000);
}
/*
* Create process.
*/
DebugUtil.trace(DebugUtil.SDM_MASTER_TRACING, Messages.SDMRunner_11);
if (monitor.isCanceled()) {
throw new InterruptedException();
}
synchronized (this) {
sdmProcess = sdmProcessBuilder.start();
}
final BufferedReader err_reader = new BufferedReader(new InputStreamReader(sdmProcess.getErrorStream()));
final BufferedReader out_reader = new BufferedReader(new InputStreamReader(sdmProcess.getInputStream()));
if (DebugUtil.SDM_MASTER_OUTPUT_TRACING) {
new Thread(new Runnable() {
public void run() {
try {
String output;
while ((output = out_reader.readLine()) != null) {
System.out.println(Messages.SDMRunner_12 + output);
}
} catch (IOException e) {
// Ignore
}
}
}, Messages.SDMRunner_13).start();
}
if (DebugUtil.SDM_MASTER_OUTPUT_TRACING) {
new Thread(new Runnable() {
public void run() {
try {
String line;
while ((line = err_reader.readLine()) != null) {
System.err.println(Messages.SDMRunner_14 + line);
}
} catch (IOException e) {
// Ignore
}
}
}, Messages.SDMRunner_15).start();
}
/*
* Wait while running but not canceled.
*/
setSdmState(SDMMasterState.RUNNING);
DebugUtil.trace(DebugUtil.SDM_MASTER_TRACING_MORE, Messages.SDMRunner_16);
while (!sdmProcess.isCompleted()) {
synchronized (this) {
wait(500);
}
if (monitor.isCanceled()) {
throw new InterruptedException();
}
}
/*
* Check if process terminated successfully (if not canceled).
*/
DebugUtil.trace(DebugUtil.SDM_MASTER_TRACING, Messages.SDMRunner_17, sdmProcess.exitValue());
if (sdmProcess.exitValue() != 0) {
if (!monitor.isCanceled()) {
throw new CoreException(new Status(IStatus.ERROR, SDMDebugCorePlugin.getUniqueIdentifier(), NLS.bind(
Messages.SDMRunner_2, sdmProcess.exitValue())));
} else {
DebugUtil.trace(DebugUtil.SDM_MASTER_TRACING, Messages.SDMRunner_18);
}
}
setSdmState(SDMMasterState.FINISHED);
return Status.OK_STATUS;
} catch (Exception e) {
/*
* Terminate the job, handling the error. Also terminates the ipjob
* since it does not make sense to the ipjob running without
* debugger.
*/
DebugUtil.error(DebugUtil.SDM_MASTER_TRACING, Messages.SDMRunner_19, e);
- setSdmState(SDMMasterState.ERROR);
synchronized (this) {
DebugUtil.error(DebugUtil.SDM_MASTER_TRACING, Messages.SDMRunner_20, e);
sdmProcess.destroy();
}
try {
DebugUtil.trace(DebugUtil.SDM_MASTER_TRACING, Messages.SDMRunner_21, ipJob.getID());
rmControl.terminateJob(ipJob);
} catch (CoreException e1) {
PTPDebugCorePlugin.log(e1);
}
if (e instanceof InterruptedException) {
+ setSdmState(SDMMasterState.FINISHED);
return Status.CANCEL_STATUS;
} else if (e instanceof CoreException) {
+ setSdmState(SDMMasterState.ERROR);
return ((CoreException) e).getStatus();
} else {
+ setSdmState(SDMMasterState.ERROR);
return new Status(IStatus.ERROR, SDMDebugCorePlugin.getUniqueIdentifier(), Messages.SDMRunner_3, e);
}
} finally {
DebugUtil.trace(DebugUtil.SDM_MASTER_TRACING, Messages.SDMRunner_22);
synchronized (this) {
sdmProcess = null;
}
}
}
@Override
protected void canceling() {
synchronized (this) {
if (sdmProcess != null) {
sdmProcess.destroy();
}
}
}
}
| false | true | protected IStatus run(IProgressMonitor monitor) {
assert command != null;
assert sdmProcess == null;
DebugUtil.trace(DebugUtil.SDM_MASTER_TRACING, Messages.SDMRunner_9);
/*
* Catch all try...catch
*/
try {
if (monitor.isCanceled()) {
throw new InterruptedException();
}
/*
* Prepare remote connection.
*/
IResourceManagerConfiguration configuration = rmControl.getConfiguration();
IRemoteServices remoteServices = PTPRemoteCorePlugin.getDefault().getRemoteServices(
configuration.getRemoteServicesId(), monitor);
IRemoteConnectionManager connectionManager = remoteServices.getConnectionManager();
IRemoteConnection connection = connectionManager.getConnection(configuration.getConnectionName());
IRemoteFileManager fileManager = remoteServices.getFileManager(connection);
IRemoteProcessBuilder sdmProcessBuilder = remoteServices.getProcessBuilder(connection, command);
if (workDir != null) {
sdmProcessBuilder.directory(fileManager.getResource(workDir));
}
/*
* Wait some time to assure that SDM servers and front end have
* started.
*/
DebugUtil.trace(DebugUtil.SDM_MASTER_TRACING, Messages.SDMRunner_10);
if (monitor.isCanceled()) {
throw new InterruptedException();
}
synchronized (this) {
wait(3000);
}
/*
* Create process.
*/
DebugUtil.trace(DebugUtil.SDM_MASTER_TRACING, Messages.SDMRunner_11);
if (monitor.isCanceled()) {
throw new InterruptedException();
}
synchronized (this) {
sdmProcess = sdmProcessBuilder.start();
}
final BufferedReader err_reader = new BufferedReader(new InputStreamReader(sdmProcess.getErrorStream()));
final BufferedReader out_reader = new BufferedReader(new InputStreamReader(sdmProcess.getInputStream()));
if (DebugUtil.SDM_MASTER_OUTPUT_TRACING) {
new Thread(new Runnable() {
public void run() {
try {
String output;
while ((output = out_reader.readLine()) != null) {
System.out.println(Messages.SDMRunner_12 + output);
}
} catch (IOException e) {
// Ignore
}
}
}, Messages.SDMRunner_13).start();
}
if (DebugUtil.SDM_MASTER_OUTPUT_TRACING) {
new Thread(new Runnable() {
public void run() {
try {
String line;
while ((line = err_reader.readLine()) != null) {
System.err.println(Messages.SDMRunner_14 + line);
}
} catch (IOException e) {
// Ignore
}
}
}, Messages.SDMRunner_15).start();
}
/*
* Wait while running but not canceled.
*/
setSdmState(SDMMasterState.RUNNING);
DebugUtil.trace(DebugUtil.SDM_MASTER_TRACING_MORE, Messages.SDMRunner_16);
while (!sdmProcess.isCompleted()) {
synchronized (this) {
wait(500);
}
if (monitor.isCanceled()) {
throw new InterruptedException();
}
}
/*
* Check if process terminated successfully (if not canceled).
*/
DebugUtil.trace(DebugUtil.SDM_MASTER_TRACING, Messages.SDMRunner_17, sdmProcess.exitValue());
if (sdmProcess.exitValue() != 0) {
if (!monitor.isCanceled()) {
throw new CoreException(new Status(IStatus.ERROR, SDMDebugCorePlugin.getUniqueIdentifier(), NLS.bind(
Messages.SDMRunner_2, sdmProcess.exitValue())));
} else {
DebugUtil.trace(DebugUtil.SDM_MASTER_TRACING, Messages.SDMRunner_18);
}
}
setSdmState(SDMMasterState.FINISHED);
return Status.OK_STATUS;
} catch (Exception e) {
/*
* Terminate the job, handling the error. Also terminates the ipjob
* since it does not make sense to the ipjob running without
* debugger.
*/
DebugUtil.error(DebugUtil.SDM_MASTER_TRACING, Messages.SDMRunner_19, e);
setSdmState(SDMMasterState.ERROR);
synchronized (this) {
DebugUtil.error(DebugUtil.SDM_MASTER_TRACING, Messages.SDMRunner_20, e);
sdmProcess.destroy();
}
try {
DebugUtil.trace(DebugUtil.SDM_MASTER_TRACING, Messages.SDMRunner_21, ipJob.getID());
rmControl.terminateJob(ipJob);
} catch (CoreException e1) {
PTPDebugCorePlugin.log(e1);
}
if (e instanceof InterruptedException) {
return Status.CANCEL_STATUS;
} else if (e instanceof CoreException) {
return ((CoreException) e).getStatus();
} else {
return new Status(IStatus.ERROR, SDMDebugCorePlugin.getUniqueIdentifier(), Messages.SDMRunner_3, e);
}
} finally {
DebugUtil.trace(DebugUtil.SDM_MASTER_TRACING, Messages.SDMRunner_22);
synchronized (this) {
sdmProcess = null;
}
}
}
| protected IStatus run(IProgressMonitor monitor) {
assert command != null;
assert sdmProcess == null;
DebugUtil.trace(DebugUtil.SDM_MASTER_TRACING, Messages.SDMRunner_9);
/*
* Catch all try...catch
*/
try {
if (monitor.isCanceled()) {
throw new InterruptedException();
}
/*
* Prepare remote connection.
*/
IResourceManagerConfiguration configuration = rmControl.getConfiguration();
IRemoteServices remoteServices = PTPRemoteCorePlugin.getDefault().getRemoteServices(
configuration.getRemoteServicesId(), monitor);
IRemoteConnectionManager connectionManager = remoteServices.getConnectionManager();
IRemoteConnection connection = connectionManager.getConnection(configuration.getConnectionName());
IRemoteFileManager fileManager = remoteServices.getFileManager(connection);
IRemoteProcessBuilder sdmProcessBuilder = remoteServices.getProcessBuilder(connection, command);
if (workDir != null) {
sdmProcessBuilder.directory(fileManager.getResource(workDir));
}
/*
* Wait some time to assure that SDM servers and front end have
* started.
*/
DebugUtil.trace(DebugUtil.SDM_MASTER_TRACING, Messages.SDMRunner_10);
if (monitor.isCanceled()) {
throw new InterruptedException();
}
synchronized (this) {
wait(3000);
}
/*
* Create process.
*/
DebugUtil.trace(DebugUtil.SDM_MASTER_TRACING, Messages.SDMRunner_11);
if (monitor.isCanceled()) {
throw new InterruptedException();
}
synchronized (this) {
sdmProcess = sdmProcessBuilder.start();
}
final BufferedReader err_reader = new BufferedReader(new InputStreamReader(sdmProcess.getErrorStream()));
final BufferedReader out_reader = new BufferedReader(new InputStreamReader(sdmProcess.getInputStream()));
if (DebugUtil.SDM_MASTER_OUTPUT_TRACING) {
new Thread(new Runnable() {
public void run() {
try {
String output;
while ((output = out_reader.readLine()) != null) {
System.out.println(Messages.SDMRunner_12 + output);
}
} catch (IOException e) {
// Ignore
}
}
}, Messages.SDMRunner_13).start();
}
if (DebugUtil.SDM_MASTER_OUTPUT_TRACING) {
new Thread(new Runnable() {
public void run() {
try {
String line;
while ((line = err_reader.readLine()) != null) {
System.err.println(Messages.SDMRunner_14 + line);
}
} catch (IOException e) {
// Ignore
}
}
}, Messages.SDMRunner_15).start();
}
/*
* Wait while running but not canceled.
*/
setSdmState(SDMMasterState.RUNNING);
DebugUtil.trace(DebugUtil.SDM_MASTER_TRACING_MORE, Messages.SDMRunner_16);
while (!sdmProcess.isCompleted()) {
synchronized (this) {
wait(500);
}
if (monitor.isCanceled()) {
throw new InterruptedException();
}
}
/*
* Check if process terminated successfully (if not canceled).
*/
DebugUtil.trace(DebugUtil.SDM_MASTER_TRACING, Messages.SDMRunner_17, sdmProcess.exitValue());
if (sdmProcess.exitValue() != 0) {
if (!monitor.isCanceled()) {
throw new CoreException(new Status(IStatus.ERROR, SDMDebugCorePlugin.getUniqueIdentifier(), NLS.bind(
Messages.SDMRunner_2, sdmProcess.exitValue())));
} else {
DebugUtil.trace(DebugUtil.SDM_MASTER_TRACING, Messages.SDMRunner_18);
}
}
setSdmState(SDMMasterState.FINISHED);
return Status.OK_STATUS;
} catch (Exception e) {
/*
* Terminate the job, handling the error. Also terminates the ipjob
* since it does not make sense to the ipjob running without
* debugger.
*/
DebugUtil.error(DebugUtil.SDM_MASTER_TRACING, Messages.SDMRunner_19, e);
synchronized (this) {
DebugUtil.error(DebugUtil.SDM_MASTER_TRACING, Messages.SDMRunner_20, e);
sdmProcess.destroy();
}
try {
DebugUtil.trace(DebugUtil.SDM_MASTER_TRACING, Messages.SDMRunner_21, ipJob.getID());
rmControl.terminateJob(ipJob);
} catch (CoreException e1) {
PTPDebugCorePlugin.log(e1);
}
if (e instanceof InterruptedException) {
setSdmState(SDMMasterState.FINISHED);
return Status.CANCEL_STATUS;
} else if (e instanceof CoreException) {
setSdmState(SDMMasterState.ERROR);
return ((CoreException) e).getStatus();
} else {
setSdmState(SDMMasterState.ERROR);
return new Status(IStatus.ERROR, SDMDebugCorePlugin.getUniqueIdentifier(), Messages.SDMRunner_3, e);
}
} finally {
DebugUtil.trace(DebugUtil.SDM_MASTER_TRACING, Messages.SDMRunner_22);
synchronized (this) {
sdmProcess = null;
}
}
}
|
diff --git a/src/main/java/org/amplafi/flow/flowproperty/ReflectionFlowPropertyValueProvider.java b/src/main/java/org/amplafi/flow/flowproperty/ReflectionFlowPropertyValueProvider.java
index 66e53df..21c46f6 100644
--- a/src/main/java/org/amplafi/flow/flowproperty/ReflectionFlowPropertyValueProvider.java
+++ b/src/main/java/org/amplafi/flow/flowproperty/ReflectionFlowPropertyValueProvider.java
@@ -1,100 +1,102 @@
/*
* 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.amplafi.flow.flowproperty;
import org.amplafi.flow.FlowPropertyValueProvider;
import org.amplafi.flow.FlowPropertyDefinition;
import com.sworddance.beans.BeanWorker;
/**
* Uses reflection to trace to find the property value.
* if at any point a null is returned then null is returned (no {@link NullPointerException} will be thrown)
*
* The root object can be either the flowPropertyProvider parameter in the {@link #get(FlowPropertyProvider, FlowPropertyDefinition)} call or another object
* supplied in the constructor.
*
* TODO need to be able to set base as a String and that is the property name that will act as the base.
* example: "messagePoint" means:
* 1) retrieve "messagePoint"
* 2) do reflection using the propertyNames to get the value.
*
* TODO: Create ability to define the {@link FlowPropertyDefinitionImpl} Default property name would be the last property in the list. So "httpManager.cachedUris" would define
* the "cachedUris" property (default)
*
* @author patmoore
*
*/
public class ReflectionFlowPropertyValueProvider extends BeanWorker implements FlowPropertyValueProvider<FlowPropertyProvider> {
private Object object;
/**
* Use the {@link FlowPropertyProvider} that is passed in the {@link #get(FlowPropertyProvider, FlowPropertyDefinition)} as the starting object to trace for
* using propertyNames.
*
* @param propertyNames
*/
public ReflectionFlowPropertyValueProvider(String propertyNames) {
super(propertyNames);
}
public ReflectionFlowPropertyValueProvider(Object object, String... propertyNames) {
super(propertyNames);
this.object = object;
}
/**
* Used when an object other than the flowPropertyProvider passed in the {@link #get(FlowPropertyProvider, FlowPropertyDefinition)} should be used
* as the root for tracing out properties.
* @param object
*/
public void setObject(Object object) {
this.object = object;
}
/**
* @return the object
*/
public Object getObject() {
return object;
}
/**
*
* @see org.amplafi.flow.FlowPropertyValueProvider#get(org.amplafi.flow.flowproperty.FlowPropertyProvider, org.amplafi.flow.FlowPropertyDefinition)
*/
@SuppressWarnings("unchecked")
@Override
public <T> T get(FlowPropertyProvider flowPropertyProvider, FlowPropertyDefinition flowPropertyDefinition) {
final Object base = this.object==null?flowPropertyProvider:this.object;
return (T) getValue(base, this.getPropertyName(0));
}
/**
* @see org.amplafi.flow.FlowPropertyValueProvider#getFlowPropertyProviderClass()
*/
@Override
public Class<FlowPropertyProvider> getFlowPropertyProviderClass() {
return FlowPropertyProvider.class;
}
@Override
public boolean isHandling(FlowPropertyDefinition flowPropertyDefinition) {
- for(String propertyName:this.getPropertyNames()) {
- if ( flowPropertyDefinition.isNamed(propertyName)) {
+ for(String complexPropertyName:this.getPropertyNames()) {
+ int beginIndex = complexPropertyName.lastIndexOf('.');
+ String simplePropertyName = beginIndex < 0?complexPropertyName:complexPropertyName.substring(beginIndex+1);
+ if ( flowPropertyDefinition.isNamed(simplePropertyName)) {
return true;
}
}
return false;
}
}
| true | true | public boolean isHandling(FlowPropertyDefinition flowPropertyDefinition) {
for(String propertyName:this.getPropertyNames()) {
if ( flowPropertyDefinition.isNamed(propertyName)) {
return true;
}
}
return false;
}
| public boolean isHandling(FlowPropertyDefinition flowPropertyDefinition) {
for(String complexPropertyName:this.getPropertyNames()) {
int beginIndex = complexPropertyName.lastIndexOf('.');
String simplePropertyName = beginIndex < 0?complexPropertyName:complexPropertyName.substring(beginIndex+1);
if ( flowPropertyDefinition.isNamed(simplePropertyName)) {
return true;
}
}
return false;
}
|
diff --git a/grid-incubation/incubator/projects/iso21090/projects/iso21090SdkQueryProcessor/test/src/org/cagrid/iso21090/tests/integration/story/SDK43DataServiceSystemTests.java b/grid-incubation/incubator/projects/iso21090/projects/iso21090SdkQueryProcessor/test/src/org/cagrid/iso21090/tests/integration/story/SDK43DataServiceSystemTests.java
index 2619bf96..9b855662 100644
--- a/grid-incubation/incubator/projects/iso21090/projects/iso21090SdkQueryProcessor/test/src/org/cagrid/iso21090/tests/integration/story/SDK43DataServiceSystemTests.java
+++ b/grid-incubation/incubator/projects/iso21090/projects/iso21090SdkQueryProcessor/test/src/org/cagrid/iso21090/tests/integration/story/SDK43DataServiceSystemTests.java
@@ -1,84 +1,84 @@
package org.cagrid.iso21090.tests.integration.story;
import gov.nih.nci.cagrid.common.Utils;
import java.io.File;
import junit.framework.TestResult;
import junit.framework.TestSuite;
import junit.textui.TestRunner;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.cagrid.iso21090.tests.integration.steps.SdkDestroyDatabaseStep;
import org.junit.After;
import org.junit.Test;
public class SDK43DataServiceSystemTests {
private static Log LOG = LogFactory.getLog(SDK43DataServiceSystemTests.class);
private long lastTime = 0;
private File tempApplicationDir = null;
@Test
- public void sdk42DataServiceSystemTests() throws Throwable {
+ public void sdk43DataServiceSystemTests() throws Throwable {
// create a temporary directory for the SDK application to package things in
tempApplicationDir = File.createTempFile("SdkWithIsoExample", "temp");
tempApplicationDir.delete();
tempApplicationDir.mkdirs();
LOG.debug("Created temp application base dir: " + tempApplicationDir.getAbsolutePath());
// create the caCORE SDK example project
splitTime();
LOG.debug("Running caCORE SDK example project creation story");
CreateExampleProjectStory createExampleStory = new CreateExampleProjectStory(tempApplicationDir);
createExampleStory.runBare();
// create and run a caGrid Data Service using the SDK's local API
splitTime();
LOG.debug("Running data service using local API story");
SDK43StyleLocalApiStory localApiStory = new SDK43StyleLocalApiStory();
localApiStory.runBare();
// create and run a caGrid Data Service using the SDK's remote API
splitTime();
LOG.debug("Running data service using remote API story");
SDK43StyleRemoteApiStory remoteApiStory = new SDK43StyleRemoteApiStory();
remoteApiStory.runBare();
}
@After
public void cleanUp() {
LOG.debug("Cleaning up after tests");
// tear down the sdk example database
try {
new SdkDestroyDatabaseStep().runStep();
} catch (Exception ex) {
LOG.warn("Error destroying SDK example project database: " + ex.getMessage());
ex.printStackTrace();
}
// throw away the temp sdk dir
LOG.debug("Deleting temp application base dir: " + tempApplicationDir.getAbsolutePath());
Utils.deleteDir(tempApplicationDir);
}
private void splitTime() {
if (lastTime == 0) {
LOG.debug("Timer started");
} else {
LOG.debug("Time elapsed: "
+ (System.currentTimeMillis() - lastTime) / 1000D + " sec");
}
lastTime = System.currentTimeMillis();
}
public static void main(String[] args) {
TestRunner runner = new TestRunner();
TestResult result = runner.doRun(new TestSuite(SDK43DataServiceSystemTests.class));
System.exit(result.errorCount() + result.failureCount());
}
}
| true | true | public void sdk42DataServiceSystemTests() throws Throwable {
// create a temporary directory for the SDK application to package things in
tempApplicationDir = File.createTempFile("SdkWithIsoExample", "temp");
tempApplicationDir.delete();
tempApplicationDir.mkdirs();
LOG.debug("Created temp application base dir: " + tempApplicationDir.getAbsolutePath());
// create the caCORE SDK example project
splitTime();
LOG.debug("Running caCORE SDK example project creation story");
CreateExampleProjectStory createExampleStory = new CreateExampleProjectStory(tempApplicationDir);
createExampleStory.runBare();
// create and run a caGrid Data Service using the SDK's local API
splitTime();
LOG.debug("Running data service using local API story");
SDK43StyleLocalApiStory localApiStory = new SDK43StyleLocalApiStory();
localApiStory.runBare();
// create and run a caGrid Data Service using the SDK's remote API
splitTime();
LOG.debug("Running data service using remote API story");
SDK43StyleRemoteApiStory remoteApiStory = new SDK43StyleRemoteApiStory();
remoteApiStory.runBare();
}
| public void sdk43DataServiceSystemTests() throws Throwable {
// create a temporary directory for the SDK application to package things in
tempApplicationDir = File.createTempFile("SdkWithIsoExample", "temp");
tempApplicationDir.delete();
tempApplicationDir.mkdirs();
LOG.debug("Created temp application base dir: " + tempApplicationDir.getAbsolutePath());
// create the caCORE SDK example project
splitTime();
LOG.debug("Running caCORE SDK example project creation story");
CreateExampleProjectStory createExampleStory = new CreateExampleProjectStory(tempApplicationDir);
createExampleStory.runBare();
// create and run a caGrid Data Service using the SDK's local API
splitTime();
LOG.debug("Running data service using local API story");
SDK43StyleLocalApiStory localApiStory = new SDK43StyleLocalApiStory();
localApiStory.runBare();
// create and run a caGrid Data Service using the SDK's remote API
splitTime();
LOG.debug("Running data service using remote API story");
SDK43StyleRemoteApiStory remoteApiStory = new SDK43StyleRemoteApiStory();
remoteApiStory.runBare();
}
|
diff --git a/src/com/herocraftonline/dev/heroes/skill/skills/SkillGills.java b/src/com/herocraftonline/dev/heroes/skill/skills/SkillGills.java
index 1ee6c697..9ce49757 100644
--- a/src/com/herocraftonline/dev/heroes/skill/skills/SkillGills.java
+++ b/src/com/herocraftonline/dev/heroes/skill/skills/SkillGills.java
@@ -1,37 +1,37 @@
package com.herocraftonline.dev.heroes.skill.skills;
import org.bukkit.entity.Player;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityListener;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import com.herocraftonline.dev.heroes.Heroes;
import com.herocraftonline.dev.heroes.persistence.Hero;
import com.herocraftonline.dev.heroes.skill.PassiveSkill;
public class SkillGills extends PassiveSkill {
public SkillGills(Heroes plugin) {
super(plugin);
name = "Gills";
description = "Negate drowning damage";
minArgs = 0;
maxArgs = 0;
}
public class SkillPlayerListener extends EntityListener {
public void onEntityDamage(EntityDamageEvent event) {
if (event.isCancelled() || !(event.getCause() == DamageCause.DROWNING)) {
return;
}
if (event.getEntity() instanceof Player) {
Player player = (Player) event.getEntity();
Hero hero = plugin.getHeroManager().getHero(player);
if (hero.getEffects().hasEffect(name)) {
- event.setDamage(0);
+ event.setCancelled(true);
}
}
}
}
}
| true | true | public void onEntityDamage(EntityDamageEvent event) {
if (event.isCancelled() || !(event.getCause() == DamageCause.DROWNING)) {
return;
}
if (event.getEntity() instanceof Player) {
Player player = (Player) event.getEntity();
Hero hero = plugin.getHeroManager().getHero(player);
if (hero.getEffects().hasEffect(name)) {
event.setDamage(0);
}
}
}
| public void onEntityDamage(EntityDamageEvent event) {
if (event.isCancelled() || !(event.getCause() == DamageCause.DROWNING)) {
return;
}
if (event.getEntity() instanceof Player) {
Player player = (Player) event.getEntity();
Hero hero = plugin.getHeroManager().getHero(player);
if (hero.getEffects().hasEffect(name)) {
event.setCancelled(true);
}
}
}
|
diff --git a/src/main/java/lcmc/robotest/PcmkTestH.java b/src/main/java/lcmc/robotest/PcmkTestH.java
index f8da24fb..11b6ab87 100644
--- a/src/main/java/lcmc/robotest/PcmkTestH.java
+++ b/src/main/java/lcmc/robotest/PcmkTestH.java
@@ -1,119 +1,121 @@
/*
* This file is part of LCMC written by Rasto Levrinc.
*
* Copyright (C) 2013, Rastislav Levrinc.
*
* The LCMC is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as published
* by the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* The LCMC 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 LCMC; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package lcmc.robotest;
import static lcmc.robotest.RoboTest.*;
import java.awt.event.KeyEvent;
import lcmc.gui.widget.MComboBox;
import lcmc.utilities.Tools;
import lcmc.utilities.Logger;
import lcmc.utilities.LoggerFactory;
/**
* This class is used to test the GUI.
*
* @author Rasto Levrinc
*/
final class PcmkTestH {
/** Logger. */
private static final Logger LOG = LoggerFactory.getLogger(PcmkTestH.class);
/** Private constructor, cannot be instantiated. */
private PcmkTestH() {
/* Cannot be instantiated. */
}
/** Create ipmi resource. */
private static void chooseIpmi(final int x,
final int y,
final boolean apply) {
moveTo(x, y);
rightClick(); /* popup */
sleep(1000);
moveTo(Tools.getString("ClusterBrowser.Hb.AddService"));
sleep(1000);
moveTo("Filesystem + Linbit:DRBD");
moveTo("Stonith Devices");
sleep(2000);
press(KeyEvent.VK_I);
sleep(200);
press(KeyEvent.VK_P);
sleep(200);
press(KeyEvent.VK_M);
sleep(200);
press(KeyEvent.VK_I);
sleep(200);
press(KeyEvent.VK_ENTER);
sleep(200);
moveTo("Target Role", MComboBox.class);
sleep(2000);
leftClick(); /* pull down */
press(KeyEvent.VK_DOWN);
sleep(500);
press(KeyEvent.VK_DOWN);
sleep(500);
+ press(KeyEvent.VK_DOWN);
+ sleep(500);
press(KeyEvent.VK_ENTER);
sleep(500);
if (apply) {
sleep(2000);
moveTo(Tools.getString("Browser.ApplyResource"));
sleep(4000);
leftClick();
sleep(2000);
}
}
static void start(final int count) {
slowFactor = 0.5f;
aborted = false;
final int ipmiX = 235;
final int ipmiY = 207;
disableStonith();
for (int i = count; i > 0; i--) {
if (i % 5 == 0) {
info("testH I: " + i);
}
checkTest("testH", 1);
/* create ipmi res */
sleep(5000);
chooseIpmi(ipmiX, ipmiY, true);
checkTest("testH", 3);
sleep(5000);
/* copy/paste */
moveTo(ipmiX + 10 , ipmiY + 10);
leftClick();
robot.keyPress(KeyEvent.VK_CONTROL);
press(KeyEvent.VK_C);
press(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
moveTo(ipmiX + 10 , ipmiY + 90);
leftClick();
moveTo(Tools.getString("Browser.ApplyResource"));
sleep(4000);
leftClick();
checkTest("testH", 4);
removeResource(ipmiX, ipmiY, CONFIRM_REMOVE);
removeResource(ipmiX, ipmiY + 90, CONFIRM_REMOVE);
}
System.gc();
}
}
| true | true | private static void chooseIpmi(final int x,
final int y,
final boolean apply) {
moveTo(x, y);
rightClick(); /* popup */
sleep(1000);
moveTo(Tools.getString("ClusterBrowser.Hb.AddService"));
sleep(1000);
moveTo("Filesystem + Linbit:DRBD");
moveTo("Stonith Devices");
sleep(2000);
press(KeyEvent.VK_I);
sleep(200);
press(KeyEvent.VK_P);
sleep(200);
press(KeyEvent.VK_M);
sleep(200);
press(KeyEvent.VK_I);
sleep(200);
press(KeyEvent.VK_ENTER);
sleep(200);
moveTo("Target Role", MComboBox.class);
sleep(2000);
leftClick(); /* pull down */
press(KeyEvent.VK_DOWN);
sleep(500);
press(KeyEvent.VK_DOWN);
sleep(500);
press(KeyEvent.VK_ENTER);
sleep(500);
if (apply) {
sleep(2000);
moveTo(Tools.getString("Browser.ApplyResource"));
sleep(4000);
leftClick();
sleep(2000);
}
}
| private static void chooseIpmi(final int x,
final int y,
final boolean apply) {
moveTo(x, y);
rightClick(); /* popup */
sleep(1000);
moveTo(Tools.getString("ClusterBrowser.Hb.AddService"));
sleep(1000);
moveTo("Filesystem + Linbit:DRBD");
moveTo("Stonith Devices");
sleep(2000);
press(KeyEvent.VK_I);
sleep(200);
press(KeyEvent.VK_P);
sleep(200);
press(KeyEvent.VK_M);
sleep(200);
press(KeyEvent.VK_I);
sleep(200);
press(KeyEvent.VK_ENTER);
sleep(200);
moveTo("Target Role", MComboBox.class);
sleep(2000);
leftClick(); /* pull down */
press(KeyEvent.VK_DOWN);
sleep(500);
press(KeyEvent.VK_DOWN);
sleep(500);
press(KeyEvent.VK_DOWN);
sleep(500);
press(KeyEvent.VK_ENTER);
sleep(500);
if (apply) {
sleep(2000);
moveTo(Tools.getString("Browser.ApplyResource"));
sleep(4000);
leftClick();
sleep(2000);
}
}
|
diff --git a/src/main/java/de/cismet/cismap/commons/gui/piccolo/FixedWidthStroke.java b/src/main/java/de/cismet/cismap/commons/gui/piccolo/FixedWidthStroke.java
index 71970602..c2030091 100755
--- a/src/main/java/de/cismet/cismap/commons/gui/piccolo/FixedWidthStroke.java
+++ b/src/main/java/de/cismet/cismap/commons/gui/piccolo/FixedWidthStroke.java
@@ -1,33 +1,33 @@
/*
* FixedWidthStroke.java
*
* Created on 16. M\u00E4rz 2005, 15:55
*/
package de.cismet.cismap.commons.gui.piccolo;
import java.awt.BasicStroke;
/**
*
* @author hell
*/
public class FixedWidthStroke extends BasicStroke {
private final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(this.getClass());
protected float multiplyer = 1.0f;
@Override
public float getLineWidth() {
- return 0.001f;
+ return 0.0000000001f; //wegen wgs84
// if (PPaintContext.CURRENT_PAINT_CONTEXT != null) {
// //log.fatal("LineWidth:"+super.getLineWidth() / (float) PPaintContext.CURRENT_PAINT_CONTEXT.getScale());
// return super.getLineWidth()*multiplyer / (float) PPaintContext.CURRENT_PAINT_CONTEXT.getScale();
// }
// else {
// return super.getLineWidth()*multiplyer;
// }
}
public void setMultiplyer(float multiplyer) {
this.multiplyer = multiplyer;
}
}
| true | true | public float getLineWidth() {
return 0.001f;
// if (PPaintContext.CURRENT_PAINT_CONTEXT != null) {
// //log.fatal("LineWidth:"+super.getLineWidth() / (float) PPaintContext.CURRENT_PAINT_CONTEXT.getScale());
// return super.getLineWidth()*multiplyer / (float) PPaintContext.CURRENT_PAINT_CONTEXT.getScale();
// }
// else {
// return super.getLineWidth()*multiplyer;
// }
}
| public float getLineWidth() {
return 0.0000000001f; //wegen wgs84
// if (PPaintContext.CURRENT_PAINT_CONTEXT != null) {
// //log.fatal("LineWidth:"+super.getLineWidth() / (float) PPaintContext.CURRENT_PAINT_CONTEXT.getScale());
// return super.getLineWidth()*multiplyer / (float) PPaintContext.CURRENT_PAINT_CONTEXT.getScale();
// }
// else {
// return super.getLineWidth()*multiplyer;
// }
}
|
diff --git a/src/com/java/gwt/libertycinema/client/BaseLayout.java b/src/com/java/gwt/libertycinema/client/BaseLayout.java
index 9c5da82..8b4c916 100644
--- a/src/com/java/gwt/libertycinema/client/BaseLayout.java
+++ b/src/com/java/gwt/libertycinema/client/BaseLayout.java
@@ -1,58 +1,58 @@
package com.java.gwt.libertycinema.client;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DockLayoutPanel;
public class BaseLayout extends Composite {
private DockLayoutPanel layout = new DockLayoutPanel(Unit.EM);
private HeaderBar headerBar;
private MainPanel mainPanel;
private FooterBar footerBar;
public BaseLayout() {
headerBar = new HeaderBar(this);
- footerBar = new FooterBar();
+ footerBar = new FooterBar(this);
mainPanel = new MainPanel(this);
layout.addNorth(headerBar, 5);
layout.addSouth(footerBar, 2);
layout.add(mainPanel);
initWidget(layout);
}
public DockLayoutPanel getLayout() {
return layout;
}
public void setLayout(DockLayoutPanel layout) {
this.layout = layout;
}
public HeaderBar getHeaderBar() {
return headerBar;
}
public void setHeaderBar(HeaderBar headerBar) {
this.headerBar = headerBar;
}
public MainPanel getMainPanel() {
return mainPanel;
}
public void setMainPanel(MainPanel mainPanel) {
this.mainPanel = mainPanel;
}
public FooterBar getFooterBar() {
return footerBar;
}
public void setFooterBar(FooterBar footerBar) {
this.footerBar = footerBar;
}
}
| true | true | public BaseLayout() {
headerBar = new HeaderBar(this);
footerBar = new FooterBar();
mainPanel = new MainPanel(this);
layout.addNorth(headerBar, 5);
layout.addSouth(footerBar, 2);
layout.add(mainPanel);
initWidget(layout);
}
| public BaseLayout() {
headerBar = new HeaderBar(this);
footerBar = new FooterBar(this);
mainPanel = new MainPanel(this);
layout.addNorth(headerBar, 5);
layout.addSouth(footerBar, 2);
layout.add(mainPanel);
initWidget(layout);
}
|
diff --git a/metamer/ftest/src/test/java/org/richfaces/tests/metamer/ftest/richPickList/TestPickListFragment.java b/metamer/ftest/src/test/java/org/richfaces/tests/metamer/ftest/richPickList/TestPickListFragment.java
index 9f1f1249f..c1b8fc5dd 100644
--- a/metamer/ftest/src/test/java/org/richfaces/tests/metamer/ftest/richPickList/TestPickListFragment.java
+++ b/metamer/ftest/src/test/java/org/richfaces/tests/metamer/ftest/richPickList/TestPickListFragment.java
@@ -1,126 +1,126 @@
/*******************************************************************************
* JBoss, Home of Professional Open Source
* Copyright 2010-2013, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*******************************************************************************/
package org.richfaces.tests.metamer.ftest.richPickList;
import static org.jboss.test.selenium.support.url.URLUtils.buildUrl;
import static org.testng.Assert.assertEquals;
import java.net.URL;
import org.openqa.selenium.support.FindBy;
import org.richfaces.fragment.common.picker.ChoicePickerHelper;
import org.richfaces.fragment.pickList.RichFacesPickList;
import org.richfaces.tests.metamer.ftest.AbstractWebDriverTest;
import org.testng.annotations.Test;
/**
*
* @author <a href="mailto:[email protected]">Jiri Stefek</a>
*/
public class TestPickListFragment extends AbstractWebDriverTest {
@FindBy(css = "[id$=pickList]")
private RichFacesPickList pickList;
@Override
public URL getTestUrl() {
return buildUrl(contextPath, "faces/components/richPickList/simple.xhtml");
}
@Test
public void testAdd() {
int sizeS = pickList.advanced().getSourceList().size();
int sizeT = pickList.advanced().getTargetList().size();
assertEquals(sizeT, 0);
String itemText = pickList.advanced().getSourceList().getItem(0).getText();
pickList.add(ChoicePickerHelper.byIndex().index(0));
assertEquals(pickList.advanced().getSourceList().size(), sizeS - 1);
assertEquals(pickList.advanced().getTargetList().size(), sizeT + 1);
assertEquals(pickList.advanced().getTargetList().getItem(0).getText(), itemText);
}
@Test
public void testAddAll() {
int sizeS = pickList.advanced().getSourceList().size();
int sizeT = pickList.advanced().getTargetList().size();
assertEquals(sizeT, 0);
pickList.addAll();
assertEquals(pickList.advanced().getSourceList().size(), 0);
assertEquals(pickList.advanced().getTargetList().size(), sizeS);
}
@Test
public void testAddMultiple() {
int sizeS = pickList.advanced().getSourceList().size();
int sizeT = pickList.advanced().getTargetList().size();
assertEquals(sizeT, 0);
pickList.addMultiple(ChoicePickerHelper.byIndex().first().last().index(7));
assertEquals(pickList.advanced().getSourceList().size(), sizeS - 3);
assertEquals(pickList.advanced().getTargetList().size(), sizeT + 3);
}
@Test
public void testRemove() {
testAdd();
int sizeS = pickList.advanced().getSourceList().size();
int sizeT = pickList.advanced().getTargetList().size();
assertEquals(sizeT, 1);
String itemText = pickList.advanced().getTargetList().getItem(0).getText();
pickList.remove(ChoicePickerHelper.byIndex().index(0));
assertEquals(pickList.advanced().getSourceList().size(), sizeS + 1);
assertEquals(pickList.advanced().getTargetList().size(), sizeT - 1);
- assertEquals(pickList.advanced().getSourceList().getItem(ChoicePickerHelper.byIndex().last()).getText(), itemText);
+ assertEquals(pickList.advanced().getSourceList().getItem(ChoicePickerHelper.byIndex().first()).getText(), itemText);
}
@Test
public void testRemoveAll() {
int sizeS = pickList.advanced().getSourceList().size();
int sizeT = pickList.advanced().getTargetList().size();
testAddMultiple();
pickList.removeAll();
assertEquals(pickList.advanced().getSourceList().size(), sizeS);
assertEquals(pickList.advanced().getTargetList().size(), sizeT);
}
@Test
public void testRemoveMultiple() {
testAddMultiple();
int sizeS = pickList.advanced().getSourceList().size();
int sizeT = pickList.advanced().getTargetList().size();
assertEquals(sizeT, 3);
pickList.removeMultiple(ChoicePickerHelper.byIndex().first().index(1));
assertEquals(pickList.advanced().getSourceList().size(), sizeS + 2);
assertEquals(pickList.advanced().getTargetList().size(), sizeT - 2);
}
}
| true | true | public void testRemove() {
testAdd();
int sizeS = pickList.advanced().getSourceList().size();
int sizeT = pickList.advanced().getTargetList().size();
assertEquals(sizeT, 1);
String itemText = pickList.advanced().getTargetList().getItem(0).getText();
pickList.remove(ChoicePickerHelper.byIndex().index(0));
assertEquals(pickList.advanced().getSourceList().size(), sizeS + 1);
assertEquals(pickList.advanced().getTargetList().size(), sizeT - 1);
assertEquals(pickList.advanced().getSourceList().getItem(ChoicePickerHelper.byIndex().last()).getText(), itemText);
}
| public void testRemove() {
testAdd();
int sizeS = pickList.advanced().getSourceList().size();
int sizeT = pickList.advanced().getTargetList().size();
assertEquals(sizeT, 1);
String itemText = pickList.advanced().getTargetList().getItem(0).getText();
pickList.remove(ChoicePickerHelper.byIndex().index(0));
assertEquals(pickList.advanced().getSourceList().size(), sizeS + 1);
assertEquals(pickList.advanced().getTargetList().size(), sizeT - 1);
assertEquals(pickList.advanced().getSourceList().getItem(ChoicePickerHelper.byIndex().first()).getText(), itemText);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.