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/NearMeServer/src/com/nearme/NearbyPoiServlet.java b/NearMeServer/src/com/nearme/NearbyPoiServlet.java
index 708f327..87a2a0f 100644
--- a/NearMeServer/src/com/nearme/NearbyPoiServlet.java
+++ b/NearMeServer/src/com/nearme/NearbyPoiServlet.java
@@ -1,91 +1,93 @@
package com.nearme;
import java.io.IOException;
import java.lang.reflect.Type;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
/**
* This servlet responds to HTTP GET requests of the form
*
* http://server/nearme/pois/LAT/LONG/RADIUS
*
* where
*
* LAT is a latitude
* LONG is a longitude
* RADIUS is a radius (in metres)
*
* and returns a JSON data structure with a list of Points of Interest
*
* @author twhume
*
*/
public class NearbyPoiServlet extends GenericNearMeServlet {
private static final long serialVersionUID = 4851880984536596503L; // Having this stops Eclipse moaning at us
private static Logger logger = Logger.getLogger(NearbyPoiServlet.class);
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
res.setContentType("application/json");
- logger.debug("url=" + req.getPathInfo() + "?" + req.getQueryString());
- PoiQuery pq = new PoiQuery(req.getPathInfo() + "?" + req.getQueryString());
+ String inPath = req.getPathInfo();
+ if (req.getQueryString()!=null) inPath += ("?" + req.getQueryString());
+ logger.debug("url=" +inPath);
+ PoiQuery pq = new PoiQuery(inPath);
try {
PoiFinder pf = new DatabasePoiFinder(datasource);
UserDAO uf = new UserDAOImpl(datasource);
/* Look up the user, and set their last known position to be the one they've supplied.
* If we don't know them, make a new record for them.
*/
User u = uf.readByDeviceId(pq.getAndroidId());
if (u==null) {
u = new User();
u.setDeviceId(pq.getAndroidId());
u.setMsisdnHash("unknown");
u = uf.write(u);
}
Position currentPos = new Position(pq.getLatitude(), pq.getLongitude());
currentPos.setWhen(new Date());
u.setLastPosition(currentPos);
uf.write(u);
/* Get a list of all nearby points of interest and add in nearby friends */
List<Poi> points = new ArrayList<Poi>();
logger.debug("types="+pq.getTypes());
if (pq.getTypes().size()>0) points.addAll(pf.find(pq));
logger.info("found " + points.size() + " POIs for user " + u.getId() + " within " + pq.getRadius() + " of (" + pq.getLatitude() + "," + pq.getLongitude() + ")");
List<Poi> friends = uf.getNearestUsers(u, pq.getRadius());
logger.info("found " + friends.size() + " friends for user " + u.getId() + " within " + pq.getRadius() + " of (" + pq.getLatitude() + "," + pq.getLongitude() + ")");
points.addAll(friends);
/* Use GSon to serialise this list onto a JSON structure, and send it to the client.
* This is a little bit complicated because we're asking it to serialise a list of stuff;
* see the manual at https://sites.google.com/site/gson/gson-user-guide#TOC-Collections-Examples
* if you /really/ want to find out why...
*/
Gson gson = new Gson();
Type listOfPois = (Type) (new TypeToken<List<Poi>>(){}).getType();
res.getOutputStream().print(gson.toJson(points, listOfPois));
logger.debug("delivered POIs OK");
} catch (SQLException e) {
logger.error(e);
e.printStackTrace();
res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
}
}
| true | true | protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
res.setContentType("application/json");
logger.debug("url=" + req.getPathInfo() + "?" + req.getQueryString());
PoiQuery pq = new PoiQuery(req.getPathInfo() + "?" + req.getQueryString());
try {
PoiFinder pf = new DatabasePoiFinder(datasource);
UserDAO uf = new UserDAOImpl(datasource);
/* Look up the user, and set their last known position to be the one they've supplied.
* If we don't know them, make a new record for them.
*/
User u = uf.readByDeviceId(pq.getAndroidId());
if (u==null) {
u = new User();
u.setDeviceId(pq.getAndroidId());
u.setMsisdnHash("unknown");
u = uf.write(u);
}
Position currentPos = new Position(pq.getLatitude(), pq.getLongitude());
currentPos.setWhen(new Date());
u.setLastPosition(currentPos);
uf.write(u);
/* Get a list of all nearby points of interest and add in nearby friends */
List<Poi> points = new ArrayList<Poi>();
logger.debug("types="+pq.getTypes());
if (pq.getTypes().size()>0) points.addAll(pf.find(pq));
logger.info("found " + points.size() + " POIs for user " + u.getId() + " within " + pq.getRadius() + " of (" + pq.getLatitude() + "," + pq.getLongitude() + ")");
List<Poi> friends = uf.getNearestUsers(u, pq.getRadius());
logger.info("found " + friends.size() + " friends for user " + u.getId() + " within " + pq.getRadius() + " of (" + pq.getLatitude() + "," + pq.getLongitude() + ")");
points.addAll(friends);
/* Use GSon to serialise this list onto a JSON structure, and send it to the client.
* This is a little bit complicated because we're asking it to serialise a list of stuff;
* see the manual at https://sites.google.com/site/gson/gson-user-guide#TOC-Collections-Examples
* if you /really/ want to find out why...
*/
Gson gson = new Gson();
Type listOfPois = (Type) (new TypeToken<List<Poi>>(){}).getType();
res.getOutputStream().print(gson.toJson(points, listOfPois));
logger.debug("delivered POIs OK");
} catch (SQLException e) {
logger.error(e);
e.printStackTrace();
res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
}
| protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
res.setContentType("application/json");
String inPath = req.getPathInfo();
if (req.getQueryString()!=null) inPath += ("?" + req.getQueryString());
logger.debug("url=" +inPath);
PoiQuery pq = new PoiQuery(inPath);
try {
PoiFinder pf = new DatabasePoiFinder(datasource);
UserDAO uf = new UserDAOImpl(datasource);
/* Look up the user, and set their last known position to be the one they've supplied.
* If we don't know them, make a new record for them.
*/
User u = uf.readByDeviceId(pq.getAndroidId());
if (u==null) {
u = new User();
u.setDeviceId(pq.getAndroidId());
u.setMsisdnHash("unknown");
u = uf.write(u);
}
Position currentPos = new Position(pq.getLatitude(), pq.getLongitude());
currentPos.setWhen(new Date());
u.setLastPosition(currentPos);
uf.write(u);
/* Get a list of all nearby points of interest and add in nearby friends */
List<Poi> points = new ArrayList<Poi>();
logger.debug("types="+pq.getTypes());
if (pq.getTypes().size()>0) points.addAll(pf.find(pq));
logger.info("found " + points.size() + " POIs for user " + u.getId() + " within " + pq.getRadius() + " of (" + pq.getLatitude() + "," + pq.getLongitude() + ")");
List<Poi> friends = uf.getNearestUsers(u, pq.getRadius());
logger.info("found " + friends.size() + " friends for user " + u.getId() + " within " + pq.getRadius() + " of (" + pq.getLatitude() + "," + pq.getLongitude() + ")");
points.addAll(friends);
/* Use GSon to serialise this list onto a JSON structure, and send it to the client.
* This is a little bit complicated because we're asking it to serialise a list of stuff;
* see the manual at https://sites.google.com/site/gson/gson-user-guide#TOC-Collections-Examples
* if you /really/ want to find out why...
*/
Gson gson = new Gson();
Type listOfPois = (Type) (new TypeToken<List<Poi>>(){}).getType();
res.getOutputStream().print(gson.toJson(points, listOfPois));
logger.debug("delivered POIs OK");
} catch (SQLException e) {
logger.error(e);
e.printStackTrace();
res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
}
|
diff --git a/webmacro/src/org/webmacro/resource/UrlProvider.java b/webmacro/src/org/webmacro/resource/UrlProvider.java
index beff9d41..4cb29634 100755
--- a/webmacro/src/org/webmacro/resource/UrlProvider.java
+++ b/webmacro/src/org/webmacro/resource/UrlProvider.java
@@ -1,132 +1,138 @@
/*
* Copyright (c) 1998, 1999 Semiotek Inc. All Rights Reserved.
*
* This software is the confidential intellectual property of
* of Semiotek Inc.; it is copyrighted and licensed, not sold.
* You may use it under the terms of the GNU General Public License,
* version 2, as published by the Free Software Foundation. If you
* do not want to use the GPL, you may still use the software after
* purchasing a proprietary developers license from Semiotek Inc.
*
* This software is provided "as is", with NO WARRANTY, not even the
* implied warranties of fitness to purpose, or merchantability. You
* assume all risks and liabilities associated with its use.
*
* See the attached License.html file for details, or contact us
* by e-mail at [email protected] to get a copy.
*/
package org.webmacro.resource;
import java.lang.*;
import java.net.*;
import java.io.*;
import org.webmacro.util.*;
import org.webmacro.*;
import org.webmacro.broker.*;
/**
* This is the canonical provider for mapping URLs to Handlers. The
* reactor will request that the "handler" provider return a Handler
* object when supplied with a URL.
* <p>
* You could implement your own version of this class to return
* handlers based on whatever criteria you wanted.
*/
final public class UrlProvider implements ResourceProvider
{
// STATIC DATA
/**
* Constant that contains the Log and ResourceProvider Type
* served by this class.
*/
final public static String TYPE = "url";
final private static Log _log = new Log("url", "URL Provider");
// RESOURCE PROVIDER API
final static private String[] _types = { TYPE };
/**
* Two thread concurrency--some concurrency is useful
*/
final public int resourceThreads() { return 2; }
/**
* We serve up "url" type resources
*/
final public String[] getTypes() { return _types; }
/**
* Cache fetched URLs for up to 10 minutes.
*/
final public int resourceExpireTime() { return 1000 * 60 * 10; }
/**
* Request a handler, the supplied name is ScriptName
*/
final public void resourceRequest(RequestResourceEvent evt)
throws NotFoundException
{
try {
- URL u = new URL(evt.getName());
+ String name = evt.getName();
+ URL u;
+ if (name.indexOf(":") < 3) {
+ u = new URL("file",null,-1,name);
+ } else {
+ u = new URL(name);
+ }
Reader in = new InputStreamReader(u.openStream());
char buf[] = new char[512];
StringWriter sw = new StringWriter();
int num;
while ( (num = in.read(buf)) != -1 ) {
sw.write(buf, 0, num);
}
evt.set(sw.toString());
in.close();
} catch (Exception e) {
_log.exception(e);
throw new NotFoundException(
"Reactor: Unable to load URL " + evt.getName() + ":" + e);
}
}
/**
* Stop the handler
*/
final public boolean resourceSave(ResourceEvent evt) {
return false;
}
/**
* Unimplemented / does nothing
*/
final public void destroy() { }
/**
* Resource broker will want to init me
*/
public void init(ResourceBroker broker)
{
// do nothing
}
/**
* Unimplemented / does nothing
*/
final public void resourceCreate(CreateResourceEvent evt) { }
/**
* Unimplemented / does nothing
*/
final public boolean resourceDelete(ResourceEvent evt) { return false; }
}
| true | true | final public void resourceRequest(RequestResourceEvent evt)
throws NotFoundException
{
try {
URL u = new URL(evt.getName());
Reader in = new InputStreamReader(u.openStream());
char buf[] = new char[512];
StringWriter sw = new StringWriter();
int num;
while ( (num = in.read(buf)) != -1 ) {
sw.write(buf, 0, num);
}
evt.set(sw.toString());
in.close();
} catch (Exception e) {
_log.exception(e);
throw new NotFoundException(
"Reactor: Unable to load URL " + evt.getName() + ":" + e);
}
}
| final public void resourceRequest(RequestResourceEvent evt)
throws NotFoundException
{
try {
String name = evt.getName();
URL u;
if (name.indexOf(":") < 3) {
u = new URL("file",null,-1,name);
} else {
u = new URL(name);
}
Reader in = new InputStreamReader(u.openStream());
char buf[] = new char[512];
StringWriter sw = new StringWriter();
int num;
while ( (num = in.read(buf)) != -1 ) {
sw.write(buf, 0, num);
}
evt.set(sw.toString());
in.close();
} catch (Exception e) {
_log.exception(e);
throw new NotFoundException(
"Reactor: Unable to load URL " + evt.getName() + ":" + e);
}
}
|
diff --git a/CubicUnitExporter/src/main/java/org/cubictest/exporters/cubicunit/runner/converters/ContextConverter.java b/CubicUnitExporter/src/main/java/org/cubictest/exporters/cubicunit/runner/converters/ContextConverter.java
index 6c103a20..d8bdca6e 100644
--- a/CubicUnitExporter/src/main/java/org/cubictest/exporters/cubicunit/runner/converters/ContextConverter.java
+++ b/CubicUnitExporter/src/main/java/org/cubictest/exporters/cubicunit/runner/converters/ContextConverter.java
@@ -1,130 +1,130 @@
/*
* This software is licensed under the terms of the GNU GENERAL PUBLIC LICENSE
* Version 2, which can be found at http://www.gnu.org/copyleft/gpl.html
*/
package org.cubictest.exporters.cubicunit.runner.converters;
import java.util.Map;
import org.cubictest.export.converters.IContextConverter;
import org.cubictest.export.converters.PostContextHandle;
import org.cubictest.export.converters.PreContextHandle;
import org.cubictest.exporters.cubicunit.runner.holders.Holder;
import org.cubictest.model.AbstractPage;
import org.cubictest.model.Identifier;
import org.cubictest.model.IdentifierType;
import org.cubictest.model.TestPartStatus;
import org.cubictest.model.context.IContext;
import org.cubictest.model.context.SimpleContext;
import org.cubicunit.Container;
import org.cubicunit.Document;
import org.cubicunit.Element;
import org.cubicunit.ElementTypes;
import org.cubicunit.internal.selenium.SeleniumAbstractElement;
import org.cubicunit.internal.selenium.SeleniumContainer;
import org.cubicunit.types.ElementContainerType;
public class ContextConverter implements IContextConverter<Holder> {
private Container container;
public PreContextHandle handlePreContext(Holder holder, IContext context) {
if(context instanceof AbstractPage ){
Document doc = holder.getDocument();
holder.setContainer(doc);
container = doc;
}else if(context instanceof SimpleContext){
SimpleContext sc = (SimpleContext) context;
try{
container = holder.getContainer();
ElementContainerType type = ElementTypes.CUSTOM_ELEMENT;
for(Identifier id : sc.getIdentifiers()){
switch(id.getType()){
case ID:
type = type.id(id.getProbability(), id.getValue());
break;
case XPATH:
//TODO: Fixme
//type = type.xpath(id.getProbability(), id.getValue());
break;
case VALUE:
type = type.text(id.getProbability(), id.getValue());
break;
case ELEMENT_NAME:
type = type.tagName(id.getProbability(), id.getValue());
break;
case INDEX:
try{
type = type.index(id.getProbability(),
Integer.parseInt(id.getValue()));
}catch (NumberFormatException e) {
}
break;
default:
break;
}
}
Container subContainer = container.get(type);
if(sc.isNot()){
if(subContainer != null)
holder.addResult(sc, TestPartStatus.FAIL);
else
holder.addResult(sc, TestPartStatus.PASS);
}else{
if(subContainer == null)
holder.addResult(sc, TestPartStatus.FAIL);
else{
TestPartStatus status = TestPartStatus.PASS;
Map<String, Object> props =
((SeleniumContainer)subContainer).getProperties();
if(props != null){
for(String key: props.keySet()){
String actualValue = (String) props.get(key);
IdentifierType id = null;
- if("diffid".equals(key)){
+ if("diffId".equals(key)){
id = IdentifierType.ID;
}else if("diffName".equals(key)){
id = IdentifierType.NAME;
}else if("diffHref".equals(key)){
id = IdentifierType.HREF;
}else if("diffSrc".equals(key)){
id = IdentifierType.SRC;
}else if("diffIndex".equals(key)){
id = IdentifierType.INDEX;
}else if("diffValue".equals(key)){
id = IdentifierType.VALUE;
}else if("diffChecked".equals(key)){
id = IdentifierType.CHECKED;
}else if("diffLabel".equals(key)){
id = IdentifierType.LABEL;
}else if("diffMultiselect".equals(key)){
id = IdentifierType.MULTISELECT;
}else if("diffSelected".equals(key)){
id = IdentifierType.SELECTED;
}else
continue;
if(sc.getIdentifier(id) != null){
sc.getIdentifier(id).setActual(actualValue);
status = TestPartStatus.WARN;
}
}
}
holder.addResult(sc, status);
holder.setContainer(subContainer);
holder.put(sc, (Element)subContainer);
}
}
}catch (RuntimeException e){
holder.addResult(sc, TestPartStatus.EXCEPTION);
throw e;
}
}
return PreContextHandle.CONTINUE;
}
public PostContextHandle handlePostContext(Holder holder, IContext context) {
holder.setContainer(container);
return PostContextHandle.DONE;
}
}
| true | true | public PreContextHandle handlePreContext(Holder holder, IContext context) {
if(context instanceof AbstractPage ){
Document doc = holder.getDocument();
holder.setContainer(doc);
container = doc;
}else if(context instanceof SimpleContext){
SimpleContext sc = (SimpleContext) context;
try{
container = holder.getContainer();
ElementContainerType type = ElementTypes.CUSTOM_ELEMENT;
for(Identifier id : sc.getIdentifiers()){
switch(id.getType()){
case ID:
type = type.id(id.getProbability(), id.getValue());
break;
case XPATH:
//TODO: Fixme
//type = type.xpath(id.getProbability(), id.getValue());
break;
case VALUE:
type = type.text(id.getProbability(), id.getValue());
break;
case ELEMENT_NAME:
type = type.tagName(id.getProbability(), id.getValue());
break;
case INDEX:
try{
type = type.index(id.getProbability(),
Integer.parseInt(id.getValue()));
}catch (NumberFormatException e) {
}
break;
default:
break;
}
}
Container subContainer = container.get(type);
if(sc.isNot()){
if(subContainer != null)
holder.addResult(sc, TestPartStatus.FAIL);
else
holder.addResult(sc, TestPartStatus.PASS);
}else{
if(subContainer == null)
holder.addResult(sc, TestPartStatus.FAIL);
else{
TestPartStatus status = TestPartStatus.PASS;
Map<String, Object> props =
((SeleniumContainer)subContainer).getProperties();
if(props != null){
for(String key: props.keySet()){
String actualValue = (String) props.get(key);
IdentifierType id = null;
if("diffid".equals(key)){
id = IdentifierType.ID;
}else if("diffName".equals(key)){
id = IdentifierType.NAME;
}else if("diffHref".equals(key)){
id = IdentifierType.HREF;
}else if("diffSrc".equals(key)){
id = IdentifierType.SRC;
}else if("diffIndex".equals(key)){
id = IdentifierType.INDEX;
}else if("diffValue".equals(key)){
id = IdentifierType.VALUE;
}else if("diffChecked".equals(key)){
id = IdentifierType.CHECKED;
}else if("diffLabel".equals(key)){
id = IdentifierType.LABEL;
}else if("diffMultiselect".equals(key)){
id = IdentifierType.MULTISELECT;
}else if("diffSelected".equals(key)){
id = IdentifierType.SELECTED;
}else
continue;
if(sc.getIdentifier(id) != null){
sc.getIdentifier(id).setActual(actualValue);
status = TestPartStatus.WARN;
}
}
}
holder.addResult(sc, status);
holder.setContainer(subContainer);
holder.put(sc, (Element)subContainer);
}
}
}catch (RuntimeException e){
holder.addResult(sc, TestPartStatus.EXCEPTION);
throw e;
}
}
return PreContextHandle.CONTINUE;
}
| public PreContextHandle handlePreContext(Holder holder, IContext context) {
if(context instanceof AbstractPage ){
Document doc = holder.getDocument();
holder.setContainer(doc);
container = doc;
}else if(context instanceof SimpleContext){
SimpleContext sc = (SimpleContext) context;
try{
container = holder.getContainer();
ElementContainerType type = ElementTypes.CUSTOM_ELEMENT;
for(Identifier id : sc.getIdentifiers()){
switch(id.getType()){
case ID:
type = type.id(id.getProbability(), id.getValue());
break;
case XPATH:
//TODO: Fixme
//type = type.xpath(id.getProbability(), id.getValue());
break;
case VALUE:
type = type.text(id.getProbability(), id.getValue());
break;
case ELEMENT_NAME:
type = type.tagName(id.getProbability(), id.getValue());
break;
case INDEX:
try{
type = type.index(id.getProbability(),
Integer.parseInt(id.getValue()));
}catch (NumberFormatException e) {
}
break;
default:
break;
}
}
Container subContainer = container.get(type);
if(sc.isNot()){
if(subContainer != null)
holder.addResult(sc, TestPartStatus.FAIL);
else
holder.addResult(sc, TestPartStatus.PASS);
}else{
if(subContainer == null)
holder.addResult(sc, TestPartStatus.FAIL);
else{
TestPartStatus status = TestPartStatus.PASS;
Map<String, Object> props =
((SeleniumContainer)subContainer).getProperties();
if(props != null){
for(String key: props.keySet()){
String actualValue = (String) props.get(key);
IdentifierType id = null;
if("diffId".equals(key)){
id = IdentifierType.ID;
}else if("diffName".equals(key)){
id = IdentifierType.NAME;
}else if("diffHref".equals(key)){
id = IdentifierType.HREF;
}else if("diffSrc".equals(key)){
id = IdentifierType.SRC;
}else if("diffIndex".equals(key)){
id = IdentifierType.INDEX;
}else if("diffValue".equals(key)){
id = IdentifierType.VALUE;
}else if("diffChecked".equals(key)){
id = IdentifierType.CHECKED;
}else if("diffLabel".equals(key)){
id = IdentifierType.LABEL;
}else if("diffMultiselect".equals(key)){
id = IdentifierType.MULTISELECT;
}else if("diffSelected".equals(key)){
id = IdentifierType.SELECTED;
}else
continue;
if(sc.getIdentifier(id) != null){
sc.getIdentifier(id).setActual(actualValue);
status = TestPartStatus.WARN;
}
}
}
holder.addResult(sc, status);
holder.setContainer(subContainer);
holder.put(sc, (Element)subContainer);
}
}
}catch (RuntimeException e){
holder.addResult(sc, TestPartStatus.EXCEPTION);
throw e;
}
}
return PreContextHandle.CONTINUE;
}
|
diff --git a/my-gdx-game/src/com/me/mygdxgame/Obstacle.java b/my-gdx-game/src/com/me/mygdxgame/Obstacle.java
index f9311dc..4201f86 100644
--- a/my-gdx-game/src/com/me/mygdxgame/Obstacle.java
+++ b/my-gdx-game/src/com/me/mygdxgame/Obstacle.java
@@ -1,61 +1,61 @@
package com.me.mygdxgame;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Rectangle;
public class Obstacle {
//Assets
private Texture image;
//End Assets
protected Rectangle hitbox;
private float RESW;
private float RESH;
final int SPRITE_WIDTH = 96;
final int SPRITE_HEIGHT = 96;
final int SCALE = 1;
final int WIDTH = SPRITE_WIDTH * SCALE;
final int HEIGHT = SPRITE_HEIGHT * SCALE;
private OrthographicCamera camera;
private float floorHeight;
protected boolean released;
Obstacle(OrthographicCamera pcamera, float x, float y) {
RESW = pcamera.viewportHeight;
RESH = pcamera.viewportHeight;
camera = pcamera;
floorHeight = y;
create(x, y);
}
public void create(float x, float y) {
image = new Texture(Gdx.files.internal("data/waterdrop.png"));
hitbox = new Rectangle(x, y, SPRITE_WIDTH,
SPRITE_HEIGHT);
}
public void draw(SpriteBatch batch) {
batch.draw(image, hitbox.x, hitbox.y);
}
public void dispose() {
image.dispose();
}
public boolean isOffScreen() {
- if (hitbox.x < camera.position.x - RESW/2 - SPRITE_WIDTH) {
+ if (hitbox.x < camera.position.x - RESW/2 - SPRITE_WIDTH * 2) {
return true;
}
else {
return false;
}
}
}
| true | true | public boolean isOffScreen() {
if (hitbox.x < camera.position.x - RESW/2 - SPRITE_WIDTH) {
return true;
}
else {
return false;
}
}
| public boolean isOffScreen() {
if (hitbox.x < camera.position.x - RESW/2 - SPRITE_WIDTH * 2) {
return true;
}
else {
return false;
}
}
|
diff --git a/src/main/java/im/jeanfrancois/etsmaps/ui/NavigationPanel.java b/src/main/java/im/jeanfrancois/etsmaps/ui/NavigationPanel.java
index 846b5ca..431ea6a 100644
--- a/src/main/java/im/jeanfrancois/etsmaps/ui/NavigationPanel.java
+++ b/src/main/java/im/jeanfrancois/etsmaps/ui/NavigationPanel.java
@@ -1,92 +1,92 @@
package im.jeanfrancois.etsmaps.ui;
import ca.odell.glazedlists.BasicEventList;
import ca.odell.glazedlists.EventList;
import ca.odell.glazedlists.gui.TableFormat;
import ca.odell.glazedlists.swing.EventComboBoxModel;
import ca.odell.glazedlists.swing.EventTableModel;
import ca.odell.glazedlists.util.concurrent.ReadWriteLock;
import com.google.inject.Inject;
import im.jeanfrancois.etsmaps.model.Landmark;
import im.jeanfrancois.etsmaps.model.Leg;
import im.jeanfrancois.etsmaps.model.NavigableMap;
import im.jeanfrancois.etsmaps.model.Route;
import net.miginfocom.swing.MigLayout;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
/**
* Navigation panel that contains all the UI controls to search for
* landmarks and navigate between them.
*
* @author jfim
*/
public class NavigationPanel extends JPanel {
private EventList<Leg> routeLegs = new BasicEventList<Leg>();
private NavigableMap map;
@Inject
public NavigationPanel(final NavigableMap map) {
this.map = map;
- setLayout(new MigLayout("wrap 2", "", "[][][][grow,fill]"));
+ setLayout(new MigLayout("wrap 2", "", "[][][][][grow,fill]"));
EventList<Landmark> landmarks = new BasicEventList<Landmark>();
landmarks.addAll(map.getLandmarks());
add(new JLabel("From"));
final JComboBox originComboBox = new JComboBox(new EventComboBoxModel<Landmark>(landmarks));
add(originComboBox);
add(new JLabel("To"));
final JComboBox destinationComboBox = new JComboBox(new EventComboBoxModel<Landmark>(landmarks));
add(destinationComboBox);
final JButton button = new JButton("Navigate");
add(button, "span 2");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Route route = map.getRouteBetweenLandmarks((Landmark) originComboBox.getSelectedItem(),
(Landmark) destinationComboBox.getSelectedItem());
ArrayList<Leg> legs = new ArrayList<Leg>();
for (int i = 0; i < route.getLegCount(); ++i) {
legs.add(route.getLeg(i));
}
ReadWriteLock lock = routeLegs.getReadWriteLock();
lock.writeLock().lock();
routeLegs.clear();
routeLegs.addAll(legs);
lock.writeLock().unlock();
}
});
add(new JLabel("Directions"), "span 2");
final JTable table = new JTable(new EventTableModel<Leg>(routeLegs,
new TableFormat<Leg>() {
public int getColumnCount() {
return 2;
}
public String getColumnName(int i) {
return "";
}
public Object getColumnValue(Leg leg, int i) {
if (i == 0) {
return leg.getDescription();
}
return leg.getLengthInMetres() + " m";
}
}));
add(new JScrollPane(table), "width 100%, span 2");
}
}
| true | true | public NavigationPanel(final NavigableMap map) {
this.map = map;
setLayout(new MigLayout("wrap 2", "", "[][][][grow,fill]"));
EventList<Landmark> landmarks = new BasicEventList<Landmark>();
landmarks.addAll(map.getLandmarks());
add(new JLabel("From"));
final JComboBox originComboBox = new JComboBox(new EventComboBoxModel<Landmark>(landmarks));
add(originComboBox);
add(new JLabel("To"));
final JComboBox destinationComboBox = new JComboBox(new EventComboBoxModel<Landmark>(landmarks));
add(destinationComboBox);
final JButton button = new JButton("Navigate");
add(button, "span 2");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Route route = map.getRouteBetweenLandmarks((Landmark) originComboBox.getSelectedItem(),
(Landmark) destinationComboBox.getSelectedItem());
ArrayList<Leg> legs = new ArrayList<Leg>();
for (int i = 0; i < route.getLegCount(); ++i) {
legs.add(route.getLeg(i));
}
ReadWriteLock lock = routeLegs.getReadWriteLock();
lock.writeLock().lock();
routeLegs.clear();
routeLegs.addAll(legs);
lock.writeLock().unlock();
}
});
add(new JLabel("Directions"), "span 2");
final JTable table = new JTable(new EventTableModel<Leg>(routeLegs,
new TableFormat<Leg>() {
public int getColumnCount() {
return 2;
}
public String getColumnName(int i) {
return "";
}
public Object getColumnValue(Leg leg, int i) {
if (i == 0) {
return leg.getDescription();
}
return leg.getLengthInMetres() + " m";
}
}));
add(new JScrollPane(table), "width 100%, span 2");
}
| public NavigationPanel(final NavigableMap map) {
this.map = map;
setLayout(new MigLayout("wrap 2", "", "[][][][][grow,fill]"));
EventList<Landmark> landmarks = new BasicEventList<Landmark>();
landmarks.addAll(map.getLandmarks());
add(new JLabel("From"));
final JComboBox originComboBox = new JComboBox(new EventComboBoxModel<Landmark>(landmarks));
add(originComboBox);
add(new JLabel("To"));
final JComboBox destinationComboBox = new JComboBox(new EventComboBoxModel<Landmark>(landmarks));
add(destinationComboBox);
final JButton button = new JButton("Navigate");
add(button, "span 2");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Route route = map.getRouteBetweenLandmarks((Landmark) originComboBox.getSelectedItem(),
(Landmark) destinationComboBox.getSelectedItem());
ArrayList<Leg> legs = new ArrayList<Leg>();
for (int i = 0; i < route.getLegCount(); ++i) {
legs.add(route.getLeg(i));
}
ReadWriteLock lock = routeLegs.getReadWriteLock();
lock.writeLock().lock();
routeLegs.clear();
routeLegs.addAll(legs);
lock.writeLock().unlock();
}
});
add(new JLabel("Directions"), "span 2");
final JTable table = new JTable(new EventTableModel<Leg>(routeLegs,
new TableFormat<Leg>() {
public int getColumnCount() {
return 2;
}
public String getColumnName(int i) {
return "";
}
public Object getColumnValue(Leg leg, int i) {
if (i == 0) {
return leg.getDescription();
}
return leg.getLengthInMetres() + " m";
}
}));
add(new JScrollPane(table), "width 100%, span 2");
}
|
diff --git a/src/main/java/de/cismet/cismap/commons/gui/piccolo/RectangleFromLineDialog.java b/src/main/java/de/cismet/cismap/commons/gui/piccolo/RectangleFromLineDialog.java
index 2392ddb3..9371406b 100644
--- a/src/main/java/de/cismet/cismap/commons/gui/piccolo/RectangleFromLineDialog.java
+++ b/src/main/java/de/cismet/cismap/commons/gui/piccolo/RectangleFromLineDialog.java
@@ -1,498 +1,498 @@
/***************************************************
*
* cismet GmbH, Saarbruecken, Germany
*
* ... and it just works.
*
****************************************************/
/*
* Copyright (C) 2010 jruiz
*
* 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/>.
*/
/*
* RectangleFromLineDialog.java
*
* Created on 04.08.2010, 13:53:09
*/
package de.cismet.cismap.commons.gui.piccolo;
import org.jdesktop.beansbinding.AbstractBindingListener;
import org.jdesktop.beansbinding.Binding;
import org.jdesktop.beansbinding.Converter;
import java.text.NumberFormat;
import java.util.LinkedList;
import javax.swing.JFormattedTextField;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
/**
* DOCUMENT ME!
*
* @author jruiz
* @version $Revision$, $Date$
*/
public class RectangleFromLineDialog extends javax.swing.JDialog {
//~ Static fields/initializers ---------------------------------------------
public static final int STATUS_NONE = -1;
public static final int STATUS_OK = 0;
public static final int STATUS_CANCELED = 1;
//~ Instance fields --------------------------------------------------------
private final transient org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(this.getClass());
private double length = 0;
private NumberFormat format = NumberFormat.getInstance();
private int returnStatus = STATUS_NONE;
private LinkedList<ChangeListener> widthChangedListeners = new LinkedList<ChangeListener>();
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnCancel;
private javax.swing.JButton btnOK;
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JPanel jPanel1;
private javax.swing.JRadioButton jRadioButton1;
private javax.swing.JRadioButton jRadioButton2;
private javax.swing.JSeparator jSeparator2;
private javax.swing.JLabel lblLength;
private javax.swing.JPanel panButtons;
private javax.swing.JPanel panParams;
private javax.swing.JPanel panSide;
private javax.swing.JTextField txtSurface;
private javax.swing.JTextField txtWidth;
private org.jdesktop.beansbinding.BindingGroup bindingGroup;
// End of variables declaration//GEN-END:variables
//~ Constructors -----------------------------------------------------------
/**
* Creates new form RectangleFromLineDialog.
*
* @param parent DOCUMENT ME!
* @param modal DOCUMENT ME!
* @param length DOCUMENT ME!
*/
public RectangleFromLineDialog(final java.awt.Frame parent, final boolean modal, final double length) {
super(parent, modal);
format.setGroupingUsed(false);
format.setMinimumFractionDigits(2);
format.setMaximumFractionDigits(2);
initComponents();
lblLength.setText(format.format(length));
this.length = length;
bindingGroup.addBindingListener(new AbstractBindingListener() {
@Override
public void synced(final Binding bndng) {
fireStateChanged();
}
});
jRadioButton1.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(final ChangeEvent ce) {
fireStateChanged();
}
});
}
//~ Methods ----------------------------------------------------------------
/**
* DOCUMENT ME!
*/
private void fireStateChanged() {
for (final ChangeListener cl : widthChangedListeners) {
cl.stateChanged(new ChangeEvent(this));
}
}
/**
* 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() {
java.awt.GridBagConstraints gridBagConstraints;
bindingGroup = new org.jdesktop.beansbinding.BindingGroup();
buttonGroup1 = new javax.swing.ButtonGroup();
panParams = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
txtSurface = new JFormattedTextField(format);
txtWidth = new JFormattedTextField(format);
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
panSide = new javax.swing.JPanel();
jRadioButton1 = new javax.swing.JRadioButton();
jRadioButton2 = new javax.swing.JRadioButton();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
lblLength = new javax.swing.JLabel();
panButtons = new javax.swing.JPanel();
jPanel1 = new javax.swing.JPanel();
btnCancel = new javax.swing.JButton();
btnOK = new javax.swing.JButton();
jSeparator2 = new javax.swing.JSeparator();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle(org.openide.util.NbBundle.getMessage(RectangleFromLineDialog.class, "RectangleFromLineDialog.title")); // NOI18N
getContentPane().setLayout(new java.awt.GridBagLayout());
panParams.setLayout(new java.awt.GridBagLayout());
jLabel1.setText(org.openide.util.NbBundle.getMessage(
RectangleFromLineDialog.class,
- "RectangleFromLineDialog.jLabel1.text_2")); // NOI18N
+ "RectangleFromLineDialog.jLabel1.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 0.05;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panParams.add(jLabel1, gridBagConstraints);
jLabel2.setText(org.openide.util.NbBundle.getMessage(
RectangleFromLineDialog.class,
- "RectangleFromLineDialog.jLabel2.text_2")); // NOI18N
+ "RectangleFromLineDialog.jLabel2.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panParams.add(jLabel2, gridBagConstraints);
txtSurface.setHorizontalAlignment(javax.swing.JTextField.TRAILING);
txtSurface.setText(org.openide.util.NbBundle.getMessage(
RectangleFromLineDialog.class,
"RectangleFromLineDialog.txtSurface.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panParams.add(txtSurface, gridBagConstraints);
txtWidth.setHorizontalAlignment(javax.swing.JTextField.TRAILING);
final org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
txtSurface,
org.jdesktop.beansbinding.ELProperty.create("${text}"),
txtWidth,
org.jdesktop.beansbinding.BeanProperty.create("text"));
binding.setSourceNullValue("0,00");
binding.setSourceUnreadableValue("0,00");
binding.setConverter(new WidthToSurfaceConverter());
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panParams.add(txtWidth, gridBagConstraints);
jLabel3.setText(org.openide.util.NbBundle.getMessage(
RectangleFromLineDialog.class,
"RectangleFromLineDialog.jLabel3.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 0.025;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panParams.add(jLabel3, gridBagConstraints);
jLabel4.setText(org.openide.util.NbBundle.getMessage(
RectangleFromLineDialog.class,
"RectangleFromLineDialog.jLabel4.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panParams.add(jLabel4, gridBagConstraints);
panSide.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER, 25, 0));
buttonGroup1.add(jRadioButton1);
jRadioButton1.setSelected(true);
jRadioButton1.setText(org.openide.util.NbBundle.getMessage(
RectangleFromLineDialog.class,
- "RectangleFromLineDialog.jRadioButton1.text_3")); // NOI18N
+ "RectangleFromLineDialog.jRadioButton1.text")); // NOI18N
panSide.add(jRadioButton1);
buttonGroup1.add(jRadioButton2);
jRadioButton2.setText(org.openide.util.NbBundle.getMessage(
RectangleFromLineDialog.class,
"RectangleFromLineDialog.jRadioButton2.text_3")); // NOI18N
panSide.add(jRadioButton2);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panParams.add(panSide, gridBagConstraints);
jLabel5.setText(org.openide.util.NbBundle.getMessage(
RectangleFromLineDialog.class,
"RectangleFromLineDialog.jLabel5.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panParams.add(jLabel5, gridBagConstraints);
jLabel6.setText(org.openide.util.NbBundle.getMessage(
RectangleFromLineDialog.class,
"RectangleFromLineDialog.jLabel6.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panParams.add(jLabel6, gridBagConstraints);
lblLength.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
lblLength.setText(org.openide.util.NbBundle.getMessage(
RectangleFromLineDialog.class,
"RectangleFromLineDialog.lblLength.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panParams.add(lblLength, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
getContentPane().add(panParams, gridBagConstraints);
jPanel1.setLayout(new java.awt.GridLayout(1, 0, 5, 0));
btnCancel.setText(org.openide.util.NbBundle.getMessage(
RectangleFromLineDialog.class,
"RectangleFromLineDialog.btnCancel.text_2")); // NOI18N
btnCancel.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
btnCancelActionPerformed(evt);
}
});
jPanel1.add(btnCancel);
btnOK.setText(org.openide.util.NbBundle.getMessage(
RectangleFromLineDialog.class,
"RectangleFromLineDialog.btnOK.text_2")); // NOI18N
btnOK.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
btnOKActionPerformed(evt);
}
});
jPanel1.add(btnOK);
panButtons.add(jPanel1);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
getContentPane().add(panButtons, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
getContentPane().add(jSeparator2, gridBagConstraints);
bindingGroup.bind();
pack();
} // </editor-fold>//GEN-END:initComponents
/**
* DOCUMENT ME!
*
* @param cl DOCUMENT ME!
*/
public void addWidthChangedListener(final ChangeListener cl) {
widthChangedListeners.add(cl);
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public double getRectangleWidth() {
return convertStringToDouble(txtWidth.getText());
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public boolean isLefty() {
return jRadioButton1.isSelected();
}
/**
* DOCUMENT ME!
*
* @param width DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
private double convertWidthToSurface(final double width) {
return width * length;
}
/**
* DOCUMENT ME!
*
* @param surface DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
private double convertSurfaceToWidth(final double surface) {
if (length == 0) {
return 0d;
} else {
return surface / length;
}
}
/**
* DOCUMENT ME!
*
* @param surfaceString DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
private static double convertStringToDouble(final String surfaceString) {
try {
return Double.parseDouble(surfaceString.replace(',', '.'));
} catch (NumberFormatException ex) {
return 0d;
}
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public int getReturnStatus() {
return returnStatus;
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void btnOKActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_btnOKActionPerformed
returnStatus = STATUS_OK;
dispose();
} //GEN-LAST:event_btnOKActionPerformed
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void btnCancelActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_btnCancelActionPerformed
returnStatus = STATUS_CANCELED;
dispose();
} //GEN-LAST:event_btnCancelActionPerformed
/**
* DOCUMENT ME!
*
* @param args the command line arguments
*/
public static void main(final String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
final RectangleFromLineDialog dialog = new RectangleFromLineDialog(
new javax.swing.JFrame(),
true,
0);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(final java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
//~ Inner Classes ----------------------------------------------------------
/**
* DOCUMENT ME!
*
* @version $Revision$, $Date$
*/
class WidthToSurfaceConverter extends Converter<String, String> {
//~ Methods ------------------------------------------------------------
@Override
public String convertForward(final String surfaceString) {
final double surface = convertStringToDouble(surfaceString);
return format.format(convertSurfaceToWidth(surface));
}
@Override
public String convertReverse(final String widthString) {
final double width = convertStringToDouble(widthString);
return format.format(convertWidthToSurface(width));
}
}
}
| false | true | private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
bindingGroup = new org.jdesktop.beansbinding.BindingGroup();
buttonGroup1 = new javax.swing.ButtonGroup();
panParams = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
txtSurface = new JFormattedTextField(format);
txtWidth = new JFormattedTextField(format);
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
panSide = new javax.swing.JPanel();
jRadioButton1 = new javax.swing.JRadioButton();
jRadioButton2 = new javax.swing.JRadioButton();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
lblLength = new javax.swing.JLabel();
panButtons = new javax.swing.JPanel();
jPanel1 = new javax.swing.JPanel();
btnCancel = new javax.swing.JButton();
btnOK = new javax.swing.JButton();
jSeparator2 = new javax.swing.JSeparator();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle(org.openide.util.NbBundle.getMessage(RectangleFromLineDialog.class, "RectangleFromLineDialog.title")); // NOI18N
getContentPane().setLayout(new java.awt.GridBagLayout());
panParams.setLayout(new java.awt.GridBagLayout());
jLabel1.setText(org.openide.util.NbBundle.getMessage(
RectangleFromLineDialog.class,
"RectangleFromLineDialog.jLabel1.text_2")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 0.05;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panParams.add(jLabel1, gridBagConstraints);
jLabel2.setText(org.openide.util.NbBundle.getMessage(
RectangleFromLineDialog.class,
"RectangleFromLineDialog.jLabel2.text_2")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panParams.add(jLabel2, gridBagConstraints);
txtSurface.setHorizontalAlignment(javax.swing.JTextField.TRAILING);
txtSurface.setText(org.openide.util.NbBundle.getMessage(
RectangleFromLineDialog.class,
"RectangleFromLineDialog.txtSurface.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panParams.add(txtSurface, gridBagConstraints);
txtWidth.setHorizontalAlignment(javax.swing.JTextField.TRAILING);
final org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
txtSurface,
org.jdesktop.beansbinding.ELProperty.create("${text}"),
txtWidth,
org.jdesktop.beansbinding.BeanProperty.create("text"));
binding.setSourceNullValue("0,00");
binding.setSourceUnreadableValue("0,00");
binding.setConverter(new WidthToSurfaceConverter());
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panParams.add(txtWidth, gridBagConstraints);
jLabel3.setText(org.openide.util.NbBundle.getMessage(
RectangleFromLineDialog.class,
"RectangleFromLineDialog.jLabel3.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 0.025;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panParams.add(jLabel3, gridBagConstraints);
jLabel4.setText(org.openide.util.NbBundle.getMessage(
RectangleFromLineDialog.class,
"RectangleFromLineDialog.jLabel4.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panParams.add(jLabel4, gridBagConstraints);
panSide.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER, 25, 0));
buttonGroup1.add(jRadioButton1);
jRadioButton1.setSelected(true);
jRadioButton1.setText(org.openide.util.NbBundle.getMessage(
RectangleFromLineDialog.class,
"RectangleFromLineDialog.jRadioButton1.text_3")); // NOI18N
panSide.add(jRadioButton1);
buttonGroup1.add(jRadioButton2);
jRadioButton2.setText(org.openide.util.NbBundle.getMessage(
RectangleFromLineDialog.class,
"RectangleFromLineDialog.jRadioButton2.text_3")); // NOI18N
panSide.add(jRadioButton2);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panParams.add(panSide, gridBagConstraints);
jLabel5.setText(org.openide.util.NbBundle.getMessage(
RectangleFromLineDialog.class,
"RectangleFromLineDialog.jLabel5.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panParams.add(jLabel5, gridBagConstraints);
jLabel6.setText(org.openide.util.NbBundle.getMessage(
RectangleFromLineDialog.class,
"RectangleFromLineDialog.jLabel6.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panParams.add(jLabel6, gridBagConstraints);
lblLength.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
lblLength.setText(org.openide.util.NbBundle.getMessage(
RectangleFromLineDialog.class,
"RectangleFromLineDialog.lblLength.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panParams.add(lblLength, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
getContentPane().add(panParams, gridBagConstraints);
jPanel1.setLayout(new java.awt.GridLayout(1, 0, 5, 0));
btnCancel.setText(org.openide.util.NbBundle.getMessage(
RectangleFromLineDialog.class,
"RectangleFromLineDialog.btnCancel.text_2")); // NOI18N
btnCancel.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
btnCancelActionPerformed(evt);
}
});
jPanel1.add(btnCancel);
btnOK.setText(org.openide.util.NbBundle.getMessage(
RectangleFromLineDialog.class,
"RectangleFromLineDialog.btnOK.text_2")); // NOI18N
btnOK.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
btnOKActionPerformed(evt);
}
});
jPanel1.add(btnOK);
panButtons.add(jPanel1);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
getContentPane().add(panButtons, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
getContentPane().add(jSeparator2, gridBagConstraints);
bindingGroup.bind();
pack();
} // </editor-fold>//GEN-END:initComponents
| private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
bindingGroup = new org.jdesktop.beansbinding.BindingGroup();
buttonGroup1 = new javax.swing.ButtonGroup();
panParams = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
txtSurface = new JFormattedTextField(format);
txtWidth = new JFormattedTextField(format);
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
panSide = new javax.swing.JPanel();
jRadioButton1 = new javax.swing.JRadioButton();
jRadioButton2 = new javax.swing.JRadioButton();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
lblLength = new javax.swing.JLabel();
panButtons = new javax.swing.JPanel();
jPanel1 = new javax.swing.JPanel();
btnCancel = new javax.swing.JButton();
btnOK = new javax.swing.JButton();
jSeparator2 = new javax.swing.JSeparator();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle(org.openide.util.NbBundle.getMessage(RectangleFromLineDialog.class, "RectangleFromLineDialog.title")); // NOI18N
getContentPane().setLayout(new java.awt.GridBagLayout());
panParams.setLayout(new java.awt.GridBagLayout());
jLabel1.setText(org.openide.util.NbBundle.getMessage(
RectangleFromLineDialog.class,
"RectangleFromLineDialog.jLabel1.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 0.05;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panParams.add(jLabel1, gridBagConstraints);
jLabel2.setText(org.openide.util.NbBundle.getMessage(
RectangleFromLineDialog.class,
"RectangleFromLineDialog.jLabel2.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panParams.add(jLabel2, gridBagConstraints);
txtSurface.setHorizontalAlignment(javax.swing.JTextField.TRAILING);
txtSurface.setText(org.openide.util.NbBundle.getMessage(
RectangleFromLineDialog.class,
"RectangleFromLineDialog.txtSurface.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panParams.add(txtSurface, gridBagConstraints);
txtWidth.setHorizontalAlignment(javax.swing.JTextField.TRAILING);
final org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
txtSurface,
org.jdesktop.beansbinding.ELProperty.create("${text}"),
txtWidth,
org.jdesktop.beansbinding.BeanProperty.create("text"));
binding.setSourceNullValue("0,00");
binding.setSourceUnreadableValue("0,00");
binding.setConverter(new WidthToSurfaceConverter());
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panParams.add(txtWidth, gridBagConstraints);
jLabel3.setText(org.openide.util.NbBundle.getMessage(
RectangleFromLineDialog.class,
"RectangleFromLineDialog.jLabel3.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 0.025;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panParams.add(jLabel3, gridBagConstraints);
jLabel4.setText(org.openide.util.NbBundle.getMessage(
RectangleFromLineDialog.class,
"RectangleFromLineDialog.jLabel4.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panParams.add(jLabel4, gridBagConstraints);
panSide.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER, 25, 0));
buttonGroup1.add(jRadioButton1);
jRadioButton1.setSelected(true);
jRadioButton1.setText(org.openide.util.NbBundle.getMessage(
RectangleFromLineDialog.class,
"RectangleFromLineDialog.jRadioButton1.text")); // NOI18N
panSide.add(jRadioButton1);
buttonGroup1.add(jRadioButton2);
jRadioButton2.setText(org.openide.util.NbBundle.getMessage(
RectangleFromLineDialog.class,
"RectangleFromLineDialog.jRadioButton2.text_3")); // NOI18N
panSide.add(jRadioButton2);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panParams.add(panSide, gridBagConstraints);
jLabel5.setText(org.openide.util.NbBundle.getMessage(
RectangleFromLineDialog.class,
"RectangleFromLineDialog.jLabel5.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panParams.add(jLabel5, gridBagConstraints);
jLabel6.setText(org.openide.util.NbBundle.getMessage(
RectangleFromLineDialog.class,
"RectangleFromLineDialog.jLabel6.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panParams.add(jLabel6, gridBagConstraints);
lblLength.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
lblLength.setText(org.openide.util.NbBundle.getMessage(
RectangleFromLineDialog.class,
"RectangleFromLineDialog.lblLength.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
panParams.add(lblLength, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
getContentPane().add(panParams, gridBagConstraints);
jPanel1.setLayout(new java.awt.GridLayout(1, 0, 5, 0));
btnCancel.setText(org.openide.util.NbBundle.getMessage(
RectangleFromLineDialog.class,
"RectangleFromLineDialog.btnCancel.text_2")); // NOI18N
btnCancel.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
btnCancelActionPerformed(evt);
}
});
jPanel1.add(btnCancel);
btnOK.setText(org.openide.util.NbBundle.getMessage(
RectangleFromLineDialog.class,
"RectangleFromLineDialog.btnOK.text_2")); // NOI18N
btnOK.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
btnOKActionPerformed(evt);
}
});
jPanel1.add(btnOK);
panButtons.add(jPanel1);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
getContentPane().add(panButtons, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
getContentPane().add(jSeparator2, gridBagConstraints);
bindingGroup.bind();
pack();
} // </editor-fold>//GEN-END:initComponents
|
diff --git a/activemq-core/src/main/java/org/apache/activemq/broker/jmx/CompositeDataHelper.java b/activemq-core/src/main/java/org/apache/activemq/broker/jmx/CompositeDataHelper.java
index ec27ae2f3..8ef55c88a 100644
--- a/activemq-core/src/main/java/org/apache/activemq/broker/jmx/CompositeDataHelper.java
+++ b/activemq-core/src/main/java/org/apache/activemq/broker/jmx/CompositeDataHelper.java
@@ -1,73 +1,73 @@
/**
*
* 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.activemq.broker.jmx;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.TabularData;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* @version $Revision: 1.1 $
*/
public class CompositeDataHelper {
/**
* Extracts the named TabularData field from the CompositeData and converts it to a Map
* which is the method used to get the typesafe user properties.
*/
public static Map getTabularMap(CompositeData cdata, String fieldName) {
Map map = new HashMap();
appendTabularMap(map, cdata, fieldName);
return map;
}
public static void appendTabularMap(Map map, CompositeData cdata, String fieldName) {
Object tabularObject = cdata.get(fieldName);
if (tabularObject instanceof TabularData) {
TabularData tabularData = (TabularData) tabularObject;
- Collection<CompositeData> values = tabularData.values();
+ Collection<CompositeData> values = (Collection<CompositeData>) tabularData.values();
for (CompositeData compositeData : values) {
Object key = compositeData.get("key");
Object value = compositeData.get("value");
map.put(key, value);
}
}
}
/**
* Returns a map of all the user properties in the given message {@link javax.management.openmbean.CompositeData}
* object
*
* @param cdata
* @return
*/
public static Map getMessageUserProperties(CompositeData cdata) {
Map map = new HashMap();
appendTabularMap(map, cdata, CompositeDataConstants.STRING_PROPERTIES);
appendTabularMap(map, cdata, CompositeDataConstants.BOOLEAN_PROPERTIES);
appendTabularMap(map, cdata, CompositeDataConstants.BYTE_PROPERTIES);
appendTabularMap(map, cdata, CompositeDataConstants.SHORT_PROPERTIES);
appendTabularMap(map, cdata, CompositeDataConstants.INT_PROPERTIES);
appendTabularMap(map, cdata, CompositeDataConstants.LONG_PROPERTIES);
appendTabularMap(map, cdata, CompositeDataConstants.FLOAT_PROPERTIES);
appendTabularMap(map, cdata, CompositeDataConstants.DOUBLE_PROPERTIES);
return map;
}
}
| true | true | public static void appendTabularMap(Map map, CompositeData cdata, String fieldName) {
Object tabularObject = cdata.get(fieldName);
if (tabularObject instanceof TabularData) {
TabularData tabularData = (TabularData) tabularObject;
Collection<CompositeData> values = tabularData.values();
for (CompositeData compositeData : values) {
Object key = compositeData.get("key");
Object value = compositeData.get("value");
map.put(key, value);
}
}
}
| public static void appendTabularMap(Map map, CompositeData cdata, String fieldName) {
Object tabularObject = cdata.get(fieldName);
if (tabularObject instanceof TabularData) {
TabularData tabularData = (TabularData) tabularObject;
Collection<CompositeData> values = (Collection<CompositeData>) tabularData.values();
for (CompositeData compositeData : values) {
Object key = compositeData.get("key");
Object value = compositeData.get("value");
map.put(key, value);
}
}
}
|
diff --git a/blocks/sublima-app/src/main/java/com/computas/sublima/app/controller/RedirectController.java b/blocks/sublima-app/src/main/java/com/computas/sublima/app/controller/RedirectController.java
index 0147b581..1afa5c05 100644
--- a/blocks/sublima-app/src/main/java/com/computas/sublima/app/controller/RedirectController.java
+++ b/blocks/sublima-app/src/main/java/com/computas/sublima/app/controller/RedirectController.java
@@ -1,27 +1,31 @@
package com.computas.sublima.app.controller;
import org.apache.cocoon.components.flow.apples.StatelessAppleController;
import org.apache.cocoon.components.flow.apples.AppleRequest;
import org.apache.cocoon.components.flow.apples.AppleResponse;
import org.apache.cocoon.environment.Request;
import static com.computas.sublima.query.service.SettingsService.getProperty;
/**
* This will just redirect using a 303 to a DESCRIBE of the URI
* User: kkj
* Date: Oct 17, 2008
* Time: 2:11:13 PM
*/
public class RedirectController implements StatelessAppleController {
public void process(AppleRequest req, AppleResponse res) throws Exception {
Request r = req.getCocoonRequest();
- String uri = getProperty("sublima.base.url") + "sparql?query=" +
- "DESCRIBE <" + r.getScheme() + "://" + r.getServerName() + ":"
- + r.getServerPort() + r.getRequestURI() + ">";
- res.getCocoonResponse().addHeader("Location", uri);
+ String uri = r.getScheme() + "://" + r.getServerName();
+ if (r.getServerPort() != 80) {
+ uri = uri + ":" + r.getServerPort();
+ }
+ uri = uri + r.getRequestURI();
+ String url = getProperty("sublima.base.url") + "sparql?query=" +
+ "DESCRIBE <" + uri + ">";
+ res.getCocoonResponse().addHeader("Location", url);
res.sendStatus(303);
}
}
| true | true | public void process(AppleRequest req, AppleResponse res) throws Exception {
Request r = req.getCocoonRequest();
String uri = getProperty("sublima.base.url") + "sparql?query=" +
"DESCRIBE <" + r.getScheme() + "://" + r.getServerName() + ":"
+ r.getServerPort() + r.getRequestURI() + ">";
res.getCocoonResponse().addHeader("Location", uri);
res.sendStatus(303);
}
| public void process(AppleRequest req, AppleResponse res) throws Exception {
Request r = req.getCocoonRequest();
String uri = r.getScheme() + "://" + r.getServerName();
if (r.getServerPort() != 80) {
uri = uri + ":" + r.getServerPort();
}
uri = uri + r.getRequestURI();
String url = getProperty("sublima.base.url") + "sparql?query=" +
"DESCRIBE <" + uri + ">";
res.getCocoonResponse().addHeader("Location", url);
res.sendStatus(303);
}
|
diff --git a/src/main/java/com/alta189/chavaadmin/ChavaAdmin.java b/src/main/java/com/alta189/chavaadmin/ChavaAdmin.java
index 7110391..1b3f7b7 100644
--- a/src/main/java/com/alta189/chavaadmin/ChavaAdmin.java
+++ b/src/main/java/com/alta189/chavaadmin/ChavaAdmin.java
@@ -1,92 +1,92 @@
package com.alta189.chavaadmin;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.alta189.chavabot.ChavaManager;
import com.alta189.chavabot.events.Order;
import com.alta189.chavabot.events.botevents.PrivateMessageEvent;
import com.alta189.chavabot.events.botevents.SendActionEvent;
import com.alta189.chavabot.events.botevents.SendMessageEvent;
import com.alta189.chavabot.events.botevents.SendNoticeEvent;
import com.alta189.chavabot.events.channelevents.MessageEvent;
import com.alta189.chavabot.events.ircevents.ConnectEvent;
import com.alta189.chavabot.plugins.java.JavaPlugin;
import com.alta189.chavabot.util.SettingsHandler;
public class ChavaAdmin extends JavaPlugin {
private static SettingsHandler settings;
private static String logChan = null;
private List<String> channels = new ArrayList<String>();
@Override
public void onEnable() {
System.out.println("ChavaAdmin enabled");
try {
if (!getDataFolder().exists()) getDataFolder().mkdir();
- ChavaAdmin.settings = new SettingsHandler(ChavaAdmin.class.getResource("").openStream(), new File(this.getDataFolder(), "settings.properties"));
+ ChavaAdmin.settings = new SettingsHandler(ChavaAdmin.class.getResource("settings").openStream(), new File(this.getDataFolder(), "settings.properties"));
ChavaAdmin.settings.load();
ChavaAdmin.logChan = ChavaAdmin.settings.getPropertyString("bot-log-channel", null);
} catch (IOException e) {
getPluginLoader().disablePlugin(this);
e.printStackTrace();
return;
}
ConnectEvent.register(new ConnectListener(), Order.Default, this);
PrivateMessageEvent.register(new PrivateMsgListener(), Order.Default, this);
MessageEvent.register(new MsgListener(), Order.Default, this);
SendMessageEvent.register(new SendMsgListener(this), Order.Latest, this);
SendActionEvent.register(new SendActionListener(this), Order.Latest, this);
SendNoticeEvent.register(new SendNoticeListener(this), Order.Latest, this);
if (ChavaAdmin.settings.checkProperty("muted-channels")) {
String chans = ChavaAdmin.settings.getPropertyString("muted-channels", null);
if (chans != null) {
for (String chan : chans.split(",")) {
channels.add(chan);
}
}
}
}
@Override
public void onDisable() {
System.out.println("ChavaAdmin disabled");
StringBuilder chans = new StringBuilder();
for (String chan : channels) {
chans.append(chan).append(",");
}
if (chans.length() > 1)
ChavaAdmin.settings.changeProperty("muted-channels", chans.toString().substring(0, chans.toString().length() - 2));
ChavaAdmin.settings = null;
}
public static SettingsHandler getSettings() {
return settings;
}
public static String getLogChannel() {
return logChan;
}
public static void log(String event) {
if (logChan != null) {
ChavaManager.getInstance().getChavaBot().sendMessage(logChan, event);
}
}
public boolean isMuted(String channel) {
return channels.contains(channel);
}
public void muteChannel(String channel) {
channels.add(channel);
}
public void unmuteChannel(String channel) {
channels.remove(channel);
}
}
| true | true | public void onEnable() {
System.out.println("ChavaAdmin enabled");
try {
if (!getDataFolder().exists()) getDataFolder().mkdir();
ChavaAdmin.settings = new SettingsHandler(ChavaAdmin.class.getResource("").openStream(), new File(this.getDataFolder(), "settings.properties"));
ChavaAdmin.settings.load();
ChavaAdmin.logChan = ChavaAdmin.settings.getPropertyString("bot-log-channel", null);
} catch (IOException e) {
getPluginLoader().disablePlugin(this);
e.printStackTrace();
return;
}
ConnectEvent.register(new ConnectListener(), Order.Default, this);
PrivateMessageEvent.register(new PrivateMsgListener(), Order.Default, this);
MessageEvent.register(new MsgListener(), Order.Default, this);
SendMessageEvent.register(new SendMsgListener(this), Order.Latest, this);
SendActionEvent.register(new SendActionListener(this), Order.Latest, this);
SendNoticeEvent.register(new SendNoticeListener(this), Order.Latest, this);
if (ChavaAdmin.settings.checkProperty("muted-channels")) {
String chans = ChavaAdmin.settings.getPropertyString("muted-channels", null);
if (chans != null) {
for (String chan : chans.split(",")) {
channels.add(chan);
}
}
}
}
| public void onEnable() {
System.out.println("ChavaAdmin enabled");
try {
if (!getDataFolder().exists()) getDataFolder().mkdir();
ChavaAdmin.settings = new SettingsHandler(ChavaAdmin.class.getResource("settings").openStream(), new File(this.getDataFolder(), "settings.properties"));
ChavaAdmin.settings.load();
ChavaAdmin.logChan = ChavaAdmin.settings.getPropertyString("bot-log-channel", null);
} catch (IOException e) {
getPluginLoader().disablePlugin(this);
e.printStackTrace();
return;
}
ConnectEvent.register(new ConnectListener(), Order.Default, this);
PrivateMessageEvent.register(new PrivateMsgListener(), Order.Default, this);
MessageEvent.register(new MsgListener(), Order.Default, this);
SendMessageEvent.register(new SendMsgListener(this), Order.Latest, this);
SendActionEvent.register(new SendActionListener(this), Order.Latest, this);
SendNoticeEvent.register(new SendNoticeListener(this), Order.Latest, this);
if (ChavaAdmin.settings.checkProperty("muted-channels")) {
String chans = ChavaAdmin.settings.getPropertyString("muted-channels", null);
if (chans != null) {
for (String chan : chans.split(",")) {
channels.add(chan);
}
}
}
}
|
diff --git a/org.eclipse.mylyn.java.ui/src/org/eclipse/mylyn/internal/java/ui/search/XmlActiveSearchUpdater.java b/org.eclipse.mylyn.java.ui/src/org/eclipse/mylyn/internal/java/ui/search/XmlActiveSearchUpdater.java
index 3f0480b37..c714542b9 100644
--- a/org.eclipse.mylyn.java.ui/src/org/eclipse/mylyn/internal/java/ui/search/XmlActiveSearchUpdater.java
+++ b/org.eclipse.mylyn.java.ui/src/org/eclipse/mylyn/internal/java/ui/search/XmlActiveSearchUpdater.java
@@ -1,101 +1,101 @@
/*******************************************************************************
* Copyright (c) 2004, 2007 Mylyn project committers 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.mylyn.internal.java.ui.search;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IResourceDeltaVisitor;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.mylyn.monitor.core.StatusHandler;
import org.eclipse.search.internal.ui.text.FileSearchResult;
import org.eclipse.search.ui.IQueryListener;
import org.eclipse.search.ui.ISearchQuery;
import org.eclipse.search.ui.NewSearchUI;
import org.eclipse.search.ui.text.Match;
/**
* COPIED FROM: org.eclipse.search.internal.ui.text.SearchResultUpdater
*
* @author Shawn Minto
*
*/
public class XmlActiveSearchUpdater implements IResourceChangeListener, IQueryListener {
private final FileSearchResult fResult;
public XmlActiveSearchUpdater(FileSearchResult result) {
fResult = result;
NewSearchUI.addQueryListener(this);
ResourcesPlugin.getWorkspace().addResourceChangeListener(this);
}
public void resourceChanged(IResourceChangeEvent event) {
IResourceDelta delta = event.getDelta();
if (delta != null) {
handleDelta(delta);
}
}
private void handleDelta(IResourceDelta d) {
try {
d.accept(new IResourceDeltaVisitor() {
public boolean visit(IResourceDelta delta) throws CoreException {
switch (delta.getKind()) {
case IResourceDelta.ADDED:
return false;
case IResourceDelta.REMOVED:
IResource res = delta.getResource();
if (res instanceof IFile) {
Match[] matches = fResult.getMatches(res);
fResult.removeMatches(matches);
- for (Match matche : matches) {
- // Match m = matches[j];
- // XmlNodeHelper xnode =
- // XmlJavaReferencesProvider.nodeMap.remove(m);
- // System.out.println("REMOVED RES: " +
- // xnode.getHandle());
- // System.out.println(XmlJavaReferencesProvider.nodeMap);
- }
+// for (Match matche : matches) {
+// Match m = matches[j];
+// XmlNodeHelper xnode =
+// XmlJavaReferencesProvider.nodeMap.remove(m);
+// System.out.println("REMOVED RES: " +
+// xnode.getHandle());
+// System.out.println(XmlJavaReferencesProvider.nodeMap);
+// }
}
break;
case IResourceDelta.CHANGED:
// TODO want to do something on chages to invalidate
// handle changed resource
break;
}
return true;
}
});
} catch (CoreException e) {
StatusHandler.log(e.getStatus());
}
}
public void queryAdded(ISearchQuery query) {
// don't care
}
public void queryRemoved(ISearchQuery query) {
if (fResult.equals(query.getSearchResult())) {
ResourcesPlugin.getWorkspace().removeResourceChangeListener(this);
NewSearchUI.removeQueryListener(this);
}
}
public void queryStarting(ISearchQuery query) {
// don't care
}
public void queryFinished(ISearchQuery query) {
// don't care
}
}
| true | true | private void handleDelta(IResourceDelta d) {
try {
d.accept(new IResourceDeltaVisitor() {
public boolean visit(IResourceDelta delta) throws CoreException {
switch (delta.getKind()) {
case IResourceDelta.ADDED:
return false;
case IResourceDelta.REMOVED:
IResource res = delta.getResource();
if (res instanceof IFile) {
Match[] matches = fResult.getMatches(res);
fResult.removeMatches(matches);
for (Match matche : matches) {
// Match m = matches[j];
// XmlNodeHelper xnode =
// XmlJavaReferencesProvider.nodeMap.remove(m);
// System.out.println("REMOVED RES: " +
// xnode.getHandle());
// System.out.println(XmlJavaReferencesProvider.nodeMap);
}
}
break;
case IResourceDelta.CHANGED:
// TODO want to do something on chages to invalidate
// handle changed resource
break;
}
return true;
}
});
} catch (CoreException e) {
StatusHandler.log(e.getStatus());
}
}
| private void handleDelta(IResourceDelta d) {
try {
d.accept(new IResourceDeltaVisitor() {
public boolean visit(IResourceDelta delta) throws CoreException {
switch (delta.getKind()) {
case IResourceDelta.ADDED:
return false;
case IResourceDelta.REMOVED:
IResource res = delta.getResource();
if (res instanceof IFile) {
Match[] matches = fResult.getMatches(res);
fResult.removeMatches(matches);
// for (Match matche : matches) {
// Match m = matches[j];
// XmlNodeHelper xnode =
// XmlJavaReferencesProvider.nodeMap.remove(m);
// System.out.println("REMOVED RES: " +
// xnode.getHandle());
// System.out.println(XmlJavaReferencesProvider.nodeMap);
// }
}
break;
case IResourceDelta.CHANGED:
// TODO want to do something on chages to invalidate
// handle changed resource
break;
}
return true;
}
});
} catch (CoreException e) {
StatusHandler.log(e.getStatus());
}
}
|
diff --git a/izpack-api/src/main/java/com/izforge/izpack/api/data/LocaleDatabase.java b/izpack-api/src/main/java/com/izforge/izpack/api/data/LocaleDatabase.java
index ea59dd4c5..32cdc2948 100644
--- a/izpack-api/src/main/java/com/izforge/izpack/api/data/LocaleDatabase.java
+++ b/izpack-api/src/main/java/com/izforge/izpack/api/data/LocaleDatabase.java
@@ -1,180 +1,180 @@
/*
* IzPack - Copyright 2001-2008 Julien Ponge, All Rights Reserved.
*
* http://izpack.org/
* http://izpack.codehaus.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.izforge.izpack.api.data;
import com.izforge.izpack.api.adaptator.IXMLElement;
import com.izforge.izpack.api.adaptator.IXMLParser;
import com.izforge.izpack.api.adaptator.impl.XMLParser;
import com.izforge.izpack.api.exception.IzPackException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
/**
* Represents a database of a locale.
*
* @author Julien Ponge
* @author J. Chris Folsom <[email protected]>
*/
public class LocaleDatabase extends TreeMap<String, String>
{
/*
* Static cache of locale databases mapped by their iso name.
*/
private static Map<String, LocaleDatabase> cachedLocales = new HashMap<String, LocaleDatabase>();
/**
* The directory where language packs are kept inside the installer jar file.
*/
public static final String LOCALE_DATABASE_DIRECTORY = "/langpacks/";
/**
* The suffix for language pack definitions (.xml).
*/
public static final String LOCALE_DATABASE_DEF_SUFFIX = ".xml";
/*
* static character for replacing quotes
*/
private static final char TEMP_QUOTING_CHARACTER = '\uffff';
static final long serialVersionUID = 4941525634108401848L;
/**
* The constructor.
*
* @param in An InputStream to read the translation from.
* @throws Exception Description of the Exception
*/
public LocaleDatabase(InputStream in) throws Exception
{
// We call the superclass default constructor
super();
add(in);
}
/**
* Adds the contents of the given stream to the data base. The stream have to contain key value
* pairs as declared by the DTD langpack.dtd.
*
* @param in an InputStream to read the translation from.
* @throws Exception
*/
public void add(InputStream in)
{
// Initialises the parser
IXMLParser parser = new XMLParser();
// We get the data
IXMLElement data = parser.parse(in);
// We check the data
if (!"langpack".equalsIgnoreCase(data.getName()))
{
throw new IzPackException(
"this is not an IzPack XML langpack file");
}
// We fill the Hashtable
for (IXMLElement child : data.getChildren())
{
String text = child.getContent();
if (text != null && !"".equals(text))
{
put(child.getAttribute("id"), text.trim());
}
else
{
put(child.getAttribute("id"), child.getAttribute("txt"));
}
}
}
/**
* Convenience method to retrieve an element.
*
* @param key The key of the element to retrieve.
* @return The element value or the key if not found.
*/
public String getString(String key)
{
String val = get(key);
// At a change of the return value at val == null the method
// com.izforge.izpack.installer.IzPanel.getI18nStringForClass
// should be also addapted.
if (val == null)
{
val = key;
}
return val;
}
/**
* Convenience method to retrieve an element and simultaneously insert variables into the
* string. A place holder has to be build with the substring {n} where n is the parameter
* argument beginning with 0. The first argument is therefore {0}. If a parameter starts with a
* dollar sign the value will be used as key into the LocalDatabase. The key can be written as
* $MYKEY or ${MYKEY}. For all place holders an argument should be exist and vis a versa.
*
* @param key The key of the element to retrieve.
* @param variables the variables to insert
* @return The element value with the variables inserted or the key if not found.
*/
public String getString(String key, String[] variables)
{
for (int i = 0; i < variables.length; ++i)
{
if (variables[i] == null)
{
// The argument array with index is NULL! Replace it with N/A
variables[i] = "N/A";
}
else if (variables[i].startsWith("$"))
{ // Argument is also a key into the LocaleDatabase.
String curArg = variables[i];
if (curArg.startsWith("${"))
{
curArg = curArg.substring(2, curArg.length() - 1);
}
else
{
curArg = curArg.substring(1);
}
variables[i] = getString(curArg);
}
}
String message = getString(key);
// replace all ' characters because MessageFormat.format()
// don't substitute quoted place holders '{0}'
message = message.replace('\'', TEMP_QUOTING_CHARACTER);
- message = MessageFormat.format(message, new Object[]{variables});
+ message = MessageFormat.format(message, variables);
// replace all ' characters back
return message.replace(TEMP_QUOTING_CHARACTER, '\'');
}
}
| true | true | public String getString(String key, String[] variables)
{
for (int i = 0; i < variables.length; ++i)
{
if (variables[i] == null)
{
// The argument array with index is NULL! Replace it with N/A
variables[i] = "N/A";
}
else if (variables[i].startsWith("$"))
{ // Argument is also a key into the LocaleDatabase.
String curArg = variables[i];
if (curArg.startsWith("${"))
{
curArg = curArg.substring(2, curArg.length() - 1);
}
else
{
curArg = curArg.substring(1);
}
variables[i] = getString(curArg);
}
}
String message = getString(key);
// replace all ' characters because MessageFormat.format()
// don't substitute quoted place holders '{0}'
message = message.replace('\'', TEMP_QUOTING_CHARACTER);
message = MessageFormat.format(message, new Object[]{variables});
// replace all ' characters back
return message.replace(TEMP_QUOTING_CHARACTER, '\'');
}
| public String getString(String key, String[] variables)
{
for (int i = 0; i < variables.length; ++i)
{
if (variables[i] == null)
{
// The argument array with index is NULL! Replace it with N/A
variables[i] = "N/A";
}
else if (variables[i].startsWith("$"))
{ // Argument is also a key into the LocaleDatabase.
String curArg = variables[i];
if (curArg.startsWith("${"))
{
curArg = curArg.substring(2, curArg.length() - 1);
}
else
{
curArg = curArg.substring(1);
}
variables[i] = getString(curArg);
}
}
String message = getString(key);
// replace all ' characters because MessageFormat.format()
// don't substitute quoted place holders '{0}'
message = message.replace('\'', TEMP_QUOTING_CHARACTER);
message = MessageFormat.format(message, variables);
// replace all ' characters back
return message.replace(TEMP_QUOTING_CHARACTER, '\'');
}
|
diff --git a/android/phoenix/src/org/retroarch/browser/RetroArch.java b/android/phoenix/src/org/retroarch/browser/RetroArch.java
index a9c981dfed..ad360f0da7 100644
--- a/android/phoenix/src/org/retroarch/browser/RetroArch.java
+++ b/android/phoenix/src/org/retroarch/browser/RetroArch.java
@@ -1,666 +1,666 @@
package org.retroarch.browser;
import org.retroarch.R;
import java.io.*;
import android.content.*;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.AssetManager;
import android.annotation.TargetApi;
import android.app.*;
import android.media.AudioManager;
import android.net.Uri;
import android.os.*;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.widget.*;
import android.util.Log;
import android.view.*;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.inputmethod.*;
import android.graphics.drawable.*;
class ModuleWrapper implements IconAdapterItem {
public final File file;
private ConfigFile config;
public ModuleWrapper(Context aContext, File aFile, ConfigFile config) throws IOException {
file = aFile;
this.config = config;
}
@Override
public boolean isEnabled() {
return true;
}
@Override
public String getText() {
String stripped = file.getName().replace(".so", "");
if (config.keyExists(stripped)) {
return config.getString(stripped);
} else
return stripped;
}
@Override
public int getIconResourceId() {
return 0;
}
@Override
public Drawable getIconDrawable() {
return null;
}
}
public class RetroArch extends Activity implements
AdapterView.OnItemClickListener {
private IconAdapter<ModuleWrapper> adapter;
static private final int ACTIVITY_LOAD_ROM = 0;
static private String libretro_path;
static private Double report_refreshrate;
static private final String TAG = "RetroArch-Phoenix";
private ConfigFile config;
private ConfigFile core_config;
private final double getDisplayRefreshRate() {
// Android is *very* likely to screw this up.
// It is rarely a good value to use, so make sure it's not
// completely wrong. Some phones return refresh rates that are completely bogus
// (like 0.3 Hz, etc), so try to be very conservative here.
final WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
final Display display = wm.getDefaultDisplay();
double rate = display.getRefreshRate();
if (rate > 61.0 || rate < 58.0)
rate = 59.95;
return rate;
}
private final double getRefreshRate() {
double rate = 0;
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
String refresh_rate = prefs.getString("video_refresh_rate", "");
if (!refresh_rate.isEmpty()) {
try {
rate = Double.parseDouble(refresh_rate);
} catch (NumberFormatException e) {
Log.e(TAG, "Cannot parse: " + refresh_rate + " as a double!");
rate = getDisplayRefreshRate();
}
} else {
rate = getDisplayRefreshRate();
}
Log.i(TAG, "Using refresh rate: " + rate + " Hz.");
return rate;
}
private String readCPUInfo() {
String result = "";
try {
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream("/proc/cpuinfo")));
String line;
while ((line = br.readLine()) != null)
result += line + "\n";
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
return result;
}
private boolean cpuInfoIsNeon(String info) {
return info.contains("neon");
}
private byte[] loadAsset(String asset) throws IOException {
String path = asset;
InputStream stream = getAssets().open(path);
int len = stream.available();
byte[] buf = new byte[len];
stream.read(buf, 0, len);
return buf;
}
private void extractAssets(AssetManager manager, String cacheDir, String relativePath, int level) throws IOException {
final String[] paths = manager.list(relativePath);
if (paths != null && paths.length > 0) { // Directory
//Log.d(TAG, "Extracting assets directory: " + relativePath);
for (final String path : paths)
extractAssets(manager, cacheDir, relativePath + (level > 0 ? File.separator : "") + path, level + 1);
} else { // File, extract.
//Log.d(TAG, "Extracting assets file: " + relativePath);
String parentPath = new File(relativePath).getParent();
if (parentPath != null) {
File parentFile = new File(cacheDir, parentPath);
parentFile.mkdirs(); // Doesn't throw.
}
byte[] asset = loadAsset(relativePath);
BufferedOutputStream writer = new BufferedOutputStream(
new FileOutputStream(new File(cacheDir, relativePath)));
writer.write(asset, 0, asset.length);
writer.flush();
writer.close();
}
}
private void extractAssets() {
int version = 0;
try {
version = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
} catch(NameNotFoundException e) {
// weird exception, shouldn't happen
}
try {
AssetManager assets = getAssets();
String cacheDir = getCacheDir().getAbsolutePath();
File cacheVersion = new File(cacheDir, ".cacheversion");
if (cacheVersion != null && cacheVersion.isFile() && cacheVersion.canRead() && cacheVersion.canWrite())
{
DataInputStream cacheStream = new DataInputStream(new FileInputStream(cacheVersion));
int currentCacheVersion = 0;
try {
currentCacheVersion = cacheStream.readInt();
} catch (IOException e) {}
cacheStream.close();
if (currentCacheVersion == version)
{
Log.i("ASSETS", "Assets already extracted, skipping...");
return;
}
}
//extractAssets(assets, cacheDir, "", 0);
Log.i("ASSETS", "Extracting shader assets now ...");
try {
extractAssets(assets, cacheDir, "Shaders", 1);
} catch (IOException e) {
Log.i("ASSETS", "Failed to extract shaders ...");
}
Log.i("ASSETS", "Extracting overlay assets now ...");
try {
extractAssets(assets, cacheDir, "Overlays", 1);
} catch (IOException e) {
Log.i("ASSETS", "Failed to extract overlays ...");
}
DataOutputStream outputCacheVersion = new DataOutputStream(new FileOutputStream(cacheVersion, false));
outputCacheVersion.writeInt(version);
outputCacheVersion.close();
} catch (IOException e) {
Log.e(TAG, "Failed to extract assets to cache.");
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
config = new ConfigFile(new File(getDefaultConfigPath()));
} catch (IOException e) {
config = new ConfigFile();
}
core_config = new ConfigFile();
try {
core_config.append(getAssets().open("libretro_cores.cfg"));
} catch (IOException e) {
Log.e(TAG, "Failed to load libretro_cores.cfg from assets.");
}
String cpuInfo = readCPUInfo();
boolean cpuIsNeon = cpuInfoIsNeon(cpuInfo);
report_refreshrate = getDisplayRefreshRate();
// Extracting assets appears to take considerable amount of time, so
// move extraction to a thread.
Thread assetThread = new Thread(new Runnable() {
public void run() {
extractAssets();
}
});
assetThread.start();
setContentView(R.layout.line_list);
// Setup the list
adapter = new IconAdapter<ModuleWrapper>(this, R.layout.line_list_item);
ListView list = (ListView) findViewById(R.id.list);
list.setAdapter(adapter);
list.setOnItemClickListener(this);
setTitle("Select Libretro core");
// Populate the list
final String modulePath = getApplicationInfo().nativeLibraryDir;
final File[] libs = new File(modulePath).listFiles();
for (final File lib : libs) {
String libName = lib.getName();
// Never append a NEON lib if we don't have NEON.
if (libName.contains("neon") && !cpuIsNeon)
continue;
// If we have a NEON version with NEON capable CPU,
// never append a non-NEON version.
if (cpuIsNeon && !libName.contains("neon")) {
boolean hasNeonVersion = false;
for (final File lib_ : libs) {
String otherName = lib_.getName();
String baseName = libName.replace(".so", "");
if (otherName.contains("neon") && otherName.startsWith(baseName)) {
hasNeonVersion = true;
break;
}
}
if (hasNeonVersion)
continue;
}
// Allow both libretro-core.so and libretro_core.so.
if (libName.startsWith("libretro") && !libName.startsWith("libretroarch")) {
try {
adapter.add(new ModuleWrapper(this, lib, core_config));
} catch (IOException e) {
e.printStackTrace();
}
}
}
this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
this.registerForContextMenu(findViewById(android.R.id.content));
}
}
@Override
protected void onStart() {
super.onStart();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
if (!prefs.getBoolean("first_time_refreshrate_calculate", false)) {
prefs.edit().putBoolean("first_time_refreshrate_calculate", true).commit();
AlertDialog.Builder alert = new AlertDialog.Builder(this)
.setTitle("Calculate Refresh Rate")
.setMessage("It is highly recommended you run the refresh rate calibration test before you use RetroArch. Do you want to run it now?\n\nIf you choose No, you can run it at any time in the video preferences.\n\nIf you get performance problems even after calibration, please try threaded video driver in video preferences.")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(getBaseContext(), DisplayRefreshRateTest.class);
startActivity(i);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
alert.show();
}
}
@Override
public void onItemClick(AdapterView<?> aListView, View aView,
int aPosition, long aID) {
final ModuleWrapper item = adapter.getItem(aPosition);
libretro_path = item.file.getAbsolutePath();
Intent myIntent;
myIntent = new Intent(this, ROMActivity.class);
startActivityForResult(myIntent, ACTIVITY_LOAD_ROM);
}
private String getDefaultConfigPath() {
String internal = System.getenv("INTERNAL_STORAGE");
String external = System.getenv("EXTERNAL_STORAGE");
if (external != null) {
String confPath = external + File.separator + "retroarch.cfg";
if (new File(confPath).exists())
return confPath;
} else if (internal != null) {
String confPath = internal + File.separator + "retroarch.cfg";
if (new File(confPath).exists())
return confPath;
} else {
String confPath = "/mnt/extsd/retroarch.cfg";
if (new File(confPath).exists())
return confPath;
}
if (internal != null && new File(internal + File.separator + "retroarch.cfg").canWrite())
return internal + File.separator + "retroarch.cfg";
else if (external != null && new File(internal + File.separator + "retroarch.cfg").canWrite())
return external + File.separator + "retroarch.cfg";
else
return getCacheDir().getAbsolutePath() + File.separator + "retroarch.cfg";
}
private void updateConfigFile() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
config.setBoolean("audio_rate_control", prefs.getBoolean("audio_rate_control", true));
config.setBoolean("audio_enable", prefs.getBoolean("audio_enable", true));
config.setBoolean("video_smooth", prefs.getBoolean("video_smooth", true));
config.setBoolean("video_allow_rotate", prefs.getBoolean("video_allow_rotate", true));
config.setBoolean("savestate_auto_load", prefs.getBoolean("savestate_auto_load", false));
config.setBoolean("savestate_auto_save", prefs.getBoolean("savestate_auto_save", false));
config.setBoolean("rewind_enable", prefs.getBoolean("rewind_enable", false));
config.setBoolean("video_vsync", prefs.getBoolean("video_vsync", true));
config.setBoolean("input_autodetect_enable", prefs.getBoolean("input_autodetect_enable", true));
config.setBoolean("input_debug_enable", prefs.getBoolean("input_debug_enable", false));
config.setInt("input_autodetect_icade_profile_pad1", prefs.getInt("input_autodetect_icade_profile_pad1", 0));
config.setInt("input_autodetect_icade_profile_pad2", prefs.getInt("input_autodetect_icade_profile_pad2", 0));
config.setInt("input_autodetect_icade_profile_pad3", prefs.getInt("input_autodetect_icade_profile_pad3", 0));
config.setInt("input_autodetect_icade_profile_pad4", prefs.getInt("input_autodetect_icade_profile_pad4", 0));
config.setDouble("video_refresh_rate", getRefreshRate());
- config.setBoolean("video_threaded", prefs.getBoolean("video_threaded", true));
+ config.setBoolean("video_threaded", prefs.getBoolean("video_threaded", false));
String aspect = prefs.getString("video_aspect_ratio", "auto");
if (aspect.equals("full")) {
config.setBoolean("video_force_aspect", false);
} else if (aspect.equals("auto")) {
config.setBoolean("video_force_aspect", true);
config.setBoolean("video_force_aspect_auto", true);
config.setDouble("video_aspect_ratio", -1.0);
} else if (aspect.equals("square")) {
config.setBoolean("video_force_aspect", true);
config.setBoolean("video_force_aspect_auto", false);
config.setDouble("video_aspect_ratio", -1.0);
} else {
double aspect_ratio = Double.parseDouble(aspect);
config.setBoolean("video_force_aspect", true);
config.setDouble("video_aspect_ratio", aspect_ratio);
}
config.setBoolean("video_scale_integer", prefs.getBoolean("video_scale_integer", false));
String shaderPath = prefs.getString("video_bsnes_shader", "");
if (prefs.getBoolean("video_shader_enable", false) && new File(shaderPath).exists()) {
config.setString("video_shader_type", "bsnes");
config.setString("video_bsnes_shader", shaderPath);
} else {
config.setString("video_shader_type", "none");
config.setString("video_bsnes_shader", "");
}
config.setBoolean("video_render_to_texture", prefs.getBoolean("video_render_to_texture", false));
config.setString("video_second_pass_shader",
prefs.getBoolean("video_second_pass_shader_enable", false) ?
prefs.getString("video_second_pass_shader", "") : "");
config.setBoolean("video_second_pass_smooth", prefs.getBoolean("video_second_pass_smooth", true));
config.setString("video_fbo_scale_x", prefs.getString("video_fbo_scale", "2.0"));
config.setString("video_fbo_scale_y", prefs.getString("video_fbo_scale", "2.0"));
boolean useOverlay = prefs.getBoolean("input_overlay_enable", true);
if (useOverlay) {
String overlayPath = prefs.getString("input_overlay", getCacheDir() + "/Overlays/snes-landscape.cfg");
config.setString("input_overlay", overlayPath);
config.setDouble("input_overlay_opacity", prefs.getFloat("input_overlay_opacity", 1.0f));
} else {
config.setString("input_overlay", "");
}
config.setString("savefile_directory", prefs.getBoolean("savefile_directory_enable", false) ?
prefs.getString("savefile_directory", "") : "");
config.setString("savestate_directory", prefs.getBoolean("savestate_directory_enable", false) ?
prefs.getString("savestate_directory", "") : "");
config.setBoolean("video_font_enable", prefs.getBoolean("video_font_enable", true));
for (int i = 1; i <= 4; i++)
{
final String btns[] = {"up", "down", "left", "right", "a", "b", "x", "y", "start", "select", "l", "r", "l2", "r2", "l3", "r3" };
for (String b : btns)
{
String p = "input_player" + String.valueOf(i) + "_" + b + "_btn";
config.setInt(p, prefs.getInt(p, 0));
}
}
String confPath = getDefaultConfigPath();
try {
config.write(new File(confPath));
} catch (IOException e) {
Log.e(TAG, "Failed to save config file to: " + confPath);
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Intent myIntent;
String current_ime = Settings.Secure.getString(getContentResolver(), Settings.Secure.DEFAULT_INPUT_METHOD);
updateConfigFile();
switch (requestCode) {
case ACTIVITY_LOAD_ROM:
if (data.getStringExtra("PATH") != null) {
Toast.makeText(this,
"Loading: [" + data.getStringExtra("PATH") + "]...",
Toast.LENGTH_SHORT).show();
myIntent = new Intent(this, NativeActivity.class);
myIntent.putExtra("ROM", data.getStringExtra("PATH"));
myIntent.putExtra("LIBRETRO", libretro_path);
myIntent.putExtra("CONFIGFILE", getDefaultConfigPath());
myIntent.putExtra("IME", current_ime);
startActivity(myIntent);
}
break;
}
}
@Override
public boolean onCreateOptionsMenu(Menu aMenu) {
super.onCreateOptionsMenu(aMenu);
getMenuInflater().inflate(R.menu.directory_list, aMenu);
return true;
}
public void showPopup(View v) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
{
PopupMenuAbstract menu = new PopupMenuAbstract(this, v);
MenuInflater inflater = menu.getMenuInflater();
inflater.inflate(R.menu.context_menu, menu.getMenu());
menu.setOnMenuItemClickListener(new PopupMenuAbstract.OnMenuItemClickListener()
{
@Override
public boolean onMenuItemClick(MenuItem item) {
return onContextItemSelected(item);
}
});
menu.show();
}
else
{
this.openContextMenu(findViewById(android.R.id.content));
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem aItem) {
switch (aItem.getItemId()) {
case R.id.settings:
showPopup(findViewById(R.id.settings));
return true;
default:
return super.onOptionsItemSelected(aItem);
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.input_method_select:
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showInputMethodPicker();
return true;
case R.id.rarch_settings:
Intent rset = new Intent(this, SettingsActivity.class);
startActivity(rset);
return true;
case R.id.help:
Intent help = new Intent(this, HelpActivity.class);
startActivity(help);
return true;
case R.id.report_ime:
String current_ime = Settings.Secure.getString(getContentResolver(), Settings.Secure.DEFAULT_INPUT_METHOD);
new AlertDialog.Builder(this).setMessage(current_ime).setNeutralButton("Close", null).show();
return true;
case R.id.report_refreshrate:
String current_rate = "Screen Refresh Rate: " + Double.valueOf(report_refreshrate).toString();
new AlertDialog.Builder(this).setMessage(current_rate).setNeutralButton("Close", null).show();
return true;
case R.id.retroarch_guide:
Intent rguide = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.libretro.org/documents/retroarch-manual.pdf"));
startActivity(rguide);
return true;
case R.id.cores_guide:
Intent cguide = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.libretro.org/documents/retroarch-cores-manual.pdf"));
startActivity(cguide);
return true;
case R.id.overlay_guide:
Intent mguide = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.libretro.org/documents/overlay.pdf"));
startActivity(mguide);
return true;
default:
return false;
}
}
}
abstract class LazyPopupMenu {
public abstract Menu getMenu();
public abstract MenuInflater getMenuInflater();
public abstract void setOnMenuItemClickListener(LazyPopupMenu.OnMenuItemClickListener listener);
public abstract void show();
public interface OnMenuItemClickListener {
public abstract boolean onMenuItemClick(MenuItem item);
}
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
class HoneycombPopupMenu extends LazyPopupMenu {
private PopupMenu instance;
HoneycombPopupMenu.OnMenuItemClickListener listen;
public HoneycombPopupMenu(Context context, View anchor)
{
instance = new PopupMenu(context, anchor);
}
@Override
public void setOnMenuItemClickListener(HoneycombPopupMenu.OnMenuItemClickListener listener)
{
listen = listener;
instance.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
return listen.onMenuItemClick(item);
}
});
}
@Override
public Menu getMenu() {
return instance.getMenu();
}
@Override
public MenuInflater getMenuInflater() {
return instance.getMenuInflater();
}
@Override
public void show() {
instance.show();
}
}
class PopupMenuAbstract extends LazyPopupMenu
{
private LazyPopupMenu lazy;
public PopupMenuAbstract(Context context, View anchor)
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
{
lazy = new HoneycombPopupMenu(context, anchor);
}
}
@Override
public Menu getMenu() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
{
return lazy.getMenu();
}
else
{
return null;
}
}
@Override
public MenuInflater getMenuInflater() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
{
return lazy.getMenuInflater();
}
else
{
return null;
}
}
@Override
public void setOnMenuItemClickListener(PopupMenuAbstract.OnMenuItemClickListener listener) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
{
lazy.setOnMenuItemClickListener(listener);
}
}
@Override
public void show() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
{
lazy.show();
}
}
}
| true | true | private void updateConfigFile() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
config.setBoolean("audio_rate_control", prefs.getBoolean("audio_rate_control", true));
config.setBoolean("audio_enable", prefs.getBoolean("audio_enable", true));
config.setBoolean("video_smooth", prefs.getBoolean("video_smooth", true));
config.setBoolean("video_allow_rotate", prefs.getBoolean("video_allow_rotate", true));
config.setBoolean("savestate_auto_load", prefs.getBoolean("savestate_auto_load", false));
config.setBoolean("savestate_auto_save", prefs.getBoolean("savestate_auto_save", false));
config.setBoolean("rewind_enable", prefs.getBoolean("rewind_enable", false));
config.setBoolean("video_vsync", prefs.getBoolean("video_vsync", true));
config.setBoolean("input_autodetect_enable", prefs.getBoolean("input_autodetect_enable", true));
config.setBoolean("input_debug_enable", prefs.getBoolean("input_debug_enable", false));
config.setInt("input_autodetect_icade_profile_pad1", prefs.getInt("input_autodetect_icade_profile_pad1", 0));
config.setInt("input_autodetect_icade_profile_pad2", prefs.getInt("input_autodetect_icade_profile_pad2", 0));
config.setInt("input_autodetect_icade_profile_pad3", prefs.getInt("input_autodetect_icade_profile_pad3", 0));
config.setInt("input_autodetect_icade_profile_pad4", prefs.getInt("input_autodetect_icade_profile_pad4", 0));
config.setDouble("video_refresh_rate", getRefreshRate());
config.setBoolean("video_threaded", prefs.getBoolean("video_threaded", true));
String aspect = prefs.getString("video_aspect_ratio", "auto");
if (aspect.equals("full")) {
config.setBoolean("video_force_aspect", false);
} else if (aspect.equals("auto")) {
config.setBoolean("video_force_aspect", true);
config.setBoolean("video_force_aspect_auto", true);
config.setDouble("video_aspect_ratio", -1.0);
} else if (aspect.equals("square")) {
config.setBoolean("video_force_aspect", true);
config.setBoolean("video_force_aspect_auto", false);
config.setDouble("video_aspect_ratio", -1.0);
} else {
double aspect_ratio = Double.parseDouble(aspect);
config.setBoolean("video_force_aspect", true);
config.setDouble("video_aspect_ratio", aspect_ratio);
}
config.setBoolean("video_scale_integer", prefs.getBoolean("video_scale_integer", false));
String shaderPath = prefs.getString("video_bsnes_shader", "");
if (prefs.getBoolean("video_shader_enable", false) && new File(shaderPath).exists()) {
config.setString("video_shader_type", "bsnes");
config.setString("video_bsnes_shader", shaderPath);
} else {
config.setString("video_shader_type", "none");
config.setString("video_bsnes_shader", "");
}
config.setBoolean("video_render_to_texture", prefs.getBoolean("video_render_to_texture", false));
config.setString("video_second_pass_shader",
prefs.getBoolean("video_second_pass_shader_enable", false) ?
prefs.getString("video_second_pass_shader", "") : "");
config.setBoolean("video_second_pass_smooth", prefs.getBoolean("video_second_pass_smooth", true));
config.setString("video_fbo_scale_x", prefs.getString("video_fbo_scale", "2.0"));
config.setString("video_fbo_scale_y", prefs.getString("video_fbo_scale", "2.0"));
boolean useOverlay = prefs.getBoolean("input_overlay_enable", true);
if (useOverlay) {
String overlayPath = prefs.getString("input_overlay", getCacheDir() + "/Overlays/snes-landscape.cfg");
config.setString("input_overlay", overlayPath);
config.setDouble("input_overlay_opacity", prefs.getFloat("input_overlay_opacity", 1.0f));
} else {
config.setString("input_overlay", "");
}
config.setString("savefile_directory", prefs.getBoolean("savefile_directory_enable", false) ?
prefs.getString("savefile_directory", "") : "");
config.setString("savestate_directory", prefs.getBoolean("savestate_directory_enable", false) ?
prefs.getString("savestate_directory", "") : "");
config.setBoolean("video_font_enable", prefs.getBoolean("video_font_enable", true));
for (int i = 1; i <= 4; i++)
{
final String btns[] = {"up", "down", "left", "right", "a", "b", "x", "y", "start", "select", "l", "r", "l2", "r2", "l3", "r3" };
for (String b : btns)
{
String p = "input_player" + String.valueOf(i) + "_" + b + "_btn";
config.setInt(p, prefs.getInt(p, 0));
}
}
String confPath = getDefaultConfigPath();
try {
config.write(new File(confPath));
} catch (IOException e) {
Log.e(TAG, "Failed to save config file to: " + confPath);
}
}
| private void updateConfigFile() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
config.setBoolean("audio_rate_control", prefs.getBoolean("audio_rate_control", true));
config.setBoolean("audio_enable", prefs.getBoolean("audio_enable", true));
config.setBoolean("video_smooth", prefs.getBoolean("video_smooth", true));
config.setBoolean("video_allow_rotate", prefs.getBoolean("video_allow_rotate", true));
config.setBoolean("savestate_auto_load", prefs.getBoolean("savestate_auto_load", false));
config.setBoolean("savestate_auto_save", prefs.getBoolean("savestate_auto_save", false));
config.setBoolean("rewind_enable", prefs.getBoolean("rewind_enable", false));
config.setBoolean("video_vsync", prefs.getBoolean("video_vsync", true));
config.setBoolean("input_autodetect_enable", prefs.getBoolean("input_autodetect_enable", true));
config.setBoolean("input_debug_enable", prefs.getBoolean("input_debug_enable", false));
config.setInt("input_autodetect_icade_profile_pad1", prefs.getInt("input_autodetect_icade_profile_pad1", 0));
config.setInt("input_autodetect_icade_profile_pad2", prefs.getInt("input_autodetect_icade_profile_pad2", 0));
config.setInt("input_autodetect_icade_profile_pad3", prefs.getInt("input_autodetect_icade_profile_pad3", 0));
config.setInt("input_autodetect_icade_profile_pad4", prefs.getInt("input_autodetect_icade_profile_pad4", 0));
config.setDouble("video_refresh_rate", getRefreshRate());
config.setBoolean("video_threaded", prefs.getBoolean("video_threaded", false));
String aspect = prefs.getString("video_aspect_ratio", "auto");
if (aspect.equals("full")) {
config.setBoolean("video_force_aspect", false);
} else if (aspect.equals("auto")) {
config.setBoolean("video_force_aspect", true);
config.setBoolean("video_force_aspect_auto", true);
config.setDouble("video_aspect_ratio", -1.0);
} else if (aspect.equals("square")) {
config.setBoolean("video_force_aspect", true);
config.setBoolean("video_force_aspect_auto", false);
config.setDouble("video_aspect_ratio", -1.0);
} else {
double aspect_ratio = Double.parseDouble(aspect);
config.setBoolean("video_force_aspect", true);
config.setDouble("video_aspect_ratio", aspect_ratio);
}
config.setBoolean("video_scale_integer", prefs.getBoolean("video_scale_integer", false));
String shaderPath = prefs.getString("video_bsnes_shader", "");
if (prefs.getBoolean("video_shader_enable", false) && new File(shaderPath).exists()) {
config.setString("video_shader_type", "bsnes");
config.setString("video_bsnes_shader", shaderPath);
} else {
config.setString("video_shader_type", "none");
config.setString("video_bsnes_shader", "");
}
config.setBoolean("video_render_to_texture", prefs.getBoolean("video_render_to_texture", false));
config.setString("video_second_pass_shader",
prefs.getBoolean("video_second_pass_shader_enable", false) ?
prefs.getString("video_second_pass_shader", "") : "");
config.setBoolean("video_second_pass_smooth", prefs.getBoolean("video_second_pass_smooth", true));
config.setString("video_fbo_scale_x", prefs.getString("video_fbo_scale", "2.0"));
config.setString("video_fbo_scale_y", prefs.getString("video_fbo_scale", "2.0"));
boolean useOverlay = prefs.getBoolean("input_overlay_enable", true);
if (useOverlay) {
String overlayPath = prefs.getString("input_overlay", getCacheDir() + "/Overlays/snes-landscape.cfg");
config.setString("input_overlay", overlayPath);
config.setDouble("input_overlay_opacity", prefs.getFloat("input_overlay_opacity", 1.0f));
} else {
config.setString("input_overlay", "");
}
config.setString("savefile_directory", prefs.getBoolean("savefile_directory_enable", false) ?
prefs.getString("savefile_directory", "") : "");
config.setString("savestate_directory", prefs.getBoolean("savestate_directory_enable", false) ?
prefs.getString("savestate_directory", "") : "");
config.setBoolean("video_font_enable", prefs.getBoolean("video_font_enable", true));
for (int i = 1; i <= 4; i++)
{
final String btns[] = {"up", "down", "left", "right", "a", "b", "x", "y", "start", "select", "l", "r", "l2", "r2", "l3", "r3" };
for (String b : btns)
{
String p = "input_player" + String.valueOf(i) + "_" + b + "_btn";
config.setInt(p, prefs.getInt(p, 0));
}
}
String confPath = getDefaultConfigPath();
try {
config.write(new File(confPath));
} catch (IOException e) {
Log.e(TAG, "Failed to save config file to: " + confPath);
}
}
|
diff --git a/src/edu/brown/cs32/goingrogue/gameobjects/creatures/AICreature.java b/src/edu/brown/cs32/goingrogue/gameobjects/creatures/AICreature.java
index 9c3d2c4..2a1d3f6 100755
--- a/src/edu/brown/cs32/goingrogue/gameobjects/creatures/AICreature.java
+++ b/src/edu/brown/cs32/goingrogue/gameobjects/creatures/AICreature.java
@@ -1,70 +1,70 @@
package edu.brown.cs32.goingrogue.gameobjects.creatures;
import edu.brown.cs32.goingrogue.gameobjects.actions.Action;
import edu.brown.cs32.goingrogue.gameobjects.actions.MoveAction;
import edu.brown.cs32.goingrogue.util.CreatureSize;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.List;
import static edu.brown.cs32.bweedon.geometry.Point2DUtil.getAngleFromTo;
import edu.brown.cs32.goingrogue.gameobjects.actions.ArcAttackAction;
import edu.brown.cs32.jcadler.GameLogic.RogueMap.Room;
/**
*
* @author Ben Weedon (bweedon)
*/
public class AICreature extends Creature {
private List<Creature> _creatures;
private List<Room> _rooms;
private final double DIST_TO_ATTACK = 0.5;
public AICreature(Point2D.Double pos, double direction, String name, List<Attribute> attributes,
CreatureStats stats, String spritePath, CreatureSize size, List<Creature> creatures,
List<Room> rooms) {
super(pos, direction, name, attributes, stats, spritePath, size);
_creatures = creatures;
_rooms = rooms;
}
@Override
public boolean isItem() {
return false;
}
@Override
public List<Action> getActionsWithUpdate(int delta) {
Creature closestCreature = null;
for (int i = 0; i < _creatures.size(); ++i) {
Creature currCreature = _creatures.get(i);
Point2D currCreaturePos = currCreature.getPosition();
if (closestCreature == null) {
closestCreature = currCreature;
} else if ((getPosition().distance(currCreaturePos)
< getPosition().distance(closestCreature.getPosition()))
&& (!currCreature.equals(this))
&& (currCreature.getAttributes().contains(Attribute.PLAYER))) {
closestCreature = currCreature;
}
}
List<Action> returnActions = new ArrayList<>();
if (closestCreature != null) {
setDirection(getAngleFromTo(getPosition(), closestCreature.getPosition()));
if (getPosition().distance(closestCreature.getPosition()) < DIST_TO_ATTACK) {
returnActions.add(
new ArcAttackAction(getDirection(), getWeaponRange(), getWeaponArcLength(),
getWeaponAttackTimer(), this));
- //return returnActions;
+ return returnActions;
} else {
returnActions.add(new MoveAction(getDirection(), this));
- // return returnActions;
+ return returnActions;
}
}
-// setActions(returnActions);
-// return returnActions;
- return new ArrayList<>();
+ setActions(returnActions);
+ return returnActions;
+// return new ArrayList<>();
}
}
| false | true | public List<Action> getActionsWithUpdate(int delta) {
Creature closestCreature = null;
for (int i = 0; i < _creatures.size(); ++i) {
Creature currCreature = _creatures.get(i);
Point2D currCreaturePos = currCreature.getPosition();
if (closestCreature == null) {
closestCreature = currCreature;
} else if ((getPosition().distance(currCreaturePos)
< getPosition().distance(closestCreature.getPosition()))
&& (!currCreature.equals(this))
&& (currCreature.getAttributes().contains(Attribute.PLAYER))) {
closestCreature = currCreature;
}
}
List<Action> returnActions = new ArrayList<>();
if (closestCreature != null) {
setDirection(getAngleFromTo(getPosition(), closestCreature.getPosition()));
if (getPosition().distance(closestCreature.getPosition()) < DIST_TO_ATTACK) {
returnActions.add(
new ArcAttackAction(getDirection(), getWeaponRange(), getWeaponArcLength(),
getWeaponAttackTimer(), this));
//return returnActions;
} else {
returnActions.add(new MoveAction(getDirection(), this));
// return returnActions;
}
}
// setActions(returnActions);
// return returnActions;
return new ArrayList<>();
}
| public List<Action> getActionsWithUpdate(int delta) {
Creature closestCreature = null;
for (int i = 0; i < _creatures.size(); ++i) {
Creature currCreature = _creatures.get(i);
Point2D currCreaturePos = currCreature.getPosition();
if (closestCreature == null) {
closestCreature = currCreature;
} else if ((getPosition().distance(currCreaturePos)
< getPosition().distance(closestCreature.getPosition()))
&& (!currCreature.equals(this))
&& (currCreature.getAttributes().contains(Attribute.PLAYER))) {
closestCreature = currCreature;
}
}
List<Action> returnActions = new ArrayList<>();
if (closestCreature != null) {
setDirection(getAngleFromTo(getPosition(), closestCreature.getPosition()));
if (getPosition().distance(closestCreature.getPosition()) < DIST_TO_ATTACK) {
returnActions.add(
new ArcAttackAction(getDirection(), getWeaponRange(), getWeaponArcLength(),
getWeaponAttackTimer(), this));
return returnActions;
} else {
returnActions.add(new MoveAction(getDirection(), this));
return returnActions;
}
}
setActions(returnActions);
return returnActions;
// return new ArrayList<>();
}
|
diff --git a/JMapMatchingGUI/src/org/life/sl/readers/osm/OSMFileReader.java b/JMapMatchingGUI/src/org/life/sl/readers/osm/OSMFileReader.java
index 3bffed9..f404168 100644
--- a/JMapMatchingGUI/src/org/life/sl/readers/osm/OSMFileReader.java
+++ b/JMapMatchingGUI/src/org/life/sl/readers/osm/OSMFileReader.java
@@ -1,124 +1,124 @@
package org.life.sl.readers.osm;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import org.life.sl.graphs.PathSegmentGraph;
import org.openstreetmap.josm.Main;
import org.openstreetmap.josm.data.Preferences;
import org.openstreetmap.josm.data.coor.LatLon;
import org.openstreetmap.josm.data.osm.DataSet;
import org.openstreetmap.josm.data.osm.Node;
import org.openstreetmap.josm.data.osm.Way;
import org.openstreetmap.josm.data.projection.Epsg4326;
import org.openstreetmap.josm.io.IllegalDataException;
import org.openstreetmap.josm.io.OsmReader;
import org.openstreetmap.josm.tools.Pair;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.CoordinateSequence;
import com.vividsolutions.jts.geom.CoordinateSequenceFactory;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.LineString;
//import com.vividsolutions.jts.operation.linemerge.LineMergeGraph;
/**
* @author Bernhard Snizek <[email protected]>
*
*/
public class OSMFileReader {
private static PathSegmentGraph psg;
private static GeometryFactory gf;
public OSMFileReader() {
// initialize the geometry factory
gf = new GeometryFactory();
psg = new PathSegmentGraph();
}
/**
* loads an OSM File and builds up the road Network (Path Segmented Graph)
*
* @param osmFileName : OSM File Name as a String
* @throws FileNotFoundException
* @throws IllegalDataException
*
*/
public void readOSMFile(String osmFileName) throws FileNotFoundException, IllegalDataException {
Main.pref = new Preferences();
Main.proj = new Epsg4326();
Main.pref.put("tags.direction", false);
DataSet dsRestriction = OsmReader.parseDataSet(new FileInputStream(osmFileName), null);
Collection<Way> ways = dsRestriction.getWays();
for (Way way : ways) {
if (way.get("highway") != null) {
if (way.get("highway").equals("residential")) {
String roadName = way.getName();
System.out.println(roadName);
List<Node> nodes = way.getNodes();
Coordinate[] array1 = new Coordinate[nodes.size()];
int counter = 0;
for (Node node : nodes) {
LatLon ll = node.getCoor();
Coordinate c = new Coordinate(ll.lat(), ll.lon()); // z = 0, no elevation
array1[counter] = c;
counter = counter +1;
}
com.vividsolutions.jts.geom.GeometryFactory fact = new com.vividsolutions.jts.geom.GeometryFactory();
com.vividsolutions.jts.geom.LineString lineString = fact.createLineString(array1);
HashMap<String, Object> hm = new HashMap<String, Object>();
hm.put("roadname", roadName);
hm.put("geometry", lineString);
lineString.setUserData(hm);
- psg.addLineString(lineString);
+ psg.addLineString(lineString, (int) way.getId());
}
}
}
}
public void readOnline() {
}
public PathSegmentGraph asLineMergeGraph() {
return psg;
}
// /**
// * @param args
// * @throws FileNotFoundException
// * @throws IllegalDataException
// */
// public static void main(String[] args) throws FileNotFoundException, IllegalDataException {
// String filename = "testdata/testnet.osm";
// OSMFileReader osm_reader = new OSMFileReader();
// osm_reader.readOSMFile(filename);
// PathSegmentGraph psg = osm_reader.asLineMergeGraph();
// }
}
| true | true | public void readOSMFile(String osmFileName) throws FileNotFoundException, IllegalDataException {
Main.pref = new Preferences();
Main.proj = new Epsg4326();
Main.pref.put("tags.direction", false);
DataSet dsRestriction = OsmReader.parseDataSet(new FileInputStream(osmFileName), null);
Collection<Way> ways = dsRestriction.getWays();
for (Way way : ways) {
if (way.get("highway") != null) {
if (way.get("highway").equals("residential")) {
String roadName = way.getName();
System.out.println(roadName);
List<Node> nodes = way.getNodes();
Coordinate[] array1 = new Coordinate[nodes.size()];
int counter = 0;
for (Node node : nodes) {
LatLon ll = node.getCoor();
Coordinate c = new Coordinate(ll.lat(), ll.lon()); // z = 0, no elevation
array1[counter] = c;
counter = counter +1;
}
com.vividsolutions.jts.geom.GeometryFactory fact = new com.vividsolutions.jts.geom.GeometryFactory();
com.vividsolutions.jts.geom.LineString lineString = fact.createLineString(array1);
HashMap<String, Object> hm = new HashMap<String, Object>();
hm.put("roadname", roadName);
hm.put("geometry", lineString);
lineString.setUserData(hm);
psg.addLineString(lineString);
}
}
}
}
| public void readOSMFile(String osmFileName) throws FileNotFoundException, IllegalDataException {
Main.pref = new Preferences();
Main.proj = new Epsg4326();
Main.pref.put("tags.direction", false);
DataSet dsRestriction = OsmReader.parseDataSet(new FileInputStream(osmFileName), null);
Collection<Way> ways = dsRestriction.getWays();
for (Way way : ways) {
if (way.get("highway") != null) {
if (way.get("highway").equals("residential")) {
String roadName = way.getName();
System.out.println(roadName);
List<Node> nodes = way.getNodes();
Coordinate[] array1 = new Coordinate[nodes.size()];
int counter = 0;
for (Node node : nodes) {
LatLon ll = node.getCoor();
Coordinate c = new Coordinate(ll.lat(), ll.lon()); // z = 0, no elevation
array1[counter] = c;
counter = counter +1;
}
com.vividsolutions.jts.geom.GeometryFactory fact = new com.vividsolutions.jts.geom.GeometryFactory();
com.vividsolutions.jts.geom.LineString lineString = fact.createLineString(array1);
HashMap<String, Object> hm = new HashMap<String, Object>();
hm.put("roadname", roadName);
hm.put("geometry", lineString);
lineString.setUserData(hm);
psg.addLineString(lineString, (int) way.getId());
}
}
}
}
|
diff --git a/src/main/java/mobisocial/socialkit/musubi/DbUser.java b/src/main/java/mobisocial/socialkit/musubi/DbUser.java
index cf7fc70..4e21fa1 100644
--- a/src/main/java/mobisocial/socialkit/musubi/DbUser.java
+++ b/src/main/java/mobisocial/socialkit/musubi/DbUser.java
@@ -1,160 +1,164 @@
/*
* Copyright (C) 2011 The Stanford MobiSocial Laboratory
*
* 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 mobisocial.socialkit.musubi;
import java.io.UnsupportedEncodingException;
import java.security.KeyFactory;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.X509EncodedKeySpec;
import mobisocial.socialkit.User;
import mobisocial.socialkit.util.FastBase64;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.util.Log;
/**
* A User object with details backed by a database cursor.
*
*/
public class DbUser implements User {
static final String COL_ID = "_id";
static final String COL_NAME = "name";
static final String COL_PUBLIC_KEY = "public_key";
static final String COL_PERSON_ID = "person_id";
static final String COL_PICTURE = "picture";
static final long LOCAL_USER_ID = -666;
private final long mLocalId;
private final String mId;
private final String mName;
private final Uri mFeedUri;
private final boolean mIsLocalUser;
private final Context mContext;
DbUser(Context context, boolean isLocalUser, String name, long localId, String personId,
Uri feedUri) {
mIsLocalUser = isLocalUser;
mName = name;
mId = personId;
mFeedUri = feedUri;
mContext = context;
mLocalId = localId;
}
public String getId() {
return mId;
}
/**
* Returns the local database id for this user.
*/
public long getLocalId() {
return mLocalId;
}
public String getName() {
return mName;
}
public Bitmap getPicture() {
Uri uri;
if (!mIsLocalUser) {
uri = Uri.parse("content://" + Musubi.AUTHORITY + "/members/" +
mFeedUri.getLastPathSegment());
} else {
uri = Uri.parse("content://" + Musubi.AUTHORITY + "/local_user/" +
mFeedUri.getLastPathSegment());
}
String[] projection = { COL_PICTURE };
String selection = null;
String[] selectionArgs = null;
String sortOrder = null;
Cursor c = mContext.getContentResolver().query(
uri, projection, selection, selectionArgs, sortOrder);
try {
if (c == null || !c.moveToFirst()) {
Log.w(Musubi.TAG, "No picture found for " + mId);
return null;
}
byte[] pic = c.getBlob(c.getColumnIndexOrThrow(COL_PICTURE));
+ if(pic == null) {
+ Log.w(Musubi.TAG, "No picture found for " + mId);
+ return null;
+ }
return BitmapFactory.decodeByteArray(pic, 0, pic.length);
} finally {
if (c != null) {
c.close();
}
}
}
static RSAPublicKey publicKeyFromString(String str){
try{
byte[] pubKeyBytes = FastBase64.decode(str);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(pubKeyBytes);
return (RSAPublicKey)keyFactory.generatePublic(publicKeySpec);
}
catch(Exception e){
throw new IllegalStateException("Error loading public key: " + e);
}
}
// TODO: This is synchronized with bumblebee's Util.makePersonId.
// bumblebee should depend on SocialKit and call this method.
static String makePersonIdForPublicKey(PublicKey key) {
String me = null;
try {
me = SHA1(key.getEncoded());
} catch (Exception e) {
throw new IllegalArgumentException("Could not compute SHA1 of public key.", e);
}
return me.substring(0, 10);
}
private static String SHA1(byte[] input) throws NoSuchAlgorithmException,
UnsupportedEncodingException {
MessageDigest md;
md = MessageDigest.getInstance("SHA-1");
byte[] sha1hash = new byte[40];
md.update(input, 0, input.length);
sha1hash = md.digest();
return convertToHex(sha1hash);
}
private static String convertToHex(byte[] data) {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < data.length; i++) {
int halfbyte = (data[i] >>> 4) & 0x0F;
int two_halfs = 0;
do {
if ((0 <= halfbyte) && (halfbyte <= 9)) {
buf.append((char) ('0' + halfbyte));
} else {
buf.append((char) ('a' + (halfbyte - 10)));
}
halfbyte = data[i] & 0x0F;
} while (two_halfs++ < 1);
}
return buf.toString();
}
}
| true | true | public Bitmap getPicture() {
Uri uri;
if (!mIsLocalUser) {
uri = Uri.parse("content://" + Musubi.AUTHORITY + "/members/" +
mFeedUri.getLastPathSegment());
} else {
uri = Uri.parse("content://" + Musubi.AUTHORITY + "/local_user/" +
mFeedUri.getLastPathSegment());
}
String[] projection = { COL_PICTURE };
String selection = null;
String[] selectionArgs = null;
String sortOrder = null;
Cursor c = mContext.getContentResolver().query(
uri, projection, selection, selectionArgs, sortOrder);
try {
if (c == null || !c.moveToFirst()) {
Log.w(Musubi.TAG, "No picture found for " + mId);
return null;
}
byte[] pic = c.getBlob(c.getColumnIndexOrThrow(COL_PICTURE));
return BitmapFactory.decodeByteArray(pic, 0, pic.length);
} finally {
if (c != null) {
c.close();
}
}
}
| public Bitmap getPicture() {
Uri uri;
if (!mIsLocalUser) {
uri = Uri.parse("content://" + Musubi.AUTHORITY + "/members/" +
mFeedUri.getLastPathSegment());
} else {
uri = Uri.parse("content://" + Musubi.AUTHORITY + "/local_user/" +
mFeedUri.getLastPathSegment());
}
String[] projection = { COL_PICTURE };
String selection = null;
String[] selectionArgs = null;
String sortOrder = null;
Cursor c = mContext.getContentResolver().query(
uri, projection, selection, selectionArgs, sortOrder);
try {
if (c == null || !c.moveToFirst()) {
Log.w(Musubi.TAG, "No picture found for " + mId);
return null;
}
byte[] pic = c.getBlob(c.getColumnIndexOrThrow(COL_PICTURE));
if(pic == null) {
Log.w(Musubi.TAG, "No picture found for " + mId);
return null;
}
return BitmapFactory.decodeByteArray(pic, 0, pic.length);
} finally {
if (c != null) {
c.close();
}
}
}
|
diff --git a/public/java/src/org/broadinstitute/sting/gatk/walkers/variantrecalibration/VariantDataManager.java b/public/java/src/org/broadinstitute/sting/gatk/walkers/variantrecalibration/VariantDataManager.java
index a2782fe34..a957bfd85 100755
--- a/public/java/src/org/broadinstitute/sting/gatk/walkers/variantrecalibration/VariantDataManager.java
+++ b/public/java/src/org/broadinstitute/sting/gatk/walkers/variantrecalibration/VariantDataManager.java
@@ -1,295 +1,295 @@
/*
* Copyright (c) 2011 The Broad Institute
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
* THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.broadinstitute.sting.gatk.walkers.variantrecalibration;
import org.apache.log4j.Logger;
import org.broadinstitute.sting.gatk.GenomeAnalysisEngine;
import org.broadinstitute.sting.gatk.refdata.RefMetaDataTracker;
import org.broadinstitute.sting.utils.GenomeLoc;
import org.broadinstitute.sting.utils.MathUtils;
import org.broadinstitute.sting.utils.collections.ExpandingArrayList;
import org.broadinstitute.sting.utils.exceptions.UserException;
import org.broadinstitute.sting.utils.variantcontext.VariantContext;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Created by IntelliJ IDEA.
* User: rpoplin
* Date: Mar 4, 2011
*/
public class VariantDataManager {
private ExpandingArrayList<VariantDatum> data;
private final double[] meanVector;
private final double[] varianceVector; // this is really the standard deviation
public final List<String> annotationKeys;
private final VariantRecalibratorArgumentCollection VRAC;
protected final static Logger logger = Logger.getLogger(VariantDataManager.class);
protected final List<TrainingSet> trainingSets;
public VariantDataManager( final List<String> annotationKeys, final VariantRecalibratorArgumentCollection VRAC ) {
this.data = null;
this.annotationKeys = new ArrayList<String>( annotationKeys );
this.VRAC = VRAC;
meanVector = new double[this.annotationKeys.size()];
varianceVector = new double[this.annotationKeys.size()];
trainingSets = new ArrayList<TrainingSet>();
}
public void setData( final ExpandingArrayList<VariantDatum> data ) {
this.data = data;
}
public ExpandingArrayList<VariantDatum> getData() {
return data;
}
public void normalizeData() {
boolean foundZeroVarianceAnnotation = false;
for( int iii = 0; iii < meanVector.length; iii++ ) {
final double theMean = mean(iii);
final double theSTD = standardDeviation(theMean, iii);
logger.info( annotationKeys.get(iii) + String.format(": \t mean = %.2f\t standard deviation = %.2f", theMean, theSTD) );
if( Double.isNaN(theMean) ) {
throw new UserException.BadInput("Values for " + annotationKeys.get(iii) + " annotation not detected for ANY training variant in the input callset. VariantAnnotator may be used to add these annotations. See http://www.broadinstitute.org/gsa/wiki/index.php/VariantAnnotator");
}
foundZeroVarianceAnnotation = foundZeroVarianceAnnotation || (theSTD < 1E-6);
meanVector[iii] = theMean;
varianceVector[iii] = theSTD;
for( final VariantDatum datum : data ) {
// Transform each data point via: (x - mean) / standard deviation
datum.annotations[iii] = ( datum.isNull[iii] ? GenomeAnalysisEngine.getRandomGenerator().nextGaussian() : ( datum.annotations[iii] - theMean ) / theSTD );
}
}
if( foundZeroVarianceAnnotation ) {
throw new UserException.BadInput( "Found annotations with zero variance. They must be excluded before proceeding." );
}
// trim data by standard deviation threshold and mark failing data for exclusion later
for( final VariantDatum datum : data ) {
boolean remove = false;
for( final double val : datum.annotations ) {
remove = remove || (Math.abs(val) > VRAC.STD_THRESHOLD);
}
datum.failingSTDThreshold = remove;
}
}
public void addTrainingSet( final TrainingSet trainingSet ) {
trainingSets.add( trainingSet );
}
public boolean checkHasTrainingSet() {
for( final TrainingSet trainingSet : trainingSets ) {
if( trainingSet.isTraining ) { return true; }
}
return false;
}
public boolean checkHasTruthSet() {
for( final TrainingSet trainingSet : trainingSets ) {
if( trainingSet.isTruth ) { return true; }
}
return false;
}
public boolean checkHasKnownSet() {
for( final TrainingSet trainingSet : trainingSets ) {
if( trainingSet.isKnown ) { return true; }
}
return false;
}
public ExpandingArrayList<VariantDatum> getTrainingData() {
final ExpandingArrayList<VariantDatum> trainingData = new ExpandingArrayList<VariantDatum>();
for( final VariantDatum datum : data ) {
if( datum.atTrainingSite && !datum.failingSTDThreshold && datum.originalQual > VRAC.QUAL_THRESHOLD ) {
trainingData.add( datum );
}
}
logger.info( "Training with " + trainingData.size() + " variants after standard deviation thresholding." );
if( trainingData.size() < VRAC.MIN_NUM_BAD_VARIANTS ) {
logger.warn( "WARNING: Training with very few variant sites! Please check the model reporting PDF to ensure the quality of the model is reliable." );
}
return trainingData;
}
public ExpandingArrayList<VariantDatum> selectWorstVariants( double bottomPercentage, final int minimumNumber ) {
// The return value is the list of training variants
final ExpandingArrayList<VariantDatum> trainingData = new ExpandingArrayList<VariantDatum>();
// First add to the training list all sites overlapping any bad sites training tracks
for( final VariantDatum datum : data ) {
if( datum.atAntiTrainingSite && !datum.failingSTDThreshold && !Double.isInfinite(datum.lod) ) {
trainingData.add( datum );
}
}
final int numBadSitesAdded = trainingData.size();
logger.info( "Found " + numBadSitesAdded + " variants overlapping bad sites training tracks." );
// Next sort the variants by the LOD coming from the positive model and add to the list the bottom X percent of variants
Collections.sort( data );
final int numToAdd = Math.max( minimumNumber - trainingData.size(), Math.round((float)bottomPercentage * data.size()) );
if( numToAdd > data.size() ) {
throw new UserException.BadInput( "Error during negative model training. Minimum number of variants to use in training is larger than the whole call set. One can attempt to lower the --minNumBadVariants arugment but this is unsafe." );
} else if( numToAdd == minimumNumber - trainingData.size() ) {
logger.warn( "WARNING: Training with very few variant sites! Please check the model reporting PDF to ensure the quality of the model is reliable." );
bottomPercentage = ((float) numToAdd) / ((float) data.size());
}
int index = 0, numAdded = 0;
- while( numAdded < numToAdd ) {
+ while( numAdded < numToAdd && index < data.size() ) {
final VariantDatum datum = data.get(index++);
- if( !datum.atAntiTrainingSite && !datum.failingSTDThreshold && !Double.isInfinite(datum.lod) ) {
+ if( datum != null && !datum.atAntiTrainingSite && !datum.failingSTDThreshold && !Double.isInfinite(datum.lod) ) {
datum.atAntiTrainingSite = true;
trainingData.add( datum );
numAdded++;
}
}
logger.info( "Additionally training with worst " + String.format("%.3f", (float) bottomPercentage * 100.0f) + "% of passing data --> " + (trainingData.size() - numBadSitesAdded) + " variants with LOD <= " + String.format("%.4f", data.get(index).lod) + "." );
return trainingData;
}
public ExpandingArrayList<VariantDatum> getRandomDataForPlotting( int numToAdd ) {
numToAdd = Math.min(numToAdd, data.size());
final ExpandingArrayList<VariantDatum> returnData = new ExpandingArrayList<VariantDatum>();
for( int iii = 0; iii < numToAdd; iii++) {
final VariantDatum datum = data.get(GenomeAnalysisEngine.getRandomGenerator().nextInt(data.size()));
if( !datum.failingSTDThreshold ) {
returnData.add(datum);
}
}
// Add an extra 5% of points from bad training set, since that set is small but interesting
for( int iii = 0; iii < Math.floor(0.05*numToAdd); iii++) {
final VariantDatum datum = data.get(GenomeAnalysisEngine.getRandomGenerator().nextInt(data.size()));
if( datum.atAntiTrainingSite && !datum.failingSTDThreshold ) { returnData.add(datum); }
else { iii--; }
}
return returnData;
}
private double mean( final int index ) {
double sum = 0.0;
int numNonNull = 0;
for( final VariantDatum datum : data ) {
if( datum.atTrainingSite && !datum.isNull[index] ) { sum += datum.annotations[index]; numNonNull++; }
}
return sum / ((double) numNonNull);
}
private double standardDeviation( final double mean, final int index ) {
double sum = 0.0;
int numNonNull = 0;
for( final VariantDatum datum : data ) {
if( datum.atTrainingSite && !datum.isNull[index] ) { sum += ((datum.annotations[index] - mean)*(datum.annotations[index] - mean)); numNonNull++; }
}
return Math.sqrt( sum / ((double) numNonNull) );
}
public void decodeAnnotations( final VariantDatum datum, final VariantContext vc, final boolean jitter ) {
final double[] annotations = new double[annotationKeys.size()];
final boolean[] isNull = new boolean[annotationKeys.size()];
int iii = 0;
for( final String key : annotationKeys ) {
isNull[iii] = false;
annotations[iii] = decodeAnnotation( key, vc, jitter );
if( Double.isNaN(annotations[iii]) ) { isNull[iii] = true; }
iii++;
}
datum.annotations = annotations;
datum.isNull = isNull;
}
private static double decodeAnnotation( final String annotationKey, final VariantContext vc, final boolean jitter ) {
double value;
try {
value = Double.parseDouble( (String)vc.getAttribute( annotationKey ) );
if( Double.isInfinite(value) ) { value = Double.NaN; }
if( jitter && annotationKey.equalsIgnoreCase("HRUN") ) { // Integer valued annotations must be jittered a bit to work in this GMM
value += -0.25 + 0.5 * GenomeAnalysisEngine.getRandomGenerator().nextDouble();
}
if (vc.isIndel() && annotationKey.equalsIgnoreCase("QD")) {
// normalize QD by event length for indel case
int eventLength = Math.abs(vc.getAlternateAllele(0).getBaseString().length() - vc.getReference().getBaseString().length()); // ignore multi-allelic complication here for now
if (eventLength > 0) { // sanity check
value /= (double)eventLength;
}
}
if( jitter && annotationKey.equalsIgnoreCase("HaplotypeScore") && MathUtils.compareDoubles(value, 0.0, 0.0001) == 0 ) { value = -0.2 + 0.4*GenomeAnalysisEngine.getRandomGenerator().nextDouble(); }
if( jitter && annotationKey.equalsIgnoreCase("FS") && MathUtils.compareDoubles(value, 0.0, 0.001) == 0 ) { value = -0.2 + 0.4*GenomeAnalysisEngine.getRandomGenerator().nextDouble(); }
} catch( Exception e ) {
value = Double.NaN; // The VQSR works with missing data by marginalizing over the missing dimension when evaluating the Gaussian mixture model
}
return value;
}
public void parseTrainingSets( final RefMetaDataTracker tracker, final GenomeLoc genomeLoc, final VariantContext evalVC, final VariantDatum datum, final boolean TRUST_ALL_POLYMORPHIC ) {
datum.isKnown = false;
datum.atTruthSite = false;
datum.atTrainingSite = false;
datum.atAntiTrainingSite = false;
datum.prior = 2.0;
for( final TrainingSet trainingSet : trainingSets ) {
for( final VariantContext trainVC : tracker.getValues(trainingSet.rodBinding, genomeLoc) ) {
if( isValidVariant( evalVC, trainVC, TRUST_ALL_POLYMORPHIC ) ) {
datum.isKnown = datum.isKnown || trainingSet.isKnown;
datum.atTruthSite = datum.atTruthSite || trainingSet.isTruth;
datum.atTrainingSite = datum.atTrainingSite || trainingSet.isTraining;
datum.prior = Math.max( datum.prior, trainingSet.prior );
datum.consensusCount += ( trainingSet.isConsensus ? 1 : 0 );
}
if( trainVC != null ) {
datum.atAntiTrainingSite = datum.atAntiTrainingSite || trainingSet.isAntiTraining;
}
}
}
}
private boolean isValidVariant( final VariantContext evalVC, final VariantContext trainVC, final boolean TRUST_ALL_POLYMORPHIC) {
return trainVC != null && trainVC.isNotFiltered() && trainVC.isVariant() &&
((evalVC.isSNP() && trainVC.isSNP()) || ((evalVC.isIndel()||evalVC.isMixed()) && (trainVC.isIndel()||trainVC.isMixed()))) &&
(TRUST_ALL_POLYMORPHIC || !trainVC.hasGenotypes() || trainVC.isPolymorphicInSamples());
}
public void writeOutRecalibrationTable( final PrintStream RECAL_FILE ) {
for( final VariantDatum datum : data ) {
RECAL_FILE.println(String.format("%s,%d,%d,%.4f,%s",
datum.contig, datum.start, datum.stop, datum.lod,
(datum.worstAnnotation != -1 ? annotationKeys.get(datum.worstAnnotation) : "NULL")));
}
}
}
| false | true | public ExpandingArrayList<VariantDatum> selectWorstVariants( double bottomPercentage, final int minimumNumber ) {
// The return value is the list of training variants
final ExpandingArrayList<VariantDatum> trainingData = new ExpandingArrayList<VariantDatum>();
// First add to the training list all sites overlapping any bad sites training tracks
for( final VariantDatum datum : data ) {
if( datum.atAntiTrainingSite && !datum.failingSTDThreshold && !Double.isInfinite(datum.lod) ) {
trainingData.add( datum );
}
}
final int numBadSitesAdded = trainingData.size();
logger.info( "Found " + numBadSitesAdded + " variants overlapping bad sites training tracks." );
// Next sort the variants by the LOD coming from the positive model and add to the list the bottom X percent of variants
Collections.sort( data );
final int numToAdd = Math.max( minimumNumber - trainingData.size(), Math.round((float)bottomPercentage * data.size()) );
if( numToAdd > data.size() ) {
throw new UserException.BadInput( "Error during negative model training. Minimum number of variants to use in training is larger than the whole call set. One can attempt to lower the --minNumBadVariants arugment but this is unsafe." );
} else if( numToAdd == minimumNumber - trainingData.size() ) {
logger.warn( "WARNING: Training with very few variant sites! Please check the model reporting PDF to ensure the quality of the model is reliable." );
bottomPercentage = ((float) numToAdd) / ((float) data.size());
}
int index = 0, numAdded = 0;
while( numAdded < numToAdd ) {
final VariantDatum datum = data.get(index++);
if( !datum.atAntiTrainingSite && !datum.failingSTDThreshold && !Double.isInfinite(datum.lod) ) {
datum.atAntiTrainingSite = true;
trainingData.add( datum );
numAdded++;
}
}
logger.info( "Additionally training with worst " + String.format("%.3f", (float) bottomPercentage * 100.0f) + "% of passing data --> " + (trainingData.size() - numBadSitesAdded) + " variants with LOD <= " + String.format("%.4f", data.get(index).lod) + "." );
return trainingData;
}
| public ExpandingArrayList<VariantDatum> selectWorstVariants( double bottomPercentage, final int minimumNumber ) {
// The return value is the list of training variants
final ExpandingArrayList<VariantDatum> trainingData = new ExpandingArrayList<VariantDatum>();
// First add to the training list all sites overlapping any bad sites training tracks
for( final VariantDatum datum : data ) {
if( datum.atAntiTrainingSite && !datum.failingSTDThreshold && !Double.isInfinite(datum.lod) ) {
trainingData.add( datum );
}
}
final int numBadSitesAdded = trainingData.size();
logger.info( "Found " + numBadSitesAdded + " variants overlapping bad sites training tracks." );
// Next sort the variants by the LOD coming from the positive model and add to the list the bottom X percent of variants
Collections.sort( data );
final int numToAdd = Math.max( minimumNumber - trainingData.size(), Math.round((float)bottomPercentage * data.size()) );
if( numToAdd > data.size() ) {
throw new UserException.BadInput( "Error during negative model training. Minimum number of variants to use in training is larger than the whole call set. One can attempt to lower the --minNumBadVariants arugment but this is unsafe." );
} else if( numToAdd == minimumNumber - trainingData.size() ) {
logger.warn( "WARNING: Training with very few variant sites! Please check the model reporting PDF to ensure the quality of the model is reliable." );
bottomPercentage = ((float) numToAdd) / ((float) data.size());
}
int index = 0, numAdded = 0;
while( numAdded < numToAdd && index < data.size() ) {
final VariantDatum datum = data.get(index++);
if( datum != null && !datum.atAntiTrainingSite && !datum.failingSTDThreshold && !Double.isInfinite(datum.lod) ) {
datum.atAntiTrainingSite = true;
trainingData.add( datum );
numAdded++;
}
}
logger.info( "Additionally training with worst " + String.format("%.3f", (float) bottomPercentage * 100.0f) + "% of passing data --> " + (trainingData.size() - numBadSitesAdded) + " variants with LOD <= " + String.format("%.4f", data.get(index).lod) + "." );
return trainingData;
}
|
diff --git a/org.openscada.da.master.common/src/org/openscada/da/master/common/Activator.java b/org.openscada.da.master.common/src/org/openscada/da/master/common/Activator.java
index 98e43288e..19da47923 100644
--- a/org.openscada.da.master.common/src/org/openscada/da/master/common/Activator.java
+++ b/org.openscada.da.master.common/src/org/openscada/da/master/common/Activator.java
@@ -1,115 +1,115 @@
package org.openscada.da.master.common;
import java.util.Dictionary;
import java.util.Hashtable;
import org.openscada.ca.ConfigurationAdministrator;
import org.openscada.ca.ConfigurationFactory;
import org.openscada.da.master.MasterItem;
import org.openscada.da.master.common.manual.ManualHandlerFactoryImpl;
import org.openscada.da.master.common.negate.NegateHandlerFactoryImpl;
import org.openscada.da.master.common.scale.ScaleHandlerFactoryImpl;
import org.openscada.da.master.common.sum.CommonSumHandlerFactoryImpl;
import org.openscada.utils.osgi.pool.ObjectPoolTracker;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.util.tracker.ServiceTracker;
public class Activator implements BundleActivator
{
private CommonSumHandlerFactoryImpl factory1;
private CommonSumHandlerFactoryImpl factory2;
private CommonSumHandlerFactoryImpl factory3;
private CommonSumHandlerFactoryImpl factory4;
private ObjectPoolTracker poolTracker;
private ServiceTracker caTracker;
private ScaleHandlerFactoryImpl factory5;
private NegateHandlerFactoryImpl factory6;
private ManualHandlerFactoryImpl factory7;
/*
* (non-Javadoc)
* @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
*/
public void start ( final BundleContext context ) throws Exception
{
this.poolTracker = new ObjectPoolTracker ( context, MasterItem.class.getName () );
this.poolTracker.open ();
this.caTracker = new ServiceTracker ( context, ConfigurationAdministrator.class.getName (), null );
this.caTracker.open ();
- this.factory2 = makeFactory ( context, this.poolTracker, "alarm", 3000 );
- this.factory3 = makeFactory ( context, this.poolTracker, "manual", 3100 );
+ this.factory2 = makeFactory ( context, this.poolTracker, "alarm", 5020 );
+ this.factory3 = makeFactory ( context, this.poolTracker, "manual", 5010 );
this.factory1 = makeFactory ( context, this.poolTracker, "error", 5000 );
- this.factory4 = makeFactory ( context, this.poolTracker, "ackRequired", 5500 );
+ this.factory4 = makeFactory ( context, this.poolTracker, "ackRequired", 5030 );
{
- this.factory5 = new ScaleHandlerFactoryImpl ( context, this.poolTracker, this.caTracker, 1000 );
+ this.factory5 = new ScaleHandlerFactoryImpl ( context, this.poolTracker, this.caTracker, 500 );
final Dictionary<String, String> properties = new Hashtable<String, String> ();
properties.put ( Constants.SERVICE_DESCRIPTION, "A local scaling master handler" );
properties.put ( ConfigurationAdministrator.FACTORY_ID, ScaleHandlerFactoryImpl.FACTORY_ID );
context.registerService ( ConfigurationFactory.class.getName (), this.factory5, properties );
}
{
- this.factory6 = new NegateHandlerFactoryImpl ( context, this.poolTracker, this.caTracker, 1000 );
+ this.factory6 = new NegateHandlerFactoryImpl ( context, this.poolTracker, this.caTracker, 501 );
final Dictionary<String, String> properties = new Hashtable<String, String> ();
properties.put ( Constants.SERVICE_DESCRIPTION, "A local negate master handler" );
properties.put ( ConfigurationAdministrator.FACTORY_ID, NegateHandlerFactoryImpl.FACTORY_ID );
context.registerService ( ConfigurationFactory.class.getName (), this.factory6, properties );
}
{
- this.factory7 = new ManualHandlerFactoryImpl ( context, this.poolTracker, this.caTracker, 1500 );
+ this.factory7 = new ManualHandlerFactoryImpl ( context, this.poolTracker, this.caTracker, 1000 );
final Dictionary<String, String> properties = new Hashtable<String, String> ();
properties.put ( Constants.SERVICE_DESCRIPTION, "A local manual override master handler" );
properties.put ( ConfigurationAdministrator.FACTORY_ID, ManualHandlerFactoryImpl.FACTORY_ID );
context.registerService ( ConfigurationFactory.class.getName (), this.factory7, properties );
}
}
private static CommonSumHandlerFactoryImpl makeFactory ( final BundleContext context, final ObjectPoolTracker poolTracker, final String tag, final int priority ) throws InvalidSyntaxException
{
final CommonSumHandlerFactoryImpl factory = new CommonSumHandlerFactoryImpl ( context, poolTracker, tag, priority );
final Dictionary<String, String> properties = new Hashtable<String, String> ();
properties.put ( Constants.SERVICE_DESCRIPTION, String.format ( "A sum %s handler", tag ) );
properties.put ( ConfigurationAdministrator.FACTORY_ID, "da.master.handler.sum." + tag );
context.registerService ( ConfigurationFactory.class.getName (), factory, properties );
return factory;
}
/*
* (non-Javadoc)
* @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
*/
public void stop ( final BundleContext context ) throws Exception
{
this.factory1.dispose ();
this.factory2.dispose ();
this.factory3.dispose ();
this.factory4.dispose ();
this.factory5.dispose ();
this.factory6.dispose ();
this.factory7.dispose ();
this.poolTracker.close ();
this.poolTracker = null;
this.caTracker.close ();
this.caTracker = null;
}
}
| false | true | public void start ( final BundleContext context ) throws Exception
{
this.poolTracker = new ObjectPoolTracker ( context, MasterItem.class.getName () );
this.poolTracker.open ();
this.caTracker = new ServiceTracker ( context, ConfigurationAdministrator.class.getName (), null );
this.caTracker.open ();
this.factory2 = makeFactory ( context, this.poolTracker, "alarm", 3000 );
this.factory3 = makeFactory ( context, this.poolTracker, "manual", 3100 );
this.factory1 = makeFactory ( context, this.poolTracker, "error", 5000 );
this.factory4 = makeFactory ( context, this.poolTracker, "ackRequired", 5500 );
{
this.factory5 = new ScaleHandlerFactoryImpl ( context, this.poolTracker, this.caTracker, 1000 );
final Dictionary<String, String> properties = new Hashtable<String, String> ();
properties.put ( Constants.SERVICE_DESCRIPTION, "A local scaling master handler" );
properties.put ( ConfigurationAdministrator.FACTORY_ID, ScaleHandlerFactoryImpl.FACTORY_ID );
context.registerService ( ConfigurationFactory.class.getName (), this.factory5, properties );
}
{
this.factory6 = new NegateHandlerFactoryImpl ( context, this.poolTracker, this.caTracker, 1000 );
final Dictionary<String, String> properties = new Hashtable<String, String> ();
properties.put ( Constants.SERVICE_DESCRIPTION, "A local negate master handler" );
properties.put ( ConfigurationAdministrator.FACTORY_ID, NegateHandlerFactoryImpl.FACTORY_ID );
context.registerService ( ConfigurationFactory.class.getName (), this.factory6, properties );
}
{
this.factory7 = new ManualHandlerFactoryImpl ( context, this.poolTracker, this.caTracker, 1500 );
final Dictionary<String, String> properties = new Hashtable<String, String> ();
properties.put ( Constants.SERVICE_DESCRIPTION, "A local manual override master handler" );
properties.put ( ConfigurationAdministrator.FACTORY_ID, ManualHandlerFactoryImpl.FACTORY_ID );
context.registerService ( ConfigurationFactory.class.getName (), this.factory7, properties );
}
}
| public void start ( final BundleContext context ) throws Exception
{
this.poolTracker = new ObjectPoolTracker ( context, MasterItem.class.getName () );
this.poolTracker.open ();
this.caTracker = new ServiceTracker ( context, ConfigurationAdministrator.class.getName (), null );
this.caTracker.open ();
this.factory2 = makeFactory ( context, this.poolTracker, "alarm", 5020 );
this.factory3 = makeFactory ( context, this.poolTracker, "manual", 5010 );
this.factory1 = makeFactory ( context, this.poolTracker, "error", 5000 );
this.factory4 = makeFactory ( context, this.poolTracker, "ackRequired", 5030 );
{
this.factory5 = new ScaleHandlerFactoryImpl ( context, this.poolTracker, this.caTracker, 500 );
final Dictionary<String, String> properties = new Hashtable<String, String> ();
properties.put ( Constants.SERVICE_DESCRIPTION, "A local scaling master handler" );
properties.put ( ConfigurationAdministrator.FACTORY_ID, ScaleHandlerFactoryImpl.FACTORY_ID );
context.registerService ( ConfigurationFactory.class.getName (), this.factory5, properties );
}
{
this.factory6 = new NegateHandlerFactoryImpl ( context, this.poolTracker, this.caTracker, 501 );
final Dictionary<String, String> properties = new Hashtable<String, String> ();
properties.put ( Constants.SERVICE_DESCRIPTION, "A local negate master handler" );
properties.put ( ConfigurationAdministrator.FACTORY_ID, NegateHandlerFactoryImpl.FACTORY_ID );
context.registerService ( ConfigurationFactory.class.getName (), this.factory6, properties );
}
{
this.factory7 = new ManualHandlerFactoryImpl ( context, this.poolTracker, this.caTracker, 1000 );
final Dictionary<String, String> properties = new Hashtable<String, String> ();
properties.put ( Constants.SERVICE_DESCRIPTION, "A local manual override master handler" );
properties.put ( ConfigurationAdministrator.FACTORY_ID, ManualHandlerFactoryImpl.FACTORY_ID );
context.registerService ( ConfigurationFactory.class.getName (), this.factory7, properties );
}
}
|
diff --git a/src/de/ub0r/android/andGMXsms/Connector.java b/src/de/ub0r/android/andGMXsms/Connector.java
index 695ca22d..a6be865a 100644
--- a/src/de/ub0r/android/andGMXsms/Connector.java
+++ b/src/de/ub0r/android/andGMXsms/Connector.java
@@ -1,357 +1,382 @@
package de.ub0r.android.andGMXsms;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Message;
/**
* AsyncTask to manage IO to GMX API.
*
* @author flx
*/
public class Connector extends AsyncTask<String, Boolean, Boolean> {
/** Dialog ID. */
public static final int DIALOG_IO = 0;
/** Target host. */
private static final String TARGET_HOST = "app0.wr-gmbh.de";
// private static final String TARGET_HOST = "app5.wr-gmbh.de";
/** Target path on host. */
private static final String TARGET_PATH = "/WRServer/WRServer.dll/WR";
/** Target mime encoding. */
private static final String TARGET_ENCODING = "wr-cs";
/** Target mime type. */
private static final String TARGET_CONTENT = "text/plain";
/** HTTP Useragent. */
private static final String TARGET_AGENT = "Mozilla/3.0 (compatible)";
/** Target version of protocol. */
private static final String TARGET_PROTOVERSION = "1.13.03";
/** Max Buffer size. */
private static final int MAX_BUFSIZE = 4096;
/** SMS DB: address. */
private static final String ADDRESS = "address";
/** SMS DB: person. */
// private static final String PERSON = "person";
/** SMS DB: date. */
// private static final String DATE = "date";
/** SMS DB: read. */
private static final String READ = "read";
/** SMS DB: status. */
// private static final String STATUS = "status";
/** SMS DB: type. */
private static final String TYPE = "type";
/** SMS DB: body. */
private static final String BODY = "body";
/** SMS DB: type - sent. */
private static final int MESSAGE_TYPE_SENT = 2;
/** ID of text in array. */
public static final int ID_TEXT = 0;
/** ID of receiver in array. */
public static final int ID_TO = 1;
/** receiver. */
private String to;
/** text. */
private String text;
/**
* Write key,value to StringBuffer.
*
* @param buffer
* buffer
* @param key
* key
* @param value
* value
*/
private static void writePair(final StringBuffer buffer, final String key,
final String value) {
buffer.append(key);
buffer.append('=');
buffer.append(value.replace("\\", "\\\\").replace(">", "\\>").replace(
"<", "\\<"));
buffer.append("\\p");
}
/**
* Create default data hashtable.
*
* @param packetName
* packetName
* @param packetVersion
* packetVersion
* @return Hashtable filled with customer_id and password.
*/
private static StringBuffer openBuffer(final String packetName,
final String packetVersion) {
StringBuffer ret = new StringBuffer();
ret.append("<WR TYPE=\"RQST\" NAME=\"");
ret.append(packetName);
ret.append("\" VER=\"");
ret.append(packetVersion);
ret.append("\" PROGVER=\"");
ret.append(TARGET_PROTOVERSION);
ret.append("\">");
writePair(ret, "customer_id", AndGMXsms.prefsUser);
writePair(ret, "password", AndGMXsms.prefsPassword);
return ret;
}
/**
* Close Buffer.
*
* @param buffer
* buffer
* @return buffer
*/
private static StringBuffer closeBuffer(final StringBuffer buffer) {
buffer.append("</WR>");
return buffer;
}
/**
* Send data.
*
* @param packetData
* packetData
* @return successful?
*/
private boolean sendData(final StringBuffer packetData) {
try {
// get Connection
HttpURLConnection c = (HttpURLConnection) (new URL("http://"
+ TARGET_HOST + TARGET_PATH)).openConnection();
// set prefs
c.setRequestProperty("User-Agent", TARGET_AGENT);
c.setRequestProperty("Content-Encoding", TARGET_ENCODING);
c.setRequestProperty("Content-Type", TARGET_CONTENT);
c.setRequestMethod("POST");
c.setDoOutput(true);
// push post data
OutputStream os = c.getOutputStream();
os.write(packetData.toString().getBytes());
os.close();
os = null;
// send data
int resp = c.getResponseCode();
if (resp != HttpURLConnection.HTTP_OK) {
Message.obtain(
AndGMXsms.me.messageHandler,
AndGMXsms.MESSAGE_LOG,
AndGMXsms.me.getResources().getString(
R.string.log_error_http + resp)).sendToTarget();
}
// read received data
int bufsize = c.getHeaderFieldInt("Content-Length", -1);
StringBuffer data = null;
if (bufsize > 0) {
data = new StringBuffer();
InputStream is = c.getInputStream();
byte[] buf;
if (bufsize > MAX_BUFSIZE) {
buf = new byte[MAX_BUFSIZE];
} else {
buf = new byte[bufsize];
}
int read = is.read(buf, 0, buf.length);
int count = read;
while (read > 0) {
data.append(new String(buf, 0, read, "ASCII"));
read = is.read(buf, 0, buf.length);
count += read;
}
buf = null;
is.close();
is = null;
String resultString = data.toString();
if (resultString.startsWith("The truth")) {
// wrong data sent!
Message.obtain(
AndGMXsms.me.messageHandler,
AndGMXsms.MESSAGE_LOG,
AndGMXsms.me.getResources().getString(
R.string.log_error_server)
+ resultString).sendToTarget();
return false;
}
// get result code
int resultIndex = resultString.indexOf("rslt=");
if (resultIndex < 0) {
return false;
}
String resultValue = resultString.substring(resultIndex + 5,
resultIndex + 6);
String outp = resultString.substring(resultIndex).replace(
"\\p", "\n");
outp = outp.replace("</WR>", "");
if (!resultValue.equals("0")) {
- Message.obtain(AndGMXsms.me.messageHandler,
- AndGMXsms.MESSAGE_LOG, outp).sendToTarget();
+ try {
+ int rslt = Integer.parseInt(resultValue);
+ switch (rslt) {
+ case 11: // 11 wrong pw
+ Message.obtain(
+ AndGMXsms.me.messageHandler,
+ AndGMXsms.MESSAGE_LOG,
+ AndGMXsms.me.getResources().getString(
+ R.string.log_error_pw))
+ .sendToTarget();
+ break;
+ case 25: // 25 wrong mail/pw
+ Message.obtain(
+ AndGMXsms.me.messageHandler,
+ AndGMXsms.MESSAGE_LOG,
+ AndGMXsms.me.getResources().getString(
+ R.string.log_error_mail))
+ .sendToTarget();
+ default:
+ Message.obtain(AndGMXsms.me.messageHandler,
+ AndGMXsms.MESSAGE_LOG, outp).sendToTarget();
+ }
+ } catch (Exception e) {
+ Message.obtain(AndGMXsms.me.messageHandler,
+ AndGMXsms.MESSAGE_LOG, e.toString())
+ .sendToTarget();
+ }
return false;
} else {
// result: ok
// fetch additional info
resultIndex = outp.indexOf("free_rem_month=");
if (resultIndex > 0) {
int resIndex = outp.indexOf("\n", resultIndex);
String freecount = outp.substring(resultIndex
+ "free_rem_month=".length(), resIndex);
resultIndex = outp.indexOf("free_max_month=");
if (resultIndex > 0) {
resIndex = outp.indexOf("\n", resultIndex);
freecount += " / "
+ outp.substring(resultIndex
+ "free_max_month=".length(),
resIndex);
}
Message.obtain(AndGMXsms.me.messageHandler,
AndGMXsms.MESSAGE_FREECOUNT, freecount)
.sendToTarget();
}
}
} else {
Message.obtain(
AndGMXsms.me.messageHandler,
AndGMXsms.MESSAGE_LOG,
AndGMXsms.me.getResources().getString(
R.string.log_http_header_missing))
.sendToTarget();
return false;
}
} catch (IOException e) {
Message.obtain(AndGMXsms.me.messageHandler, AndGMXsms.MESSAGE_LOG,
e.toString()).sendToTarget();
return false;
}
return true;
}
/**
* Get free sms count.
*
* @return ok?
*/
private boolean getFree() {
return this
.sendData(closeBuffer(openBuffer("GET_SMS_CREDITS", "1.00")));
}
/**
* Send sms.
*
* @return ok?
*/
private boolean send() {
StringBuffer packetData = openBuffer("SEND_SMS", "1.01");
// fill buffer
writePair(packetData, "sms_text", this.text);
// table: <id>, <name>, <number>
String receivers = "<TBL ROWS=\"1\" COLS=\"3\">"
+ "receiver_id\\;receiver_name\\;receiver_number\\;"
+ "1\\;null\\;" + this.to + "\\;" + "</TBL>";
writePair(packetData, "receivers", receivers);
writePair(packetData, "send_option", "sms");
writePair(packetData, "sms_sender", AndGMXsms.prefsSender);
// if date!='': data['send_date'] = date
// push data
if (!this.sendData(closeBuffer(packetData))) {
// failed!
Message.obtain(AndGMXsms.me.messageHandler, AndGMXsms.MESSAGE_LOG,
AndGMXsms.me.getResources().getString(R.string.log_error))
.sendToTarget();
return false;
} else {
// result: ok
Composer.reset();
// save sms to content://sms/sent
ContentValues values = new ContentValues();
values.put(ADDRESS, this.to);
// values.put(DATE, "1237080365055");
values.put(READ, 1);
// values.put(STATUS, -1);
values.put(TYPE, MESSAGE_TYPE_SENT);
values.put(BODY, this.text);
// Uri inserted =
AndGMXsms.me.getContentResolver().insert(
Uri.parse("content://sms/sent"), values);
return true;
}
}
/**
* Run IO in background.
*
* @param textTo
* (text,receiver)
* @return ok?
*/
@Override
protected final Boolean doInBackground(final String... textTo) {
boolean ret = false;
if (textTo == null || textTo[0] == null) {
this.publishProgress((Boolean) null);
ret = this.getFree();
} else if (textTo.length >= 2) {
this.text = textTo[ID_TEXT];
this.to = textTo[ID_TO];
this.publishProgress((Boolean) null);
ret = this.send();
}
return new Boolean(ret);
}
/**
* Update progress. Only ran once on startup to display progress dialog.
*
* @param progress
* finished?
*/
@Override
protected final void onProgressUpdate(final Boolean... progress) {
if (this.to == null) {
AndGMXsms.dialogString = AndGMXsms.me.getResources().getString(
R.string.log_update);
AndGMXsms.dialog = ProgressDialog.show(AndGMXsms.me, null,
AndGMXsms.dialogString, true);
} else {
AndGMXsms.dialogString = AndGMXsms.me.getResources().getString(
R.string.log_sending)
+ " (" + this.to + ")";
AndGMXsms.dialog = ProgressDialog.show(AndGMXsms.me, null,
AndGMXsms.dialogString, true);
}
}
/**
* Push data back to GUI. Close progress dialog.
*
* @param result
* result
*/
@Override
protected final void onPostExecute(final Boolean result) {
AndGMXsms.dialogString = null;
if (AndGMXsms.dialog != null) {
try {
AndGMXsms.dialog.dismiss();
AndGMXsms.dialog = null;
} catch (Exception e) {
// nothing to do
}
}
}
}
| true | true | private boolean sendData(final StringBuffer packetData) {
try {
// get Connection
HttpURLConnection c = (HttpURLConnection) (new URL("http://"
+ TARGET_HOST + TARGET_PATH)).openConnection();
// set prefs
c.setRequestProperty("User-Agent", TARGET_AGENT);
c.setRequestProperty("Content-Encoding", TARGET_ENCODING);
c.setRequestProperty("Content-Type", TARGET_CONTENT);
c.setRequestMethod("POST");
c.setDoOutput(true);
// push post data
OutputStream os = c.getOutputStream();
os.write(packetData.toString().getBytes());
os.close();
os = null;
// send data
int resp = c.getResponseCode();
if (resp != HttpURLConnection.HTTP_OK) {
Message.obtain(
AndGMXsms.me.messageHandler,
AndGMXsms.MESSAGE_LOG,
AndGMXsms.me.getResources().getString(
R.string.log_error_http + resp)).sendToTarget();
}
// read received data
int bufsize = c.getHeaderFieldInt("Content-Length", -1);
StringBuffer data = null;
if (bufsize > 0) {
data = new StringBuffer();
InputStream is = c.getInputStream();
byte[] buf;
if (bufsize > MAX_BUFSIZE) {
buf = new byte[MAX_BUFSIZE];
} else {
buf = new byte[bufsize];
}
int read = is.read(buf, 0, buf.length);
int count = read;
while (read > 0) {
data.append(new String(buf, 0, read, "ASCII"));
read = is.read(buf, 0, buf.length);
count += read;
}
buf = null;
is.close();
is = null;
String resultString = data.toString();
if (resultString.startsWith("The truth")) {
// wrong data sent!
Message.obtain(
AndGMXsms.me.messageHandler,
AndGMXsms.MESSAGE_LOG,
AndGMXsms.me.getResources().getString(
R.string.log_error_server)
+ resultString).sendToTarget();
return false;
}
// get result code
int resultIndex = resultString.indexOf("rslt=");
if (resultIndex < 0) {
return false;
}
String resultValue = resultString.substring(resultIndex + 5,
resultIndex + 6);
String outp = resultString.substring(resultIndex).replace(
"\\p", "\n");
outp = outp.replace("</WR>", "");
if (!resultValue.equals("0")) {
Message.obtain(AndGMXsms.me.messageHandler,
AndGMXsms.MESSAGE_LOG, outp).sendToTarget();
return false;
} else {
// result: ok
// fetch additional info
resultIndex = outp.indexOf("free_rem_month=");
if (resultIndex > 0) {
int resIndex = outp.indexOf("\n", resultIndex);
String freecount = outp.substring(resultIndex
+ "free_rem_month=".length(), resIndex);
resultIndex = outp.indexOf("free_max_month=");
if (resultIndex > 0) {
resIndex = outp.indexOf("\n", resultIndex);
freecount += " / "
+ outp.substring(resultIndex
+ "free_max_month=".length(),
resIndex);
}
Message.obtain(AndGMXsms.me.messageHandler,
AndGMXsms.MESSAGE_FREECOUNT, freecount)
.sendToTarget();
}
}
} else {
Message.obtain(
AndGMXsms.me.messageHandler,
AndGMXsms.MESSAGE_LOG,
AndGMXsms.me.getResources().getString(
R.string.log_http_header_missing))
.sendToTarget();
return false;
}
} catch (IOException e) {
Message.obtain(AndGMXsms.me.messageHandler, AndGMXsms.MESSAGE_LOG,
e.toString()).sendToTarget();
return false;
}
return true;
}
| private boolean sendData(final StringBuffer packetData) {
try {
// get Connection
HttpURLConnection c = (HttpURLConnection) (new URL("http://"
+ TARGET_HOST + TARGET_PATH)).openConnection();
// set prefs
c.setRequestProperty("User-Agent", TARGET_AGENT);
c.setRequestProperty("Content-Encoding", TARGET_ENCODING);
c.setRequestProperty("Content-Type", TARGET_CONTENT);
c.setRequestMethod("POST");
c.setDoOutput(true);
// push post data
OutputStream os = c.getOutputStream();
os.write(packetData.toString().getBytes());
os.close();
os = null;
// send data
int resp = c.getResponseCode();
if (resp != HttpURLConnection.HTTP_OK) {
Message.obtain(
AndGMXsms.me.messageHandler,
AndGMXsms.MESSAGE_LOG,
AndGMXsms.me.getResources().getString(
R.string.log_error_http + resp)).sendToTarget();
}
// read received data
int bufsize = c.getHeaderFieldInt("Content-Length", -1);
StringBuffer data = null;
if (bufsize > 0) {
data = new StringBuffer();
InputStream is = c.getInputStream();
byte[] buf;
if (bufsize > MAX_BUFSIZE) {
buf = new byte[MAX_BUFSIZE];
} else {
buf = new byte[bufsize];
}
int read = is.read(buf, 0, buf.length);
int count = read;
while (read > 0) {
data.append(new String(buf, 0, read, "ASCII"));
read = is.read(buf, 0, buf.length);
count += read;
}
buf = null;
is.close();
is = null;
String resultString = data.toString();
if (resultString.startsWith("The truth")) {
// wrong data sent!
Message.obtain(
AndGMXsms.me.messageHandler,
AndGMXsms.MESSAGE_LOG,
AndGMXsms.me.getResources().getString(
R.string.log_error_server)
+ resultString).sendToTarget();
return false;
}
// get result code
int resultIndex = resultString.indexOf("rslt=");
if (resultIndex < 0) {
return false;
}
String resultValue = resultString.substring(resultIndex + 5,
resultIndex + 6);
String outp = resultString.substring(resultIndex).replace(
"\\p", "\n");
outp = outp.replace("</WR>", "");
if (!resultValue.equals("0")) {
try {
int rslt = Integer.parseInt(resultValue);
switch (rslt) {
case 11: // 11 wrong pw
Message.obtain(
AndGMXsms.me.messageHandler,
AndGMXsms.MESSAGE_LOG,
AndGMXsms.me.getResources().getString(
R.string.log_error_pw))
.sendToTarget();
break;
case 25: // 25 wrong mail/pw
Message.obtain(
AndGMXsms.me.messageHandler,
AndGMXsms.MESSAGE_LOG,
AndGMXsms.me.getResources().getString(
R.string.log_error_mail))
.sendToTarget();
default:
Message.obtain(AndGMXsms.me.messageHandler,
AndGMXsms.MESSAGE_LOG, outp).sendToTarget();
}
} catch (Exception e) {
Message.obtain(AndGMXsms.me.messageHandler,
AndGMXsms.MESSAGE_LOG, e.toString())
.sendToTarget();
}
return false;
} else {
// result: ok
// fetch additional info
resultIndex = outp.indexOf("free_rem_month=");
if (resultIndex > 0) {
int resIndex = outp.indexOf("\n", resultIndex);
String freecount = outp.substring(resultIndex
+ "free_rem_month=".length(), resIndex);
resultIndex = outp.indexOf("free_max_month=");
if (resultIndex > 0) {
resIndex = outp.indexOf("\n", resultIndex);
freecount += " / "
+ outp.substring(resultIndex
+ "free_max_month=".length(),
resIndex);
}
Message.obtain(AndGMXsms.me.messageHandler,
AndGMXsms.MESSAGE_FREECOUNT, freecount)
.sendToTarget();
}
}
} else {
Message.obtain(
AndGMXsms.me.messageHandler,
AndGMXsms.MESSAGE_LOG,
AndGMXsms.me.getResources().getString(
R.string.log_http_header_missing))
.sendToTarget();
return false;
}
} catch (IOException e) {
Message.obtain(AndGMXsms.me.messageHandler, AndGMXsms.MESSAGE_LOG,
e.toString()).sendToTarget();
return false;
}
return true;
}
|
diff --git a/P2aktuell/src/ro/inf/p2/uebung02/Wechseln.java b/P2aktuell/src/ro/inf/p2/uebung02/Wechseln.java
index 9d41a6b..8f40a12 100644
--- a/P2aktuell/src/ro/inf/p2/uebung02/Wechseln.java
+++ b/P2aktuell/src/ro/inf/p2/uebung02/Wechseln.java
@@ -1,30 +1,30 @@
package ro.inf.p2.uebung02;
/**
* Created with IntelliJ IDEA.
* User: felix
* Date: 3/28/13
* Time: 11:41 PM
* To change this template use File | Settings | File Templates.
*/
public class Wechseln {
public static final int[] werte =
new int[]{200, 100, 50, 20, 10, 5, 2, 1};
public static int[] anzahl(int betrag) {
- int[] array = new int[]{0, 0, 0, 0, 0, 0, 0, 0};
+ int[] array = new int[8];
int i = 0;
for (int wert:werte) {
while (betrag >= wert) {
betrag -= wert;
array[i] += 1;
}
i++;
}
return array;
}
}
| true | true | public static int[] anzahl(int betrag) {
int[] array = new int[]{0, 0, 0, 0, 0, 0, 0, 0};
int i = 0;
for (int wert:werte) {
while (betrag >= wert) {
betrag -= wert;
array[i] += 1;
}
i++;
}
return array;
}
| public static int[] anzahl(int betrag) {
int[] array = new int[8];
int i = 0;
for (int wert:werte) {
while (betrag >= wert) {
betrag -= wert;
array[i] += 1;
}
i++;
}
return array;
}
|
diff --git a/iMat/src/imat/SplashPanel.java b/iMat/src/imat/SplashPanel.java
index e81915c..7cd5956 100755
--- a/iMat/src/imat/SplashPanel.java
+++ b/iMat/src/imat/SplashPanel.java
@@ -1,368 +1,371 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* StartViewPanel.java
*
* Created on 2013-feb-23, 17:31:49
*/
package imat;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.util.*;
import javax.swing.*;
import se.chalmers.ait.dat215.project.*;
/**
*
* @author victorsandell
*/
public class SplashPanel extends javax.swing.JPanel implements TitleLabelInterface{
private String title;
private Dimension d;
/** Creates new form StartViewPanel */
public SplashPanel() {
initComponents();
addChosenProducts(null);
addLatestPurchases();
title = "Startsida";
d = new Dimension(0, 0);
}
private void addChosenProducts(List<Product> products){
for(int i = 0; i < 3; i++){
Product p;
p = IMatDataHandler.getInstance().getProduct(i+1);
FoodPanel fp = new FoodPanel(p, 120, 120);
jPanel5.add(fp);
}
}
public void addSavedPurchases(List<ShoppingItemList> lists){
jPanel16.setLayout(new GridLayout(lists.size()+1, 1, 0, 15));
for(int i = 0; i < lists.size(); i++){
jPanel16.add(new ShoppingListPanel(lists.get(i)));
}
d = new Dimension(700, lists.size()*175 + 600);
this.setPreferredSize(d);
}
private void addLatestPurchases(){
List<Order> oList = IMatDataHandler.getInstance().getOrders();
jPanel15.setLayout(new GridLayout(oList.size(), 1, 0, 15));
for(Order o : oList){
jPanel15.add(new ShoppingListPanel(o));
}
Dimension dTmp = new Dimension(700, oList.size()*175 + 550);
try{
if(dTmp.height > d.height){
d = dTmp;
this.setPreferredSize(dTmp);
}
}catch(NullPointerException e){
this.setPreferredSize(d);
}
}
public String getTitle(){
return title;
}
public void setTitle(String s){
;
}
/** 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() {
jPanel12 = new javax.swing.JPanel();
jPanel1 = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jPanel8 = new javax.swing.JPanel();
jPanel5 = new javax.swing.JPanel();
jPanel4 = new javax.swing.JPanel();
jPanel7 = new javax.swing.JPanel();
jLabel3 = new javax.swing.JLabel();
jPanel6 = new javax.swing.JPanel();
jPanel16 = new javax.swing.JPanel();
jPanel9 = new javax.swing.JPanel();
jPanel10 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
jPanel11 = new javax.swing.JPanel();
jPanel15 = new javax.swing.JPanel();
jPanel14 = new javax.swing.JPanel();
jPanel12.setName("jPanel12"); // NOI18N
org.jdesktop.layout.GroupLayout jPanel12Layout = new org.jdesktop.layout.GroupLayout(jPanel12);
jPanel12.setLayout(jPanel12Layout);
jPanel12Layout.setHorizontalGroup(
jPanel12Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 100, Short.MAX_VALUE)
);
jPanel12Layout.setVerticalGroup(
jPanel12Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 100, Short.MAX_VALUE)
);
setName("Form"); // NOI18N
jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jPanel1.setName("jPanel1"); // NOI18N
jPanel1.setPreferredSize(new java.awt.Dimension(500, 140));
jPanel1.setLayout(new java.awt.BorderLayout());
jPanel2.setMinimumSize(new java.awt.Dimension(0, 0));
jPanel2.setName("jPanel2"); // NOI18N
jPanel2.setPreferredSize(new java.awt.Dimension(500, 20));
org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(imat.IMatApp.class).getContext().getResourceMap(SplashPanel.class);
+ jLabel1.setFont(resourceMap.getFont("jLabel1.font")); // NOI18N
jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
jLabel1.setName("jLabel1"); // NOI18N
org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jLabel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 594, Short.MAX_VALUE)
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jLabel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 20, Short.MAX_VALUE)
);
jPanel1.add(jPanel2, java.awt.BorderLayout.NORTH);
jPanel8.setName("jPanel8"); // NOI18N
jPanel8.setPreferredSize(new java.awt.Dimension(735, 150));
jPanel5.setName("jPanel5"); // NOI18N
jPanel5.setLayout(new java.awt.GridLayout(1, 3, 20, 10));
org.jdesktop.layout.GroupLayout jPanel8Layout = new org.jdesktop.layout.GroupLayout(jPanel8);
jPanel8.setLayout(jPanel8Layout);
jPanel8Layout.setHorizontalGroup(
jPanel8Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 594, Short.MAX_VALUE)
.add(jPanel8Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel8Layout.createSequentialGroup()
.addContainerGap()
.add(jPanel5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 554, Short.MAX_VALUE)
.addContainerGap()))
);
jPanel8Layout.setVerticalGroup(
jPanel8Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 161, Short.MAX_VALUE)
.add(jPanel8Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel8Layout.createSequentialGroup()
.add(jPanel5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 141, Short.MAX_VALUE)
.addContainerGap()))
);
jPanel1.add(jPanel8, java.awt.BorderLayout.CENTER);
jPanel4.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jPanel4.setName("jPanel4"); // NOI18N
jPanel4.setPreferredSize(new java.awt.Dimension(260, 430));
jPanel4.setLayout(new java.awt.BorderLayout());
jPanel7.setName("jPanel7"); // NOI18N
jPanel7.setPreferredSize(new java.awt.Dimension(258, 25));
+ jLabel3.setFont(resourceMap.getFont("jLabel3.font")); // NOI18N
jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
jLabel3.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel3.setName("jLabel3"); // NOI18N
org.jdesktop.layout.GroupLayout jPanel7Layout = new org.jdesktop.layout.GroupLayout(jPanel7);
jPanel7.setLayout(jPanel7Layout);
jPanel7Layout.setHorizontalGroup(
jPanel7Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jLabel3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 258, Short.MAX_VALUE)
);
jPanel7Layout.setVerticalGroup(
jPanel7Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jLabel3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 25, Short.MAX_VALUE)
);
jPanel4.add(jPanel7, java.awt.BorderLayout.NORTH);
jPanel6.setName("jPanel6"); // NOI18N
jPanel6.setPreferredSize(new java.awt.Dimension(300, 403));
jPanel16.setName("jPanel16"); // NOI18N
org.jdesktop.layout.GroupLayout jPanel16Layout = new org.jdesktop.layout.GroupLayout(jPanel16);
jPanel16.setLayout(jPanel16Layout);
jPanel16Layout.setHorizontalGroup(
jPanel16Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 218, Short.MAX_VALUE)
);
jPanel16Layout.setVerticalGroup(
jPanel16Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 376, Short.MAX_VALUE)
);
org.jdesktop.layout.GroupLayout jPanel6Layout = new org.jdesktop.layout.GroupLayout(jPanel6);
jPanel6.setLayout(jPanel6Layout);
jPanel6Layout.setHorizontalGroup(
jPanel6Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 258, Short.MAX_VALUE)
.add(jPanel6Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel6Layout.createSequentialGroup()
.addContainerGap()
.add(jPanel16, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap()))
);
jPanel6Layout.setVerticalGroup(
jPanel6Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 416, Short.MAX_VALUE)
.add(jPanel6Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel6Layout.createSequentialGroup()
.addContainerGap()
.add(jPanel16, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap()))
);
jPanel4.add(jPanel6, java.awt.BorderLayout.CENTER);
jPanel9.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jPanel9.setName("jPanel9"); // NOI18N
jPanel9.setPreferredSize(new java.awt.Dimension(260, 430));
jPanel9.setLayout(new java.awt.BorderLayout());
jPanel10.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jPanel10.setName("jPanel10"); // NOI18N
jPanel10.setPreferredSize(new java.awt.Dimension(260, 25));
+ jLabel2.setFont(resourceMap.getFont("jLabel2.font")); // NOI18N
jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
jLabel2.setName("jLabel2"); // NOI18N
org.jdesktop.layout.GroupLayout jPanel10Layout = new org.jdesktop.layout.GroupLayout(jPanel10);
jPanel10.setLayout(jPanel10Layout);
jPanel10Layout.setHorizontalGroup(
jPanel10Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jLabel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 256, Short.MAX_VALUE)
);
jPanel10Layout.setVerticalGroup(
jPanel10Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jLabel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 23, Short.MAX_VALUE)
);
jPanel9.add(jPanel10, java.awt.BorderLayout.PAGE_START);
jPanel11.setName("jPanel11"); // NOI18N
jPanel15.setName("jPanel15"); // NOI18N
org.jdesktop.layout.GroupLayout jPanel15Layout = new org.jdesktop.layout.GroupLayout(jPanel15);
jPanel15.setLayout(jPanel15Layout);
jPanel15Layout.setHorizontalGroup(
jPanel15Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 218, Short.MAX_VALUE)
);
jPanel15Layout.setVerticalGroup(
jPanel15Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 376, Short.MAX_VALUE)
);
org.jdesktop.layout.GroupLayout jPanel11Layout = new org.jdesktop.layout.GroupLayout(jPanel11);
jPanel11.setLayout(jPanel11Layout);
jPanel11Layout.setHorizontalGroup(
jPanel11Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel11Layout.createSequentialGroup()
.addContainerGap()
.add(jPanel15, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
jPanel11Layout.setVerticalGroup(
jPanel11Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel11Layout.createSequentialGroup()
.addContainerGap()
.add(jPanel15, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
jPanel9.add(jPanel11, java.awt.BorderLayout.CENTER);
jPanel14.setName("jPanel14"); // NOI18N
org.jdesktop.layout.GroupLayout jPanel14Layout = new org.jdesktop.layout.GroupLayout(jPanel14);
jPanel14.setLayout(jPanel14Layout);
jPanel14Layout.setHorizontalGroup(
jPanel14Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 44, Short.MAX_VALUE)
);
jPanel14Layout.setVerticalGroup(
jPanel14Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 644, Short.MAX_VALUE)
);
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(jPanel14, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
.add(layout.createSequentialGroup()
.add(jPanel4, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(jPanel9, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 596, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(126, 126, 126))
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
.add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 183, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(18, 18, 18)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(jPanel9, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 443, Short.MAX_VALUE)
.add(org.jdesktop.layout.GroupLayout.LEADING, jPanel4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 443, Short.MAX_VALUE)))
.add(jPanel14, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel10;
private javax.swing.JPanel jPanel11;
private javax.swing.JPanel jPanel12;
private javax.swing.JPanel jPanel14;
private javax.swing.JPanel jPanel15;
private javax.swing.JPanel jPanel16;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JPanel jPanel6;
private javax.swing.JPanel jPanel7;
private javax.swing.JPanel jPanel8;
private javax.swing.JPanel jPanel9;
// End of variables declaration//GEN-END:variables
}
| false | true | private void initComponents() {
jPanel12 = new javax.swing.JPanel();
jPanel1 = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jPanel8 = new javax.swing.JPanel();
jPanel5 = new javax.swing.JPanel();
jPanel4 = new javax.swing.JPanel();
jPanel7 = new javax.swing.JPanel();
jLabel3 = new javax.swing.JLabel();
jPanel6 = new javax.swing.JPanel();
jPanel16 = new javax.swing.JPanel();
jPanel9 = new javax.swing.JPanel();
jPanel10 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
jPanel11 = new javax.swing.JPanel();
jPanel15 = new javax.swing.JPanel();
jPanel14 = new javax.swing.JPanel();
jPanel12.setName("jPanel12"); // NOI18N
org.jdesktop.layout.GroupLayout jPanel12Layout = new org.jdesktop.layout.GroupLayout(jPanel12);
jPanel12.setLayout(jPanel12Layout);
jPanel12Layout.setHorizontalGroup(
jPanel12Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 100, Short.MAX_VALUE)
);
jPanel12Layout.setVerticalGroup(
jPanel12Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 100, Short.MAX_VALUE)
);
setName("Form"); // NOI18N
jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jPanel1.setName("jPanel1"); // NOI18N
jPanel1.setPreferredSize(new java.awt.Dimension(500, 140));
jPanel1.setLayout(new java.awt.BorderLayout());
jPanel2.setMinimumSize(new java.awt.Dimension(0, 0));
jPanel2.setName("jPanel2"); // NOI18N
jPanel2.setPreferredSize(new java.awt.Dimension(500, 20));
org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(imat.IMatApp.class).getContext().getResourceMap(SplashPanel.class);
jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
jLabel1.setName("jLabel1"); // NOI18N
org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jLabel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 594, Short.MAX_VALUE)
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jLabel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 20, Short.MAX_VALUE)
);
jPanel1.add(jPanel2, java.awt.BorderLayout.NORTH);
jPanel8.setName("jPanel8"); // NOI18N
jPanel8.setPreferredSize(new java.awt.Dimension(735, 150));
jPanel5.setName("jPanel5"); // NOI18N
jPanel5.setLayout(new java.awt.GridLayout(1, 3, 20, 10));
org.jdesktop.layout.GroupLayout jPanel8Layout = new org.jdesktop.layout.GroupLayout(jPanel8);
jPanel8.setLayout(jPanel8Layout);
jPanel8Layout.setHorizontalGroup(
jPanel8Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 594, Short.MAX_VALUE)
.add(jPanel8Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel8Layout.createSequentialGroup()
.addContainerGap()
.add(jPanel5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 554, Short.MAX_VALUE)
.addContainerGap()))
);
jPanel8Layout.setVerticalGroup(
jPanel8Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 161, Short.MAX_VALUE)
.add(jPanel8Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel8Layout.createSequentialGroup()
.add(jPanel5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 141, Short.MAX_VALUE)
.addContainerGap()))
);
jPanel1.add(jPanel8, java.awt.BorderLayout.CENTER);
jPanel4.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jPanel4.setName("jPanel4"); // NOI18N
jPanel4.setPreferredSize(new java.awt.Dimension(260, 430));
jPanel4.setLayout(new java.awt.BorderLayout());
jPanel7.setName("jPanel7"); // NOI18N
jPanel7.setPreferredSize(new java.awt.Dimension(258, 25));
jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
jLabel3.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel3.setName("jLabel3"); // NOI18N
org.jdesktop.layout.GroupLayout jPanel7Layout = new org.jdesktop.layout.GroupLayout(jPanel7);
jPanel7.setLayout(jPanel7Layout);
jPanel7Layout.setHorizontalGroup(
jPanel7Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jLabel3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 258, Short.MAX_VALUE)
);
jPanel7Layout.setVerticalGroup(
jPanel7Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jLabel3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 25, Short.MAX_VALUE)
);
jPanel4.add(jPanel7, java.awt.BorderLayout.NORTH);
jPanel6.setName("jPanel6"); // NOI18N
jPanel6.setPreferredSize(new java.awt.Dimension(300, 403));
jPanel16.setName("jPanel16"); // NOI18N
org.jdesktop.layout.GroupLayout jPanel16Layout = new org.jdesktop.layout.GroupLayout(jPanel16);
jPanel16.setLayout(jPanel16Layout);
jPanel16Layout.setHorizontalGroup(
jPanel16Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 218, Short.MAX_VALUE)
);
jPanel16Layout.setVerticalGroup(
jPanel16Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 376, Short.MAX_VALUE)
);
org.jdesktop.layout.GroupLayout jPanel6Layout = new org.jdesktop.layout.GroupLayout(jPanel6);
jPanel6.setLayout(jPanel6Layout);
jPanel6Layout.setHorizontalGroup(
jPanel6Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 258, Short.MAX_VALUE)
.add(jPanel6Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel6Layout.createSequentialGroup()
.addContainerGap()
.add(jPanel16, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap()))
);
jPanel6Layout.setVerticalGroup(
jPanel6Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 416, Short.MAX_VALUE)
.add(jPanel6Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel6Layout.createSequentialGroup()
.addContainerGap()
.add(jPanel16, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap()))
);
jPanel4.add(jPanel6, java.awt.BorderLayout.CENTER);
jPanel9.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jPanel9.setName("jPanel9"); // NOI18N
jPanel9.setPreferredSize(new java.awt.Dimension(260, 430));
jPanel9.setLayout(new java.awt.BorderLayout());
jPanel10.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jPanel10.setName("jPanel10"); // NOI18N
jPanel10.setPreferredSize(new java.awt.Dimension(260, 25));
jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
jLabel2.setName("jLabel2"); // NOI18N
org.jdesktop.layout.GroupLayout jPanel10Layout = new org.jdesktop.layout.GroupLayout(jPanel10);
jPanel10.setLayout(jPanel10Layout);
jPanel10Layout.setHorizontalGroup(
jPanel10Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jLabel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 256, Short.MAX_VALUE)
);
jPanel10Layout.setVerticalGroup(
jPanel10Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jLabel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 23, Short.MAX_VALUE)
);
jPanel9.add(jPanel10, java.awt.BorderLayout.PAGE_START);
jPanel11.setName("jPanel11"); // NOI18N
jPanel15.setName("jPanel15"); // NOI18N
org.jdesktop.layout.GroupLayout jPanel15Layout = new org.jdesktop.layout.GroupLayout(jPanel15);
jPanel15.setLayout(jPanel15Layout);
jPanel15Layout.setHorizontalGroup(
jPanel15Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 218, Short.MAX_VALUE)
);
jPanel15Layout.setVerticalGroup(
jPanel15Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 376, Short.MAX_VALUE)
);
org.jdesktop.layout.GroupLayout jPanel11Layout = new org.jdesktop.layout.GroupLayout(jPanel11);
jPanel11.setLayout(jPanel11Layout);
jPanel11Layout.setHorizontalGroup(
jPanel11Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel11Layout.createSequentialGroup()
.addContainerGap()
.add(jPanel15, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
jPanel11Layout.setVerticalGroup(
jPanel11Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel11Layout.createSequentialGroup()
.addContainerGap()
.add(jPanel15, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
jPanel9.add(jPanel11, java.awt.BorderLayout.CENTER);
jPanel14.setName("jPanel14"); // NOI18N
org.jdesktop.layout.GroupLayout jPanel14Layout = new org.jdesktop.layout.GroupLayout(jPanel14);
jPanel14.setLayout(jPanel14Layout);
jPanel14Layout.setHorizontalGroup(
jPanel14Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 44, Short.MAX_VALUE)
);
jPanel14Layout.setVerticalGroup(
jPanel14Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 644, Short.MAX_VALUE)
);
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(jPanel14, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
.add(layout.createSequentialGroup()
.add(jPanel4, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(jPanel9, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 596, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(126, 126, 126))
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
.add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 183, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(18, 18, 18)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(jPanel9, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 443, Short.MAX_VALUE)
.add(org.jdesktop.layout.GroupLayout.LEADING, jPanel4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 443, Short.MAX_VALUE)))
.add(jPanel14, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
);
}// </editor-fold>//GEN-END:initComponents
| private void initComponents() {
jPanel12 = new javax.swing.JPanel();
jPanel1 = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jPanel8 = new javax.swing.JPanel();
jPanel5 = new javax.swing.JPanel();
jPanel4 = new javax.swing.JPanel();
jPanel7 = new javax.swing.JPanel();
jLabel3 = new javax.swing.JLabel();
jPanel6 = new javax.swing.JPanel();
jPanel16 = new javax.swing.JPanel();
jPanel9 = new javax.swing.JPanel();
jPanel10 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
jPanel11 = new javax.swing.JPanel();
jPanel15 = new javax.swing.JPanel();
jPanel14 = new javax.swing.JPanel();
jPanel12.setName("jPanel12"); // NOI18N
org.jdesktop.layout.GroupLayout jPanel12Layout = new org.jdesktop.layout.GroupLayout(jPanel12);
jPanel12.setLayout(jPanel12Layout);
jPanel12Layout.setHorizontalGroup(
jPanel12Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 100, Short.MAX_VALUE)
);
jPanel12Layout.setVerticalGroup(
jPanel12Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 100, Short.MAX_VALUE)
);
setName("Form"); // NOI18N
jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jPanel1.setName("jPanel1"); // NOI18N
jPanel1.setPreferredSize(new java.awt.Dimension(500, 140));
jPanel1.setLayout(new java.awt.BorderLayout());
jPanel2.setMinimumSize(new java.awt.Dimension(0, 0));
jPanel2.setName("jPanel2"); // NOI18N
jPanel2.setPreferredSize(new java.awt.Dimension(500, 20));
org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(imat.IMatApp.class).getContext().getResourceMap(SplashPanel.class);
jLabel1.setFont(resourceMap.getFont("jLabel1.font")); // NOI18N
jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
jLabel1.setName("jLabel1"); // NOI18N
org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jLabel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 594, Short.MAX_VALUE)
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jLabel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 20, Short.MAX_VALUE)
);
jPanel1.add(jPanel2, java.awt.BorderLayout.NORTH);
jPanel8.setName("jPanel8"); // NOI18N
jPanel8.setPreferredSize(new java.awt.Dimension(735, 150));
jPanel5.setName("jPanel5"); // NOI18N
jPanel5.setLayout(new java.awt.GridLayout(1, 3, 20, 10));
org.jdesktop.layout.GroupLayout jPanel8Layout = new org.jdesktop.layout.GroupLayout(jPanel8);
jPanel8.setLayout(jPanel8Layout);
jPanel8Layout.setHorizontalGroup(
jPanel8Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 594, Short.MAX_VALUE)
.add(jPanel8Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel8Layout.createSequentialGroup()
.addContainerGap()
.add(jPanel5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 554, Short.MAX_VALUE)
.addContainerGap()))
);
jPanel8Layout.setVerticalGroup(
jPanel8Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 161, Short.MAX_VALUE)
.add(jPanel8Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel8Layout.createSequentialGroup()
.add(jPanel5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 141, Short.MAX_VALUE)
.addContainerGap()))
);
jPanel1.add(jPanel8, java.awt.BorderLayout.CENTER);
jPanel4.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jPanel4.setName("jPanel4"); // NOI18N
jPanel4.setPreferredSize(new java.awt.Dimension(260, 430));
jPanel4.setLayout(new java.awt.BorderLayout());
jPanel7.setName("jPanel7"); // NOI18N
jPanel7.setPreferredSize(new java.awt.Dimension(258, 25));
jLabel3.setFont(resourceMap.getFont("jLabel3.font")); // NOI18N
jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
jLabel3.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel3.setName("jLabel3"); // NOI18N
org.jdesktop.layout.GroupLayout jPanel7Layout = new org.jdesktop.layout.GroupLayout(jPanel7);
jPanel7.setLayout(jPanel7Layout);
jPanel7Layout.setHorizontalGroup(
jPanel7Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jLabel3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 258, Short.MAX_VALUE)
);
jPanel7Layout.setVerticalGroup(
jPanel7Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jLabel3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 25, Short.MAX_VALUE)
);
jPanel4.add(jPanel7, java.awt.BorderLayout.NORTH);
jPanel6.setName("jPanel6"); // NOI18N
jPanel6.setPreferredSize(new java.awt.Dimension(300, 403));
jPanel16.setName("jPanel16"); // NOI18N
org.jdesktop.layout.GroupLayout jPanel16Layout = new org.jdesktop.layout.GroupLayout(jPanel16);
jPanel16.setLayout(jPanel16Layout);
jPanel16Layout.setHorizontalGroup(
jPanel16Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 218, Short.MAX_VALUE)
);
jPanel16Layout.setVerticalGroup(
jPanel16Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 376, Short.MAX_VALUE)
);
org.jdesktop.layout.GroupLayout jPanel6Layout = new org.jdesktop.layout.GroupLayout(jPanel6);
jPanel6.setLayout(jPanel6Layout);
jPanel6Layout.setHorizontalGroup(
jPanel6Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 258, Short.MAX_VALUE)
.add(jPanel6Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel6Layout.createSequentialGroup()
.addContainerGap()
.add(jPanel16, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap()))
);
jPanel6Layout.setVerticalGroup(
jPanel6Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 416, Short.MAX_VALUE)
.add(jPanel6Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel6Layout.createSequentialGroup()
.addContainerGap()
.add(jPanel16, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap()))
);
jPanel4.add(jPanel6, java.awt.BorderLayout.CENTER);
jPanel9.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jPanel9.setName("jPanel9"); // NOI18N
jPanel9.setPreferredSize(new java.awt.Dimension(260, 430));
jPanel9.setLayout(new java.awt.BorderLayout());
jPanel10.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jPanel10.setName("jPanel10"); // NOI18N
jPanel10.setPreferredSize(new java.awt.Dimension(260, 25));
jLabel2.setFont(resourceMap.getFont("jLabel2.font")); // NOI18N
jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
jLabel2.setName("jLabel2"); // NOI18N
org.jdesktop.layout.GroupLayout jPanel10Layout = new org.jdesktop.layout.GroupLayout(jPanel10);
jPanel10.setLayout(jPanel10Layout);
jPanel10Layout.setHorizontalGroup(
jPanel10Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jLabel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 256, Short.MAX_VALUE)
);
jPanel10Layout.setVerticalGroup(
jPanel10Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jLabel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 23, Short.MAX_VALUE)
);
jPanel9.add(jPanel10, java.awt.BorderLayout.PAGE_START);
jPanel11.setName("jPanel11"); // NOI18N
jPanel15.setName("jPanel15"); // NOI18N
org.jdesktop.layout.GroupLayout jPanel15Layout = new org.jdesktop.layout.GroupLayout(jPanel15);
jPanel15.setLayout(jPanel15Layout);
jPanel15Layout.setHorizontalGroup(
jPanel15Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 218, Short.MAX_VALUE)
);
jPanel15Layout.setVerticalGroup(
jPanel15Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 376, Short.MAX_VALUE)
);
org.jdesktop.layout.GroupLayout jPanel11Layout = new org.jdesktop.layout.GroupLayout(jPanel11);
jPanel11.setLayout(jPanel11Layout);
jPanel11Layout.setHorizontalGroup(
jPanel11Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel11Layout.createSequentialGroup()
.addContainerGap()
.add(jPanel15, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
jPanel11Layout.setVerticalGroup(
jPanel11Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel11Layout.createSequentialGroup()
.addContainerGap()
.add(jPanel15, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
jPanel9.add(jPanel11, java.awt.BorderLayout.CENTER);
jPanel14.setName("jPanel14"); // NOI18N
org.jdesktop.layout.GroupLayout jPanel14Layout = new org.jdesktop.layout.GroupLayout(jPanel14);
jPanel14.setLayout(jPanel14Layout);
jPanel14Layout.setHorizontalGroup(
jPanel14Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 44, Short.MAX_VALUE)
);
jPanel14Layout.setVerticalGroup(
jPanel14Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 644, Short.MAX_VALUE)
);
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(jPanel14, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
.add(layout.createSequentialGroup()
.add(jPanel4, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(jPanel9, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 596, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(126, 126, 126))
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
.add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 183, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(18, 18, 18)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(jPanel9, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 443, Short.MAX_VALUE)
.add(org.jdesktop.layout.GroupLayout.LEADING, jPanel4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 443, Short.MAX_VALUE)))
.add(jPanel14, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
);
}// </editor-fold>//GEN-END:initComponents
|
diff --git a/src/main/java/org/junit/experimental/ParallelComputer.java b/src/main/java/org/junit/experimental/ParallelComputer.java
index 34ed52f9..96271e7d 100644
--- a/src/main/java/org/junit/experimental/ParallelComputer.java
+++ b/src/main/java/org/junit/experimental/ParallelComputer.java
@@ -1,67 +1,67 @@
package org.junit.experimental;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.junit.runner.Computer;
import org.junit.runner.Runner;
import org.junit.runners.ParentRunner;
import org.junit.runners.model.InitializationError;
import org.junit.runners.model.RunnerBuilder;
import org.junit.runners.model.RunnerScheduler;
public class ParallelComputer extends Computer {
private final boolean fClasses;
private final boolean fMethods;
public ParallelComputer(boolean classes, boolean methods) {
fClasses = classes;
fMethods = methods;
}
public static Computer classes() {
return new ParallelComputer(true, false);
}
public static Computer methods() {
return new ParallelComputer(false, true);
}
private static Runner parallelize(Runner runner) {
if (runner instanceof ParentRunner) {
((ParentRunner<?>) runner).setScheduler(new RunnerScheduler() {
private final ExecutorService fService = Executors.newCachedThreadPool();
public void schedule(Runnable childStatement) {
fService.submit(childStatement);
}
public void finished() {
try {
fService.shutdown();
- fService.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
+ fService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
e.printStackTrace(System.err);
}
}
});
}
return runner;
}
@Override
public Runner getSuite(RunnerBuilder builder, java.lang.Class<?>[] classes)
throws InitializationError {
Runner suite = super.getSuite(builder, classes);
return fClasses ? parallelize(suite) : suite;
}
@Override
protected Runner getRunner(RunnerBuilder builder, Class<?> testClass)
throws Throwable {
Runner runner = super.getRunner(builder, testClass);
return fMethods ? parallelize(runner) : runner;
}
}
| true | true | private static Runner parallelize(Runner runner) {
if (runner instanceof ParentRunner) {
((ParentRunner<?>) runner).setScheduler(new RunnerScheduler() {
private final ExecutorService fService = Executors.newCachedThreadPool();
public void schedule(Runnable childStatement) {
fService.submit(childStatement);
}
public void finished() {
try {
fService.shutdown();
fService.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
} catch (InterruptedException e) {
e.printStackTrace(System.err);
}
}
});
}
return runner;
}
| private static Runner parallelize(Runner runner) {
if (runner instanceof ParentRunner) {
((ParentRunner<?>) runner).setScheduler(new RunnerScheduler() {
private final ExecutorService fService = Executors.newCachedThreadPool();
public void schedule(Runnable childStatement) {
fService.submit(childStatement);
}
public void finished() {
try {
fService.shutdown();
fService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
e.printStackTrace(System.err);
}
}
});
}
return runner;
}
|
diff --git a/src/com/cole2sworld/ColeBans/commands/Switch.java b/src/com/cole2sworld/ColeBans/commands/Switch.java
index f36bb86..3ca3261 100644
--- a/src/com/cole2sworld/ColeBans/commands/Switch.java
+++ b/src/com/cole2sworld/ColeBans/commands/Switch.java
@@ -1,51 +1,52 @@
package com.cole2sworld.ColeBans.commands;
import java.lang.reflect.InvocationTargetException;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import com.cole2sworld.ColeBans.GlobalConf;
import com.cole2sworld.ColeBans.Main;
import com.cole2sworld.ColeBans.Util;
import com.cole2sworld.ColeBans.framework.PermissionSet;
import com.cole2sworld.ColeBans.handlers.BanHandler;
public class Switch extends CBCommand {
@Override
public String run(String[] args, CommandSender admin) {
PermissionSet perm = new PermissionSet(admin);
if (!perm.canSwitch) return ChatColor.RED+"You don't have permission to do that.";
if (args.length > 1) return ChatColor.RED+"The switch command must be used with only the destination handler as an argument";
else {
try {
BanHandler dest = Util.lookupHandler(args[0]);
Main.LOG.info("Starting conversion from "+Main.instance.banHandler.getClass().getSimpleName().replace(GlobalConf.Advanced.suffix, "")+" to "+args[0]);
admin.sendMessage(ChatColor.YELLOW+"Starting conversion...");
Main.instance.banHandler.convert(dest);
Main.instance.banHandler.onDisable();
GlobalConf.conf.set("settings.banHandler", args[0]);
+ Main.instance.saveConfig();
Main.instance.banHandler = dest;
Main.LOG.info("Conversion succeeded!");
admin.sendMessage(ChatColor.GREEN+"Conversion succeeded!");
} catch (IllegalArgumentException e) {
return ChatColor.DARK_RED+"Given ban handler is wierdly implemented";
} catch (SecurityException e) {
return ChatColor.DARK_RED+"Plugin conflict!";
} catch (ClassCastException e) {
return ChatColor.DARK_RED+"Given ban handler is not actually a ban handler";
} catch (ClassNotFoundException e) {
return ChatColor.DARK_RED+"No such ban handler '"+args[0]+"' Make sure you got the caps right!";
} catch (IllegalAccessException e) {
return ChatColor.DARK_RED+"Given ban handler is wierdly implemented";
} catch (InvocationTargetException e) {
return ChatColor.DARK_RED+"Given ban handler is wierdly implemented";
} catch (NoSuchMethodException e) {
return ChatColor.DARK_RED+"Given ban handler is wierdly implemented";
}
}
return null;
}
}
| true | true | public String run(String[] args, CommandSender admin) {
PermissionSet perm = new PermissionSet(admin);
if (!perm.canSwitch) return ChatColor.RED+"You don't have permission to do that.";
if (args.length > 1) return ChatColor.RED+"The switch command must be used with only the destination handler as an argument";
else {
try {
BanHandler dest = Util.lookupHandler(args[0]);
Main.LOG.info("Starting conversion from "+Main.instance.banHandler.getClass().getSimpleName().replace(GlobalConf.Advanced.suffix, "")+" to "+args[0]);
admin.sendMessage(ChatColor.YELLOW+"Starting conversion...");
Main.instance.banHandler.convert(dest);
Main.instance.banHandler.onDisable();
GlobalConf.conf.set("settings.banHandler", args[0]);
Main.instance.banHandler = dest;
Main.LOG.info("Conversion succeeded!");
admin.sendMessage(ChatColor.GREEN+"Conversion succeeded!");
} catch (IllegalArgumentException e) {
return ChatColor.DARK_RED+"Given ban handler is wierdly implemented";
} catch (SecurityException e) {
return ChatColor.DARK_RED+"Plugin conflict!";
} catch (ClassCastException e) {
return ChatColor.DARK_RED+"Given ban handler is not actually a ban handler";
} catch (ClassNotFoundException e) {
return ChatColor.DARK_RED+"No such ban handler '"+args[0]+"' Make sure you got the caps right!";
} catch (IllegalAccessException e) {
return ChatColor.DARK_RED+"Given ban handler is wierdly implemented";
} catch (InvocationTargetException e) {
return ChatColor.DARK_RED+"Given ban handler is wierdly implemented";
} catch (NoSuchMethodException e) {
return ChatColor.DARK_RED+"Given ban handler is wierdly implemented";
}
}
return null;
}
| public String run(String[] args, CommandSender admin) {
PermissionSet perm = new PermissionSet(admin);
if (!perm.canSwitch) return ChatColor.RED+"You don't have permission to do that.";
if (args.length > 1) return ChatColor.RED+"The switch command must be used with only the destination handler as an argument";
else {
try {
BanHandler dest = Util.lookupHandler(args[0]);
Main.LOG.info("Starting conversion from "+Main.instance.banHandler.getClass().getSimpleName().replace(GlobalConf.Advanced.suffix, "")+" to "+args[0]);
admin.sendMessage(ChatColor.YELLOW+"Starting conversion...");
Main.instance.banHandler.convert(dest);
Main.instance.banHandler.onDisable();
GlobalConf.conf.set("settings.banHandler", args[0]);
Main.instance.saveConfig();
Main.instance.banHandler = dest;
Main.LOG.info("Conversion succeeded!");
admin.sendMessage(ChatColor.GREEN+"Conversion succeeded!");
} catch (IllegalArgumentException e) {
return ChatColor.DARK_RED+"Given ban handler is wierdly implemented";
} catch (SecurityException e) {
return ChatColor.DARK_RED+"Plugin conflict!";
} catch (ClassCastException e) {
return ChatColor.DARK_RED+"Given ban handler is not actually a ban handler";
} catch (ClassNotFoundException e) {
return ChatColor.DARK_RED+"No such ban handler '"+args[0]+"' Make sure you got the caps right!";
} catch (IllegalAccessException e) {
return ChatColor.DARK_RED+"Given ban handler is wierdly implemented";
} catch (InvocationTargetException e) {
return ChatColor.DARK_RED+"Given ban handler is wierdly implemented";
} catch (NoSuchMethodException e) {
return ChatColor.DARK_RED+"Given ban handler is wierdly implemented";
}
}
return null;
}
|
diff --git a/src/edu/worcester/cs499summer2012/adapter/TaskListAdapter.java b/src/edu/worcester/cs499summer2012/adapter/TaskListAdapter.java
index f1bf775..9c8a59b 100644
--- a/src/edu/worcester/cs499summer2012/adapter/TaskListAdapter.java
+++ b/src/edu/worcester/cs499summer2012/adapter/TaskListAdapter.java
@@ -1,339 +1,340 @@
/*
* TaskListAdapter.java
*
* Copyright 2012 Jonathan Hasenzahl, James Celona, Dhimitraq Jorgji
*
* 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 edu.worcester.cs499summer2012.adapter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.preference.PreferenceManager;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import edu.worcester.cs499summer2012.R;
import edu.worcester.cs499summer2012.activity.SettingsActivity;
import edu.worcester.cs499summer2012.comparator.TaskAutoComparator;
import edu.worcester.cs499summer2012.comparator.TaskCategoryComparator;
import edu.worcester.cs499summer2012.comparator.TaskCompletionComparator;
import edu.worcester.cs499summer2012.comparator.TaskDateCreatedComparator;
import edu.worcester.cs499summer2012.comparator.TaskDateDueComparator;
import edu.worcester.cs499summer2012.comparator.TaskDateModifiedComparator;
import edu.worcester.cs499summer2012.comparator.TaskNameComparator;
import edu.worcester.cs499summer2012.comparator.TaskPriorityComparator;
import edu.worcester.cs499summer2012.database.TasksDataSource;
import edu.worcester.cs499summer2012.service.TaskAlarm;
import edu.worcester.cs499summer2012.task.Task;
import edu.worcester.cs499summer2012.task.ToastMaker;
/**
* ListView adapter for the TaskList container. Enables tasks in a TaskList
* to be viewed in a ListView. Also allows for list sorting using task
* comparators.
* @author Jonathan Hasenzahl
*/
public class TaskListAdapter extends ArrayAdapter<Task> {
/**************************************************************************
* Static fields and methods *
**************************************************************************/
public static final int AUTO_SORT = 0;
public static final int CUSTOM_SORT = 1;
static class ViewHolder {
public CheckBox is_completed;
public TextView name;
public View category;
public ImageView priority;
public TextView due_date;
}
/**************************************************************************
* Private fields *
**************************************************************************/
private final Activity activity;
private final ArrayList<Task> tasks;
private TasksDataSource data_source;
private SharedPreferences prefs;
private int sort_type;
/**************************************************************************
* Constructors *
**************************************************************************/
/**
* Default constructor. Creates a new TaskListAdapter containing a TaskList
* and assigned to an Activity.
* @param activity the Activity that owns this adapter
* @param tasks the TaskList handled by this adapter
*/
public TaskListAdapter(Activity activity, ArrayList<Task> tasks) {
super(activity, R.layout.row_task, tasks);
this.activity = activity;
this.tasks = tasks;
data_source = TasksDataSource.getInstance(this.activity);
prefs = PreferenceManager.getDefaultSharedPreferences(this.activity);
setNotifyOnChange(true);
}
/**************************************************************************
* Overridden parent methods *
**************************************************************************/
/**
* This method is called automatically when the user scrolls the ListView.
* Updates the View of a single visible row, reflecting the list being
* scrolled by the user.
* @param position the index of the TaskList
* @param convert_view the View to be updated
* @param parent the parent ViewGroup of convert_view
* @return the updated View
*/
@Override
public View getView(int position, View convert_view, ViewGroup parent) {
View view = convert_view;
Task task = tasks.get(position);
if (view == null) {
LayoutInflater inflater = activity.getLayoutInflater();
view = inflater.inflate(R.layout.row_task, null);
final ViewHolder view_holder = new ViewHolder();
view_holder.is_completed = (CheckBox) view.findViewById(R.id.checkbox_row_complete);
view_holder.is_completed.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Task task = (Task) view_holder.is_completed.getTag();
task.toggleIsCompleted();
task.setDateModified(System.currentTimeMillis());
// Update DB
data_source.updateTask(task);
// Alarm logic: Complete/Uncomplete a task
// * Don't forget to update date modified!
// * Task must be updated in database first
// * Cancel alarm first to be safe
// * Cancel an existing notification
// * If user completed the task:
// * If is repeating:
// * Set repeating alarm to get new due date (possibly uncompletes the task)
// * Notify user that repeated task has been rescheduled
// * Set alarm
// * (Future repeating due date will be handled by the service after alarm rings)
// * Else user uncompleted the task:
// * If has due date and is not past due:
// * Set alarm
TaskAlarm alarm = new TaskAlarm();
alarm.cancelAlarm(activity, task.getID());
alarm.cancelNotification(activity, task.getID());
if (task.isCompleted()) {
toast(R.string.toast_task_completed);
if (task.isRepeating()) {
task = alarm.setRepeatingAlarm(activity, task.getID());
if (!task.isCompleted()) {
alarm.setAlarm(activity, task);
toast(ToastMaker.getRepeatMessage(activity,
R.string.toast_task_repeated,
task.getDateDueCal()));
} else {
toast(ToastMaker.getRepeatMessage(activity,
R.string.toast_task_repeat_delayed,
task.getDateDueCal()));
}
}
} else {
if (task.hasDateDue() && !task.isPastDue())
alarm.setAlarm(activity, task);
}
// If "hide completed tasks" option, then remove the task from the adapter
if (prefs.getBoolean(SettingsActivity.HIDE_COMPLETED, true) && task.isCompleted())
tasks.remove(task);
sort();
}
});
view_holder.name = (TextView) view.findViewById(R.id.text_row_name);
view_holder.category = (View) view.findViewById(R.id.view_row_category);
view_holder.priority = (ImageView) view.findViewById(R.id.image_row_priority);
view_holder.due_date = (TextView) view.findViewById(R.id.text_row_due_date);
view.setTag(view_holder);
view_holder.is_completed.setTag(task);
} else
((ViewHolder) view.getTag()).is_completed.setTag(task);
ViewHolder holder = (ViewHolder) view.getTag();
// Set is completed
boolean is_complete = task.isCompleted();
holder.is_completed.setChecked(is_complete);
// Set name
holder.name.setText(task.getName());
holder.name.setTextColor(is_complete ? Color.GRAY : Color.WHITE);
// Set category
holder.category.setVisibility(View.VISIBLE);
holder.category.setBackgroundColor(data_source.getCategory(task.getCategory()).getColor());
// Set priority
if (is_complete)
holder.priority.setVisibility(View.INVISIBLE);
else {
holder.priority.setVisibility(View.VISIBLE);
switch (task.getPriority()) {
case Task.URGENT:
holder.priority.setImageResource(R.drawable.ic_urgent);
break;
case Task.TRIVIAL:
holder.priority.setImageResource(R.drawable.ic_trivial);
break;
case Task.NORMAL:
default:
holder.priority.setImageResource(R.drawable.ic_normal);
break;
}
}
// Set due date
if (is_complete)
holder.due_date.setVisibility(View.INVISIBLE);
else {
holder.due_date.setVisibility(View.VISIBLE);
holder.due_date.setTextColor(Color.LTGRAY);
if (task.hasDateDue()) {
Calendar current_date = GregorianCalendar.getInstance();
Calendar due_date = task.getDateDueCal();
- if (due_date.get(Calendar.YEAR) > current_date.get(Calendar.YEAR)) {
+ if (due_date.before(current_date))
+ {
+ // Due date is past
+ holder.due_date.setText("Past due");
+ holder.due_date.setTextColor(Color.RED);
+ } else if (due_date.get(Calendar.YEAR) > current_date.get(Calendar.YEAR)) {
// Due date is in a future year
holder.due_date.setText(DateFormat.format("MMM d'\n'yyyy", due_date));
} else if (due_date.get(Calendar.DAY_OF_YEAR) - current_date.get(Calendar.DAY_OF_YEAR) > 6) {
// Due date is more than a week away
holder.due_date.setText(DateFormat.format("MMM d", due_date));
} else if (due_date.get(Calendar.DAY_OF_YEAR) > current_date.get(Calendar.DAY_OF_YEAR)) {
// Due date is after today
holder.due_date.setText(DateFormat.format("E'\n'h:mmaa", due_date));
- } else if (!task.isPastDue()) {
+ } else {
// Due date is today
holder.due_date.setText(DateFormat.format("'Today\n'h:mmaa", due_date));
- } else {
- // Due date is past
- holder.due_date.setText("Past due");
- holder.due_date.setTextColor(Color.RED);
- }
+ }
} else
holder.due_date.setText("");
}
return view;
}
public void sort() {
if (sort_type == AUTO_SORT) {
this.sort(new TaskAutoComparator());
} else {
ArrayList<edu.worcester.cs499summer2012.task.Comparator> comparators = data_source.getComparators();
// Must iterate through the list backwards so higher sorting is done later
for (int i = comparators.size(); i > 0; i--) {
edu.worcester.cs499summer2012.task.Comparator comparator = comparators.get(i - 1);
if (comparator.isEnabled()) {
switch (comparator.getId()) {
case edu.worcester.cs499summer2012.task.Comparator.NAME:
this.sort(new TaskNameComparator());
break;
case edu.worcester.cs499summer2012.task.Comparator.COMPLETION:
this.sort(new TaskCompletionComparator());
break;
case edu.worcester.cs499summer2012.task.Comparator.PRIORITY:
this.sort(new TaskPriorityComparator());
break;
case edu.worcester.cs499summer2012.task.Comparator.CATEGORY:
this.sort(new TaskCategoryComparator());
break;
case edu.worcester.cs499summer2012.task.Comparator.DATE_DUE:
this.sort(new TaskDateDueComparator());
break;
case edu.worcester.cs499summer2012.task.Comparator.DATE_CREATED:
this.sort(new TaskDateCreatedComparator());
break;
case edu.worcester.cs499summer2012.task.Comparator.DATE_MODIFIED:
this.sort(new TaskDateModifiedComparator());
break;
default:
break;
}
}
}
}
this.notifyDataSetChanged();
}
/**************************************************************************
* Getters and setters *
**************************************************************************/
public int getSortType() {
return sort_type;
}
public void setSortType(int sort_type) {
if (sort_type == AUTO_SORT || sort_type == CUSTOM_SORT)
this.sort_type = sort_type;
}
/**
* Displays a message in a Toast notification for a short duration.
*/
private void toast(String message) {
Toast.makeText(activity, message, Toast.LENGTH_SHORT).show();
}
/**
* Displays a message in a Toast notification for a short duration.
*/
private void toast(int message) {
Toast.makeText(activity, message, Toast.LENGTH_SHORT).show();
}
}
| false | true | public View getView(int position, View convert_view, ViewGroup parent) {
View view = convert_view;
Task task = tasks.get(position);
if (view == null) {
LayoutInflater inflater = activity.getLayoutInflater();
view = inflater.inflate(R.layout.row_task, null);
final ViewHolder view_holder = new ViewHolder();
view_holder.is_completed = (CheckBox) view.findViewById(R.id.checkbox_row_complete);
view_holder.is_completed.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Task task = (Task) view_holder.is_completed.getTag();
task.toggleIsCompleted();
task.setDateModified(System.currentTimeMillis());
// Update DB
data_source.updateTask(task);
// Alarm logic: Complete/Uncomplete a task
// * Don't forget to update date modified!
// * Task must be updated in database first
// * Cancel alarm first to be safe
// * Cancel an existing notification
// * If user completed the task:
// * If is repeating:
// * Set repeating alarm to get new due date (possibly uncompletes the task)
// * Notify user that repeated task has been rescheduled
// * Set alarm
// * (Future repeating due date will be handled by the service after alarm rings)
// * Else user uncompleted the task:
// * If has due date and is not past due:
// * Set alarm
TaskAlarm alarm = new TaskAlarm();
alarm.cancelAlarm(activity, task.getID());
alarm.cancelNotification(activity, task.getID());
if (task.isCompleted()) {
toast(R.string.toast_task_completed);
if (task.isRepeating()) {
task = alarm.setRepeatingAlarm(activity, task.getID());
if (!task.isCompleted()) {
alarm.setAlarm(activity, task);
toast(ToastMaker.getRepeatMessage(activity,
R.string.toast_task_repeated,
task.getDateDueCal()));
} else {
toast(ToastMaker.getRepeatMessage(activity,
R.string.toast_task_repeat_delayed,
task.getDateDueCal()));
}
}
} else {
if (task.hasDateDue() && !task.isPastDue())
alarm.setAlarm(activity, task);
}
// If "hide completed tasks" option, then remove the task from the adapter
if (prefs.getBoolean(SettingsActivity.HIDE_COMPLETED, true) && task.isCompleted())
tasks.remove(task);
sort();
}
});
view_holder.name = (TextView) view.findViewById(R.id.text_row_name);
view_holder.category = (View) view.findViewById(R.id.view_row_category);
view_holder.priority = (ImageView) view.findViewById(R.id.image_row_priority);
view_holder.due_date = (TextView) view.findViewById(R.id.text_row_due_date);
view.setTag(view_holder);
view_holder.is_completed.setTag(task);
} else
((ViewHolder) view.getTag()).is_completed.setTag(task);
ViewHolder holder = (ViewHolder) view.getTag();
// Set is completed
boolean is_complete = task.isCompleted();
holder.is_completed.setChecked(is_complete);
// Set name
holder.name.setText(task.getName());
holder.name.setTextColor(is_complete ? Color.GRAY : Color.WHITE);
// Set category
holder.category.setVisibility(View.VISIBLE);
holder.category.setBackgroundColor(data_source.getCategory(task.getCategory()).getColor());
// Set priority
if (is_complete)
holder.priority.setVisibility(View.INVISIBLE);
else {
holder.priority.setVisibility(View.VISIBLE);
switch (task.getPriority()) {
case Task.URGENT:
holder.priority.setImageResource(R.drawable.ic_urgent);
break;
case Task.TRIVIAL:
holder.priority.setImageResource(R.drawable.ic_trivial);
break;
case Task.NORMAL:
default:
holder.priority.setImageResource(R.drawable.ic_normal);
break;
}
}
// Set due date
if (is_complete)
holder.due_date.setVisibility(View.INVISIBLE);
else {
holder.due_date.setVisibility(View.VISIBLE);
holder.due_date.setTextColor(Color.LTGRAY);
if (task.hasDateDue()) {
Calendar current_date = GregorianCalendar.getInstance();
Calendar due_date = task.getDateDueCal();
if (due_date.get(Calendar.YEAR) > current_date.get(Calendar.YEAR)) {
// Due date is in a future year
holder.due_date.setText(DateFormat.format("MMM d'\n'yyyy", due_date));
} else if (due_date.get(Calendar.DAY_OF_YEAR) - current_date.get(Calendar.DAY_OF_YEAR) > 6) {
// Due date is more than a week away
holder.due_date.setText(DateFormat.format("MMM d", due_date));
} else if (due_date.get(Calendar.DAY_OF_YEAR) > current_date.get(Calendar.DAY_OF_YEAR)) {
// Due date is after today
holder.due_date.setText(DateFormat.format("E'\n'h:mmaa", due_date));
} else if (!task.isPastDue()) {
// Due date is today
holder.due_date.setText(DateFormat.format("'Today\n'h:mmaa", due_date));
} else {
// Due date is past
holder.due_date.setText("Past due");
holder.due_date.setTextColor(Color.RED);
}
} else
holder.due_date.setText("");
}
return view;
}
| public View getView(int position, View convert_view, ViewGroup parent) {
View view = convert_view;
Task task = tasks.get(position);
if (view == null) {
LayoutInflater inflater = activity.getLayoutInflater();
view = inflater.inflate(R.layout.row_task, null);
final ViewHolder view_holder = new ViewHolder();
view_holder.is_completed = (CheckBox) view.findViewById(R.id.checkbox_row_complete);
view_holder.is_completed.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Task task = (Task) view_holder.is_completed.getTag();
task.toggleIsCompleted();
task.setDateModified(System.currentTimeMillis());
// Update DB
data_source.updateTask(task);
// Alarm logic: Complete/Uncomplete a task
// * Don't forget to update date modified!
// * Task must be updated in database first
// * Cancel alarm first to be safe
// * Cancel an existing notification
// * If user completed the task:
// * If is repeating:
// * Set repeating alarm to get new due date (possibly uncompletes the task)
// * Notify user that repeated task has been rescheduled
// * Set alarm
// * (Future repeating due date will be handled by the service after alarm rings)
// * Else user uncompleted the task:
// * If has due date and is not past due:
// * Set alarm
TaskAlarm alarm = new TaskAlarm();
alarm.cancelAlarm(activity, task.getID());
alarm.cancelNotification(activity, task.getID());
if (task.isCompleted()) {
toast(R.string.toast_task_completed);
if (task.isRepeating()) {
task = alarm.setRepeatingAlarm(activity, task.getID());
if (!task.isCompleted()) {
alarm.setAlarm(activity, task);
toast(ToastMaker.getRepeatMessage(activity,
R.string.toast_task_repeated,
task.getDateDueCal()));
} else {
toast(ToastMaker.getRepeatMessage(activity,
R.string.toast_task_repeat_delayed,
task.getDateDueCal()));
}
}
} else {
if (task.hasDateDue() && !task.isPastDue())
alarm.setAlarm(activity, task);
}
// If "hide completed tasks" option, then remove the task from the adapter
if (prefs.getBoolean(SettingsActivity.HIDE_COMPLETED, true) && task.isCompleted())
tasks.remove(task);
sort();
}
});
view_holder.name = (TextView) view.findViewById(R.id.text_row_name);
view_holder.category = (View) view.findViewById(R.id.view_row_category);
view_holder.priority = (ImageView) view.findViewById(R.id.image_row_priority);
view_holder.due_date = (TextView) view.findViewById(R.id.text_row_due_date);
view.setTag(view_holder);
view_holder.is_completed.setTag(task);
} else
((ViewHolder) view.getTag()).is_completed.setTag(task);
ViewHolder holder = (ViewHolder) view.getTag();
// Set is completed
boolean is_complete = task.isCompleted();
holder.is_completed.setChecked(is_complete);
// Set name
holder.name.setText(task.getName());
holder.name.setTextColor(is_complete ? Color.GRAY : Color.WHITE);
// Set category
holder.category.setVisibility(View.VISIBLE);
holder.category.setBackgroundColor(data_source.getCategory(task.getCategory()).getColor());
// Set priority
if (is_complete)
holder.priority.setVisibility(View.INVISIBLE);
else {
holder.priority.setVisibility(View.VISIBLE);
switch (task.getPriority()) {
case Task.URGENT:
holder.priority.setImageResource(R.drawable.ic_urgent);
break;
case Task.TRIVIAL:
holder.priority.setImageResource(R.drawable.ic_trivial);
break;
case Task.NORMAL:
default:
holder.priority.setImageResource(R.drawable.ic_normal);
break;
}
}
// Set due date
if (is_complete)
holder.due_date.setVisibility(View.INVISIBLE);
else {
holder.due_date.setVisibility(View.VISIBLE);
holder.due_date.setTextColor(Color.LTGRAY);
if (task.hasDateDue()) {
Calendar current_date = GregorianCalendar.getInstance();
Calendar due_date = task.getDateDueCal();
if (due_date.before(current_date))
{
// Due date is past
holder.due_date.setText("Past due");
holder.due_date.setTextColor(Color.RED);
} else if (due_date.get(Calendar.YEAR) > current_date.get(Calendar.YEAR)) {
// Due date is in a future year
holder.due_date.setText(DateFormat.format("MMM d'\n'yyyy", due_date));
} else if (due_date.get(Calendar.DAY_OF_YEAR) - current_date.get(Calendar.DAY_OF_YEAR) > 6) {
// Due date is more than a week away
holder.due_date.setText(DateFormat.format("MMM d", due_date));
} else if (due_date.get(Calendar.DAY_OF_YEAR) > current_date.get(Calendar.DAY_OF_YEAR)) {
// Due date is after today
holder.due_date.setText(DateFormat.format("E'\n'h:mmaa", due_date));
} else {
// Due date is today
holder.due_date.setText(DateFormat.format("'Today\n'h:mmaa", due_date));
}
} else
holder.due_date.setText("");
}
return view;
}
|
diff --git a/src/com/android/contacts/quickcontact/DataAction.java b/src/com/android/contacts/quickcontact/DataAction.java
index 4593591ab..6d239e686 100644
--- a/src/com/android/contacts/quickcontact/DataAction.java
+++ b/src/com/android/contacts/quickcontact/DataAction.java
@@ -1,275 +1,276 @@
package com.android.contacts.quickcontact;
import com.android.contacts.ContactsUtils;
import com.android.contacts.R;
import com.android.contacts.model.AccountType.DataKind;
import com.android.contacts.util.Constants;
import com.android.contacts.util.PhoneCapabilityTester;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.Im;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.SipAddress;
import android.provider.ContactsContract.CommonDataKinds.Website;
import android.text.TextUtils;
import android.util.Log;
/**
* Description of a specific {@link Data#_ID} item, with style information
* defined by a {@link DataKind}.
*/
public class DataAction implements Action {
private static final String TAG = "DataAction";
private final Context mContext;
private final DataKind mKind;
private final String mMimeType;
private CharSequence mHeader;
private CharSequence mBody;
private Intent mIntent;
private boolean mAlternate;
private Uri mDataUri;
private long mDataId;
private boolean mIsPrimary;
/**
* Create an action from common {@link Data} elements.
*/
public DataAction(Context context, String mimeType, DataKind kind,
long dataId, Cursor cursor) {
mContext = context;
mKind = kind;
mMimeType = mimeType;
// Inflate strings from cursor
mAlternate = Constants.MIME_SMS_ADDRESS.equals(mimeType);
if (mAlternate && mKind.actionAltHeader != null) {
mHeader = mKind.actionAltHeader.inflateUsing(context, cursor);
} else if (mKind.actionHeader != null) {
mHeader = mKind.actionHeader.inflateUsing(context, cursor);
}
if (getAsInt(cursor, Data.IS_SUPER_PRIMARY) != 0) {
mIsPrimary = true;
}
if (mKind.actionBody != null) {
mBody = mKind.actionBody.inflateUsing(context, cursor);
}
mDataId = dataId;
mDataUri = ContentUris.withAppendedId(Data.CONTENT_URI, dataId);
// Handle well-known MIME-types with special care
if (Phone.CONTENT_ITEM_TYPE.equals(mimeType)) {
if (PhoneCapabilityTester.isPhone(mContext)) {
final String number = getAsString(cursor, Phone.NUMBER);
if (!TextUtils.isEmpty(number)) {
final Uri callUri = Uri.fromParts(Constants.SCHEME_TEL, number, null);
mIntent = new Intent(Intent.ACTION_CALL_PRIVILEGED, callUri);
}
}
} else if (SipAddress.CONTENT_ITEM_TYPE.equals(mimeType)) {
if (PhoneCapabilityTester.isSipPhone(mContext)) {
final String address = getAsString(cursor, SipAddress.SIP_ADDRESS);
if (!TextUtils.isEmpty(address)) {
final Uri callUri = Uri.fromParts(Constants.SCHEME_SIP, address, null);
mIntent = new Intent(Intent.ACTION_CALL_PRIVILEGED, callUri);
// Note that this item will get a SIP-specific variant
// of the "call phone" icon, rather than the standard
// app icon for the Phone app (which we show for
// regular phone numbers.) That's because the phone
// app explicitly specifies an android:icon attribute
// for the SIP-related intent-filters in its manifest.
}
}
} else if (Constants.MIME_SMS_ADDRESS.equals(mimeType)) {
if (PhoneCapabilityTester.isSmsIntentRegistered(mContext)) {
final String number = getAsString(cursor, Phone.NUMBER);
if (!TextUtils.isEmpty(number)) {
final Uri smsUri = Uri.fromParts(Constants.SCHEME_SMSTO, number, null);
mIntent = new Intent(Intent.ACTION_SENDTO, smsUri);
}
}
} else if (Email.CONTENT_ITEM_TYPE.equals(mimeType)) {
final String address = getAsString(cursor, Email.DATA);
if (!TextUtils.isEmpty(address)) {
final Uri mailUri = Uri.fromParts(Constants.SCHEME_MAILTO, address, null);
mIntent = new Intent(Intent.ACTION_SENDTO, mailUri);
}
} else if (Website.CONTENT_ITEM_TYPE.equals(mimeType)) {
final String url = getAsString(cursor, Website.URL);
if (!TextUtils.isEmpty(url)) {
mIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
}
} else if (Im.CONTENT_ITEM_TYPE.equals(mimeType)) {
final boolean isEmail = Email.CONTENT_ITEM_TYPE.equals(
getAsString(cursor, Data.MIMETYPE));
if (isEmail || isProtocolValid(cursor)) {
final int protocol = isEmail ? Im.PROTOCOL_GOOGLE_TALK :
getAsInt(cursor, Im.PROTOCOL);
if (isEmail) {
// Use Google Talk string when using Email, and clear data
// Uri so we don't try saving Email as primary.
mHeader = context.getText(R.string.chat_gtalk);
mDataUri = null;
}
String host = getAsString(cursor, Im.CUSTOM_PROTOCOL);
String data = getAsString(cursor,
isEmail ? Email.DATA : Im.DATA);
if (protocol != Im.PROTOCOL_CUSTOM) {
// Try bringing in a well-known host for specific protocols
host = ContactsUtils.lookupProviderNameFromId(protocol);
}
if (!TextUtils.isEmpty(host) && !TextUtils.isEmpty(data)) {
final String authority = host.toLowerCase();
final Uri imUri = new Uri.Builder().scheme(Constants.SCHEME_IMTO).authority(
authority).appendPath(data).build();
mIntent = new Intent(Intent.ACTION_SENDTO, imUri);
}
}
}
if (mIntent == null) {
// Otherwise fall back to default VIEW action
- mIntent = new Intent(Intent.ACTION_VIEW, mDataUri);
+ mIntent = new Intent(Intent.ACTION_VIEW);
+ mIntent.setDataAndType(mDataUri, mimeType);
}
// Always launch as new task, since we're like a launcher
mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
}
/** Read {@link String} from the given {@link Cursor}. */
private static String getAsString(Cursor cursor, String columnName) {
final int index = cursor.getColumnIndex(columnName);
return cursor.getString(index);
}
/** Read {@link Integer} from the given {@link Cursor}. */
private static int getAsInt(Cursor cursor, String columnName) {
final int index = cursor.getColumnIndex(columnName);
return cursor.getInt(index);
}
private boolean isProtocolValid(Cursor cursor) {
final int columnIndex = cursor.getColumnIndex(Im.PROTOCOL);
if (cursor.isNull(columnIndex)) {
return false;
}
try {
Integer.valueOf(cursor.getString(columnIndex));
} catch (NumberFormatException e) {
return false;
}
return true;
}
/** {@inheritDoc} */
@Override
public CharSequence getHeader() {
return mHeader;
}
/** {@inheritDoc} */
@Override
public CharSequence getBody() {
return mBody;
}
/** {@inheritDoc} */
@Override
public String getMimeType() {
return mMimeType;
}
/** {@inheritDoc} */
@Override
public Uri getDataUri() {
return mDataUri;
}
/** {@inheritDoc} */
@Override
public long getDataId() {
return mDataId;
}
/** {@inheritDoc} */
@Override
public Boolean isPrimary() {
return mIsPrimary;
}
/** {@inheritDoc} */
@Override
public Drawable getFallbackIcon() {
// Bail early if no valid resources
final String resPackageName = mKind.resPackageName;
if (resPackageName == null) return null;
final PackageManager pm = mContext.getPackageManager();
if (mAlternate && mKind.iconAltRes != -1) {
return pm.getDrawable(resPackageName, mKind.iconAltRes, null);
} else if (mKind.iconRes != -1) {
return pm.getDrawable(resPackageName, mKind.iconRes, null);
} else {
return null;
}
}
/** {@inheritDoc} */
@Override
public Intent getIntent() {
return mIntent;
}
/** {@inheritDoc} */
@Override
public boolean collapseWith(Action other) {
if (!shouldCollapseWith(other)) {
return false;
}
return true;
}
/** {@inheritDoc} */
@Override
public boolean shouldCollapseWith(Action t) {
if (t == null) {
return false;
}
if (!(t instanceof DataAction)) {
Log.e(TAG, "t must be DataAction");
return false;
}
DataAction other = (DataAction)t;
if (!ContactsUtils.areObjectsEqual(mKind, other.mKind)) {
return false;
}
if (!ContactsUtils.shouldCollapse(mContext, mMimeType, mBody, other.mMimeType,
other.mBody)) {
return false;
}
if (!TextUtils.equals(mMimeType, other.mMimeType)
|| !ContactsUtils.areIntentActionEqual(mIntent, other.mIntent)
) {
return false;
}
return true;
}
}
| true | true | public DataAction(Context context, String mimeType, DataKind kind,
long dataId, Cursor cursor) {
mContext = context;
mKind = kind;
mMimeType = mimeType;
// Inflate strings from cursor
mAlternate = Constants.MIME_SMS_ADDRESS.equals(mimeType);
if (mAlternate && mKind.actionAltHeader != null) {
mHeader = mKind.actionAltHeader.inflateUsing(context, cursor);
} else if (mKind.actionHeader != null) {
mHeader = mKind.actionHeader.inflateUsing(context, cursor);
}
if (getAsInt(cursor, Data.IS_SUPER_PRIMARY) != 0) {
mIsPrimary = true;
}
if (mKind.actionBody != null) {
mBody = mKind.actionBody.inflateUsing(context, cursor);
}
mDataId = dataId;
mDataUri = ContentUris.withAppendedId(Data.CONTENT_URI, dataId);
// Handle well-known MIME-types with special care
if (Phone.CONTENT_ITEM_TYPE.equals(mimeType)) {
if (PhoneCapabilityTester.isPhone(mContext)) {
final String number = getAsString(cursor, Phone.NUMBER);
if (!TextUtils.isEmpty(number)) {
final Uri callUri = Uri.fromParts(Constants.SCHEME_TEL, number, null);
mIntent = new Intent(Intent.ACTION_CALL_PRIVILEGED, callUri);
}
}
} else if (SipAddress.CONTENT_ITEM_TYPE.equals(mimeType)) {
if (PhoneCapabilityTester.isSipPhone(mContext)) {
final String address = getAsString(cursor, SipAddress.SIP_ADDRESS);
if (!TextUtils.isEmpty(address)) {
final Uri callUri = Uri.fromParts(Constants.SCHEME_SIP, address, null);
mIntent = new Intent(Intent.ACTION_CALL_PRIVILEGED, callUri);
// Note that this item will get a SIP-specific variant
// of the "call phone" icon, rather than the standard
// app icon for the Phone app (which we show for
// regular phone numbers.) That's because the phone
// app explicitly specifies an android:icon attribute
// for the SIP-related intent-filters in its manifest.
}
}
} else if (Constants.MIME_SMS_ADDRESS.equals(mimeType)) {
if (PhoneCapabilityTester.isSmsIntentRegistered(mContext)) {
final String number = getAsString(cursor, Phone.NUMBER);
if (!TextUtils.isEmpty(number)) {
final Uri smsUri = Uri.fromParts(Constants.SCHEME_SMSTO, number, null);
mIntent = new Intent(Intent.ACTION_SENDTO, smsUri);
}
}
} else if (Email.CONTENT_ITEM_TYPE.equals(mimeType)) {
final String address = getAsString(cursor, Email.DATA);
if (!TextUtils.isEmpty(address)) {
final Uri mailUri = Uri.fromParts(Constants.SCHEME_MAILTO, address, null);
mIntent = new Intent(Intent.ACTION_SENDTO, mailUri);
}
} else if (Website.CONTENT_ITEM_TYPE.equals(mimeType)) {
final String url = getAsString(cursor, Website.URL);
if (!TextUtils.isEmpty(url)) {
mIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
}
} else if (Im.CONTENT_ITEM_TYPE.equals(mimeType)) {
final boolean isEmail = Email.CONTENT_ITEM_TYPE.equals(
getAsString(cursor, Data.MIMETYPE));
if (isEmail || isProtocolValid(cursor)) {
final int protocol = isEmail ? Im.PROTOCOL_GOOGLE_TALK :
getAsInt(cursor, Im.PROTOCOL);
if (isEmail) {
// Use Google Talk string when using Email, and clear data
// Uri so we don't try saving Email as primary.
mHeader = context.getText(R.string.chat_gtalk);
mDataUri = null;
}
String host = getAsString(cursor, Im.CUSTOM_PROTOCOL);
String data = getAsString(cursor,
isEmail ? Email.DATA : Im.DATA);
if (protocol != Im.PROTOCOL_CUSTOM) {
// Try bringing in a well-known host for specific protocols
host = ContactsUtils.lookupProviderNameFromId(protocol);
}
if (!TextUtils.isEmpty(host) && !TextUtils.isEmpty(data)) {
final String authority = host.toLowerCase();
final Uri imUri = new Uri.Builder().scheme(Constants.SCHEME_IMTO).authority(
authority).appendPath(data).build();
mIntent = new Intent(Intent.ACTION_SENDTO, imUri);
}
}
}
if (mIntent == null) {
// Otherwise fall back to default VIEW action
mIntent = new Intent(Intent.ACTION_VIEW, mDataUri);
}
// Always launch as new task, since we're like a launcher
mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
}
| public DataAction(Context context, String mimeType, DataKind kind,
long dataId, Cursor cursor) {
mContext = context;
mKind = kind;
mMimeType = mimeType;
// Inflate strings from cursor
mAlternate = Constants.MIME_SMS_ADDRESS.equals(mimeType);
if (mAlternate && mKind.actionAltHeader != null) {
mHeader = mKind.actionAltHeader.inflateUsing(context, cursor);
} else if (mKind.actionHeader != null) {
mHeader = mKind.actionHeader.inflateUsing(context, cursor);
}
if (getAsInt(cursor, Data.IS_SUPER_PRIMARY) != 0) {
mIsPrimary = true;
}
if (mKind.actionBody != null) {
mBody = mKind.actionBody.inflateUsing(context, cursor);
}
mDataId = dataId;
mDataUri = ContentUris.withAppendedId(Data.CONTENT_URI, dataId);
// Handle well-known MIME-types with special care
if (Phone.CONTENT_ITEM_TYPE.equals(mimeType)) {
if (PhoneCapabilityTester.isPhone(mContext)) {
final String number = getAsString(cursor, Phone.NUMBER);
if (!TextUtils.isEmpty(number)) {
final Uri callUri = Uri.fromParts(Constants.SCHEME_TEL, number, null);
mIntent = new Intent(Intent.ACTION_CALL_PRIVILEGED, callUri);
}
}
} else if (SipAddress.CONTENT_ITEM_TYPE.equals(mimeType)) {
if (PhoneCapabilityTester.isSipPhone(mContext)) {
final String address = getAsString(cursor, SipAddress.SIP_ADDRESS);
if (!TextUtils.isEmpty(address)) {
final Uri callUri = Uri.fromParts(Constants.SCHEME_SIP, address, null);
mIntent = new Intent(Intent.ACTION_CALL_PRIVILEGED, callUri);
// Note that this item will get a SIP-specific variant
// of the "call phone" icon, rather than the standard
// app icon for the Phone app (which we show for
// regular phone numbers.) That's because the phone
// app explicitly specifies an android:icon attribute
// for the SIP-related intent-filters in its manifest.
}
}
} else if (Constants.MIME_SMS_ADDRESS.equals(mimeType)) {
if (PhoneCapabilityTester.isSmsIntentRegistered(mContext)) {
final String number = getAsString(cursor, Phone.NUMBER);
if (!TextUtils.isEmpty(number)) {
final Uri smsUri = Uri.fromParts(Constants.SCHEME_SMSTO, number, null);
mIntent = new Intent(Intent.ACTION_SENDTO, smsUri);
}
}
} else if (Email.CONTENT_ITEM_TYPE.equals(mimeType)) {
final String address = getAsString(cursor, Email.DATA);
if (!TextUtils.isEmpty(address)) {
final Uri mailUri = Uri.fromParts(Constants.SCHEME_MAILTO, address, null);
mIntent = new Intent(Intent.ACTION_SENDTO, mailUri);
}
} else if (Website.CONTENT_ITEM_TYPE.equals(mimeType)) {
final String url = getAsString(cursor, Website.URL);
if (!TextUtils.isEmpty(url)) {
mIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
}
} else if (Im.CONTENT_ITEM_TYPE.equals(mimeType)) {
final boolean isEmail = Email.CONTENT_ITEM_TYPE.equals(
getAsString(cursor, Data.MIMETYPE));
if (isEmail || isProtocolValid(cursor)) {
final int protocol = isEmail ? Im.PROTOCOL_GOOGLE_TALK :
getAsInt(cursor, Im.PROTOCOL);
if (isEmail) {
// Use Google Talk string when using Email, and clear data
// Uri so we don't try saving Email as primary.
mHeader = context.getText(R.string.chat_gtalk);
mDataUri = null;
}
String host = getAsString(cursor, Im.CUSTOM_PROTOCOL);
String data = getAsString(cursor,
isEmail ? Email.DATA : Im.DATA);
if (protocol != Im.PROTOCOL_CUSTOM) {
// Try bringing in a well-known host for specific protocols
host = ContactsUtils.lookupProviderNameFromId(protocol);
}
if (!TextUtils.isEmpty(host) && !TextUtils.isEmpty(data)) {
final String authority = host.toLowerCase();
final Uri imUri = new Uri.Builder().scheme(Constants.SCHEME_IMTO).authority(
authority).appendPath(data).build();
mIntent = new Intent(Intent.ACTION_SENDTO, imUri);
}
}
}
if (mIntent == null) {
// Otherwise fall back to default VIEW action
mIntent = new Intent(Intent.ACTION_VIEW);
mIntent.setDataAndType(mDataUri, mimeType);
}
// Always launch as new task, since we're like a launcher
mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
}
|
diff --git a/src/tagtime/ping/PingWindow.java b/src/tagtime/ping/PingWindow.java
index 605f999..14621ee 100644
--- a/src/tagtime/ping/PingWindow.java
+++ b/src/tagtime/ping/PingWindow.java
@@ -1,368 +1,368 @@
/*
* Copyright 2011-2012 Joseph Cloutier
*
* This file is part of TagTime.
*
* TagTime 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.
*
* TagTime 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 TagTime. If not, see <http://www.gnu.org/licenses/>.
*/
package tagtime.ping;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowListener;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JRootPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ListSelectionModel;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import tagtime.Main;
import tagtime.TagTime;
import tagtime.settings.SettingType;
import tagtime.util.TagCount;
/**
* The popup window displayed for each ping.
*/
public class PingWindow extends JFrame implements ActionListener {
private static final long serialVersionUID = 1489384636886031541L;
public final TagTime tagTimeInstance;
private static final String SUBMIT = "Submit";
private static final String CANCEL = "Cancel";
private static final int GRID_WIDTH = 3;
private static final Insets ZERO_INSETS = new Insets(0, 0, 0, 0);
final JTextArea inputText;
final JList quickTags;
private PingJob ownerJob;
public PingWindow(TagTime tagTimeInstance, PingJob ownerJob, List<TagCount> tagCounts) {
//create the window
super("Pinging " + tagTimeInstance.username + " - TagTime");
this.tagTimeInstance = tagTimeInstance;
setIconImage(Main.getIconImage());
setLocation(tagTimeInstance.settings.getIntValue(SettingType.WINDOW_X),
tagTimeInstance.settings.getIntValue(SettingType.WINDOW_Y));
//record the job that created this window
this.ownerJob = ownerJob;
//set up the root pane
JRootPane root = getRootPane();
//root.setLayout(new BoxLayout(root, BoxLayout.PAGE_AXIS));
root.setLayout(new GridBagLayout());
root.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
GridBagConstraints constraints = new GridBagConstraints();
//define the cancel and submit buttons
final JButton cancelButton = new JButton(CANCEL);
cancelButton.addActionListener(this);
final JButton submitButton = new JButton(SUBMIT);
submitButton.setActionCommand(SUBMIT);
submitButton.addActionListener(this);
//get the last tags submitted
String ditto = tagTimeInstance.log.getLastTags();
- if(ditto == null || ditto.length() == 0 || ditto.indexOf(' ') == 0) {
+ if(ditto != null && (ditto.length() == 0 || ditto.indexOf(' ') == -1)) {
ditto = null;
}
//convert the given list of TagCount objects to a list of strings
String[] cachedTags = new String[tagCounts.size() + (ditto != null ? 1 : 0)];
for(int i = tagCounts.size() - 1; i >= 0; i--) {
cachedTags[i + (ditto != null ? 1 : 0)] = tagCounts.get(i).getTag();
}
//add the "ditto" tags in front of the list if appropriate
if(ditto != null) {
cachedTags[0] = ditto;
}
Dimension windowSize = new Dimension(
tagTimeInstance.settings.getIntValue(SettingType.WINDOW_WIDTH),
tagTimeInstance.settings.getIntValue(SettingType.WINDOW_HEIGHT));
//set up the list of previously-submitted tags
quickTags = new JList(cachedTags);
quickTags.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
quickTags.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
addSelectedTag();
}
});
//prepare the list to be displayed
JScrollPane listDisplay = new JScrollPane(quickTags);
//set up the input text field
inputText = new JTextArea();
inputText.setRows(2);
inputText.setLineWrap(true);
inputText.setWrapStyleWord(true);
inputText.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void removeUpdate(DocumentEvent e) {
//the submit button should be enabled if and only if text
//has been entered
submitButton.setEnabled(inputText.getText().length() > 0);
}
@Override
public void insertUpdate(DocumentEvent e) {
submitButton.setEnabled(true);
}
@Override
public void changedUpdate(DocumentEvent e) {
//this doesn't seem to be called at any time
System.out.println("changedUpdate()");
}
});
//put the input text in a scrolling area
JScrollPane inputTextScrollPane = new JScrollPane(inputText);
Dimension inputTextDimension = new Dimension(windowSize.width,
2 * getFontMetrics(inputText.getFont()).getHeight());
inputTextScrollPane.setMinimumSize(inputTextDimension);
inputTextScrollPane.setMaximumSize(inputTextDimension);
inputTextScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
//create the heading text
JLabel label = new JLabel("<html>It's tag time! " +
"What are you doing <i>right now</i>?</html>");
/*** place the components ***/
//the label goes across the top
resetConstraints(constraints);
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridwidth = GRID_WIDTH;
constraints.insets = new Insets(0, 0, 8, 0);
root.add(label, constraints);
//the list goes below the label, goes all the way across,
//and is the only one with vertical weight
resetConstraints(constraints);
constraints.fill = GridBagConstraints.BOTH;
constraints.gridy = 1;
constraints.gridwidth = GRID_WIDTH;
constraints.weighty = 1;
constraints.insets = new Insets(0, 0, 3, 0);
root.add(listDisplay, constraints);
//the input text goes below the list
resetConstraints(constraints);
constraints.fill = GridBagConstraints.BOTH;
constraints.gridy = 2;
constraints.gridwidth = GRID_WIDTH;
constraints.insets = new Insets(0, 0, 5, 0);
root.add(inputTextScrollPane, constraints);
//the cancel button goes in the bottom right
resetConstraints(constraints);
constraints.gridx = GRID_WIDTH - 1;
constraints.gridy = 3;
constraints.weightx = 0;
root.add(cancelButton, constraints);
//the submit button goes next to the cancel button
resetConstraints(constraints);
constraints.gridx = GRID_WIDTH - 2;
constraints.gridy = 3;
constraints.weightx = 0;
constraints.insets = new Insets(0, 0, 0, 8);
root.add(submitButton, constraints);
//an invisible box goes next to the submit and cancel buttons,
//to push them to the side
resetConstraints(constraints);
constraints.gridy = 3;
root.add(Box.createRigidArea(new Dimension(3, 3)), constraints);
setSize(windowSize);
//the submit button is selected when the user presses enter, but
//only if it's enabled, and it doesn't get enabled until the user
//enters a tag
submitButton.setEnabled(false);
root.setDefaultButton(submitButton);
//clean up when closed
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
//if the user moves/resizes this window, record the new location/size
addComponentListener(new ComponentAdapter() {
@Override
public void componentMoved(ComponentEvent e) {
PingWindow.this.tagTimeInstance.settings.setValue(SettingType.WINDOW_X, getX());
PingWindow.this.tagTimeInstance.settings.setValue(SettingType.WINDOW_Y, getY());
}
@Override
public void componentResized(ComponentEvent e) {
PingWindow.this.tagTimeInstance.settings.setValue(SettingType.WINDOW_WIDTH,
getWidth());
PingWindow.this.tagTimeInstance.settings.setValue(SettingType.WINDOW_HEIGHT,
getHeight());
}
});
}
private void resetConstraints(GridBagConstraints constraints) {
constraints.gridx = 0;
constraints.gridy = 0;
constraints.gridwidth = 1;
constraints.gridheight = 1;
constraints.weightx = 1;
constraints.weighty = 0;
constraints.fill = GridBagConstraints.NONE;
constraints.anchor = GridBagConstraints.EAST;
constraints.insets = ZERO_INSETS;
}
@Override
public void setVisible(boolean b) {
if(b == isVisible()) {
return;
}
if(b) {
//focus on this window and the input text only if the window
//is allowed to steal focus
if(tagTimeInstance.settings.getBooleanValue(SettingType.STEAL_FOCUS)) {
super.setVisible(true);
inputText.requestFocus();
} else {
//in some environments, setting visible to true causes the
//window to steal focus
setFocusableWindowState(false);
super.setVisible(true);
setFocusableWindowState(true);
}
playSound();
} else {
super.setVisible(false);
}
}
/**
* Plays the sound associated with opening a window.
*/
private void playSound() {
File soundFile = new File(Main.getSoundDirectory() + "/"
+ tagTimeInstance.settings.getStringValue(SettingType.SOUND_TO_PLAY));
if(!soundFile.exists()) {
return;
}
Clip soundClip;
try {
soundClip = AudioSystem.getClip();
AudioInputStream inputStream = AudioSystem.
getAudioInputStream(soundFile);
soundClip.open(inputStream);
} catch(UnsupportedAudioFileException e) {
e.printStackTrace();
return;
} catch(IOException e) {
e.printStackTrace();
return;
} catch(LineUnavailableException e) {
e.printStackTrace();
return;
}
soundClip.loop(0);
}
@Override
public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand();
if(action.equals(SUBMIT)) {
ownerJob.submit(inputText.getText());
dispose();
//flush all saved data upon submission (multiple windows
//may be canceled at once, but there should be a minimum of
//a few seconds between submissions)
tagTimeInstance.settings.flush();
} else if(action.equals(CANCEL)) {
dispose();
}
}
@Override
public void dispose() {
for(WindowListener listener : getWindowListeners()) {
removeWindowListener(listener);
}
//this will do nothing if the data was submitted normally
ownerJob.submitCanceled();
super.dispose();
}
protected void addSelectedTag() {
Object selectedValue = quickTags.getSelectedValue();
String currentText = inputText.getText();
//append the selected tag only if it isn't already there
if(selectedValue != null && !currentText.contains(selectedValue.toString())) {
//add a space if needed
if(currentText.length() > 0
&& currentText.charAt(currentText.length() - 1) != ' ') {
inputText.append(" ");
}
inputText.append(selectedValue.toString());
}
}
}
| true | true | public PingWindow(TagTime tagTimeInstance, PingJob ownerJob, List<TagCount> tagCounts) {
//create the window
super("Pinging " + tagTimeInstance.username + " - TagTime");
this.tagTimeInstance = tagTimeInstance;
setIconImage(Main.getIconImage());
setLocation(tagTimeInstance.settings.getIntValue(SettingType.WINDOW_X),
tagTimeInstance.settings.getIntValue(SettingType.WINDOW_Y));
//record the job that created this window
this.ownerJob = ownerJob;
//set up the root pane
JRootPane root = getRootPane();
//root.setLayout(new BoxLayout(root, BoxLayout.PAGE_AXIS));
root.setLayout(new GridBagLayout());
root.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
GridBagConstraints constraints = new GridBagConstraints();
//define the cancel and submit buttons
final JButton cancelButton = new JButton(CANCEL);
cancelButton.addActionListener(this);
final JButton submitButton = new JButton(SUBMIT);
submitButton.setActionCommand(SUBMIT);
submitButton.addActionListener(this);
//get the last tags submitted
String ditto = tagTimeInstance.log.getLastTags();
if(ditto == null || ditto.length() == 0 || ditto.indexOf(' ') == 0) {
ditto = null;
}
//convert the given list of TagCount objects to a list of strings
String[] cachedTags = new String[tagCounts.size() + (ditto != null ? 1 : 0)];
for(int i = tagCounts.size() - 1; i >= 0; i--) {
cachedTags[i + (ditto != null ? 1 : 0)] = tagCounts.get(i).getTag();
}
//add the "ditto" tags in front of the list if appropriate
if(ditto != null) {
cachedTags[0] = ditto;
}
Dimension windowSize = new Dimension(
tagTimeInstance.settings.getIntValue(SettingType.WINDOW_WIDTH),
tagTimeInstance.settings.getIntValue(SettingType.WINDOW_HEIGHT));
//set up the list of previously-submitted tags
quickTags = new JList(cachedTags);
quickTags.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
quickTags.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
addSelectedTag();
}
});
//prepare the list to be displayed
JScrollPane listDisplay = new JScrollPane(quickTags);
//set up the input text field
inputText = new JTextArea();
inputText.setRows(2);
inputText.setLineWrap(true);
inputText.setWrapStyleWord(true);
inputText.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void removeUpdate(DocumentEvent e) {
//the submit button should be enabled if and only if text
//has been entered
submitButton.setEnabled(inputText.getText().length() > 0);
}
@Override
public void insertUpdate(DocumentEvent e) {
submitButton.setEnabled(true);
}
@Override
public void changedUpdate(DocumentEvent e) {
//this doesn't seem to be called at any time
System.out.println("changedUpdate()");
}
});
//put the input text in a scrolling area
JScrollPane inputTextScrollPane = new JScrollPane(inputText);
Dimension inputTextDimension = new Dimension(windowSize.width,
2 * getFontMetrics(inputText.getFont()).getHeight());
inputTextScrollPane.setMinimumSize(inputTextDimension);
inputTextScrollPane.setMaximumSize(inputTextDimension);
inputTextScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
//create the heading text
JLabel label = new JLabel("<html>It's tag time! " +
"What are you doing <i>right now</i>?</html>");
/*** place the components ***/
//the label goes across the top
resetConstraints(constraints);
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridwidth = GRID_WIDTH;
constraints.insets = new Insets(0, 0, 8, 0);
root.add(label, constraints);
//the list goes below the label, goes all the way across,
//and is the only one with vertical weight
resetConstraints(constraints);
constraints.fill = GridBagConstraints.BOTH;
constraints.gridy = 1;
constraints.gridwidth = GRID_WIDTH;
constraints.weighty = 1;
constraints.insets = new Insets(0, 0, 3, 0);
root.add(listDisplay, constraints);
//the input text goes below the list
resetConstraints(constraints);
constraints.fill = GridBagConstraints.BOTH;
constraints.gridy = 2;
constraints.gridwidth = GRID_WIDTH;
constraints.insets = new Insets(0, 0, 5, 0);
root.add(inputTextScrollPane, constraints);
//the cancel button goes in the bottom right
resetConstraints(constraints);
constraints.gridx = GRID_WIDTH - 1;
constraints.gridy = 3;
constraints.weightx = 0;
root.add(cancelButton, constraints);
//the submit button goes next to the cancel button
resetConstraints(constraints);
constraints.gridx = GRID_WIDTH - 2;
constraints.gridy = 3;
constraints.weightx = 0;
constraints.insets = new Insets(0, 0, 0, 8);
root.add(submitButton, constraints);
//an invisible box goes next to the submit and cancel buttons,
//to push them to the side
resetConstraints(constraints);
constraints.gridy = 3;
root.add(Box.createRigidArea(new Dimension(3, 3)), constraints);
setSize(windowSize);
//the submit button is selected when the user presses enter, but
//only if it's enabled, and it doesn't get enabled until the user
//enters a tag
submitButton.setEnabled(false);
root.setDefaultButton(submitButton);
//clean up when closed
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
//if the user moves/resizes this window, record the new location/size
addComponentListener(new ComponentAdapter() {
@Override
public void componentMoved(ComponentEvent e) {
PingWindow.this.tagTimeInstance.settings.setValue(SettingType.WINDOW_X, getX());
PingWindow.this.tagTimeInstance.settings.setValue(SettingType.WINDOW_Y, getY());
}
@Override
public void componentResized(ComponentEvent e) {
PingWindow.this.tagTimeInstance.settings.setValue(SettingType.WINDOW_WIDTH,
getWidth());
PingWindow.this.tagTimeInstance.settings.setValue(SettingType.WINDOW_HEIGHT,
getHeight());
}
});
}
| public PingWindow(TagTime tagTimeInstance, PingJob ownerJob, List<TagCount> tagCounts) {
//create the window
super("Pinging " + tagTimeInstance.username + " - TagTime");
this.tagTimeInstance = tagTimeInstance;
setIconImage(Main.getIconImage());
setLocation(tagTimeInstance.settings.getIntValue(SettingType.WINDOW_X),
tagTimeInstance.settings.getIntValue(SettingType.WINDOW_Y));
//record the job that created this window
this.ownerJob = ownerJob;
//set up the root pane
JRootPane root = getRootPane();
//root.setLayout(new BoxLayout(root, BoxLayout.PAGE_AXIS));
root.setLayout(new GridBagLayout());
root.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
GridBagConstraints constraints = new GridBagConstraints();
//define the cancel and submit buttons
final JButton cancelButton = new JButton(CANCEL);
cancelButton.addActionListener(this);
final JButton submitButton = new JButton(SUBMIT);
submitButton.setActionCommand(SUBMIT);
submitButton.addActionListener(this);
//get the last tags submitted
String ditto = tagTimeInstance.log.getLastTags();
if(ditto != null && (ditto.length() == 0 || ditto.indexOf(' ') == -1)) {
ditto = null;
}
//convert the given list of TagCount objects to a list of strings
String[] cachedTags = new String[tagCounts.size() + (ditto != null ? 1 : 0)];
for(int i = tagCounts.size() - 1; i >= 0; i--) {
cachedTags[i + (ditto != null ? 1 : 0)] = tagCounts.get(i).getTag();
}
//add the "ditto" tags in front of the list if appropriate
if(ditto != null) {
cachedTags[0] = ditto;
}
Dimension windowSize = new Dimension(
tagTimeInstance.settings.getIntValue(SettingType.WINDOW_WIDTH),
tagTimeInstance.settings.getIntValue(SettingType.WINDOW_HEIGHT));
//set up the list of previously-submitted tags
quickTags = new JList(cachedTags);
quickTags.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
quickTags.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
addSelectedTag();
}
});
//prepare the list to be displayed
JScrollPane listDisplay = new JScrollPane(quickTags);
//set up the input text field
inputText = new JTextArea();
inputText.setRows(2);
inputText.setLineWrap(true);
inputText.setWrapStyleWord(true);
inputText.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void removeUpdate(DocumentEvent e) {
//the submit button should be enabled if and only if text
//has been entered
submitButton.setEnabled(inputText.getText().length() > 0);
}
@Override
public void insertUpdate(DocumentEvent e) {
submitButton.setEnabled(true);
}
@Override
public void changedUpdate(DocumentEvent e) {
//this doesn't seem to be called at any time
System.out.println("changedUpdate()");
}
});
//put the input text in a scrolling area
JScrollPane inputTextScrollPane = new JScrollPane(inputText);
Dimension inputTextDimension = new Dimension(windowSize.width,
2 * getFontMetrics(inputText.getFont()).getHeight());
inputTextScrollPane.setMinimumSize(inputTextDimension);
inputTextScrollPane.setMaximumSize(inputTextDimension);
inputTextScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
//create the heading text
JLabel label = new JLabel("<html>It's tag time! " +
"What are you doing <i>right now</i>?</html>");
/*** place the components ***/
//the label goes across the top
resetConstraints(constraints);
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridwidth = GRID_WIDTH;
constraints.insets = new Insets(0, 0, 8, 0);
root.add(label, constraints);
//the list goes below the label, goes all the way across,
//and is the only one with vertical weight
resetConstraints(constraints);
constraints.fill = GridBagConstraints.BOTH;
constraints.gridy = 1;
constraints.gridwidth = GRID_WIDTH;
constraints.weighty = 1;
constraints.insets = new Insets(0, 0, 3, 0);
root.add(listDisplay, constraints);
//the input text goes below the list
resetConstraints(constraints);
constraints.fill = GridBagConstraints.BOTH;
constraints.gridy = 2;
constraints.gridwidth = GRID_WIDTH;
constraints.insets = new Insets(0, 0, 5, 0);
root.add(inputTextScrollPane, constraints);
//the cancel button goes in the bottom right
resetConstraints(constraints);
constraints.gridx = GRID_WIDTH - 1;
constraints.gridy = 3;
constraints.weightx = 0;
root.add(cancelButton, constraints);
//the submit button goes next to the cancel button
resetConstraints(constraints);
constraints.gridx = GRID_WIDTH - 2;
constraints.gridy = 3;
constraints.weightx = 0;
constraints.insets = new Insets(0, 0, 0, 8);
root.add(submitButton, constraints);
//an invisible box goes next to the submit and cancel buttons,
//to push them to the side
resetConstraints(constraints);
constraints.gridy = 3;
root.add(Box.createRigidArea(new Dimension(3, 3)), constraints);
setSize(windowSize);
//the submit button is selected when the user presses enter, but
//only if it's enabled, and it doesn't get enabled until the user
//enters a tag
submitButton.setEnabled(false);
root.setDefaultButton(submitButton);
//clean up when closed
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
//if the user moves/resizes this window, record the new location/size
addComponentListener(new ComponentAdapter() {
@Override
public void componentMoved(ComponentEvent e) {
PingWindow.this.tagTimeInstance.settings.setValue(SettingType.WINDOW_X, getX());
PingWindow.this.tagTimeInstance.settings.setValue(SettingType.WINDOW_Y, getY());
}
@Override
public void componentResized(ComponentEvent e) {
PingWindow.this.tagTimeInstance.settings.setValue(SettingType.WINDOW_WIDTH,
getWidth());
PingWindow.this.tagTimeInstance.settings.setValue(SettingType.WINDOW_HEIGHT,
getHeight());
}
});
}
|
diff --git a/src/java-server-framework/org/xins/server/API.java b/src/java-server-framework/org/xins/server/API.java
index 332b3e50f..3556fa4ee 100644
--- a/src/java-server-framework/org/xins/server/API.java
+++ b/src/java-server-framework/org/xins/server/API.java
@@ -1,1501 +1,1505 @@
/*
* $Id$
*
* Copyright 2003-2005 Wanadoo Nederland B.V.
* See the COPYRIGHT file for redistribution and use restrictions.
*/
package org.xins.server;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.TimeZone;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import org.xins.common.MandatoryArgumentChecker;
import org.xins.common.Utils;
import org.xins.common.collections.BasicPropertyReader;
import org.xins.common.collections.InvalidPropertyValueException;
import org.xins.common.collections.MissingRequiredPropertyException;
import org.xins.common.collections.PropertyReader;
import org.xins.common.io.FastStringWriter;
import org.xins.common.manageable.BootstrapException;
import org.xins.common.manageable.DeinitializationException;
import org.xins.common.manageable.InitializationException;
import org.xins.common.manageable.Manageable;
import org.xins.common.net.IPAddressUtils;
import org.xins.common.spec.APISpec;
import org.xins.common.spec.InvalidSpecificationException;
import org.xins.common.text.DateConverter;
import org.xins.common.text.ParseException;
import org.xins.common.xml.Element;
import org.xins.common.xml.ElementBuilder;
import org.xins.logdoc.LogdocSerializable;
/**
* Base class for API implementation classes.
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:[email protected]">[email protected]</a>)
* @author Anthony Goubard (<a href="mailto:[email protected]">[email protected]</a>)
* @author Tauseef Rehman (<a href="mailto:[email protected]">[email protected]</a>)
*
* @since XINS 1.0.0
*/
public abstract class API
extends Manageable
implements DefaultResultCodes {
//-------------------------------------------------------------------------
// Class fields
//-------------------------------------------------------------------------
/**
* Fully-qualified name of this class.
*/
private static final String CLASSNAME = API.class.getName();
/**
* Successful empty call result.
*/
private static final FunctionResult SUCCESSFUL_RESULT =
new FunctionResult();
/**
* The runtime (initialization) property that defines the ACL (access
* control list) rules.
*/
private static final String ACL_PROPERTY = "org.xins.server.acl";
/**
* The name of the build property that specifies the version of the API.
*/
private static final String API_VERSION_PROPERTY = "org.xins.api.version";
/**
* The name of the build property that specifies the hostname of the
* machine the package was built on.
*/
private static final String BUILD_HOST_PROPERTY =
"org.xins.api.build.host";
/**
* The name of the build property that specifies the time the package was
* built.
*/
private static final String BUILD_TIME_PROPERTY =
"org.xins.api.build.time";
/**
* The name of the build property that specifies which version of XINS was
* used to build the package.
*/
private static final String BUILD_XINS_VERSION_PROPERTY =
"org.xins.api.build.version";
//-------------------------------------------------------------------------
// Class functions
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
// Constructors
//-------------------------------------------------------------------------
/**
* Constructs a new <code>API</code> object.
*
* @param name
* the name of the API, cannot be <code>null</code> nor can it be an
* empty string.
*
* @throws IllegalArgumentException
* if <code>name == null
* || name.{@link String#length() length()} < 1</code>.
*/
protected API(String name)
throws IllegalArgumentException {
// Check preconditions
MandatoryArgumentChecker.check("name", name);
if (name.length() < 1) {
String message = "name.length() == "
+ name.length();
throw new IllegalArgumentException(message);
}
// Initialize fields
_name = name;
_startupTimestamp = System.currentTimeMillis();
_lastStatisticsReset = _startupTimestamp;
_manageableObjects = new ArrayList(20);
_functionsByName = new HashMap(89);
_functionList = new ArrayList(80);
_resultCodesByName = new HashMap(89);
_resultCodeList = new ArrayList(80);
_emptyProperties = new RuntimeProperties();
_timeZone = TimeZone.getDefault();
_localIPAddress = IPAddressUtils.getLocalHostIPAddress();
}
//-------------------------------------------------------------------------
// Fields
//-------------------------------------------------------------------------
/**
* The engine that owns this <code>API</code> object.
*/
private Engine _engine;
/**
* The name of this API. Cannot be <code>null</code> and cannot be an empty
* string.
*/
private final String _name;
/**
* List of registered manageable objects. See {@link #add(Manageable)}.
*
* <p />This field is initialized to a non-<code>null</code> value by the
* constructor.
*/
private final List _manageableObjects;
/**
* Map that maps function names to <code>Function</code> instances.
* Contains all functions associated with this API.
*
* <p />This field is initialized to a non-<code>null</code> value by the
* constructor.
*/
private final Map _functionsByName;
/**
* List of all functions. This field cannot be <code>null</code>.
*/
private final List _functionList;
/**
* Map that maps result code names to <code>ResultCode</code> instances.
* Contains all result codes associated with this API.
*
* <p />This field is initialized to a non-<code>null</code> value by the
* constructor.
*/
private final Map _resultCodesByName;
/**
* List of all result codes. This field cannot be <code>null</code>.
*/
private final List _resultCodeList;
/**
* The build-time settings. This field is initialized exactly once by
* {@link #bootstrap(PropertyReader)}. It can be <code>null</code> before
* that.
*/
private PropertyReader _buildSettings;
/**
* The {@link RuntimeProperties} containing the method to verify and access
* the defined runtime properties.
*/
private RuntimeProperties _emptyProperties;
/**
* The runtime-time settings. This field is initialized by
* {@link #init(PropertyReader)}. It can be <code>null</code> before that.
*/
private PropertyReader _runtimeSettings;
/**
* Timestamp indicating when this API instance was created.
*/
private final long _startupTimestamp;
/**
* Last time the statistics were reset. Initially the startup timestamp.
*/
private long _lastStatisticsReset;
/**
* Host name for the machine that was used for this build.
*/
private String _buildHost;
/**
* Time stamp that indicates when this build was done.
*/
private String _buildTime;
/**
* XINS version used to build the web application package.
*/
private String _buildVersion;
/**
* The time zone used when generating dates for output.
*/
private final TimeZone _timeZone;
/**
* Version of the API.
*/
private String _apiVersion;
/**
* The access rule list.
*/
private AccessRuleList _accessRuleList;
/**
* The API specification.
*/
private APISpec _apiSpecification;
/**
* The local IP address.
*/
private String _localIPAddress;
//-------------------------------------------------------------------------
// Methods
//-------------------------------------------------------------------------
/**
* Gets the name of this API.
*
* @return
* the name of this API, never <code>null</code> and never an empty
* string.
*/
public final String getName() {
return _name;
}
/**
* Gets the properties specified in the implementation.
*
* @return
* the runtime properties for the API, cannot be <code>null</code>.
*/
public RuntimeProperties getProperties() {
return _emptyProperties;
}
/**
* Gets the timestamp that indicates when this <code>API</code> instance
* was created.
*
* @return
* the time this instance was constructed, as a number of milliseconds
* since midnight January 1, 1970.
*/
public final long getStartupTimestamp() {
return _startupTimestamp;
}
/**
* Returns the applicable time zone.
*
* @return
* the time zone, never <code>null</code>.
*/
public final TimeZone getTimeZone() {
return _timeZone;
}
/**
* Bootstraps this API (wrapper method). This method calls
* {@link #bootstrapImpl2(PropertyReader)}.
*
* @param buildSettings
* the build-time configuration properties, not <code>null</code>.
*
* @throws IllegalStateException
* if this API is currently not bootstraping.
*
* @throws MissingRequiredPropertyException
* if a required property is not given.
*
* @throws InvalidPropertyValueException
* if a property has an invalid value.
*
* @throws BootstrapException
* if the bootstrap fails.
*/
protected final void bootstrapImpl(PropertyReader buildSettings)
throws IllegalStateException,
MissingRequiredPropertyException,
InvalidPropertyValueException,
BootstrapException {
// Check state
Manageable.State state = getState();
if (state != BOOTSTRAPPING) {
String message = "State is "
+ state
+ " instead of "
+ BOOTSTRAPPING
+ '.';
Utils.logProgrammingError(message);
throw new IllegalStateException(message);
}
// Log the time zone
String tzShortName = _timeZone.getDisplayName(false, TimeZone.SHORT);
String tzLongName = _timeZone.getDisplayName(false, TimeZone.LONG);
Log.log_3404(tzShortName, tzLongName);
// Store the build-time settings
_buildSettings = buildSettings;
// Get build-time properties
_apiVersion = _buildSettings.get(API_VERSION_PROPERTY );
_buildHost = _buildSettings.get(BUILD_HOST_PROPERTY );
_buildTime = _buildSettings.get(BUILD_TIME_PROPERTY );
_buildVersion = _buildSettings.get(BUILD_XINS_VERSION_PROPERTY);
Log.log_3212(_buildHost, _buildTime, _buildVersion, _name, _apiVersion);
if (_buildVersion == null) {
// TODO: Log warning: build version not set in build properties
// Check if build version identifies a production release of XINS
} else if (! Library.isProductionRelease(_buildVersion)) {
Log.log_3228(_buildVersion);
}
// Let the subclass perform initialization
// TODO: What if bootstrapImpl2 throws an unexpected exception?
bootstrapImpl2(buildSettings);
// Bootstrap all instances
int count = _manageableObjects.size();
for (int i = 0; i < count; i++) {
Manageable m = (Manageable) _manageableObjects.get(i);
String className = m.getClass().getName();
Log.log_3213(_name, className);
try {
m.bootstrap(_buildSettings);
Log.log_3214(_name, className);
// Missing property
} catch (MissingRequiredPropertyException exception) {
Log.log_3215(_name, className, exception.getPropertyName());
throw exception;
// Invalid property
} catch (InvalidPropertyValueException exception) {
Log.log_3216(_name,
className,
exception.getPropertyName(),
exception.getPropertyValue(),
exception.getReason());
throw exception;
// Catch BootstrapException and any other exceptions not caught
// by previous catch statements
} catch (Throwable exception) {
// Log event
Log.log_3217(exception, _name, className);
// Throw a BootstrapException. If necessary, wrap around the
// caught exception
if (exception instanceof BootstrapException) {
throw (BootstrapException) exception;
} else {
throw new BootstrapException(exception);
}
}
}
// Bootstrap all functions
count = _functionList.size();
for (int i = 0; i < count; i++) {
Function f = (Function) _functionList.get(i);
String functionName = f.getName();
Log.log_3220(_name, functionName);
try {
f.bootstrap(_buildSettings);
Log.log_3221(_name, functionName);
// Missing required property
} catch (MissingRequiredPropertyException exception) {
Log.log_3222(_name, functionName, exception.getPropertyName());
throw exception;
// Invalid property value
} catch (InvalidPropertyValueException exception) {
Log.log_3223(_name,
functionName,
exception.getPropertyName(),
exception.getPropertyValue(),
exception.getReason());
throw exception;
// Catch BootstrapException and any other exceptions not caught
// by previous catch statements
} catch (Throwable exception) {
// Log this event
Log.log_3224(exception, _name, functionName);
// Throw a BootstrapException. If necessary, wrap around the
// caught exception
if (exception instanceof BootstrapException) {
throw (BootstrapException) exception;
} else {
throw new BootstrapException(exception);
}
}
}
}
/**
* Bootstraps this API (implementation method).
*
* <p />The implementation of this method in class {@link API} is empty.
* Custom subclasses can perform any necessary bootstrapping in this
* class.
*
* <p />Note that bootstrapping and initialization are different. Bootstrap
* includes only the one-time configuration of the API based on the
* build-time settings, while the initialization
*
* <p />The {@link #add(Manageable)} may be called from this method,
* and from this method <em>only</em>.
*
* @param buildSettings
* the build-time properties, guaranteed not to be <code>null</code>.
*
* @throws MissingRequiredPropertyException
* if a required property is not given.
*
* @throws InvalidPropertyValueException
* if a property has an invalid value.
*
* @throws BootstrapException
* if the bootstrap fails.
*/
protected void bootstrapImpl2(PropertyReader buildSettings)
throws MissingRequiredPropertyException,
InvalidPropertyValueException,
BootstrapException {
// empty
}
/**
* Stores a reference to the <code>Engine</code> that owns this
* <code>API</code> object.
*
* @param engine
* the {@link Engine} instance, should not be <code>null</code>.
*/
void setEngine(Engine engine) {
_engine = engine;
}
/**
* Triggers re-initialization of this API. This method is meant to be
* called by API function implementations when it is anticipated that the
* API should be re-initialized.
*/
protected final void reinitializeImpl() {
_engine.initAPI();
}
/**
* Initializes this API.
*
* @param runtimeSettings
* the runtime configuration settings, cannot be <code>null</code>.
*
* @throws MissingRequiredPropertyException
* if a required property is missing.
*
* @throws InvalidPropertyValueException
* if a property has an invalid value.
*
* @throws InitializationException
* if the initialization failed for some other reason.
*
* @throws IllegalStateException
* if this API is currently not initializing.
*/
protected final void initImpl(PropertyReader runtimeSettings)
throws MissingRequiredPropertyException,
InvalidPropertyValueException,
InitializationException,
IllegalStateException {
// Check state
Manageable.State state = getState();
if (state != INITIALIZING) {
String message = "State is "
+ state
+ " instead of "
+ INITIALIZING
+ '.';
Utils.logProgrammingError(message);
throw new IllegalStateException(message);
}
Log.log_3405(_name);
// Store runtime settings
_runtimeSettings = runtimeSettings;
// Initialize ACL subsystem
//
// TODO: Investigate whether we can take the configuration file reload
// interval from somewhere (ConfigManager? Engine?).
String acl = runtimeSettings.get(ACL_PROPERTY);
String propName = APIServlet.CONFIG_RELOAD_INTERVAL_PROPERTY;
String propValue = runtimeSettings.get(propName);
int interval = APIServlet.DEFAULT_CONFIG_RELOAD_INTERVAL;
if (propValue != null && propValue.trim().length() > 0) {
- // TODO: Can this ever fail? Check and test.
- interval = Integer.parseInt(propValue);
+ try {
+ interval = Integer.parseInt(propValue);
+ } catch (NumberFormatException e) {
+ throw new InvalidPropertyValueException(propName, propValue,
+ "Invalid interval. Must be a 32-bit integer number.");
+ }
if (interval < 0) {
throw new InvalidPropertyValueException(propName, propValue,
"Negative interval not allowed. Use 0 to disable reloading.");
}
}
// Dispose the old access control list
if (_accessRuleList != null) {
_accessRuleList.dispose();
}
// New access control list is empty
if (acl == null || acl.trim().length() < 1) {
_accessRuleList = AccessRuleList.EMPTY;
Log.log_3426(ACL_PROPERTY);
// New access control list is non-empty
} else {
// Parse the new ACL
try {
_accessRuleList =
AccessRuleList.parseAccessRuleList(acl, interval);
int ruleCount = _accessRuleList.getRuleCount();
Log.log_3427(ruleCount);
// Parsing failed
} catch (ParseException exception) {
String exceptionMessage = exception.getMessage();
if (exceptionMessage != null) {
exceptionMessage = exceptionMessage.trim();
if (exceptionMessage.length() < 1) {
exceptionMessage = null;
}
}
Log.log_3428(ACL_PROPERTY, acl, exceptionMessage);
throw new InvalidPropertyValueException(ACL_PROPERTY,
acl,
exceptionMessage);
}
}
// Initialize the RuntimeProperties object.
getProperties().init(runtimeSettings);
// Initialize all instances
int count = _manageableObjects.size();
for (int i = 0; i < count; i++) {
Manageable m = (Manageable) _manageableObjects.get(i);
String className = m.getClass().getName();
Log.log_3416(_name, className);
try {
m.init(runtimeSettings);
Log.log_3417(_name, className);
// Missing required property
} catch (MissingRequiredPropertyException exception) {
Log.log_3418(_name, className, exception.getPropertyName());
throw exception;
// Invalid property value
} catch (InvalidPropertyValueException exception) {
Log.log_3419(_name,
className,
exception.getPropertyName(),
exception.getPropertyValue(),
exception.getReason());
throw exception;
// Catch InitializationException and any other exceptions not caught
// by previous catch statements
} catch (Throwable exception) {
// Log this event
Log.log_3420(exception, _name, className);
if (exception instanceof InitializationException) {
throw (InitializationException) exception;
} else {
throw new InitializationException(exception);
}
}
}
// Initialize all functions
count = _functionList.size();
for (int i = 0; i < count; i++) {
Function f = (Function) _functionList.get(i);
String functionName = f.getName();
Log.log_3421(_name, functionName);
try {
f.init(runtimeSettings);
Log.log_3422(_name, functionName);
// Missing required property
} catch (MissingRequiredPropertyException exception) {
Log.log_3423(_name, functionName, exception.getPropertyName());
throw exception;
// Invalid property value
} catch (InvalidPropertyValueException exception) {
Log.log_3424(_name,
functionName,
exception.getPropertyName(),
exception.getPropertyValue(),
exception.getReason());
throw exception;
// Catch InitializationException and any other exceptions not caught
// by previous catch statements
} catch (Throwable exception) {
// Log this event
Log.log_3425(exception, _name, functionName);
// Throw an InitializationException. If necessary, wrap around the
// caught exception
if (exception instanceof InitializationException) {
throw (InitializationException) exception;
} else {
throw new InitializationException(exception);
}
}
}
// TODO: Call initImpl2(PropertyReader) ?
Log.log_3406(_name);
}
/**
* Adds the specified manageable object. It will not immediately be
* bootstrapped and initialized.
*
* @param m
* the manageable object to add, not <code>null</code>.
*
* @throws IllegalStateException
* if this API is currently not bootstrapping.
*
* @throws IllegalArgumentException
* if <code>instance == null</code>.
*/
protected final void add(Manageable m)
throws IllegalStateException,
IllegalArgumentException {
// Check state
Manageable.State state = getState();
if (state != BOOTSTRAPPING) {
String message = "State is "
+ state
+ " instead of "
+ BOOTSTRAPPING
+ '.';
Utils.logProgrammingError(message);
throw new IllegalStateException(message);
}
// Check preconditions
MandatoryArgumentChecker.check("m", m);
String className = m.getClass().getName();
Log.log_3218(_name, className);
// Store the manageable object in the list
_manageableObjects.add(m);
}
/**
* Performs shutdown of this XINS API. This method will never throw any
* exception.
*/
protected final void deinitImpl() {
// Deinitialize instances
int count = _manageableObjects.size();
for (int i = 0; i < count; i++) {
Manageable m = (Manageable) _manageableObjects.get(i);
String className = m.getClass().getName();
Log.log_3603(_name, className);
try {
m.deinit();
Log.log_3604(_name, className);
} catch (DeinitializationException exception) {
Log.log_3605(_name, className, exception.getMessage());
} catch (Throwable exception) {
Log.log_3606(exception, _name, className);
}
}
_manageableObjects.clear();
// Deinitialize functions
count = _functionList.size();
for (int i = 0; i < count; i++) {
Function f = (Function) _functionList.get(i);
String functionName = f.getName();
Log.log_3607(_name, functionName);
try {
f.deinit();
Log.log_3608(_name, functionName);
} catch (DeinitializationException exception) {
Log.log_3609(_name, functionName, exception.getMessage());
} catch (Throwable exception) {
Log.log_3610(exception, _name, functionName);
}
}
}
/**
* Callback method invoked when a function is constructed.
*
* @param function
* the function that is added, not <code>null</code>.
*
* @throws NullPointerException
* if <code>function == null</code>.
*
* @throws IllegalStateException
* if this API state is incorrect.
*/
final void functionAdded(Function function)
throws NullPointerException, IllegalStateException {
// Check state
Manageable.State state = getState();
if (state != UNUSABLE) {
String message = "State is "
+ state
+ " instead of "
+ UNUSABLE
+ '.';
Utils.logProgrammingError(message);
throw new IllegalStateException(message);
}
_functionsByName.put(function.getName(), function);
_functionList.add(function);
}
/**
* Callback method invoked when a result code is constructed.
*
* @param resultCode
* the result code that is added, not <code>null</code>.
*
* @throws NullPointerException
* if <code>resultCode == null</code>.
*/
final void resultCodeAdded(ResultCode resultCode)
throws NullPointerException {
_resultCodesByName.put(resultCode.getName(), resultCode);
_resultCodeList.add(resultCode);
}
/**
* Returns the function with the specified name.
*
* @param name
* the name of the function, will not be checked if it is
* <code>null</code>.
*
* @return
* the function with the specified name, or <code>null</code> if there
* is no match.
*/
final Function getFunction(String name) {
return (Function) _functionsByName.get(name);
}
/**
* Get the specification of the API.
*
* @return
* the {@link APISpec} specification object, never <code>null</code>.
*
* @throws InvalidSpecificationException
* if the specification cannot be found or is invalid.
*
* @since XINS 1.3.0
*/
public final APISpec getAPISpecification()
throws InvalidSpecificationException {
if (_apiSpecification == null) {
String baseURL = null;
ServletConfig config = _engine.getServletConfig();
ServletContext context = config.getServletContext();
try {
baseURL = context.getResource("specs/").toExternalForm();
} catch (MalformedURLException muex) {
// Let the base URL be null
}
_apiSpecification = new APISpec(getClass(), baseURL);
}
return _apiSpecification;
}
/**
* Determines if the specified IP address is allowed to access the
* specified function, returning a <code>boolean</code> value.
*
* <p>This method finds the first matching rule and then returns the
* <em>allow</em> property of that rule (see
* {@link AccessRule#isAllowRule()}). If there is no matching rule, then
* <code>false</code> is returned.
*
* @param ip
* the IP address, cannot be <code>null</code>.
*
* @param functionName
* the name of the function, cannot be <code>null</code>.
*
* @return
* <code>true</code> if the request is allowed, <code>false</code> if
* the request is denied.
*
* @throws IllegalArgumentException
* if <code>ip == null || functionName == null</code>.
*
* @throws ParseException
* if the specified IP address is malformed.
*/
public boolean allow(String ip, String functionName)
throws IllegalArgumentException {
// If no property is defined only localhost is allowed
if (_accessRuleList == AccessRuleList.EMPTY &&
(ip.equals("127.0.0.1") || ip.equals(_localIPAddress))) {
return true;
}
// Match an access rule
Boolean allowed;
try {
allowed = _accessRuleList.isAllowed(ip, functionName);
// If the IP address cannot be parsed there is a programming error
// somewhere
} catch (ParseException exception) {
String thisMethod = "allow(java.lang.String,java.lang.String)";
String subjectClass = _accessRuleList.getClass().getName();
String subjectMethod = "allow(java.lang.String,java.lang.String)";
String detail = "Malformed IP address: \"" + ip + "\".";
throw Utils.logProgrammingError(CLASSNAME, thisMethod,
subjectClass, subjectMethod,
detail, exception);
}
// If there is a match, return the allow-indication
if (allowed != null) {
return allowed.booleanValue();
}
// No matching access rule match, do not allow
Log.log_3553(ip, functionName);
return false;
}
/**
* Forwards a call to a function. The call will actually be handled by
* {@link Function#handleCall(long,FunctionRequest,String)}.
*
* @param start
* the start time of the request, in milliseconds since midnight January
* 1, 1970.
*
* @param functionRequest
* the function request, never <code>null</code>.
*
* @param ip
* the IP address of the requester, never <code>null</code>.
*
* @return
* the result of the call, never <code>null</code>.
*
* @throws IllegalStateException
* if this object is currently not initialized.
*
* @throws NullPointerException
* if <code>functionRequest == null</code>.
*
* @throws NoSuchFunctionException
* if there is no matching function for the specified request.
*
* @throws AccessDeniedException
* if access is denied for the specified combination of IP address and
* function name.
*/
final FunctionResult handleCall(long start,
FunctionRequest functionRequest,
String ip)
throws IllegalStateException,
NullPointerException,
NoSuchFunctionException,
AccessDeniedException {
final String THIS_METHOD = "handleCall(long,"
+ FunctionRequest.class.getName()
+ ",java.lang.String)";
// Check state first
assertUsable();
// Determine the function name
String functionName = functionRequest.getFunctionName();
// Check the access rule list
boolean allow = allow(ip, functionName);
if (! allow) {
throw new AccessDeniedException(ip, functionName);
}
// Short-circuit if we are shutting down
if (getState().equals(DEINITIALIZING)) {
Log.log_3611(_name, functionName);
return new FunctionResult("_InternalError");
}
// Handle meta-functions
if (functionName.charAt(0) == '_') {
try {
return callMetaFunction(start, functionName, functionRequest, ip);
} catch (NoSuchFunctionException exception) {
throw exception;
} catch (Throwable exception) {
final int CALL_ID = 0; // TODO
return handleFunctionException(start, functionRequest, ip,
CALL_ID, exception);
}
}
// Handle normal functions
Function function = getFunction(functionName);
if (function == null) {
throw new NoSuchFunctionException(functionName);
}
return function.handleCall(start, functionRequest, ip);
}
/**
* Handles a call to a meta-function.
*
* @param start
* the start time of the request, in milliseconds since midnight January
* 1, 1970.
*
* @param functionName
* the name of the meta-function, cannot be <code>null</code> and must
* start with the underscore character <code>'_'</code>.
*
* @param functionRequest
* the function request, never <code>null</code>.
*
* @param ip
* the IP address of the requester, never <code>null</code>.
*
* @return
* the result of the function call, never <code>null</code>.
*
* @throws NoSuchFunctionException
* if there is no meta-function by the specified name.
*/
private FunctionResult callMetaFunction(long start,
String functionName,
FunctionRequest functionRequest,
String ip)
throws NoSuchFunctionException {
// Check preconditions
MandatoryArgumentChecker.check("functionName", functionName);
if (functionName.length() < 1) {
throw new IllegalArgumentException("functionName.length() < 1");
} else if (functionName.charAt(0) != '_') {
throw new IllegalArgumentException("Function name \"" +
functionName +
"\" is not a meta-function.");
}
FunctionResult result;
// No Operation
if ("_NoOp".equals(functionName)) {
result = SUCCESSFUL_RESULT;
// Retrieve function list
} else if ("_GetFunctionList".equals(functionName)) {
result = doGetFunctionList();
// Get function call quantity and performance statistics
} else if ("_GetStatistics".equals(functionName)) {
// Determine value of 'detailed' argument
String detailedArg = functionRequest.getParameters().get("detailed");
boolean detailed = "true".equals(detailedArg);
// Get the statistics
result = doGetStatistics(detailed);
// Determine value of 'reset' argument
String resetArg = functionRequest.getParameters().get("reset");
boolean reset = "true".equals(resetArg);
if (reset) {
doResetStatistics();
}
// Get version information
} else if ("_GetVersion".equals(functionName)) {
result = doGetVersion();
// Check links to underlying systems
} else if ("_CheckLinks".equals(functionName)) {
result = doCheckLinks();
// Retrieve configuration settings
} else if ("_GetSettings".equals(functionName)) {
result = doGetSettings();
// Disable a function
} else if ("_DisableFunction".equals(functionName)) {
String disabledFunction = functionRequest.getParameters().get("functionName");
result = doDisableFunction(disabledFunction);
// Enable a function
} else if ("_EnableFunction".equals(functionName)) {
String enabledFunction = functionRequest.getParameters().get("functionName");
result = doEnableFunction(enabledFunction);
// Reset the statistics
} else if ("_ResetStatistics".equals(functionName)) {
result = doResetStatistics();
// Reload the runtime properties
} else if ("_ReloadProperties".equals(functionName)) {
_engine.getConfigManager().reloadPropertiesIfChanged();
result = SUCCESSFUL_RESULT;
// Meta-function does not exist
} else {
throw new NoSuchFunctionException(functionName);
}
// Determine duration
long duration = System.currentTimeMillis() - start;
// Determine error code, fallback is a zero character
String code = result.getErrorCode();
if (code == null || code.length() < 1) {
code = "0";
}
// Prepare for transaction logging
LogdocSerializable serStart = new FormattedDate(start);
LogdocSerializable inParams =
new FormattedParameters(functionRequest.getParameters());
LogdocSerializable outParams =
new FormattedParameters(result.getParameters());
// Log transaction before returning the result
Log.log_3540(serStart, ip, functionName, duration, code, inParams,
outParams);
Log.log_3541(serStart, ip, functionName, duration, code);
return result;
}
/**
* Handles an exception caught while a function was executed.
*
* @param start
* the start time of the call, as milliseconds since midnight January 1,
* 1970.
*
* @param functionRequest
* the request, never <code>null</code>.
*
* @param ip
* the IP address of the requester, never <code>null</code>.
*
* @param callID
* the call identifier, never <code>null</code>.
*
* @param exception
* the exception caught, never <code>null</code>.
*
* @return
* the call result, never <code>null</code>.
*/
FunctionResult handleFunctionException(long start,
FunctionRequest functionRequest,
String ip,
int callID,
Throwable exception) {
Log.log_3500(exception, _name, callID);
// Create a set of parameters for the result
BasicPropertyReader resultParams = new BasicPropertyReader();
// Add the exception class
String exceptionClass = exception.getClass().getName();
resultParams.set("_exception.class", exceptionClass);
// Add the exception message, if any
String exceptionMessage = exception.getMessage();
if (exceptionMessage != null) {
exceptionMessage = exceptionMessage.trim();
if (exceptionMessage.length() > 0) {
resultParams.set("_exception.message", exceptionMessage);
}
}
// Add the stack trace, if any
FastStringWriter stWriter = new FastStringWriter(360);
PrintWriter printWriter = new PrintWriter(stWriter);
exception.printStackTrace(printWriter);
String stackTrace = stWriter.toString();
if (stackTrace != null) {
stackTrace = stackTrace.trim();
if (stackTrace.length() > 0) {
resultParams.set("_exception.stacktrace", stackTrace);
}
}
return new FunctionResult("_InternalError", resultParams);
}
/**
* Returns a list of all functions in this API. Per function the name and
* the version are returned.
*
* @return
* the call result, never <code>null</code>.
*/
private final FunctionResult doGetFunctionList() {
// Initialize a builder
FunctionResult builder = new FunctionResult();
// Loop over all functions
int count = _functionList.size();
for (int i = 0; i < count; i++) {
// Get some details about the function
Function function = (Function) _functionList.get(i);
String name = function.getName();
String version = function.getVersion();
String enabled = function.isEnabled()
? "true"
: "false";
// Add an element describing the function
ElementBuilder functionElem = new ElementBuilder("function");
functionElem.setAttribute("name", name );
functionElem.setAttribute("version", version);
functionElem.setAttribute("enabled", enabled);
builder.add(functionElem.createElement());
}
return builder;
}
/**
* Converts the specified timestamp to a date string.
*
* @param millis
* the timestamp, as a number of milliseconds since the Epoch.
*
* @return
* the date string, never <code>null</code>.
*/
private final String toDateString(long millis) {
return DateConverter.toDateString(_timeZone, millis);
}
/**
* Returns the call statistics for all functions in this API.
*
* @param detailed
* If <code>true</code>, the unsuccessful result will be returned sorted
* per error code. Otherwise the unsuccessful result won't be displayed
* by error code.
*
* @return
* the call result, never <code>null</code>.
*/
private final FunctionResult doGetStatistics(boolean detailed) {
// Initialize a builder
FunctionResult builder = new FunctionResult();
builder.param("startup", toDateString(_startupTimestamp));
builder.param("lastReset", toDateString(_lastStatisticsReset));
builder.param("now", toDateString(System.currentTimeMillis()));
// Currently available processors
Runtime rt = Runtime.getRuntime();
try {
builder.param("availableProcessors",
String.valueOf(rt.availableProcessors()));
} catch (NoSuchMethodError error) {
// NOTE: Runtime.availableProcessors() is not available in Java 1.3
}
// Heap memory statistics
ElementBuilder heap = new ElementBuilder("heap");
long free = rt.freeMemory();
long total = rt.totalMemory();
heap.setAttribute("used", String.valueOf(total - free));
heap.setAttribute("free", String.valueOf(free));
heap.setAttribute("total", String.valueOf(total));
try {
heap.setAttribute("max", String.valueOf(rt.maxMemory()));
} catch (NoSuchMethodError error) {
// NOTE: Runtime.maxMemory() is not available in Java 1.3
}
builder.add(heap.createElement());
// Function-specific statistics
int count = _functionList.size();
for (int i = 0; i < count; i++) {
Function function = (Function) _functionList.get(i);
FunctionStatistics stats = function.getStatistics();
ElementBuilder functionElem = new ElementBuilder("function");
functionElem.setAttribute("name", function.getName());
// Successful
Element successful = stats.getSuccessfulElement();
functionElem.addChild(successful);
// Unsuccessful
Element[] unsuccessful = stats.getUnsuccessfulElement(detailed);
for(int j = 0; j < unsuccessful.length; j++) {
functionElem.addChild(unsuccessful[j]);
}
builder.add(functionElem.createElement());
}
return builder;
}
/**
* Returns the XINS version.
*
* @return
* the call result, never <code>null</code>.
*/
private final FunctionResult doGetVersion() {
FunctionResult builder = new FunctionResult();
builder.param("java.version", System.getProperty("java.version"));
builder.param("xmlenc.version", org.znerd.xmlenc.Library.getVersion());
builder.param("xins.version", Library.getVersion());
builder.param("api.version", _apiVersion);
return builder;
}
/**
* Returns the links in linked system components. It uses the
* {@link CheckLinks} to connect to each link and builds a
* {@link FunctionResult} which will have the total link count and total
* link failures.
*
* @return
* the call result, never <code>null</code>.
*/
private final FunctionResult doCheckLinks() {
return CheckLinks.checkLinks(getProperties().descriptors());
}
/**
* Returns the settings.
*
* @return
* the call result, never <code>null</code>.
*/
private final FunctionResult doGetSettings() {
final String THIS_METHOD = "doGetSettings()";
FunctionResult builder = new FunctionResult();
// Build settings
Iterator names = _buildSettings.getNames();
ElementBuilder build = new ElementBuilder("build");
while (names.hasNext()) {
String key = (String) names.next();
String value = _buildSettings.get(key);
ElementBuilder property = new ElementBuilder("property");
property.setAttribute("name", key);
property.setText(value);
build.addChild(property.createElement());
}
builder.add(build.createElement());
// Runtime settings
names = _runtimeSettings.getNames();
ElementBuilder runtime = new ElementBuilder("runtime");
while (names.hasNext()) {
String key = (String) names.next();
String value = _runtimeSettings.get(key);
ElementBuilder property = new ElementBuilder("property");
property.setAttribute("name", key);
property.setText(value);
runtime.addChild(property.createElement());
}
builder.add(runtime.createElement());
// System properties
Properties sysProps;
try {
sysProps = System.getProperties();
} catch (SecurityException ex) {
final String SUBJECT_CLASS = "java.lang.System";
final String SUBJECT_METHOD = "getProperties()";
Utils.logProgrammingError(CLASSNAME, THIS_METHOD,
SUBJECT_CLASS, SUBJECT_METHOD,
null, ex);
sysProps = new Properties();
}
Enumeration e = sysProps.propertyNames();
ElementBuilder system = new ElementBuilder("system");
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
String value = sysProps.getProperty(key);
if ( key != null && key.trim().length() > 0
&& value != null && value.trim().length() > 0) {
ElementBuilder property = new ElementBuilder("property");
property.setAttribute("name", key);
property.setText(value);
system.addChild(property.createElement());
}
}
builder.add(system.createElement());
return builder;
}
/**
* Enables a function.
*
* @param functionName
* the name of the function to disable, can be <code>null</code>.
*
* @return
* the call result, never <code>null</code>.
*/
private final FunctionResult doEnableFunction(String functionName) {
// Get the name of the function to enable
if (functionName == null || functionName.length() < 1) {
InvalidRequestResult invalidRequest = new InvalidRequestResult();
invalidRequest.addMissingParameter("functionName");
return invalidRequest;
}
// Get the Function object
Function function = getFunction(functionName);
if (function == null) {
return new InvalidRequestResult();
}
// Enable or disable the function
function.setEnabled(true);
return SUCCESSFUL_RESULT;
}
/**
* Disables a function.
*
* @param functionName
* the name of the function to disable, can be <code>null</code>.
*
* @return
* the call result, never <code>null</code>.
*/
private final FunctionResult doDisableFunction(String functionName) {
// Get the name of the function to disable
if (functionName == null || functionName.length() < 1) {
InvalidRequestResult invalidRequest = new InvalidRequestResult();
invalidRequest.addMissingParameter("functionName");
return invalidRequest;
}
// Get the Function object
Function function = getFunction(functionName);
if (function == null) {
return new InvalidRequestResult();
}
// Enable or disable the function
function.setEnabled(false);
return SUCCESSFUL_RESULT;
}
/**
* Resets the statistics.
*
* @return
* the call result, never <code>null</code>.
*/
private final FunctionResult doResetStatistics() {
// Remember when we last reset the statistics
_lastStatisticsReset = System.currentTimeMillis();
// Function-specific statistics
int count = _functionList.size();
for (int i = 0; i < count; i++) {
Function function = (Function) _functionList.get(i);
function.getStatistics().resetStatistics();
}
return SUCCESSFUL_RESULT;
}
}
| true | true | protected final void initImpl(PropertyReader runtimeSettings)
throws MissingRequiredPropertyException,
InvalidPropertyValueException,
InitializationException,
IllegalStateException {
// Check state
Manageable.State state = getState();
if (state != INITIALIZING) {
String message = "State is "
+ state
+ " instead of "
+ INITIALIZING
+ '.';
Utils.logProgrammingError(message);
throw new IllegalStateException(message);
}
Log.log_3405(_name);
// Store runtime settings
_runtimeSettings = runtimeSettings;
// Initialize ACL subsystem
//
// TODO: Investigate whether we can take the configuration file reload
// interval from somewhere (ConfigManager? Engine?).
String acl = runtimeSettings.get(ACL_PROPERTY);
String propName = APIServlet.CONFIG_RELOAD_INTERVAL_PROPERTY;
String propValue = runtimeSettings.get(propName);
int interval = APIServlet.DEFAULT_CONFIG_RELOAD_INTERVAL;
if (propValue != null && propValue.trim().length() > 0) {
// TODO: Can this ever fail? Check and test.
interval = Integer.parseInt(propValue);
if (interval < 0) {
throw new InvalidPropertyValueException(propName, propValue,
"Negative interval not allowed. Use 0 to disable reloading.");
}
}
// Dispose the old access control list
if (_accessRuleList != null) {
_accessRuleList.dispose();
}
// New access control list is empty
if (acl == null || acl.trim().length() < 1) {
_accessRuleList = AccessRuleList.EMPTY;
Log.log_3426(ACL_PROPERTY);
// New access control list is non-empty
} else {
// Parse the new ACL
try {
_accessRuleList =
AccessRuleList.parseAccessRuleList(acl, interval);
int ruleCount = _accessRuleList.getRuleCount();
Log.log_3427(ruleCount);
// Parsing failed
} catch (ParseException exception) {
String exceptionMessage = exception.getMessage();
if (exceptionMessage != null) {
exceptionMessage = exceptionMessage.trim();
if (exceptionMessage.length() < 1) {
exceptionMessage = null;
}
}
Log.log_3428(ACL_PROPERTY, acl, exceptionMessage);
throw new InvalidPropertyValueException(ACL_PROPERTY,
acl,
exceptionMessage);
}
}
// Initialize the RuntimeProperties object.
getProperties().init(runtimeSettings);
// Initialize all instances
int count = _manageableObjects.size();
for (int i = 0; i < count; i++) {
Manageable m = (Manageable) _manageableObjects.get(i);
String className = m.getClass().getName();
Log.log_3416(_name, className);
try {
m.init(runtimeSettings);
Log.log_3417(_name, className);
// Missing required property
} catch (MissingRequiredPropertyException exception) {
Log.log_3418(_name, className, exception.getPropertyName());
throw exception;
// Invalid property value
} catch (InvalidPropertyValueException exception) {
Log.log_3419(_name,
className,
exception.getPropertyName(),
exception.getPropertyValue(),
exception.getReason());
throw exception;
// Catch InitializationException and any other exceptions not caught
// by previous catch statements
} catch (Throwable exception) {
// Log this event
Log.log_3420(exception, _name, className);
if (exception instanceof InitializationException) {
throw (InitializationException) exception;
} else {
throw new InitializationException(exception);
}
}
}
// Initialize all functions
count = _functionList.size();
for (int i = 0; i < count; i++) {
Function f = (Function) _functionList.get(i);
String functionName = f.getName();
Log.log_3421(_name, functionName);
try {
f.init(runtimeSettings);
Log.log_3422(_name, functionName);
// Missing required property
} catch (MissingRequiredPropertyException exception) {
Log.log_3423(_name, functionName, exception.getPropertyName());
throw exception;
// Invalid property value
} catch (InvalidPropertyValueException exception) {
Log.log_3424(_name,
functionName,
exception.getPropertyName(),
exception.getPropertyValue(),
exception.getReason());
throw exception;
// Catch InitializationException and any other exceptions not caught
// by previous catch statements
} catch (Throwable exception) {
// Log this event
Log.log_3425(exception, _name, functionName);
// Throw an InitializationException. If necessary, wrap around the
// caught exception
if (exception instanceof InitializationException) {
throw (InitializationException) exception;
} else {
throw new InitializationException(exception);
}
}
}
// TODO: Call initImpl2(PropertyReader) ?
Log.log_3406(_name);
}
| protected final void initImpl(PropertyReader runtimeSettings)
throws MissingRequiredPropertyException,
InvalidPropertyValueException,
InitializationException,
IllegalStateException {
// Check state
Manageable.State state = getState();
if (state != INITIALIZING) {
String message = "State is "
+ state
+ " instead of "
+ INITIALIZING
+ '.';
Utils.logProgrammingError(message);
throw new IllegalStateException(message);
}
Log.log_3405(_name);
// Store runtime settings
_runtimeSettings = runtimeSettings;
// Initialize ACL subsystem
//
// TODO: Investigate whether we can take the configuration file reload
// interval from somewhere (ConfigManager? Engine?).
String acl = runtimeSettings.get(ACL_PROPERTY);
String propName = APIServlet.CONFIG_RELOAD_INTERVAL_PROPERTY;
String propValue = runtimeSettings.get(propName);
int interval = APIServlet.DEFAULT_CONFIG_RELOAD_INTERVAL;
if (propValue != null && propValue.trim().length() > 0) {
try {
interval = Integer.parseInt(propValue);
} catch (NumberFormatException e) {
throw new InvalidPropertyValueException(propName, propValue,
"Invalid interval. Must be a 32-bit integer number.");
}
if (interval < 0) {
throw new InvalidPropertyValueException(propName, propValue,
"Negative interval not allowed. Use 0 to disable reloading.");
}
}
// Dispose the old access control list
if (_accessRuleList != null) {
_accessRuleList.dispose();
}
// New access control list is empty
if (acl == null || acl.trim().length() < 1) {
_accessRuleList = AccessRuleList.EMPTY;
Log.log_3426(ACL_PROPERTY);
// New access control list is non-empty
} else {
// Parse the new ACL
try {
_accessRuleList =
AccessRuleList.parseAccessRuleList(acl, interval);
int ruleCount = _accessRuleList.getRuleCount();
Log.log_3427(ruleCount);
// Parsing failed
} catch (ParseException exception) {
String exceptionMessage = exception.getMessage();
if (exceptionMessage != null) {
exceptionMessage = exceptionMessage.trim();
if (exceptionMessage.length() < 1) {
exceptionMessage = null;
}
}
Log.log_3428(ACL_PROPERTY, acl, exceptionMessage);
throw new InvalidPropertyValueException(ACL_PROPERTY,
acl,
exceptionMessage);
}
}
// Initialize the RuntimeProperties object.
getProperties().init(runtimeSettings);
// Initialize all instances
int count = _manageableObjects.size();
for (int i = 0; i < count; i++) {
Manageable m = (Manageable) _manageableObjects.get(i);
String className = m.getClass().getName();
Log.log_3416(_name, className);
try {
m.init(runtimeSettings);
Log.log_3417(_name, className);
// Missing required property
} catch (MissingRequiredPropertyException exception) {
Log.log_3418(_name, className, exception.getPropertyName());
throw exception;
// Invalid property value
} catch (InvalidPropertyValueException exception) {
Log.log_3419(_name,
className,
exception.getPropertyName(),
exception.getPropertyValue(),
exception.getReason());
throw exception;
// Catch InitializationException and any other exceptions not caught
// by previous catch statements
} catch (Throwable exception) {
// Log this event
Log.log_3420(exception, _name, className);
if (exception instanceof InitializationException) {
throw (InitializationException) exception;
} else {
throw new InitializationException(exception);
}
}
}
// Initialize all functions
count = _functionList.size();
for (int i = 0; i < count; i++) {
Function f = (Function) _functionList.get(i);
String functionName = f.getName();
Log.log_3421(_name, functionName);
try {
f.init(runtimeSettings);
Log.log_3422(_name, functionName);
// Missing required property
} catch (MissingRequiredPropertyException exception) {
Log.log_3423(_name, functionName, exception.getPropertyName());
throw exception;
// Invalid property value
} catch (InvalidPropertyValueException exception) {
Log.log_3424(_name,
functionName,
exception.getPropertyName(),
exception.getPropertyValue(),
exception.getReason());
throw exception;
// Catch InitializationException and any other exceptions not caught
// by previous catch statements
} catch (Throwable exception) {
// Log this event
Log.log_3425(exception, _name, functionName);
// Throw an InitializationException. If necessary, wrap around the
// caught exception
if (exception instanceof InitializationException) {
throw (InitializationException) exception;
} else {
throw new InitializationException(exception);
}
}
}
// TODO: Call initImpl2(PropertyReader) ?
Log.log_3406(_name);
}
|
diff --git a/fog/src/de/tuilmenau/ics/fog/transfer/manager/ProcessGateConstruction.java b/fog/src/de/tuilmenau/ics/fog/transfer/manager/ProcessGateConstruction.java
index 3b8a9940..b4859e8f 100644
--- a/fog/src/de/tuilmenau/ics/fog/transfer/manager/ProcessGateConstruction.java
+++ b/fog/src/de/tuilmenau/ics/fog/transfer/manager/ProcessGateConstruction.java
@@ -1,220 +1,220 @@
/*******************************************************************************
* Forwarding on Gates Simulator/Emulator
* Copyright (C) 2012, Integrated Communication Systems Group, TU Ilmenau.
*
* This program and the accompanying materials are dual-licensed under either
* the terms of the Eclipse Public License v1.0 as published by the Eclipse
* Foundation
*
* or (per the licensee's choosing)
*
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
******************************************************************************/
package de.tuilmenau.ics.fog.transfer.manager;
import de.tuilmenau.ics.fog.FoGEntity;
import de.tuilmenau.ics.fog.facade.Identity;
import de.tuilmenau.ics.fog.facade.Name;
import de.tuilmenau.ics.fog.facade.NetworkException;
import de.tuilmenau.ics.fog.transfer.ForwardingNode;
import de.tuilmenau.ics.fog.transfer.Gate;
import de.tuilmenau.ics.fog.transfer.Gate.GateState;
import de.tuilmenau.ics.fog.transfer.gates.AbstractGate;
import de.tuilmenau.ics.fog.transfer.gates.GateID;
import de.tuilmenau.ics.fog.ui.Viewable;
public abstract class ProcessGateConstruction extends Process
{
public ProcessGateConstruction(ForwardingNode base, AbstractGate replacementFor, Identity owner)
{
super(base, owner);
mReplacementFor = replacementFor;
}
protected abstract AbstractGate newGate(FoGEntity entity) throws NetworkException;
public Gate create() throws NetworkException
{
mLogger.log(this, "Creating gate..");
ForwardingNode tBase = getBase();
// synch for test&set of down gates
synchronized(tBase) {
// create gate
mLogger.log(this, " ..allocating new gate");
mGate = newGate(getBase().getEntity());
// assign gate a local ID
if(mReplacementFor != null) {
// check if gate is still available
if(mReplacementFor.isOperational() || (mReplacementFor.getState() == GateState.INIT)) {
if(tBase.replaceGate(mReplacementFor, mGate)) {
mLogger.log(this, "Gate " +mGate +" created at " +tBase +" as replacement for " +mReplacementFor);
mReplacementFor.shutdown();
} else {
mLogger.err(this, "Was not able to replace " +mReplacementFor +". Register it as new gate.");
tBase.registerGate(mGate);
}
} else {
// init in order to be able to switch to delete
mLogger.log(this, " ..initializing gate");
mGate.initialise();
mLogger.log(this, " ..shutting down the gate");
mGate.shutdown();
mGate = null;
// invalidate the process
mReplacementFor = null;
throw new NetworkException(this, "Gate " +mReplacementFor +" that should be replaced is not operational. Terminating the construction of a replacement.");
}
} else {
mLogger.log(this, " ..registering gate");
tBase.registerGate(mGate);
mLogger.log(this, "gate " +mGate +" created at " +tBase);
}
}
// switch it to init state
mGate.initialise();
// start terminate timer for timeout till update
restartTimer();
return mGate;
}
public void update(GateID reverseGateNumberAtPeer, Name peerNodeRoutingName, Identity peerIdentity) throws NetworkException
{
FoGEntity tNode = getBase().getEntity();
// check access permissions
if(mPeerIdentity == null) {
if(peerIdentity != null) {
// check for impossible identity
if(peerIdentity.equals(getBase().getEntity().getIdentity())) {
- throw new NetworkException(this, "Can not set peer " +peerIdentity +", since it is equal to node itself. Maybe peer did not sign message?");
+ throw new NetworkException(this, "Can not set peer " +peerIdentity +", since it is equal to the base (" + getBase().getEntity() + ") itself. Maybe peer did not sign message?");
} else {
mPeerIdentity = peerIdentity;
}
}
} else {
if(!mPeerIdentity.equals(peerIdentity)) {
throw new NetworkException(this, "Access not permitted for " +peerIdentity +". Peer identity is " +mPeerIdentity +".");
}
}
// lazy creation?
if((mGate == null) && (getState() == ProcessState.STARTING)) {
mLogger.log(this, "Update called before create. Doing implicit creation.");
try {
create();
}
catch (NetworkException tExc) {
throw new NetworkException(this, "Can not create the gate implicitly. Abording update call.", tExc);
}
}
// switch to check timer mode
setState(ProcessState.OPERATING);
restartTimer();
// store reverse gate
// if reverse gate is not established, reference is null. Then we just
// have a one way down gate
mGate.setReverseGateID(reverseGateNumberAtPeer);
mGate.setRemoteDestinationName(peerNodeRoutingName);
// inform the routing service if the peer name is known
if(peerNodeRoutingName != null) {
try {
tNode.getTransferPlane().registerLink(getBase(), mGate);
}
catch (NetworkException exc) {
mLogger.err(this, "Failed to register link " +mGate +" at " +getBase() +" at routing service.", exc);
// Do not throw it again, because informing the routing
// service might not be required.
}
}
// else: hidden gate; do not inform RS
}
@Override
public boolean isChangableBy(Identity changer)
{
// check, if owner is requesting change
boolean allowed = super.isChangableBy(changer);
if(!allowed) {
// check, if peer is requesting change
if(mPeerIdentity != null) {
allowed = mPeerIdentity.equals(changer);
if(!allowed) {
// admin rights of function provider itself
allowed = mPeerIdentity.equals(mGate.getEntity().getIdentity());
}
} else {
allowed = true;
}
}
return allowed;
}
@Override
public boolean check()
{
if(mGate != null) {
// gate ok?
return (mGate.getState() == GateState.OPERATE);
} else {
// something wrong since create was not called or terminate does not stop timer
mLogger.err(this, "Internal error: Gate " +mGate +" not available.");
return false;
}
}
public GateID getGateNumber() throws NetworkException
{
if(mGate != null) return mGate.getGateID();
else {
if(mReplacementFor != null) return mReplacementFor.getGateID();
else throw new NetworkException(this, "No gate number available. Call create before.");
}
}
@Override
protected void finished()
{
// deleting gate
mLogger.log(this, "removing gate " +mGate);
if(mGate != null) {
synchronized(getBase()) {
mGate.shutdown();
getBase().unregisterGate(mGate);
mGate = null;
}
}
super.finished();
}
@Viewable("Gate")
protected AbstractGate mGate;
@Viewable("Peer identity")
private Identity mPeerIdentity;
private AbstractGate mReplacementFor;
}
| true | true | public void update(GateID reverseGateNumberAtPeer, Name peerNodeRoutingName, Identity peerIdentity) throws NetworkException
{
FoGEntity tNode = getBase().getEntity();
// check access permissions
if(mPeerIdentity == null) {
if(peerIdentity != null) {
// check for impossible identity
if(peerIdentity.equals(getBase().getEntity().getIdentity())) {
throw new NetworkException(this, "Can not set peer " +peerIdentity +", since it is equal to node itself. Maybe peer did not sign message?");
} else {
mPeerIdentity = peerIdentity;
}
}
} else {
if(!mPeerIdentity.equals(peerIdentity)) {
throw new NetworkException(this, "Access not permitted for " +peerIdentity +". Peer identity is " +mPeerIdentity +".");
}
}
// lazy creation?
if((mGate == null) && (getState() == ProcessState.STARTING)) {
mLogger.log(this, "Update called before create. Doing implicit creation.");
try {
create();
}
catch (NetworkException tExc) {
throw new NetworkException(this, "Can not create the gate implicitly. Abording update call.", tExc);
}
}
// switch to check timer mode
setState(ProcessState.OPERATING);
restartTimer();
// store reverse gate
// if reverse gate is not established, reference is null. Then we just
// have a one way down gate
mGate.setReverseGateID(reverseGateNumberAtPeer);
mGate.setRemoteDestinationName(peerNodeRoutingName);
// inform the routing service if the peer name is known
if(peerNodeRoutingName != null) {
try {
tNode.getTransferPlane().registerLink(getBase(), mGate);
}
catch (NetworkException exc) {
mLogger.err(this, "Failed to register link " +mGate +" at " +getBase() +" at routing service.", exc);
// Do not throw it again, because informing the routing
// service might not be required.
}
}
// else: hidden gate; do not inform RS
}
| public void update(GateID reverseGateNumberAtPeer, Name peerNodeRoutingName, Identity peerIdentity) throws NetworkException
{
FoGEntity tNode = getBase().getEntity();
// check access permissions
if(mPeerIdentity == null) {
if(peerIdentity != null) {
// check for impossible identity
if(peerIdentity.equals(getBase().getEntity().getIdentity())) {
throw new NetworkException(this, "Can not set peer " +peerIdentity +", since it is equal to the base (" + getBase().getEntity() + ") itself. Maybe peer did not sign message?");
} else {
mPeerIdentity = peerIdentity;
}
}
} else {
if(!mPeerIdentity.equals(peerIdentity)) {
throw new NetworkException(this, "Access not permitted for " +peerIdentity +". Peer identity is " +mPeerIdentity +".");
}
}
// lazy creation?
if((mGate == null) && (getState() == ProcessState.STARTING)) {
mLogger.log(this, "Update called before create. Doing implicit creation.");
try {
create();
}
catch (NetworkException tExc) {
throw new NetworkException(this, "Can not create the gate implicitly. Abording update call.", tExc);
}
}
// switch to check timer mode
setState(ProcessState.OPERATING);
restartTimer();
// store reverse gate
// if reverse gate is not established, reference is null. Then we just
// have a one way down gate
mGate.setReverseGateID(reverseGateNumberAtPeer);
mGate.setRemoteDestinationName(peerNodeRoutingName);
// inform the routing service if the peer name is known
if(peerNodeRoutingName != null) {
try {
tNode.getTransferPlane().registerLink(getBase(), mGate);
}
catch (NetworkException exc) {
mLogger.err(this, "Failed to register link " +mGate +" at " +getBase() +" at routing service.", exc);
// Do not throw it again, because informing the routing
// service might not be required.
}
}
// else: hidden gate; do not inform RS
}
|
diff --git a/geronimo-el_2.2_spec/src/main/java/javax/el/BeanELResolver.java b/geronimo-el_2.2_spec/src/main/java/javax/el/BeanELResolver.java
index 1fee02d8..dd547254 100644
--- a/geronimo-el_2.2_spec/src/main/java/javax/el/BeanELResolver.java
+++ b/geronimo-el_2.2_spec/src/main/java/javax/el/BeanELResolver.java
@@ -1,453 +1,453 @@
/*
* 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 javax.el;
import java.beans.BeanInfo;
import java.beans.FeatureDescriptor;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ConcurrentHashMap;
public class BeanELResolver extends ELResolver {
private final boolean readOnly;
private final ConcurrentCache<String, BeanProperties> cache = new ConcurrentCache<String, BeanProperties>(
1000);
public BeanELResolver() {
this.readOnly = false;
}
public BeanELResolver(boolean readOnly) {
this.readOnly = readOnly;
}
public Object getValue(ELContext context, Object base, Object property)
throws NullPointerException, PropertyNotFoundException, ELException {
if (context == null) {
throw new NullPointerException();
}
if (base == null || property == null) {
return null;
}
context.setPropertyResolved(true);
Method m = this.property(context, base, property).read(context);
try {
return m.invoke(base, (Object[]) null);
} catch (IllegalAccessException e) {
throw new ELException(e);
} catch (InvocationTargetException e) {
throw new ELException(message(context, "propertyReadError",
new Object[] { base.getClass().getName(),
property.toString() }), e.getCause());
} catch (Exception e) {
throw new ELException(e);
}
}
public Class<?> getType(ELContext context, Object base, Object property)
throws NullPointerException, PropertyNotFoundException, ELException {
if (context == null) {
throw new NullPointerException();
}
if (base == null || property == null) {
return null;
}
context.setPropertyResolved(true);
return this.property(context, base, property).getPropertyType();
}
public void setValue(ELContext context, Object base, Object property,
Object value) throws NullPointerException,
PropertyNotFoundException, PropertyNotWritableException,
ELException {
if (context == null) {
throw new NullPointerException();
}
if (base == null || property == null) {
return;
}
context.setPropertyResolved(true);
if (this.readOnly) {
throw new PropertyNotWritableException(message(context,
"resolverNotWriteable", new Object[] { base.getClass()
.getName() }));
}
Method m = this.property(context, base, property).write(context);
try {
m.invoke(base, value);
} catch (IllegalAccessException e) {
throw new ELException(e);
} catch (InvocationTargetException e) {
throw new ELException(message(context, "propertyWriteError",
new Object[] { base.getClass().getName(),
property.toString() }), e.getCause());
} catch (Exception e) {
throw new ELException(e);
}
}
public boolean isReadOnly(ELContext context, Object base, Object property)
throws NullPointerException, PropertyNotFoundException, ELException {
if (context == null) {
throw new NullPointerException();
}
if (base == null || property == null) {
return false;
}
context.setPropertyResolved(true);
return this.readOnly
|| this.property(context, base, property).isReadOnly();
}
public Iterator<FeatureDescriptor> getFeatureDescriptors(ELContext context, Object base) {
if (context == null) {
throw new NullPointerException();
}
if (base == null) {
return null;
}
try {
BeanInfo info = Introspector.getBeanInfo(base.getClass());
PropertyDescriptor[] pds = info.getPropertyDescriptors();
for (PropertyDescriptor pd : pds) {
pd.setValue(RESOLVABLE_AT_DESIGN_TIME, Boolean.TRUE);
pd.setValue(TYPE, pd.getPropertyType());
}
return Arrays.asList((FeatureDescriptor[]) pds).iterator();
} catch (IntrospectionException e) {
//
}
return null;
}
public Class<?> getCommonPropertyType(ELContext context, Object base) {
if (context == null) {
throw new NullPointerException();
}
if (base != null) {
return Object.class;
}
return null;
}
protected final static class BeanProperties {
private final Map<String, BeanProperty> properties;
private final Class<?> type;
public BeanProperties(Class<?> type) throws ELException {
this.type = type;
this.properties = new HashMap<String, BeanProperty>();
try {
BeanInfo info = Introspector.getBeanInfo(this.type);
PropertyDescriptor[] pds = info.getPropertyDescriptors();
for (PropertyDescriptor pd : pds) {
this.properties.put(pd.getName(), new BeanProperty(
type, pd));
}
} catch (IntrospectionException ie) {
throw new ELException(ie);
}
}
private BeanProperty get(ELContext ctx, String name) {
BeanProperty property = this.properties.get(name);
if (property == null) {
throw new PropertyNotFoundException(message(ctx,
"propertyNotFound",
new Object[] { type.getName(), name }));
}
return property;
}
public BeanProperty getBeanProperty(String name) {
return get(null, name);
}
private Class<?> getType() {
return type;
}
}
protected final static class BeanProperty {
private final Class<?> type;
private final Class<?> owner;
private final PropertyDescriptor descriptor;
private Method read;
private Method write;
public BeanProperty(Class<?> owner, PropertyDescriptor descriptor) {
this.owner = owner;
this.descriptor = descriptor;
this.type = descriptor.getPropertyType();
}
public Class getPropertyType() {
return this.type;
}
public boolean isReadOnly() {
return this.write == null
&& (null == (this.write = getMethod(this.owner, descriptor.getWriteMethod())));
}
public Method getWriteMethod() {
return write(null);
}
public Method getReadMethod() {
return this.read(null);
}
private Method write(ELContext ctx) {
if (this.write == null) {
this.write = getMethod(this.owner, descriptor.getWriteMethod());
if (this.write == null) {
throw new PropertyNotFoundException(message(ctx,
"propertyNotWritable", new Object[] {
type.getName(), descriptor.getName() }));
}
}
return this.write;
}
private Method read(ELContext ctx) {
if (this.read == null) {
this.read = getMethod(this.owner, descriptor.getReadMethod());
if (this.read == null) {
throw new PropertyNotFoundException(message(ctx,
"propertyNotReadable", new Object[] {
type.getName(), descriptor.getName() }));
}
}
return this.read;
}
}
private BeanProperty property(ELContext ctx, Object base,
Object property) {
Class<?> type = base.getClass();
String prop = property.toString();
BeanProperties props = this.cache.get(type.getName());
if (props == null || type != props.getType()) {
props = new BeanProperties(type);
this.cache.put(type.getName(), props);
}
return props.get(ctx, prop);
}
private static Method getMethod(Class type, Method m) {
if (m == null || Modifier.isPublic(type.getModifiers())) {
return m;
}
Class[] inf = type.getInterfaces();
Method mp;
for (Class anInf : inf) {
try {
mp = anInf.getMethod(m.getName(), m.getParameterTypes());
mp = getMethod(mp.getDeclaringClass(), mp);
if (mp != null) {
return mp;
}
} catch (NoSuchMethodException e) {
//continue
}
}
Class sup = type.getSuperclass();
if (sup != null) {
try {
mp = sup.getMethod(m.getName(), m.getParameterTypes());
mp = getMethod(mp.getDeclaringClass(), mp);
if (mp != null) {
return mp;
}
} catch (NoSuchMethodException e) {
//continue
}
}
return null;
}
private final static class ConcurrentCache<K,V> {
private final int size;
private final Map<K,V> eden;
private final Map<K,V> longterm;
public ConcurrentCache(int size) {
this.size = size;
this.eden = new ConcurrentHashMap<K,V>(size);
this.longterm = new WeakHashMap<K,V>(size);
}
public V get(K key) {
V value = this.eden.get(key);
if (value == null) {
value = this.longterm.get(key);
if (value != null) {
this.eden.put(key, value);
}
}
return value;
}
public void put(K key, V value) {
if (this.eden.size() >= this.size) {
this.longterm.putAll(this.eden);
this.eden.clear();
}
this.eden.put(key, value);
}
}
public Object invoke(ELContext context, Object base, Object method, Class<?>[] paramTypes, Object[] params) {
if (context == null) {
throw new NullPointerException("ELContext could not be nulll");
}
// Why static invocation is not supported
if(base == null || method == null) {
return null;
}
if (params == null) {
params = new Object[0];
}
ExpressionFactory expressionFactory = (ExpressionFactory) context.getContext(ExpressionFactory.class);
if (expressionFactory == null) {
expressionFactory = ExpressionFactory.newInstance();
}
String methodName = (String) expressionFactory.coerceToType(method, String.class);
if (methodName.length() == 0) {
throw new MethodNotFoundException("The parameter method could not be zero-length");
}
Class<?> targetClass = base.getClass();
if (methodName.equals("<init>") || methodName.equals("<cinit>")) {
throw new MethodNotFoundException(method + " is not found in target class " + targetClass.getName());
}
Method targetMethod = null;
if (paramTypes == null) {
int paramsNumber = params.length;
for (Method m : targetClass.getMethods()) {
if (m.getName().equals(methodName) && m.getParameterTypes().length == paramsNumber) {
targetMethod = m;
break;
}
}
if (targetMethod == null) {
for (Method m : targetClass.getMethods()) {
if (m.getName().equals(methodName) && m.isVarArgs() && paramsNumber >= (m.getParameterTypes().length - 1)) {
targetMethod = m;
break;
}
}
}
} else {
try {
targetMethod = targetClass.getMethod(methodName, paramTypes);
} catch (SecurityException e) {
throw new ELException(e);
} catch (NoSuchMethodException e) {
throw new MethodNotFoundException(e);
}
}
if (targetMethod == null) {
throw new MethodNotFoundException(method + " is not found in target class " + targetClass.getName());
}
if (paramTypes == null) {
paramTypes = targetMethod.getParameterTypes();
}
//Initial check whether the types and parameter values length
if (targetMethod.isVarArgs()) {
if (paramTypes.length - 1 > params.length) {
throw new IllegalArgumentException("Inconsistent number between argument types and values");
}
} else if (paramTypes.length != params.length) {
throw new IllegalArgumentException("Inconsistent number between argument types and values");
}
try {
Object[] finalParamValues = new Object[paramTypes.length];
int iCurrentIndex = 0;
for (int iLoopSize = paramTypes.length - 1; iCurrentIndex < iLoopSize; iCurrentIndex++) {
finalParamValues[iCurrentIndex] = expressionFactory.coerceToType(params[iCurrentIndex],paramTypes[iCurrentIndex]);
}
/**
* Not sure it is over-designed. Do not find detailed description about how the parameter values are passed if the method is of variable arguments.
* It might be an array directly passed or each parameter value passed one by one.
*/
if (targetMethod.isVarArgs()) {
// varArgsClassType should be an array type
Class<?> varArgsClassType = paramTypes[iCurrentIndex];
// 1. If there is no parameter value left for the variable argment, create a zero-length array
// 2. If there is only one parameter value left for the variable argment, and it has the same array type with the varArgsClass, pass in directly
// 3. Eles, create an array of varArgsClass type, and add all the left coerced parameter values
if (iCurrentIndex == params.length) {
finalParamValues[iCurrentIndex] = Array.newInstance(varArgsClassType.getComponentType(), 0);
} else if (iCurrentIndex == params.length - 1 && varArgsClassType == params[iCurrentIndex].getClass()
&& varArgsClassType.getClassLoader() == params[iCurrentIndex].getClass().getClassLoader()) {
- finalParamValues[iCurrentIndex] = paramTypes[iCurrentIndex];
+ finalParamValues[iCurrentIndex] = params[iCurrentIndex];
} else {
Object targetArray = Array.newInstance(varArgsClassType.getComponentType(), params.length - iCurrentIndex);
Class<?> componentClassType = varArgsClassType.getComponentType();
for (int i = 0, iLoopSize = params.length - iCurrentIndex; i < iLoopSize; i++) {
Array.set(targetArray, i, expressionFactory.coerceToType(iCurrentIndex + i, componentClassType));
}
finalParamValues[iCurrentIndex] = targetArray;
}
} else {
finalParamValues[iCurrentIndex] = expressionFactory.coerceToType(params[iCurrentIndex], paramTypes[iCurrentIndex]);
}
Object retValue = targetMethod.invoke(base, finalParamValues);
context.setPropertyResolved(true);
return retValue;
} catch (IllegalAccessException e) {
throw new ELException(e);
} catch (InvocationTargetException e) {
throw new ELException(e.getCause());
}
}
}
| true | true | public Object invoke(ELContext context, Object base, Object method, Class<?>[] paramTypes, Object[] params) {
if (context == null) {
throw new NullPointerException("ELContext could not be nulll");
}
// Why static invocation is not supported
if(base == null || method == null) {
return null;
}
if (params == null) {
params = new Object[0];
}
ExpressionFactory expressionFactory = (ExpressionFactory) context.getContext(ExpressionFactory.class);
if (expressionFactory == null) {
expressionFactory = ExpressionFactory.newInstance();
}
String methodName = (String) expressionFactory.coerceToType(method, String.class);
if (methodName.length() == 0) {
throw new MethodNotFoundException("The parameter method could not be zero-length");
}
Class<?> targetClass = base.getClass();
if (methodName.equals("<init>") || methodName.equals("<cinit>")) {
throw new MethodNotFoundException(method + " is not found in target class " + targetClass.getName());
}
Method targetMethod = null;
if (paramTypes == null) {
int paramsNumber = params.length;
for (Method m : targetClass.getMethods()) {
if (m.getName().equals(methodName) && m.getParameterTypes().length == paramsNumber) {
targetMethod = m;
break;
}
}
if (targetMethod == null) {
for (Method m : targetClass.getMethods()) {
if (m.getName().equals(methodName) && m.isVarArgs() && paramsNumber >= (m.getParameterTypes().length - 1)) {
targetMethod = m;
break;
}
}
}
} else {
try {
targetMethod = targetClass.getMethod(methodName, paramTypes);
} catch (SecurityException e) {
throw new ELException(e);
} catch (NoSuchMethodException e) {
throw new MethodNotFoundException(e);
}
}
if (targetMethod == null) {
throw new MethodNotFoundException(method + " is not found in target class " + targetClass.getName());
}
if (paramTypes == null) {
paramTypes = targetMethod.getParameterTypes();
}
//Initial check whether the types and parameter values length
if (targetMethod.isVarArgs()) {
if (paramTypes.length - 1 > params.length) {
throw new IllegalArgumentException("Inconsistent number between argument types and values");
}
} else if (paramTypes.length != params.length) {
throw new IllegalArgumentException("Inconsistent number between argument types and values");
}
try {
Object[] finalParamValues = new Object[paramTypes.length];
int iCurrentIndex = 0;
for (int iLoopSize = paramTypes.length - 1; iCurrentIndex < iLoopSize; iCurrentIndex++) {
finalParamValues[iCurrentIndex] = expressionFactory.coerceToType(params[iCurrentIndex],paramTypes[iCurrentIndex]);
}
/**
* Not sure it is over-designed. Do not find detailed description about how the parameter values are passed if the method is of variable arguments.
* It might be an array directly passed or each parameter value passed one by one.
*/
if (targetMethod.isVarArgs()) {
// varArgsClassType should be an array type
Class<?> varArgsClassType = paramTypes[iCurrentIndex];
// 1. If there is no parameter value left for the variable argment, create a zero-length array
// 2. If there is only one parameter value left for the variable argment, and it has the same array type with the varArgsClass, pass in directly
// 3. Eles, create an array of varArgsClass type, and add all the left coerced parameter values
if (iCurrentIndex == params.length) {
finalParamValues[iCurrentIndex] = Array.newInstance(varArgsClassType.getComponentType(), 0);
} else if (iCurrentIndex == params.length - 1 && varArgsClassType == params[iCurrentIndex].getClass()
&& varArgsClassType.getClassLoader() == params[iCurrentIndex].getClass().getClassLoader()) {
finalParamValues[iCurrentIndex] = paramTypes[iCurrentIndex];
} else {
Object targetArray = Array.newInstance(varArgsClassType.getComponentType(), params.length - iCurrentIndex);
Class<?> componentClassType = varArgsClassType.getComponentType();
for (int i = 0, iLoopSize = params.length - iCurrentIndex; i < iLoopSize; i++) {
Array.set(targetArray, i, expressionFactory.coerceToType(iCurrentIndex + i, componentClassType));
}
finalParamValues[iCurrentIndex] = targetArray;
}
} else {
finalParamValues[iCurrentIndex] = expressionFactory.coerceToType(params[iCurrentIndex], paramTypes[iCurrentIndex]);
}
Object retValue = targetMethod.invoke(base, finalParamValues);
context.setPropertyResolved(true);
return retValue;
} catch (IllegalAccessException e) {
throw new ELException(e);
} catch (InvocationTargetException e) {
throw new ELException(e.getCause());
}
}
| public Object invoke(ELContext context, Object base, Object method, Class<?>[] paramTypes, Object[] params) {
if (context == null) {
throw new NullPointerException("ELContext could not be nulll");
}
// Why static invocation is not supported
if(base == null || method == null) {
return null;
}
if (params == null) {
params = new Object[0];
}
ExpressionFactory expressionFactory = (ExpressionFactory) context.getContext(ExpressionFactory.class);
if (expressionFactory == null) {
expressionFactory = ExpressionFactory.newInstance();
}
String methodName = (String) expressionFactory.coerceToType(method, String.class);
if (methodName.length() == 0) {
throw new MethodNotFoundException("The parameter method could not be zero-length");
}
Class<?> targetClass = base.getClass();
if (methodName.equals("<init>") || methodName.equals("<cinit>")) {
throw new MethodNotFoundException(method + " is not found in target class " + targetClass.getName());
}
Method targetMethod = null;
if (paramTypes == null) {
int paramsNumber = params.length;
for (Method m : targetClass.getMethods()) {
if (m.getName().equals(methodName) && m.getParameterTypes().length == paramsNumber) {
targetMethod = m;
break;
}
}
if (targetMethod == null) {
for (Method m : targetClass.getMethods()) {
if (m.getName().equals(methodName) && m.isVarArgs() && paramsNumber >= (m.getParameterTypes().length - 1)) {
targetMethod = m;
break;
}
}
}
} else {
try {
targetMethod = targetClass.getMethod(methodName, paramTypes);
} catch (SecurityException e) {
throw new ELException(e);
} catch (NoSuchMethodException e) {
throw new MethodNotFoundException(e);
}
}
if (targetMethod == null) {
throw new MethodNotFoundException(method + " is not found in target class " + targetClass.getName());
}
if (paramTypes == null) {
paramTypes = targetMethod.getParameterTypes();
}
//Initial check whether the types and parameter values length
if (targetMethod.isVarArgs()) {
if (paramTypes.length - 1 > params.length) {
throw new IllegalArgumentException("Inconsistent number between argument types and values");
}
} else if (paramTypes.length != params.length) {
throw new IllegalArgumentException("Inconsistent number between argument types and values");
}
try {
Object[] finalParamValues = new Object[paramTypes.length];
int iCurrentIndex = 0;
for (int iLoopSize = paramTypes.length - 1; iCurrentIndex < iLoopSize; iCurrentIndex++) {
finalParamValues[iCurrentIndex] = expressionFactory.coerceToType(params[iCurrentIndex],paramTypes[iCurrentIndex]);
}
/**
* Not sure it is over-designed. Do not find detailed description about how the parameter values are passed if the method is of variable arguments.
* It might be an array directly passed or each parameter value passed one by one.
*/
if (targetMethod.isVarArgs()) {
// varArgsClassType should be an array type
Class<?> varArgsClassType = paramTypes[iCurrentIndex];
// 1. If there is no parameter value left for the variable argment, create a zero-length array
// 2. If there is only one parameter value left for the variable argment, and it has the same array type with the varArgsClass, pass in directly
// 3. Eles, create an array of varArgsClass type, and add all the left coerced parameter values
if (iCurrentIndex == params.length) {
finalParamValues[iCurrentIndex] = Array.newInstance(varArgsClassType.getComponentType(), 0);
} else if (iCurrentIndex == params.length - 1 && varArgsClassType == params[iCurrentIndex].getClass()
&& varArgsClassType.getClassLoader() == params[iCurrentIndex].getClass().getClassLoader()) {
finalParamValues[iCurrentIndex] = params[iCurrentIndex];
} else {
Object targetArray = Array.newInstance(varArgsClassType.getComponentType(), params.length - iCurrentIndex);
Class<?> componentClassType = varArgsClassType.getComponentType();
for (int i = 0, iLoopSize = params.length - iCurrentIndex; i < iLoopSize; i++) {
Array.set(targetArray, i, expressionFactory.coerceToType(iCurrentIndex + i, componentClassType));
}
finalParamValues[iCurrentIndex] = targetArray;
}
} else {
finalParamValues[iCurrentIndex] = expressionFactory.coerceToType(params[iCurrentIndex], paramTypes[iCurrentIndex]);
}
Object retValue = targetMethod.invoke(base, finalParamValues);
context.setPropertyResolved(true);
return retValue;
} catch (IllegalAccessException e) {
throw new ELException(e);
} catch (InvocationTargetException e) {
throw new ELException(e.getCause());
}
}
|
diff --git a/Android/NHProject/NewsHub/src/main/java/org/gnuton/newshub/adapters/FeedListAdapter.java b/Android/NHProject/NewsHub/src/main/java/org/gnuton/newshub/adapters/FeedListAdapter.java
index 363ec02..e25a528 100644
--- a/Android/NHProject/NewsHub/src/main/java/org/gnuton/newshub/adapters/FeedListAdapter.java
+++ b/Android/NHProject/NewsHub/src/main/java/org/gnuton/newshub/adapters/FeedListAdapter.java
@@ -1,90 +1,94 @@
package org.gnuton.newshub.adapters;
import android.content.Context;
import android.text.Html;
import android.text.Spanned;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import org.gnuton.newshub.R;
import org.gnuton.newshub.types.RSSFeed;
import org.gnuton.newshub.utils.NetworkUtils;
import org.gnuton.newshub.utils.Utils;
import java.util.List;
/**
* Feed list adapter
*/
public class FeedListAdapter extends ArrayAdapter<RSSFeed> {
private final List<RSSFeed> feeds;
final int mStyle;
final boolean mShortUrl;
public FeedListAdapter(Context context, int textViewResourceId, List<RSSFeed> feeds, boolean shortUrl, int style) {
super(context, textViewResourceId, feeds);
this.feeds = feeds;
this.mStyle = style;
this.mShortUrl = shortUrl;
}
public FeedListAdapter(Context context, int textViewResourceId, List<RSSFeed> feeds, boolean shortUrl) {
super(context, textViewResourceId, feeds);
this.feeds = feeds;
this.mStyle = -1;
this.mShortUrl = shortUrl;
}
public static class ViewHolder{
public TextView title;
public TextView desc;
public ImageView sidebar;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolder holder;
// Create delegate (View + view holder) when needed, or get the holder for the current view to convert.
if (v == null) {
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.feedlist_item, null);
holder = new ViewHolder();
+ assert v != null;
holder.title = (TextView) v.findViewById(R.id.FeedListItemTitleTextView);
- if (mStyle != -1 )
- holder.title.setTextAppearance(v.getContext(), mStyle);
+ if (mStyle != -1 ) {
+ Context context = v.getContext();
+ if (context != null)
+ holder.title.setTextAppearance(context, mStyle);
+ }
holder.desc = (TextView) v.findViewById(R.id.FeedListItemDescTextView);
holder.sidebar = (ImageView) v.findViewById(R.id.sidebar);
v.setTag(holder);
}
else
holder=(ViewHolder)v.getTag();
// Update the delegate setting data stored in the holder
final RSSFeed f = feeds.get(position);
if (f != null) {
Spanned myStringSpanned = Html.fromHtml(f.title, null, null);
holder.title.setText(myStringSpanned, TextView.BufferType.SPANNABLE);
String urlDomain;
if (!mShortUrl)
urlDomain= NetworkUtils.getMoreDetailedDomainName(f.url);
else
urlDomain= NetworkUtils.getDomainName(f.url);
holder.desc.setText(urlDomain);
holder.sidebar.setBackgroundColor(Utils.generateColor(f.title));
}
// returns the updated delegate
return v;
}
}
| false | true | public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolder holder;
// Create delegate (View + view holder) when needed, or get the holder for the current view to convert.
if (v == null) {
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.feedlist_item, null);
holder = new ViewHolder();
holder.title = (TextView) v.findViewById(R.id.FeedListItemTitleTextView);
if (mStyle != -1 )
holder.title.setTextAppearance(v.getContext(), mStyle);
holder.desc = (TextView) v.findViewById(R.id.FeedListItemDescTextView);
holder.sidebar = (ImageView) v.findViewById(R.id.sidebar);
v.setTag(holder);
}
else
holder=(ViewHolder)v.getTag();
// Update the delegate setting data stored in the holder
final RSSFeed f = feeds.get(position);
if (f != null) {
Spanned myStringSpanned = Html.fromHtml(f.title, null, null);
holder.title.setText(myStringSpanned, TextView.BufferType.SPANNABLE);
String urlDomain;
if (!mShortUrl)
urlDomain= NetworkUtils.getMoreDetailedDomainName(f.url);
else
urlDomain= NetworkUtils.getDomainName(f.url);
holder.desc.setText(urlDomain);
holder.sidebar.setBackgroundColor(Utils.generateColor(f.title));
}
// returns the updated delegate
return v;
}
| public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolder holder;
// Create delegate (View + view holder) when needed, or get the holder for the current view to convert.
if (v == null) {
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.feedlist_item, null);
holder = new ViewHolder();
assert v != null;
holder.title = (TextView) v.findViewById(R.id.FeedListItemTitleTextView);
if (mStyle != -1 ) {
Context context = v.getContext();
if (context != null)
holder.title.setTextAppearance(context, mStyle);
}
holder.desc = (TextView) v.findViewById(R.id.FeedListItemDescTextView);
holder.sidebar = (ImageView) v.findViewById(R.id.sidebar);
v.setTag(holder);
}
else
holder=(ViewHolder)v.getTag();
// Update the delegate setting data stored in the holder
final RSSFeed f = feeds.get(position);
if (f != null) {
Spanned myStringSpanned = Html.fromHtml(f.title, null, null);
holder.title.setText(myStringSpanned, TextView.BufferType.SPANNABLE);
String urlDomain;
if (!mShortUrl)
urlDomain= NetworkUtils.getMoreDetailedDomainName(f.url);
else
urlDomain= NetworkUtils.getDomainName(f.url);
holder.desc.setText(urlDomain);
holder.sidebar.setBackgroundColor(Utils.generateColor(f.title));
}
// returns the updated delegate
return v;
}
|
diff --git a/assignment-tool/tool/src/java/org/sakaiproject/assignment/tool/AssignmentAction.java b/assignment-tool/tool/src/java/org/sakaiproject/assignment/tool/AssignmentAction.java
index 36b53dd9..b8357e49 100644
--- a/assignment-tool/tool/src/java/org/sakaiproject/assignment/tool/AssignmentAction.java
+++ b/assignment-tool/tool/src/java/org/sakaiproject/assignment/tool/AssignmentAction.java
@@ -1,10096 +1,10096 @@
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006, 2007 The Sakai Foundation.
*
* Licensed under the Educational Community License, Version 1.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.opensource.org/licenses/ecl1.php
*
* 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.sakaiproject.assignment.tool;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Hashtable;
import java.util.HashSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.nio.channels.*;
import java.nio.*;
import org.sakaiproject.announcement.api.AnnouncementChannel;
import org.sakaiproject.announcement.api.AnnouncementMessage;
import org.sakaiproject.announcement.api.AnnouncementMessageEdit;
import org.sakaiproject.announcement.api.AnnouncementMessageHeaderEdit;
import org.sakaiproject.announcement.api.AnnouncementService;
import org.sakaiproject.assignment.api.Assignment;
import org.sakaiproject.assignment.api.AssignmentContentEdit;
import org.sakaiproject.assignment.api.AssignmentEdit;
import org.sakaiproject.assignment.api.AssignmentSubmission;
import org.sakaiproject.assignment.api.AssignmentSubmissionEdit;
import org.sakaiproject.assignment.cover.AssignmentService;
import org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer;
import org.sakaiproject.assignment.taggable.api.TaggingHelperInfo;
import org.sakaiproject.assignment.taggable.api.TaggingManager;
import org.sakaiproject.assignment.taggable.api.TaggingProvider;
import org.sakaiproject.assignment.taggable.tool.DecoratedTaggingProvider;
import org.sakaiproject.assignment.taggable.tool.DecoratedTaggingProvider.Pager;
import org.sakaiproject.assignment.taggable.tool.DecoratedTaggingProvider.Sort;
import org.sakaiproject.authz.api.SecurityAdvisor;
import org.sakaiproject.authz.cover.SecurityService;
import org.sakaiproject.authz.api.AuthzGroup;
import org.sakaiproject.authz.api.GroupNotDefinedException;
import org.sakaiproject.authz.api.PermissionsHelper;
import org.sakaiproject.authz.cover.AuthzGroupService;
import org.sakaiproject.calendar.api.Calendar;
import org.sakaiproject.calendar.api.CalendarEvent;
import org.sakaiproject.calendar.api.CalendarEventEdit;
import org.sakaiproject.calendar.api.CalendarService;
import org.sakaiproject.cheftool.Context;
import org.sakaiproject.cheftool.JetspeedRunData;
import org.sakaiproject.cheftool.PagedResourceActionII;
import org.sakaiproject.cheftool.PortletConfig;
import org.sakaiproject.cheftool.RunData;
import org.sakaiproject.cheftool.VelocityPortlet;
import org.sakaiproject.component.cover.ComponentManager;
import org.sakaiproject.component.cover.ServerConfigurationService;
import org.sakaiproject.content.api.ContentResource;
import org.sakaiproject.content.api.ContentResourceEdit;
import org.sakaiproject.content.api.ContentTypeImageService;
import org.sakaiproject.content.api.FilePickerHelper;
import org.sakaiproject.content.cover.ContentHostingService;
import org.sakaiproject.content.api.ContentResourceEdit;
import org.sakaiproject.entity.api.Entity;
import org.sakaiproject.entity.api.Reference;
import org.sakaiproject.entity.api.ResourceProperties;
import org.sakaiproject.entity.api.ResourcePropertiesEdit;
import org.sakaiproject.entity.cover.EntityManager;
import org.sakaiproject.event.api.SessionState;
import org.sakaiproject.event.cover.EventTrackingService;
import org.sakaiproject.event.cover.NotificationService;
import org.sakaiproject.exception.IdInvalidException;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.exception.IdUsedException;
import org.sakaiproject.exception.InUseException;
import org.sakaiproject.exception.PermissionException;
import org.sakaiproject.javax.PagingPosition;
import org.sakaiproject.service.gradebook.shared.AssignmentHasIllegalPointsException;
import org.sakaiproject.service.gradebook.shared.GradebookService;
import org.sakaiproject.service.gradebook.shared.AssignmentHasIllegalPointsException;
import org.sakaiproject.service.gradebook.shared.ConflictingAssignmentNameException;
import org.sakaiproject.service.gradebook.shared.ConflictingExternalIdException;
import org.sakaiproject.service.gradebook.shared.GradebookNotFoundException;
import org.sakaiproject.service.gradebook.shared.GradebookService;
import org.sakaiproject.site.api.Group;
import org.sakaiproject.site.api.Site;
import org.sakaiproject.site.cover.SiteService;
import org.sakaiproject.time.api.Time;
import org.sakaiproject.time.api.TimeBreakdown;
import org.sakaiproject.time.cover.TimeService;
import org.sakaiproject.tool.api.Tool;
import org.sakaiproject.tool.api.ToolSession;
import org.sakaiproject.tool.cover.ToolManager;
import org.sakaiproject.tool.cover.SessionManager;
import org.sakaiproject.user.api.User;
import org.sakaiproject.user.cover.UserDirectoryService;
import org.sakaiproject.util.FileItem;
import org.sakaiproject.util.FormattedText;
import org.sakaiproject.util.ParameterParser;
import org.sakaiproject.util.ResourceLoader;
import org.sakaiproject.util.SortedIterator;
import org.sakaiproject.util.StringUtil;
import org.sakaiproject.util.Validator;
import org.sakaiproject.contentreview.service.ContentReviewService;
/**
* <p>
* AssignmentAction is the action class for the assignment tool.
* </p>
*/
public class AssignmentAction extends PagedResourceActionII
{
private static ResourceLoader rb = new ResourceLoader("assignment");
private static final String ASSIGNMENT_TOOL_ID = "sakai.assignment.grades";
private static final Boolean allowReviewService = ServerConfigurationService.getBoolean("assignment.useContentReview", false);
/** Is the review service available? */
private static final String ALLOW_REVIEW_SERVICE = "allow_review_service";
/** Is review service enabled? */
private static final String ENABLE_REVIEW_SERVICE = "enable_review_service";
private static final String NEW_ASSIGNMENT_USE_REVIEW_SERVICE = "new_assignment_use_review_service";
private static final String NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW = "new_assignment_allow_student_view";
/** The attachments */
private static final String ATTACHMENTS = "Assignment.attachments";
/** The content type image lookup service in the State. */
private static final String STATE_CONTENT_TYPE_IMAGE_SERVICE = "Assignment.content_type_image_service";
/** The calendar service in the State. */
private static final String STATE_CALENDAR_SERVICE = "Assignment.calendar_service";
/** The announcement service in the State. */
private static final String STATE_ANNOUNCEMENT_SERVICE = "Assignment.announcement_service";
/** The calendar object */
private static final String CALENDAR = "calendar";
/** The calendar tool */
private static final String CALENDAR_TOOL_EXIST = "calendar_tool_exisit";
/** The announcement tool */
private static final String ANNOUNCEMENT_TOOL_EXIST = "announcement_tool_exist";
/** The announcement channel */
private static final String ANNOUNCEMENT_CHANNEL = "announcement_channel";
/** The state mode */
private static final String STATE_MODE = "Assignment.mode";
/** The context string */
private static final String STATE_CONTEXT_STRING = "Assignment.context_string";
/** The user */
private static final String STATE_USER = "Assignment.user";
// SECTION MOD
/** Used to keep track of the section info not currently being used. */
private static final String STATE_SECTION_STRING = "Assignment.section_string";
/** **************************** sort assignment ********************** */
/** state sort * */
private static final String SORTED_BY = "Assignment.sorted_by";
/** state sort ascendingly * */
private static final String SORTED_ASC = "Assignment.sorted_asc";
/** default sorting */
private static final String SORTED_BY_DEFAULT = "default";
/** sort by assignment title */
private static final String SORTED_BY_TITLE = "title";
/** sort by assignment section */
private static final String SORTED_BY_SECTION = "section";
/** sort by assignment due date */
private static final String SORTED_BY_DUEDATE = "duedate";
/** sort by assignment open date */
private static final String SORTED_BY_OPENDATE = "opendate";
/** sort by assignment status */
private static final String SORTED_BY_ASSIGNMENT_STATUS = "assignment_status";
/** sort by assignment submission status */
private static final String SORTED_BY_SUBMISSION_STATUS = "submission_status";
/** sort by assignment number of submissions */
private static final String SORTED_BY_NUM_SUBMISSIONS = "num_submissions";
/** sort by assignment number of ungraded submissions */
private static final String SORTED_BY_NUM_UNGRADED = "num_ungraded";
/** sort by assignment submission grade */
private static final String SORTED_BY_GRADE = "grade";
/** sort by assignment maximun grade available */
private static final String SORTED_BY_MAX_GRADE = "max_grade";
/** sort by assignment range */
private static final String SORTED_BY_FOR = "for";
/** sort by group title */
private static final String SORTED_BY_GROUP_TITLE = "group_title";
/** sort by group description */
private static final String SORTED_BY_GROUP_DESCRIPTION = "group_description";
/** *************************** sort submission in instructor grade view *********************** */
/** state sort submission* */
private static final String SORTED_GRADE_SUBMISSION_BY = "Assignment.grade_submission_sorted_by";
/** state sort submission ascendingly * */
private static final String SORTED_GRADE_SUBMISSION_ASC = "Assignment.grade_submission_sorted_asc";
/** state sort submission by submitters last name * */
private static final String SORTED_GRADE_SUBMISSION_BY_LASTNAME = "sorted_grade_submission_by_lastname";
/** state sort submission by submit time * */
private static final String SORTED_GRADE_SUBMISSION_BY_SUBMIT_TIME = "sorted_grade_submission_by_submit_time";
/** state sort submission by submission status * */
private static final String SORTED_GRADE_SUBMISSION_BY_STATUS = "sorted_grade_submission_by_status";
/** state sort submission by submission grade * */
private static final String SORTED_GRADE_SUBMISSION_BY_GRADE = "sorted_grade_submission_by_grade";
/** state sort submission by submission released * */
private static final String SORTED_GRADE_SUBMISSION_BY_RELEASED = "sorted_grade_submission_by_released";
/** state sort submissuib by content review score **/
private static final String SORTED_GRADE_SUBMISSION_CONTENTREVIEW = "sorted_grade_submission_by_contentreview";
/** *************************** sort submission *********************** */
/** state sort submission* */
private static final String SORTED_SUBMISSION_BY = "Assignment.submission_sorted_by";
/** state sort submission ascendingly * */
private static final String SORTED_SUBMISSION_ASC = "Assignment.submission_sorted_asc";
/** state sort submission by submitters last name * */
private static final String SORTED_SUBMISSION_BY_LASTNAME = "sorted_submission_by_lastname";
/** state sort submission by submit time * */
private static final String SORTED_SUBMISSION_BY_SUBMIT_TIME = "sorted_submission_by_submit_time";
/** state sort submission by submission grade * */
private static final String SORTED_SUBMISSION_BY_GRADE = "sorted_submission_by_grade";
/** state sort submission by submission status * */
private static final String SORTED_SUBMISSION_BY_STATUS = "sorted_submission_by_status";
/** state sort submission by submission released * */
private static final String SORTED_SUBMISSION_BY_RELEASED = "sorted_submission_by_released";
/** state sort submission by assignment title */
private static final String SORTED_SUBMISSION_BY_ASSIGNMENT = "sorted_submission_by_assignment";
/** state sort submission by max grade */
private static final String SORTED_SUBMISSION_BY_MAX_GRADE = "sorted_submission_by_max_grade";
/** ******************** student's view assignment submission ****************************** */
/** the assignment object been viewing * */
private static final String VIEW_SUBMISSION_ASSIGNMENT_REFERENCE = "Assignment.view_submission_assignment_reference";
/** the submission text to the assignment * */
private static final String VIEW_SUBMISSION_TEXT = "Assignment.view_submission_text";
/** the submission answer to Honor Pledge * */
private static final String VIEW_SUBMISSION_HONOR_PLEDGE_YES = "Assignment.view_submission_honor_pledge_yes";
/** ***************** student's preview of submission *************************** */
/** the assignment id * */
private static final String PREVIEW_SUBMISSION_ASSIGNMENT_REFERENCE = "preview_submission_assignment_reference";
/** the submission text * */
private static final String PREVIEW_SUBMISSION_TEXT = "preview_submission_text";
/** the submission honor pledge answer * */
private static final String PREVIEW_SUBMISSION_HONOR_PLEDGE_YES = "preview_submission_honor_pledge_yes";
/** the submission attachments * */
private static final String PREVIEW_SUBMISSION_ATTACHMENTS = "preview_attachments";
/** the flag indicate whether the to show the student view or not */
private static final String PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG = "preview_assignment_student_view_hide_flag";
/** the flag indicate whether the to show the assignment info or not */
private static final String PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG = "preview_assignment_assignment_hide_flag";
/** the assignment id */
private static final String PREVIEW_ASSIGNMENT_ASSIGNMENT_ID = "preview_assignment_assignment_id";
/** the assignment content id */
private static final String PREVIEW_ASSIGNMENT_ASSIGNMENTCONTENT_ID = "preview_assignment_assignmentcontent_id";
/** ************** view assignment ***************************************** */
/** the hide assignment flag in the view assignment page * */
private static final String VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG = "view_assignment_hide_assignment_flag";
/** the hide student view flag in the view assignment page * */
private static final String VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG = "view_assignment_hide_student_view_flag";
/** ******************* instructor's view assignment ***************************** */
private static final String VIEW_ASSIGNMENT_ID = "view_assignment_id";
/** ******************* instructor's edit assignment ***************************** */
private static final String EDIT_ASSIGNMENT_ID = "edit_assignment_id";
/** ******************* instructor's delete assignment ids ***************************** */
private static final String DELETE_ASSIGNMENT_IDS = "delete_assignment_ids";
/** ******************* flags controls the grade assignment page layout ******************* */
private static final String GRADE_ASSIGNMENT_EXPAND_FLAG = "grade_assignment_expand_flag";
private static final String GRADE_SUBMISSION_EXPAND_FLAG = "grade_submission_expand_flag";
private static final String GRADE_NO_SUBMISSION_DEFAULT_GRADE = "grade_no_submission_default_grade";
/** ******************* instructor's grade submission ***************************** */
private static final String GRADE_SUBMISSION_ASSIGNMENT_ID = "grade_submission_assignment_id";
private static final String GRADE_SUBMISSION_SUBMISSION_ID = "grade_submission_submission_id";
private static final String GRADE_SUBMISSION_FEEDBACK_COMMENT = "grade_submission_feedback_comment";
private static final String GRADE_SUBMISSION_FEEDBACK_TEXT = "grade_submission_feedback_text";
private static final String GRADE_SUBMISSION_FEEDBACK_ATTACHMENT = "grade_submission_feedback_attachment";
private static final String GRADE_SUBMISSION_GRADE = "grade_submission_grade";
private static final String GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG = "grade_submission_assignment_expand_flag";
private static final String GRADE_SUBMISSION_ALLOW_RESUBMIT = "grade_submission_allow_resubmit";
/** ******************* instructor's export assignment ***************************** */
private static final String EXPORT_ASSIGNMENT_REF = "export_assignment_ref";
private static final String EXPORT_ASSIGNMENT_ID = "export_assignment_id";
/** ****************** instructor's new assignment ****************************** */
private static final String NEW_ASSIGNMENT_TITLE = "new_assignment_title";
// assignment order for default view
private static final String NEW_ASSIGNMENT_ORDER = "new_assignment_order";
// open date
private static final String NEW_ASSIGNMENT_OPENMONTH = "new_assignment_openmonth";
private static final String NEW_ASSIGNMENT_OPENDAY = "new_assignment_openday";
private static final String NEW_ASSIGNMENT_OPENYEAR = "new_assignment_openyear";
private static final String NEW_ASSIGNMENT_OPENHOUR = "new_assignment_openhour";
private static final String NEW_ASSIGNMENT_OPENMIN = "new_assignment_openmin";
private static final String NEW_ASSIGNMENT_OPENAMPM = "new_assignment_openampm";
// due date
private static final String NEW_ASSIGNMENT_DUEMONTH = "new_assignment_duemonth";
private static final String NEW_ASSIGNMENT_DUEDAY = "new_assignment_dueday";
private static final String NEW_ASSIGNMENT_DUEYEAR = "new_assignment_dueyear";
private static final String NEW_ASSIGNMENT_DUEHOUR = "new_assignment_duehour";
private static final String NEW_ASSIGNMENT_DUEMIN = "new_assignment_duemin";
private static final String NEW_ASSIGNMENT_DUEAMPM = "new_assignment_dueampm";
private static final String NEW_ASSIGNMENT_DUEDATE_CALENDAR_ASSIGNMENT_ID = "new_assignment_duedate_calendar_assignment_id";
private static final String NEW_ASSIGNMENT_PAST_DUE_DATE = "new_assignment_past_due_date";
// close date
private static final String NEW_ASSIGNMENT_ENABLECLOSEDATE = "new_assignment_enableclosedate";
private static final String NEW_ASSIGNMENT_CLOSEMONTH = "new_assignment_closemonth";
private static final String NEW_ASSIGNMENT_CLOSEDAY = "new_assignment_closeday";
private static final String NEW_ASSIGNMENT_CLOSEYEAR = "new_assignment_closeyear";
private static final String NEW_ASSIGNMENT_CLOSEHOUR = "new_assignment_closehour";
private static final String NEW_ASSIGNMENT_CLOSEMIN = "new_assignment_closemin";
private static final String NEW_ASSIGNMENT_CLOSEAMPM = "new_assignment_closeampm";
private static final String NEW_ASSIGNMENT_ATTACHMENT = "new_assignment_attachment";
private static final String NEW_ASSIGNMENT_SECTION = "new_assignment_section";
private static final String NEW_ASSIGNMENT_SUBMISSION_TYPE = "new_assignment_submission_type";
private static final String NEW_ASSIGNMENT_GRADE_TYPE = "new_assignment_grade_type";
private static final String NEW_ASSIGNMENT_GRADE_POINTS = "new_assignment_grade_points";
private static final String NEW_ASSIGNMENT_DESCRIPTION = "new_assignment_instructions";
private static final String NEW_ASSIGNMENT_DUE_DATE_SCHEDULED = "new_assignment_due_date_scheduled";
private static final String NEW_ASSIGNMENT_OPEN_DATE_ANNOUNCED = "new_assignment_open_date_announced";
private static final String NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE = "new_assignment_check_add_honor_pledge";
private static final String NEW_ASSIGNMENT_HIDE_OPTION_FLAG = "new_assignment_hide_option_flag";
private static final String NEW_ASSIGNMENT_FOCUS = "new_assignment_focus";
private static final String NEW_ASSIGNMENT_DESCRIPTION_EMPTY = "new_assignment_description_empty";
private static final String NEW_ASSIGNMENT_ADD_TO_GRADEBOOK = "new_assignment_add_to_gradebook";
private static final String NEW_ASSIGNMENT_RANGE = "new_assignment_range";
private static final String NEW_ASSIGNMENT_GROUPS = "new_assignment_groups";
/**************************** assignment year range *************************/
private static final String NEW_ASSIGNMENT_YEAR_RANGE_FROM = "new_assignment_year_range_from";
private static final String NEW_ASSIGNMENT_YEAR_RANGE_TO = "new_assignment_year_range_to";
// submission level of resubmit due time
private static final String ALLOW_RESUBMIT_CLOSEMONTH = "allow_resubmit_closeMonth";
private static final String ALLOW_RESUBMIT_CLOSEDAY = "allow_resubmit_closeDay";
private static final String ALLOW_RESUBMIT_CLOSEYEAR = "allow_resubmit_closeYear";
private static final String ALLOW_RESUBMIT_CLOSEHOUR = "allow_resubmit_closeHour";
private static final String ALLOW_RESUBMIT_CLOSEMIN = "allow_resubmit_closeMin";
private static final String ALLOW_RESUBMIT_CLOSEAMPM = "allow_resubmit_closeAMPM";
private static final String ATTACHMENTS_MODIFIED = "attachments_modified";
/** **************************** instructor's view student submission ***************** */
// the show/hide table based on member id
private static final String STUDENT_LIST_SHOW_TABLE = "STUDENT_LIST_SHOW_TABLE";
/** **************************** student view grade submission id *********** */
private static final String VIEW_GRADE_SUBMISSION_ID = "view_grade_submission_id";
// alert for grade exceeds max grade setting
private static final String GRADE_GREATER_THAN_MAX_ALERT = "grade_greater_than_max_alert";
/** **************************** modes *************************** */
/** The list view of assignments */
private static final String MODE_LIST_ASSIGNMENTS = "lisofass1"; // set in velocity template
/** The student view of an assignment submission */
private static final String MODE_STUDENT_VIEW_SUBMISSION = "Assignment.mode_view_submission";
/** The student view of an assignment submission confirmation */
private static final String MODE_STUDENT_VIEW_SUBMISSION_CONFIRMATION = "Assignment.mode_view_submission_confirmation";
/** The student preview of an assignment submission */
private static final String MODE_STUDENT_PREVIEW_SUBMISSION = "Assignment.mode_student_preview_submission";
/** The student view of graded submission */
private static final String MODE_STUDENT_VIEW_GRADE = "Assignment.mode_student_view_grade";
/** The student view of assignments */
private static final String MODE_STUDENT_VIEW_ASSIGNMENT = "Assignment.mode_student_view_assignment";
/** The instructor view of creating a new assignment or editing an existing one */
private static final String MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT = "Assignment.mode_instructor_new_edit_assignment";
/** The instructor view to reorder assignments */
private static final String MODE_INSTRUCTOR_REORDER_ASSIGNMENT = "reorder";
/** The instructor view to delete an assignment */
private static final String MODE_INSTRUCTOR_DELETE_ASSIGNMENT = "Assignment.mode_instructor_delete_assignment";
/** The instructor view to grade an assignment */
private static final String MODE_INSTRUCTOR_GRADE_ASSIGNMENT = "Assignment.mode_instructor_grade_assignment";
/** The instructor view to grade a submission */
private static final String MODE_INSTRUCTOR_GRADE_SUBMISSION = "Assignment.mode_instructor_grade_submission";
/** The instructor view of preview grading a submission */
private static final String MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION = "Assignment.mode_instructor_preview_grade_submission";
/** The instructor preview of one assignment */
private static final String MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT = "Assignment.mode_instructor_preview_assignments";
/** The instructor view of one assignment */
private static final String MODE_INSTRUCTOR_VIEW_ASSIGNMENT = "Assignment.mode_instructor_view_assignments";
/** The instructor view to list students of an assignment */
private static final String MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT = "lisofass2"; // set in velocity template
/** The instructor view of assignment submission report */
private static final String MODE_INSTRUCTOR_REPORT_SUBMISSIONS = "grarep"; // set in velocity template
/** The instructor view of uploading all from archive file */
private static final String MODE_INSTRUCTOR_UPLOAD_ALL = "uploadAll";
/** The student view of assignment submission report */
private static final String MODE_STUDENT_VIEW = "stuvie"; // set in velocity template
/** ************************* vm names ************************** */
/** The list view of assignments */
private static final String TEMPLATE_LIST_ASSIGNMENTS = "_list_assignments";
/** The student view of assignment */
private static final String TEMPLATE_STUDENT_VIEW_ASSIGNMENT = "_student_view_assignment";
/** The student view of showing an assignment submission */
private static final String TEMPLATE_STUDENT_VIEW_SUBMISSION = "_student_view_submission";
/** The student view of an assignment submission confirmation */
private static final String TEMPLATE_STUDENT_VIEW_SUBMISSION_CONFIRMATION = "_student_view_submission_confirmation";
/** The student preview an assignment submission */
private static final String TEMPLATE_STUDENT_PREVIEW_SUBMISSION = "_student_preview_submission";
/** The student view of graded submission */
private static final String TEMPLATE_STUDENT_VIEW_GRADE = "_student_view_grade";
/** The instructor view to create a new assignment or edit an existing one */
private static final String TEMPLATE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT = "_instructor_new_edit_assignment";
/** The instructor view to reorder the default assignments */
private static final String TEMPLATE_INSTRUCTOR_REORDER_ASSIGNMENT = "_instructor_reorder_assignment";
/** The instructor view to edit assignment */
private static final String TEMPLATE_INSTRUCTOR_DELETE_ASSIGNMENT = "_instructor_delete_assignment";
/** The instructor view to edit assignment */
private static final String TEMPLATE_INSTRUCTOR_GRADE_SUBMISSION = "_instructor_grading_submission";
/** The instructor preview to edit assignment */
private static final String TEMPLATE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION = "_instructor_preview_grading_submission";
/** The instructor view to grade the assignment */
private static final String TEMPLATE_INSTRUCTOR_GRADE_ASSIGNMENT = "_instructor_list_submissions";
/** The instructor preview of assignment */
private static final String TEMPLATE_INSTRUCTOR_PREVIEW_ASSIGNMENT = "_instructor_preview_assignment";
/** The instructor view of assignment */
private static final String TEMPLATE_INSTRUCTOR_VIEW_ASSIGNMENT = "_instructor_view_assignment";
/** The instructor view to edit assignment */
private static final String TEMPLATE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT = "_instructor_student_list_submissions";
/** The instructor view to assignment submission report */
private static final String TEMPLATE_INSTRUCTOR_REPORT_SUBMISSIONS = "_instructor_report_submissions";
/** The instructor view to upload all information from archive file */
private static final String TEMPLATE_INSTRUCTOR_UPLOAD_ALL = "_instructor_uploadAll";
/** The opening mark comment */
private static final String COMMENT_OPEN = "{{";
/** The closing mark for comment */
private static final String COMMENT_CLOSE = "}}";
/** The selected view */
private static final String STATE_SELECTED_VIEW = "state_selected_view";
/** The configuration choice of with grading option or not */
private static final String WITH_GRADES = "with_grades";
/** The alert flag when doing global navigation from improper mode */
private static final String ALERT_GLOBAL_NAVIGATION = "alert_global_navigation";
/** The total list item before paging */
private static final String STATE_PAGEING_TOTAL_ITEMS = "state_paging_total_items";
/** is current user allowed to grade assignment? */
private static final String STATE_ALLOW_GRADE_SUBMISSION = "state_allow_grade_submission";
/** property for previous feedback attachments **/
private static final String PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS = "prop_submission_previous_feedback_attachments";
/** the user and submission list for list of submissions page */
private static final String USER_SUBMISSIONS = "user_submissions";
/** ************************* Taggable constants ************************** */
/** identifier of tagging provider that will provide the appropriate helper */
private static final String PROVIDER_ID = "providerId";
/** Reference to an activity */
private static final String ACTIVITY_REF = "activityRef";
/** Reference to an item */
private static final String ITEM_REF = "itemRef";
/** session attribute for list of decorated tagging providers */
private static final String PROVIDER_LIST = "providerList";
// whether the choice of emails instructor submission notification is available in the installation
private static final String ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS = "assignment.instructor.notifications";
// default for whether or how the instructor receive submission notification emails, none(default)|each|digest
private static final String ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DEFAULT = "assignment.instructor.notifications.default";
/****************************** Upload all screen ***************************/
private static final String UPLOAD_ALL_HAS_SUBMISSION_TEXT = "upload_all_has_submission_text";
private static final String UPLOAD_ALL_HAS_SUBMISSION_ATTACHMENT = "upload_all_has_submission_attachment";
private static final String UPLOAD_ALL_HAS_GRADEFILE = "upload_all_has_gradefile";
private static final String UPLOAD_ALL_HAS_COMMENTS= "upload_all_has_comments";
private static final String UPLOAD_ALL_HAS_FEEDBACK_TEXT= "upload_all_has_feedback_text";
private static final String UPLOAD_ALL_HAS_FEEDBACK_ATTACHMENT = "upload_all_has_feedback_attachment";
private static final String UPLOAD_ALL_RELEASE_GRADES = "upload_all_release_grades";
// this is to track whether the site has multiple assignment, hence if true, show the reorder link
private static final String HAS_MULTIPLE_ASSIGNMENTS = "has_multiple_assignments";
// view all or grouped submission list
private static final String VIEW_SUBMISSION_LIST_OPTION = "view_submission_list_option";
/**
* central place for dispatching the build routines based on the state name
*/
public String buildMainPanelContext(VelocityPortlet portlet, Context context, RunData data, SessionState state)
{
String template = null;
context.put("tlang", rb);
context.put("cheffeedbackhelper", this);
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
// allow add assignment?
boolean allowAddAssignment = AssignmentService.allowAddAssignment(contextString);
context.put("allowAddAssignment", Boolean.valueOf(allowAddAssignment));
Object allowGradeSubmission = state.getAttribute(STATE_ALLOW_GRADE_SUBMISSION);
// allow update site?
context.put("allowUpdateSite", Boolean
.valueOf(SiteService.allowUpdateSite((String) state.getAttribute(STATE_CONTEXT_STRING))));
// allow all.groups?
boolean allowAllGroups = AssignmentService.allowAllGroups(contextString);
context.put("allowAllGroups", Boolean.valueOf(allowAllGroups));
//Is the review service allowed?
Site s = null;
try {
s = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING));
}
catch (IdUnusedException iue) {
Log.warn("chef", "Site not found!");
}
getContentReviewService();
if (allowReviewService && contentReviewService.isSiteAcceptable(s)) {
context.put("allowReviewService", allowReviewService);
} else {
context.put("allowReviewService", false);
}
// grading option
context.put("withGrade", state.getAttribute(WITH_GRADES));
String mode = (String) state.getAttribute(STATE_MODE);
if (!mode.equals(MODE_LIST_ASSIGNMENTS))
{
// allow grade assignment?
if (state.getAttribute(STATE_ALLOW_GRADE_SUBMISSION) == null)
{
state.setAttribute(STATE_ALLOW_GRADE_SUBMISSION, Boolean.FALSE);
}
context.put("allowGradeSubmission", state.getAttribute(STATE_ALLOW_GRADE_SUBMISSION));
}
if (mode.equals(MODE_LIST_ASSIGNMENTS))
{
// build the context for the student assignment view
template = build_list_assignments_context(portlet, context, data, state);
}
else if (mode.equals(MODE_STUDENT_VIEW_ASSIGNMENT))
{
// the student view of assignment
template = build_student_view_assignment_context(portlet, context, data, state);
}
else if (mode.equals(MODE_STUDENT_VIEW_SUBMISSION))
{
// disable auto-updates while leaving the list view
justDelivered(state);
// build the context for showing one assignment submission
template = build_student_view_submission_context(portlet, context, data, state);
}
else if (mode.equals(MODE_STUDENT_VIEW_SUBMISSION_CONFIRMATION))
{
// build the context for showing one assignment submission confirmation
template = build_student_view_submission_confirmation_context(portlet, context, data, state);
}
else if (mode.equals(MODE_STUDENT_PREVIEW_SUBMISSION))
{
// build the context for showing one assignment submission
template = build_student_preview_submission_context(portlet, context, data, state);
}
else if (mode.equals(MODE_STUDENT_VIEW_GRADE))
{
// disable auto-updates while leaving the list view
justDelivered(state);
// build the context for showing one graded submission
template = build_student_view_grade_context(portlet, context, data, state);
}
else if (mode.equals(MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT))
{
// allow add assignment?
boolean allowAddSiteAssignment = AssignmentService.allowAddSiteAssignment(contextString);
context.put("allowAddSiteAssignment", Boolean.valueOf(allowAddSiteAssignment));
// disable auto-updates while leaving the list view
justDelivered(state);
// build the context for the instructor's create new assignment view
template = build_instructor_new_edit_assignment_context(portlet, context, data, state);
}
else if (mode.equals(MODE_INSTRUCTOR_DELETE_ASSIGNMENT))
{
if (state.getAttribute(DELETE_ASSIGNMENT_IDS) != null)
{
// disable auto-updates while leaving the list view
justDelivered(state);
// build the context for the instructor's delete assignment
template = build_instructor_delete_assignment_context(portlet, context, data, state);
}
}
else if (mode.equals(MODE_INSTRUCTOR_GRADE_ASSIGNMENT))
{
if (allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue())
{
// if allowed for grading, build the context for the instructor's grade assignment
template = build_instructor_grade_assignment_context(portlet, context, data, state);
}
}
else if (mode.equals(MODE_INSTRUCTOR_GRADE_SUBMISSION))
{
if (allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue())
{
// if allowed for grading, disable auto-updates while leaving the list view
justDelivered(state);
// build the context for the instructor's grade submission
template = build_instructor_grade_submission_context(portlet, context, data, state);
}
}
else if (mode.equals(MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION))
{
if ( allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue())
{
// if allowed for grading, build the context for the instructor's preview grade submission
template = build_instructor_preview_grade_submission_context(portlet, context, data, state);
}
}
else if (mode.equals(MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT))
{
// build the context for preview one assignment
template = build_instructor_preview_assignment_context(portlet, context, data, state);
}
else if (mode.equals(MODE_INSTRUCTOR_VIEW_ASSIGNMENT))
{
// disable auto-updates while leaving the list view
justDelivered(state);
// build the context for view one assignment
template = build_instructor_view_assignment_context(portlet, context, data, state);
}
else if (mode.equals(MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT))
{
if ( allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue())
{
// if allowed for grading, build the context for the instructor's create new assignment view
template = build_instructor_view_students_assignment_context(portlet, context, data, state);
}
}
else if (mode.equals(MODE_INSTRUCTOR_REPORT_SUBMISSIONS))
{
if ( allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue())
{
// if allowed for grading, build the context for the instructor's view of report submissions
template = build_instructor_report_submissions(portlet, context, data, state);
}
}
else if (mode.equals(MODE_INSTRUCTOR_UPLOAD_ALL))
{
if ( allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue())
{
// if allowed for grading, build the context for the instructor's view of uploading all info from archive file
template = build_instructor_upload_all(portlet, context, data, state);
}
}
else if (mode.equals(MODE_INSTRUCTOR_REORDER_ASSIGNMENT))
{
// disable auto-updates while leaving the list view
justDelivered(state);
// build the context for the instructor's create new assignment view
template = build_instructor_reorder_assignment_context(portlet, context, data, state);
}
if (template == null)
{
// default to student list view
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
template = build_list_assignments_context(portlet, context, data, state);
}
// this is a check for seeing if there are any assignments. The check is used to see if we display a Reorder link in the vm files
if (state.getAttribute(HAS_MULTIPLE_ASSIGNMENTS) != null)
{
context.put("assignmentscheck", state.getAttribute(HAS_MULTIPLE_ASSIGNMENTS));
}
return template;
} // buildNormalContext
/**
* build the student view of showing an assignment submission
*/
protected String build_student_view_submission_context(VelocityPortlet portlet, Context context, RunData data,
SessionState state)
{
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
context.put("context", contextString);
User user = (User) state.getAttribute(STATE_USER);
String currentAssignmentReference = (String) state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE);
Assignment assignment = null;
try
{
assignment = AssignmentService.getAssignment(currentAssignmentReference);
context.put("assignment", assignment);
context.put("canSubmit", Boolean.valueOf(AssignmentService.canSubmit(contextString, assignment)));
if (assignment.getContent().getTypeOfSubmission() == Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION)
{
context.put("nonElectronicType", Boolean.TRUE);
}
AssignmentSubmission s = AssignmentService.getSubmission(assignment.getReference(), user);
if (s != null)
{
context.put("submission", s);
ResourceProperties p = s.getProperties();
if (p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT) != null)
{
context.put("prevFeedbackText", p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT));
}
if (p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT) != null)
{
context.put("prevFeedbackComment", p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT));
}
if (p.getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS) != null)
{
context.put("prevFeedbackAttachments", getPrevFeedbackAttachments(p));
}
}
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannot_find_assignment"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot16"));
}
TaggingManager taggingManager = (TaggingManager) ComponentManager
.get("org.sakaiproject.assignment.taggable.api.TaggingManager");
if (taggingManager.isTaggable() && assignment != null)
{
addProviders(context, state);
addActivity(context, assignment);
context.put("taggable", Boolean.valueOf(true));
}
// name value pairs for the vm
context.put("name_submission_text", VIEW_SUBMISSION_TEXT);
context.put("value_submission_text", state.getAttribute(VIEW_SUBMISSION_TEXT));
context.put("name_submission_honor_pledge_yes", VIEW_SUBMISSION_HONOR_PLEDGE_YES);
context.put("value_submission_honor_pledge_yes", state.getAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES));
context.put("attachments", state.getAttribute(ATTACHMENTS));
context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE));
context.put("currentTime", TimeService.newTime());
boolean allowSubmit = AssignmentService.allowAddSubmission((String) state.getAttribute(STATE_CONTEXT_STRING));
if (!allowSubmit)
{
addAlert(state, rb.getString("not_allowed_to_submit"));
}
context.put("allowSubmit", new Boolean(allowSubmit));
String template = (String) getContext(data).get("template");
return template + TEMPLATE_STUDENT_VIEW_SUBMISSION;
} // build_student_view_submission_context
/**
* build the student view of showing an assignment submission confirmation
*/
protected String build_student_view_submission_confirmation_context(VelocityPortlet portlet, Context context, RunData data,
SessionState state)
{
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
context.put("context", contextString);
// get user information
User user = (User) state.getAttribute(STATE_USER);
context.put("user_name", user.getDisplayName());
context.put("user_id", user.getDisplayId());
if (StringUtil.trimToNull(user.getEmail()) != null)
context.put("user_email", user.getEmail());
// get site information
try
{
// get current site
Site site = SiteService.getSite(contextString);
context.put("site_title", site.getTitle());
}
catch (Exception ignore)
{
Log.warn("chef", this + ignore.getMessage() + " siteId= " + contextString);
}
// get assignment and submission information
String currentAssignmentReference = (String) state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE);
try
{
Assignment currentAssignment = AssignmentService.getAssignment(currentAssignmentReference);
context.put("assignment_title", currentAssignment.getTitle());
AssignmentSubmission s = AssignmentService.getSubmission(currentAssignment.getReference(), user);
if (s != null)
{
context.put("submitted", Boolean.valueOf(s.getSubmitted()));
context.put("submission_id", s.getId());
if (s.getTimeSubmitted() != null)
{
context.put("submit_time", s.getTimeSubmitted().toStringLocalFull());
}
List attachments = s.getSubmittedAttachments();
if (attachments != null && attachments.size()>0)
{
context.put("submit_attachments", s.getSubmittedAttachments());
}
context.put("submit_text", StringUtil.trimToNull(s.getSubmittedText()));
context.put("email_confirmation", Boolean.valueOf(ServerConfigurationService.getBoolean("assignment.submission.confirmation.email", true)));
}
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannot_find_assignment"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot16"));
}
String template = (String) getContext(data).get("template");
return template + TEMPLATE_STUDENT_VIEW_SUBMISSION_CONFIRMATION;
} // build_student_view_submission_confirmation_context
/**
* build the student view of assignment
*/
protected String build_student_view_assignment_context(VelocityPortlet portlet, Context context, RunData data,
SessionState state)
{
context.put("context", state.getAttribute(STATE_CONTEXT_STRING));
String aId = (String) state.getAttribute(VIEW_ASSIGNMENT_ID);
Assignment assignment = null;
try
{
assignment = AssignmentService.getAssignment(aId);
context.put("assignment", assignment);
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannot_find_assignment"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot14"));
}
TaggingManager taggingManager = (TaggingManager) ComponentManager
.get("org.sakaiproject.assignment.taggable.api.TaggingManager");
if (taggingManager.isTaggable() && assignment != null)
{
addProviders(context, state);
addActivity(context, assignment);
context.put("taggable", Boolean.valueOf(true));
}
context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE));
context.put("gradeTypeTable", gradeTypeTable());
context.put("userDirectoryService", UserDirectoryService.getInstance());
String template = (String) getContext(data).get("template");
return template + TEMPLATE_STUDENT_VIEW_ASSIGNMENT;
} // build_student_view_submission_context
/**
* build the student preview of showing an assignment submission
*/
protected String build_student_preview_submission_context(VelocityPortlet portlet, Context context, RunData data,
SessionState state)
{
User user = (User) state.getAttribute(STATE_USER);
String aReference = (String) state.getAttribute(PREVIEW_SUBMISSION_ASSIGNMENT_REFERENCE);
try
{
context.put("assignment", AssignmentService.getAssignment(aReference));
context.put("submission", AssignmentService.getSubmission(aReference, user));
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin3"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot16"));
}
context.put("text", state.getAttribute(PREVIEW_SUBMISSION_TEXT));
context.put("honor_pledge_yes", state.getAttribute(PREVIEW_SUBMISSION_HONOR_PLEDGE_YES));
context.put("attachments", state.getAttribute(PREVIEW_SUBMISSION_ATTACHMENTS));
context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE));
String template = (String) getContext(data).get("template");
return template + TEMPLATE_STUDENT_PREVIEW_SUBMISSION;
} // build_student_preview_submission_context
/**
* build the student view of showing a graded submission
*/
protected String build_student_view_grade_context(VelocityPortlet portlet, Context context, RunData data, SessionState state)
{
context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE));
AssignmentSubmission submission = null;
try
{
submission = AssignmentService.getSubmission((String) state.getAttribute(VIEW_GRADE_SUBMISSION_ID));
Assignment assignment = submission.getAssignment();
context.put("assignment", assignment);
if (assignment.getContent().getTypeOfSubmission() == Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION)
{
context.put("nonElectronicType", Boolean.TRUE);
}
context.put("submission", submission);
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin5"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("not_allowed_to_get_submission"));
}
TaggingManager taggingManager = (TaggingManager) ComponentManager
.get("org.sakaiproject.assignment.taggable.api.TaggingManager");
if (taggingManager.isTaggable() && submission != null)
{
AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager
.get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer");
List<DecoratedTaggingProvider> providers = addProviders(context, state);
List<TaggingHelperInfo> itemHelpers = new ArrayList<TaggingHelperInfo>();
for (DecoratedTaggingProvider provider : providers)
{
TaggingHelperInfo helper = provider.getProvider()
.getItemHelperInfo(
assignmentActivityProducer.getItem(
submission,
UserDirectoryService.getCurrentUser()
.getId()).getReference());
if (helper != null)
{
itemHelpers.add(helper);
}
}
addItem(context, submission, UserDirectoryService.getCurrentUser().getId());
addActivity(context, submission.getAssignment());
context.put("itemHelpers", itemHelpers);
context.put("taggable", Boolean.valueOf(true));
}
String template = (String) getContext(data).get("template");
return template + TEMPLATE_STUDENT_VIEW_GRADE;
} // build_student_view_grade_context
/**
* build the view of assignments list
*/
protected String build_list_assignments_context(VelocityPortlet portlet, Context context, RunData data, SessionState state)
{
TaggingManager taggingManager = (TaggingManager) ComponentManager
.get("org.sakaiproject.assignment.taggable.api.TaggingManager");
if (taggingManager.isTaggable())
{
context.put("producer", ComponentManager
.get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer"));
context.put("providers", taggingManager.getProviders());
context.put("taggable", Boolean.valueOf(true));
}
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
context.put("contextString", contextString);
context.put("user", state.getAttribute(STATE_USER));
context.put("service", AssignmentService.getInstance());
context.put("TimeService", TimeService.getInstance());
context.put("LongObject", new Long(TimeService.newTime().getTime()));
context.put("currentTime", TimeService.newTime());
String sortedBy = (String) state.getAttribute(SORTED_BY);
String sortedAsc = (String) state.getAttribute(SORTED_ASC);
// clean sort criteria
if (sortedBy.equals(SORTED_BY_GROUP_TITLE) || sortedBy.equals(SORTED_BY_GROUP_DESCRIPTION))
{
sortedBy = SORTED_BY_DUEDATE;
sortedAsc = Boolean.TRUE.toString();
state.setAttribute(SORTED_BY, sortedBy);
state.setAttribute(SORTED_ASC, sortedAsc);
}
context.put("sortedBy", sortedBy);
context.put("sortedAsc", sortedAsc);
if (state.getAttribute(STATE_SELECTED_VIEW) != null)
{
context.put("view", state.getAttribute(STATE_SELECTED_VIEW));
}
Hashtable assignments_submissions = new Hashtable();
List assignments = prepPage(state);
context.put("assignments", assignments.iterator());
// allow get assignment
context.put("allowGetAssignment", Boolean.valueOf(AssignmentService.allowGetAssignment(contextString)));
// test whether user user can grade at least one assignment
// and update the state variable.
boolean allowGradeSubmission = false;
for (Iterator aIterator=assignments.iterator(); !allowGradeSubmission && aIterator.hasNext(); )
{
if (AssignmentService.allowGradeSubmission(((Assignment) aIterator.next()).getReference()))
{
allowGradeSubmission = true;
}
}
state.setAttribute(STATE_ALLOW_GRADE_SUBMISSION, new Boolean(allowGradeSubmission));
context.put("allowGradeSubmission", state.getAttribute(STATE_ALLOW_GRADE_SUBMISSION));
// allow remove assignment?
boolean allowRemoveAssignment = false;
for (Iterator aIterator=assignments.iterator(); !allowRemoveAssignment && aIterator.hasNext(); )
{
if (AssignmentService.allowRemoveAssignment(((Assignment) aIterator.next()).getReference()))
{
allowRemoveAssignment = true;
}
}
context.put("allowRemoveAssignment", Boolean.valueOf(allowRemoveAssignment));
add2ndToolbarFields(data, context);
// inform the observing courier that we just updated the page...
// if there are pending requests to do so they can be cleared
justDelivered(state);
pagingInfoToContext(state, context);
// put site object into context
try
{
// get current site
Site site = SiteService.getSite(contextString);
context.put("site", site);
// any group in the site?
Collection groups = site.getGroups();
context.put("groups", (groups != null && groups.size()>0)?Boolean.TRUE:Boolean.FALSE);
// add active user list
AuthzGroup realm = AuthzGroupService.getAuthzGroup(SiteService.siteReference(contextString));
if (realm != null)
{
context.put("activeUserIds", realm.getUsers());
}
}
catch (Exception ignore)
{
Log.warn("chef", this + ignore.getMessage() + " siteId= " + contextString);
}
boolean allowSubmit = AssignmentService.allowAddSubmission(contextString);
context.put("allowSubmit", new Boolean(allowSubmit));
// related to resubmit settings
context.put("allowResubmitNumberProp", AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
context.put("allowResubmitCloseTimeProp", AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME);
// the type int for non-electronic submission
context.put("typeNonElectronic", Integer.valueOf(Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION));
String template = (String) getContext(data).get("template");
return template + TEMPLATE_LIST_ASSIGNMENTS;
} // build_list_assignments_context
private HashSet<String> getSubmittersIdSet(List submissions)
{
HashSet<String> rv = new HashSet<String>();
for (Iterator iSubmissions=submissions.iterator(); iSubmissions.hasNext();)
{
List submitterIds = ((AssignmentSubmission) iSubmissions.next()).getSubmitterIds();
if (submitterIds != null && submitterIds.size() > 0)
{
rv.add((String) submitterIds.get(0));
}
}
return rv;
}
private HashSet<String> getAllowAddSubmissionUsersIdSet(List users)
{
HashSet<String> rv = new HashSet<String>();
for (Iterator iUsers=users.iterator(); iUsers.hasNext();)
{
rv.add(((User) iUsers.next()).getId());
}
return rv;
}
/**
* build the instructor view of creating a new assignment or editing an existing one
*/
protected String build_instructor_new_edit_assignment_context(VelocityPortlet portlet, Context context, RunData data,
SessionState state)
{
// is the assignment an new assignment
String assignmentId = (String) state.getAttribute(EDIT_ASSIGNMENT_ID);
if (assignmentId != null)
{
try
{
Assignment a = AssignmentService.getAssignment(assignmentId);
context.put("assignment", a);
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin3") + ": " + assignmentId);
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot14") + ": " + assignmentId);
}
}
// set up context variables
setAssignmentFormContext(state, context);
context.put("fField", state.getAttribute(NEW_ASSIGNMENT_FOCUS));
String sortedBy = (String) state.getAttribute(SORTED_BY);
String sortedAsc = (String) state.getAttribute(SORTED_ASC);
context.put("sortedBy", sortedBy);
context.put("sortedAsc", sortedAsc);
String template = (String) getContext(data).get("template");
return template + TEMPLATE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT;
} // build_instructor_new_assignment_context
protected void setAssignmentFormContext(SessionState state, Context context)
{
// put the names and values into vm file
context.put("name_UseReviewService", NEW_ASSIGNMENT_USE_REVIEW_SERVICE);
context.put("name_AllowStudentView", NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW);
context.put("name_title", NEW_ASSIGNMENT_TITLE);
context.put("name_order", NEW_ASSIGNMENT_ORDER);
context.put("name_OpenMonth", NEW_ASSIGNMENT_OPENMONTH);
context.put("name_OpenDay", NEW_ASSIGNMENT_OPENDAY);
context.put("name_OpenYear", NEW_ASSIGNMENT_OPENYEAR);
context.put("name_OpenHour", NEW_ASSIGNMENT_OPENHOUR);
context.put("name_OpenMin", NEW_ASSIGNMENT_OPENMIN);
context.put("name_OpenAMPM", NEW_ASSIGNMENT_OPENAMPM);
context.put("name_DueMonth", NEW_ASSIGNMENT_DUEMONTH);
context.put("name_DueDay", NEW_ASSIGNMENT_DUEDAY);
context.put("name_DueYear", NEW_ASSIGNMENT_DUEYEAR);
context.put("name_DueHour", NEW_ASSIGNMENT_DUEHOUR);
context.put("name_DueMin", NEW_ASSIGNMENT_DUEMIN);
context.put("name_DueAMPM", NEW_ASSIGNMENT_DUEAMPM);
context.put("name_EnableCloseDate", NEW_ASSIGNMENT_ENABLECLOSEDATE);
context.put("name_CloseMonth", NEW_ASSIGNMENT_CLOSEMONTH);
context.put("name_CloseDay", NEW_ASSIGNMENT_CLOSEDAY);
context.put("name_CloseYear", NEW_ASSIGNMENT_CLOSEYEAR);
context.put("name_CloseHour", NEW_ASSIGNMENT_CLOSEHOUR);
context.put("name_CloseMin", NEW_ASSIGNMENT_CLOSEMIN);
context.put("name_CloseAMPM", NEW_ASSIGNMENT_CLOSEAMPM);
context.put("name_Section", NEW_ASSIGNMENT_SECTION);
context.put("name_SubmissionType", NEW_ASSIGNMENT_SUBMISSION_TYPE);
context.put("name_GradeType", NEW_ASSIGNMENT_GRADE_TYPE);
context.put("name_GradePoints", NEW_ASSIGNMENT_GRADE_POINTS);
context.put("name_Description", NEW_ASSIGNMENT_DESCRIPTION);
// do not show the choice when there is no Schedule tool yet
if (state.getAttribute(CALENDAR) != null)
context.put("name_CheckAddDueDate", ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE);
//don't show the choice when there is no Announcement tool yet
if (state.getAttribute(ANNOUNCEMENT_CHANNEL) != null)
context.put("name_CheckAutoAnnounce", ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE);
context.put("name_CheckAddHonorPledge", NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE);
// number of resubmissions allowed
context.put("name_allowResubmitNumber", AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
// set the values
context.put("value_year_from", state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_FROM));
context.put("value_year_to", state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_TO));
context.put("value_title", state.getAttribute(NEW_ASSIGNMENT_TITLE));
context.put("value_position_order", state.getAttribute(NEW_ASSIGNMENT_ORDER));
context.put("value_OpenMonth", state.getAttribute(NEW_ASSIGNMENT_OPENMONTH));
context.put("value_OpenDay", state.getAttribute(NEW_ASSIGNMENT_OPENDAY));
context.put("value_OpenYear", state.getAttribute(NEW_ASSIGNMENT_OPENYEAR));
context.put("value_OpenHour", state.getAttribute(NEW_ASSIGNMENT_OPENHOUR));
context.put("value_OpenMin", state.getAttribute(NEW_ASSIGNMENT_OPENMIN));
context.put("value_OpenAMPM", state.getAttribute(NEW_ASSIGNMENT_OPENAMPM));
context.put("value_DueMonth", state.getAttribute(NEW_ASSIGNMENT_DUEMONTH));
context.put("value_DueDay", state.getAttribute(NEW_ASSIGNMENT_DUEDAY));
context.put("value_DueYear", state.getAttribute(NEW_ASSIGNMENT_DUEYEAR));
context.put("value_DueHour", state.getAttribute(NEW_ASSIGNMENT_DUEHOUR));
context.put("value_DueMin", state.getAttribute(NEW_ASSIGNMENT_DUEMIN));
context.put("value_DueAMPM", state.getAttribute(NEW_ASSIGNMENT_DUEAMPM));
context.put("value_EnableCloseDate", state.getAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE));
context.put("value_CloseMonth", state.getAttribute(NEW_ASSIGNMENT_CLOSEMONTH));
context.put("value_CloseDay", state.getAttribute(NEW_ASSIGNMENT_CLOSEDAY));
context.put("value_CloseYear", state.getAttribute(NEW_ASSIGNMENT_CLOSEYEAR));
context.put("value_CloseHour", state.getAttribute(NEW_ASSIGNMENT_CLOSEHOUR));
context.put("value_CloseMin", state.getAttribute(NEW_ASSIGNMENT_CLOSEMIN));
context.put("value_CloseAMPM", state.getAttribute(NEW_ASSIGNMENT_CLOSEAMPM));
context.put("value_Sections", state.getAttribute(NEW_ASSIGNMENT_SECTION));
context.put("value_SubmissionType", state.getAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE));
context.put("value_totalSubmissionTypes", Assignment.SUBMISSION_TYPES.length);
context.put("value_GradeType", state.getAttribute(NEW_ASSIGNMENT_GRADE_TYPE));
// format to show one decimal place
String maxGrade = (String) state.getAttribute(NEW_ASSIGNMENT_GRADE_POINTS);
context.put("value_GradePoints", displayGrade(state, maxGrade));
context.put("value_Description", state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION));
// Keep the use review service setting
context.put("value_UseReviewService", state.getAttribute(NEW_ASSIGNMENT_USE_REVIEW_SERVICE));
context.put("value_AllowStudentView", state.getAttribute(NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW));
// don't show the choice when there is no Schedule tool yet
if (state.getAttribute(CALENDAR) != null)
context.put("value_CheckAddDueDate", state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE));
// don't show the choice when there is no Announcement tool yet
if (state.getAttribute(ANNOUNCEMENT_CHANNEL) != null)
context.put("value_CheckAutoAnnounce", state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE));
String s = (String) state.getAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE);
if (s == null) s = "1";
context.put("value_CheckAddHonorPledge", s);
// number of resubmissions allowed
if (state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null)
{
context.put("value_allowResubmitNumber", Integer.valueOf((String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER)));
}
else
{
// defaults to 0
context.put("value_allowResubmitNumber", Integer.valueOf(0));
}
// get all available assignments from Gradebook tool except for those created from
boolean gradebookExists = isGradebookDefined();
if (gradebookExists)
{
GradebookService g = (GradebookService) (org.sakaiproject.service.gradebook.shared.GradebookService) ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService");
String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext();
try
{
// get all assignments in Gradebook
List gradebookAssignments = g.getAssignments(gradebookUid);
List gradebookAssignmentsExceptSamigo = new Vector();
// filtering out those from Samigo
for (Iterator i=gradebookAssignments.iterator(); i.hasNext();)
{
org.sakaiproject.service.gradebook.shared.Assignment gAssignment = (org.sakaiproject.service.gradebook.shared.Assignment) i.next();
if (!gAssignment.isExternallyMaintained() || gAssignment.isExternallyMaintained() && gAssignment.getExternalAppName().equals(getToolTitle()))
{
gradebookAssignmentsExceptSamigo.add(gAssignment);
}
}
context.put("gradebookAssignments", gradebookAssignmentsExceptSamigo);
if (StringUtil.trimToNull((String) state.getAttribute(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK)) == null)
{
state.setAttribute(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, AssignmentService.GRADEBOOK_INTEGRATION_NO);
}
context.put("withGradebook", Boolean.TRUE);
// offer the gradebook integration choice only in the Assignments with Grading tool
boolean withGrade = ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue();
if (withGrade)
{
context.put("name_Addtogradebook", AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK);
context.put("name_AssociateGradebookAssignment", AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT);
}
context.put("gradebookChoice", state.getAttribute(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK));
context.put("gradebookChoice_no", AssignmentService.GRADEBOOK_INTEGRATION_NO);
context.put("gradebookChoice_add", AssignmentService.GRADEBOOK_INTEGRATION_ADD);
context.put("gradebookChoice_associate", AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE);
context.put("associateGradebookAssignment", state.getAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT));
}
catch (Exception e)
{
// not able to link to Gradebook
Log.warn("chef", this + e.getMessage());
}
if (StringUtil.trimToNull((String) state.getAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK)) == null)
{
state.setAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, AssignmentService.GRADEBOOK_INTEGRATION_NO);
}
}
context.put("monthTable", monthTable());
context.put("gradeTypeTable", gradeTypeTable());
context.put("submissionTypeTable", submissionTypeTable());
context.put("hide_assignment_option_flag", state.getAttribute(NEW_ASSIGNMENT_HIDE_OPTION_FLAG));
context.put("attachments", state.getAttribute(ATTACHMENTS));
context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE));
String range = StringUtil.trimToNull((String) state.getAttribute(NEW_ASSIGNMENT_RANGE));
if (range != null)
{
context.put("range", range);
}
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
// put site object into context
try
{
// get current site
Site site = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING));
context.put("site", site);
}
catch (Exception ignore)
{
}
if (AssignmentService.getAllowGroupAssignments())
{
Collection groupsAllowAddAssignment = AssignmentService.getGroupsAllowAddAssignment(contextString);
if (range == null)
{
if (AssignmentService.allowAddSiteAssignment(contextString))
{
// default to make site selection
context.put("range", "site");
}
else if (groupsAllowAddAssignment.size() > 0)
{
// to group otherwise
context.put("range", "groups");
}
}
// group list which user can add message to
if (groupsAllowAddAssignment.size() > 0)
{
String sort = (String) state.getAttribute(SORTED_BY);
String asc = (String) state.getAttribute(SORTED_ASC);
if (sort == null || (!sort.equals(SORTED_BY_GROUP_TITLE) && !sort.equals(SORTED_BY_GROUP_DESCRIPTION)))
{
sort = SORTED_BY_GROUP_TITLE;
asc = Boolean.TRUE.toString();
state.setAttribute(SORTED_BY, sort);
state.setAttribute(SORTED_ASC, asc);
}
context.put("groups", new SortedIterator(groupsAllowAddAssignment.iterator(), new AssignmentComparator(state, sort, asc)));
context.put("assignmentGroups", state.getAttribute(NEW_ASSIGNMENT_GROUPS));
}
}
context.put("allowGroupAssignmentsInGradebook", new Boolean(AssignmentService.getAllowGroupAssignmentsInGradebook()));
// the notification email choices
if (state.getAttribute(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS) != null && ((Boolean) state.getAttribute(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS)).booleanValue())
{
context.put("name_assignment_instructor_notifications", ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS);
if (state.getAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE) == null)
{
// set the notification value using site default
state.setAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE, state.getAttribute(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DEFAULT));
}
context.put("value_assignment_instructor_notifications", state.getAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE));
// the option values
context.put("value_assignment_instructor_notifications_none", Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_NONE);
context.put("value_assignment_instructor_notifications_each", Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_EACH);
context.put("value_assignment_instructor_notifications_digest", Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DIGEST);
}
} // setAssignmentFormContext
/**
* build the instructor view of create a new assignment
*/
protected String build_instructor_preview_assignment_context(VelocityPortlet portlet, Context context, RunData data,
SessionState state)
{
context.put("time", TimeService.newTime());
context.put("user", UserDirectoryService.getCurrentUser());
context.put("value_Title", (String) state.getAttribute(NEW_ASSIGNMENT_TITLE));
context.put("name_order", NEW_ASSIGNMENT_ORDER);
context.put("value_position_order", (String) state.getAttribute(NEW_ASSIGNMENT_ORDER));
Time openTime = getOpenTime(state);
context.put("value_OpenDate", openTime);
// due time
int dueMonth = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEMONTH)).intValue();
int dueDay = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEDAY)).intValue();
int dueYear = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEYEAR)).intValue();
int dueHour = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEHOUR)).intValue();
int dueMin = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEMIN)).intValue();
String dueAMPM = (String) state.getAttribute(NEW_ASSIGNMENT_DUEAMPM);
if ((dueAMPM.equals("PM")) && (dueHour != 12))
{
dueHour = dueHour + 12;
}
if ((dueHour == 12) && (dueAMPM.equals("AM")))
{
dueHour = 0;
}
Time dueTime = TimeService.newTimeLocal(dueYear, dueMonth, dueDay, dueHour, dueMin, 0, 0);
context.put("value_DueDate", dueTime);
// close time
Time closeTime = TimeService.newTime();
Boolean enableCloseDate = (Boolean) state.getAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE);
context.put("value_EnableCloseDate", enableCloseDate);
if ((enableCloseDate).booleanValue())
{
int closeMonth = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEMONTH)).intValue();
int closeDay = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEDAY)).intValue();
int closeYear = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEYEAR)).intValue();
int closeHour = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEHOUR)).intValue();
int closeMin = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEMIN)).intValue();
String closeAMPM = (String) state.getAttribute(NEW_ASSIGNMENT_CLOSEAMPM);
if ((closeAMPM.equals("PM")) && (closeHour != 12))
{
closeHour = closeHour + 12;
}
if ((closeHour == 12) && (closeAMPM.equals("AM")))
{
closeHour = 0;
}
closeTime = TimeService.newTimeLocal(closeYear, closeMonth, closeDay, closeHour, closeMin, 0, 0);
context.put("value_CloseDate", closeTime);
}
context.put("value_Sections", state.getAttribute(NEW_ASSIGNMENT_SECTION));
context.put("value_SubmissionType", state.getAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE));
context.put("value_GradeType", state.getAttribute(NEW_ASSIGNMENT_GRADE_TYPE));
String maxGrade = (String) state.getAttribute(NEW_ASSIGNMENT_GRADE_POINTS);
context.put("value_GradePoints", displayGrade(state, maxGrade));
context.put("value_Description", state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION));
context.put("value_CheckAddDueDate", state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE));
context.put("value_CheckAutoAnnounce", state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE));
context.put("value_CheckAddHonorPledge", state.getAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE));
// get all available assignments from Gradebook tool except for those created from
if (isGradebookDefined())
{
context.put("gradebookChoice", state.getAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK));
context.put("associateGradebookAssignment", state.getAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT));
}
context.put("monthTable", monthTable());
context.put("gradeTypeTable", gradeTypeTable());
context.put("submissionTypeTable", submissionTypeTable());
context.put("hide_assignment_option_flag", state.getAttribute(NEW_ASSIGNMENT_HIDE_OPTION_FLAG));
context.put("attachments", state.getAttribute(ATTACHMENTS));
context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE));
context.put("preview_assignment_assignment_hide_flag", state.getAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG));
context.put("preview_assignment_student_view_hide_flag", state.getAttribute(PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG));
String assignmentId = StringUtil.trimToNull((String) state.getAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_ID));
if (assignmentId != null)
{
// editing existing assignment
context.put("value_assignment_id", assignmentId);
try
{
Assignment a = AssignmentService.getAssignment(assignmentId);
context.put("isDraft", Boolean.valueOf(a.getDraft()));
}
catch (Exception e)
{
Log.warn("chef", this + e.getMessage() + assignmentId);
}
}
else
{
// new assignment
context.put("isDraft", Boolean.TRUE);
}
context.put("value_assignmentcontent_id", state.getAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENTCONTENT_ID));
context.put("currentTime", TimeService.newTime());
String template = (String) getContext(data).get("template");
return template + TEMPLATE_INSTRUCTOR_PREVIEW_ASSIGNMENT;
} // build_instructor_preview_assignment_context
/**
* build the instructor view to delete an assignment
*/
protected String build_instructor_delete_assignment_context(VelocityPortlet portlet, Context context, RunData data,
SessionState state)
{
Vector assignments = new Vector();
Vector assignmentIds = (Vector) state.getAttribute(DELETE_ASSIGNMENT_IDS);
for (int i = 0; i < assignmentIds.size(); i++)
{
try
{
Assignment a = AssignmentService.getAssignment((String) assignmentIds.get(i));
Iterator submissions = AssignmentService.getSubmissions(a).iterator();
if (submissions.hasNext())
{
// if there is submission to the assignment, show the alert
addAlert(state, rb.getString("areyousur") + " \"" + a.getTitle() + "\" " + rb.getString("whihassub") + "\n");
}
assignments.add(a);
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin3"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot14"));
}
}
context.put("assignments", assignments);
context.put("service", AssignmentService.getInstance());
context.put("currentTime", TimeService.newTime());
String template = (String) getContext(data).get("template");
return template + TEMPLATE_INSTRUCTOR_DELETE_ASSIGNMENT;
} // build_instructor_delete_assignment_context
/**
* build the instructor view to grade an submission
*/
protected String build_instructor_grade_submission_context(VelocityPortlet portlet, Context context, RunData data,
SessionState state)
{
int gradeType = -1;
// assignment
Assignment a = null;
try
{
a = AssignmentService.getAssignment((String) state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID));
context.put("assignment", a);
gradeType = a.getContent().getTypeOfGrade();
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin5"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("not_allowed_to_view"));
}
// assignment submission
try
{
AssignmentSubmission s = AssignmentService.getSubmission((String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID));
if (s != null)
{
context.put("submission", s);
ResourceProperties p = s.getProperties();
if (p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT) != null)
{
context.put("prevFeedbackText", p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT));
}
if (p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT) != null)
{
context.put("prevFeedbackComment", p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT));
}
if (p.getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS) != null)
{
context.put("prevFeedbackAttachments", getPrevFeedbackAttachments(p));
}
// get the submission level of close date setting
context.put("name_CloseMonth", ALLOW_RESUBMIT_CLOSEMONTH);
context.put("name_CloseDay", ALLOW_RESUBMIT_CLOSEDAY);
context.put("name_CloseYear", ALLOW_RESUBMIT_CLOSEYEAR);
context.put("name_CloseHour", ALLOW_RESUBMIT_CLOSEHOUR);
context.put("name_CloseMin", ALLOW_RESUBMIT_CLOSEMIN);
context.put("name_CloseAMPM", ALLOW_RESUBMIT_CLOSEAMPM);
String closeTimeString =(String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME);
Time time = null;
if (closeTimeString != null)
{
// if there is a local setting
time = TimeService.newTime(Long.parseLong(closeTimeString));
}
else if (a != null)
{
// if there is no local setting, default to assignment close time
time = a.getCloseTime();
}
TimeBreakdown closeTime = time.breakdownLocal();
context.put("value_CloseMonth", new Integer(closeTime.getMonth()));
context.put("value_CloseDay", new Integer(closeTime.getDay()));
context.put("value_CloseYear", new Integer(closeTime.getYear()));
int closeHour = closeTime.getHour();
if (closeHour >= 12)
{
context.put("value_CloseAMPM", "PM");
}
else
{
context.put("value_CloseAMPM", "AM");
}
if (closeHour == 0)
{
// for midnight point, we mark it as 12AM
closeHour = 12;
}
context.put("value_CloseHour", new Integer((closeHour > 12) ? closeHour - 12 : closeHour));
context.put("value_CloseMin", new Integer(closeTime.getMin()));
}
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin5"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("not_allowed_to_view"));
}
context.put("user", state.getAttribute(STATE_USER));
context.put("submissionTypeTable", submissionTypeTable());
context.put("gradeTypeTable", gradeTypeTable());
context.put("instructorAttachments", state.getAttribute(ATTACHMENTS));
context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE));
context.put("service", AssignmentService.getInstance());
// names
context.put("name_grade_assignment_id", GRADE_SUBMISSION_ASSIGNMENT_ID);
context.put("name_feedback_comment", GRADE_SUBMISSION_FEEDBACK_COMMENT);
context.put("name_feedback_text", GRADE_SUBMISSION_FEEDBACK_TEXT);
context.put("name_feedback_attachment", GRADE_SUBMISSION_FEEDBACK_ATTACHMENT);
context.put("name_grade", GRADE_SUBMISSION_GRADE);
context.put("name_allowResubmitNumber", AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
// values
context.put("value_year_from", state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_FROM));
context.put("value_year_to", state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_TO));
context.put("value_grade_assignment_id", state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID));
context.put("value_feedback_comment", state.getAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT));
context.put("value_feedback_text", state.getAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT));
context.put("value_feedback_attachment", state.getAttribute(ATTACHMENTS));
if (state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null)
{
context.put("value_allowResubmitNumber", Integer.valueOf((String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER)));
}
// format to show one decimal place in grade
context.put("value_grade", (gradeType == 3) ? displayGrade(state, (String) state.getAttribute(GRADE_SUBMISSION_GRADE))
: state.getAttribute(GRADE_SUBMISSION_GRADE));
context.put("assignment_expand_flag", state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG));
context.put("gradingAttachments", state.getAttribute(ATTACHMENTS));
// is this a non-electronic submission type of assignment
context.put("nonElectronic", (a!=null && a.getContent().getTypeOfSubmission() == Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION)?Boolean.TRUE:Boolean.FALSE);
String template = (String) getContext(data).get("template");
return template + TEMPLATE_INSTRUCTOR_GRADE_SUBMISSION;
} // build_instructor_grade_submission_context
private List getPrevFeedbackAttachments(ResourceProperties p) {
String attachmentsString = p.getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS);
String[] attachmentsReferences = attachmentsString.split(",");
List prevFeedbackAttachments = EntityManager.newReferenceList();
for (int k =0; k < attachmentsReferences.length; k++)
{
prevFeedbackAttachments.add(EntityManager.newReference(attachmentsReferences[k]));
}
return prevFeedbackAttachments;
}
/**
* build the instructor preview of grading submission
*/
protected String build_instructor_preview_grade_submission_context(VelocityPortlet portlet, Context context, RunData data,
SessionState state)
{
// assignment
int gradeType = -1;
try
{
Assignment a = AssignmentService.getAssignment((String) state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID));
context.put("assignment", a);
gradeType = a.getContent().getTypeOfGrade();
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin3"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot14"));
}
// submission
try
{
context.put("submission", AssignmentService.getSubmission((String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID)));
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin5"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("not_allowed_to_view"));
}
User user = (User) state.getAttribute(STATE_USER);
context.put("user", user);
context.put("submissionTypeTable", submissionTypeTable());
context.put("gradeTypeTable", gradeTypeTable());
context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE));
context.put("service", AssignmentService.getInstance());
// filter the feedback text for the instructor comment and mark it as red
String feedbackText = (String) state.getAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT);
context.put("feedback_comment", state.getAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT));
context.put("feedback_text", feedbackText);
context.put("feedback_attachment", state.getAttribute(GRADE_SUBMISSION_FEEDBACK_ATTACHMENT));
// format to show one decimal place
String grade = (String) state.getAttribute(GRADE_SUBMISSION_GRADE);
if (gradeType == 3)
{
grade = displayGrade(state, grade);
}
context.put("grade", grade);
context.put("comment_open", COMMENT_OPEN);
context.put("comment_close", COMMENT_CLOSE);
context.put("allowResubmitNumber", state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER));
String closeTimeString =(String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME);
if (closeTimeString != null)
{
// close time for resubmit
Time time = TimeService.newTime(Long.parseLong(closeTimeString));
context.put("allowResubmitCloseTime", time.toStringLocalFull());
}
String template = (String) getContext(data).get("template");
return template + TEMPLATE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION;
} // build_instructor_preview_grade_submission_context
/**
* build the instructor view to grade an assignment
*/
protected String build_instructor_grade_assignment_context(VelocityPortlet portlet, Context context, RunData data,
SessionState state)
{
context.put("user", state.getAttribute(STATE_USER));
// sorting related fields
context.put("sortedBy", state.getAttribute(SORTED_GRADE_SUBMISSION_BY));
context.put("sortedAsc", state.getAttribute(SORTED_GRADE_SUBMISSION_ASC));
context.put("sort_lastName", SORTED_GRADE_SUBMISSION_BY_LASTNAME);
context.put("sort_submitTime", SORTED_GRADE_SUBMISSION_BY_SUBMIT_TIME);
context.put("sort_submitStatus", SORTED_GRADE_SUBMISSION_BY_STATUS);
context.put("sort_submitGrade", SORTED_GRADE_SUBMISSION_BY_GRADE);
context.put("sort_submitReleased", SORTED_GRADE_SUBMISSION_BY_RELEASED);
context.put("sort_submitReview", SORTED_GRADE_SUBMISSION_CONTENTREVIEW);
Assignment assignment = null;
try
{
assignment = AssignmentService.getAssignment((String) state.getAttribute(EXPORT_ASSIGNMENT_REF));
context.put("assignment", assignment);
state.setAttribute(EXPORT_ASSIGNMENT_ID, assignment.getId());
// ever set the default grade for no-submissions
String defaultGrade = assignment.getProperties().getProperty(GRADE_NO_SUBMISSION_DEFAULT_GRADE);
if (defaultGrade != null)
{
context.put("defaultGrade", defaultGrade);
}
// groups
if (state.getAttribute(VIEW_SUBMISSION_LIST_OPTION) == null)
{
state.setAttribute(VIEW_SUBMISSION_LIST_OPTION, rb.getString("gen.viewallgroupssections"));
}
String view = (String)state.getAttribute(VIEW_SUBMISSION_LIST_OPTION);
context.put("view", view);
// access point url for zip file download
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
String accessPointUrl = ServerConfigurationService.getAccessUrl().concat(AssignmentService.submissionsZipReference(
contextString, (String) state.getAttribute(EXPORT_ASSIGNMENT_REF)));
if (!view.equals(rb.getString("gen.viewallgroupssections")))
{
// append the group info to the end
accessPointUrl = accessPointUrl.concat(view);
}
context.put("accessPointUrl", accessPointUrl);
if (AssignmentService.getAllowGroupAssignments())
{
Collection groupsAllowGradeAssignment = AssignmentService.getGroupsAllowGradeAssignment((String) state.getAttribute(STATE_CONTEXT_STRING), assignment.getReference());
// group list which user can add message to
if (groupsAllowGradeAssignment.size() > 0)
{
String sort = (String) state.getAttribute(SORTED_BY);
String asc = (String) state.getAttribute(SORTED_ASC);
if (sort == null || (!sort.equals(SORTED_BY_GROUP_TITLE) && !sort.equals(SORTED_BY_GROUP_DESCRIPTION)))
{
sort = SORTED_BY_GROUP_TITLE;
asc = Boolean.TRUE.toString();
state.setAttribute(SORTED_BY, sort);
state.setAttribute(SORTED_ASC, asc);
}
context.put("groups", new SortedIterator(groupsAllowGradeAssignment.iterator(), new AssignmentComparator(state, sort, asc)));
}
}
// for non-electronic assignment
if (assignment.getContent() != null && assignment.getContent().getTypeOfSubmission() == Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION)
{
List submissions = AssignmentService.getSubmissions(assignment);
// the following operation is accessible for those with add assignment right
List allowAddSubmissionUsers = AssignmentService.allowAddSubmissionUsers(assignment.getReference());
HashSet<String> submittersIdSet = getSubmittersIdSet(submissions);
HashSet<String> allowAddSubmissionUsersIdSet = getAllowAddSubmissionUsersIdSet(allowAddSubmissionUsers);
if (!submittersIdSet.equals(allowAddSubmissionUsersIdSet))
{
// get the difference between two sets
try
{
HashSet<String> addSubmissionUserIdSet = (HashSet<String>) allowAddSubmissionUsersIdSet.clone();
addSubmissionUserIdSet.removeAll(submittersIdSet);
HashSet<String> removeSubmissionUserIdSet = (HashSet<String>) submittersIdSet.clone();
removeSubmissionUserIdSet.removeAll(allowAddSubmissionUsersIdSet);
try
{
addRemoveSubmissionsForNonElectronicAssignment(state, submissions, addSubmissionUserIdSet, removeSubmissionUserIdSet, assignment);
}
catch (Exception ee)
{
Log.warn("chef", this + ee.getMessage());
}
}
catch (Exception e)
{
Log.warn("chef", this + e.getMessage());
}
}
}
List userSubmissions = prepPage(state);
state.setAttribute(USER_SUBMISSIONS, userSubmissions);
context.put("userSubmissions", state.getAttribute(USER_SUBMISSIONS));
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin3"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot14"));
}
TaggingManager taggingManager = (TaggingManager) ComponentManager
.get("org.sakaiproject.assignment.taggable.api.TaggingManager");
if (taggingManager.isTaggable() && assignment != null)
{
context.put("producer", ComponentManager
.get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer"));
addProviders(context, state);
addActivity(context, assignment);
context.put("taggable", Boolean.valueOf(true));
}
context.put("submissionTypeTable", submissionTypeTable());
context.put("gradeTypeTable", gradeTypeTable());
context.put("attachments", state.getAttribute(ATTACHMENTS));
// Get turnitin results for instructors
context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE));
context.put("service", AssignmentService.getInstance());
context.put("assignment_expand_flag", state.getAttribute(GRADE_ASSIGNMENT_EXPAND_FLAG));
context.put("submission_expand_flag", state.getAttribute(GRADE_SUBMISSION_EXPAND_FLAG));
// the user directory service
context.put("userDirectoryService", UserDirectoryService.getInstance());
add2ndToolbarFields(data, context);
pagingInfoToContext(state, context);
String template = (String) getContext(data).get("template");
return template + TEMPLATE_INSTRUCTOR_GRADE_ASSIGNMENT;
} // build_instructor_grade_assignment_context
/**
* build the instructor view of an assignment
*/
protected String build_instructor_view_assignment_context(VelocityPortlet portlet, Context context, RunData data,
SessionState state)
{
context.put("tlang", rb);
Assignment assignment = null;
try
{
assignment = AssignmentService.getAssignment((String) state.getAttribute(VIEW_ASSIGNMENT_ID));
context.put("assignment", assignment);
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin3"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot14"));
}
TaggingManager taggingManager = (TaggingManager) ComponentManager
.get("org.sakaiproject.assignment.taggable.api.TaggingManager");
if (taggingManager.isTaggable() && assignment != null)
{
List<DecoratedTaggingProvider> providers = addProviders(context, state);
List<TaggingHelperInfo> activityHelpers = new ArrayList<TaggingHelperInfo>();
AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager
.get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer");
for (DecoratedTaggingProvider provider : providers)
{
TaggingHelperInfo helper = provider.getProvider()
.getActivityHelperInfo(
assignmentActivityProducer.getActivity(
assignment).getReference());
if (helper != null)
{
activityHelpers.add(helper);
}
}
addActivity(context, assignment);
context.put("activityHelpers", activityHelpers);
context.put("taggable", Boolean.valueOf(true));
}
context.put("currentTime", TimeService.newTime());
context.put("submissionTypeTable", submissionTypeTable());
context.put("gradeTypeTable", gradeTypeTable());
context.put("hideAssignmentFlag", state.getAttribute(VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG));
context.put("hideStudentViewFlag", state.getAttribute(VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG));
context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE));
// the user directory service
context.put("userDirectoryService", UserDirectoryService.getInstance());
String template = (String) getContext(data).get("template");
return template + TEMPLATE_INSTRUCTOR_VIEW_ASSIGNMENT;
} // build_instructor_view_assignment_context
/**
* build the instructor view of reordering assignments
*/
protected String build_instructor_reorder_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state)
{
context.put("context", state.getAttribute(STATE_CONTEXT_STRING));
List assignments = prepPage(state);
context.put("assignments", assignments.iterator());
context.put("assignmentsize", assignments.size());
String sortedBy = (String) state.getAttribute(SORTED_BY);
String sortedAsc = (String) state.getAttribute(SORTED_ASC);
context.put("sortedBy", sortedBy);
context.put("sortedAsc", sortedAsc);
// put site object into context
try
{
// get current site
Site site = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING));
context.put("site", site);
}
catch (Exception ignore)
{
}
context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE));
context.put("gradeTypeTable", gradeTypeTable());
context.put("userDirectoryService", UserDirectoryService.getInstance());
String template = (String) getContext(data).get("template");
return template + TEMPLATE_INSTRUCTOR_REORDER_ASSIGNMENT;
} // build_instructor_reorder_assignment_context
/**
* build the instructor view to view the list of students for an assignment
*/
protected String build_instructor_view_students_assignment_context(VelocityPortlet portlet, Context context, RunData data,
SessionState state)
{
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
// get the realm and its member
List studentMembers = new Vector();
List allowSubmitMembers = AssignmentService.allowAddAnySubmissionUsers(contextString);
for (Iterator allowSubmitMembersIterator=allowSubmitMembers.iterator(); allowSubmitMembersIterator.hasNext();)
{
// get user
try
{
String userId = (String) allowSubmitMembersIterator.next();
User user = UserDirectoryService.getUser(userId);
studentMembers.add(user);
}
catch (Exception ee)
{
Log.warn("chef", this + ee.getMessage());
}
}
context.put("studentMembers", studentMembers);
context.put("assignmentService", AssignmentService.getInstance());
Hashtable showStudentAssignments = new Hashtable();
if (state.getAttribute(STUDENT_LIST_SHOW_TABLE) != null)
{
Set showStudentListSet = (Set) state.getAttribute(STUDENT_LIST_SHOW_TABLE);
context.put("studentListShowSet", showStudentListSet);
for (Iterator showStudentListSetIterator=showStudentListSet.iterator(); showStudentListSetIterator.hasNext();)
{
// get user
try
{
String userId = (String) showStudentListSetIterator.next();
User user = UserDirectoryService.getUser(userId);
// sort the assignments into the default order before adding
Iterator assignmentSorter = AssignmentService.getAssignmentsForContext(contextString, userId);
// filter to obtain only grade-able assignments
List rv = new Vector();
while (assignmentSorter.hasNext())
{
Assignment a = (Assignment) assignmentSorter.next();
if (AssignmentService.allowGradeSubmission(a.getReference()))
{
rv.add(a);
}
}
Iterator assignmentSortFinal = new SortedIterator(rv.iterator(), new AssignmentComparator(state, SORTED_BY_DEFAULT, Boolean.TRUE.toString()));
showStudentAssignments.put(user, assignmentSortFinal);
}
catch (Exception ee)
{
Log.warn("chef", this + ee.getMessage());
}
}
}
context.put("studentAssignmentsTable", showStudentAssignments);
add2ndToolbarFields(data, context);
String template = (String) getContext(data).get("template");
return template + TEMPLATE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT;
} // build_instructor_view_students_assignment_context
/**
* build the instructor view to report the submissions
*/
protected String build_instructor_report_submissions(VelocityPortlet portlet, Context context, RunData data, SessionState state)
{
context.put("submissions", prepPage(state));
context.put("sortedBy", (String) state.getAttribute(SORTED_SUBMISSION_BY));
context.put("sortedAsc", (String) state.getAttribute(SORTED_SUBMISSION_ASC));
context.put("sortedBy_lastName", SORTED_SUBMISSION_BY_LASTNAME);
context.put("sortedBy_submitTime", SORTED_SUBMISSION_BY_SUBMIT_TIME);
context.put("sortedBy_grade", SORTED_SUBMISSION_BY_GRADE);
context.put("sortedBy_status", SORTED_SUBMISSION_BY_STATUS);
context.put("sortedBy_released", SORTED_SUBMISSION_BY_RELEASED);
context.put("sortedBy_assignment", SORTED_SUBMISSION_BY_ASSIGNMENT);
context.put("sortedBy_maxGrade", SORTED_SUBMISSION_BY_MAX_GRADE);
add2ndToolbarFields(data, context);
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
context.put("accessPointUrl", ServerConfigurationService.getAccessUrl()
+ AssignmentService.gradesSpreadsheetReference(contextString, null));
pagingInfoToContext(state, context);
String template = (String) getContext(data).get("template");
return template + TEMPLATE_INSTRUCTOR_REPORT_SUBMISSIONS;
} // build_instructor_report_submissions
// Is Gradebook defined for the site?
protected boolean isGradebookDefined()
{
boolean rv = false;
try
{
GradebookService g = (GradebookService) (org.sakaiproject.service.gradebook.shared.GradebookService) ComponentManager
.get("org.sakaiproject.service.gradebook.GradebookService");
String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext();
if (g.isGradebookDefined(gradebookUid))
{
rv = true;
}
}
catch (Exception e)
{
Log.debug("chef", this + rb.getString("addtogradebook.alertMessage") + "\n" + e.getMessage());
}
return rv;
} // isGradebookDefined()
/**
* build the instructor view to upload information from archive file
*/
protected String build_instructor_upload_all(VelocityPortlet portlet, Context context, RunData data, SessionState state)
{
context.put("hasSubmissionText", state.getAttribute(UPLOAD_ALL_HAS_SUBMISSION_TEXT));
context.put("hasSubmissionAttachment", state.getAttribute(UPLOAD_ALL_HAS_SUBMISSION_ATTACHMENT));
context.put("hasGradeFile", state.getAttribute(UPLOAD_ALL_HAS_GRADEFILE));
context.put("hasComments", state.getAttribute(UPLOAD_ALL_HAS_COMMENTS));
context.put("hasFeedbackText", state.getAttribute(UPLOAD_ALL_HAS_FEEDBACK_TEXT));
context.put("hasFeedbackAttachment", state.getAttribute(UPLOAD_ALL_HAS_FEEDBACK_ATTACHMENT));
context.put("releaseGrades", state.getAttribute(UPLOAD_ALL_RELEASE_GRADES));
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
context.put("accessPointUrl", (ServerConfigurationService.getAccessUrl()).concat(AssignmentService.submissionsZipReference(
contextString, (String) state.getAttribute(EXPORT_ASSIGNMENT_REF))));
String template = (String) getContext(data).get("template");
return template + TEMPLATE_INSTRUCTOR_UPLOAD_ALL;
} // build_instructor_upload_all
/**
** Retrieve tool title from Tool configuration file or use default
** (This should return i18n version of tool title if available)
**/
private String getToolTitle()
{
Tool tool = ToolManager.getTool(ASSIGNMENT_TOOL_ID);
String toolTitle = null;
if (tool == null)
toolTitle = "Assignments";
else
toolTitle = tool.getTitle();
return toolTitle;
}
/**
* integration with gradebook
*
* @param state
* @param assignmentRef Assignment reference
* @param associateGradebookAssignment The title for the associated GB assignment
* @param addUpdateRemoveAssignment "add" for adding the assignment; "update" for updating the assignment; "remove" for remove assignment
* @param oldAssignment_title The original assignment title
* @param newAssignment_title The updated assignment title
* @param newAssignment_maxPoints The maximum point of the assignment
* @param newAssignment_dueTime The due time of the assignment
* @param submissionRef Any submission grade need to be updated? Do bulk update if null
* @param updateRemoveSubmission "update" for update submission;"remove" for remove submission
*/
protected void integrateGradebook (SessionState state, String assignmentRef, String associateGradebookAssignment, String addUpdateRemoveAssignment, String oldAssignment_title, String newAssignment_title, int newAssignment_maxPoints, Time newAssignment_dueTime, String submissionRef, String updateRemoveSubmission)
{
associateGradebookAssignment = StringUtil.trimToNull(associateGradebookAssignment);
// add or remove external grades to gradebook
// a. if Gradebook does not exists, do nothing, 'cos setting should have been hidden
// b. if Gradebook exists, just call addExternal and removeExternal and swallow any exception. The
// exception are indication that the assessment is already in the Gradebook or there is nothing
// to remove.
String assignmentToolTitle = getToolTitle();
GradebookService g = (GradebookService) (org.sakaiproject.service.gradebook.shared.GradebookService) ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService");
String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext();
if (g.isGradebookDefined(gradebookUid))
{
boolean isExternalAssignmentDefined=g.isExternalAssignmentDefined(gradebookUid, assignmentRef);
boolean isExternalAssociateAssignmentDefined = g.isExternalAssignmentDefined(gradebookUid, associateGradebookAssignment);
boolean isAssignmentDefined = g.isAssignmentDefined(gradebookUid, associateGradebookAssignment);
if (addUpdateRemoveAssignment != null)
{
// add an entry into Gradebook for newly created assignment or modified assignment, and there wasn't a correspond record in gradebook yet
if ((addUpdateRemoveAssignment.equals(AssignmentService.GRADEBOOK_INTEGRATION_ADD) || (addUpdateRemoveAssignment.equals("update") && !isExternalAssignmentDefined)) && associateGradebookAssignment == null)
{
// add assignment into gradebook
try
{
// add assignment to gradebook
g.addExternalAssessment(gradebookUid, assignmentRef, null, newAssignment_title,
newAssignment_maxPoints/10.0, new Date(newAssignment_dueTime.getTime()), assignmentToolTitle);
}
catch (AssignmentHasIllegalPointsException e)
{
addAlert(state, rb.getString("addtogradebook.illegalPoints"));
}
catch (ConflictingAssignmentNameException e)
{
// add alert prompting for change assignment title
addAlert(state, rb.getString("addtogradebook.nonUniqueTitle"));
}
catch (ConflictingExternalIdException e)
{
// this shouldn't happen, as we have already checked for assignment reference before. Log the error
Log.warn("chef", this + e.getMessage());
}
catch (GradebookNotFoundException e)
{
// this shouldn't happen, as we have checked for gradebook existence before
Log.warn("chef", this + e.getMessage());
}
catch (Exception e)
{
// ignore
Log.warn("chef", this + e.getMessage());
}
}
else if (addUpdateRemoveAssignment.equals("update"))
{
// no need for updating external assignment
/*if (associateGradebookAssignment != null && isExternalAssociateAssignmentDefined)
{
try
{
Assignment a = AssignmentService.getAssignment(associateGradebookAssignment);
// update attributes if the GB assignment was created for the assignment
g.updateExternalAssessment(gradebookUid, associateGradebookAssignment, null, newAssignment_title, newAssignment_maxPoints/10.0, new Date(newAssignment_dueTime.getTime()));
}
catch(Exception e)
{
Log.warn("chef", rb.getString("cannot_find_assignment") + assignmentRef + ": " + e.getMessage());
}
}*/
} // addUpdateRemove != null
else if (addUpdateRemoveAssignment.equals("remove"))
{
// remove assignment and all submission grades
removeNonAssociatedExternalGradebookEntry((String) state.getAttribute(STATE_CONTEXT_STRING), assignmentRef, associateGradebookAssignment, g, gradebookUid);
}
}
if (updateRemoveSubmission != null)
{
try
{
Assignment a = AssignmentService.getAssignment(assignmentRef);
if (updateRemoveSubmission.equals("update")
&& a.getProperties().getProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK) != null
&& !a.getProperties().getProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK).equals(AssignmentService.GRADEBOOK_INTEGRATION_NO)
&& a.getContent().getTypeOfGrade() == Assignment.SCORE_GRADE_TYPE)
{
if (submissionRef == null)
{
// bulk add all grades for assignment into gradebook
Iterator submissions = AssignmentService.getSubmissions(a).iterator();
Map m = new HashMap();
// any score to copy over? get all the assessmentGradingData and copy over
while (submissions.hasNext())
{
AssignmentSubmission aSubmission = (AssignmentSubmission) submissions.next();
if (aSubmission.getGradeReleased())
{
User[] submitters = aSubmission.getSubmitters();
String submitterId = submitters[0].getId();
String gradeString = StringUtil.trimToNull(aSubmission.getGrade());
Double grade = gradeString != null ? Double.valueOf(displayGrade(state,gradeString)) : null;
m.put(submitterId, grade);
}
}
// need to update only when there is at least one submission
if (m.size()>0)
{
if (associateGradebookAssignment != null)
{
if (isExternalAssociateAssignmentDefined)
{
// the associated assignment is externally maintained
g.updateExternalAssessmentScores(gradebookUid, associateGradebookAssignment, m);
}
else if (isAssignmentDefined)
{
// the associated assignment is internal one, update records one by one
submissions = AssignmentService.getSubmissions(a).iterator();
while (submissions.hasNext())
{
AssignmentSubmission aSubmission = (AssignmentSubmission) submissions.next();
User[] submitters = aSubmission.getSubmitters();
String submitterId = submitters[0].getId();
String gradeString = StringUtil.trimToNull(aSubmission.getGrade());
Double grade = (gradeString != null && aSubmission.getGradeReleased()) ? Double.valueOf(displayGrade(state,gradeString)) : null;
g.setAssignmentScore(gradebookUid, associateGradebookAssignment, submitterId, grade, assignmentToolTitle);
}
}
}
else if (isExternalAssignmentDefined)
{
g.updateExternalAssessmentScores(gradebookUid, assignmentRef, m);
}
}
}
else
{
try
{
// only update one submission
AssignmentSubmission aSubmission = (AssignmentSubmission) AssignmentService
.getSubmission(submissionRef);
User[] submitters = aSubmission.getSubmitters();
String gradeString = StringUtil.trimToNull(aSubmission.getGrade());
if (associateGradebookAssignment != null)
{
if (g.isExternalAssignmentDefined(gradebookUid, associateGradebookAssignment))
{
// the associated assignment is externally maintained
g.updateExternalAssessmentScore(gradebookUid, associateGradebookAssignment, submitters[0].getId(),
(gradeString != null && aSubmission.getGradeReleased()) ? Double.valueOf(displayGrade(state,gradeString)) : null);
}
else if (g.isAssignmentDefined(gradebookUid, associateGradebookAssignment))
{
// the associated assignment is internal one, update records
g.setAssignmentScore(gradebookUid, associateGradebookAssignment, submitters[0].getId(),
(gradeString != null && aSubmission.getGradeReleased()) ? Double.valueOf(displayGrade(state,gradeString)) : null, assignmentToolTitle);
}
}
else
{
g.updateExternalAssessmentScore(gradebookUid, assignmentRef, submitters[0].getId(),
(gradeString != null && aSubmission.getGradeReleased()) ? Double.valueOf(displayGrade(state,gradeString)) : null);
}
}
catch (Exception e)
{
Log.warn("chef", "Cannot find submission " + submissionRef + ": " + e.getMessage());
}
}
}
else if (updateRemoveSubmission.equals("remove"))
{
if (submissionRef == null)
{
// remove all submission grades (when changing the associated entry in Gradebook)
Iterator submissions = AssignmentService.getSubmissions(a).iterator();
// any score to copy over? get all the assessmentGradingData and copy over
while (submissions.hasNext())
{
AssignmentSubmission aSubmission = (AssignmentSubmission) submissions.next();
User[] submitters = aSubmission.getSubmitters();
if (isExternalAssociateAssignmentDefined)
{
// if the old associated assignment is an external maintained one
g.updateExternalAssessmentScore(gradebookUid, associateGradebookAssignment, submitters[0].getId(), null);
}
else if (isAssignmentDefined)
{
g.setAssignmentScore(gradebookUid, associateGradebookAssignment, submitters[0].getId(), null, assignmentToolTitle);
}
}
}
else
{
// remove only one submission grade
try
{
AssignmentSubmission aSubmission = (AssignmentSubmission) AssignmentService
.getSubmission(submissionRef);
User[] submitters = aSubmission.getSubmitters();
g.updateExternalAssessmentScore(gradebookUid, assignmentRef, submitters[0].getId(), null);
}
catch (Exception e)
{
Log.warn("chef", "Cannot find submission " + submissionRef + ": " + e.getMessage());
}
}
}
}
catch (Exception e)
{
Log.warn("chef", rb.getString("cannot_find_assignment") + assignmentRef + ": " + e.getMessage());
}
} // updateRemoveSubmission != null
}
} // integrateGradebook
/**
* Go to the instructor view
*/
public void doView_instructor(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
state.setAttribute(SORTED_BY, SORTED_BY_DEFAULT);
state.setAttribute(SORTED_ASC, Boolean.TRUE.toString());
} // doView_instructor
/**
* Go to the student view
*/
public void doView_student(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// to the student list of assignment view
state.setAttribute(SORTED_BY, SORTED_BY_DEFAULT);
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
} // doView_student
/**
* Action is to view the content of one specific assignment submission
*/
public void doView_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// reset the submission context
resetViewSubmission(state);
ParameterParser params = data.getParameters();
String assignmentReference = params.getString("assignmentReference");
state.setAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE, assignmentReference);
User u = (User) state.getAttribute(STATE_USER);
try
{
AssignmentSubmission submission = AssignmentService.getSubmission(assignmentReference, u);
if (submission != null)
{
state.setAttribute(VIEW_SUBMISSION_TEXT, submission.getSubmittedText());
state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, (new Boolean(submission.getHonorPledgeFlag())).toString());
List v = EntityManager.newReferenceList();
Iterator l = submission.getSubmittedAttachments().iterator();
while (l.hasNext())
{
v.add(l.next());
}
state.setAttribute(ATTACHMENTS, v);
}
else
{
state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, "false");
state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList());
}
state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_SUBMISSION);
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin5"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("not_allowed_to_view"));
} // try
} // doView_submission
/**
* Action is to view the content of one specific assignment submission
*/
public void doView_submission_list_option(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String view = params.getString("view");
state.setAttribute(VIEW_SUBMISSION_LIST_OPTION, view);
} // doView_submission_list_option
/**
* Preview of the submission
*/
public void doPreview_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
// String assignmentId = params.getString(assignmentId);
state.setAttribute(PREVIEW_SUBMISSION_ASSIGNMENT_REFERENCE, state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE));
// retrieve the submission text (as formatted text)
boolean checkForFormattingErrors = true; // the student is submitting something - so check for errors
String text = processFormattedTextFromBrowser(state, params.getCleanString(VIEW_SUBMISSION_TEXT), checkForFormattingErrors);
state.setAttribute(PREVIEW_SUBMISSION_TEXT, text);
state.setAttribute(VIEW_SUBMISSION_TEXT, text);
// assign the honor pledge attribute
String honor_pledge_yes = params.getString(VIEW_SUBMISSION_HONOR_PLEDGE_YES);
if (honor_pledge_yes == null)
{
honor_pledge_yes = "false";
}
state.setAttribute(PREVIEW_SUBMISSION_HONOR_PLEDGE_YES, honor_pledge_yes);
state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, honor_pledge_yes);
state.setAttribute(PREVIEW_SUBMISSION_ATTACHMENTS, state.getAttribute(ATTACHMENTS));
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(STATE_MODE, MODE_STUDENT_PREVIEW_SUBMISSION);
}
} // doPreview_submission
/**
* Preview of the grading of submission
*/
public void doPreview_grade_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// read user input
readGradeForm(data, state, "read");
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION);
}
} // doPreview_grade_submission
/**
* Action is to end the preview submission process
*/
public void doDone_preview_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// back to the student list view of assignments
state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_SUBMISSION);
} // doDone_preview_submission
/**
* Action is to end the view assignment process
*/
public void doDone_view_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// back to the student list view of assignments
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
} // doDone_view_assignments
/**
* Action is to end the preview new assignment process
*/
public void doDone_preview_new_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// back to the new assignment page
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT);
} // doDone_preview_new_assignment
/**
* Action is to end the user view assignment process and redirect him to the assignment list view
*/
public void doCancel_student_view_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// reset the view assignment
state.setAttribute(VIEW_ASSIGNMENT_ID, "");
// back to the student list view of assignments
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
} // doCancel_student_view_assignment
/**
* Action is to end the show submission process
*/
public void doCancel_show_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// reset the view assignment
state.setAttribute(VIEW_ASSIGNMENT_ID, "");
// back to the student list view of assignments
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
} // doCancel_show_submission
/**
* Action is to cancel the delete assignment process
*/
public void doCancel_delete_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// reset the show assignment object
state.setAttribute(DELETE_ASSIGNMENT_IDS, new Vector());
// back to the instructor list view of assignments
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
} // doCancel_delete_assignment
/**
* Action is to end the show submission process
*/
public void doCancel_edit_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// back to the student list view of assignments
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
// reset sorting
setDefaultSort(state);
} // doCancel_edit_assignment
/**
* Action is to end the show submission process
*/
public void doCancel_new_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// reset the assignment object
resetAssignment(state);
// back to the student list view of assignments
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
// reset sorting
setDefaultSort(state);
} // doCancel_new_assignment
/**
* Action is to cancel the grade submission process
*/
public void doCancel_grade_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// reset the assignment object
// resetAssignment (state);
// back to the student list view of assignments
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT);
} // doCancel_grade_submission
/**
* Action is to cancel the preview grade process
*/
public void doCancel_preview_grade_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// back to the instructor view of grading a submission
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_SUBMISSION);
} // doCancel_preview_grade_submission
/**
* Action is to cancel the reorder process
*/
public void doCancel_reorder(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// back to the list view of assignments
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
} // doCancel_reorder
/**
* Action is to cancel the preview grade process
*/
public void doCancel_preview_to_list_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// back to the instructor view of grading a submission
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT);
} // doCancel_preview_to_list_submission
/**
* Action is to return to the view of list assignments
*/
public void doList_assignments(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// back to the student list view of assignments
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
state.setAttribute(SORTED_BY, SORTED_BY_DEFAULT);
state.setAttribute(SORTED_ASC, Boolean.TRUE.toString());
} // doList_assignments
/**
* Action is to cancel the student view grade process
*/
public void doCancel_view_grade(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// reset the view grade submission id
state.setAttribute(VIEW_GRADE_SUBMISSION_ID, "");
// back to the student list view of assignments
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
} // doCancel_view_grade
/**
* Action is to save the grade to submission
*/
public void doSave_grade_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
readGradeForm(data, state, "save");
if (state.getAttribute(STATE_MESSAGE) == null)
{
grade_submission_option(data, "save");
}
} // doSave_grade_submission
/**
* Action is to release the grade to submission
*/
public void doRelease_grade_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
readGradeForm(data, state, "release");
if (state.getAttribute(STATE_MESSAGE) == null)
{
grade_submission_option(data, "release");
}
} // doRelease_grade_submission
/**
* Action is to return submission with or without grade
*/
public void doReturn_grade_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
readGradeForm(data, state, "return");
if (state.getAttribute(STATE_MESSAGE) == null)
{
grade_submission_option(data, "return");
}
} // doReturn_grade_submission
/**
* Action is to return submission with or without grade from preview
*/
public void doReturn_preview_grade_submission(RunData data)
{
grade_submission_option(data, "return");
} // doReturn_grade_preview_submission
/**
* Action is to save submission with or without grade from preview
*/
public void doSave_preview_grade_submission(RunData data)
{
grade_submission_option(data, "save");
} // doSave_grade_preview_submission
/**
* Common grading routine plus specific operation to differenciate cases when saving, releasing or returning grade.
*/
private void grade_submission_option(RunData data, String gradeOption)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
boolean withGrade = state.getAttribute(WITH_GRADES) != null ? ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue(): false;
String sId = (String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID);
try
{
// for points grading, one have to enter number as the points
String grade = (String) state.getAttribute(GRADE_SUBMISSION_GRADE);
AssignmentSubmissionEdit sEdit = AssignmentService.editSubmission(sId);
Assignment a = sEdit.getAssignment();
int typeOfGrade = a.getContent().getTypeOfGrade();
if (!withGrade)
{
// no grade input needed for the without-grade version of assignment tool
sEdit.setGraded(true);
if (gradeOption.equals("return") || gradeOption.equals("release"))
{
sEdit.setGradeReleased(true);
}
}
else if (grade == null)
{
sEdit.setGrade("");
sEdit.setGraded(false);
sEdit.setGradeReleased(false);
}
else
{
if (typeOfGrade == 1)
{
sEdit.setGrade(rb.getString("gen.nograd"));
}
else
{
sEdit.setGrade(grade);
}
if (grade.length() != 0)
{
sEdit.setGraded(true);
}
else
{
sEdit.setGraded(false);
}
}
if (gradeOption.equals("release"))
{
sEdit.setGradeReleased(true);
sEdit.setGraded(true);
// clear the returned flag
sEdit.setReturned(false);
sEdit.setTimeReturned(null);
}
else if (gradeOption.equals("return"))
{
sEdit.setGradeReleased(true);
sEdit.setGraded(true);
sEdit.setReturned(true);
sEdit.setTimeReturned(TimeService.newTime());
sEdit.setHonorPledgeFlag(Boolean.FALSE.booleanValue());
}
else if (gradeOption.equals("save"))
{
sEdit.setGradeReleased(false);
sEdit.setReturned(false);
sEdit.setTimeReturned(null);
}
if (state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null)
{
// get resubmit number
ResourcePropertiesEdit pEdit = sEdit.getPropertiesEdit();
pEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, (String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER));
if (state.getAttribute(ALLOW_RESUBMIT_CLOSEYEAR) != null)
{
// get resubmit time
Time closeTime = getAllowSubmitCloseTime(state);
pEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME, String.valueOf(closeTime.getTime()));
}
else
{
pEdit.removeProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME);
}
}
// the instructor comment
String feedbackCommentString = StringUtil
.trimToNull((String) state.getAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT));
if (feedbackCommentString != null)
{
sEdit.setFeedbackComment(feedbackCommentString);
}
// the instructor inline feedback
String feedbackTextString = (String) state.getAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT);
if (feedbackTextString != null)
{
sEdit.setFeedbackText(feedbackTextString);
}
List v = (List) state.getAttribute(GRADE_SUBMISSION_FEEDBACK_ATTACHMENT);
if (v != null)
{
// clear the old attachments first
sEdit.clearFeedbackAttachments();
for (int i = 0; i < v.size(); i++)
{
sEdit.addFeedbackAttachment((Reference) v.get(i));
}
}
String sReference = sEdit.getReference();
AssignmentService.commitEdit(sEdit);
// update grades in gradebook
String aReference = a.getReference();
String associateGradebookAssignment = StringUtil.trimToNull(a.getProperties().getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT));
if (gradeOption.equals("release") || gradeOption.equals("return"))
{
// update grade in gradebook
integrateGradebook(state, aReference, associateGradebookAssignment, null, null, null, -1, null, sReference, "update");
}
else
{
// remove grade from gradebook
integrateGradebook(state, aReference, associateGradebookAssignment, null, null, null, -1, null, sReference, "remove");
}
}
catch (IdUnusedException e)
{
}
catch (PermissionException e)
{
}
catch (InUseException e)
{
addAlert(state, rb.getString("somelsis") + " " + rb.getString("submiss"));
} // try
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT);
state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList());
}
} // grade_submission_option
/**
* Action is to save the submission as a draft
*/
public void doSave_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
// retrieve the submission text (as formatted text)
boolean checkForFormattingErrors = true; // the student is submitting something - so check for errors
String text = processFormattedTextFromBrowser(state, params.getCleanString(VIEW_SUBMISSION_TEXT), checkForFormattingErrors);
if (text == null)
{
text = (String) state.getAttribute(VIEW_SUBMISSION_TEXT);
}
String honorPledgeYes = params.getString(VIEW_SUBMISSION_HONOR_PLEDGE_YES);
if (honorPledgeYes == null)
{
honorPledgeYes = "false";
}
String aReference = (String) state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE);
User u = (User) state.getAttribute(STATE_USER);
if (state.getAttribute(STATE_MESSAGE) == null)
{
try
{
Assignment a = AssignmentService.getAssignment(aReference);
String assignmentId = a.getId();
AssignmentSubmission submission = AssignmentService.getSubmission(aReference, u);
if (submission != null)
{
// the submission already exists, change the text and honor pledge value, save as draft
try
{
AssignmentSubmissionEdit edit = AssignmentService.editSubmission(submission.getReference());
edit.setSubmittedText(text);
edit.setHonorPledgeFlag(Boolean.valueOf(honorPledgeYes).booleanValue());
edit.setSubmitted(false);
// edit.addSubmitter (u);
edit.setAssignment(a);
// add attachments
List attachments = (List) state.getAttribute(ATTACHMENTS);
if (attachments != null)
{
// clear the old attachments first
edit.clearSubmittedAttachments();
// add each new attachment
Iterator it = attachments.iterator();
while (it.hasNext())
{
edit.addSubmittedAttachment((Reference) it.next());
}
}
AssignmentService.commitEdit(edit);
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin2") + " " + a.getTitle());
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot12"));
}
catch (InUseException e)
{
addAlert(state, rb.getString("somelsis") + " " + rb.getString("submiss"));
}
}
else
{
// new submission, save as draft
try
{
AssignmentSubmissionEdit edit = AssignmentService.addSubmission((String) state
.getAttribute(STATE_CONTEXT_STRING), assignmentId, SessionManager.getCurrentSessionUserId());
edit.setSubmittedText(text);
edit.setHonorPledgeFlag(Boolean.valueOf(honorPledgeYes).booleanValue());
edit.setSubmitted(false);
// edit.addSubmitter (u);
edit.setAssignment(a);
// add attachments
List attachments = (List) state.getAttribute(ATTACHMENTS);
if (attachments != null)
{
// add each attachment
Iterator it = attachments.iterator();
while (it.hasNext())
{
edit.addSubmittedAttachment((Reference) it.next());
}
}
AssignmentService.commitEdit(edit);
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot4"));
}
}
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin5"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("not_allowed_to_view"));
}
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_SUBMISSION_CONFIRMATION);
}
} // doSave_submission
/**
* Action is to post the submission
*/
public void doPost_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
String aReference = (String) state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE);
Assignment a = null;
try
{
a = AssignmentService.getAssignment(aReference);
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin2"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot14"));
}
if (AssignmentService.canSubmit(contextString, a))
{
ParameterParser params = data.getParameters();
// retrieve the submission text (as formatted text)
boolean checkForFormattingErrors = true; // the student is submitting something - so check for errors
String text = processFormattedTextFromBrowser(state, params.getCleanString(VIEW_SUBMISSION_TEXT), checkForFormattingErrors);
if (text == null)
{
text = (String) state.getAttribute(VIEW_SUBMISSION_TEXT);
}
else
{
state.setAttribute(VIEW_SUBMISSION_TEXT, text);
}
String honorPledgeYes = params.getString(VIEW_SUBMISSION_HONOR_PLEDGE_YES);
if (honorPledgeYes == null)
{
honorPledgeYes = (String) state.getAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES);
}
if (honorPledgeYes == null)
{
honorPledgeYes = "false";
}
User u = (User) state.getAttribute(STATE_USER);
String assignmentId = "";
if (state.getAttribute(STATE_MESSAGE) == null)
{
assignmentId = a.getId();
if (a.getContent().getHonorPledge() != 1)
{
if (!Boolean.valueOf(honorPledgeYes).booleanValue())
{
addAlert(state, rb.getString("youarenot18"));
}
state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, honorPledgeYes);
}
// check the submission inputs based on the submission type
int submissionType = a.getContent().getTypeOfSubmission();
if (submissionType == 1)
{
// for the inline only submission
if (text.length() == 0)
{
addAlert(state, rb.getString("youmust7"));
}
}
else if (submissionType == 2)
{
// for the attachment only submission
Vector v = (Vector) state.getAttribute(ATTACHMENTS);
if ((v == null) || (v.size() == 0))
{
addAlert(state, rb.getString("youmust1"));
}
}
else if (submissionType == 3)
{
// for the inline and attachment submission
Vector v = (Vector) state.getAttribute(ATTACHMENTS);
if ((text.length() == 0) && ((v == null) || (v.size() == 0)))
{
addAlert(state, rb.getString("youmust2"));
}
}
}
if ((state.getAttribute(STATE_MESSAGE) == null) && (a != null))
{
try
{
AssignmentSubmission submission = AssignmentService.getSubmission(a.getReference(), u);
if (submission != null)
{
// the submission already exists, change the text and honor pledge value, post it
try
{
AssignmentSubmissionEdit sEdit = AssignmentService.editSubmission(submission.getReference());
sEdit.setSubmittedText(text);
sEdit.setHonorPledgeFlag(Boolean.valueOf(honorPledgeYes).booleanValue());
sEdit.setTimeSubmitted(TimeService.newTime());
sEdit.setSubmitted(true);
// for resubmissions
// when resubmit, keep the Returned flag on till the instructor grade again.
Time now = TimeService.newTime();
ResourcePropertiesEdit sPropertiesEdit = sEdit.getPropertiesEdit();
if (sEdit.getGraded())
{
// add the current grade into previous grade histroy
String previousGrades = (String) sEdit.getProperties().getProperty(
ResourceProperties.PROP_SUBMISSION_SCALED_PREVIOUS_GRADES);
if (previousGrades == null)
{
previousGrades = (String) sEdit.getProperties().getProperty(
ResourceProperties.PROP_SUBMISSION_PREVIOUS_GRADES);
if (previousGrades != null)
{
int typeOfGrade = a.getContent().getTypeOfGrade();
if (typeOfGrade == 3)
{
// point grade assignment type
// some old unscaled grades, need to scale the number and remove the old property
String[] grades = StringUtil.split(previousGrades, " ");
String newGrades = "";
for (int jj = 0; jj < grades.length; jj++)
{
String grade = grades[jj];
if (grade.indexOf(".") == -1)
{
// show the grade with decimal point
grade = grade.concat(".0");
}
newGrades = newGrades.concat(grade + " ");
}
previousGrades = newGrades;
}
sPropertiesEdit.removeProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_GRADES);
}
else
{
previousGrades = "";
}
}
previousGrades = rb.getString("gen.subm6") + now.toStringLocalFull() + "<p />" + sEdit.getGradeDisplay() + "<p />" +previousGrades;
sPropertiesEdit.addProperty(ResourceProperties.PROP_SUBMISSION_SCALED_PREVIOUS_GRADES,
previousGrades);
// clear the current grade and make the submission ungraded
sEdit.setGraded(false);
sEdit.setGrade("");
sEdit.setGradeReleased(false);
// keep the history of assignment feed back text
String feedbackTextHistory = sPropertiesEdit
.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT) != null ? sPropertiesEdit
.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT)
: "";
feedbackTextHistory = rb.getString("gen.subm6") + now.toStringLocalFull() + "<p />" + sEdit.getFeedbackText() + "<p />" + feedbackTextHistory;
sPropertiesEdit.addProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT,
feedbackTextHistory);
// keep the history of assignment feed back comment
String feedbackCommentHistory = sPropertiesEdit
.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT) != null ? sPropertiesEdit
.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT)
: "";
feedbackCommentHistory = rb.getString("gen.subm6") + now.toStringLocalFull() + "<p />" + sEdit.getFeedbackComment() + "<p />" + feedbackCommentHistory;
sPropertiesEdit.addProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT,
feedbackCommentHistory);
// keep the history of assignment feed back comment
String feedbackAttachmentHistory = sPropertiesEdit
.getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS) != null ? sPropertiesEdit
.getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS)
: "";
List feedbackAttachments = sEdit.getFeedbackAttachments();
String att = rb.getString("gen.subm6") + now.toStringLocalFull() + "<p />";
for (int k = 0; k<feedbackAttachments.size();k++)
{
att = att + ((Reference) feedbackAttachments.get(k)).getReference() + "<p />";
}
feedbackAttachmentHistory = att + feedbackAttachmentHistory;
sPropertiesEdit.addProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS,
feedbackAttachmentHistory);
// reset the previous grading context
sEdit.setFeedbackText("");
sEdit.setFeedbackComment("");
sEdit.clearFeedbackAttachments();
// decrease the allow_resubmit_number
if (sPropertiesEdit.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null)
{
int number = Integer.parseInt(sPropertiesEdit.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER));
// minus 1 from the submit number
if (number>=1)
{
sPropertiesEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, String.valueOf(number-1));
}
else if (number == -1)
{
sPropertiesEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, String.valueOf(-1));
}
}
}
// sEdit.addSubmitter (u);
sEdit.setAssignment(a);
// add attachments
List attachments = (List) state.getAttribute(ATTACHMENTS);
if (attachments != null)
{
//Post the attachments before clearing so that we don't sumbit duplicate attachments
//Check if we need to post the attachments
if (a.getContent().getAllowReviewService()) {
if (!attachments.isEmpty()) {
sEdit.postAttachment(attachments);
}
}
// clear the old attachments first
sEdit.clearSubmittedAttachments();
// add each new attachment
Iterator it = attachments.iterator();
while (it.hasNext())
{
sEdit.addSubmittedAttachment((Reference) it.next());
}
}
AssignmentService.commitEdit(sEdit);
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin2") + " " + a.getTitle());
}
catch (PermissionException e)
{
addAlert(state, rb.getString("no_permissiion_to_edit_submission"));
}
catch (InUseException e)
{
addAlert(state, rb.getString("somelsis") + " " + rb.getString("submiss"));
}
}
else
{
// new submission, post it
try
{
AssignmentSubmissionEdit edit = AssignmentService.addSubmission(contextString, assignmentId, SessionManager.getCurrentSessionUserId());
edit.setSubmittedText(text);
edit.setHonorPledgeFlag(Boolean.valueOf(honorPledgeYes).booleanValue());
edit.setTimeSubmitted(TimeService.newTime());
edit.setSubmitted(true);
// edit.addSubmitter (u);
edit.setAssignment(a);
// add attachments
List attachments = (List) state.getAttribute(ATTACHMENTS);
if (attachments != null)
{
// add each attachment
if ((!attachments.isEmpty()) && a.getContent().getAllowReviewService())
edit.postAttachment(attachments);
// add each attachment
Iterator it = attachments.iterator();
while (it.hasNext())
{
edit.addSubmittedAttachment((Reference) it.next());
}
}
// get the assignment setting for resubmitting
if (a.getProperties().getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null)
{
edit.getPropertiesEdit().addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, a.getProperties().getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER));
}
AssignmentService.commitEdit(edit);
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot13"));
}
} // if -else
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin5"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("not_allowed_to_view"));
}
} // if
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_SUBMISSION_CONFIRMATION);
}
} // if
} // doPost_submission
/**
* Action is to confirm the submission and return to list view
*/
public void doConfirm_assignment_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList());
}
/**
* Action is to show the new assignment screen
*/
public void doNew_assignment(RunData data, Context context)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
if (!alertGlobalNavigation(state, data))
{
if (AssignmentService.allowAddAssignment((String) state.getAttribute(STATE_CONTEXT_STRING)))
{
resetAssignment(state);
state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList());
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT);
}
else
{
addAlert(state, rb.getString("youarenot2"));
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
}
}
} // doNew_Assignment
/**
* Action is to show the reorder assignment screen
*/
public void doReorder(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// this insures the default order is loaded into the reordering tool
state.setAttribute(SORTED_BY, SORTED_BY_DEFAULT);
state.setAttribute(SORTED_ASC, Boolean.TRUE.toString());
if (!alertGlobalNavigation(state, data))
{
if (AssignmentService.allowAllGroups((String) state.getAttribute(STATE_CONTEXT_STRING)))
{
resetAssignment(state);
state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList());
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_REORDER_ASSIGNMENT);
}
else
{
addAlert(state, rb.getString("youarenot19"));
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
}
}
} // doReorder
/**
* Action is to save the input infos for assignment fields
*
* @param validify
* Need to validify the inputs or not
*/
protected void setNewAssignmentParameters(RunData data, boolean validify)
{
// read the form inputs
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
// put the input value into the state attributes
String title = params.getString(NEW_ASSIGNMENT_TITLE);
state.setAttribute(NEW_ASSIGNMENT_TITLE, title);
String order = params.getString(NEW_ASSIGNMENT_ORDER);
state.setAttribute(NEW_ASSIGNMENT_ORDER, order);
if (title.length() == 0)
{
// empty assignment title
addAlert(state, rb.getString("plespethe1"));
}
// open time
int openMonth = (new Integer(params.getString(NEW_ASSIGNMENT_OPENMONTH))).intValue();
state.setAttribute(NEW_ASSIGNMENT_OPENMONTH, new Integer(openMonth));
int openDay = (new Integer(params.getString(NEW_ASSIGNMENT_OPENDAY))).intValue();
state.setAttribute(NEW_ASSIGNMENT_OPENDAY, new Integer(openDay));
int openYear = (new Integer(params.getString(NEW_ASSIGNMENT_OPENYEAR))).intValue();
state.setAttribute(NEW_ASSIGNMENT_OPENYEAR, new Integer(openYear));
int openHour = (new Integer(params.getString(NEW_ASSIGNMENT_OPENHOUR))).intValue();
state.setAttribute(NEW_ASSIGNMENT_OPENHOUR, new Integer(openHour));
int openMin = (new Integer(params.getString(NEW_ASSIGNMENT_OPENMIN))).intValue();
state.setAttribute(NEW_ASSIGNMENT_OPENMIN, new Integer(openMin));
String openAMPM = params.getString(NEW_ASSIGNMENT_OPENAMPM);
state.setAttribute(NEW_ASSIGNMENT_OPENAMPM, openAMPM);
if ((openAMPM.equals("PM")) && (openHour != 12))
{
openHour = openHour + 12;
}
if ((openHour == 12) && (openAMPM.equals("AM")))
{
openHour = 0;
}
Time openTime = TimeService.newTimeLocal(openYear, openMonth, openDay, openHour, openMin, 0, 0);
// validate date
if (!Validator.checkDate(openDay, openMonth, openYear))
{
addAlert(state, rb.getString("date.invalid") + rb.getString("date.opendate") + ".");
}
// due time
int dueMonth = (new Integer(params.getString(NEW_ASSIGNMENT_DUEMONTH))).intValue();
state.setAttribute(NEW_ASSIGNMENT_DUEMONTH, new Integer(dueMonth));
int dueDay = (new Integer(params.getString(NEW_ASSIGNMENT_DUEDAY))).intValue();
state.setAttribute(NEW_ASSIGNMENT_DUEDAY, new Integer(dueDay));
int dueYear = (new Integer(params.getString(NEW_ASSIGNMENT_DUEYEAR))).intValue();
state.setAttribute(NEW_ASSIGNMENT_DUEYEAR, new Integer(dueYear));
int dueHour = (new Integer(params.getString(NEW_ASSIGNMENT_DUEHOUR))).intValue();
state.setAttribute(NEW_ASSIGNMENT_DUEHOUR, new Integer(dueHour));
int dueMin = (new Integer(params.getString(NEW_ASSIGNMENT_DUEMIN))).intValue();
state.setAttribute(NEW_ASSIGNMENT_DUEMIN, new Integer(dueMin));
String dueAMPM = params.getString(NEW_ASSIGNMENT_DUEAMPM);
state.setAttribute(NEW_ASSIGNMENT_DUEAMPM, dueAMPM);
if ((dueAMPM.equals("PM")) && (dueHour != 12))
{
dueHour = dueHour + 12;
}
if ((dueHour == 12) && (dueAMPM.equals("AM")))
{
dueHour = 0;
}
Time dueTime = TimeService.newTimeLocal(dueYear, dueMonth, dueDay, dueHour, dueMin, 0, 0);
// show alert message when due date is in past. Remove it after user confirms the choice.
if (dueTime.before(TimeService.newTime()) && state.getAttribute(NEW_ASSIGNMENT_PAST_DUE_DATE) == null)
{
state.setAttribute(NEW_ASSIGNMENT_PAST_DUE_DATE, Boolean.TRUE);
}
else
{
// clean the attribute after user confirm
state.removeAttribute(NEW_ASSIGNMENT_PAST_DUE_DATE);
}
if (state.getAttribute(NEW_ASSIGNMENT_PAST_DUE_DATE) != null)
{
addAlert(state, rb.getString("assig4"));
}
if (!dueTime.after(openTime))
{
addAlert(state, rb.getString("assig3"));
}
if (!Validator.checkDate(dueDay, dueMonth, dueYear))
{
addAlert(state, rb.getString("date.invalid") + rb.getString("date.duedate") + ".");
}
state.setAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE, new Boolean(true));
// close time
int closeMonth = (new Integer(params.getString(NEW_ASSIGNMENT_CLOSEMONTH))).intValue();
state.setAttribute(NEW_ASSIGNMENT_CLOSEMONTH, new Integer(closeMonth));
int closeDay = (new Integer(params.getString(NEW_ASSIGNMENT_CLOSEDAY))).intValue();
state.setAttribute(NEW_ASSIGNMENT_CLOSEDAY, new Integer(closeDay));
int closeYear = (new Integer(params.getString(NEW_ASSIGNMENT_CLOSEYEAR))).intValue();
state.setAttribute(NEW_ASSIGNMENT_CLOSEYEAR, new Integer(closeYear));
int closeHour = (new Integer(params.getString(NEW_ASSIGNMENT_CLOSEHOUR))).intValue();
state.setAttribute(NEW_ASSIGNMENT_CLOSEHOUR, new Integer(closeHour));
int closeMin = (new Integer(params.getString(NEW_ASSIGNMENT_CLOSEMIN))).intValue();
state.setAttribute(NEW_ASSIGNMENT_CLOSEMIN, new Integer(closeMin));
String closeAMPM = params.getString(NEW_ASSIGNMENT_CLOSEAMPM);
state.setAttribute(NEW_ASSIGNMENT_CLOSEAMPM, closeAMPM);
if ((closeAMPM.equals("PM")) && (closeHour != 12))
{
closeHour = closeHour + 12;
}
if ((closeHour == 12) && (closeAMPM.equals("AM")))
{
closeHour = 0;
}
Time closeTime = TimeService.newTimeLocal(closeYear, closeMonth, closeDay, closeHour, closeMin, 0, 0);
// validate date
if (!Validator.checkDate(closeDay, closeMonth, closeYear))
{
addAlert(state, rb.getString("date.invalid") + rb.getString("date.closedate") + ".");
}
if (!closeTime.after(openTime))
{
addAlert(state, rb.getString("acesubdea3"));
}
if (closeTime.before(dueTime))
{
addAlert(state, rb.getString("acesubdea2"));
}
// SECTION MOD
String sections_string = "";
String mode = (String) state.getAttribute(STATE_MODE);
if (mode == null) mode = "";
state.setAttribute(NEW_ASSIGNMENT_SECTION, sections_string);
state.setAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE, new Integer(params.getString(NEW_ASSIGNMENT_SUBMISSION_TYPE)));
int gradeType = -1;
// grade type and grade points
if (state.getAttribute(WITH_GRADES) != null && ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue())
{
gradeType = Integer.parseInt(params.getString(NEW_ASSIGNMENT_GRADE_TYPE));
state.setAttribute(NEW_ASSIGNMENT_GRADE_TYPE, new Integer(gradeType));
}
String r = params.getString(NEW_ASSIGNMENT_USE_REVIEW_SERVICE);
String b;
// set whether we use the review service or not
if (r == null) b = Boolean.FALSE.toString();
else b = Boolean.TRUE.toString();
state.setAttribute(NEW_ASSIGNMENT_USE_REVIEW_SERVICE, b);
//set whether students can view the review service results
r = params.getString(NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW);
if (r == null) b = Boolean.FALSE.toString();
else b = Boolean.TRUE.toString();
state.setAttribute(NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW, b);
// treat the new assignment description as formatted text
boolean checkForFormattingErrors = true; // instructor is creating a new assignment - so check for errors
String description = processFormattedTextFromBrowser(state, params.getCleanString(NEW_ASSIGNMENT_DESCRIPTION),
checkForFormattingErrors);
state.setAttribute(NEW_ASSIGNMENT_DESCRIPTION, description);
if (state.getAttribute(CALENDAR) != null)
{
// calendar enabled for the site
if (params.getString(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE) != null
&& params.getString(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE).equalsIgnoreCase(Boolean.TRUE.toString()))
{
state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, Boolean.TRUE.toString());
}
else
{
state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, Boolean.FALSE.toString());
}
}
else
{
// no calendar yet for the site
state.removeAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE);
}
if (params.getString(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE) != null
&& params.getString(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE)
.equalsIgnoreCase(Boolean.TRUE.toString()))
{
state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, Boolean.TRUE.toString());
}
else
{
state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, Boolean.FALSE.toString());
}
String s = params.getString(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE);
// set the honor pledge to be "no honor pledge"
if (s == null) s = "1";
state.setAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE, s);
String grading = params.getString(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK);
state.setAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, grading);
// only when choose to associate with assignment in Gradebook
String associateAssignment = params.getString(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT);
if (grading != null)
{
if (grading.equals(AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE))
{
state.setAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, associateAssignment);
}
else
{
state.setAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, "");
}
if (!grading.equals(AssignmentService.GRADEBOOK_INTEGRATION_NO))
{
// gradebook integration only available to point-grade assignment
if (gradeType != Assignment.SCORE_GRADE_TYPE)
{
addAlert(state, rb.getString("addtogradebook.wrongGradeScale"));
}
// if chosen as "associate", have to choose one assignment from Gradebook
if (grading.equals(AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE) && StringUtil.trimToNull(associateAssignment) == null)
{
addAlert(state, rb.getString("grading.associate.alert"));
}
}
}
List attachments = (List) state.getAttribute(ATTACHMENTS);
state.setAttribute(NEW_ASSIGNMENT_ATTACHMENT, attachments);
if (validify)
{
if (((description == null) || (description.length() == 0)) && ((attachments == null || attachments.size() == 0)))
{
// if there is no description nor an attachment, show the following alert message.
// One could ignore the message and still post the assignment
if (state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY) == null)
{
state.setAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY, Boolean.TRUE.toString());
}
else
{
state.removeAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY);
}
}
else
{
state.removeAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY);
}
}
if (validify && state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY) != null)
{
addAlert(state, rb.getString("thiasshas"));
}
if (state.getAttribute(WITH_GRADES) != null && ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue())
{
// the grade point
String gradePoints = params.getString(NEW_ASSIGNMENT_GRADE_POINTS);
state.setAttribute(NEW_ASSIGNMENT_GRADE_POINTS, gradePoints);
if (gradePoints != null)
{
if (gradeType == 3)
{
if ((gradePoints.length() == 0))
{
// in case of point grade assignment, user must specify maximum grade point
addAlert(state, rb.getString("plespethe3"));
}
else
{
validPointGrade(state, gradePoints);
// when scale is points, grade must be integer and less than maximum value
if (state.getAttribute(STATE_MESSAGE) == null)
{
gradePoints = scalePointGrade(state, gradePoints);
}
state.setAttribute(NEW_ASSIGNMENT_GRADE_POINTS, gradePoints);
}
}
}
}
// assignment range?
String range = data.getParameters().getString("range");
state.setAttribute(NEW_ASSIGNMENT_RANGE, range);
if (range.equals("groups"))
{
String[] groupChoice = data.getParameters().getStrings("selectedGroups");
if (groupChoice != null && groupChoice.length != 0)
{
state.setAttribute(NEW_ASSIGNMENT_GROUPS, new ArrayList(Arrays.asList(groupChoice)));
}
else
{
state.setAttribute(NEW_ASSIGNMENT_GROUPS, null);
addAlert(state, rb.getString("java.alert.youchoosegroup"));
}
}
else
{
state.removeAttribute(NEW_ASSIGNMENT_GROUPS);
}
// allow resubmission numbers
String nString = params.getString(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
if (nString != null)
{
state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, nString);
}
// assignment notification option
String notiOption = params.getString(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS);
if (notiOption != null)
{
state.setAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE, notiOption);
}
} // setNewAssignmentParameters
/**
* Action is to hide the preview assignment student view
*/
public void doHide_submission_assignment_instruction(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG, new Boolean(false));
// save user input
readGradeForm(data, state, "read");
} // doHide_preview_assignment_student_view
/**
* Action is to show the preview assignment student view
*/
public void doShow_submission_assignment_instruction(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG, new Boolean(true));
// save user input
readGradeForm(data, state, "read");
} // doShow_submission_assignment_instruction
/**
* Action is to hide the preview assignment student view
*/
public void doHide_preview_assignment_student_view(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG, new Boolean(true));
} // doHide_preview_assignment_student_view
/**
* Action is to show the preview assignment student view
*/
public void doShow_preview_assignment_student_view(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG, new Boolean(false));
} // doShow_preview_assignment_student_view
/**
* Action is to hide the preview assignment assignment infos
*/
public void doHide_preview_assignment_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG, new Boolean(true));
} // doHide_preview_assignment_assignment
/**
* Action is to show the preview assignment assignment info
*/
public void doShow_preview_assignment_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG, new Boolean(false));
} // doShow_preview_assignment_assignment
/**
* Action is to hide the assignment option
*/
public void doHide_assignment_option(RunData data)
{
setNewAssignmentParameters(data, false);
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(NEW_ASSIGNMENT_HIDE_OPTION_FLAG, new Boolean(true));
state.setAttribute(NEW_ASSIGNMENT_FOCUS, "eventSubmit_doShow_assignment_option");
} // doHide_assignment_option
/**
* Action is to show the assignment option
*/
public void doShow_assignment_option(RunData data)
{
setNewAssignmentParameters(data, false);
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(NEW_ASSIGNMENT_HIDE_OPTION_FLAG, new Boolean(false));
state.setAttribute(NEW_ASSIGNMENT_FOCUS, NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE);
} // doShow_assignment_option
/**
* Action is to hide the assignment content in the view assignment page
*/
public void doHide_view_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG, new Boolean(true));
} // doHide_view_assignment
/**
* Action is to show the assignment content in the view assignment page
*/
public void doShow_view_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG, new Boolean(false));
} // doShow_view_assignment
/**
* Action is to hide the student view in the view assignment page
*/
public void doHide_view_student_view(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG, new Boolean(true));
} // doHide_view_student_view
/**
* Action is to show the student view in the view assignment page
*/
public void doShow_view_student_view(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG, new Boolean(false));
} // doShow_view_student_view
/**
* Action is to post assignment
*/
public void doPost_assignment(RunData data)
{
// post assignment
postOrSaveAssignment(data, "post");
} // doPost_assignment
/**
* Action is to tag items via an items tagging helper
*/
public void doHelp_items(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
TaggingManager taggingManager = (TaggingManager) ComponentManager
.get("org.sakaiproject.assignment.taggable.api.TaggingManager");
TaggingProvider provider = taggingManager.findProviderById(params
.getString(PROVIDER_ID));
String activityRef = params.getString(ACTIVITY_REF);
TaggingHelperInfo helperInfo = provider
.getItemsHelperInfo(activityRef);
// get into helper mode with this helper tool
startHelper(data.getRequest(), helperInfo.getHelperId());
Map<String, ? extends Object> helperParms = helperInfo
.getParameterMap();
for (Iterator<String> keys = helperParms.keySet().iterator(); keys
.hasNext();) {
String key = keys.next();
state.setAttribute(key, helperParms.get(key));
}
} // doHelp_items
/**
* Action is to tag an individual item via an item tagging helper
*/
public void doHelp_item(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
TaggingManager taggingManager = (TaggingManager) ComponentManager
.get("org.sakaiproject.assignment.taggable.api.TaggingManager");
TaggingProvider provider = taggingManager.findProviderById(params
.getString(PROVIDER_ID));
String itemRef = params.getString(ITEM_REF);
TaggingHelperInfo helperInfo = provider
.getItemHelperInfo(itemRef);
// get into helper mode with this helper tool
startHelper(data.getRequest(), helperInfo.getHelperId());
Map<String, ? extends Object> helperParms = helperInfo
.getParameterMap();
for (Iterator<String> keys = helperParms.keySet().iterator(); keys
.hasNext();) {
String key = keys.next();
state.setAttribute(key, helperParms.get(key));
}
} // doHelp_item
/**
* Action is to tag an activity via an activity tagging helper
*/
public void doHelp_activity(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
TaggingManager taggingManager = (TaggingManager) ComponentManager
.get("org.sakaiproject.assignment.taggable.api.TaggingManager");
TaggingProvider provider = taggingManager.findProviderById(params
.getString(PROVIDER_ID));
String activityRef = params.getString(ACTIVITY_REF);
TaggingHelperInfo helperInfo = provider
.getActivityHelperInfo(activityRef);
// get into helper mode with this helper tool
startHelper(data.getRequest(), helperInfo.getHelperId());
Map<String, ? extends Object> helperParms = helperInfo
.getParameterMap();
for (String key : helperParms.keySet()) {
state.setAttribute(key, helperParms.get(key));
}
} // doHelp_activity
/**
* post or save assignment
*/
private void postOrSaveAssignment(RunData data, String postOrSave)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String siteId = (String) state.getAttribute(STATE_CONTEXT_STRING);
boolean post = (postOrSave != null) && postOrSave.equals("post");
// assignment old title
String aOldTitle = null;
// assignment old associated Gradebook entry if any
String oAssociateGradebookAssignment = null;
String mode = (String) state.getAttribute(STATE_MODE);
if (!mode.equals(MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT))
{
// read input data if the mode is not preview mode
setNewAssignmentParameters(data, true);
}
String assignmentId = params.getString("assignmentId");
String assignmentContentId = params.getString("assignmentContentId");
// whether this is an editing which changes non-electronic assignment to any other type?
boolean bool_change_from_non_electronic = false;
if (state.getAttribute(STATE_MESSAGE) == null)
{
// AssignmentContent object
AssignmentContentEdit ac = getAssignmentContentEdit(state, assignmentContentId);
// Assignment
AssignmentEdit a = getAssignmentEdit(state, assignmentId);
bool_change_from_non_electronic = change_from_non_electronic(state, assignmentId, assignmentContentId, ac);
// put the names and values into vm file
String title = (String) state.getAttribute(NEW_ASSIGNMENT_TITLE);
String order = (String) state.getAttribute(NEW_ASSIGNMENT_ORDER);
// open time
Time openTime = getOpenTime(state);
// due time
Time dueTime = getDueTime(state);
// close time
Time closeTime = dueTime;
boolean enableCloseDate = ((Boolean) state.getAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE)).booleanValue();
if (enableCloseDate)
{
closeTime = getCloseTime(state);
}
// sections
String section = (String) state.getAttribute(NEW_ASSIGNMENT_SECTION);
int submissionType = ((Integer) state.getAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE)).intValue();
int gradeType = ((Integer) state.getAttribute(NEW_ASSIGNMENT_GRADE_TYPE)).intValue();
String gradePoints = (String) state.getAttribute(NEW_ASSIGNMENT_GRADE_POINTS);
String description = (String) state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION);
String checkAddDueTime = state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE)!=null?(String) state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE):null;
String checkAutoAnnounce = (String) state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE);
String checkAddHonorPledge = (String) state.getAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE);
String addtoGradebook = state.getAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK) != null?(String) state.getAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK):"" ;
String associateGradebookAssignment = (String) state.getAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT);
String allowResubmitNumber = state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null?(String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER):null;
boolean useReviewService = "true".equalsIgnoreCase((String) state.getAttribute(NEW_ASSIGNMENT_USE_REVIEW_SERVICE));
boolean allowStudentViewReport = "true".equalsIgnoreCase((String) state.getAttribute(NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW));
// the attachments
List attachments = (List) state.getAttribute(ATTACHMENTS);
List attachments1 = EntityManager.newReferenceList(attachments);
// set group property
String range = (String) state.getAttribute(NEW_ASSIGNMENT_RANGE);
Collection groups = new Vector();
try
{
Site site = SiteService.getSite(siteId);
Collection groupChoice = (Collection) state.getAttribute(NEW_ASSIGNMENT_GROUPS);
if (range.equals(Assignment.AssignmentAccess.GROUPED) && (groupChoice == null || groupChoice.size() == 0))
{
// show alert if no group is selected for the group access assignment
addAlert(state, rb.getString("java.alert.youchoosegroup"));
}
else if (groupChoice != null)
{
for (Iterator iGroups = groupChoice.iterator(); iGroups.hasNext();)
{
String groupId = (String) iGroups.next();
groups.add(site.getGroup(groupId));
}
}
}
catch (Exception e)
{
Log.warn("chef", this + e.getMessage());
}
if ((state.getAttribute(STATE_MESSAGE) == null) && (ac != null) && (a != null))
{
aOldTitle = a.getTitle();
// old open time
Time oldOpenTime = a.getOpenTime();
// old due time
Time oldDueTime = a.getDueTime();
// commit the changes to AssignmentContent object
commitAssignmentContentEdit(state, ac, title, submissionType,useReviewService,allowStudentViewReport, gradeType, gradePoints, description, checkAddHonorPledge, attachments1);
// set the Assignment Properties object
ResourcePropertiesEdit aPropertiesEdit = a.getPropertiesEdit();
oAssociateGradebookAssignment = aPropertiesEdit.getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT);
editAssignmentProperties(a, checkAddDueTime, checkAutoAnnounce, addtoGradebook, associateGradebookAssignment, allowResubmitNumber, aPropertiesEdit);
// the notification option
if (state.getAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE) != null)
{
aPropertiesEdit.addProperty(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE, (String) state.getAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE));
}
// comment the changes to Assignment object
commitAssignmentEdit(state, post, ac, a, title, openTime, dueTime, closeTime, enableCloseDate, section, range, groups);
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList());
resetAssignment(state);
}
if (post)
{
// only if user is posting the assignment
if (ac.getTypeOfSubmission() == Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION)
{
try
{
// temporally make the assignment to be an draft and undraft it after the following operations are done
AssignmentEdit aEdit = AssignmentService.editAssignment(a.getReference());
aEdit.setDraft(true);
AssignmentService.commitEdit(aEdit);
// for non-electronic assignment
List submissions = AssignmentService.getSubmissions(a);
if (submissions != null && submissions.size() >0)
{
// assignment already exist and with submissions
for (Iterator iSubmissions = submissions.iterator(); iSubmissions.hasNext();)
{
AssignmentSubmission s = (AssignmentSubmission) iSubmissions.next();
// remove all submissions
try
{
AssignmentSubmissionEdit sEdit = AssignmentService.editSubmission(s.getReference());
AssignmentService.removeSubmission(sEdit);
}
catch (Exception ee)
{
Log.debug("chef", this + ee.getMessage() + s.getReference());
}
}
}
// add submission for every one who can submit
HashSet<String> addSubmissionUserIdSet = (HashSet<String>) getAllowAddSubmissionUsersIdSet(AssignmentService.allowAddSubmissionUsers(a.getReference()));
addRemoveSubmissionsForNonElectronicAssignment(state, submissions, addSubmissionUserIdSet, new HashSet(), a);
// undraft it
aEdit = AssignmentService.editAssignment(a.getReference());
aEdit.setDraft(false);
AssignmentService.commitEdit(aEdit);
}
catch (Exception e)
{
Log.debug("chef", this + e.getMessage() + a.getReference());
}
}
else if (bool_change_from_non_electronic)
{
// not non_electronic type any more
List submissions = AssignmentService.getSubmissions(a);
if (submissions != null && submissions.size() >0)
{
// assignment already exist and with submissions
for (Iterator iSubmissions = submissions.iterator(); iSubmissions.hasNext();)
{
AssignmentSubmission s = (AssignmentSubmission) iSubmissions.next();
try
{
AssignmentSubmissionEdit sEdit = AssignmentService.editSubmission(s.getReference());
sEdit.setSubmitted(false);
sEdit.setTimeSubmitted(null);
AssignmentService.commitEdit(sEdit);
}
catch (Exception e)
{
Log.debug("chef", this + e.getMessage() + s.getReference());
}
}
}
}
// add the due date to schedule if the schedule exists
integrateWithCalendar(state, a, title, dueTime, checkAddDueTime, oldDueTime, aPropertiesEdit);
// the open date been announced
integrateWithAnnouncement(state, aOldTitle, a, title, openTime, checkAutoAnnounce, oldOpenTime);
// integrate with Gradebook
try
{
initIntegrateWithGradebook(state, siteId, aOldTitle, oAssociateGradebookAssignment, a, title, dueTime, gradeType, gradePoints, addtoGradebook, associateGradebookAssignment, range);
}
catch (AssignmentHasIllegalPointsException e)
{
addAlert(state, rb.getString("addtogradebook.illegalPoints"));
}
} //if
} // if
} // if
// set default sorting
setDefaultSort(state);
} // doPost_assignment
/**
*
*/
private boolean change_from_non_electronic(SessionState state, String assignmentId, String assignmentContentId, AssignmentContentEdit ac)
{
// whether this is an editing which changes non-electronic assignment to any other type?
if (StringUtil.trimToNull(assignmentId) != null && StringUtil.trimToNull(assignmentContentId) != null)
{
// editing
if (ac.getTypeOfSubmission() == Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION
&& ((Integer) state.getAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE)).intValue() != Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION)
{
// changing from non-electronic type
return true;
}
}
return false;
}
/**
* default sorting
*/
private void setDefaultSort(SessionState state) {
state.setAttribute(SORTED_BY, SORTED_BY_DEFAULT);
state.setAttribute(SORTED_ASC, Boolean.TRUE.toString());
}
/**
* Add submission objects if necessary for non-electronic type of assignment
* @param state
* @param a
*/
private void addRemoveSubmissionsForNonElectronicAssignment(SessionState state, List submissions, HashSet<String> addSubmissionForUsers, HashSet<String> removeSubmissionForUsers, Assignment a)
{
// create submission object for those user who doesn't have one yet
for (Iterator iUserIds = addSubmissionForUsers.iterator(); iUserIds.hasNext();)
{
String userId = (String) iUserIds.next();
try
{
User u = UserDirectoryService.getUser(userId);
// only include those users that can submit to this assignment
if (u != null)
{
// construct fake submissions for grading purpose
AssignmentSubmissionEdit submission = AssignmentService.addSubmission(a.getContext(), a.getId(), userId);
submission.removeSubmitter(UserDirectoryService.getCurrentUser());
submission.addSubmitter(u);
submission.setTimeSubmitted(TimeService.newTime());
submission.setSubmitted(true);
submission.setAssignment(a);
AssignmentService.commitEdit(submission);
}
}
catch (Exception e)
{
Log.warn("chef", this + e.toString() + "error adding submission for userId = " + userId);
}
}
// remove submission object for those who no longer in the site
for (Iterator iUserIds = removeSubmissionForUsers.iterator(); iUserIds.hasNext();)
{
String userId = (String) iUserIds.next();
String submissionRef = null;
// TODO: we don't have an efficient way to retrieve specific user's submission now, so until then, we still need to iterate the whole submission list
for (Iterator iSubmissions=submissions.iterator(); iSubmissions.hasNext() && submissionRef == null;)
{
AssignmentSubmission submission = (AssignmentSubmission) iSubmissions.next();
List submitterIds = submission.getSubmitterIds();
if (submitterIds != null && submitterIds.size() > 0 && userId.equals((String) submitterIds.get(0)))
{
submissionRef = submission.getReference();
}
}
if (submissionRef != null)
{
try
{
AssignmentSubmissionEdit submissionEdit = AssignmentService.editSubmission(submissionRef);
AssignmentService.removeSubmission(submissionEdit);
}
catch (Exception e)
{
Log.warn("chef", this + e.toString() + " error remove submission for userId = " + userId);
}
}
}
}
private void initIntegrateWithGradebook(SessionState state, String siteId, String aOldTitle, String oAssociateGradebookAssignment, AssignmentEdit a, String title, Time dueTime, int gradeType, String gradePoints, String addtoGradebook, String associateGradebookAssignment, String range) {
String context = (String) state.getAttribute(STATE_CONTEXT_STRING);
boolean gradebookExists = isGradebookDefined();
// only if the gradebook is defined
if (gradebookExists)
{
GradebookService g = (GradebookService) (org.sakaiproject.service.gradebook.shared.GradebookService) ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService");
String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext();
String aReference = a.getReference();
String addUpdateRemoveAssignment = "remove";
if (!addtoGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_NO))
{
// if integrate with Gradebook
if (!AssignmentService.getAllowGroupAssignmentsInGradebook() && (range.equals("groups")))
{
// if grouped assignment is not allowed to add into Gradebook
addAlert(state, rb.getString("java.alert.noGroupedAssignmentIntoGB"));
String ref = "";
try
{
ref = a.getReference();
AssignmentEdit aEdit = AssignmentService.editAssignment(ref);
aEdit.getPropertiesEdit().removeProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK);
aEdit.getPropertiesEdit().removeProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT);
AssignmentService.commitEdit(aEdit);
}
catch (Exception ignore)
{
// ignore the exception
Log.warn("chef", rb.getString("cannotfin2") + ref);
}
integrateGradebook(state, aReference, associateGradebookAssignment, "remove", null, null, -1, null, null, null);
}
else
{
if (addtoGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_ADD))
{
addUpdateRemoveAssignment = AssignmentService.GRADEBOOK_INTEGRATION_ADD;
}
else if (addtoGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE))
{
addUpdateRemoveAssignment = "update";
}
if (!addUpdateRemoveAssignment.equals("remove") && gradeType == 3)
{
try
{
integrateGradebook(state, aReference, associateGradebookAssignment, addUpdateRemoveAssignment, aOldTitle, title, Integer.parseInt (gradePoints), dueTime, null, null);
// add all existing grades, if any, into Gradebook
integrateGradebook(state, aReference, associateGradebookAssignment, null, null, null, -1, null, null, "update");
// if the assignment has been assoicated with a different entry in gradebook before, remove those grades from the entry in Gradebook
if (StringUtil.trimToNull(oAssociateGradebookAssignment) != null && !oAssociateGradebookAssignment.equals(associateGradebookAssignment))
{
// if the old assoicated assignment entry in GB is an external one, but doesn't have anything assoicated with it in Assignment tool, remove it
removeNonAssociatedExternalGradebookEntry(context, a.getReference(), oAssociateGradebookAssignment,g, gradebookUid);
}
}
catch (NumberFormatException nE)
{
alertInvalidPoint(state, gradePoints);
}
}
else
{
integrateGradebook(state, aReference, associateGradebookAssignment, "remove", null, null, -1, null, null, null);
}
}
}
else
{
// need to remove the associated gradebook entry if 1) it is external and 2) no other assignment are associated with it
removeNonAssociatedExternalGradebookEntry(context, a.getReference(), oAssociateGradebookAssignment,g, gradebookUid);
}
}
}
private void removeNonAssociatedExternalGradebookEntry(String context, String assignmentReference, String associateGradebookAssignment, GradebookService g, String gradebookUid) {
boolean isExternalAssignmentDefined=g.isExternalAssignmentDefined(gradebookUid, associateGradebookAssignment);
if (isExternalAssignmentDefined)
{
// iterate through all assignments currently in the site, see if any is associated with this GB entry
Iterator i = AssignmentService.getAssignmentsForContext(context);
boolean found = false;
while (!found && i.hasNext())
{
Assignment aI = (Assignment) i.next();
String gbEntry = aI.getProperties().getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT);
if (aI.getProperties().getProperty(ResourceProperties.PROP_ASSIGNMENT_DELETED) == null && gbEntry != null && gbEntry.equals(associateGradebookAssignment) && !aI.getReference().equals(assignmentReference))
{
found = true;
}
}
// so if none of the assignment in this site is associated with the entry, remove the entry
if (!found)
{
g.removeExternalAssessment(gradebookUid, associateGradebookAssignment);
}
}
}
private void integrateWithAnnouncement(SessionState state, String aOldTitle, AssignmentEdit a, String title, Time openTime, String checkAutoAnnounce, Time oldOpenTime)
{
if (checkAutoAnnounce.equalsIgnoreCase(Boolean.TRUE.toString()))
{
AnnouncementChannel channel = (AnnouncementChannel) state.getAttribute(ANNOUNCEMENT_CHANNEL);
if (channel != null)
{
// whether the assignment's title or open date has been updated
boolean updatedTitle = false;
boolean updatedOpenDate = false;
String openDateAnnounced = StringUtil.trimToNull(a.getProperties().getProperty(NEW_ASSIGNMENT_OPEN_DATE_ANNOUNCED));
String openDateAnnouncementId = StringUtil.trimToNull(a.getPropertiesEdit().getProperty(ResourceProperties.PROP_ASSIGNMENT_OPENDATE_ANNOUNCEMENT_MESSAGE_ID));
if (openDateAnnounced != null && openDateAnnouncementId != null)
{
try
{
AnnouncementMessage message = channel.getAnnouncementMessage(openDateAnnouncementId);
if (!message.getAnnouncementHeader().getSubject().contains(title))/*whether title has been changed*/
{
updatedTitle = true;
}
if (!message.getBody().contains(openTime.toStringLocalFull())) /*whether open date has been changed*/
{
updatedOpenDate = true;
}
}
catch (IdUnusedException e)
{
Log.warn("chef", e.getMessage());
}
catch (PermissionException e)
{
Log.warn("chef", e.getMessage());
}
}
// need to create announcement message if assignment is added or assignment has been updated
if (openDateAnnounced == null || updatedTitle || updatedOpenDate)
{
try
{
AnnouncementMessageEdit message = channel.addAnnouncementMessage();
AnnouncementMessageHeaderEdit header = message.getAnnouncementHeaderEdit();
header.setDraft(/* draft */false);
header.replaceAttachments(/* attachment */EntityManager.newReferenceList());
if (openDateAnnounced == null)
{
// making new announcement
header.setSubject(/* subject */rb.getString("assig6") + " " + title);
}
else
{
// updated title
header.setSubject(/* subject */rb.getString("assig5") + " " + title);
}
if (updatedOpenDate)
{
// revised assignment open date
message.setBody(/* body */rb.getString("newope") + " "
+ FormattedText.convertPlaintextToFormattedText(title) + " " + rb.getString("is") + " "
+ openTime.toStringLocalFull() + ". ");
}
else
{
// assignment open date
message.setBody(/* body */rb.getString("opedat") + " "
+ FormattedText.convertPlaintextToFormattedText(title) + " " + rb.getString("is") + " "
+ openTime.toStringLocalFull() + ". ");
}
// group information
if (a.getAccess().equals(Assignment.AssignmentAccess.GROUPED))
{
try
{
// get the group ids selected
Collection groupRefs = a.getGroups();
// make a collection of Group objects
Collection groups = new Vector();
//make a collection of Group objects from the collection of group ref strings
Site site = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING));
for (Iterator iGroupRefs = groupRefs.iterator(); iGroupRefs.hasNext();)
{
String groupRef = (String) iGroupRefs.next();
groups.add(site.getGroup(groupRef));
}
// set access
header.setGroupAccess(groups);
}
catch (Exception exception)
{
// log
Log.warn("chef", exception.getMessage());
}
}
else
{
// site announcement
header.clearGroupAccess();
}
channel.commitMessage(message, NotificationService.NOTI_NONE);
// commit related properties into Assignment object
String ref = "";
try
{
ref = a.getReference();
AssignmentEdit aEdit = AssignmentService.editAssignment(ref);
aEdit.getPropertiesEdit().addProperty(NEW_ASSIGNMENT_OPEN_DATE_ANNOUNCED, Boolean.TRUE.toString());
if (message != null)
{
aEdit.getPropertiesEdit().addProperty(ResourceProperties.PROP_ASSIGNMENT_OPENDATE_ANNOUNCEMENT_MESSAGE_ID, message.getId());
}
AssignmentService.commitEdit(aEdit);
}
catch (Exception ignore)
{
// ignore the exception
Log.warn("chef", rb.getString("cannotfin2") + ref);
}
}
catch (PermissionException ee)
{
Log.warn("chef", rb.getString("cannotmak"));
}
}
}
} // if
}
private void integrateWithCalendar(SessionState state, AssignmentEdit a, String title, Time dueTime, String checkAddDueTime, Time oldDueTime, ResourcePropertiesEdit aPropertiesEdit)
{
if (state.getAttribute(CALENDAR) != null)
{
Calendar c = (Calendar) state.getAttribute(CALENDAR);
String dueDateScheduled = a.getProperties().getProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED);
String oldEventId = aPropertiesEdit.getProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID);
CalendarEvent e = null;
if (dueDateScheduled != null || oldEventId != null)
{
// find the old event
boolean found = false;
if (oldEventId != null && c != null)
{
try
{
e = c.getEvent(oldEventId);
found = true;
}
catch (IdUnusedException ee)
{
Log.warn("chef", "The old event has been deleted: event id=" + oldEventId + ". ");
}
catch (PermissionException ee)
{
Log.warn("chef", "You do not have the permission to view the schedule event id= "
+ oldEventId + ".");
}
}
else
{
TimeBreakdown b = oldDueTime.breakdownLocal();
// TODO: check- this was new Time(year...), not local! -ggolden
Time startTime = TimeService.newTimeLocal(b.getYear(), b.getMonth(), b.getDay(), 0, 0, 0, 0);
Time endTime = TimeService.newTimeLocal(b.getYear(), b.getMonth(), b.getDay(), 23, 59, 59, 999);
try
{
Iterator events = c.getEvents(TimeService.newTimeRange(startTime, endTime), null)
.iterator();
while ((!found) && (events.hasNext()))
{
e = (CalendarEvent) events.next();
if (((String) e.getDisplayName()).indexOf(rb.getString("assig1") + " " + title) != -1)
{
found = true;
}
}
}
catch (PermissionException ignore)
{
// ignore PermissionException
}
}
if (found)
{
// remove the founded old event
try
{
c.removeEvent(c.getEditEvent(e.getId(), CalendarService.EVENT_REMOVE_CALENDAR));
}
catch (PermissionException ee)
{
Log.warn("chef", rb.getString("cannotrem") + " " + title + ". ");
}
catch (InUseException ee)
{
Log.warn("chef", rb.getString("somelsis") + " " + rb.getString("calen"));
}
catch (IdUnusedException ee)
{
Log.warn("chef", rb.getString("cannotfin6") + e.getId());
}
}
}
if (checkAddDueTime.equalsIgnoreCase(Boolean.TRUE.toString()))
{
if (c != null)
{
// commit related properties into Assignment object
String ref = "";
try
{
ref = a.getReference();
AssignmentEdit aEdit = AssignmentService.editAssignment(ref);
try
{
e = null;
CalendarEvent.EventAccess eAccess = CalendarEvent.EventAccess.SITE;
Collection eGroups = new Vector();
if (aEdit.getAccess().equals(Assignment.AssignmentAccess.GROUPED))
{
eAccess = CalendarEvent.EventAccess.GROUPED;
Collection groupRefs = aEdit.getGroups();
// make a collection of Group objects from the collection of group ref strings
Site site = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING));
for (Iterator iGroupRefs = groupRefs.iterator(); iGroupRefs.hasNext();)
{
String groupRef = (String) iGroupRefs.next();
eGroups.add(site.getGroup(groupRef));
}
}
e = c.addEvent(/* TimeRange */TimeService.newTimeRange(dueTime.getTime(), /* 0 duration */0 * 60 * 1000),
/* title */rb.getString("due") + " " + title,
/* description */rb.getString("assig1") + " " + title + " " + "is due on "
+ dueTime.toStringLocalFull() + ". ",
/* type */rb.getString("deadl"),
/* location */"",
/* access */ eAccess,
/* groups */ eGroups,
/* attachments */EntityManager.newReferenceList());
aEdit.getProperties().addProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED, Boolean.TRUE.toString());
if (e != null)
{
aEdit.getProperties().addProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID, e.getId());
}
// edit the calendar ojbject and add an assignment id field
CalendarEventEdit edit = c.getEditEvent(e.getId(), org.sakaiproject.calendar.api.CalendarService.EVENT_ADD_CALENDAR);
edit.setField(NEW_ASSIGNMENT_DUEDATE_CALENDAR_ASSIGNMENT_ID, a.getId());
c.commitEvent(edit);
}
catch (IdUnusedException ee)
{
Log.warn("chef", ee.getMessage());
}
catch (PermissionException ee)
{
Log.warn("chef", rb.getString("cannotfin1"));
}
catch (Exception ee)
{
Log.warn("chef", ee.getMessage());
}
// try-catch
AssignmentService.commitEdit(aEdit);
}
catch (Exception ignore)
{
// ignore the exception
Log.warn("chef", rb.getString("cannotfin2") + ref);
}
} // if
} // if
}
}
private void commitAssignmentEdit(SessionState state, boolean post, AssignmentContentEdit ac, AssignmentEdit a, String title, Time openTime, Time dueTime, Time closeTime, boolean enableCloseDate, String s, String range, Collection groups)
{
a.setTitle(title);
a.setContent(ac);
a.setContext((String) state.getAttribute(STATE_CONTEXT_STRING));
a.setSection(s);
a.setOpenTime(openTime);
a.setDueTime(dueTime);
// set the drop dead date as the due date
a.setDropDeadTime(dueTime);
if (enableCloseDate)
{
a.setCloseTime(closeTime);
}
else
{
// if editing an old assignment with close date
if (a.getCloseTime() != null)
{
a.setCloseTime(null);
}
}
// post the assignment
a.setDraft(!post);
try
{
if (range.equals("site"))
{
a.setAccess(Assignment.AssignmentAccess.SITE);
a.clearGroupAccess();
}
else if (range.equals("groups"))
{
a.setGroupAccess(groups);
}
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot1"));
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
// commit assignment first
AssignmentService.commitEdit(a);
}
}
private void editAssignmentProperties(AssignmentEdit a, String checkAddDueTime, String checkAutoAnnounce, String addtoGradebook, String associateGradebookAssignment, String allowResubmitNumber, ResourcePropertiesEdit aPropertiesEdit)
{
if (aPropertiesEdit.getProperty("newAssignment") != null)
{
if (aPropertiesEdit.getProperty("newAssignment").equalsIgnoreCase(Boolean.TRUE.toString()))
{
// not a newly created assignment, been added.
aPropertiesEdit.addProperty("newAssignment", Boolean.FALSE.toString());
}
}
else
{
// for newly created assignment
aPropertiesEdit.addProperty("newAssignment", Boolean.TRUE.toString());
}
if (checkAddDueTime != null)
{
aPropertiesEdit.addProperty(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, checkAddDueTime);
}
else
{
aPropertiesEdit.removeProperty(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE);
}
aPropertiesEdit.addProperty(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, checkAutoAnnounce);
aPropertiesEdit.addProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, addtoGradebook);
aPropertiesEdit.addProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, associateGradebookAssignment);
if (addtoGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_ADD))
{
// if the choice is to add an entry into Gradebook, let just mark it as associated with such new entry then
aPropertiesEdit.addProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE);
aPropertiesEdit.addProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, a.getReference());
}
// allow resubmit number
if (allowResubmitNumber != null)
{
aPropertiesEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, allowResubmitNumber);
}
}
private void commitAssignmentContentEdit(SessionState state, AssignmentContentEdit ac, String title, int submissionType,boolean useReviewService, boolean allowStudentViewReport, int gradeType, String gradePoints, String description, String checkAddHonorPledge, List attachments1)
{
ac.setTitle(title);
ac.setInstructions(description);
ac.setHonorPledge(Integer.parseInt(checkAddHonorPledge));
ac.setTypeOfSubmission(submissionType);
ac.setAllowReviewService(useReviewService);
ac.setAllowStudentViewReport(allowStudentViewReport);
ac.setTypeOfGrade(gradeType);
if (gradeType == 3)
{
try
{
ac.setMaxGradePoint(Integer.parseInt(gradePoints));
}
catch (NumberFormatException e)
{
alertInvalidPoint(state, gradePoints);
}
}
ac.setGroupProject(true);
ac.setIndividuallyGraded(false);
if (submissionType != 1)
{
ac.setAllowAttachments(true);
}
else
{
ac.setAllowAttachments(false);
}
// clear attachments
ac.clearAttachments();
// add each attachment
Iterator it = EntityManager.newReferenceList(attachments1).iterator();
while (it.hasNext())
{
Reference r = (Reference) it.next();
ac.addAttachment(r);
}
state.setAttribute(ATTACHMENTS_MODIFIED, new Boolean(false));
// commit the changes
AssignmentService.commitEdit(ac);
}
/**
* reorderAssignments
*/
private void reorderAssignments(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
List assignments = prepPage(state);
Iterator it = assignments.iterator();
// temporarily allow the user to read and write from assignments (asn.revise permission)
SecurityService.pushAdvisor(new SecurityAdvisor()
{
public SecurityAdvice isAllowed(String userId, String function, String reference)
{
return SecurityAdvice.ALLOWED;
}
});
while (it.hasNext()) // reads and writes the parameter for default ordering
{
Assignment a = (Assignment) it.next();
String assignmentid = a.getId();
String assignmentposition = params.getString("position_" + assignmentid);
AssignmentEdit ae = getAssignmentEdit(state, assignmentid);
ae.setPosition_order(new Long(assignmentposition).intValue());
AssignmentService.commitEdit(ae);
}
// clear the permission
SecurityService.clearAdvisors();
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList());
//resetAssignment(state);
}
} // reorderAssignments
private AssignmentEdit getAssignmentEdit(SessionState state, String assignmentId)
{
AssignmentEdit a = null;
if (assignmentId.length() == 0)
{
// create a new assignment
try
{
a = AssignmentService.addAssignment((String) state.getAttribute(STATE_CONTEXT_STRING));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot1"));
}
}
else
{
try
{
// edit assignment
a = AssignmentService.editAssignment(assignmentId);
}
catch (InUseException e)
{
addAlert(state, rb.getString("theassicon"));
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin3"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot14"));
} // try-catch
} // if-else
return a;
}
private AssignmentContentEdit getAssignmentContentEdit(SessionState state, String assignmentContentId)
{
AssignmentContentEdit ac = null;
if (assignmentContentId.length() == 0)
{
// new assignment
try
{
ac = AssignmentService.addAssignmentContent((String) state.getAttribute(STATE_CONTEXT_STRING));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot3"));
}
}
else
{
try
{
// edit assignment
ac = AssignmentService.editAssignmentContent(assignmentContentId);
}
catch (InUseException e)
{
addAlert(state, rb.getString("theassicon"));
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin4"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot15"));
}
}
return ac;
}
private Time getOpenTime(SessionState state)
{
int openMonth = ((Integer) state.getAttribute(NEW_ASSIGNMENT_OPENMONTH)).intValue();
int openDay = ((Integer) state.getAttribute(NEW_ASSIGNMENT_OPENDAY)).intValue();
int openYear = ((Integer) state.getAttribute(NEW_ASSIGNMENT_OPENYEAR)).intValue();
int openHour = ((Integer) state.getAttribute(NEW_ASSIGNMENT_OPENHOUR)).intValue();
int openMin = ((Integer) state.getAttribute(NEW_ASSIGNMENT_OPENMIN)).intValue();
String openAMPM = (String) state.getAttribute(NEW_ASSIGNMENT_OPENAMPM);
if ((openAMPM.equals("PM")) && (openHour != 12))
{
openHour = openHour + 12;
}
if ((openHour == 12) && (openAMPM.equals("AM")))
{
openHour = 0;
}
Time openTime = TimeService.newTimeLocal(openYear, openMonth, openDay, openHour, openMin, 0, 0);
return openTime;
}
private Time getCloseTime(SessionState state)
{
Time closeTime;
int closeMonth = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEMONTH)).intValue();
int closeDay = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEDAY)).intValue();
int closeYear = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEYEAR)).intValue();
int closeHour = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEHOUR)).intValue();
int closeMin = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEMIN)).intValue();
String closeAMPM = (String) state.getAttribute(NEW_ASSIGNMENT_CLOSEAMPM);
if ((closeAMPM.equals("PM")) && (closeHour != 12))
{
closeHour = closeHour + 12;
}
if ((closeHour == 12) && (closeAMPM.equals("AM")))
{
closeHour = 0;
}
closeTime = TimeService.newTimeLocal(closeYear, closeMonth, closeDay, closeHour, closeMin, 0, 0);
return closeTime;
}
private Time getDueTime(SessionState state)
{
int dueMonth = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEMONTH)).intValue();
int dueDay = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEDAY)).intValue();
int dueYear = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEYEAR)).intValue();
int dueHour = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEHOUR)).intValue();
int dueMin = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEMIN)).intValue();
String dueAMPM = (String) state.getAttribute(NEW_ASSIGNMENT_DUEAMPM);
if ((dueAMPM.equals("PM")) && (dueHour != 12))
{
dueHour = dueHour + 12;
}
if ((dueHour == 12) && (dueAMPM.equals("AM")))
{
dueHour = 0;
}
Time dueTime = TimeService.newTimeLocal(dueYear, dueMonth, dueDay, dueHour, dueMin, 0, 0);
return dueTime;
}
private Time getAllowSubmitCloseTime(SessionState state)
{
int closeMonth = ((Integer) state.getAttribute(ALLOW_RESUBMIT_CLOSEMONTH)).intValue();
int closeDay = ((Integer) state.getAttribute(ALLOW_RESUBMIT_CLOSEDAY)).intValue();
int closeYear = ((Integer) state.getAttribute(ALLOW_RESUBMIT_CLOSEYEAR)).intValue();
int closeHour = ((Integer) state.getAttribute(ALLOW_RESUBMIT_CLOSEHOUR)).intValue();
int closeMin = ((Integer) state.getAttribute(ALLOW_RESUBMIT_CLOSEMIN)).intValue();
String closeAMPM = (String) state.getAttribute(ALLOW_RESUBMIT_CLOSEAMPM);
if ((closeAMPM.equals("PM")) && (closeHour != 12))
{
closeHour = closeHour + 12;
}
if ((closeHour == 12) && (closeAMPM.equals("AM")))
{
closeHour = 0;
}
Time closeTime = TimeService.newTimeLocal(closeYear, closeMonth, closeDay, closeHour, closeMin, 0, 0);
return closeTime;
}
/**
* Action is to post new assignment
*/
public void doSave_assignment(RunData data)
{
postOrSaveAssignment(data, "save");
} // doSave_assignment
/**
* Action is to reorder assignments
*/
public void doReorder_assignment(RunData data)
{
reorderAssignments(data);
} // doReorder_assignments
/**
* Action is to preview the selected assignment
*/
public void doPreview_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
setNewAssignmentParameters(data, false);
String assignmentId = data.getParameters().getString("assignmentId");
state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_ID, assignmentId);
String assignmentContentId = data.getParameters().getString("assignmentContentId");
state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENTCONTENT_ID, assignmentContentId);
state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG, new Boolean(false));
state.setAttribute(PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG, new Boolean(true));
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT);
}
} // doPreview_assignment
/**
* Action is to view the selected assignment
*/
public void doView_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
// show the assignment portion
state.setAttribute(VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG, new Boolean(false));
// show the student view portion
state.setAttribute(VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG, new Boolean(true));
String assignmentId = params.getString("assignmentId");
state.setAttribute(VIEW_ASSIGNMENT_ID, assignmentId);
try
{
Assignment a = AssignmentService.getAssignment(assignmentId);
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin3"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot14"));
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_VIEW_ASSIGNMENT);
}
} // doView_Assignment
/**
* Action is for student to view one assignment content
*/
public void doView_assignment_as_student(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String assignmentId = params.getString("assignmentId");
state.setAttribute(VIEW_ASSIGNMENT_ID, assignmentId);
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_ASSIGNMENT);
}
} // doView_assignment_as_student
/**
* Action is to show the edit assignment screen
*/
public void doEdit_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String assignmentId = StringUtil.trimToNull(params.getString("assignmentId"));
// whether the user can modify the assignment
state.setAttribute(EDIT_ASSIGNMENT_ID, assignmentId);
try
{
Assignment a = AssignmentService.getAssignment(assignmentId);
// for the non_electronice assignment, submissions are auto-generated by the time that assignment is created;
// don't need to go through the following checkings.
if (a.getContent().getTypeOfSubmission() != Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION)
{
Iterator submissions = AssignmentService.getSubmissions(a).iterator();
if (submissions.hasNext())
{
// any submitted?
boolean anySubmitted = false;
for (;submissions.hasNext() && !anySubmitted;)
{
AssignmentSubmission s = (AssignmentSubmission) submissions.next();
if (s.getSubmitted() && s.getTimeSubmitted() != null)
{
anySubmitted = true;
}
}
// any draft submission
boolean anyDraft = false;
for (;submissions.hasNext() && !anyDraft;)
{
AssignmentSubmission s = (AssignmentSubmission) submissions.next();
if (!s.getSubmitted())
{
anyDraft = true;
}
}
if (anySubmitted)
{
// if there is any submitted submission to this assignment, show alert
addAlert(state, rb.getString("assig1") + " " + a.getTitle() + " " + rb.getString("hassum"));
}
if (anyDraft)
{
// otherwise, show alert about someone has started working on the assignment, not necessarily submitted
addAlert(state, rb.getString("hasDraftSum"));
}
}
}
// SECTION MOD
state.setAttribute(STATE_SECTION_STRING, a.getSection());
// put the names and values into vm file
state.setAttribute(NEW_ASSIGNMENT_TITLE, a.getTitle());
state.setAttribute(NEW_ASSIGNMENT_ORDER, a.getPosition_order());
TimeBreakdown openTime = a.getOpenTime().breakdownLocal();
state.setAttribute(NEW_ASSIGNMENT_OPENMONTH, new Integer(openTime.getMonth()));
state.setAttribute(NEW_ASSIGNMENT_OPENDAY, new Integer(openTime.getDay()));
state.setAttribute(NEW_ASSIGNMENT_OPENYEAR, new Integer(openTime.getYear()));
int openHour = openTime.getHour();
if (openHour >= 12)
{
state.setAttribute(NEW_ASSIGNMENT_OPENAMPM, "PM");
}
else
{
state.setAttribute(NEW_ASSIGNMENT_OPENAMPM, "AM");
}
if (openHour == 0)
{
// for midnight point, we mark it as 12AM
openHour = 12;
}
state.setAttribute(NEW_ASSIGNMENT_OPENHOUR, new Integer((openHour > 12) ? openHour - 12 : openHour));
state.setAttribute(NEW_ASSIGNMENT_OPENMIN, new Integer(openTime.getMin()));
TimeBreakdown dueTime = a.getDueTime().breakdownLocal();
state.setAttribute(NEW_ASSIGNMENT_DUEMONTH, new Integer(dueTime.getMonth()));
state.setAttribute(NEW_ASSIGNMENT_DUEDAY, new Integer(dueTime.getDay()));
state.setAttribute(NEW_ASSIGNMENT_DUEYEAR, new Integer(dueTime.getYear()));
int dueHour = dueTime.getHour();
if (dueHour >= 12)
{
state.setAttribute(NEW_ASSIGNMENT_DUEAMPM, "PM");
}
else
{
state.setAttribute(NEW_ASSIGNMENT_DUEAMPM, "AM");
}
if (dueHour == 0)
{
// for midnight point, we mark it as 12AM
dueHour = 12;
}
state.setAttribute(NEW_ASSIGNMENT_DUEHOUR, new Integer((dueHour > 12) ? dueHour - 12 : dueHour));
state.setAttribute(NEW_ASSIGNMENT_DUEMIN, new Integer(dueTime.getMin()));
// generate alert when editing an assignment past due date
if (a.getDueTime().before(TimeService.newTime()))
{
addAlert(state, rb.getString("youarenot17"));
}
if (a.getCloseTime() != null)
{
state.setAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE, new Boolean(true));
TimeBreakdown closeTime = a.getCloseTime().breakdownLocal();
state.setAttribute(NEW_ASSIGNMENT_CLOSEMONTH, new Integer(closeTime.getMonth()));
state.setAttribute(NEW_ASSIGNMENT_CLOSEDAY, new Integer(closeTime.getDay()));
state.setAttribute(NEW_ASSIGNMENT_CLOSEYEAR, new Integer(closeTime.getYear()));
int closeHour = closeTime.getHour();
if (closeHour >= 12)
{
state.setAttribute(NEW_ASSIGNMENT_CLOSEAMPM, "PM");
}
else
{
state.setAttribute(NEW_ASSIGNMENT_CLOSEAMPM, "AM");
}
if (closeHour == 0)
{
// for the midnight point, we mark it as 12 AM
closeHour = 12;
}
state.setAttribute(NEW_ASSIGNMENT_CLOSEHOUR, new Integer((closeHour > 12) ? closeHour - 12 : closeHour));
state.setAttribute(NEW_ASSIGNMENT_CLOSEMIN, new Integer(closeTime.getMin()));
}
else
{
state.setAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE, new Boolean(false));
state.setAttribute(NEW_ASSIGNMENT_CLOSEMONTH, state.getAttribute(NEW_ASSIGNMENT_DUEMONTH));
state.setAttribute(NEW_ASSIGNMENT_CLOSEDAY, state.getAttribute(NEW_ASSIGNMENT_DUEDAY));
state.setAttribute(NEW_ASSIGNMENT_CLOSEYEAR, state.getAttribute(NEW_ASSIGNMENT_DUEYEAR));
state.setAttribute(NEW_ASSIGNMENT_CLOSEHOUR, state.getAttribute(NEW_ASSIGNMENT_DUEHOUR));
state.setAttribute(NEW_ASSIGNMENT_CLOSEMIN, state.getAttribute(NEW_ASSIGNMENT_DUEMIN));
state.setAttribute(NEW_ASSIGNMENT_CLOSEAMPM, state.getAttribute(NEW_ASSIGNMENT_DUEAMPM));
}
state.setAttribute(NEW_ASSIGNMENT_SECTION, a.getSection());
state.setAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE, new Integer(a.getContent().getTypeOfSubmission()));
int typeOfGrade = a.getContent().getTypeOfGrade();
state.setAttribute(NEW_ASSIGNMENT_GRADE_TYPE, new Integer(typeOfGrade));
if (typeOfGrade == 3)
{
state.setAttribute(NEW_ASSIGNMENT_GRADE_POINTS, a.getContent().getMaxGradePointDisplay());
}
state.setAttribute(NEW_ASSIGNMENT_DESCRIPTION, a.getContent().getInstructions());
ResourceProperties properties = a.getProperties();
state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, properties.getProperty(
ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE));
state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, properties.getProperty(
ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE));
state.setAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE, Integer.toString(a.getContent().getHonorPledge()));
state.setAttribute(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, properties.getProperty(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK));
state.setAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, properties.getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT));
state.setAttribute(ATTACHMENTS, a.getContent().getAttachments());
// notification option
if (properties.getProperty(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE) != null)
{
state.setAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE, properties.getProperty(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE));
}
// group setting
if (a.getAccess().equals(Assignment.AssignmentAccess.SITE))
{
state.setAttribute(NEW_ASSIGNMENT_RANGE, "site");
}
else
{
state.setAttribute(NEW_ASSIGNMENT_RANGE, "groups");
}
state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, properties.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null?properties.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER):"0");
// set whether we use the review service or not
state.setAttribute(NEW_ASSIGNMENT_USE_REVIEW_SERVICE, new Boolean(a.getContent().getAllowReviewService()).toString());
//set whether students can view the review service results
state.setAttribute(NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW, new Boolean(a.getContent().getAllowStudentViewReport()).toString());
state.setAttribute(NEW_ASSIGNMENT_GROUPS, a.getGroups());
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin3"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot14"));
}
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT);
} // doEdit_Assignment
/**
* Action is to show the delete assigment confirmation screen
*/
public void doDelete_confirm_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String[] assignmentIds = params.getStrings("selectedAssignments");
if (assignmentIds != null)
{
Vector ids = new Vector();
for (int i = 0; i < assignmentIds.length; i++)
{
String id = (String) assignmentIds[i];
if (!AssignmentService.allowRemoveAssignment(id))
{
addAlert(state, rb.getString("youarenot9") + " " + id + ". ");
}
ids.add(id);
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
// can remove all the selected assignments
state.setAttribute(DELETE_ASSIGNMENT_IDS, ids);
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_DELETE_ASSIGNMENT);
}
}
else
{
addAlert(state, rb.getString("youmust6"));
}
} // doDelete_confirm_Assignment
/**
* Action is to delete the confirmed assignments
*/
public void doDelete_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// get the delete assignment ids
Vector ids = (Vector) state.getAttribute(DELETE_ASSIGNMENT_IDS);
for (int i = 0; i < ids.size(); i++)
{
String assignmentId = (String) ids.get(i);
try
{
AssignmentEdit aEdit = AssignmentService.editAssignment(assignmentId);
ResourcePropertiesEdit pEdit = aEdit.getPropertiesEdit();
String associateGradebookAssignment = pEdit.getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT);
String title = aEdit.getTitle();
// remove releted event if there is one
String isThereEvent = pEdit.getProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED);
if (isThereEvent != null && isThereEvent.equals(Boolean.TRUE.toString()))
{
removeCalendarEvent(state, aEdit, pEdit, title);
} // if-else
if (!AssignmentService.getSubmissions(aEdit).iterator().hasNext())
{
// there is no submission to this assignment yet, delete the assignment record completely
try
{
TaggingManager taggingManager = (TaggingManager) ComponentManager
.get("org.sakaiproject.assignment.taggable.api.TaggingManager");
AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager
.get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer");
if (taggingManager.isTaggable()) {
for (TaggingProvider provider : taggingManager
.getProviders()) {
provider.removeTags(assignmentActivityProducer
.getActivity(aEdit));
}
}
AssignmentService.removeAssignment(aEdit);
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot11") + " " + aEdit.getTitle() + ". ");
}
}
else
{
// remove the assignment by marking the remove status property true
pEdit.addProperty(ResourceProperties.PROP_ASSIGNMENT_DELETED, Boolean.TRUE.toString());
AssignmentService.commitEdit(aEdit);
}
// remove from Gradebook
integrateGradebook(state, (String) ids.get (i), associateGradebookAssignment, "remove", null, null, -1, null, null, null);
}
catch (InUseException e)
{
addAlert(state, rb.getString("somelsis") + " " + rb.getString("assig2"));
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin3"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot6"));
}
} // for
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(DELETE_ASSIGNMENT_IDS, new Vector());
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
}
} // doDelete_Assignment
private void removeCalendarEvent(SessionState state, AssignmentEdit aEdit, ResourcePropertiesEdit pEdit, String title) throws PermissionException
{
// remove the associated calender event
Calendar c = (Calendar) state.getAttribute(CALENDAR);
if (c != null)
{
// already has calendar object
// get the old event
CalendarEvent e = null;
boolean found = false;
String oldEventId = pEdit.getProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID);
if (oldEventId != null)
{
try
{
e = c.getEvent(oldEventId);
found = true;
}
catch (IdUnusedException ee)
{
// no action needed for this condition
}
catch (PermissionException ee)
{
}
}
else
{
TimeBreakdown b = aEdit.getDueTime().breakdownLocal();
// TODO: check- this was new Time(year...), not local! -ggolden
Time startTime = TimeService.newTimeLocal(b.getYear(), b.getMonth(), b.getDay(), 0, 0, 0, 0);
Time endTime = TimeService.newTimeLocal(b.getYear(), b.getMonth(), b.getDay(), 23, 59, 59, 999);
Iterator events = c.getEvents(TimeService.newTimeRange(startTime, endTime), null).iterator();
while ((!found) && (events.hasNext()))
{
e = (CalendarEvent) events.next();
if (((String) e.getDisplayName()).indexOf(rb.getString("assig1") + " " + title) != -1)
{
found = true;
}
}
}
// remove the founded old event
if (found)
{
// found the old event delete it
try
{
c.removeEvent(c.getEditEvent(e.getId(), CalendarService.EVENT_REMOVE_CALENDAR));
pEdit.removeProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED);
pEdit.removeProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID);
}
catch (PermissionException ee)
{
Log.warn("chef", rb.getString("cannotrem") + " " + title + ". ");
}
catch (InUseException ee)
{
Log.warn("chef", rb.getString("somelsis") + " " + rb.getString("calen"));
}
catch (IdUnusedException ee)
{
Log.warn("chef", rb.getString("cannotfin6") + e.getId());
}
}
}
}
/**
* Action is to delete the assignment and also the related AssignmentSubmission
*/
public void doDeep_delete_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// get the delete assignment ids
Vector ids = (Vector) state.getAttribute(DELETE_ASSIGNMENT_IDS);
for (int i = 0; i < ids.size(); i++)
{
String currentId = (String) ids.get(i);
try
{
AssignmentEdit a = AssignmentService.editAssignment(currentId);
try
{
TaggingManager taggingManager = (TaggingManager) ComponentManager
.get("org.sakaiproject.assignment.taggable.api.TaggingManager");
AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager
.get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer");
if (taggingManager.isTaggable()) {
for (TaggingProvider provider : taggingManager
.getProviders()) {
provider.removeTags(assignmentActivityProducer
.getActivity(a));
}
}
AssignmentService.removeAssignment(a);
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot11") + " " + a.getTitle() + ". ");
}
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin3"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot14"));
}
catch (InUseException e)
{
addAlert(state, rb.getString("somelsis") + " " + rb.getString("assig2"));
}
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(DELETE_ASSIGNMENT_IDS, new Vector());
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
}
} // doDeep_delete_Assignment
/**
* Action is to show the duplicate assignment screen
*/
public void doDuplicate_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// we are changing the view, so start with first page again.
resetPaging(state);
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
ParameterParser params = data.getParameters();
String assignmentId = StringUtil.trimToNull(params.getString("assignmentId"));
if (assignmentId != null)
{
try
{
AssignmentEdit aEdit = AssignmentService.addDuplicateAssignment(contextString, assignmentId);
// clean the duplicate's property
ResourcePropertiesEdit aPropertiesEdit = aEdit.getPropertiesEdit();
aPropertiesEdit.removeProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED);
aPropertiesEdit.removeProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID);
aPropertiesEdit.removeProperty(NEW_ASSIGNMENT_OPEN_DATE_ANNOUNCED);
aPropertiesEdit.removeProperty(ResourceProperties.PROP_ASSIGNMENT_OPENDATE_ANNOUNCEMENT_MESSAGE_ID);
AssignmentService.commitEdit(aEdit);
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot5"));
}
catch (IdInvalidException e)
{
addAlert(state, rb.getString("theassiid") + " " + assignmentId + " " + rb.getString("isnotval"));
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("theassiid") + " " + assignmentId + " " + rb.getString("hasnotbee"));
}
catch (Exception e)
{
}
}
} // doDuplicate_Assignment
/**
* Action is to show the grade submission screen
*/
public void doGrade_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// reset the submission context
resetViewSubmission(state);
ParameterParser params = data.getParameters();
// reset the grade assignment id
state.setAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID, params.getString("assignmentId"));
state.setAttribute(GRADE_SUBMISSION_SUBMISSION_ID, params.getString("submissionId"));
// allow resubmit number
String allowResubmitNumber = "0";
Assignment a = null;
try
{
a = AssignmentService.getAssignment((String) state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID));
if (a.getProperties().getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null)
{
allowResubmitNumber= a.getProperties().getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
}
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin5"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("not_allowed_to_view"));
}
try
{
AssignmentSubmission s = AssignmentService.getSubmission((String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID));
if ((s.getFeedbackText() == null) || (s.getFeedbackText().length() == 0))
{
state.setAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT, s.getSubmittedText());
}
else
{
state.setAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT, s.getFeedbackText());
}
state.setAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT, s.getFeedbackComment());
List v = EntityManager.newReferenceList();
Iterator attachments = s.getFeedbackAttachments().iterator();
while (attachments.hasNext())
{
v.add(attachments.next());
}
state.setAttribute(ATTACHMENTS, v);
state.setAttribute(GRADE_SUBMISSION_GRADE, s.getGrade());
ResourceProperties p = s.getProperties();
if (p.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null)
{
allowResubmitNumber = p.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
}
else if (p.getProperty(GRADE_SUBMISSION_ALLOW_RESUBMIT) != null)
{
// if there is any legacy setting for generally allow resubmit, set the allow resubmit number to be 1, and remove the legacy property
allowResubmitNumber = "1";
}
state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, allowResubmitNumber);
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin5"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("not_allowed_to_view"));
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute(GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG, new Boolean(false));
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_SUBMISSION);
}
} // doGrade_submission
/**
* Action is to release all the grades of the submission
*/
public void doRelease_grades(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
try
{
// get the assignment
Assignment a = AssignmentService.getAssignment(params.getString("assignmentId"));
String aReference = a.getReference();
Iterator submissions = AssignmentService.getSubmissions(a).iterator();
while (submissions.hasNext())
{
AssignmentSubmission s = (AssignmentSubmission) submissions.next();
if (s.getGraded())
{
AssignmentSubmissionEdit sEdit = AssignmentService.editSubmission(s.getReference());
String grade = s.getGrade();
boolean withGrade = state.getAttribute(WITH_GRADES) != null ? ((Boolean) state.getAttribute(WITH_GRADES))
.booleanValue() : false;
if (withGrade)
{
// for the assignment tool with grade option, a valide grade is needed
if (grade != null && !grade.equals(""))
{
sEdit.setGradeReleased(true);
}
}
else
{
// for the assignment tool without grade option, no grade is needed
sEdit.setGradeReleased(true);
}
// also set the return status
sEdit.setReturned(true);
sEdit.setTimeReturned(TimeService.newTime());
sEdit.setHonorPledgeFlag(Boolean.FALSE.booleanValue());
AssignmentService.commitEdit(sEdit);
}
} // while
// add grades into Gradebook
String integrateWithGradebook = a.getProperties().getProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK);
if (integrateWithGradebook != null && !integrateWithGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_NO))
{
// integrate with Gradebook
String associateGradebookAssignment = StringUtil.trimToNull(a.getProperties().getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT));
integrateGradebook(state, aReference, associateGradebookAssignment, null, null, null, -1, null, null, "update");
}
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin3"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot14"));
}
catch (InUseException e)
{
addAlert(state, rb.getString("somelsis") + " " + rb.getString("submiss"));
}
} // doRelease_grades
/**
* Action is to show the assignment in grading page
*/
public void doExpand_grade_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(GRADE_ASSIGNMENT_EXPAND_FLAG, new Boolean(true));
} // doExpand_grade_assignment
/**
* Action is to hide the assignment in grading page
*/
public void doCollapse_grade_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(GRADE_ASSIGNMENT_EXPAND_FLAG, new Boolean(false));
} // doCollapse_grade_assignment
/**
* Action is to show the submissions in grading page
*/
public void doExpand_grade_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(GRADE_SUBMISSION_EXPAND_FLAG, new Boolean(true));
} // doExpand_grade_submission
/**
* Action is to hide the submissions in grading page
*/
public void doCollapse_grade_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(GRADE_SUBMISSION_EXPAND_FLAG, new Boolean(false));
} // doCollapse_grade_submission
/**
* Action is to show the grade assignment
*/
public void doGrade_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
// clean state attribute
state.removeAttribute(USER_SUBMISSIONS);
state.setAttribute(EXPORT_ASSIGNMENT_REF, params.getString("assignmentId"));
try
{
Assignment a = AssignmentService.getAssignment((String) state.getAttribute(EXPORT_ASSIGNMENT_REF));
state.setAttribute(EXPORT_ASSIGNMENT_ID, a.getId());
state.setAttribute(GRADE_ASSIGNMENT_EXPAND_FLAG, new Boolean(false));
state.setAttribute(GRADE_SUBMISSION_EXPAND_FLAG, new Boolean(true));
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT);
// we are changing the view, so start with first page again.
resetPaging(state);
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin3"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot14"));
}
} // doGrade_assignment
/**
* Action is to show the View Students assignment screen
*/
public void doView_students_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT);
} // doView_students_Assignment
/**
* Action is to show the student submissions
*/
public void doShow_student_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
Set t = (Set) state.getAttribute(STUDENT_LIST_SHOW_TABLE);
ParameterParser params = data.getParameters();
String id = params.getString("studentId");
// add the student id into the table
t.add(id);
state.setAttribute(STUDENT_LIST_SHOW_TABLE, t);
} // doShow_student_submission
/**
* Action is to hide the student submissions
*/
public void doHide_student_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
Set t = (Set) state.getAttribute(STUDENT_LIST_SHOW_TABLE);
ParameterParser params = data.getParameters();
String id = params.getString("studentId");
// remove the student id from the table
t.remove(id);
state.setAttribute(STUDENT_LIST_SHOW_TABLE, t);
} // doHide_student_submission
/**
* Action is to show the graded assignment submission
*/
public void doView_grade(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
state.setAttribute(VIEW_GRADE_SUBMISSION_ID, params.getString("submissionId"));
state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_GRADE);
} // doView_grade
/**
* Action is to show the student submissions
*/
public void doReport_submissions(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_REPORT_SUBMISSIONS);
state.setAttribute(SORTED_BY, SORTED_SUBMISSION_BY_LASTNAME);
state.setAttribute(SORTED_ASC, Boolean.TRUE.toString());
} // doReport_submissions
/**
*
*
*/
public void doAssignment_form(RunData data)
{
ParameterParser params = data.getParameters();
String option = (String) params.getString("option");
if (option != null)
{
if (option.equals("post"))
{
// post assignment
doPost_assignment(data);
}
else if (option.equals("save"))
{
// save assignment
doSave_assignment(data);
}
else if (option.equals("reorder"))
{
// reorder assignments
doReorder_assignment(data);
}
else if (option.equals("preview"))
{
// preview assignment
doPreview_assignment(data);
}
else if (option.equals("cancel"))
{
// cancel creating assignment
doCancel_new_assignment(data);
}
else if (option.equals("canceledit"))
{
// cancel editing assignment
doCancel_edit_assignment(data);
}
else if (option.equals("attach"))
{
// attachments
doAttachments(data);
}
else if (option.equals("view"))
{
// view
doView(data);
}
else if (option.equals("permissions"))
{
// permissions
doPermissions(data);
}
else if (option.equals("returngrade"))
{
// return grading
doReturn_grade_submission(data);
}
else if (option.equals("savegrade"))
{
// save grading
doSave_grade_submission(data);
}
else if (option.equals("previewgrade"))
{
// preview grading
doPreview_grade_submission(data);
}
else if (option.equals("cancelgrade"))
{
// cancel grading
doCancel_grade_submission(data);
}
else if (option.equals("cancelreorder"))
{
// cancel reordering
doCancel_reorder(data);
}
else if (option.equals("sortbygrouptitle"))
{
// read input data
setNewAssignmentParameters(data, true);
// sort by group title
doSortbygrouptitle(data);
}
else if (option.equals("sortbygroupdescription"))
{
// read input data
setNewAssignmentParameters(data, true);
// sort group by description
doSortbygroupdescription(data);
}
else if (option.equals("hide_instruction"))
{
// hide the assignment instruction
doHide_submission_assignment_instruction(data);
}
else if (option.equals("show_instruction"))
{
// show the assignment instruction
doShow_submission_assignment_instruction(data);
}
else if (option.equals("sortbygroupdescription"))
{
// show the assignment instruction
doShow_submission_assignment_instruction(data);
}
else if (option.equals("revise") || option.equals("done"))
{
// back from the preview mode
doDone_preview_new_assignment(data);
}
}
}
/**
* Action is to use when doAattchmentsadding requested, corresponding to chef_Assignments-new "eventSubmit_doAattchmentsadding" when "add attachments" is clicked
*/
public void doAttachments(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String mode = (String) state.getAttribute(STATE_MODE);
if (mode.equals(MODE_STUDENT_VIEW_SUBMISSION))
{
// retrieve the submission text (as formatted text)
boolean checkForFormattingErrors = true; // the student is submitting something - so check for errors
String text = processFormattedTextFromBrowser(state, params.getCleanString(VIEW_SUBMISSION_TEXT),
checkForFormattingErrors);
state.setAttribute(VIEW_SUBMISSION_TEXT, text);
if (params.getString(VIEW_SUBMISSION_HONOR_PLEDGE_YES) != null)
{
state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, "true");
}
// TODO: file picker to save in dropbox? -ggolden
// User[] users = { UserDirectoryService.getCurrentUser() };
// state.setAttribute(ResourcesAction.STATE_SAVE_ATTACHMENT_IN_DROPBOX, users);
}
else if (mode.equals(MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT))
{
setNewAssignmentParameters(data, false);
}
else if (mode.equals(MODE_INSTRUCTOR_GRADE_SUBMISSION))
{
readGradeForm(data, state, "read");
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
// get into helper mode with this helper tool
startHelper(data.getRequest(), "sakai.filepicker");
state.setAttribute(FilePickerHelper.FILE_PICKER_TITLE_TEXT, rb.getString("gen.addatttoassig"));
state.setAttribute(FilePickerHelper.FILE_PICKER_INSTRUCTION_TEXT, rb.getString("gen.addatttoassiginstr"));
// use the real attachment list
state.setAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS, state.getAttribute(ATTACHMENTS));
}
}
/**
* readGradeForm
*/
public void readGradeForm(RunData data, SessionState state, String gradeOption)
{
ParameterParser params = data.getParameters();
boolean withGrade = state.getAttribute(WITH_GRADES) != null ? ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue()
: false;
boolean checkForFormattingErrors = false; // so that grading isn't held up by formatting errors
String feedbackComment = processFormattedTextFromBrowser(state, params.getCleanString(GRADE_SUBMISSION_FEEDBACK_COMMENT),
checkForFormattingErrors);
if (feedbackComment != null)
{
state.setAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT, feedbackComment);
}
String feedbackText = processAssignmentFeedbackFromBrowser(state, params.getCleanString(GRADE_SUBMISSION_FEEDBACK_TEXT));
if (feedbackText != null)
{
state.setAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT, feedbackText);
}
state.setAttribute(GRADE_SUBMISSION_FEEDBACK_ATTACHMENT, state.getAttribute(ATTACHMENTS));
String g = params.getCleanString(GRADE_SUBMISSION_GRADE);
if (g != null)
{
state.setAttribute(GRADE_SUBMISSION_GRADE, g);
}
String sId = (String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID);
try
{
// for points grading, one have to enter number as the points
String grade = (String) state.getAttribute(GRADE_SUBMISSION_GRADE);
Assignment a = AssignmentService.getSubmission(sId).getAssignment();
int typeOfGrade = a.getContent().getTypeOfGrade();
if (withGrade)
{
// do grade validation only for Assignment with Grade tool
if (typeOfGrade == 3)
{
if ((grade.length() == 0))
{
state.setAttribute(GRADE_SUBMISSION_GRADE, grade);
}
else
{
// the preview grade process might already scaled up the grade by 10
if (!((String) state.getAttribute(STATE_MODE)).equals(MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION))
{
validPointGrade(state, grade);
if (state.getAttribute(STATE_MESSAGE) == null)
{
int maxGrade = a.getContent().getMaxGradePoint();
try
{
if (Integer.parseInt(scalePointGrade(state, grade)) > maxGrade)
{
if (state.getAttribute(GRADE_GREATER_THAN_MAX_ALERT) == null)
{
// alert user first when he enters grade bigger than max scale
addAlert(state, rb.getString("grad2"));
state.setAttribute(GRADE_GREATER_THAN_MAX_ALERT, Boolean.TRUE);
}
else
{
// remove the alert once user confirms he wants to give student higher grade
state.removeAttribute(GRADE_GREATER_THAN_MAX_ALERT);
}
}
}
catch (NumberFormatException e)
{
alertInvalidPoint(state, grade);
}
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
grade = scalePointGrade(state, grade);
}
state.setAttribute(GRADE_SUBMISSION_GRADE, grade);
}
}
}
// if ungraded and grade type is not "ungraded" type
if ((grade == null || grade.equals("ungraded")) && (typeOfGrade != 1) && gradeOption.equals("release"))
{
addAlert(state, rb.getString("plespethe2"));
}
}
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin5"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("not_allowed_to_view"));
}
// allow resubmit number and due time
if (params.getString(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null)
{
String allowResubmitNumberString = params.getString(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, params.getString(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER));
if (Integer.parseInt(allowResubmitNumberString) != 0)
{
int closeMonth = (new Integer(params.getString(ALLOW_RESUBMIT_CLOSEMONTH))).intValue();
state.setAttribute(ALLOW_RESUBMIT_CLOSEMONTH, new Integer(closeMonth));
int closeDay = (new Integer(params.getString(ALLOW_RESUBMIT_CLOSEDAY))).intValue();
state.setAttribute(ALLOW_RESUBMIT_CLOSEDAY, new Integer(closeDay));
int closeYear = (new Integer(params.getString(ALLOW_RESUBMIT_CLOSEYEAR))).intValue();
state.setAttribute(ALLOW_RESUBMIT_CLOSEYEAR, new Integer(closeYear));
int closeHour = (new Integer(params.getString(ALLOW_RESUBMIT_CLOSEHOUR))).intValue();
state.setAttribute(ALLOW_RESUBMIT_CLOSEHOUR, new Integer(closeHour));
int closeMin = (new Integer(params.getString(ALLOW_RESUBMIT_CLOSEMIN))).intValue();
state.setAttribute(ALLOW_RESUBMIT_CLOSEMIN, new Integer(closeMin));
String closeAMPM = params.getString(ALLOW_RESUBMIT_CLOSEAMPM);
state.setAttribute(ALLOW_RESUBMIT_CLOSEAMPM, closeAMPM);
if ((closeAMPM.equals("PM")) && (closeHour != 12))
{
closeHour = closeHour + 12;
}
if ((closeHour == 12) && (closeAMPM.equals("AM")))
{
closeHour = 0;
}
Time closeTime = TimeService.newTimeLocal(closeYear, closeMonth, closeDay, closeHour, closeMin, 0, 0);
state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME, String.valueOf(closeTime.getTime()));
// validate date
if (closeTime.before(TimeService.newTime()))
{
addAlert(state, rb.getString("acesubdea4"));
}
if (!Validator.checkDate(closeDay, closeMonth, closeYear))
{
addAlert(state, rb.getString("date.invalid") + rb.getString("date.closedate") + ".");
}
}
else
{
// reset the state attributes
state.removeAttribute(ALLOW_RESUBMIT_CLOSEMONTH);
state.removeAttribute(ALLOW_RESUBMIT_CLOSEDAY);
state.removeAttribute(ALLOW_RESUBMIT_CLOSEYEAR);
state.removeAttribute(ALLOW_RESUBMIT_CLOSEHOUR);
state.removeAttribute(ALLOW_RESUBMIT_CLOSEMIN);
state.removeAttribute(ALLOW_RESUBMIT_CLOSEAMPM);
state.removeAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME);
}
}
}
/**
* Populate the state object, if needed - override to do something!
*/
protected void initState(SessionState state, VelocityPortlet portlet, JetspeedRunData data)
{
super.initState(state, portlet, data);
String siteId = ToolManager.getCurrentPlacement().getContext();
// show the list of assignment view first
if (state.getAttribute(STATE_SELECTED_VIEW) == null)
{
state.setAttribute(STATE_SELECTED_VIEW, MODE_LIST_ASSIGNMENTS);
}
if (state.getAttribute(STATE_USER) == null)
{
state.setAttribute(STATE_USER, UserDirectoryService.getCurrentUser());
}
/** The content type image lookup service in the State. */
ContentTypeImageService iService = (ContentTypeImageService) state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE);
if (iService == null)
{
iService = org.sakaiproject.content.cover.ContentTypeImageService.getInstance();
state.setAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE, iService);
} // if
/** The calendar tool */
if (state.getAttribute(CALENDAR_TOOL_EXIST) == null)
{
if (!siteHasTool(siteId, "sakai.schedule"))
{
state.setAttribute(CALENDAR_TOOL_EXIST, Boolean.FALSE);
state.removeAttribute(CALENDAR);
}
else
{
state.setAttribute(CALENDAR_TOOL_EXIST, Boolean.TRUE);
if (state.getAttribute(CALENDAR) == null )
{
state.setAttribute(CALENDAR_TOOL_EXIST, Boolean.TRUE);
CalendarService cService = org.sakaiproject.calendar.cover.CalendarService.getInstance();
state.setAttribute(STATE_CALENDAR_SERVICE, cService);
String calendarId = ServerConfigurationService.getString("calendar", null);
if (calendarId == null)
{
calendarId = cService.calendarReference(siteId, SiteService.MAIN_CONTAINER);
try
{
state.setAttribute(CALENDAR, cService.getCalendar(calendarId));
}
catch (IdUnusedException e)
{
Log.info("chef", "No calendar found for site " + siteId);
state.removeAttribute(CALENDAR);
}
catch (PermissionException e)
{
Log.info("chef", "No permission to get the calender. ");
state.removeAttribute(CALENDAR);
}
catch (Exception ex)
{
Log.info("chef", "Assignment : Action : init state : calendar exception : " + ex);
state.removeAttribute(CALENDAR);
}
}
}
}
}
/** The Announcement tool */
if (state.getAttribute(ANNOUNCEMENT_TOOL_EXIST) == null)
{
if (!siteHasTool(siteId, "sakai.announcements"))
{
state.setAttribute(ANNOUNCEMENT_TOOL_EXIST, Boolean.FALSE);
state.removeAttribute(ANNOUNCEMENT_CHANNEL);
}
else
{
state.setAttribute(ANNOUNCEMENT_TOOL_EXIST, Boolean.TRUE);
if (state.getAttribute(ANNOUNCEMENT_CHANNEL) == null )
{
/** The announcement service in the State. */
AnnouncementService aService = (AnnouncementService) state.getAttribute(STATE_ANNOUNCEMENT_SERVICE);
if (aService == null)
{
aService = org.sakaiproject.announcement.cover.AnnouncementService.getInstance();
state.setAttribute(STATE_ANNOUNCEMENT_SERVICE, aService);
String channelId = ServerConfigurationService.getString("channel", null);
if (channelId == null)
{
channelId = aService.channelReference(siteId, SiteService.MAIN_CONTAINER);
try
{
state.setAttribute(ANNOUNCEMENT_CHANNEL, aService.getAnnouncementChannel(channelId));
}
catch (IdUnusedException e)
{
Log.warn("chef", "No announcement channel found. ");
state.removeAttribute(ANNOUNCEMENT_CHANNEL);
}
catch (PermissionException e)
{
Log.warn("chef", "No permission to annoucement channel. ");
}
catch (Exception ex)
{
Log.warn("chef", "Assignment : Action : init state : calendar exception : " + ex);
}
}
}
}
}
} // if
if (state.getAttribute(STATE_CONTEXT_STRING) == null)
{
state.setAttribute(STATE_CONTEXT_STRING, siteId);
} // if context string is null
if (state.getAttribute(SORTED_BY) == null)
{
setDefaultSort(state);
}
if (state.getAttribute(SORTED_GRADE_SUBMISSION_BY) == null)
{
state.setAttribute(SORTED_GRADE_SUBMISSION_BY, SORTED_GRADE_SUBMISSION_BY_LASTNAME);
}
if (state.getAttribute(SORTED_GRADE_SUBMISSION_ASC) == null)
{
state.setAttribute(SORTED_GRADE_SUBMISSION_ASC, Boolean.TRUE.toString());
}
if (state.getAttribute(SORTED_SUBMISSION_BY) == null)
{
state.setAttribute(SORTED_SUBMISSION_BY, SORTED_SUBMISSION_BY_LASTNAME);
}
if (state.getAttribute(SORTED_SUBMISSION_ASC) == null)
{
state.setAttribute(SORTED_SUBMISSION_ASC, Boolean.TRUE.toString());
}
if (state.getAttribute(NEW_ASSIGNMENT_HIDE_OPTION_FLAG) == null)
{
resetAssignment(state);
}
if (state.getAttribute(STUDENT_LIST_SHOW_TABLE) == null)
{
state.setAttribute(STUDENT_LIST_SHOW_TABLE, new HashSet());
}
if (state.getAttribute(ATTACHMENTS_MODIFIED) == null)
{
state.setAttribute(ATTACHMENTS_MODIFIED, new Boolean(false));
}
// SECTION MOD
if (state.getAttribute(STATE_SECTION_STRING) == null)
{
state.setAttribute(STATE_SECTION_STRING, "001");
}
// // setup the observer to notify the Main panel
// if (state.getAttribute(STATE_OBSERVER) == null)
// {
// // the delivery location for this tool
// String deliveryId = clientWindowId(state, portlet.getID());
//
// // the html element to update on delivery
// String elementId = mainPanelUpdateId(portlet.getID());
//
// // the event resource reference pattern to watch for
// String pattern = AssignmentService.assignmentReference((String) state.getAttribute (STATE_CONTEXT_STRING), "");
//
// state.setAttribute(STATE_OBSERVER, new MultipleEventsObservingCourier(deliveryId, elementId, pattern));
// }
if (state.getAttribute(STATE_MODE) == null)
{
state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS);
}
if (state.getAttribute(STATE_TOP_PAGE_MESSAGE) == null)
{
state.setAttribute(STATE_TOP_PAGE_MESSAGE, new Integer(0));
}
if (state.getAttribute(WITH_GRADES) == null)
{
PortletConfig config = portlet.getPortletConfig();
String withGrades = StringUtil.trimToNull(config.getInitParameter("withGrades"));
if (withGrades == null)
{
withGrades = Boolean.FALSE.toString();
}
state.setAttribute(WITH_GRADES, new Boolean(withGrades));
}
// whether the choice of emails instructor submission notification is available in the installation
if (state.getAttribute(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS) == null)
{
state.setAttribute(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS, Boolean.valueOf(ServerConfigurationService.getBoolean(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS, true)));
}
// whether or how the instructor receive submission notification emails, none(default)|each|digest
if (state.getAttribute(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DEFAULT) == null)
{
state.setAttribute(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DEFAULT, ServerConfigurationService.getString(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DEFAULT, Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_NONE));
}
if (state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_FROM) == null)
{
state.setAttribute(NEW_ASSIGNMENT_YEAR_RANGE_FROM, new Integer(2002));
}
if (state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_TO) == null)
{
state.setAttribute(NEW_ASSIGNMENT_YEAR_RANGE_TO, new Integer(2012));
}
} // initState
/**
* whether the site has the specified tool
* @param siteId
* @return
*/
private boolean siteHasTool(String siteId, String toolId) {
boolean rv = false;
try
{
Site s = SiteService.getSite(siteId);
if (s.getToolForCommonId(toolId) != null)
{
rv = true;
}
}
catch (Exception e)
{
Log.info("chef", this + e.getMessage() + siteId);
}
return rv;
}
/**
* reset the attributes for view submission
*/
private void resetViewSubmission(SessionState state)
{
state.removeAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE);
state.removeAttribute(VIEW_SUBMISSION_TEXT);
state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, "false");
state.removeAttribute(GRADE_GREATER_THAN_MAX_ALERT);
} // resetViewSubmission
/**
* reset the attributes for view submission
*/
private void resetAssignment(SessionState state)
{
// put the input value into the state attributes
state.setAttribute(NEW_ASSIGNMENT_TITLE, "");
// get current time
Time t = TimeService.newTime();
TimeBreakdown tB = t.breakdownLocal();
int month = tB.getMonth();
int day = tB.getDay();
int year = tB.getYear();
// set the open time to be 12:00 PM
state.setAttribute(NEW_ASSIGNMENT_OPENMONTH, new Integer(month));
state.setAttribute(NEW_ASSIGNMENT_OPENDAY, new Integer(day));
state.setAttribute(NEW_ASSIGNMENT_OPENYEAR, new Integer(year));
state.setAttribute(NEW_ASSIGNMENT_OPENHOUR, new Integer(12));
state.setAttribute(NEW_ASSIGNMENT_OPENMIN, new Integer(0));
state.setAttribute(NEW_ASSIGNMENT_OPENAMPM, "PM");
// due date is shifted forward by 7 days
t.setTime(t.getTime() + 7 * 24 * 60 * 60 * 1000);
tB = t.breakdownLocal();
month = tB.getMonth();
day = tB.getDay();
year = tB.getYear();
// set the due time to be 5:00pm
state.setAttribute(NEW_ASSIGNMENT_DUEMONTH, new Integer(month));
state.setAttribute(NEW_ASSIGNMENT_DUEDAY, new Integer(day));
state.setAttribute(NEW_ASSIGNMENT_DUEYEAR, new Integer(year));
state.setAttribute(NEW_ASSIGNMENT_DUEHOUR, new Integer(5));
state.setAttribute(NEW_ASSIGNMENT_DUEMIN, new Integer(0));
state.setAttribute(NEW_ASSIGNMENT_DUEAMPM, "PM");
// enable the close date by default
state.setAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE, new Boolean(true));
// set the close time to be 5:00 pm, same as the due time by default
state.setAttribute(NEW_ASSIGNMENT_CLOSEMONTH, new Integer(month));
state.setAttribute(NEW_ASSIGNMENT_CLOSEDAY, new Integer(day));
state.setAttribute(NEW_ASSIGNMENT_CLOSEYEAR, new Integer(year));
state.setAttribute(NEW_ASSIGNMENT_CLOSEHOUR, new Integer(5));
state.setAttribute(NEW_ASSIGNMENT_CLOSEMIN, new Integer(0));
state.setAttribute(NEW_ASSIGNMENT_CLOSEAMPM, "PM");
state.setAttribute(NEW_ASSIGNMENT_SECTION, "001");
state.setAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE, new Integer(Assignment.TEXT_AND_ATTACHMENT_ASSIGNMENT_SUBMISSION));
state.setAttribute(NEW_ASSIGNMENT_GRADE_TYPE, new Integer(Assignment.UNGRADED_GRADE_TYPE));
state.setAttribute(NEW_ASSIGNMENT_GRADE_POINTS, "");
state.setAttribute(NEW_ASSIGNMENT_DESCRIPTION, "");
state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, Boolean.FALSE.toString());
state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, Boolean.FALSE.toString());
// make the honor pledge not include as the default
state.setAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE, (new Integer(Assignment.HONOR_PLEDGE_NONE)).toString());
state.setAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, AssignmentService.GRADEBOOK_INTEGRATION_NO);
state.setAttribute(NEW_ASSIGNMENT_ATTACHMENT, EntityManager.newReferenceList());
state.setAttribute(NEW_ASSIGNMENT_HIDE_OPTION_FLAG, new Boolean(false));
state.setAttribute(NEW_ASSIGNMENT_FOCUS, NEW_ASSIGNMENT_TITLE);
state.removeAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY);
// reset the global navigaion alert flag
if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) != null)
{
state.removeAttribute(ALERT_GLOBAL_NAVIGATION);
}
state.removeAttribute(NEW_ASSIGNMENT_RANGE);
state.removeAttribute(NEW_ASSIGNMENT_GROUPS);
// remove the edit assignment id if any
state.removeAttribute(EDIT_ASSIGNMENT_ID);
// remove the resubmit number
state.removeAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER);
} // resetNewAssignment
/**
* construct a Hashtable using integer as the key and three character string of the month as the value
*/
private Hashtable monthTable()
{
Hashtable n = new Hashtable();
n.put(new Integer(1), rb.getString("jan"));
n.put(new Integer(2), rb.getString("feb"));
n.put(new Integer(3), rb.getString("mar"));
n.put(new Integer(4), rb.getString("apr"));
n.put(new Integer(5), rb.getString("may"));
n.put(new Integer(6), rb.getString("jun"));
n.put(new Integer(7), rb.getString("jul"));
n.put(new Integer(8), rb.getString("aug"));
n.put(new Integer(9), rb.getString("sep"));
n.put(new Integer(10), rb.getString("oct"));
n.put(new Integer(11), rb.getString("nov"));
n.put(new Integer(12), rb.getString("dec"));
return n;
} // monthTable
/**
* construct a Hashtable using the integer as the key and grade type String as the value
*/
private Hashtable gradeTypeTable()
{
Hashtable n = new Hashtable();
n.put(new Integer(2), rb.getString("letter"));
n.put(new Integer(3), rb.getString("points"));
n.put(new Integer(4), rb.getString("pass"));
n.put(new Integer(5), rb.getString("check"));
n.put(new Integer(1), rb.getString("ungra"));
return n;
} // gradeTypeTable
/**
* construct a Hashtable using the integer as the key and submission type String as the value
*/
private Hashtable submissionTypeTable()
{
Hashtable n = new Hashtable();
n.put(new Integer(1), rb.getString("inlin"));
n.put(new Integer(2), rb.getString("attaonly"));
n.put(new Integer(3), rb.getString("inlinatt"));
n.put(new Integer(4), rb.getString("nonelec"));
return n;
} // submissionTypeTable
/**
* Sort based on the given property
*/
public void doSort(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// we are changing the sort, so start from the first page again
resetPaging(state);
setupSort(data, data.getParameters().getString("criteria"));
}
/**
* setup sorting parameters
*
* @param criteria
* String for sortedBy
*/
private void setupSort(RunData data, String criteria)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// current sorting sequence
String asc = "";
if (!criteria.equals(state.getAttribute(SORTED_BY)))
{
state.setAttribute(SORTED_BY, criteria);
asc = Boolean.TRUE.toString();
state.setAttribute(SORTED_ASC, asc);
}
else
{
// current sorting sequence
asc = (String) state.getAttribute(SORTED_ASC);
// toggle between the ascending and descending sequence
if (asc.equals(Boolean.TRUE.toString()))
{
asc = Boolean.FALSE.toString();
}
else
{
asc = Boolean.TRUE.toString();
}
state.setAttribute(SORTED_ASC, asc);
}
} // doSort
/**
* Do sort by group title
*/
public void doSortbygrouptitle(RunData data)
{
setupSort(data, SORTED_BY_GROUP_TITLE);
} // doSortbygrouptitle
/**
* Do sort by group description
*/
public void doSortbygroupdescription(RunData data)
{
setupSort(data, SORTED_BY_GROUP_DESCRIPTION);
} // doSortbygroupdescription
/**
* Sort submission based on the given property
*/
public void doSort_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// we are changing the sort, so start from the first page again
resetPaging(state);
// get the ParameterParser from RunData
ParameterParser params = data.getParameters();
String criteria = params.getString("criteria");
// current sorting sequence
String asc = "";
if (!criteria.equals(state.getAttribute(SORTED_SUBMISSION_BY)))
{
state.setAttribute(SORTED_SUBMISSION_BY, criteria);
asc = Boolean.TRUE.toString();
state.setAttribute(SORTED_SUBMISSION_ASC, asc);
}
else
{
// current sorting sequence
state.setAttribute(SORTED_SUBMISSION_BY, criteria);
asc = (String) state.getAttribute(SORTED_SUBMISSION_ASC);
// toggle between the ascending and descending sequence
if (asc.equals(Boolean.TRUE.toString()))
{
asc = Boolean.FALSE.toString();
}
else
{
asc = Boolean.TRUE.toString();
}
state.setAttribute(SORTED_SUBMISSION_ASC, asc);
}
} // doSort_submission
/**
* Sort submission based on the given property in instructor grade view
*/
public void doSort_grade_submission(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// we are changing the sort, so start from the first page again
resetPaging(state);
// get the ParameterParser from RunData
ParameterParser params = data.getParameters();
String criteria = params.getString("criteria");
// current sorting sequence
String asc = "";
if (!criteria.equals(state.getAttribute(SORTED_GRADE_SUBMISSION_BY)))
{
state.setAttribute(SORTED_GRADE_SUBMISSION_BY, criteria);
//for content review default is desc
if (criteria.equals(SORTED_GRADE_SUBMISSION_CONTENTREVIEW))
asc = Boolean.FALSE.toString();
else
asc = Boolean.TRUE.toString();
state.setAttribute(SORTED_GRADE_SUBMISSION_ASC, asc);
}
else
{
// current sorting sequence
state.setAttribute(SORTED_GRADE_SUBMISSION_BY, criteria);
asc = (String) state.getAttribute(SORTED_GRADE_SUBMISSION_ASC);
// toggle between the ascending and descending sequence
if (asc.equals(Boolean.TRUE.toString()))
{
asc = Boolean.FALSE.toString();
}
else
{
asc = Boolean.TRUE.toString();
}
state.setAttribute(SORTED_GRADE_SUBMISSION_ASC, asc);
}
} // doSort_grade_submission
public void doSort_tags(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String criteria = params.getString("criteria");
String providerId = params.getString(PROVIDER_ID);
String savedText = params.getString("savedText");
state.setAttribute(VIEW_SUBMISSION_TEXT, savedText);
String mode = (String) state.getAttribute(STATE_MODE);
List<DecoratedTaggingProvider> providers = (List) state
.getAttribute(mode + PROVIDER_LIST);
for (DecoratedTaggingProvider dtp : providers) {
if (dtp.getProvider().getId().equals(providerId)) {
Sort sort = dtp.getSort();
if (sort.getSort().equals(criteria)) {
sort.setAscending(sort.isAscending() ? false : true);
} else {
sort.setSort(criteria);
sort.setAscending(true);
}
break;
}
}
}
public void doPage_tags(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String page = params.getString("page");
String pageSize = params.getString("pageSize");
String providerId = params.getString(PROVIDER_ID);
String savedText = params.getString("savedText");
state.setAttribute(VIEW_SUBMISSION_TEXT, savedText);
String mode = (String) state.getAttribute(STATE_MODE);
List<DecoratedTaggingProvider> providers = (List) state
.getAttribute(mode + PROVIDER_LIST);
for (DecoratedTaggingProvider dtp : providers) {
if (dtp.getProvider().getId().equals(providerId)) {
Pager pager = dtp.getPager();
pager.setPageSize(Integer.valueOf(pageSize));
if (Pager.FIRST.equals(page)) {
pager.setFirstItem(0);
} else if (Pager.PREVIOUS.equals(page)) {
pager.setFirstItem(pager.getFirstItem()
- pager.getPageSize());
} else if (Pager.NEXT.equals(page)) {
pager.setFirstItem(pager.getFirstItem()
+ pager.getPageSize());
} else if (Pager.LAST.equals(page)) {
pager.setFirstItem((pager.getTotalItems() / pager
.getPageSize())
* pager.getPageSize());
}
break;
}
}
}
/**
* the UserSubmission clas
*/
public class UserSubmission
{
/**
* the User object
*/
User m_user = null;
/**
* the AssignmentSubmission object
*/
AssignmentSubmission m_submission = null;
public UserSubmission(User u, AssignmentSubmission s)
{
m_user = u;
m_submission = s;
}
/**
* Returns the AssignmentSubmission object
*/
public AssignmentSubmission getSubmission()
{
return m_submission;
}
/**
* Returns the User object
*/
public User getUser()
{
return m_user;
}
}
/**
* the AssignmentComparator clas
*/
private class AssignmentComparator implements Comparator
{
Collator collator = Collator.getInstance();
/**
* the SessionState object
*/
SessionState m_state = null;
/**
* the criteria
*/
String m_criteria = null;
/**
* the criteria
*/
String m_asc = null;
/**
* the user
*/
User m_user = null;
/**
* constructor
*
* @param state
* The state object
* @param criteria
* The sort criteria string
* @param asc
* The sort order string. TRUE_STRING if ascending; "false" otherwise.
*/
public AssignmentComparator(SessionState state, String criteria, String asc)
{
m_state = state;
m_criteria = criteria;
m_asc = asc;
} // constructor
/**
* constructor
*
* @param state
* The state object
* @param criteria
* The sort criteria string
* @param asc
* The sort order string. TRUE_STRING if ascending; "false" otherwise.
* @param user
* The user object
*/
public AssignmentComparator(SessionState state, String criteria, String asc, User user)
{
m_state = state;
m_criteria = criteria;
m_asc = asc;
m_user = user;
} // constructor
/**
* caculate the range string for an assignment
*/
private String getAssignmentRange(Assignment a)
{
String rv = "";
if (a.getAccess().equals(Assignment.AssignmentAccess.SITE))
{
// site assignment
rv = rb.getString("range.allgroups");
}
else
{
try
{
// get current site
Site site = SiteService.getSite(ToolManager.getCurrentPlacement().getContext());
for (Iterator k = a.getGroups().iterator(); k.hasNext();)
{
// announcement by group
rv = rv.concat(site.getGroup((String) k.next()).getTitle());
}
}
catch (Exception ignore)
{
}
}
return rv;
} // getAssignmentRange
/**
* implementing the compare function
*
* @param o1
* The first object
* @param o2
* The second object
* @return The compare result. 1 is o1 < o2; -1 otherwise
*/
public int compare(Object o1, Object o2)
{
int result = -1;
if (m_criteria == null)
{
m_criteria = SORTED_BY_DEFAULT;
}
/** *********** for sorting assignments ****************** */
if (m_criteria.equals(SORTED_BY_DEFAULT))
{
int s1 = ((Assignment) o1).getPosition_order();
int s2 = ((Assignment) o2).getPosition_order();
if ( s1 == s2 ) // we either have 2 assignments with no existing postion_order or a numbering error, so sort by duedate
{
// sorted by the assignment due date
Time t1 = ((Assignment) o1).getDueTime();
Time t2 = ((Assignment) o2).getDueTime();
if (t1 == null)
{
result = -1;
}
else if (t2 == null)
{
result = 1;
}
else if (t1.equals(t2))
{
t1 = ((Assignment) o1).getTimeCreated();
t2 = ((Assignment) o2).getTimeCreated();
}
if (t1!=null && t2!=null && t1.before(t2))
{
result = -1;
}
else
{
result = 1;
}
}
else if ( s1 == 0 && s2 > 0 ) // order has not been set on this object, so put it at the bottom of the list
{
result = 1;
}
else if ( s2 == 0 && s1 > 0 ) // making sure assignments with no position_order stay at the bottom
{
result = -1;
}
else // 2 legitimate postion orders
{
result = (s1 < s2) ? -1 : 1;
}
}
if (m_criteria.equals(SORTED_BY_TITLE))
{
// sorted by the assignment title
String s1 = ((Assignment) o1).getTitle();
String s2 = ((Assignment) o2).getTitle();
result = compareString(s1, s2);
}
else if (m_criteria.equals(SORTED_BY_SECTION))
{
// sorted by the assignment section
String s1 = ((Assignment) o1).getSection();
String s2 = ((Assignment) o2).getSection();
result = compareString(s1, s2);
}
else if (m_criteria.equals(SORTED_BY_DUEDATE))
{
// sorted by the assignment due date
Time t1 = ((Assignment) o1).getDueTime();
Time t2 = ((Assignment) o2).getDueTime();
if (t1 == null)
{
result = -1;
}
else if (t2 == null)
{
result = 1;
}
else if (t1.before(t2))
{
result = -1;
}
else
{
result = 1;
}
}
else if (m_criteria.equals(SORTED_BY_OPENDATE))
{
// sorted by the assignment open
Time t1 = ((Assignment) o1).getOpenTime();
Time t2 = ((Assignment) o2).getOpenTime();
if (t1 == null)
{
result = -1;
}
else if (t2 == null)
{
result = 1;
}
if (t1.before(t2))
{
result = -1;
}
else
{
result = 1;
}
}
else if (m_criteria.equals(SORTED_BY_ASSIGNMENT_STATUS))
{
String s1 = getAssignmentStatus((Assignment) o1);
String s2 = getAssignmentStatus((Assignment) o2);
result = compareString(s1, s2);
}
else if (m_criteria.equals(SORTED_BY_NUM_SUBMISSIONS))
{
// sort by numbers of submissions
// initialize
int subNum1 = 0;
int subNum2 = 0;
Iterator submissions1 = AssignmentService.getSubmissions((Assignment) o1).iterator();
while (submissions1.hasNext())
{
AssignmentSubmission submission1 = (AssignmentSubmission) submissions1.next();
if (submission1.getSubmitted()) subNum1++;
}
Iterator submissions2 = AssignmentService.getSubmissions((Assignment) o2).iterator();
while (submissions2.hasNext())
{
AssignmentSubmission submission2 = (AssignmentSubmission) submissions2.next();
if (submission2.getSubmitted()) subNum2++;
}
result = (subNum1 > subNum2) ? 1 : -1;
}
else if (m_criteria.equals(SORTED_BY_NUM_UNGRADED))
{
// sort by numbers of ungraded submissions
// initialize
int ungraded1 = 0;
int ungraded2 = 0;
Iterator submissions1 = AssignmentService.getSubmissions((Assignment) o1).iterator();
while (submissions1.hasNext())
{
AssignmentSubmission submission1 = (AssignmentSubmission) submissions1.next();
if (submission1.getSubmitted() && !submission1.getGraded()) ungraded1++;
}
Iterator submissions2 = AssignmentService.getSubmissions((Assignment) o2).iterator();
while (submissions2.hasNext())
{
AssignmentSubmission submission2 = (AssignmentSubmission) submissions2.next();
if (submission2.getSubmitted() && !submission2.getGraded()) ungraded2++;
}
result = (ungraded1 > ungraded2) ? 1 : -1;
}
else if (m_criteria.equals(SORTED_BY_SUBMISSION_STATUS))
{
try
{
AssignmentSubmission submission1 = AssignmentService.getSubmission(((Assignment) o1).getId(), m_user);
String status1 = getSubmissionStatus(submission1, (Assignment) o1);
AssignmentSubmission submission2 = AssignmentService.getSubmission(((Assignment) o2).getId(), m_user);
String status2 = getSubmissionStatus(submission2, (Assignment) o2);
result = compareString(status1, status2);
}
catch (IdUnusedException e)
{
return 1;
}
catch (PermissionException e)
{
return 1;
}
}
else if (m_criteria.equals(SORTED_BY_GRADE))
{
try
{
AssignmentSubmission submission1 = AssignmentService.getSubmission(((Assignment) o1).getId(), m_user);
String grade1 = " ";
if (submission1 != null && submission1.getGraded() && submission1.getGradeReleased())
{
grade1 = submission1.getGrade();
}
AssignmentSubmission submission2 = AssignmentService.getSubmission(((Assignment) o2).getId(), m_user);
String grade2 = " ";
if (submission2 != null && submission2.getGraded() && submission2.getGradeReleased())
{
grade2 = submission2.getGrade();
}
result = compareString(grade1, grade2);
}
catch (IdUnusedException e)
{
return 1;
}
catch (PermissionException e)
{
return 1;
}
}
else if (m_criteria.equals(SORTED_BY_MAX_GRADE))
{
String maxGrade1 = maxGrade(((Assignment) o1).getContent().getTypeOfGrade(), (Assignment) o1);
String maxGrade2 = maxGrade(((Assignment) o2).getContent().getTypeOfGrade(), (Assignment) o2);
try
{
// do integer comparation inside point grade type
int max1 = Integer.parseInt(maxGrade1);
int max2 = Integer.parseInt(maxGrade2);
result = (max1 < max2) ? -1 : 1;
}
catch (NumberFormatException e)
{
// otherwise do an alpha-compare
result = compareString(maxGrade1, maxGrade2);
}
}
// group related sorting
else if (m_criteria.equals(SORTED_BY_FOR))
{
// sorted by the public view attribute
String factor1 = getAssignmentRange((Assignment) o1);
String factor2 = getAssignmentRange((Assignment) o2);
result = compareString(factor1, factor2);
}
else if (m_criteria.equals(SORTED_BY_GROUP_TITLE))
{
// sorted by the group title
String factor1 = ((Group) o1).getTitle();
String factor2 = ((Group) o2).getTitle();
result = compareString(factor1, factor2);
}
else if (m_criteria.equals(SORTED_BY_GROUP_DESCRIPTION))
{
// sorted by the group description
String factor1 = ((Group) o1).getDescription();
String factor2 = ((Group) o2).getDescription();
if (factor1 == null)
{
factor1 = "";
}
if (factor2 == null)
{
factor2 = "";
}
result = compareString(factor1, factor2);
}
/** ***************** for sorting submissions in instructor grade assignment view ************* */
else if(m_criteria.equals(SORTED_GRADE_SUBMISSION_CONTENTREVIEW))
{
UserSubmission u1 = (UserSubmission) o1;
UserSubmission u2 = (UserSubmission) o2;
if (u1 == null || u2 == null || u1.getUser() == null || u2.getUser() == null )
{
result = 1;
}
else
{
AssignmentSubmission s1 = u1.getSubmission();
AssignmentSubmission s2 = u2.getSubmission();
if (s1 == null)
{
result = -1;
}
else if (s2 == null )
{
result = 1;
}
else
{
int score1 = u1.getSubmission().getReviewScore();
int score2 = u2.getSubmission().getReviewScore();
result = (new Integer(score1)).intValue() > (new Integer(score2)).intValue() ? 1 : -1;
}
}
}
else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_LASTNAME))
{
// sorted by the submitters sort name
UserSubmission u1 = (UserSubmission) o1;
UserSubmission u2 = (UserSubmission) o2;
if (u1 == null || u2 == null || u1.getUser() == null || u2.getUser() == null )
{
result = 1;
}
else
{
String lName1 = u1.getUser().getSortName();
String lName2 = u2.getUser().getSortName();
result = compareString(lName1, lName2);
}
}
else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_SUBMIT_TIME))
{
// sorted by submission time
UserSubmission u1 = (UserSubmission) o1;
UserSubmission u2 = (UserSubmission) o2;
if (u1 == null || u2 == null)
{
result = -1;
}
else
{
AssignmentSubmission s1 = u1.getSubmission();
AssignmentSubmission s2 = u2.getSubmission();
if (s1 == null || s1.getTimeSubmitted() == null)
{
result = -1;
}
else if (s2 == null || s2.getTimeSubmitted() == null)
{
result = 1;
}
else if (s1.getTimeSubmitted().before(s2.getTimeSubmitted()))
{
result = -1;
}
else
{
result = 1;
}
}
}
else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_STATUS))
{
// sort by submission status
UserSubmission u1 = (UserSubmission) o1;
UserSubmission u2 = (UserSubmission) o2;
String status1 = "";
String status2 = "";
if (u1 == null)
{
status1 = rb.getString("listsub.nosub");
}
else
{
AssignmentSubmission s1 = u1.getSubmission();
if (s1 == null)
{
status1 = rb.getString("listsub.nosub");
}
else
{
status1 = getSubmissionStatus(m_state, (AssignmentSubmission) s1);
}
}
if (u2 == null)
{
status2 = rb.getString("listsub.nosub");
}
else
{
AssignmentSubmission s2 = u2.getSubmission();
if (s2 == null)
{
status2 = rb.getString("listsub.nosub");
}
else
{
status2 = getSubmissionStatus(m_state, (AssignmentSubmission) s2);
}
}
result = compareString(status1, status2);
}
else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_GRADE))
{
// sort by submission status
UserSubmission u1 = (UserSubmission) o1;
UserSubmission u2 = (UserSubmission) o2;
if (u1 == null || u2 == null)
{
result = -1;
}
else
{
AssignmentSubmission s1 = u1.getSubmission();
AssignmentSubmission s2 = u2.getSubmission();
//sort by submission grade
if (s1 == null)
{
result = -1;
}
else if (s2 == null)
{
result = 1;
}
else
{
String grade1 = s1.getGrade();
String grade2 = s2.getGrade();
if (grade1 == null)
{
grade1 = "";
}
if (grade2 == null)
{
grade2 = "";
}
// if scale is points
if ((s1.getAssignment().getContent().getTypeOfGrade() == 3)
&& ((s2.getAssignment().getContent().getTypeOfGrade() == 3)))
{
if (grade1.equals(""))
{
result = -1;
}
else if (grade2.equals(""))
{
result = 1;
}
else
{
result = (new Double(grade1)).doubleValue() > (new Double(grade2)).doubleValue() ? 1 : -1;
}
}
else
{
result = compareString(grade1, grade2);
}
}
}
}
else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_RELEASED))
{
// sort by submission status
UserSubmission u1 = (UserSubmission) o1;
UserSubmission u2 = (UserSubmission) o2;
if (u1 == null || u2 == null)
{
result = -1;
}
else
{
AssignmentSubmission s1 = u1.getSubmission();
AssignmentSubmission s2 = u2.getSubmission();
if (s1 == null)
{
result = -1;
}
else if (s2 == null)
{
result = 1;
}
else
{
// sort by submission released
String released1 = (new Boolean(s1.getGradeReleased())).toString();
String released2 = (new Boolean(s2.getGradeReleased())).toString();
result = compareString(released1, released2);
}
}
}
/****** for other sort on submissions **/
else if (m_criteria.equals(SORTED_SUBMISSION_BY_LASTNAME))
{
// sorted by the submitters sort name
User[] u1 = ((AssignmentSubmission) o1).getSubmitters();
User[] u2 = ((AssignmentSubmission) o2).getSubmitters();
if (u1 == null || u2 == null)
{
return 1;
}
else
{
String submitters1 = "";
String submitters2 = "";
for (int j = 0; j < u1.length; j++)
{
if (u1[j] != null && u1[j].getLastName() != null)
{
if (j > 0)
{
submitters1 = submitters1.concat("; ");
}
submitters1 = submitters1.concat("" + u1[j].getLastName());
}
}
for (int j = 0; j < u2.length; j++)
{
if (u2[j] != null && u2[j].getLastName() != null)
{
if (j > 0)
{
submitters2 = submitters2.concat("; ");
}
submitters2 = submitters2.concat(u2[j].getLastName());
}
}
result = compareString(submitters1, submitters2);
}
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_SUBMIT_TIME))
{
// sorted by submission time
Time t1 = ((AssignmentSubmission) o1).getTimeSubmitted();
Time t2 = ((AssignmentSubmission) o2).getTimeSubmitted();
if (t1 == null)
{
result = -1;
}
else if (t2 == null)
{
result = 1;
}
else if (t1.before(t2))
{
result = -1;
}
else
{
result = 1;
}
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_STATUS))
{
// sort by submission status
String status1 = getSubmissionStatus(m_state, (AssignmentSubmission) o1);
String status2 = getSubmissionStatus(m_state, (AssignmentSubmission) o2);
result = compareString(status1, status2);
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_GRADE))
{
// sort by submission grade
String grade1 = ((AssignmentSubmission) o1).getGrade();
String grade2 = ((AssignmentSubmission) o2).getGrade();
if (grade1 == null)
{
grade1 = "";
}
if (grade2 == null)
{
grade2 = "";
}
// if scale is points
if ((((AssignmentSubmission) o1).getAssignment().getContent().getTypeOfGrade() == 3)
&& ((((AssignmentSubmission) o2).getAssignment().getContent().getTypeOfGrade() == 3)))
{
if (grade1.equals(""))
{
result = -1;
}
else if (grade2.equals(""))
{
result = 1;
}
else
{
result = (new Double(grade1)).doubleValue() > (new Double(grade2)).doubleValue() ? 1 : -1;
}
}
else
{
result = compareString(grade1, grade2);
}
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_GRADE))
{
// sort by submission grade
String grade1 = ((AssignmentSubmission) o1).getGrade();
String grade2 = ((AssignmentSubmission) o2).getGrade();
if (grade1 == null)
{
grade1 = "";
}
if (grade2 == null)
{
grade2 = "";
}
// if scale is points
if ((((AssignmentSubmission) o1).getAssignment().getContent().getTypeOfGrade() == 3)
&& ((((AssignmentSubmission) o2).getAssignment().getContent().getTypeOfGrade() == 3)))
{
if (grade1.equals(""))
{
result = -1;
}
else if (grade2.equals(""))
{
result = 1;
}
else
{
result = (new Double(grade1)).doubleValue() > (new Double(grade2)).doubleValue() ? 1 : -1;
}
}
else
{
result = compareString(grade1, grade2);
}
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_MAX_GRADE))
{
Assignment a1 = ((AssignmentSubmission) o1).getAssignment();
Assignment a2 = ((AssignmentSubmission) o2).getAssignment();
String maxGrade1 = maxGrade(a1.getContent().getTypeOfGrade(), a1);
String maxGrade2 = maxGrade(a2.getContent().getTypeOfGrade(), a2);
try
{
// do integer comparation inside point grade type
int max1 = Integer.parseInt(maxGrade1);
int max2 = Integer.parseInt(maxGrade2);
result = (max1 < max2) ? -1 : 1;
}
catch (NumberFormatException e)
{
// otherwise do an alpha-compare
result = maxGrade1.compareTo(maxGrade2);
}
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_RELEASED))
{
// sort by submission released
String released1 = (new Boolean(((AssignmentSubmission) o1).getGradeReleased())).toString();
String released2 = (new Boolean(((AssignmentSubmission) o2).getGradeReleased())).toString();
result = compareString(released1, released2);
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_ASSIGNMENT))
{
// sort by submission's assignment
String title1 = ((AssignmentSubmission) o1).getAssignment().getContent().getTitle();
String title2 = ((AssignmentSubmission) o2).getAssignment().getContent().getTitle();
result = compareString(title1, title2);
}
// sort ascending or descending
- if (m_asc.equals(Boolean.FALSE.toString()))
+ if (!Boolean.valueOf(m_asc))
{
result = -result;
}
return result;
} // compare
private int compareString(String s1, String s2)
{
int result;
if (s1 == null && s2 == null) {
result = 0;
} else if (s2 == null) {
result = 1;
} else if (s1 == null) {
result = -1;
} else {
result = collator.compare(s1.toLowerCase(), s2.toLowerCase());
}
return result;
}
/**
* get the submissin status
*/
private String getSubmissionStatus(SessionState state, AssignmentSubmission s)
{
String status = "";
if (s.getReturned())
{
if (s.getTimeReturned() != null && s.getTimeSubmitted() != null && s.getTimeReturned().before(s.getTimeSubmitted()))
{
status = rb.getString("listsub.resubmi");
}
else
{
status = rb.getString("gen.returned");
}
}
else if (s.getGraded())
{
if (state.getAttribute(WITH_GRADES) != null && ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue())
{
status = rb.getString("grad3");
}
else
{
status = rb.getString("gen.commented");
}
}
else
{
status = rb.getString("gen.ung1");
}
return status;
} // getSubmissionStatus
/**
* get the status string of assignment
*/
private String getAssignmentStatus(Assignment a)
{
String status = "";
Time currentTime = TimeService.newTime();
if (a.getDraft())
status = rb.getString("draft2");
else if (a.getOpenTime().after(currentTime))
status = rb.getString("notope");
else if (a.getDueTime().after(currentTime))
status = rb.getString("ope");
else if ((a.getCloseTime() != null) && (a.getCloseTime().before(currentTime)))
status = rb.getString("clos");
else
status = rb.getString("due2");
return status;
} // getAssignmentStatus
/**
* get submission status
*/
private String getSubmissionStatus(AssignmentSubmission submission, Assignment assignment)
{
String status = "";
if (submission != null)
if (submission.getSubmitted())
if (submission.getGraded() && submission.getGradeReleased())
status = rb.getString("grad3");
else if (submission.getReturned())
status = rb.getString("return") + " " + submission.getTimeReturned().toStringLocalFull();
else
{
status = rb.getString("submitt") + submission.getTimeSubmitted().toStringLocalFull();
if (submission.getTimeSubmitted().after(assignment.getDueTime())) status = status + rb.getString("late");
}
else
status = rb.getString("inpro");
else
status = rb.getString("notsta");
return status;
} // getSubmissionStatus
/**
* get assignment maximun grade available based on the assignment grade type
*
* @param gradeType
* The int value of grade type
* @param a
* The assignment object
* @return The max grade String
*/
private String maxGrade(int gradeType, Assignment a)
{
String maxGrade = "";
if (gradeType == -1)
{
// Grade type not set
maxGrade = rb.getString("granotset");
}
else if (gradeType == 1)
{
// Ungraded grade type
maxGrade = rb.getString("nogra");
}
else if (gradeType == 2)
{
// Letter grade type
maxGrade = "A";
}
else if (gradeType == 3)
{
// Score based grade type
maxGrade = Integer.toString(a.getContent().getMaxGradePoint());
}
else if (gradeType == 4)
{
// Pass/fail grade type
maxGrade = rb.getString("pass2");
}
else if (gradeType == 5)
{
// Grade type that only requires a check
maxGrade = rb.getString("check2");
}
return maxGrade;
} // maxGrade
} // DiscussionComparator
/**
* Fire up the permissions editor
*/
public void doPermissions(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
if (!alertGlobalNavigation(state, data))
{
// we are changing the view, so start with first page again.
resetPaging(state);
// clear search form
doSearch_clear(data, null);
if (SiteService.allowUpdateSite((String) state.getAttribute(STATE_CONTEXT_STRING)))
{
// get into helper mode with this helper tool
startHelper(data.getRequest(), "sakai.permissions.helper");
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
String siteRef = SiteService.siteReference(contextString);
// setup for editing the permissions of the site for this tool, using the roles of this site, too
state.setAttribute(PermissionsHelper.TARGET_REF, siteRef);
// ... with this description
state.setAttribute(PermissionsHelper.DESCRIPTION, rb.getString("setperfor") + " "
+ SiteService.getSiteDisplay(contextString));
// ... showing only locks that are prpefixed with this
state.setAttribute(PermissionsHelper.PREFIX, "asn.");
// disable auto-updates while leaving the list view
justDelivered(state);
}
// reset the global navigaion alert flag
if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) != null)
{
state.removeAttribute(ALERT_GLOBAL_NAVIGATION);
}
// switching back to assignment list view
state.setAttribute(STATE_SELECTED_VIEW, MODE_LIST_ASSIGNMENTS);
doList_assignments(data);
}
} // doPermissions
/**
* transforms the Iterator to Vector
*/
private Vector iterator_to_vector(Iterator l)
{
Vector v = new Vector();
while (l.hasNext())
{
v.add(l.next());
}
return v;
} // iterator_to_vector
/**
* Implement this to return alist of all the resources that there are to page. Sort them as appropriate.
*/
protected List readResourcesPage(SessionState state, int first, int last)
{
List returnResources = (List) state.getAttribute(STATE_PAGEING_TOTAL_ITEMS);
PagingPosition page = new PagingPosition(first, last);
page.validate(returnResources.size());
returnResources = returnResources.subList(page.getFirst() - 1, page.getLast());
return returnResources;
} // readAllResources
/*
* (non-Javadoc)
*
* @see org.sakaiproject.cheftool.PagedResourceActionII#sizeResources(org.sakaiproject.service.framework.session.SessionState)
*/
protected int sizeResources(SessionState state)
{
String mode = (String) state.getAttribute(STATE_MODE);
String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING);
// all the resources for paging
List returnResources = new Vector();
boolean allowAddAssignment = AssignmentService.allowAddAssignment(contextString);
if (mode.equalsIgnoreCase(MODE_LIST_ASSIGNMENTS))
{
String view = "";
if (state.getAttribute(STATE_SELECTED_VIEW) != null)
{
view = (String) state.getAttribute(STATE_SELECTED_VIEW);
}
if (allowAddAssignment && view.equals(MODE_LIST_ASSIGNMENTS))
{
// read all Assignments
returnResources = AssignmentService.getListAssignmentsForContext((String) state
.getAttribute(STATE_CONTEXT_STRING));
}
else if (allowAddAssignment && view.equals(MODE_STUDENT_VIEW)
|| !allowAddAssignment)
{
// in the student list view of assignments
Iterator assignments = AssignmentService
.getAssignmentsForContext(contextString);
Time currentTime = TimeService.newTime();
while (assignments.hasNext())
{
Assignment a = (Assignment) assignments.next();
try
{
String deleted = a.getProperties().getProperty(ResourceProperties.PROP_ASSIGNMENT_DELETED);
if (deleted == null || deleted.equals(""))
{
// show not deleted assignments
Time openTime = a.getOpenTime();
if (openTime != null && currentTime.after(openTime) && !a.getDraft())
{
returnResources.add(a);
}
}
else if (deleted.equalsIgnoreCase(Boolean.TRUE.toString()) && (a.getContent().getTypeOfSubmission() != Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION) && AssignmentService.getSubmission(a.getReference(), (User) state
.getAttribute(STATE_USER)) != null)
{
// and those deleted but not non-electronic assignments but the user has made submissions to them
returnResources.add(a);
}
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin3"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot14"));
}
}
}
state.setAttribute(HAS_MULTIPLE_ASSIGNMENTS, Boolean.valueOf(returnResources.size() > 1));
}
else if (mode.equalsIgnoreCase(MODE_INSTRUCTOR_REORDER_ASSIGNMENT))
{
returnResources = AssignmentService.getListAssignmentsForContext((String) state
.getAttribute(STATE_CONTEXT_STRING));
}
else if (mode.equalsIgnoreCase(MODE_INSTRUCTOR_REPORT_SUBMISSIONS))
{
Vector submissions = new Vector();
Vector assignments = iterator_to_vector(AssignmentService.getAssignmentsForContext((String) state
.getAttribute(STATE_CONTEXT_STRING)));
if (assignments.size() > 0)
{
// users = AssignmentService.allowAddSubmissionUsers (((Assignment)assignments.get(0)).getReference ());
}
for (int j = 0; j < assignments.size(); j++)
{
Assignment a = (Assignment) assignments.get(j);
String deleted = a.getProperties().getProperty(ResourceProperties.PROP_ASSIGNMENT_DELETED);
if ((deleted == null || deleted.equals("")) && (!a.getDraft()) && AssignmentService.allowGradeSubmission(a.getReference()))
{
try
{
List assignmentSubmissions = AssignmentService.getSubmissions(a);
for (int k = 0; k < assignmentSubmissions.size(); k++)
{
AssignmentSubmission s = (AssignmentSubmission) assignmentSubmissions.get(k);
if (s != null && (s.getSubmitted() || (s.getReturned() && (s.getTimeLastModified().before(s
.getTimeReturned())))))
{
// has been subitted or has been returned and not work on it yet
submissions.add(s);
} // if-else
}
}
catch (Exception e)
{
}
}
}
returnResources = submissions;
}
else if (mode.equalsIgnoreCase(MODE_INSTRUCTOR_GRADE_ASSIGNMENT))
{
// range
String authzGroupId = "";
try
{
Assignment a = AssignmentService.getAssignment((String) state.getAttribute(EXPORT_ASSIGNMENT_REF));
// all submissions
List submissions = AssignmentService.getSubmissions(a);
// now are we view all sections/groups or just specific one?
String allOrOneGroup = (String) state.getAttribute(VIEW_SUBMISSION_LIST_OPTION);
if (allOrOneGroup.equals(rb.getString("gen.viewallgroupssections")))
{
// see all submissions
authzGroupId = SiteService.siteReference(contextString);
}
else
{
// filter out only those submissions from the selected-group members
authzGroupId = allOrOneGroup;
}
// all users that can submit
List allowAddSubmissionUsers = AssignmentService.allowAddSubmissionUsers((String) state.getAttribute(EXPORT_ASSIGNMENT_REF));
try
{
AuthzGroup group = AuthzGroupService.getAuthzGroup(authzGroupId);
Set grants = group.getUsers();
for (Iterator iUserIds = grants.iterator(); iUserIds.hasNext();)
{
String userId = (String) iUserIds.next();
try
{
User u = UserDirectoryService.getUser(userId);
// only include those users that can submit to this assignment
if (u != null && allowAddSubmissionUsers.contains(u))
{
boolean found = false;
for (int i = 0; !found && i<submissions.size();i++)
{
AssignmentSubmission s = (AssignmentSubmission) submissions.get(i);
if (s.getSubmitterIds().contains(userId))
{
returnResources.add(new UserSubmission(u, s));
found = true;
}
}
// add those users who haven't made any submissions
if (!found)
{
// construct fake submissions for grading purpose
AssignmentSubmissionEdit s = AssignmentService.addSubmission(contextString, a.getId(), userId);
s.removeSubmitter(UserDirectoryService.getCurrentUser());
s.addSubmitter(u);
s.setSubmitted(true);
s.setAssignment(a);
AssignmentService.commitEdit(s);
// update the UserSubmission list by adding newly created Submission object
AssignmentSubmission sub = AssignmentService.getSubmission(s.getReference());
returnResources.add(new UserSubmission(u, sub));
}
}
}
catch (Exception e)
{
Log.warn("chef", this + e.toString() + " here userId = " + userId);
}
}
}
catch (Exception e)
{
Log.warn("chef", e.getMessage() + " authGroupId=" + authzGroupId);
}
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfin3"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youarenot14"));
}
}
// sort them all
String ascending = "true";
String sort = "";
ascending = (String) state.getAttribute(SORTED_ASC);
sort = (String) state.getAttribute(SORTED_BY);
if (mode.equalsIgnoreCase(MODE_INSTRUCTOR_GRADE_ASSIGNMENT) && (sort == null || !sort.startsWith("sorted_grade_submission_by")))
{
ascending = (String) state.getAttribute(SORTED_GRADE_SUBMISSION_ASC);
sort = (String) state.getAttribute(SORTED_GRADE_SUBMISSION_BY);
}
else if (mode.equalsIgnoreCase(MODE_INSTRUCTOR_REPORT_SUBMISSIONS) && (sort == null || sort.startsWith("sorted_submission_by")))
{
ascending = (String) state.getAttribute(SORTED_SUBMISSION_ASC);
sort = (String) state.getAttribute(SORTED_SUBMISSION_BY);
}
else
{
ascending = (String) state.getAttribute(SORTED_ASC);
sort = (String) state.getAttribute(SORTED_BY);
}
if ((returnResources.size() > 1) && !mode.equalsIgnoreCase(MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT))
{
Collections.sort(returnResources, new AssignmentComparator(state, sort, ascending));
}
// record the total item number
state.setAttribute(STATE_PAGEING_TOTAL_ITEMS, returnResources);
return returnResources.size();
}
public void doView(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
if (!alertGlobalNavigation(state, data))
{
// we are changing the view, so start with first page again.
resetPaging(state);
// clear search form
doSearch_clear(data, null);
String viewMode = data.getParameters().getString("view");
state.setAttribute(STATE_SELECTED_VIEW, viewMode);
if (viewMode.equals(MODE_LIST_ASSIGNMENTS))
{
doList_assignments(data);
}
else if (viewMode.equals(MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT))
{
doView_students_assignment(data);
}
else if (viewMode.equals(MODE_INSTRUCTOR_REPORT_SUBMISSIONS))
{
doReport_submissions(data);
}
else if (viewMode.equals(MODE_STUDENT_VIEW))
{
doView_student(data);
}
// reset the global navigaion alert flag
if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) != null)
{
state.removeAttribute(ALERT_GLOBAL_NAVIGATION);
}
}
} // doView
/**
* put those variables related to 2ndToolbar into context
*/
private void add2ndToolbarFields(RunData data, Context context)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
context.put("totalPageNumber", new Integer(totalPageNumber(state)));
context.put("form_search", FORM_SEARCH);
context.put("formPageNumber", FORM_PAGE_NUMBER);
context.put("prev_page_exists", state.getAttribute(STATE_PREV_PAGE_EXISTS));
context.put("next_page_exists", state.getAttribute(STATE_NEXT_PAGE_EXISTS));
context.put("current_page", state.getAttribute(STATE_CURRENT_PAGE));
context.put("selectedView", state.getAttribute(STATE_MODE));
} // add2ndToolbarFields
/**
* valid grade for point based type
*/
private void validPointGrade(SessionState state, String grade)
{
if (grade != null && !grade.equals(""))
{
if (grade.startsWith("-"))
{
// check for negative sign
addAlert(state, rb.getString("plesuse3"));
}
else
{
int index = grade.indexOf(".");
if (index != -1)
{
// when there is decimal points inside the grade, scale the number by 10
// but only one decimal place is supported
// for example, change 100.0 to 1000
if (!grade.equals("."))
{
if (grade.length() > index + 2)
{
// if there are more than one decimal point
addAlert(state, rb.getString("plesuse2"));
}
else
{
// decimal points is the only allowed character inside grade
// replace it with '1', and try to parse the new String into int
String gradeString = (grade.endsWith(".")) ? grade.substring(0, index).concat("0") : grade.substring(0,
index).concat(grade.substring(index + 1));
try
{
Integer.parseInt(gradeString);
}
catch (NumberFormatException e)
{
alertInvalidPoint(state, gradeString);
}
}
}
else
{
// grade is "."
addAlert(state, rb.getString("plesuse1"));
}
}
else
{
// There is no decimal point; should be int number
String gradeString = grade + "0";
try
{
Integer.parseInt(gradeString);
}
catch (NumberFormatException e)
{
alertInvalidPoint(state, gradeString);
}
}
}
}
} // validPointGrade
/**
* valid grade for point based type
*/
private void validLetterGrade(SessionState state, String grade)
{
String VALID_CHARS_FOR_LETTER_GRADE = " ABCDEFGHIJKLMNOPQRSTUVWXYZ+-";
boolean invalid = false;
if (grade != null)
{
grade = grade.toUpperCase();
for (int i = 0; i < grade.length() && !invalid; i++)
{
char c = grade.charAt(i);
if (VALID_CHARS_FOR_LETTER_GRADE.indexOf(c) == -1)
{
invalid = true;
}
}
if (invalid)
{
addAlert(state, rb.getString("plesuse0"));
}
}
}
private void alertInvalidPoint(SessionState state, String grade)
{
String VALID_CHARS_FOR_INT = "-01234567890";
boolean invalid = false;
// case 1: contains invalid char for int
for (int i = 0; i < grade.length() && !invalid; i++)
{
char c = grade.charAt(i);
if (VALID_CHARS_FOR_INT.indexOf(c) == -1)
{
invalid = true;
}
}
if (invalid)
{
addAlert(state, rb.getString("plesuse1"));
}
else
{
int maxInt = Integer.MAX_VALUE / 10;
int maxDec = Integer.MAX_VALUE - maxInt * 10;
// case 2: Due to our internal scaling, input String is larger than Integer.MAX_VALUE/10
addAlert(state, rb.getString("plesuse4") + maxInt + "." + maxDec + ".");
}
}
/**
* display grade properly
*/
private String displayGrade(SessionState state, String grade)
{
if (state.getAttribute(STATE_MESSAGE) == null)
{
if (grade != null && (grade.length() >= 1))
{
if (grade.indexOf(".") != -1)
{
if (grade.startsWith("."))
{
grade = "0".concat(grade);
}
else if (grade.endsWith("."))
{
grade = grade.concat("0");
}
}
else
{
try
{
Integer.parseInt(grade);
grade = grade.substring(0, grade.length() - 1) + "." + grade.substring(grade.length() - 1);
}
catch (NumberFormatException e)
{
alertInvalidPoint(state, grade);
}
}
}
else
{
grade = "";
}
}
return grade;
} // displayGrade
/**
* scale the point value by 10 if there is a valid point grade
*/
private String scalePointGrade(SessionState state, String point)
{
validPointGrade(state, point);
if (state.getAttribute(STATE_MESSAGE) == null)
{
if (point != null && (point.length() >= 1))
{
// when there is decimal points inside the grade, scale the number by 10
// but only one decimal place is supported
// for example, change 100.0 to 1000
int index = point.indexOf(".");
if (index != -1)
{
if (index == 0)
{
// if the point is the first char, add a 0 for the integer part
point = "0".concat(point.substring(1));
}
else if (index < point.length() - 1)
{
// use scale integer for gradePoint
point = point.substring(0, index) + point.substring(index + 1);
}
else
{
// decimal point is the last char
point = point.substring(0, index) + "0";
}
}
else
{
// if there is no decimal place, scale up the integer by 10
point = point + "0";
}
// filter out the "zero grade"
if (point.equals("00"))
{
point = "0";
}
}
}
return point;
} // scalePointGrade
/**
* Processes formatted text that is coming back from the browser (from the formatted text editing widget).
*
* @param state
* Used to pass in any user-visible alerts or errors when processing the text
* @param strFromBrowser
* The string from the browser
* @param checkForFormattingErrors
* Whether to check for formatted text errors - if true, look for errors in the formatted text. If false, accept the formatted text without looking for errors.
* @return The formatted text
*/
private String processFormattedTextFromBrowser(SessionState state, String strFromBrowser, boolean checkForFormattingErrors)
{
StringBuilder alertMsg = new StringBuilder();
try
{
boolean replaceWhitespaceTags = true;
String text = FormattedText.processFormattedText(strFromBrowser, alertMsg, checkForFormattingErrors,
replaceWhitespaceTags);
if (alertMsg.length() > 0) addAlert(state, alertMsg.toString());
return text;
}
catch (Exception e)
{
Log.warn("chef", this + ": ", e);
return strFromBrowser;
}
}
/**
* Processes the given assignmnent feedback text, as returned from the user's browser. Makes sure that the Chef-style markup {{like this}} is properly balanced.
*/
private String processAssignmentFeedbackFromBrowser(SessionState state, String strFromBrowser)
{
if (strFromBrowser == null || strFromBrowser.length() == 0) return strFromBrowser;
StringBuilder buf = new StringBuilder(strFromBrowser);
int pos = -1;
int numopentags = 0;
while ((pos = buf.indexOf("{{")) != -1)
{
buf.replace(pos, pos + "{{".length(), "<ins>");
numopentags++;
}
while ((pos = buf.indexOf("}}")) != -1)
{
buf.replace(pos, pos + "}}".length(), "</ins>");
numopentags--;
}
while (numopentags > 0)
{
buf.append("</ins>");
numopentags--;
}
boolean checkForFormattingErrors = false; // so that grading isn't held up by formatting errors
buf = new StringBuilder(processFormattedTextFromBrowser(state, buf.toString(), checkForFormattingErrors));
while ((pos = buf.indexOf("<ins>")) != -1)
{
buf.replace(pos, pos + "<ins>".length(), "{{");
}
while ((pos = buf.indexOf("</ins>")) != -1)
{
buf.replace(pos, pos + "</ins>".length(), "}}");
}
return buf.toString();
}
/**
* Called to deal with old Chef-style assignment feedback annotation, {{like this}}.
*
* @param value
* A formatted text string that may contain {{}} style markup
* @return HTML ready to for display on a browser
*/
public static String escapeAssignmentFeedback(String value)
{
if (value == null || value.length() == 0) return value;
value = fixAssignmentFeedback(value);
StringBuilder buf = new StringBuilder(value);
int pos = -1;
while ((pos = buf.indexOf("{{")) != -1)
{
buf.replace(pos, pos + "{{".length(), "<span class='highlight'>");
}
while ((pos = buf.indexOf("}}")) != -1)
{
buf.replace(pos, pos + "}}".length(), "</span>");
}
return FormattedText.escapeHtmlFormattedText(buf.toString());
}
/**
* Escapes the given assignment feedback text, to be edited as formatted text (perhaps using the formatted text widget)
*/
public static String escapeAssignmentFeedbackTextarea(String value)
{
if (value == null || value.length() == 0) return value;
value = fixAssignmentFeedback(value);
return FormattedText.escapeHtmlFormattedTextarea(value);
}
/**
* Apply the fix to pre 1.1.05 assignments submissions feedback.
*/
private static String fixAssignmentFeedback(String value)
{
if (value == null || value.length() == 0) return value;
StringBuilder buf = new StringBuilder(value);
int pos = -1;
// <br/> -> \n
while ((pos = buf.indexOf("<br/>")) != -1)
{
buf.replace(pos, pos + "<br/>".length(), "\n");
}
// <span class='chefAlert'>( -> {{
while ((pos = buf.indexOf("<span class='chefAlert'>(")) != -1)
{
buf.replace(pos, pos + "<span class='chefAlert'>(".length(), "{{");
}
// )</span> -> }}
while ((pos = buf.indexOf(")</span>")) != -1)
{
buf.replace(pos, pos + ")</span>".length(), "}}");
}
while ((pos = buf.indexOf("<ins>")) != -1)
{
buf.replace(pos, pos + "<ins>".length(), "{{");
}
while ((pos = buf.indexOf("</ins>")) != -1)
{
buf.replace(pos, pos + "</ins>".length(), "}}");
}
return buf.toString();
} // fixAssignmentFeedback
/**
* Apply the fix to pre 1.1.05 assignments submissions feedback.
*/
public static String showPrevFeedback(String value)
{
if (value == null || value.length() == 0) return value;
StringBuilder buf = new StringBuilder(value);
int pos = -1;
// <br/> -> \n
while ((pos = buf.indexOf("\n")) != -1)
{
buf.replace(pos, pos + "\n".length(), "<br />");
}
return buf.toString();
} // showPrevFeedback
private boolean alertGlobalNavigation(SessionState state, RunData data)
{
String mode = (String) state.getAttribute(STATE_MODE);
ParameterParser params = data.getParameters();
if (mode.equals(MODE_STUDENT_VIEW_SUBMISSION) || mode.equals(MODE_STUDENT_PREVIEW_SUBMISSION)
|| mode.equals(MODE_STUDENT_VIEW_GRADE) || mode.equals(MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT)
|| mode.equals(MODE_INSTRUCTOR_DELETE_ASSIGNMENT) || mode.equals(MODE_INSTRUCTOR_GRADE_SUBMISSION)
|| mode.equals(MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION) || mode.equals(MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT)
|| mode.equals(MODE_INSTRUCTOR_VIEW_ASSIGNMENT) || mode.equals(MODE_INSTRUCTOR_REORDER_ASSIGNMENT))
{
if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) == null)
{
addAlert(state, rb.getString("alert.globalNavi"));
state.setAttribute(ALERT_GLOBAL_NAVIGATION, Boolean.TRUE);
if (mode.equals(MODE_STUDENT_VIEW_SUBMISSION))
{
// retrieve the submission text (as formatted text)
boolean checkForFormattingErrors = true; // the student is submitting something - so check for errors
String text = processFormattedTextFromBrowser(state, params.getCleanString(VIEW_SUBMISSION_TEXT),
checkForFormattingErrors);
state.setAttribute(VIEW_SUBMISSION_TEXT, text);
if (params.getString(VIEW_SUBMISSION_HONOR_PLEDGE_YES) != null)
{
state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, "true");
}
state.setAttribute(FilePickerHelper.FILE_PICKER_TITLE_TEXT, rb.getString("gen.addatt"));
// TODO: file picker to save in dropbox? -ggolden
// User[] users = { UserDirectoryService.getCurrentUser() };
// state.setAttribute(ResourcesAction.STATE_SAVE_ATTACHMENT_IN_DROPBOX, users);
}
else if (mode.equals(MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT))
{
setNewAssignmentParameters(data, false);
}
else if (mode.equals(MODE_INSTRUCTOR_GRADE_SUBMISSION))
{
readGradeForm(data, state, "read");
}
return true;
}
}
return false;
} // alertGlobalNavigation
/**
* Dispatch function inside add submission page
*/
public void doRead_add_submission_form(RunData data)
{
String option = data.getParameters().getString("option");
if (option.equals("cancel"))
{
// cancel
doCancel_show_submission(data);
}
else if (option.equals("preview"))
{
// preview
doPreview_submission(data);
}
else if (option.equals("save"))
{
// save draft
doSave_submission(data);
}
else if (option.equals("post"))
{
// post
doPost_submission(data);
}
else if (option.equals("revise"))
{
// done preview
doDone_preview_submission(data);
}
else if (option.equals("attach"))
{
// attach
ToolSession toolSession = SessionManager.getCurrentToolSession();
String userId = SessionManager.getCurrentSessionUserId();
String siteId = SiteService.getUserSiteId(userId);
String collectionId = ContentHostingService.getSiteCollection(siteId);
toolSession.setAttribute(FilePickerHelper.DEFAULT_COLLECTION_ID, collectionId);
doAttachments(data);
}
}
/**
* Set default score for all ungraded non electronic submissions
* @param data
*/
public void doSet_defaultNotGradedNonElectronicScore(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
String grade = StringUtil.trimToNull(params.getString("defaultGrade"));
if (grade == null)
{
addAlert(state, rb.getString("plespethe2"));
}
String assignmentId = (String) state.getAttribute(EXPORT_ASSIGNMENT_REF);
try
{
// record the default grade setting for no-submission
AssignmentEdit aEdit = AssignmentService.editAssignment(assignmentId);
aEdit.getPropertiesEdit().addProperty(GRADE_NO_SUBMISSION_DEFAULT_GRADE, grade);
AssignmentService.commitEdit(aEdit);
Assignment a = AssignmentService.getAssignment(assignmentId);
if (a.getContent().getTypeOfGrade() == Assignment.SCORE_GRADE_TYPE)
{
//for point-based grades
validPointGrade(state, grade);
if (state.getAttribute(STATE_MESSAGE) == null)
{
int maxGrade = a.getContent().getMaxGradePoint();
try
{
if (Integer.parseInt(scalePointGrade(state, grade)) > maxGrade)
{
if (state.getAttribute(GRADE_GREATER_THAN_MAX_ALERT) == null)
{
// alert user first when he enters grade bigger than max scale
addAlert(state, rb.getString("grad2"));
state.setAttribute(GRADE_GREATER_THAN_MAX_ALERT, Boolean.TRUE);
}
else
{
// remove the alert once user confirms he wants to give student higher grade
state.removeAttribute(GRADE_GREATER_THAN_MAX_ALERT);
}
}
}
catch (NumberFormatException e)
{
alertInvalidPoint(state, grade);
}
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
grade = scalePointGrade(state, grade);
}
}
if (grade != null && state.getAttribute(STATE_MESSAGE) == null)
{
// get the user list
List submissions = AssignmentService.getSubmissions(a);
for (int i = 0; i<submissions.size(); i++)
{
// get the submission object
AssignmentSubmission submission = (AssignmentSubmission) submissions.get(i);
if (submission.getSubmitted() && !submission.getGraded())
{
// update the grades for those existing non-submissions
AssignmentSubmissionEdit sEdit = AssignmentService.editSubmission(submission.getReference());
sEdit.setGrade(grade);
sEdit.setGraded(true);
AssignmentService.commitEdit(sEdit);
}
}
}
}
catch (Exception e)
{
Log.warn("chef", e.toString());
}
}
/**
*
*/
public void doSet_defaultNoSubmissionScore(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
String grade = StringUtil.trimToNull(params.getString("defaultGrade"));
if (grade == null)
{
addAlert(state, rb.getString("plespethe2"));
}
String assignmentId = (String) state.getAttribute(EXPORT_ASSIGNMENT_REF);
try
{
// record the default grade setting for no-submission
AssignmentEdit aEdit = AssignmentService.editAssignment(assignmentId);
aEdit.getPropertiesEdit().addProperty(GRADE_NO_SUBMISSION_DEFAULT_GRADE, grade);
AssignmentService.commitEdit(aEdit);
Assignment a = AssignmentService.getAssignment(assignmentId);
if (a.getContent().getTypeOfGrade() == Assignment.SCORE_GRADE_TYPE)
{
//for point-based grades
validPointGrade(state, grade);
if (state.getAttribute(STATE_MESSAGE) == null)
{
int maxGrade = a.getContent().getMaxGradePoint();
try
{
if (Integer.parseInt(scalePointGrade(state, grade)) > maxGrade)
{
if (state.getAttribute(GRADE_GREATER_THAN_MAX_ALERT) == null)
{
// alert user first when he enters grade bigger than max scale
addAlert(state, rb.getString("grad2"));
state.setAttribute(GRADE_GREATER_THAN_MAX_ALERT, Boolean.TRUE);
}
else
{
// remove the alert once user confirms he wants to give student higher grade
state.removeAttribute(GRADE_GREATER_THAN_MAX_ALERT);
}
}
}
catch (NumberFormatException e)
{
alertInvalidPoint(state, grade);
}
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
grade = scalePointGrade(state, grade);
}
}
if (grade != null && state.getAttribute(STATE_MESSAGE) == null)
{
// get the user list
List userSubmissions = new Vector();
if (state.getAttribute(USER_SUBMISSIONS) != null)
{
userSubmissions = (List) state.getAttribute(USER_SUBMISSIONS);
}
// constructor a new UserSubmissions list
List userSubmissionsNew = new Vector();
for (int i = 0; i<userSubmissions.size(); i++)
{
// get the UserSubmission object
UserSubmission us = (UserSubmission) userSubmissions.get(i);
User u = us.getUser();
AssignmentSubmission submission = us.getSubmission();
// check whether there is a submission associated
if (submission == null)
{
AssignmentSubmissionEdit s = AssignmentService.addSubmission((String) state.getAttribute(STATE_CONTEXT_STRING), assignmentId, u.getId());
s.removeSubmitter(UserDirectoryService.getCurrentUser());
s.addSubmitter(u);
// submitted by without submit time
s.setSubmitted(true);
s.setGrade(grade);
s.setGraded(true);
s.setAssignment(a);
AssignmentService.commitEdit(s);
// update the UserSubmission list by adding newly created Submission object
AssignmentSubmission sub = AssignmentService.getSubmission(s.getReference());
userSubmissionsNew.add(new UserSubmission(u, sub));
}
else if (submission.getTimeSubmitted() == null)
{
// update the grades for those existing non-submissions
AssignmentSubmissionEdit sEdit = AssignmentService.editSubmission(submission.getReference());
sEdit.setGrade(grade);
sEdit.setSubmitted(true);
sEdit.setGraded(true);
sEdit.setAssignment(a);
AssignmentService.commitEdit(sEdit);
userSubmissionsNew.add(new UserSubmission(u, AssignmentService.getSubmission(sEdit.getReference())));
}
else
{
// no change for this user
userSubmissionsNew.add(us);
}
}
state.setAttribute(USER_SUBMISSIONS, userSubmissionsNew);
}
}
catch (Exception e)
{
Log.warn("chef", e.toString());
}
}
/**
*
* @return
*/
public void doUpload_all(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String flow = params.getString("flow");
if (flow.equals("upload"))
{
// upload
doUpload_all_upload(data);
}
else if (flow.equals("cancel"))
{
// cancel
doCancel_upload_all(data);
}
}
public void doUpload_all_upload(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String contextString = ToolManager.getCurrentPlacement().getContext();
String toolTitle = ToolManager.getTool(ASSIGNMENT_TOOL_ID).getTitle();
String aReference = (String) state.getAttribute(EXPORT_ASSIGNMENT_REF);
String associateGradebookAssignment = null;
boolean hasSubmissionText = false;
boolean hasSubmissionAttachment = false;
boolean hasGradeFile = false;
boolean hasFeedbackText = false;
boolean hasComment = false;
boolean hasFeedbackAttachment = false;
boolean releaseGrades = false;
// check against the content elements selection
if (params.getString("studentSubmissionText") != null)
{
// should contain student submission text information
hasSubmissionText = true;
}
if (params.getString("studentSubmissionAttachment") != null)
{
// should contain student submission attachment information
hasSubmissionAttachment = true;
}
if (params.getString("gradeFile") != null)
{
// should contain grade file
hasGradeFile = true;
}
if (params.getString("feedbackTexts") != null)
{
// inline text
hasFeedbackText = true;
}
if (params.getString("feedbackComments") != null)
{
// comments.txt should be available
hasComment = true;
}
if (params.getString("feedbackAttachments") != null)
{
// feedback attachment
hasFeedbackAttachment = true;
}
if (params.getString("release") != null)
{
// comments.xml should be available
releaseGrades = params.getBoolean("release");
}
state.setAttribute(UPLOAD_ALL_HAS_SUBMISSION_TEXT, Boolean.valueOf(hasSubmissionText));
state.setAttribute(UPLOAD_ALL_HAS_SUBMISSION_ATTACHMENT, Boolean.valueOf(hasSubmissionAttachment));
state.setAttribute(UPLOAD_ALL_HAS_GRADEFILE, Boolean.valueOf(hasGradeFile));
state.setAttribute(UPLOAD_ALL_HAS_COMMENTS, Boolean.valueOf(hasComment));
state.setAttribute(UPLOAD_ALL_HAS_FEEDBACK_TEXT, Boolean.valueOf(hasFeedbackText));
state.setAttribute(UPLOAD_ALL_HAS_FEEDBACK_ATTACHMENT, Boolean.valueOf(hasFeedbackAttachment));
state.setAttribute(UPLOAD_ALL_RELEASE_GRADES, Boolean.valueOf(releaseGrades));
if (!hasSubmissionText && !hasSubmissionAttachment && !hasGradeFile && !hasComment && !hasFeedbackAttachment)
{
// has to choose one upload feature
addAlert(state, rb.getString("uploadall.alert.choose.element"));
}
else
{
// constructor the hashtable for all submission objects
Hashtable submissionTable = new Hashtable();
Assignment assignment = null;
try
{
assignment = AssignmentService.getAssignment(aReference);
associateGradebookAssignment = StringUtil.trimToNull(assignment.getProperties().getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT));
Iterator sIterator = AssignmentService.getSubmissions(assignment).iterator();
while (sIterator.hasNext())
{
AssignmentSubmission s = (AssignmentSubmission) sIterator.next();
User[] users = s.getSubmitters();
if (users.length > 0 && users[0] != null)
{
submissionTable.put(users[0].getSortName(), new UploadGradeWrapper("", "", "", new Vector(), new Vector(), "", ""));
}
}
}
catch (Exception e)
{
Log.warn("chef", e.toString());
}
// see if the user uploaded a file
FileItem fileFromUpload = null;
String fileName = null;
fileFromUpload = params.getFileItem("file");
String max_file_size_mb = ServerConfigurationService.getString("content.upload.max", "1");
int max_bytes = 1024 * 1024;
try
{
max_bytes = Integer.parseInt(max_file_size_mb) * 1024 * 1024;
}
catch(Exception e)
{
// if unable to parse an integer from the value
// in the properties file, use 1 MB as a default
max_file_size_mb = "1";
max_bytes = 1024 * 1024;
}
if(fileFromUpload == null)
{
// "The user submitted a file to upload but it was too big!"
addAlert(state, rb.getString("uploadall.size") + " " + max_file_size_mb + "MB " + rb.getString("uploadall.exceeded"));
}
else if (fileFromUpload.getFileName() == null || fileFromUpload.getFileName().length() == 0)
{
// no file
addAlert(state, rb.getString("uploadall.alert.zipFile"));
}
else
{
byte[] fileData = fileFromUpload.get();
if(fileData.length >= max_bytes)
{
addAlert(state, rb.getString("uploadall.size") + " " + max_file_size_mb + "MB " + rb.getString("uploadall.exceeded"));
}
else if(fileData.length > 0)
{
ZipInputStream zin = new ZipInputStream(new ByteArrayInputStream(fileData));
ZipEntry entry;
try
{
while ((entry=zin.getNextEntry()) != null)
{
String entryName = entry.getName();
if (!entry.isDirectory() && entryName.indexOf("/._") == -1)
{
if (entryName.endsWith("grades.csv"))
{
if (hasGradeFile)
{
// read grades.cvs from zip
String result = StringUtil.trimToZero(readIntoString(zin));
String[] lines=null;
if (result.indexOf("\r") != -1)
lines = result.split("\r");
else if (result.indexOf("\n") != -1)
lines = result.split("\n");
for (int i = 3; i<lines.length; i++)
{
// escape the first three header lines
String[] items = lines[i].split(",");
if (items.length > 3)
{
// has grade information
try
{
User u = UserDirectoryService.getUserByEid(items[0]/*user id*/);
if (u != null)
{
UploadGradeWrapper w = (UploadGradeWrapper) submissionTable.get(u.getSortName());
if (w != null)
{
String itemString = items[3];
int gradeType = assignment.getContent().getTypeOfGrade();
if (gradeType == Assignment.SCORE_GRADE_TYPE)
{
validPointGrade(state, itemString);
}
else
{
validLetterGrade(state, itemString);
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
w.setGrade(gradeType == Assignment.SCORE_GRADE_TYPE?scalePointGrade(state, itemString):itemString);
submissionTable.put(u.getSortName(), w);
}
}
}
}
catch (Exception e )
{
Log.warn("chef", e.toString());
}
}
}
}
}
else
{
// get user sort name
String userName = "";
if (entryName.indexOf("/") != -1)
{
// remove the part of zip name
userName = entryName.substring(entryName.indexOf("/")+1);
// get out the user name part
if (userName.indexOf("/") != -1)
{
userName = userName.substring(0, userName.indexOf("/"));
}
// remove the eid part
if (userName.indexOf("(") != -1)
{
userName = userName.substring(0, userName.indexOf("("));
}
}
if (hasComment && entryName.indexOf("comments") != -1)
{
// read the comments file
String comment = getBodyTextFromZipHtml(zin);
if (submissionTable.containsKey(userName) && comment != null)
{
UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userName);
r.setComment(comment);
submissionTable.put(userName, r);
}
}
if (hasFeedbackText && entryName.indexOf("feedbackText") != -1)
{
// upload the feedback text
String text = getBodyTextFromZipHtml(zin);
if (submissionTable.containsKey(userName) && text != null)
{
UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userName);
r.setFeedbackText(text);
submissionTable.put(userName, r);
}
}
if (hasSubmissionText && entryName.indexOf("_submissionText") != -1)
{
// upload the student submission text
String text = getBodyTextFromZipHtml(zin);
if (submissionTable.containsKey(userName) && text != null)
{
UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userName);
r.setText(text);
submissionTable.put(userName, r);
}
}
if (hasSubmissionAttachment)
{
// upload the submission attachment
String submissionFolder = "/" + rb.getString("download.submission.attachment") + "/";
if ( entryName.indexOf(submissionFolder) != -1)
uploadZipAttachments(state, submissionTable, zin, entry, entryName, userName, "submission");
}
if (hasFeedbackAttachment)
{
// upload the feedback attachment
String submissionFolder = "/" + rb.getString("download.feedback.attachment") + "/";
if ( entryName.indexOf(submissionFolder) != -1)
uploadZipAttachments(state, submissionTable, zin, entry, entryName, userName, "feedback");
}
// if this is a timestamp file
if (entryName.indexOf("timestamp") != -1)
{
byte[] timeStamp = readIntoBytes(zin, entryName, entry.getSize());
UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userName);
r.setSubmissionTimestamp(new String(timeStamp));
submissionTable.put(userName, r);
}
}
}
}
}
catch (IOException e)
{
// uploaded file is not a valid archive
addAlert(state, rb.getString("uploadall.alert.zipFile"));
}
}
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
// update related submissions
if (assignment != null)
{
Iterator sIterator = AssignmentService.getSubmissions(assignment).iterator();
while (sIterator.hasNext())
{
AssignmentSubmission s = (AssignmentSubmission) sIterator.next();
User[] users = s.getSubmitters();
if (users.length > 0 && users[0] != null)
{
String uName = users[0].getSortName();
if (submissionTable.containsKey(uName))
{
// update the AssignmetnSubmission record
try
{
AssignmentSubmissionEdit sEdit = AssignmentService.editSubmission(s.getReference());
UploadGradeWrapper w = (UploadGradeWrapper) submissionTable.get(uName);
// the submission text
if (hasSubmissionText)
{
sEdit.setSubmittedText(w.getText());
}
// the feedback text
if (hasFeedbackText)
{
sEdit.setFeedbackText(w.getFeedbackText());
}
// the submission attachment
if (hasSubmissionAttachment)
{
sEdit.clearSubmittedAttachments();
for (Iterator attachments = w.getSubmissionAttachments().iterator(); attachments.hasNext();)
{
sEdit.addSubmittedAttachment((Reference) attachments.next());
}
}
// the feedback attachment
if (hasFeedbackAttachment)
{
sEdit.clearFeedbackAttachments();
for (Iterator attachments = w.getFeedbackAttachments().iterator(); attachments.hasNext();)
{
sEdit.addFeedbackAttachment((Reference) attachments.next());
}
}
// the feedback comment
if (hasComment)
{
sEdit.setFeedbackComment(w.getComment());
}
// the grade file
if (hasGradeFile)
{
// set grade
String grade = StringUtil.trimToNull(w.getGrade());
sEdit.setGrade(grade);
if (grade != null && !grade.equals(rb.getString("gen.nograd")) && !grade.equals("ungraded"))
sEdit.setGraded(true);
}
// release or not
sEdit.setGradeReleased(releaseGrades);
sEdit.setReturned(releaseGrades);
if (releaseGrades)
{
sEdit.setTimeReturned(TimeService.newTime());
// update grade in gradebook
if (associateGradebookAssignment != null)
{
integrateGradebook(state, aReference, associateGradebookAssignment, null, null, null, -1, null, sEdit.getReference(), "update");
}
}
// if the current submission lacks timestamp while the timestamp exists inside the zip file
if (StringUtil.trimToNull(w.getSubmissionTimeStamp()) != null && sEdit.getTimeSubmitted() == null)
{
sEdit.setTimeSubmitted(TimeService.newTimeGmt(w.getSubmissionTimeStamp()));
sEdit.setSubmitted(true);
}
// commit
AssignmentService.commitEdit(sEdit);
}
catch (Exception ee)
{
Log.debug("chef", ee.toString());
}
}
}
}
}
}
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
// go back to the list of submissions view
cleanUploadAllContext(state);
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT);
}
}
/**
* This is to get the submission or feedback attachment from the upload zip file into the submission object
* @param state
* @param submissionTable
* @param zin
* @param entry
* @param entryName
* @param userName
* @param submissionOrFeedback
*/
private void uploadZipAttachments(SessionState state, Hashtable submissionTable, ZipInputStream zin, ZipEntry entry, String entryName, String userName, String submissionOrFeedback) {
// upload all the files as instuctor attachments to the submission for grading purpose
String fName = entryName.substring(entryName.lastIndexOf("/") + 1, entryName.length());
ContentTypeImageService iService = (ContentTypeImageService) state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE);
try
{
if (submissionTable.containsKey(userName))
{
// get file extension for detecting content type
// ignore those hidden files
String extension = "";
if(!fName.contains(".") || (fName.contains(".") && fName.indexOf(".") != 0))
{
// add the file as attachment
ResourceProperties properties = ContentHostingService.newResourceProperties();
properties.addProperty(ResourceProperties.PROP_DISPLAY_NAME, fName);
String[] parts = fName.split("\\.");
if(parts.length > 1)
{
extension = parts[parts.length - 1];
}
String contentType = ((ContentTypeImageService) state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)).getContentType(extension);
ContentResourceEdit attachment = ContentHostingService.addAttachmentResource(fName);
attachment.setContent(readIntoBytes(zin, entryName, entry.getSize()));
attachment.setContentType(contentType);
attachment.getPropertiesEdit().addAll(properties);
ContentHostingService.commitResource(attachment);
UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userName);
List attachments = submissionOrFeedback.equals("submission")?r.getSubmissionAttachments():r.getFeedbackAttachments();
attachments.add(EntityManager.newReference(attachment.getReference()));
if (submissionOrFeedback.equals("submission"))
{
r.setSubmissionAttachments(attachments);
}
else
{
r.setFeedbackAttachments(attachments);
}
submissionTable.put(userName, r);
}
}
}
catch (Exception ee)
{
Log.warn("chef", ee.toString());
}
}
private String getBodyTextFromZipHtml(ZipInputStream zin)
{
String rv = "";
try
{
rv = StringUtil.trimToNull(readIntoString(zin));
}
catch (IOException e)
{
Log.debug("chef", this + " " + e.toString());
}
if (rv != null)
{
int start = rv.indexOf("<body>");
int end = rv.indexOf("</body>");
if (start != -1 && end != -1)
{
// get the text in between
rv = rv.substring(start+6, end);
}
}
return rv;
}
private byte[] readIntoBytes(ZipInputStream zin, String fName, long length) throws IOException {
StringBuilder b = new StringBuilder();
byte[] buffer = new byte[4096];
File f = new File(fName);
f.getParentFile().mkdirs();
FileOutputStream fout = new FileOutputStream(f);
int len;
while ((len = zin.read(buffer)) > 0)
{
fout.write(buffer, 0, len);
}
zin.closeEntry();
fout.close();
FileInputStream fis = new FileInputStream(f);
FileChannel fc = fis.getChannel();
byte[] data = new byte[(int)(fc.size())]; // fc.size returns the size of the file which backs the channel
ByteBuffer bb = ByteBuffer.wrap(data);
fc.read(bb);
//remove the file
f.delete();
return data;
}
private String readIntoString(ZipInputStream zin) throws IOException
{
StringBuilder buffer = new StringBuilder();
int size = 2048;
byte[] data = new byte[2048];
while (true)
{
try
{
size = zin.read(data, 0, data.length);
if (size > 0)
{
buffer.append(new String(data, 0, size));
}
else
{
break;
}
}
catch (IOException e)
{
Log.debug("chef", "readIntoString " + e.toString());
}
}
return buffer.toString();
}
/**
*
* @return
*/
public void doCancel_upload_all(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT);
cleanUploadAllContext(state);
}
/**
* clean the state variabled used by upload all process
*/
private void cleanUploadAllContext(SessionState state)
{
state.removeAttribute(UPLOAD_ALL_HAS_SUBMISSION_TEXT);
state.removeAttribute(UPLOAD_ALL_HAS_SUBMISSION_ATTACHMENT);
state.removeAttribute(UPLOAD_ALL_HAS_FEEDBACK_ATTACHMENT);
state.removeAttribute(UPLOAD_ALL_HAS_FEEDBACK_TEXT);
state.removeAttribute(UPLOAD_ALL_HAS_GRADEFILE);
state.removeAttribute(UPLOAD_ALL_HAS_COMMENTS);
state.removeAttribute(UPLOAD_ALL_RELEASE_GRADES);
}
/**
* Action is to preparing to go to the upload files
*/
public void doPrep_upload_all(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_UPLOAD_ALL);
} // doPrep_upload_all
/**
* the UploadGradeWrapper class to be used for the "upload all" feature
*/
public class UploadGradeWrapper
{
/**
* the grade
*/
String m_grade = null;
/**
* the text
*/
String m_text = null;
/**
* the submission attachment list
*/
List m_submissionAttachments = EntityManager.newReferenceList();
/**
* the comment
*/
String m_comment = "";
/**
* the timestamp
*/
String m_timeStamp="";
/**
* the feedback text
*/
String m_feedbackText="";
/**
* the feedback attachment list
*/
List m_feedbackAttachments = EntityManager.newReferenceList();
public UploadGradeWrapper(String grade, String text, String comment, List submissionAttachments, List feedbackAttachments, String timeStamp, String feedbackText)
{
m_grade = grade;
m_text = text;
m_comment = comment;
m_submissionAttachments = submissionAttachments;
m_feedbackAttachments = feedbackAttachments;
m_feedbackText = feedbackText;
m_timeStamp = timeStamp;
}
/**
* Returns grade string
*/
public String getGrade()
{
return m_grade;
}
/**
* Returns the text
*/
public String getText()
{
return m_text;
}
/**
* Returns the comment string
*/
public String getComment()
{
return m_comment;
}
/**
* Returns the submission attachment list
*/
public List getSubmissionAttachments()
{
return m_submissionAttachments;
}
/**
* Returns the feedback attachment list
*/
public List getFeedbackAttachments()
{
return m_feedbackAttachments;
}
/**
* submission timestamp
* @return
*/
public String getSubmissionTimeStamp()
{
return m_timeStamp;
}
/**
* feedback text/incline comment
* @return
*/
public String getFeedbackText()
{
return m_feedbackText;
}
/**
* set the grade string
*/
public void setGrade(String grade)
{
m_grade = grade;
}
/**
* set the text
*/
public void setText(String text)
{
m_text = text;
}
/**
* set the comment string
*/
public void setComment(String comment)
{
m_comment = comment;
}
/**
* set the submission attachment list
*/
public void setSubmissionAttachments(List attachments)
{
m_submissionAttachments = attachments;
}
/**
* set the attachment list
*/
public void setFeedbackAttachments(List attachments)
{
m_feedbackAttachments = attachments;
}
/**
* set the submission timestamp
*/
public void setSubmissionTimestamp(String timeStamp)
{
m_timeStamp = timeStamp;
}
/**
* set the feedback text
*/
public void setFeedbackText(String feedbackText)
{
m_feedbackText = feedbackText;
}
}
private List<DecoratedTaggingProvider> initDecoratedProviders() {
TaggingManager taggingManager = (TaggingManager) ComponentManager
.get("org.sakaiproject.assignment.taggable.api.TaggingManager");
List<DecoratedTaggingProvider> providers = new ArrayList<DecoratedTaggingProvider>();
for (TaggingProvider provider : taggingManager.getProviders())
{
providers.add(new DecoratedTaggingProvider(provider));
}
return providers;
}
private List<DecoratedTaggingProvider> addProviders(Context context, SessionState state)
{
String mode = (String) state.getAttribute(STATE_MODE);
List<DecoratedTaggingProvider> providers = (List) state
.getAttribute(mode + PROVIDER_LIST);
if (providers == null)
{
providers = initDecoratedProviders();
state.setAttribute(mode + PROVIDER_LIST, providers);
}
context.put("providers", providers);
return providers;
}
private void addActivity(Context context, Assignment assignment)
{
AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager
.get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer");
context.put("activity", assignmentActivityProducer
.getActivity(assignment));
}
private void addItem(Context context, AssignmentSubmission submission, String userId)
{
AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager
.get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer");
context.put("item", assignmentActivityProducer
.getItem(submission, userId));
}
private ContentReviewService contentReviewService;
public String getReportURL(Long score) {
getContentReviewService();
return contentReviewService.getIconUrlforScore(score);
}
private void getContentReviewService() {
if (contentReviewService == null)
{
contentReviewService = (ContentReviewService) ComponentManager.get(ContentReviewService.class.getName());
}
}
}
| true | true | public int compare(Object o1, Object o2)
{
int result = -1;
if (m_criteria == null)
{
m_criteria = SORTED_BY_DEFAULT;
}
/** *********** for sorting assignments ****************** */
if (m_criteria.equals(SORTED_BY_DEFAULT))
{
int s1 = ((Assignment) o1).getPosition_order();
int s2 = ((Assignment) o2).getPosition_order();
if ( s1 == s2 ) // we either have 2 assignments with no existing postion_order or a numbering error, so sort by duedate
{
// sorted by the assignment due date
Time t1 = ((Assignment) o1).getDueTime();
Time t2 = ((Assignment) o2).getDueTime();
if (t1 == null)
{
result = -1;
}
else if (t2 == null)
{
result = 1;
}
else if (t1.equals(t2))
{
t1 = ((Assignment) o1).getTimeCreated();
t2 = ((Assignment) o2).getTimeCreated();
}
if (t1!=null && t2!=null && t1.before(t2))
{
result = -1;
}
else
{
result = 1;
}
}
else if ( s1 == 0 && s2 > 0 ) // order has not been set on this object, so put it at the bottom of the list
{
result = 1;
}
else if ( s2 == 0 && s1 > 0 ) // making sure assignments with no position_order stay at the bottom
{
result = -1;
}
else // 2 legitimate postion orders
{
result = (s1 < s2) ? -1 : 1;
}
}
if (m_criteria.equals(SORTED_BY_TITLE))
{
// sorted by the assignment title
String s1 = ((Assignment) o1).getTitle();
String s2 = ((Assignment) o2).getTitle();
result = compareString(s1, s2);
}
else if (m_criteria.equals(SORTED_BY_SECTION))
{
// sorted by the assignment section
String s1 = ((Assignment) o1).getSection();
String s2 = ((Assignment) o2).getSection();
result = compareString(s1, s2);
}
else if (m_criteria.equals(SORTED_BY_DUEDATE))
{
// sorted by the assignment due date
Time t1 = ((Assignment) o1).getDueTime();
Time t2 = ((Assignment) o2).getDueTime();
if (t1 == null)
{
result = -1;
}
else if (t2 == null)
{
result = 1;
}
else if (t1.before(t2))
{
result = -1;
}
else
{
result = 1;
}
}
else if (m_criteria.equals(SORTED_BY_OPENDATE))
{
// sorted by the assignment open
Time t1 = ((Assignment) o1).getOpenTime();
Time t2 = ((Assignment) o2).getOpenTime();
if (t1 == null)
{
result = -1;
}
else if (t2 == null)
{
result = 1;
}
if (t1.before(t2))
{
result = -1;
}
else
{
result = 1;
}
}
else if (m_criteria.equals(SORTED_BY_ASSIGNMENT_STATUS))
{
String s1 = getAssignmentStatus((Assignment) o1);
String s2 = getAssignmentStatus((Assignment) o2);
result = compareString(s1, s2);
}
else if (m_criteria.equals(SORTED_BY_NUM_SUBMISSIONS))
{
// sort by numbers of submissions
// initialize
int subNum1 = 0;
int subNum2 = 0;
Iterator submissions1 = AssignmentService.getSubmissions((Assignment) o1).iterator();
while (submissions1.hasNext())
{
AssignmentSubmission submission1 = (AssignmentSubmission) submissions1.next();
if (submission1.getSubmitted()) subNum1++;
}
Iterator submissions2 = AssignmentService.getSubmissions((Assignment) o2).iterator();
while (submissions2.hasNext())
{
AssignmentSubmission submission2 = (AssignmentSubmission) submissions2.next();
if (submission2.getSubmitted()) subNum2++;
}
result = (subNum1 > subNum2) ? 1 : -1;
}
else if (m_criteria.equals(SORTED_BY_NUM_UNGRADED))
{
// sort by numbers of ungraded submissions
// initialize
int ungraded1 = 0;
int ungraded2 = 0;
Iterator submissions1 = AssignmentService.getSubmissions((Assignment) o1).iterator();
while (submissions1.hasNext())
{
AssignmentSubmission submission1 = (AssignmentSubmission) submissions1.next();
if (submission1.getSubmitted() && !submission1.getGraded()) ungraded1++;
}
Iterator submissions2 = AssignmentService.getSubmissions((Assignment) o2).iterator();
while (submissions2.hasNext())
{
AssignmentSubmission submission2 = (AssignmentSubmission) submissions2.next();
if (submission2.getSubmitted() && !submission2.getGraded()) ungraded2++;
}
result = (ungraded1 > ungraded2) ? 1 : -1;
}
else if (m_criteria.equals(SORTED_BY_SUBMISSION_STATUS))
{
try
{
AssignmentSubmission submission1 = AssignmentService.getSubmission(((Assignment) o1).getId(), m_user);
String status1 = getSubmissionStatus(submission1, (Assignment) o1);
AssignmentSubmission submission2 = AssignmentService.getSubmission(((Assignment) o2).getId(), m_user);
String status2 = getSubmissionStatus(submission2, (Assignment) o2);
result = compareString(status1, status2);
}
catch (IdUnusedException e)
{
return 1;
}
catch (PermissionException e)
{
return 1;
}
}
else if (m_criteria.equals(SORTED_BY_GRADE))
{
try
{
AssignmentSubmission submission1 = AssignmentService.getSubmission(((Assignment) o1).getId(), m_user);
String grade1 = " ";
if (submission1 != null && submission1.getGraded() && submission1.getGradeReleased())
{
grade1 = submission1.getGrade();
}
AssignmentSubmission submission2 = AssignmentService.getSubmission(((Assignment) o2).getId(), m_user);
String grade2 = " ";
if (submission2 != null && submission2.getGraded() && submission2.getGradeReleased())
{
grade2 = submission2.getGrade();
}
result = compareString(grade1, grade2);
}
catch (IdUnusedException e)
{
return 1;
}
catch (PermissionException e)
{
return 1;
}
}
else if (m_criteria.equals(SORTED_BY_MAX_GRADE))
{
String maxGrade1 = maxGrade(((Assignment) o1).getContent().getTypeOfGrade(), (Assignment) o1);
String maxGrade2 = maxGrade(((Assignment) o2).getContent().getTypeOfGrade(), (Assignment) o2);
try
{
// do integer comparation inside point grade type
int max1 = Integer.parseInt(maxGrade1);
int max2 = Integer.parseInt(maxGrade2);
result = (max1 < max2) ? -1 : 1;
}
catch (NumberFormatException e)
{
// otherwise do an alpha-compare
result = compareString(maxGrade1, maxGrade2);
}
}
// group related sorting
else if (m_criteria.equals(SORTED_BY_FOR))
{
// sorted by the public view attribute
String factor1 = getAssignmentRange((Assignment) o1);
String factor2 = getAssignmentRange((Assignment) o2);
result = compareString(factor1, factor2);
}
else if (m_criteria.equals(SORTED_BY_GROUP_TITLE))
{
// sorted by the group title
String factor1 = ((Group) o1).getTitle();
String factor2 = ((Group) o2).getTitle();
result = compareString(factor1, factor2);
}
else if (m_criteria.equals(SORTED_BY_GROUP_DESCRIPTION))
{
// sorted by the group description
String factor1 = ((Group) o1).getDescription();
String factor2 = ((Group) o2).getDescription();
if (factor1 == null)
{
factor1 = "";
}
if (factor2 == null)
{
factor2 = "";
}
result = compareString(factor1, factor2);
}
/** ***************** for sorting submissions in instructor grade assignment view ************* */
else if(m_criteria.equals(SORTED_GRADE_SUBMISSION_CONTENTREVIEW))
{
UserSubmission u1 = (UserSubmission) o1;
UserSubmission u2 = (UserSubmission) o2;
if (u1 == null || u2 == null || u1.getUser() == null || u2.getUser() == null )
{
result = 1;
}
else
{
AssignmentSubmission s1 = u1.getSubmission();
AssignmentSubmission s2 = u2.getSubmission();
if (s1 == null)
{
result = -1;
}
else if (s2 == null )
{
result = 1;
}
else
{
int score1 = u1.getSubmission().getReviewScore();
int score2 = u2.getSubmission().getReviewScore();
result = (new Integer(score1)).intValue() > (new Integer(score2)).intValue() ? 1 : -1;
}
}
}
else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_LASTNAME))
{
// sorted by the submitters sort name
UserSubmission u1 = (UserSubmission) o1;
UserSubmission u2 = (UserSubmission) o2;
if (u1 == null || u2 == null || u1.getUser() == null || u2.getUser() == null )
{
result = 1;
}
else
{
String lName1 = u1.getUser().getSortName();
String lName2 = u2.getUser().getSortName();
result = compareString(lName1, lName2);
}
}
else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_SUBMIT_TIME))
{
// sorted by submission time
UserSubmission u1 = (UserSubmission) o1;
UserSubmission u2 = (UserSubmission) o2;
if (u1 == null || u2 == null)
{
result = -1;
}
else
{
AssignmentSubmission s1 = u1.getSubmission();
AssignmentSubmission s2 = u2.getSubmission();
if (s1 == null || s1.getTimeSubmitted() == null)
{
result = -1;
}
else if (s2 == null || s2.getTimeSubmitted() == null)
{
result = 1;
}
else if (s1.getTimeSubmitted().before(s2.getTimeSubmitted()))
{
result = -1;
}
else
{
result = 1;
}
}
}
else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_STATUS))
{
// sort by submission status
UserSubmission u1 = (UserSubmission) o1;
UserSubmission u2 = (UserSubmission) o2;
String status1 = "";
String status2 = "";
if (u1 == null)
{
status1 = rb.getString("listsub.nosub");
}
else
{
AssignmentSubmission s1 = u1.getSubmission();
if (s1 == null)
{
status1 = rb.getString("listsub.nosub");
}
else
{
status1 = getSubmissionStatus(m_state, (AssignmentSubmission) s1);
}
}
if (u2 == null)
{
status2 = rb.getString("listsub.nosub");
}
else
{
AssignmentSubmission s2 = u2.getSubmission();
if (s2 == null)
{
status2 = rb.getString("listsub.nosub");
}
else
{
status2 = getSubmissionStatus(m_state, (AssignmentSubmission) s2);
}
}
result = compareString(status1, status2);
}
else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_GRADE))
{
// sort by submission status
UserSubmission u1 = (UserSubmission) o1;
UserSubmission u2 = (UserSubmission) o2;
if (u1 == null || u2 == null)
{
result = -1;
}
else
{
AssignmentSubmission s1 = u1.getSubmission();
AssignmentSubmission s2 = u2.getSubmission();
//sort by submission grade
if (s1 == null)
{
result = -1;
}
else if (s2 == null)
{
result = 1;
}
else
{
String grade1 = s1.getGrade();
String grade2 = s2.getGrade();
if (grade1 == null)
{
grade1 = "";
}
if (grade2 == null)
{
grade2 = "";
}
// if scale is points
if ((s1.getAssignment().getContent().getTypeOfGrade() == 3)
&& ((s2.getAssignment().getContent().getTypeOfGrade() == 3)))
{
if (grade1.equals(""))
{
result = -1;
}
else if (grade2.equals(""))
{
result = 1;
}
else
{
result = (new Double(grade1)).doubleValue() > (new Double(grade2)).doubleValue() ? 1 : -1;
}
}
else
{
result = compareString(grade1, grade2);
}
}
}
}
else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_RELEASED))
{
// sort by submission status
UserSubmission u1 = (UserSubmission) o1;
UserSubmission u2 = (UserSubmission) o2;
if (u1 == null || u2 == null)
{
result = -1;
}
else
{
AssignmentSubmission s1 = u1.getSubmission();
AssignmentSubmission s2 = u2.getSubmission();
if (s1 == null)
{
result = -1;
}
else if (s2 == null)
{
result = 1;
}
else
{
// sort by submission released
String released1 = (new Boolean(s1.getGradeReleased())).toString();
String released2 = (new Boolean(s2.getGradeReleased())).toString();
result = compareString(released1, released2);
}
}
}
/****** for other sort on submissions **/
else if (m_criteria.equals(SORTED_SUBMISSION_BY_LASTNAME))
{
// sorted by the submitters sort name
User[] u1 = ((AssignmentSubmission) o1).getSubmitters();
User[] u2 = ((AssignmentSubmission) o2).getSubmitters();
if (u1 == null || u2 == null)
{
return 1;
}
else
{
String submitters1 = "";
String submitters2 = "";
for (int j = 0; j < u1.length; j++)
{
if (u1[j] != null && u1[j].getLastName() != null)
{
if (j > 0)
{
submitters1 = submitters1.concat("; ");
}
submitters1 = submitters1.concat("" + u1[j].getLastName());
}
}
for (int j = 0; j < u2.length; j++)
{
if (u2[j] != null && u2[j].getLastName() != null)
{
if (j > 0)
{
submitters2 = submitters2.concat("; ");
}
submitters2 = submitters2.concat(u2[j].getLastName());
}
}
result = compareString(submitters1, submitters2);
}
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_SUBMIT_TIME))
{
// sorted by submission time
Time t1 = ((AssignmentSubmission) o1).getTimeSubmitted();
Time t2 = ((AssignmentSubmission) o2).getTimeSubmitted();
if (t1 == null)
{
result = -1;
}
else if (t2 == null)
{
result = 1;
}
else if (t1.before(t2))
{
result = -1;
}
else
{
result = 1;
}
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_STATUS))
{
// sort by submission status
String status1 = getSubmissionStatus(m_state, (AssignmentSubmission) o1);
String status2 = getSubmissionStatus(m_state, (AssignmentSubmission) o2);
result = compareString(status1, status2);
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_GRADE))
{
// sort by submission grade
String grade1 = ((AssignmentSubmission) o1).getGrade();
String grade2 = ((AssignmentSubmission) o2).getGrade();
if (grade1 == null)
{
grade1 = "";
}
if (grade2 == null)
{
grade2 = "";
}
// if scale is points
if ((((AssignmentSubmission) o1).getAssignment().getContent().getTypeOfGrade() == 3)
&& ((((AssignmentSubmission) o2).getAssignment().getContent().getTypeOfGrade() == 3)))
{
if (grade1.equals(""))
{
result = -1;
}
else if (grade2.equals(""))
{
result = 1;
}
else
{
result = (new Double(grade1)).doubleValue() > (new Double(grade2)).doubleValue() ? 1 : -1;
}
}
else
{
result = compareString(grade1, grade2);
}
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_GRADE))
{
// sort by submission grade
String grade1 = ((AssignmentSubmission) o1).getGrade();
String grade2 = ((AssignmentSubmission) o2).getGrade();
if (grade1 == null)
{
grade1 = "";
}
if (grade2 == null)
{
grade2 = "";
}
// if scale is points
if ((((AssignmentSubmission) o1).getAssignment().getContent().getTypeOfGrade() == 3)
&& ((((AssignmentSubmission) o2).getAssignment().getContent().getTypeOfGrade() == 3)))
{
if (grade1.equals(""))
{
result = -1;
}
else if (grade2.equals(""))
{
result = 1;
}
else
{
result = (new Double(grade1)).doubleValue() > (new Double(grade2)).doubleValue() ? 1 : -1;
}
}
else
{
result = compareString(grade1, grade2);
}
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_MAX_GRADE))
{
Assignment a1 = ((AssignmentSubmission) o1).getAssignment();
Assignment a2 = ((AssignmentSubmission) o2).getAssignment();
String maxGrade1 = maxGrade(a1.getContent().getTypeOfGrade(), a1);
String maxGrade2 = maxGrade(a2.getContent().getTypeOfGrade(), a2);
try
{
// do integer comparation inside point grade type
int max1 = Integer.parseInt(maxGrade1);
int max2 = Integer.parseInt(maxGrade2);
result = (max1 < max2) ? -1 : 1;
}
catch (NumberFormatException e)
{
// otherwise do an alpha-compare
result = maxGrade1.compareTo(maxGrade2);
}
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_RELEASED))
{
// sort by submission released
String released1 = (new Boolean(((AssignmentSubmission) o1).getGradeReleased())).toString();
String released2 = (new Boolean(((AssignmentSubmission) o2).getGradeReleased())).toString();
result = compareString(released1, released2);
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_ASSIGNMENT))
{
// sort by submission's assignment
String title1 = ((AssignmentSubmission) o1).getAssignment().getContent().getTitle();
String title2 = ((AssignmentSubmission) o2).getAssignment().getContent().getTitle();
result = compareString(title1, title2);
}
// sort ascending or descending
if (m_asc.equals(Boolean.FALSE.toString()))
{
result = -result;
}
return result;
} // compare
| public int compare(Object o1, Object o2)
{
int result = -1;
if (m_criteria == null)
{
m_criteria = SORTED_BY_DEFAULT;
}
/** *********** for sorting assignments ****************** */
if (m_criteria.equals(SORTED_BY_DEFAULT))
{
int s1 = ((Assignment) o1).getPosition_order();
int s2 = ((Assignment) o2).getPosition_order();
if ( s1 == s2 ) // we either have 2 assignments with no existing postion_order or a numbering error, so sort by duedate
{
// sorted by the assignment due date
Time t1 = ((Assignment) o1).getDueTime();
Time t2 = ((Assignment) o2).getDueTime();
if (t1 == null)
{
result = -1;
}
else if (t2 == null)
{
result = 1;
}
else if (t1.equals(t2))
{
t1 = ((Assignment) o1).getTimeCreated();
t2 = ((Assignment) o2).getTimeCreated();
}
if (t1!=null && t2!=null && t1.before(t2))
{
result = -1;
}
else
{
result = 1;
}
}
else if ( s1 == 0 && s2 > 0 ) // order has not been set on this object, so put it at the bottom of the list
{
result = 1;
}
else if ( s2 == 0 && s1 > 0 ) // making sure assignments with no position_order stay at the bottom
{
result = -1;
}
else // 2 legitimate postion orders
{
result = (s1 < s2) ? -1 : 1;
}
}
if (m_criteria.equals(SORTED_BY_TITLE))
{
// sorted by the assignment title
String s1 = ((Assignment) o1).getTitle();
String s2 = ((Assignment) o2).getTitle();
result = compareString(s1, s2);
}
else if (m_criteria.equals(SORTED_BY_SECTION))
{
// sorted by the assignment section
String s1 = ((Assignment) o1).getSection();
String s2 = ((Assignment) o2).getSection();
result = compareString(s1, s2);
}
else if (m_criteria.equals(SORTED_BY_DUEDATE))
{
// sorted by the assignment due date
Time t1 = ((Assignment) o1).getDueTime();
Time t2 = ((Assignment) o2).getDueTime();
if (t1 == null)
{
result = -1;
}
else if (t2 == null)
{
result = 1;
}
else if (t1.before(t2))
{
result = -1;
}
else
{
result = 1;
}
}
else if (m_criteria.equals(SORTED_BY_OPENDATE))
{
// sorted by the assignment open
Time t1 = ((Assignment) o1).getOpenTime();
Time t2 = ((Assignment) o2).getOpenTime();
if (t1 == null)
{
result = -1;
}
else if (t2 == null)
{
result = 1;
}
if (t1.before(t2))
{
result = -1;
}
else
{
result = 1;
}
}
else if (m_criteria.equals(SORTED_BY_ASSIGNMENT_STATUS))
{
String s1 = getAssignmentStatus((Assignment) o1);
String s2 = getAssignmentStatus((Assignment) o2);
result = compareString(s1, s2);
}
else if (m_criteria.equals(SORTED_BY_NUM_SUBMISSIONS))
{
// sort by numbers of submissions
// initialize
int subNum1 = 0;
int subNum2 = 0;
Iterator submissions1 = AssignmentService.getSubmissions((Assignment) o1).iterator();
while (submissions1.hasNext())
{
AssignmentSubmission submission1 = (AssignmentSubmission) submissions1.next();
if (submission1.getSubmitted()) subNum1++;
}
Iterator submissions2 = AssignmentService.getSubmissions((Assignment) o2).iterator();
while (submissions2.hasNext())
{
AssignmentSubmission submission2 = (AssignmentSubmission) submissions2.next();
if (submission2.getSubmitted()) subNum2++;
}
result = (subNum1 > subNum2) ? 1 : -1;
}
else if (m_criteria.equals(SORTED_BY_NUM_UNGRADED))
{
// sort by numbers of ungraded submissions
// initialize
int ungraded1 = 0;
int ungraded2 = 0;
Iterator submissions1 = AssignmentService.getSubmissions((Assignment) o1).iterator();
while (submissions1.hasNext())
{
AssignmentSubmission submission1 = (AssignmentSubmission) submissions1.next();
if (submission1.getSubmitted() && !submission1.getGraded()) ungraded1++;
}
Iterator submissions2 = AssignmentService.getSubmissions((Assignment) o2).iterator();
while (submissions2.hasNext())
{
AssignmentSubmission submission2 = (AssignmentSubmission) submissions2.next();
if (submission2.getSubmitted() && !submission2.getGraded()) ungraded2++;
}
result = (ungraded1 > ungraded2) ? 1 : -1;
}
else if (m_criteria.equals(SORTED_BY_SUBMISSION_STATUS))
{
try
{
AssignmentSubmission submission1 = AssignmentService.getSubmission(((Assignment) o1).getId(), m_user);
String status1 = getSubmissionStatus(submission1, (Assignment) o1);
AssignmentSubmission submission2 = AssignmentService.getSubmission(((Assignment) o2).getId(), m_user);
String status2 = getSubmissionStatus(submission2, (Assignment) o2);
result = compareString(status1, status2);
}
catch (IdUnusedException e)
{
return 1;
}
catch (PermissionException e)
{
return 1;
}
}
else if (m_criteria.equals(SORTED_BY_GRADE))
{
try
{
AssignmentSubmission submission1 = AssignmentService.getSubmission(((Assignment) o1).getId(), m_user);
String grade1 = " ";
if (submission1 != null && submission1.getGraded() && submission1.getGradeReleased())
{
grade1 = submission1.getGrade();
}
AssignmentSubmission submission2 = AssignmentService.getSubmission(((Assignment) o2).getId(), m_user);
String grade2 = " ";
if (submission2 != null && submission2.getGraded() && submission2.getGradeReleased())
{
grade2 = submission2.getGrade();
}
result = compareString(grade1, grade2);
}
catch (IdUnusedException e)
{
return 1;
}
catch (PermissionException e)
{
return 1;
}
}
else if (m_criteria.equals(SORTED_BY_MAX_GRADE))
{
String maxGrade1 = maxGrade(((Assignment) o1).getContent().getTypeOfGrade(), (Assignment) o1);
String maxGrade2 = maxGrade(((Assignment) o2).getContent().getTypeOfGrade(), (Assignment) o2);
try
{
// do integer comparation inside point grade type
int max1 = Integer.parseInt(maxGrade1);
int max2 = Integer.parseInt(maxGrade2);
result = (max1 < max2) ? -1 : 1;
}
catch (NumberFormatException e)
{
// otherwise do an alpha-compare
result = compareString(maxGrade1, maxGrade2);
}
}
// group related sorting
else if (m_criteria.equals(SORTED_BY_FOR))
{
// sorted by the public view attribute
String factor1 = getAssignmentRange((Assignment) o1);
String factor2 = getAssignmentRange((Assignment) o2);
result = compareString(factor1, factor2);
}
else if (m_criteria.equals(SORTED_BY_GROUP_TITLE))
{
// sorted by the group title
String factor1 = ((Group) o1).getTitle();
String factor2 = ((Group) o2).getTitle();
result = compareString(factor1, factor2);
}
else if (m_criteria.equals(SORTED_BY_GROUP_DESCRIPTION))
{
// sorted by the group description
String factor1 = ((Group) o1).getDescription();
String factor2 = ((Group) o2).getDescription();
if (factor1 == null)
{
factor1 = "";
}
if (factor2 == null)
{
factor2 = "";
}
result = compareString(factor1, factor2);
}
/** ***************** for sorting submissions in instructor grade assignment view ************* */
else if(m_criteria.equals(SORTED_GRADE_SUBMISSION_CONTENTREVIEW))
{
UserSubmission u1 = (UserSubmission) o1;
UserSubmission u2 = (UserSubmission) o2;
if (u1 == null || u2 == null || u1.getUser() == null || u2.getUser() == null )
{
result = 1;
}
else
{
AssignmentSubmission s1 = u1.getSubmission();
AssignmentSubmission s2 = u2.getSubmission();
if (s1 == null)
{
result = -1;
}
else if (s2 == null )
{
result = 1;
}
else
{
int score1 = u1.getSubmission().getReviewScore();
int score2 = u2.getSubmission().getReviewScore();
result = (new Integer(score1)).intValue() > (new Integer(score2)).intValue() ? 1 : -1;
}
}
}
else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_LASTNAME))
{
// sorted by the submitters sort name
UserSubmission u1 = (UserSubmission) o1;
UserSubmission u2 = (UserSubmission) o2;
if (u1 == null || u2 == null || u1.getUser() == null || u2.getUser() == null )
{
result = 1;
}
else
{
String lName1 = u1.getUser().getSortName();
String lName2 = u2.getUser().getSortName();
result = compareString(lName1, lName2);
}
}
else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_SUBMIT_TIME))
{
// sorted by submission time
UserSubmission u1 = (UserSubmission) o1;
UserSubmission u2 = (UserSubmission) o2;
if (u1 == null || u2 == null)
{
result = -1;
}
else
{
AssignmentSubmission s1 = u1.getSubmission();
AssignmentSubmission s2 = u2.getSubmission();
if (s1 == null || s1.getTimeSubmitted() == null)
{
result = -1;
}
else if (s2 == null || s2.getTimeSubmitted() == null)
{
result = 1;
}
else if (s1.getTimeSubmitted().before(s2.getTimeSubmitted()))
{
result = -1;
}
else
{
result = 1;
}
}
}
else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_STATUS))
{
// sort by submission status
UserSubmission u1 = (UserSubmission) o1;
UserSubmission u2 = (UserSubmission) o2;
String status1 = "";
String status2 = "";
if (u1 == null)
{
status1 = rb.getString("listsub.nosub");
}
else
{
AssignmentSubmission s1 = u1.getSubmission();
if (s1 == null)
{
status1 = rb.getString("listsub.nosub");
}
else
{
status1 = getSubmissionStatus(m_state, (AssignmentSubmission) s1);
}
}
if (u2 == null)
{
status2 = rb.getString("listsub.nosub");
}
else
{
AssignmentSubmission s2 = u2.getSubmission();
if (s2 == null)
{
status2 = rb.getString("listsub.nosub");
}
else
{
status2 = getSubmissionStatus(m_state, (AssignmentSubmission) s2);
}
}
result = compareString(status1, status2);
}
else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_GRADE))
{
// sort by submission status
UserSubmission u1 = (UserSubmission) o1;
UserSubmission u2 = (UserSubmission) o2;
if (u1 == null || u2 == null)
{
result = -1;
}
else
{
AssignmentSubmission s1 = u1.getSubmission();
AssignmentSubmission s2 = u2.getSubmission();
//sort by submission grade
if (s1 == null)
{
result = -1;
}
else if (s2 == null)
{
result = 1;
}
else
{
String grade1 = s1.getGrade();
String grade2 = s2.getGrade();
if (grade1 == null)
{
grade1 = "";
}
if (grade2 == null)
{
grade2 = "";
}
// if scale is points
if ((s1.getAssignment().getContent().getTypeOfGrade() == 3)
&& ((s2.getAssignment().getContent().getTypeOfGrade() == 3)))
{
if (grade1.equals(""))
{
result = -1;
}
else if (grade2.equals(""))
{
result = 1;
}
else
{
result = (new Double(grade1)).doubleValue() > (new Double(grade2)).doubleValue() ? 1 : -1;
}
}
else
{
result = compareString(grade1, grade2);
}
}
}
}
else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_RELEASED))
{
// sort by submission status
UserSubmission u1 = (UserSubmission) o1;
UserSubmission u2 = (UserSubmission) o2;
if (u1 == null || u2 == null)
{
result = -1;
}
else
{
AssignmentSubmission s1 = u1.getSubmission();
AssignmentSubmission s2 = u2.getSubmission();
if (s1 == null)
{
result = -1;
}
else if (s2 == null)
{
result = 1;
}
else
{
// sort by submission released
String released1 = (new Boolean(s1.getGradeReleased())).toString();
String released2 = (new Boolean(s2.getGradeReleased())).toString();
result = compareString(released1, released2);
}
}
}
/****** for other sort on submissions **/
else if (m_criteria.equals(SORTED_SUBMISSION_BY_LASTNAME))
{
// sorted by the submitters sort name
User[] u1 = ((AssignmentSubmission) o1).getSubmitters();
User[] u2 = ((AssignmentSubmission) o2).getSubmitters();
if (u1 == null || u2 == null)
{
return 1;
}
else
{
String submitters1 = "";
String submitters2 = "";
for (int j = 0; j < u1.length; j++)
{
if (u1[j] != null && u1[j].getLastName() != null)
{
if (j > 0)
{
submitters1 = submitters1.concat("; ");
}
submitters1 = submitters1.concat("" + u1[j].getLastName());
}
}
for (int j = 0; j < u2.length; j++)
{
if (u2[j] != null && u2[j].getLastName() != null)
{
if (j > 0)
{
submitters2 = submitters2.concat("; ");
}
submitters2 = submitters2.concat(u2[j].getLastName());
}
}
result = compareString(submitters1, submitters2);
}
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_SUBMIT_TIME))
{
// sorted by submission time
Time t1 = ((AssignmentSubmission) o1).getTimeSubmitted();
Time t2 = ((AssignmentSubmission) o2).getTimeSubmitted();
if (t1 == null)
{
result = -1;
}
else if (t2 == null)
{
result = 1;
}
else if (t1.before(t2))
{
result = -1;
}
else
{
result = 1;
}
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_STATUS))
{
// sort by submission status
String status1 = getSubmissionStatus(m_state, (AssignmentSubmission) o1);
String status2 = getSubmissionStatus(m_state, (AssignmentSubmission) o2);
result = compareString(status1, status2);
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_GRADE))
{
// sort by submission grade
String grade1 = ((AssignmentSubmission) o1).getGrade();
String grade2 = ((AssignmentSubmission) o2).getGrade();
if (grade1 == null)
{
grade1 = "";
}
if (grade2 == null)
{
grade2 = "";
}
// if scale is points
if ((((AssignmentSubmission) o1).getAssignment().getContent().getTypeOfGrade() == 3)
&& ((((AssignmentSubmission) o2).getAssignment().getContent().getTypeOfGrade() == 3)))
{
if (grade1.equals(""))
{
result = -1;
}
else if (grade2.equals(""))
{
result = 1;
}
else
{
result = (new Double(grade1)).doubleValue() > (new Double(grade2)).doubleValue() ? 1 : -1;
}
}
else
{
result = compareString(grade1, grade2);
}
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_GRADE))
{
// sort by submission grade
String grade1 = ((AssignmentSubmission) o1).getGrade();
String grade2 = ((AssignmentSubmission) o2).getGrade();
if (grade1 == null)
{
grade1 = "";
}
if (grade2 == null)
{
grade2 = "";
}
// if scale is points
if ((((AssignmentSubmission) o1).getAssignment().getContent().getTypeOfGrade() == 3)
&& ((((AssignmentSubmission) o2).getAssignment().getContent().getTypeOfGrade() == 3)))
{
if (grade1.equals(""))
{
result = -1;
}
else if (grade2.equals(""))
{
result = 1;
}
else
{
result = (new Double(grade1)).doubleValue() > (new Double(grade2)).doubleValue() ? 1 : -1;
}
}
else
{
result = compareString(grade1, grade2);
}
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_MAX_GRADE))
{
Assignment a1 = ((AssignmentSubmission) o1).getAssignment();
Assignment a2 = ((AssignmentSubmission) o2).getAssignment();
String maxGrade1 = maxGrade(a1.getContent().getTypeOfGrade(), a1);
String maxGrade2 = maxGrade(a2.getContent().getTypeOfGrade(), a2);
try
{
// do integer comparation inside point grade type
int max1 = Integer.parseInt(maxGrade1);
int max2 = Integer.parseInt(maxGrade2);
result = (max1 < max2) ? -1 : 1;
}
catch (NumberFormatException e)
{
// otherwise do an alpha-compare
result = maxGrade1.compareTo(maxGrade2);
}
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_RELEASED))
{
// sort by submission released
String released1 = (new Boolean(((AssignmentSubmission) o1).getGradeReleased())).toString();
String released2 = (new Boolean(((AssignmentSubmission) o2).getGradeReleased())).toString();
result = compareString(released1, released2);
}
else if (m_criteria.equals(SORTED_SUBMISSION_BY_ASSIGNMENT))
{
// sort by submission's assignment
String title1 = ((AssignmentSubmission) o1).getAssignment().getContent().getTitle();
String title2 = ((AssignmentSubmission) o2).getAssignment().getContent().getTitle();
result = compareString(title1, title2);
}
// sort ascending or descending
if (!Boolean.valueOf(m_asc))
{
result = -result;
}
return result;
} // compare
|
diff --git a/src/main/java/com/metaweb/gridworks/protograph/Link.java b/src/main/java/com/metaweb/gridworks/protograph/Link.java
index b162c99..d67d2cc 100644
--- a/src/main/java/com/metaweb/gridworks/protograph/Link.java
+++ b/src/main/java/com/metaweb/gridworks/protograph/Link.java
@@ -1,36 +1,39 @@
package com.metaweb.gridworks.protograph;
import java.util.Properties;
import org.json.JSONException;
import org.json.JSONWriter;
import com.metaweb.gridworks.Jsonizable;
public class Link implements Jsonizable {
final public FreebaseProperty property;
final public Node target;
public Link(FreebaseProperty property, Node target) {
this.property = property;
this.target = target;
}
public FreebaseProperty getProperty() {
return property;
}
public Node getTarget() {
return target;
}
public void write(JSONWriter writer, Properties options)
throws JSONException {
writer.object();
writer.key("property"); property.write(writer, options);
- writer.key("target"); target.write(writer, options);
+ if (target != null) {
+ writer.key("target");
+ target.write(writer, options);
+ }
writer.endObject();
}
}
| true | true | public void write(JSONWriter writer, Properties options)
throws JSONException {
writer.object();
writer.key("property"); property.write(writer, options);
writer.key("target"); target.write(writer, options);
writer.endObject();
}
| public void write(JSONWriter writer, Properties options)
throws JSONException {
writer.object();
writer.key("property"); property.write(writer, options);
if (target != null) {
writer.key("target");
target.write(writer, options);
}
writer.endObject();
}
|
diff --git a/src/main/java/me/eccentric_nz/TARDIS/listeners/TARDISSaveSignListener.java b/src/main/java/me/eccentric_nz/TARDIS/listeners/TARDISSaveSignListener.java
index 5bc9d1b58..c99beb6bb 100644
--- a/src/main/java/me/eccentric_nz/TARDIS/listeners/TARDISSaveSignListener.java
+++ b/src/main/java/me/eccentric_nz/TARDIS/listeners/TARDISSaveSignListener.java
@@ -1,124 +1,126 @@
/*
* Copyright (C) 2013 eccentric_nz
*
* 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 me.eccentric_nz.TARDIS.listeners;
import java.util.HashMap;
import java.util.List;
import me.eccentric_nz.TARDIS.TARDIS;
import me.eccentric_nz.TARDIS.database.QueryFactory;
import me.eccentric_nz.TARDIS.database.ResultSetTardis;
import me.eccentric_nz.TARDIS.database.ResultSetTravellers;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
/**
*
* @author eccentric_nz
*/
public class TARDISSaveSignListener implements Listener {
private final TARDIS plugin;
public TARDISSaveSignListener(TARDIS plugin) {
this.plugin = plugin;
}
/**
* Listens for player clicking inside an inventory. If the inventory is a
* TARDIS GUI, then the click is processed accordingly.
*
* @param event a player clicking an inventory slot
*/
@EventHandler(priority = EventPriority.NORMAL)
public void onSaveTerminalClick(InventoryClickEvent event) {
Inventory inv = event.getInventory();
String name = inv.getTitle();
if (name.equals("§4TARDIS saves")) {
event.setCancelled(true);
int slot = event.getRawSlot();
if (slot < 54) {
final Player player = (Player) event.getWhoClicked();
String playerNameStr = player.getName();
// get the TARDIS the player is in
HashMap<String, Object> wheres = new HashMap<String, Object>();
wheres.put("player", playerNameStr);
ResultSetTravellers rst = new ResultSetTravellers(plugin, wheres, false);
if (rst.resultSet()) {
HashMap<String, Object> where = new HashMap<String, Object>();
where.put("tardis_id", rst.getTardis_id());
ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false);
if (rs.resultSet()) {
int id = rs.getTardis_id();
ItemStack is = inv.getItem(slot);
- ItemMeta im = is.getItemMeta();
- List<String> lore = im.getLore();
- String save = getDestination(lore);
- if (!save.equals(rs.getCurrent())) {
- HashMap<String, Object> set = new HashMap<String, Object>();
- set.put("save", save);
- HashMap<String, Object> wheret = new HashMap<String, Object>();
- wheret.put("tardis_id", id);
- new QueryFactory(plugin).doUpdate("tardis", set, wheret);
- plugin.tardisHasDestination.put(id, plugin.getArtronConfig().getInt("random"));
- if (plugin.trackRescue.containsKey(Integer.valueOf(id))) {
- plugin.trackRescue.remove(Integer.valueOf(id));
+ if (is != null) {
+ ItemMeta im = is.getItemMeta();
+ List<String> lore = im.getLore();
+ String save = getDestination(lore);
+ if (!save.equals(rs.getCurrent())) {
+ HashMap<String, Object> set = new HashMap<String, Object>();
+ set.put("save", save);
+ HashMap<String, Object> wheret = new HashMap<String, Object>();
+ wheret.put("tardis_id", id);
+ new QueryFactory(plugin).doUpdate("tardis", set, wheret);
+ plugin.tardisHasDestination.put(id, plugin.getArtronConfig().getInt("random"));
+ if (plugin.trackRescue.containsKey(Integer.valueOf(id))) {
+ plugin.trackRescue.remove(Integer.valueOf(id));
+ }
+ close(player);
+ player.sendMessage(plugin.pluginName + im.getDisplayName() + " destination set. Please release the handbrake!");
+ } else if (!lore.contains("§6Current location")) {
+ lore.add("§6Current location");
+ im.setLore(lore);
+ is.setItemMeta(im);
}
- close(player);
- player.sendMessage(plugin.pluginName + im.getDisplayName() + " destination set. Please release the handbrake!");
- } else {
- lore.add("§6Current location");
- im.setLore(lore);
- is.setItemMeta(im);
}
}
}
}
}
}
/**
* Converts an Item Stacks lore to a destination string in the correct
* format for entry into the database.
*
* @param lore the lore to read
* @return the destination string
*/
private String getDestination(List<String> lore) {
return lore.get(0) + ":" + lore.get(1) + ":" + lore.get(2) + ":" + lore.get(3);
}
/**
* Closes the inventory.
*
* @param p the player using the GUI
*/
private void close(final Player p) {
final String n = p.getName();
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
p.closeInventory();
}
}, 1L);
}
}
| false | true | public void onSaveTerminalClick(InventoryClickEvent event) {
Inventory inv = event.getInventory();
String name = inv.getTitle();
if (name.equals("§4TARDIS saves")) {
event.setCancelled(true);
int slot = event.getRawSlot();
if (slot < 54) {
final Player player = (Player) event.getWhoClicked();
String playerNameStr = player.getName();
// get the TARDIS the player is in
HashMap<String, Object> wheres = new HashMap<String, Object>();
wheres.put("player", playerNameStr);
ResultSetTravellers rst = new ResultSetTravellers(plugin, wheres, false);
if (rst.resultSet()) {
HashMap<String, Object> where = new HashMap<String, Object>();
where.put("tardis_id", rst.getTardis_id());
ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false);
if (rs.resultSet()) {
int id = rs.getTardis_id();
ItemStack is = inv.getItem(slot);
ItemMeta im = is.getItemMeta();
List<String> lore = im.getLore();
String save = getDestination(lore);
if (!save.equals(rs.getCurrent())) {
HashMap<String, Object> set = new HashMap<String, Object>();
set.put("save", save);
HashMap<String, Object> wheret = new HashMap<String, Object>();
wheret.put("tardis_id", id);
new QueryFactory(plugin).doUpdate("tardis", set, wheret);
plugin.tardisHasDestination.put(id, plugin.getArtronConfig().getInt("random"));
if (plugin.trackRescue.containsKey(Integer.valueOf(id))) {
plugin.trackRescue.remove(Integer.valueOf(id));
}
close(player);
player.sendMessage(plugin.pluginName + im.getDisplayName() + " destination set. Please release the handbrake!");
} else {
lore.add("§6Current location");
im.setLore(lore);
is.setItemMeta(im);
}
}
}
}
}
}
| public void onSaveTerminalClick(InventoryClickEvent event) {
Inventory inv = event.getInventory();
String name = inv.getTitle();
if (name.equals("§4TARDIS saves")) {
event.setCancelled(true);
int slot = event.getRawSlot();
if (slot < 54) {
final Player player = (Player) event.getWhoClicked();
String playerNameStr = player.getName();
// get the TARDIS the player is in
HashMap<String, Object> wheres = new HashMap<String, Object>();
wheres.put("player", playerNameStr);
ResultSetTravellers rst = new ResultSetTravellers(plugin, wheres, false);
if (rst.resultSet()) {
HashMap<String, Object> where = new HashMap<String, Object>();
where.put("tardis_id", rst.getTardis_id());
ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false);
if (rs.resultSet()) {
int id = rs.getTardis_id();
ItemStack is = inv.getItem(slot);
if (is != null) {
ItemMeta im = is.getItemMeta();
List<String> lore = im.getLore();
String save = getDestination(lore);
if (!save.equals(rs.getCurrent())) {
HashMap<String, Object> set = new HashMap<String, Object>();
set.put("save", save);
HashMap<String, Object> wheret = new HashMap<String, Object>();
wheret.put("tardis_id", id);
new QueryFactory(plugin).doUpdate("tardis", set, wheret);
plugin.tardisHasDestination.put(id, plugin.getArtronConfig().getInt("random"));
if (plugin.trackRescue.containsKey(Integer.valueOf(id))) {
plugin.trackRescue.remove(Integer.valueOf(id));
}
close(player);
player.sendMessage(plugin.pluginName + im.getDisplayName() + " destination set. Please release the handbrake!");
} else if (!lore.contains("§6Current location")) {
lore.add("§6Current location");
im.setLore(lore);
is.setItemMeta(im);
}
}
}
}
}
}
}
|
diff --git a/src/com/axelby/podax/SubscriptionUpdater.java b/src/com/axelby/podax/SubscriptionUpdater.java
index 63cc0f7..a0662ad 100644
--- a/src/com/axelby/podax/SubscriptionUpdater.java
+++ b/src/com/axelby/podax/SubscriptionUpdater.java
@@ -1,273 +1,274 @@
package com.axelby.podax;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlSerializer;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.util.Xml;
import com.axelby.podax.R.drawable;
import com.axelby.podax.ui.MainActivity;
import com.axelby.podax.ui.PodcastDetailActivity;
import com.axelby.riasel.Feed;
import com.axelby.riasel.FeedItem;
import com.axelby.riasel.FeedParser;
public class SubscriptionUpdater {
private Context _context;
public SubscriptionUpdater(Context context) {
_context = context;
}
public void update(long subscriptionId) {
Cursor cursor = null;
try {
if (!Helper.ensureWifi(_context))
return;
Uri subscriptionUri = ContentUris.withAppendedId(SubscriptionProvider.URI, subscriptionId);
String[] projection = new String[] {
SubscriptionProvider.COLUMN_ID,
SubscriptionProvider.COLUMN_TITLE,
SubscriptionProvider.COLUMN_URL,
SubscriptionProvider.COLUMN_ETAG,
SubscriptionProvider.COLUMN_LAST_MODIFIED,
};
ContentValues subscriptionValues = new ContentValues();
cursor = _context.getContentResolver().query(subscriptionUri, projection,
SubscriptionProvider.COLUMN_ID + " = ?",
new String[] { String.valueOf(subscriptionId) }, null);
if (!cursor.moveToNext())
return;
SubscriptionCursor subscription = new SubscriptionCursor(cursor);
showNotification(subscription);
URL url = new URL(subscription.getUrl());
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
if (subscription.getETag() != null)
connection.setRequestProperty("If-None-Match", subscription.getETag());
if (subscription.getLastModified() != null && subscription.getLastModified().getTime() > 0) {
SimpleDateFormat imsFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US);
connection.setRequestProperty("If-Modified-Since", imsFormat.format(subscription.getLastModified()));
}
int code = connection.getResponseCode();
// only valid response code is 200
// 304 (content not modified) is OK too
if (code != 200) {
return;
}
String eTag = connection.getHeaderField("ETag");
if (eTag != null) {
subscriptionValues.put(SubscriptionProvider.COLUMN_ETAG, eTag);
if (eTag.equals(subscription.getETag()))
return;
}
String encoding = connection.getContentEncoding();
if (encoding == null) {
String contentType = connection.getContentType();
if (contentType != null && contentType.indexOf(";") > -1) {
encoding = contentType.split(";")[1].trim().substring("charset=".length());
}
}
try {
XmlPullParser parser = Xml.newPullParser();
parser.setInput(connection.getInputStream(), encoding);
Feed feed = FeedParser.parseFeed(parser);
if (feed == null)
return;
subscriptionValues.putAll(feed.getContentValues());
changeKeyString(subscriptionValues, "lastBuildDate", SubscriptionProvider.COLUMN_LAST_UPDATE);
for (FeedItem item : feed.getItems()) {
if (item.getMediaURL() == null || item.getMediaURL().length() == 0)
continue;
ContentValues podcastValues = item.getContentValues();
podcastValues.put(PodcastProvider.COLUMN_SUBSCRIPTION_ID, subscriptionId);
// translate Riasel keys to old Podax keys
changeKeyString(podcastValues, "mediaURL", PodcastProvider.COLUMN_MEDIA_URL);
changeKeyString(podcastValues, "mediaSize", PodcastProvider.COLUMN_FILE_SIZE);
+ changeKeyString(podcastValues, "paymentURL", PodcastProvider.COLUMN_PAYMENT);
if (changeKeyLong(podcastValues, "publicationDate", PodcastProvider.COLUMN_PUB_DATE))
podcastValues.put(PodcastProvider.COLUMN_PUB_DATE, podcastValues.getAsLong(PodcastProvider.COLUMN_PUB_DATE) / 1000);
if (podcastValues.containsKey(PodcastProvider.COLUMN_MEDIA_URL)) {
try {
_context.getContentResolver().insert(PodcastProvider.URI, podcastValues);
} catch (IllegalArgumentException e) {
Log.w("Podax", "error while inserting podcast: " + e.getMessage());
}
}
}
if (feed.getThumbnail() != null)
downloadThumbnail(subscriptionId, feed.getThumbnail());
} catch (XmlPullParserException e) {
// not much we can do about this
Log.w("Podax", "error in subscription xml: " + e.getMessage());
showUpdateErrorNotification(subscription, _context.getString(R.string.rss_not_valid));
}
// finish grabbing subscription values and update
subscriptionValues.put(SubscriptionProvider.COLUMN_LAST_UPDATE, new Date().getTime() / 1000);
_context.getContentResolver().update(subscriptionUri, subscriptionValues, null, null);
writeSubscriptionOPML();
} catch (Exception e) {
Log.w("Podax", "error while updating: " + e.getMessage());
} finally {
if (cursor != null)
cursor.close();
UpdateService.downloadPodcastsSilently(_context);
}
}
private boolean changeKeyString(ContentValues values, String oldKey, String newKey) {
if (values.containsKey(oldKey)) {
values.put(newKey, values.getAsString(oldKey));
values.remove(oldKey);
return true;
}
return false;
};
private boolean changeKeyLong(ContentValues values, String oldKey, String newKey) {
if (values.containsKey(oldKey)) {
values.put(newKey, values.getAsLong(oldKey));
values.remove(oldKey);
return true;
}
return false;
};
private void showUpdateErrorNotification(SubscriptionCursor subscription, String reason) {
Intent notificationIntent = MainActivity.getSubscriptionIntent(_context);
PendingIntent contentIntent = PendingIntent.getActivity(_context, 0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(_context)
.setSmallIcon(drawable.icon)
.setTicker("Error Updating Subscription")
.setWhen(System.currentTimeMillis())
.setContentTitle("Error updating " + subscription.getTitle())
.setContentText(reason)
.setContentIntent(contentIntent)
.setOngoing(false)
.getNotification();
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager notificationManager = (NotificationManager) _context.getSystemService(ns);
notificationManager.notify(Constants.SUBSCRIPTION_UPDATE_ERROR, notification);
}
protected void writeSubscriptionOPML() {
try {
File file = new File(_context.getExternalFilesDir(null), "podax.opml");
FileOutputStream output = new FileOutputStream(file);
XmlSerializer serializer = Xml.newSerializer();
serializer.setOutput(output, "UTF-8");
serializer.startDocument("UTF-8", true);
serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
serializer.startTag(null, "opml");
serializer.attribute(null, "version", "1.0");
serializer.startTag(null, "head");
serializer.startTag(null, "title");
serializer.text("Podax Subscriptions");
serializer.endTag(null, "title");
serializer.endTag(null, "head");
serializer.startTag(null, "body");
String[] projection = {
SubscriptionProvider.COLUMN_TITLE,
SubscriptionProvider.COLUMN_URL,
};
Cursor c = _context.getContentResolver().query(SubscriptionProvider.URI, projection , null, null, SubscriptionProvider.COLUMN_TITLE);
while (c.moveToNext()) {
SubscriptionCursor sub = new SubscriptionCursor(c);
serializer.startTag(null, "outline");
serializer.attribute(null, "type", "rss");
serializer.attribute(null, "title", sub.getTitle());
serializer.attribute(null, "xmlUrl", sub.getUrl());
serializer.endTag(null, "outline");
}
c.close();
serializer.endTag(null, "body");
serializer.endTag(null, "opml");
serializer.endDocument();
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void downloadThumbnail(long subscriptionId, String thumbnailUrl) {
File thumbnailFile = new File(SubscriptionProvider.getThumbnailFilename(subscriptionId));
if (thumbnailFile.exists())
return;
InputStream thumbIn;
try {
thumbIn = new URL(thumbnailUrl).openStream();
FileOutputStream thumbOut = new FileOutputStream(thumbnailFile.getAbsolutePath());
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = thumbIn.read(buffer)) > 0 )
thumbOut.write(buffer, 0, bufferLength);
thumbOut.close();
thumbIn.close();
} catch (IOException e) {
if (thumbnailFile.exists())
thumbnailFile.delete();
}
}
void showNotification(SubscriptionCursor subscription) {
Intent notificationIntent = new Intent(_context, PodcastDetailActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(_context, 0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(_context)
.setSmallIcon(drawable.icon)
.setWhen(System.currentTimeMillis())
.setContentTitle("Updating " + subscription.getTitle())
.setContentIntent(contentIntent)
.getNotification();
NotificationManager notificationManager = (NotificationManager) _context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(Constants.NOTIFICATION_UPDATE, notification);
}
}
| true | true | public void update(long subscriptionId) {
Cursor cursor = null;
try {
if (!Helper.ensureWifi(_context))
return;
Uri subscriptionUri = ContentUris.withAppendedId(SubscriptionProvider.URI, subscriptionId);
String[] projection = new String[] {
SubscriptionProvider.COLUMN_ID,
SubscriptionProvider.COLUMN_TITLE,
SubscriptionProvider.COLUMN_URL,
SubscriptionProvider.COLUMN_ETAG,
SubscriptionProvider.COLUMN_LAST_MODIFIED,
};
ContentValues subscriptionValues = new ContentValues();
cursor = _context.getContentResolver().query(subscriptionUri, projection,
SubscriptionProvider.COLUMN_ID + " = ?",
new String[] { String.valueOf(subscriptionId) }, null);
if (!cursor.moveToNext())
return;
SubscriptionCursor subscription = new SubscriptionCursor(cursor);
showNotification(subscription);
URL url = new URL(subscription.getUrl());
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
if (subscription.getETag() != null)
connection.setRequestProperty("If-None-Match", subscription.getETag());
if (subscription.getLastModified() != null && subscription.getLastModified().getTime() > 0) {
SimpleDateFormat imsFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US);
connection.setRequestProperty("If-Modified-Since", imsFormat.format(subscription.getLastModified()));
}
int code = connection.getResponseCode();
// only valid response code is 200
// 304 (content not modified) is OK too
if (code != 200) {
return;
}
String eTag = connection.getHeaderField("ETag");
if (eTag != null) {
subscriptionValues.put(SubscriptionProvider.COLUMN_ETAG, eTag);
if (eTag.equals(subscription.getETag()))
return;
}
String encoding = connection.getContentEncoding();
if (encoding == null) {
String contentType = connection.getContentType();
if (contentType != null && contentType.indexOf(";") > -1) {
encoding = contentType.split(";")[1].trim().substring("charset=".length());
}
}
try {
XmlPullParser parser = Xml.newPullParser();
parser.setInput(connection.getInputStream(), encoding);
Feed feed = FeedParser.parseFeed(parser);
if (feed == null)
return;
subscriptionValues.putAll(feed.getContentValues());
changeKeyString(subscriptionValues, "lastBuildDate", SubscriptionProvider.COLUMN_LAST_UPDATE);
for (FeedItem item : feed.getItems()) {
if (item.getMediaURL() == null || item.getMediaURL().length() == 0)
continue;
ContentValues podcastValues = item.getContentValues();
podcastValues.put(PodcastProvider.COLUMN_SUBSCRIPTION_ID, subscriptionId);
// translate Riasel keys to old Podax keys
changeKeyString(podcastValues, "mediaURL", PodcastProvider.COLUMN_MEDIA_URL);
changeKeyString(podcastValues, "mediaSize", PodcastProvider.COLUMN_FILE_SIZE);
if (changeKeyLong(podcastValues, "publicationDate", PodcastProvider.COLUMN_PUB_DATE))
podcastValues.put(PodcastProvider.COLUMN_PUB_DATE, podcastValues.getAsLong(PodcastProvider.COLUMN_PUB_DATE) / 1000);
if (podcastValues.containsKey(PodcastProvider.COLUMN_MEDIA_URL)) {
try {
_context.getContentResolver().insert(PodcastProvider.URI, podcastValues);
} catch (IllegalArgumentException e) {
Log.w("Podax", "error while inserting podcast: " + e.getMessage());
}
}
}
if (feed.getThumbnail() != null)
downloadThumbnail(subscriptionId, feed.getThumbnail());
} catch (XmlPullParserException e) {
// not much we can do about this
Log.w("Podax", "error in subscription xml: " + e.getMessage());
showUpdateErrorNotification(subscription, _context.getString(R.string.rss_not_valid));
}
// finish grabbing subscription values and update
subscriptionValues.put(SubscriptionProvider.COLUMN_LAST_UPDATE, new Date().getTime() / 1000);
_context.getContentResolver().update(subscriptionUri, subscriptionValues, null, null);
writeSubscriptionOPML();
} catch (Exception e) {
Log.w("Podax", "error while updating: " + e.getMessage());
} finally {
if (cursor != null)
cursor.close();
UpdateService.downloadPodcastsSilently(_context);
}
}
| public void update(long subscriptionId) {
Cursor cursor = null;
try {
if (!Helper.ensureWifi(_context))
return;
Uri subscriptionUri = ContentUris.withAppendedId(SubscriptionProvider.URI, subscriptionId);
String[] projection = new String[] {
SubscriptionProvider.COLUMN_ID,
SubscriptionProvider.COLUMN_TITLE,
SubscriptionProvider.COLUMN_URL,
SubscriptionProvider.COLUMN_ETAG,
SubscriptionProvider.COLUMN_LAST_MODIFIED,
};
ContentValues subscriptionValues = new ContentValues();
cursor = _context.getContentResolver().query(subscriptionUri, projection,
SubscriptionProvider.COLUMN_ID + " = ?",
new String[] { String.valueOf(subscriptionId) }, null);
if (!cursor.moveToNext())
return;
SubscriptionCursor subscription = new SubscriptionCursor(cursor);
showNotification(subscription);
URL url = new URL(subscription.getUrl());
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
if (subscription.getETag() != null)
connection.setRequestProperty("If-None-Match", subscription.getETag());
if (subscription.getLastModified() != null && subscription.getLastModified().getTime() > 0) {
SimpleDateFormat imsFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US);
connection.setRequestProperty("If-Modified-Since", imsFormat.format(subscription.getLastModified()));
}
int code = connection.getResponseCode();
// only valid response code is 200
// 304 (content not modified) is OK too
if (code != 200) {
return;
}
String eTag = connection.getHeaderField("ETag");
if (eTag != null) {
subscriptionValues.put(SubscriptionProvider.COLUMN_ETAG, eTag);
if (eTag.equals(subscription.getETag()))
return;
}
String encoding = connection.getContentEncoding();
if (encoding == null) {
String contentType = connection.getContentType();
if (contentType != null && contentType.indexOf(";") > -1) {
encoding = contentType.split(";")[1].trim().substring("charset=".length());
}
}
try {
XmlPullParser parser = Xml.newPullParser();
parser.setInput(connection.getInputStream(), encoding);
Feed feed = FeedParser.parseFeed(parser);
if (feed == null)
return;
subscriptionValues.putAll(feed.getContentValues());
changeKeyString(subscriptionValues, "lastBuildDate", SubscriptionProvider.COLUMN_LAST_UPDATE);
for (FeedItem item : feed.getItems()) {
if (item.getMediaURL() == null || item.getMediaURL().length() == 0)
continue;
ContentValues podcastValues = item.getContentValues();
podcastValues.put(PodcastProvider.COLUMN_SUBSCRIPTION_ID, subscriptionId);
// translate Riasel keys to old Podax keys
changeKeyString(podcastValues, "mediaURL", PodcastProvider.COLUMN_MEDIA_URL);
changeKeyString(podcastValues, "mediaSize", PodcastProvider.COLUMN_FILE_SIZE);
changeKeyString(podcastValues, "paymentURL", PodcastProvider.COLUMN_PAYMENT);
if (changeKeyLong(podcastValues, "publicationDate", PodcastProvider.COLUMN_PUB_DATE))
podcastValues.put(PodcastProvider.COLUMN_PUB_DATE, podcastValues.getAsLong(PodcastProvider.COLUMN_PUB_DATE) / 1000);
if (podcastValues.containsKey(PodcastProvider.COLUMN_MEDIA_URL)) {
try {
_context.getContentResolver().insert(PodcastProvider.URI, podcastValues);
} catch (IllegalArgumentException e) {
Log.w("Podax", "error while inserting podcast: " + e.getMessage());
}
}
}
if (feed.getThumbnail() != null)
downloadThumbnail(subscriptionId, feed.getThumbnail());
} catch (XmlPullParserException e) {
// not much we can do about this
Log.w("Podax", "error in subscription xml: " + e.getMessage());
showUpdateErrorNotification(subscription, _context.getString(R.string.rss_not_valid));
}
// finish grabbing subscription values and update
subscriptionValues.put(SubscriptionProvider.COLUMN_LAST_UPDATE, new Date().getTime() / 1000);
_context.getContentResolver().update(subscriptionUri, subscriptionValues, null, null);
writeSubscriptionOPML();
} catch (Exception e) {
Log.w("Podax", "error while updating: " + e.getMessage());
} finally {
if (cursor != null)
cursor.close();
UpdateService.downloadPodcastsSilently(_context);
}
}
|
diff --git a/core/plugins/org.eclipse.dltk.core/utils/org/eclipse/dltk/utils/PlatformFileUtils.java b/core/plugins/org.eclipse.dltk.core/utils/org/eclipse/dltk/utils/PlatformFileUtils.java
index 735c70644..bb052825e 100644
--- a/core/plugins/org.eclipse.dltk.core/utils/org/eclipse/dltk/utils/PlatformFileUtils.java
+++ b/core/plugins/org.eclipse.dltk.core/utils/org/eclipse/dltk/utils/PlatformFileUtils.java
@@ -1,55 +1,58 @@
package org.eclipse.dltk.utils;
import java.io.File;
import java.io.IOException;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.Platform;
import org.eclipse.dltk.core.DLTKCore;
import org.eclipse.osgi.service.datalocation.Location;
public class PlatformFileUtils {
/**
* Returns same file if not exist.
*/
public static File findAbsoluteOrEclipseRelativeFile(File file) {
+ if( file.getPath().length() == 0 ) {
+ return file;
+ }
String locationName = file.getPath();
if (!file.exists() && !file.isAbsolute()) {
String loc;
Location location = Platform.getInstallLocation();
if (location != null) {
try {
loc = FileLocator.resolve(location.getURL()).getPath();
// System.out.println("relavie to:" + loc);
File nfile = new File(loc + File.separator + locationName);
// System.out.println("relavie to:" + nfile.toString());
if (nfile.exists()) {
return nfile;
}
} catch (IOException e) {
if (DLTKCore.DEBUG) {
e.printStackTrace();
}
}
}
location = Platform.getInstanceLocation();
if (location != null) {
try {
loc = FileLocator.resolve(location.getURL()).getPath();
File nfile = new File(loc + File.separator + locationName);
// System.out.println("relavie to:" + nfile.toString());
if (nfile.exists()) {
return nfile;
}
} catch (IOException e) {
if (DLTKCore.DEBUG) {
e.printStackTrace();
}
}
}
}
return file;
}
}
| true | true | public static File findAbsoluteOrEclipseRelativeFile(File file) {
String locationName = file.getPath();
if (!file.exists() && !file.isAbsolute()) {
String loc;
Location location = Platform.getInstallLocation();
if (location != null) {
try {
loc = FileLocator.resolve(location.getURL()).getPath();
// System.out.println("relavie to:" + loc);
File nfile = new File(loc + File.separator + locationName);
// System.out.println("relavie to:" + nfile.toString());
if (nfile.exists()) {
return nfile;
}
} catch (IOException e) {
if (DLTKCore.DEBUG) {
e.printStackTrace();
}
}
}
location = Platform.getInstanceLocation();
if (location != null) {
try {
loc = FileLocator.resolve(location.getURL()).getPath();
File nfile = new File(loc + File.separator + locationName);
// System.out.println("relavie to:" + nfile.toString());
if (nfile.exists()) {
return nfile;
}
} catch (IOException e) {
if (DLTKCore.DEBUG) {
e.printStackTrace();
}
}
}
}
return file;
}
| public static File findAbsoluteOrEclipseRelativeFile(File file) {
if( file.getPath().length() == 0 ) {
return file;
}
String locationName = file.getPath();
if (!file.exists() && !file.isAbsolute()) {
String loc;
Location location = Platform.getInstallLocation();
if (location != null) {
try {
loc = FileLocator.resolve(location.getURL()).getPath();
// System.out.println("relavie to:" + loc);
File nfile = new File(loc + File.separator + locationName);
// System.out.println("relavie to:" + nfile.toString());
if (nfile.exists()) {
return nfile;
}
} catch (IOException e) {
if (DLTKCore.DEBUG) {
e.printStackTrace();
}
}
}
location = Platform.getInstanceLocation();
if (location != null) {
try {
loc = FileLocator.resolve(location.getURL()).getPath();
File nfile = new File(loc + File.separator + locationName);
// System.out.println("relavie to:" + nfile.toString());
if (nfile.exists()) {
return nfile;
}
} catch (IOException e) {
if (DLTKCore.DEBUG) {
e.printStackTrace();
}
}
}
}
return file;
}
|
diff --git a/src/org/eclipse/imp/pdb/facts/io/ATermReader.java b/src/org/eclipse/imp/pdb/facts/io/ATermReader.java
index f12cc8c3..21097814 100644
--- a/src/org/eclipse/imp/pdb/facts/io/ATermReader.java
+++ b/src/org/eclipse/imp/pdb/facts/io/ATermReader.java
@@ -1,708 +1,713 @@
/*******************************************************************************
* Copyright (c) INRIA-LORIA and CWI 2006-2009
* 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:
* Jurgen Vinju ([email protected]) - initial API and implementation
*******************************************************************************/
package org.eclipse.imp.pdb.facts.io;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Set;
import org.eclipse.imp.pdb.facts.IConstructor;
import org.eclipse.imp.pdb.facts.IListWriter;
import org.eclipse.imp.pdb.facts.IMapWriter;
import org.eclipse.imp.pdb.facts.ISetWriter;
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.exceptions.FactParseError;
import org.eclipse.imp.pdb.facts.exceptions.IllegalOperationException;
import org.eclipse.imp.pdb.facts.exceptions.UndeclaredAbstractDataTypeException;
import org.eclipse.imp.pdb.facts.type.Type;
import org.eclipse.imp.pdb.facts.type.TypeFactory;
import org.eclipse.imp.pdb.facts.type.TypeStore;
// TODO: add support for values of type Value, for this we need overloading resolving
public class ATermReader extends AbstractReader {
private IValueFactory vf;
private TypeFactory tf = TypeFactory.getInstance();
private TypeStore ts;
public IValue read(IValueFactory factory, TypeStore store, Type type, InputStream stream)
throws FactParseError, IOException {
this.vf = factory;
this.ts = store;
int firstToken;
do {
firstToken = stream.read();
if (firstToken == -1) {
throw new IOException("Premature EOF.");
}
} while (Character.isWhitespace((char) firstToken));
char typeByte = (char) firstToken;
if (typeByte == '!') {
SharingStream sreader = new SharingStream(stream);
sreader.initializeSharing();
sreader.readSkippingWS();
return parse(sreader, type);
} else if (typeByte == '?') {
throw new UnsupportedOperationException("nyi");
} else if (Character.isLetterOrDigit(typeByte) || typeByte == '_'
|| typeByte == '[' || typeByte == '-') {
SharingStream sreader = new SharingStream(stream);
sreader.last_char = typeByte;
return parse(sreader, type);
} else {
throw new RuntimeException("nyi");
}
}
// TODO add support for anonymous constructors (is already done for the parseNumber case)
private IValue parse(SharingStream reader, Type expected)
throws IOException {
IValue result;
int start, end;
start = reader.getPosition();
switch (reader.getLastChar()) {
case -1:
throw new FactParseError("premature EOF encountered.", start);
case '#':
return parseAbbrev(reader);
case '[':
result = parseList(reader, expected);
break;
case '<':
throw new FactParseError("Placeholders are not supported", start);
case '"':
result = parseString(reader, expected);
break;
case '(':
result = parseTuple(reader, expected);
break;
case '-':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
result = parseNumber(reader, expected);
break;
default:
result = parseAppl(reader, expected);
}
if (reader.getLastChar() == '{') {
result = parseAnnotations(reader, result);
}
end = reader.getPosition();
reader.storeNextTerm(result, end - start);
return result;
}
private IValue parseAnnotations(SharingStream reader, IValue result)
throws IOException {
if (reader.readSkippingWS() == '}') {
reader.readSkippingWS();
} else {
result = parseAnnos(reader, result);
if (reader.getLastChar() != '}') {
throw new FactParseError("'}' expected", reader.getPosition());
}
}
return result;
}
private IValue parseAppl(SharingStream reader, Type expected)
throws IOException {
int c;
IValue result;
c = reader.getLastChar();
if (Character.isLetter(c)) {
String funname = parseId(reader);
Type node;
if (expected.isAbstractDataType()) {
Set<Type> nodes = ts.lookupConstructor(expected, funname);
// TODO deal with overloading
Iterator<Type> iterator = nodes.iterator();
if (!iterator.hasNext()) {
throw new UndeclaredAbstractDataTypeException(expected);
}
node = iterator.next();
}
else {
node = expected;
}
c = reader.skipWS();
if (reader.getLastChar() == '(') {
c = reader.readSkippingWS();
if (c == -1) {
throw new FactParseError("premature EOF encountered.", reader.getPosition());
}
if (reader.getLastChar() == ')') {
result = vf.constructor(node, new IValue[0]);
} else {
IValue[] list;
if (expected.isAbstractDataType()) {
list = parseFixedSizeATermsArray(reader, node.getFieldTypes());
}
else {
list = parseATermsArray(reader, TypeFactory.getInstance().valueType());
}
if (reader.getLastChar() != ')') {
throw new FactParseError("expected ')' but got '"
+ (char) reader.getLastChar() + "'", reader.getPosition());
}
if (expected.isAbstractDataType()) {
result = node.make(vf, list);
}
else {
result = node.make(vf, funname, list);
}
}
c = reader.readSkippingWS();
} else {
- result = node.make(vf);
+ if (node.isAbstractDataType() || node.isConstructorType()) {
+ result = node.make(vf);
+ }
+ else {
+ result = tf.nodeType().make(vf, funname);
+ }
}
} else {
throw new FactParseError("illegal character: "
+ (char) reader.getLastChar(), reader.getPosition());
}
return result;
}
private IValue parseTuple(SharingStream reader, Type expected)
throws IOException {
int c;
IValue result;
c = reader.readSkippingWS();
if (c == -1) {
throw new FactParseError("premature EOF encountered.", reader.getPosition());
}
if (reader.getLastChar() == ')') {
result = expected.make(vf);
} else {
IValue[] list = parseFixedSizeATermsArray(reader, expected);
if (reader.getLastChar() != ')') {
throw new FactParseError("expected ')' but got '"
+ (char) reader.getLastChar() + "'", reader.getPosition());
}
result = expected.make(vf, list);
}
c = reader.readSkippingWS();
return result;
}
private IValue parseString(SharingStream reader, Type expected) throws IOException {
int c;
IValue result;
String str = parseStringLiteral(reader);
// note that we interpret all strings as strings, not possible function names.
// this deviates from the ATerm library.
result = expected.make(vf, str);
c = reader.readSkippingWS();
if (c == -1) {
throw new FactParseError("premature EOF encountered.", reader.getPosition());
}
return result;
}
private IValue parseList(SharingStream reader, Type expected)
throws IOException {
IValue result;
int c;
c = reader.readSkippingWS();
if (c == -1) {
throw new FactParseError("premature EOF encountered.", reader.getPosition());
}
if (c == ']') {
c = reader.readSkippingWS();
if (expected.isListType()) {
result = expected.make(vf);
} else {
throw new FactParseError("Did not expect a list, rather a "
+ expected, reader.getPosition());
}
} else {
result = parseATerms(reader, expected);
if (reader.getLastChar() != ']') {
throw new FactParseError("expected ']' but got '"
+ (char) reader.getLastChar() + "'", reader.getPosition());
}
c = reader.readSkippingWS();
}
return result;
}
private IValue parseAnnos(SharingStream reader, IValue result) throws IOException {
result = parseAnno(reader, result);
while (reader.getLastChar() == ',') {
reader.readSkippingWS();
result = parseAnno(reader, result);
}
return result;
}
private IValue parseAnno(SharingStream reader, IValue result) throws IOException {
if (reader.getLastChar() == '[') {
int c = reader.readSkippingWS();
if (c == '"') {
String key = parseStringLiteral(reader);
Type annoType = ts.getAnnotationType(result.getType(), key);
if (reader.readSkippingWS() == ',') {
reader.readSkippingWS();
IValue value = parse(reader, annoType);
if (result.getType().isConstructorType() || result.getType().isAbstractDataType()) {
result = ((IConstructor) result).setAnnotation(key, value);
}
if (reader.getLastChar() != ']') {
throw new FactParseError("expected a ] but got a " + reader.getLastChar(), reader.getPosition());
}
reader.readSkippingWS();
return result;
}
else {
throw new FactParseError("expected a comma before the value of the annotation", reader.getPosition());
}
}
else {
throw new FactParseError("expected a label for an annotation", reader.getPosition());
}
}
// no annotations
return result;
}
static private boolean isBase64(int c) {
return Character.isLetterOrDigit(c) || c == '+' || c == '/';
}
private IValue parseAbbrev(SharingStream reader) throws IOException {
IValue result;
int abbrev;
int c = reader.read();
abbrev = 0;
while (isBase64(c)) {
abbrev *= 64;
if (c >= 'A' && c <= 'Z') {
abbrev += c - 'A';
} else if (c >= 'a' && c <= 'z') {
abbrev += c - 'a' + 26;
} else if (c >= '0' && c <= '9') {
abbrev += c - '0' + 52;
} else if (c == '+') {
abbrev += 62;
} else if (c == '/') {
abbrev += 63;
} else {
throw new RuntimeException("not a base-64 digit: " + c);
}
c = reader.read();
}
result = reader.getTerm(abbrev);
return result;
}
private IValue parseNumber(SharingStream reader, Type expected) throws IOException {
StringBuilder str = new StringBuilder();
IValue result;
do {
str.append((char) reader.getLastChar());
} while (Character.isDigit(reader.read()));
if (reader.getLastChar() != '.' && reader.getLastChar() != 'e'
&& reader.getLastChar() != 'E' && reader.getLastChar() != 'l'
&& reader.getLastChar() != 'L') {
int val;
try {
val = Integer.parseInt(str.toString());
} catch (NumberFormatException e) {
throw new FactParseError("malformed int:" + str, reader.getPosition());
}
result = expected.make(vf,ts, val);
} else if (reader.getLastChar() == 'l' || reader.getLastChar() == 'L') {
reader.read();
throw new FactParseError("No support for longs", reader.getPosition());
} else {
if (reader.getLastChar() == '.') {
str.append('.');
reader.read();
if (!Character.isDigit(reader.getLastChar()))
throw new FactParseError("digit expected", reader.getPosition());
do {
str.append((char) reader.getLastChar());
} while (Character.isDigit(reader.read()));
}
if (reader.getLastChar() == 'e' || reader.getLastChar() == 'E') {
str.append((char) reader.getLastChar());
reader.read();
if (reader.getLastChar() == '-' || reader.getLastChar() == '+') {
str.append((char) reader.getLastChar());
reader.read();
}
if (!Character.isDigit(reader.getLastChar()))
throw new FactParseError("digit expected!", reader.getPosition());
do {
str.append((char) reader.getLastChar());
} while (Character.isDigit(reader.read()));
}
double val;
try {
val = Double.valueOf(str.toString()).doubleValue();
result = expected.make(vf,ts, val);
} catch (NumberFormatException e) {
throw new FactParseError("malformed real", reader.getPosition(), e);
}
}
reader.skipWS();
return result;
}
private String parseId(SharingStream reader) throws IOException {
int c = reader.getLastChar();
StringBuilder buf = new StringBuilder(32);
do {
buf.append((char) c);
c = reader.read();
} while (Character.isLetterOrDigit(c) || c == '_' || c == '-'
|| c == '+' || c == '*' || c == '$' || c == '.');
// slight deviation here, allowing . inside of identifiers
return buf.toString();
}
private String parseStringLiteral(SharingStream reader) throws IOException {
boolean escaped;
StringBuilder str = new StringBuilder();
do {
escaped = false;
if (reader.read() == '\\') {
reader.read();
escaped = true;
}
int lastChar = reader.getLastChar();
if(lastChar == -1) throw new IOException("Premature EOF.");
if (escaped) {
switch (lastChar) {
case 'n':
str.append('\n');
break;
case 't':
str.append('\t');
break;
case 'b':
str.append('\b');
break;
case 'r':
str.append('\r');
break;
case 'f':
str.append('\f');
break;
case '\\':
str.append('\\');
break;
case '\'':
str.append('\'');
break;
case '\"':
str.append('\"');
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
str.append(reader.readOct());
break;
default:
str.append('\\').append((char) lastChar);
}
} else if (lastChar != '\"'){
str.append((char) lastChar);
}
} while (escaped || reader.getLastChar() != '"');
return str.toString();
}
private IValue parseATerms(SharingStream reader, Type expected)
throws IOException {
Type base = expected;
Type elementType = getElementType(expected);
IValue[] terms = parseATermsArray(reader, elementType);
if (base.isListType()) {
IListWriter w = expected.writer(vf);
for (int i = terms.length - 1; i >= 0; i--) {
w.insert(terms[i]);
}
return w.done();
} else if (base.isSetType()) {
ISetWriter w = expected.writer(vf);
w.insert(terms);
return w.done();
} else if (base.isMapType()) {
IMapWriter w = expected.writer(vf);
for (IValue elem : terms) {
ITuple tuple = (ITuple) elem;
w.put(tuple.get(0), tuple.get(1));
}
return w.done();
} else if (base.isRelationType()) {
ISetWriter w = expected.writer(vf);
w.insert(terms);
return w.done();
}
throw new FactParseError("Unexpected type " + expected, reader.getPosition());
}
private Type getElementType(Type expected) {
Type base = expected;
if (base.isListType()) {
return base.getElementType();
} else if (base.isSetType()) {
return base.getElementType();
} else if (base.isMapType()) {
return tf.tupleType(base.getKeyType(), base.getValueType());
} else if (base.isRelationType()) {
return base.getFieldTypes();
} else {
throw new IllegalOperationException("getElementType", expected);
}
}
private IValue[] parseATermsArray(SharingStream reader,
Type elementType) throws IOException {
List<IValue> list = new ArrayList<IValue>();
IValue term = parse(reader, elementType);
list.add(term);
while (reader.getLastChar() == ',') {
reader.readSkippingWS();
term = parse(reader, elementType);
list.add(term);
}
IValue[] array = new IValue[list.size()];
ListIterator<IValue> iter = list.listIterator();
int index = 0;
while (iter.hasNext()) {
array[index++] = iter.next();
}
return array;
}
private IValue[] parseFixedSizeATermsArray(SharingStream reader,
Type elementTypes) throws IOException {
List<IValue> list = new ArrayList<IValue>();
int i = 0;
Type elementType = elementTypes.getFieldType(i++);
IValue term = parse(reader, elementType);
list.add(term);
while (reader.getLastChar() == ',') {
elementType = elementTypes.getFieldType(i++);
reader.readSkippingWS();
term = parse(reader, elementType);
list.add(term);
}
IValue[] array = new IValue[list.size()];
ListIterator<IValue> iter = list.listIterator();
int index = 0;
while (iter.hasNext()) {
array[index++] = iter.next();
}
return array;
}
class SharingStream {
private static final int INITIAL_TABLE_SIZE = 2048;
private static final int TABLE_INCREMENT = 4096;
private static final int INITIAL_BUFFER_SIZE = 1024;
private InputStream reader;
int last_char;
private int pos;
private int nr_terms;
private IValue[] table;
private byte[] buffer;
private int limit;
private int bufferPos;
public SharingStream(InputStream reader) {
this(reader, INITIAL_BUFFER_SIZE);
}
public SharingStream(InputStream stream, int bufferSize) {
this.reader = stream;
last_char = -1;
pos = 0;
if (bufferSize < INITIAL_BUFFER_SIZE)
buffer = new byte[bufferSize];
else
buffer = new byte[INITIAL_BUFFER_SIZE];
limit = -1;
bufferPos = -1;
}
public void initializeSharing() {
table = new IValue[INITIAL_TABLE_SIZE];
nr_terms = 0;
}
public void storeNextTerm(IValue t, int size) {
if (table == null) {
return;
}
if (nr_terms == table.length) {
IValue[] new_table = new IValue[table.length + TABLE_INCREMENT];
System.arraycopy(table, 0, new_table, 0, table.length);
table = new_table;
}
table[nr_terms++] = t;
}
public IValue getTerm(int index) {
if (index < 0 || index >= nr_terms) {
throw new RuntimeException("illegal index");
}
return table[index];
}
public int read() throws IOException {
if (bufferPos == limit) {
limit = reader.read(buffer);
bufferPos = 0;
}
if (limit == -1) {
last_char = -1;
} else {
last_char = buffer[bufferPos++];
pos++;
}
return last_char;
}
public int readSkippingWS() throws IOException {
do {
last_char = read();
} while (Character.isWhitespace(last_char));
return last_char;
}
public int skipWS() throws IOException {
while (Character.isWhitespace(last_char)) {
last_char = read();
}
return last_char;
}
public int readOct() throws IOException {
int val = Character.digit(last_char, 8);
val += Character.digit(read(), 8);
if (val < 0) {
throw new FactParseError("octal must have 3 octdigits.", getPosition());
}
val += Character.digit(read(), 8);
if (val < 0) {
throw new FactParseError("octal must have 3 octdigits", getPosition());
}
return val;
}
public int getLastChar() {
return last_char;
}
public int getPosition() {
return pos;
}
}
}
| true | true | private IValue parseAppl(SharingStream reader, Type expected)
throws IOException {
int c;
IValue result;
c = reader.getLastChar();
if (Character.isLetter(c)) {
String funname = parseId(reader);
Type node;
if (expected.isAbstractDataType()) {
Set<Type> nodes = ts.lookupConstructor(expected, funname);
// TODO deal with overloading
Iterator<Type> iterator = nodes.iterator();
if (!iterator.hasNext()) {
throw new UndeclaredAbstractDataTypeException(expected);
}
node = iterator.next();
}
else {
node = expected;
}
c = reader.skipWS();
if (reader.getLastChar() == '(') {
c = reader.readSkippingWS();
if (c == -1) {
throw new FactParseError("premature EOF encountered.", reader.getPosition());
}
if (reader.getLastChar() == ')') {
result = vf.constructor(node, new IValue[0]);
} else {
IValue[] list;
if (expected.isAbstractDataType()) {
list = parseFixedSizeATermsArray(reader, node.getFieldTypes());
}
else {
list = parseATermsArray(reader, TypeFactory.getInstance().valueType());
}
if (reader.getLastChar() != ')') {
throw new FactParseError("expected ')' but got '"
+ (char) reader.getLastChar() + "'", reader.getPosition());
}
if (expected.isAbstractDataType()) {
result = node.make(vf, list);
}
else {
result = node.make(vf, funname, list);
}
}
c = reader.readSkippingWS();
} else {
result = node.make(vf);
}
} else {
throw new FactParseError("illegal character: "
+ (char) reader.getLastChar(), reader.getPosition());
}
return result;
}
| private IValue parseAppl(SharingStream reader, Type expected)
throws IOException {
int c;
IValue result;
c = reader.getLastChar();
if (Character.isLetter(c)) {
String funname = parseId(reader);
Type node;
if (expected.isAbstractDataType()) {
Set<Type> nodes = ts.lookupConstructor(expected, funname);
// TODO deal with overloading
Iterator<Type> iterator = nodes.iterator();
if (!iterator.hasNext()) {
throw new UndeclaredAbstractDataTypeException(expected);
}
node = iterator.next();
}
else {
node = expected;
}
c = reader.skipWS();
if (reader.getLastChar() == '(') {
c = reader.readSkippingWS();
if (c == -1) {
throw new FactParseError("premature EOF encountered.", reader.getPosition());
}
if (reader.getLastChar() == ')') {
result = vf.constructor(node, new IValue[0]);
} else {
IValue[] list;
if (expected.isAbstractDataType()) {
list = parseFixedSizeATermsArray(reader, node.getFieldTypes());
}
else {
list = parseATermsArray(reader, TypeFactory.getInstance().valueType());
}
if (reader.getLastChar() != ')') {
throw new FactParseError("expected ')' but got '"
+ (char) reader.getLastChar() + "'", reader.getPosition());
}
if (expected.isAbstractDataType()) {
result = node.make(vf, list);
}
else {
result = node.make(vf, funname, list);
}
}
c = reader.readSkippingWS();
} else {
if (node.isAbstractDataType() || node.isConstructorType()) {
result = node.make(vf);
}
else {
result = tf.nodeType().make(vf, funname);
}
}
} else {
throw new FactParseError("illegal character: "
+ (char) reader.getLastChar(), reader.getPosition());
}
return result;
}
|
diff --git a/tool/src/java/org/sakaiproject/profile2/tool/pages/MyPrivacy.java b/tool/src/java/org/sakaiproject/profile2/tool/pages/MyPrivacy.java
index a9f11e66..83a74f72 100644
--- a/tool/src/java/org/sakaiproject/profile2/tool/pages/MyPrivacy.java
+++ b/tool/src/java/org/sakaiproject/profile2/tool/pages/MyPrivacy.java
@@ -1,430 +1,430 @@
/**
* Copyright (c) 2008-2010 The Sakai Foundation
*
* Licensed under the Educational Community 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.osedu.org/licenses/ECL-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.sakaiproject.profile2.tool.pages;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import org.apache.log4j.Logger;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior;
import org.apache.wicket.extensions.ajax.markup.html.IndicatingAjaxButton;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.CheckBox;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.model.StringResourceModel;
import org.sakaiproject.profile2.exception.ProfilePrivacyNotDefinedException;
import org.sakaiproject.profile2.model.ProfilePrivacy;
import org.sakaiproject.profile2.tool.components.HashMapChoiceRenderer;
import org.sakaiproject.profile2.tool.components.IconWithClueTip;
import org.sakaiproject.profile2.util.ProfileConstants;
public class MyPrivacy extends BasePage {
private static final Logger log = Logger.getLogger(MyPrivacy.class);
private transient ProfilePrivacy profilePrivacy;
public MyPrivacy() {
log.debug("MyPrivacy()");
disableLink(myPrivacyLink);
//get current user
final String userUuid = sakaiProxy.getCurrentUserId();
//get the privacy record for this user from the database, or a default if none exists
profilePrivacy = privacyLogic.getPrivacyRecordForUser(userUuid, false);
//if null, throw exception
if(profilePrivacy == null) {
- throw new ProfilePrivacyNotDefinedException("Couldn't create default privacy record for " + userUuid);
+ throw new ProfilePrivacyNotDefinedException("Couldn't retrieve privacy record for " + userUuid);
}
Label heading = new Label("heading", new ResourceModel("heading.privacy"));
add(heading);
Label infoLocked = new Label("infoLocked");
infoLocked.setOutputMarkupPlaceholderTag(true);
infoLocked.setVisible(false);
add(infoLocked);
//feedback for form submit action
final Label formFeedback = new Label("formFeedback");
formFeedback.setOutputMarkupPlaceholderTag(true);
final String formFeedbackId = formFeedback.getMarkupId();
add(formFeedback);
//create model
CompoundPropertyModel<ProfilePrivacy> privacyModel = new CompoundPropertyModel<ProfilePrivacy>(profilePrivacy);
//setup form
Form<ProfilePrivacy> form = new Form<ProfilePrivacy>("form", privacyModel);
form.setOutputMarkupId(true);
//setup LinkedHashMap of privacy options for strict things
final LinkedHashMap<String, String> privacySettingsStrict = new LinkedHashMap<String, String>();
privacySettingsStrict.put("0", new StringResourceModel("privacy.option.everyone", this,null).getString());
privacySettingsStrict.put("1", new StringResourceModel("privacy.option.onlyfriends", this,null).getString());
privacySettingsStrict.put("2", new StringResourceModel("privacy.option.onlyme", this,null).getString());
//model that wraps our options
IModel dropDownModelStrict = new Model() {
public ArrayList<String> getObject() {
return new ArrayList(privacySettingsStrict.keySet());
}
};
//setup LinkedHashMap of privacy options for more relaxed things
final LinkedHashMap<String, String> privacySettingsRelaxed = new LinkedHashMap<String, String>();
privacySettingsRelaxed.put("0", new StringResourceModel("privacy.option.everyone", this,null).getString());
privacySettingsRelaxed.put("1", new StringResourceModel("privacy.option.onlyfriends", this,null).getString());
//model that wraps our options
IModel dropDownModelRelaxed = new Model() {
public ArrayList<String> getObject() {
return new ArrayList(privacySettingsRelaxed.keySet());
}
};
//when using DDC with a compoundPropertyModel we use this constructor: DDC<T>(String,IModel<List<T>>,IChoiceRenderer<T>)
//and the ID of the DDC field maps to the field in the CompoundPropertyModel
//the AjaxFormComponentUpdatingBehavior is to allow the DDC and checkboxes to fadeaway any error/success message
//that might be visible since the form has changed and it needs to be submitted again for it to take effect
//profile image privacy
WebMarkupContainer profileImageContainer = new WebMarkupContainer("profileImageContainer");
profileImageContainer.add(new Label("profileImageLabel", new ResourceModel("privacy.profileimage")));
DropDownChoice profileImageChoice = new DropDownChoice("profileImage", dropDownModelRelaxed, new HashMapChoiceRenderer(privacySettingsRelaxed));
profileImageChoice.setOutputMarkupId(true);
profileImageContainer.add(profileImageChoice);
//tooltip
profileImageContainer.add(new IconWithClueTip("profileImageToolTip", ProfileConstants.INFO_IMAGE, new ResourceModel("text.privacy.profileimage.tooltip")));
form.add(profileImageContainer);
//updater
profileImageChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
//basicInfo privacy
WebMarkupContainer basicInfoContainer = new WebMarkupContainer("basicInfoContainer");
basicInfoContainer.add(new Label("basicInfoLabel", new ResourceModel("privacy.basicinfo")));
DropDownChoice basicInfoChoice = new DropDownChoice("basicInfo", dropDownModelStrict, new HashMapChoiceRenderer(privacySettingsStrict));
basicInfoChoice.setOutputMarkupId(true);
basicInfoContainer.add(basicInfoChoice);
//tooltip
basicInfoContainer.add(new IconWithClueTip("basicInfoToolTip", ProfileConstants.INFO_IMAGE, new ResourceModel("text.privacy.basicinfo.tooltip")));
form.add(basicInfoContainer);
//updater
basicInfoChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
//contactInfo privacy
WebMarkupContainer contactInfoContainer = new WebMarkupContainer("contactInfoContainer");
contactInfoContainer.add(new Label("contactInfoLabel", new ResourceModel("privacy.contactinfo")));
DropDownChoice contactInfoChoice = new DropDownChoice("contactInfo", dropDownModelStrict, new HashMapChoiceRenderer(privacySettingsStrict));
contactInfoChoice.setOutputMarkupId(true);
contactInfoContainer.add(contactInfoChoice);
//tooltip
contactInfoContainer.add(new IconWithClueTip("contactInfoToolTip", ProfileConstants.INFO_IMAGE, new ResourceModel("text.privacy.contactinfo.tooltip")));
form.add(contactInfoContainer);
//updater
contactInfoChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
//staffInfo privacy
WebMarkupContainer staffInfoContainer = new WebMarkupContainer("staffInfoContainer");
staffInfoContainer.add(new Label("staffInfoLabel", new ResourceModel("privacy.staffinfo")));
DropDownChoice staffInfoChoice = new DropDownChoice("staffInfo", dropDownModelStrict, new HashMapChoiceRenderer(privacySettingsStrict));
staffInfoChoice.setOutputMarkupId(true);
staffInfoContainer.add(staffInfoChoice);
//tooltip
staffInfoContainer.add(new IconWithClueTip("staffInfoToolTip", ProfileConstants.INFO_IMAGE, new ResourceModel("text.privacy.staff.tooltip")));
form.add(staffInfoContainer);
//updater
staffInfoChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
//studentInfo privacy
WebMarkupContainer studentInfoContainer = new WebMarkupContainer("studentInfoContainer");
studentInfoContainer.add(new Label("studentInfoLabel", new ResourceModel("privacy.studentinfo")));
DropDownChoice studentInfoChoice = new DropDownChoice("studentInfo", dropDownModelStrict, new HashMapChoiceRenderer(privacySettingsStrict));
studentInfoChoice.setOutputMarkupId(true);
studentInfoContainer.add(studentInfoChoice);
//tooltip
studentInfoContainer.add(new IconWithClueTip("studentInfoToolTip", ProfileConstants.INFO_IMAGE, new ResourceModel("text.privacy.student.tooltip")));
form.add(studentInfoContainer);
//updater
studentInfoChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
//businesInfo privacy
WebMarkupContainer businessInfoContainer = new WebMarkupContainer("businessInfoContainer");
businessInfoContainer.add(new Label("businessInfoLabel", new ResourceModel("privacy.businessinfo")));
DropDownChoice businessInfoChoice = new DropDownChoice("businessInfo", dropDownModelStrict, new HashMapChoiceRenderer(privacySettingsStrict));
businessInfoChoice.setOutputMarkupId(true);
businessInfoContainer.add(businessInfoChoice);
//tooltip
businessInfoContainer.add(new IconWithClueTip("businessInfoToolTip", ProfileConstants.INFO_IMAGE, new ResourceModel("text.privacy.businessinfo.tooltip")));
form.add(businessInfoContainer);
//updater
businessInfoChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
businessInfoContainer.setVisible(sakaiProxy.isBusinessProfileEnabled());
//socialNetworkingInfo privacy
WebMarkupContainer socialNetworkingInfoContainer = new WebMarkupContainer("socialNetworkingInfoContainer");
socialNetworkingInfoContainer.add(new Label("socialNetworkingInfoLabel", new ResourceModel("privacy.socialinfo")));
DropDownChoice socialNetworkingInfoChoice = new DropDownChoice("socialNetworkingInfo", dropDownModelStrict, new HashMapChoiceRenderer(privacySettingsStrict));
socialNetworkingInfoChoice.setOutputMarkupId(true);
socialNetworkingInfoContainer.add(socialNetworkingInfoChoice);
//tooltip
socialNetworkingInfoContainer.add(new IconWithClueTip("socialNetworkingInfoToolTip", ProfileConstants.INFO_IMAGE, new ResourceModel("text.privacy.socialinfo.tooltip")));
form.add(socialNetworkingInfoContainer);
//updater
socialNetworkingInfoChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
//personalInfo privacy
WebMarkupContainer personalInfoContainer = new WebMarkupContainer("personalInfoContainer");
personalInfoContainer.add(new Label("personalInfoLabel", new ResourceModel("privacy.personalinfo")));
DropDownChoice personalInfoChoice = new DropDownChoice("personalInfo", dropDownModelStrict, new HashMapChoiceRenderer(privacySettingsStrict));
personalInfoChoice.setOutputMarkupId(true);
personalInfoContainer.add(personalInfoChoice);
//tooltip
personalInfoContainer.add(new IconWithClueTip("personalInfoToolTip", ProfileConstants.INFO_IMAGE, new ResourceModel("text.privacy.personalinfo.tooltip")));
form.add(personalInfoContainer);
//updater
personalInfoChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
//birthYear privacy
WebMarkupContainer birthYearContainer = new WebMarkupContainer("birthYearContainer");
birthYearContainer.add(new Label("birthYearLabel", new ResourceModel("privacy.birthyear")));
CheckBox birthYearCheckbox = new CheckBox("birthYear", new PropertyModel(privacyModel, "showBirthYear"));
birthYearCheckbox.setOutputMarkupId(true);
birthYearContainer.add(birthYearCheckbox);
//tooltip
birthYearContainer.add(new IconWithClueTip("birthYearToolTip", ProfileConstants.INFO_IMAGE, new ResourceModel("text.privacy.birthyear.tooltip")));
form.add(birthYearContainer);
//updater
birthYearCheckbox.add(new AjaxFormComponentUpdatingBehavior("onclick") {
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
//myFriends privacy
WebMarkupContainer myFriendsContainer = new WebMarkupContainer("myFriendsContainer");
myFriendsContainer.add(new Label("myFriendsLabel", new ResourceModel("privacy.myfriends")));
DropDownChoice myFriendsChoice = new DropDownChoice("myFriends", dropDownModelStrict, new HashMapChoiceRenderer(privacySettingsStrict));
myFriendsChoice.setOutputMarkupId(true);
myFriendsContainer.add(myFriendsChoice);
//tooltip
myFriendsContainer.add(new IconWithClueTip("myFriendsToolTip", ProfileConstants.INFO_IMAGE, new ResourceModel("text.privacy.myfriends.tooltip")));
form.add(myFriendsContainer);
//updater
myFriendsChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
//myStatus privacy
WebMarkupContainer myStatusContainer = new WebMarkupContainer("myStatusContainer");
myStatusContainer.add(new Label("myStatusLabel", new ResourceModel("privacy.mystatus")));
DropDownChoice myStatusChoice = new DropDownChoice("myStatus", dropDownModelRelaxed, new HashMapChoiceRenderer(privacySettingsRelaxed));
myStatusChoice.setOutputMarkupId(true);
myStatusContainer.add(myStatusChoice);
//tooltip
myStatusContainer.add(new IconWithClueTip("myStatusToolTip", ProfileConstants.INFO_IMAGE, new ResourceModel("text.privacy.mystatus.tooltip")));
form.add(myStatusContainer);
//updater
myStatusChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
// gallery privacy
WebMarkupContainer myPicturesContainer = new WebMarkupContainer("myPicturesContainer");
myPicturesContainer.add(new Label("myPicturesLabel", new ResourceModel("privacy.mypictures")));
DropDownChoice myPicturesChoice = new DropDownChoice("myPictures", dropDownModelRelaxed, new HashMapChoiceRenderer(privacySettingsRelaxed));
myPicturesChoice.setOutputMarkupId(true);
myPicturesContainer.add(myPicturesChoice);
myPicturesContainer.add(new IconWithClueTip("myPicturesToolTip", ProfileConstants.INFO_IMAGE, new ResourceModel("text.privacy.mypictures.tooltip")));
form.add(myPicturesContainer);
myPicturesChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
myPicturesContainer.setVisible(sakaiProxy.isProfileGalleryEnabledGlobally());
// messages privacy
WebMarkupContainer messagesContainer = new WebMarkupContainer("messagesContainer");
messagesContainer.add(new Label("messagesLabel", new ResourceModel("privacy.messages")));
DropDownChoice messagesChoice = new DropDownChoice("messages", dropDownModelRelaxed, new HashMapChoiceRenderer(privacySettingsRelaxed));
messagesChoice.setOutputMarkupId(true);
messagesContainer.add(messagesChoice);
messagesContainer.add(new IconWithClueTip("messagesToolTip", ProfileConstants.INFO_IMAGE, new ResourceModel("text.privacy.messages.tooltip")));
form.add(messagesContainer);
messagesChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
// kudos privacy
WebMarkupContainer myKudosContainer = new WebMarkupContainer("myKudosContainer");
myKudosContainer.add(new Label("myKudosLabel", new ResourceModel("privacy.mykudos")));
DropDownChoice kudosChoice = new DropDownChoice("myKudos", dropDownModelRelaxed, new HashMapChoiceRenderer(privacySettingsRelaxed));
kudosChoice.setOutputMarkupId(true);
myKudosContainer.add(kudosChoice);
myKudosContainer.add(new IconWithClueTip("myKudosToolTip", ProfileConstants.INFO_IMAGE, new ResourceModel("text.privacy.mykudos.tooltip")));
form.add(myKudosContainer);
kudosChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
//submit button
IndicatingAjaxButton submitButton = new IndicatingAjaxButton("submit", form) {
protected void onSubmit(AjaxRequestTarget target, Form form) {
//save() form, show feedback. perhaps redirect back to main page after a short while?
if(save(form)){
formFeedback.setDefaultModel(new ResourceModel("success.privacy.save.ok"));
formFeedback.add(new AttributeModifier("class", true, new Model<String>("success")));
//post update event
sakaiProxy.postEvent(ProfileConstants.EVENT_PRIVACY_UPDATE, "/profile/"+userUuid, true);
} else {
formFeedback.setDefaultModel(new ResourceModel("error.privacy.save.failed"));
formFeedback.add(new AttributeModifier("class", true, new Model<String>("alertMessage")));
}
target.addComponent(formFeedback);
}
};
submitButton.setModel(new ResourceModel("button.save.settings"));
submitButton.setOutputMarkupId(true);
form.add(submitButton);
//cancel button
/*
AjaxFallbackButton cancelButton = new AjaxFallbackButton("cancel", new ResourceModel("button.cancel"), form) {
protected void onSubmit(AjaxRequestTarget target, Form form) {
setResponsePage(new MyProfile());
}
};
cancelButton.setDefaultFormProcessing(false);
form.add(cancelButton);
*/
if(!sakaiProxy.isPrivacyChangeAllowedGlobally()){
infoLocked.setDefaultModel(new ResourceModel("text.privacy.cannot.modify"));
infoLocked.setVisible(true);
profileImageChoice.setEnabled(false);
basicInfoChoice.setEnabled(false);
contactInfoChoice.setEnabled(false);
studentInfoChoice.setEnabled(false);
businessInfoChoice.setEnabled(false);
personalInfoChoice.setEnabled(false);
birthYearCheckbox.setEnabled(false);
myFriendsChoice.setEnabled(false);
myStatusChoice.setEnabled(false);
myPicturesChoice.setEnabled(false);
messagesChoice.setEnabled(false);
submitButton.setEnabled(false);
submitButton.setVisible(false);
form.setEnabled(false);
}
add(form);
}
//called when the form is to be saved
private boolean save(Form<ProfilePrivacy> form) {
//get the backing model - its elems have been updated with the form params
ProfilePrivacy profilePrivacy = (ProfilePrivacy) form.getModelObject();
if(privacyLogic.savePrivacyRecord(profilePrivacy)) {
log.info("Saved ProfilePrivacy for: " + profilePrivacy.getUserUuid());
return true;
} else {
log.info("Couldn't save ProfilePrivacy for: " + profilePrivacy.getUserUuid());
return false;
}
}
}
| true | true | public MyPrivacy() {
log.debug("MyPrivacy()");
disableLink(myPrivacyLink);
//get current user
final String userUuid = sakaiProxy.getCurrentUserId();
//get the privacy record for this user from the database, or a default if none exists
profilePrivacy = privacyLogic.getPrivacyRecordForUser(userUuid, false);
//if null, throw exception
if(profilePrivacy == null) {
throw new ProfilePrivacyNotDefinedException("Couldn't create default privacy record for " + userUuid);
}
Label heading = new Label("heading", new ResourceModel("heading.privacy"));
add(heading);
Label infoLocked = new Label("infoLocked");
infoLocked.setOutputMarkupPlaceholderTag(true);
infoLocked.setVisible(false);
add(infoLocked);
//feedback for form submit action
final Label formFeedback = new Label("formFeedback");
formFeedback.setOutputMarkupPlaceholderTag(true);
final String formFeedbackId = formFeedback.getMarkupId();
add(formFeedback);
//create model
CompoundPropertyModel<ProfilePrivacy> privacyModel = new CompoundPropertyModel<ProfilePrivacy>(profilePrivacy);
//setup form
Form<ProfilePrivacy> form = new Form<ProfilePrivacy>("form", privacyModel);
form.setOutputMarkupId(true);
//setup LinkedHashMap of privacy options for strict things
final LinkedHashMap<String, String> privacySettingsStrict = new LinkedHashMap<String, String>();
privacySettingsStrict.put("0", new StringResourceModel("privacy.option.everyone", this,null).getString());
privacySettingsStrict.put("1", new StringResourceModel("privacy.option.onlyfriends", this,null).getString());
privacySettingsStrict.put("2", new StringResourceModel("privacy.option.onlyme", this,null).getString());
//model that wraps our options
IModel dropDownModelStrict = new Model() {
public ArrayList<String> getObject() {
return new ArrayList(privacySettingsStrict.keySet());
}
};
//setup LinkedHashMap of privacy options for more relaxed things
final LinkedHashMap<String, String> privacySettingsRelaxed = new LinkedHashMap<String, String>();
privacySettingsRelaxed.put("0", new StringResourceModel("privacy.option.everyone", this,null).getString());
privacySettingsRelaxed.put("1", new StringResourceModel("privacy.option.onlyfriends", this,null).getString());
//model that wraps our options
IModel dropDownModelRelaxed = new Model() {
public ArrayList<String> getObject() {
return new ArrayList(privacySettingsRelaxed.keySet());
}
};
//when using DDC with a compoundPropertyModel we use this constructor: DDC<T>(String,IModel<List<T>>,IChoiceRenderer<T>)
//and the ID of the DDC field maps to the field in the CompoundPropertyModel
//the AjaxFormComponentUpdatingBehavior is to allow the DDC and checkboxes to fadeaway any error/success message
//that might be visible since the form has changed and it needs to be submitted again for it to take effect
//profile image privacy
WebMarkupContainer profileImageContainer = new WebMarkupContainer("profileImageContainer");
profileImageContainer.add(new Label("profileImageLabel", new ResourceModel("privacy.profileimage")));
DropDownChoice profileImageChoice = new DropDownChoice("profileImage", dropDownModelRelaxed, new HashMapChoiceRenderer(privacySettingsRelaxed));
profileImageChoice.setOutputMarkupId(true);
profileImageContainer.add(profileImageChoice);
//tooltip
profileImageContainer.add(new IconWithClueTip("profileImageToolTip", ProfileConstants.INFO_IMAGE, new ResourceModel("text.privacy.profileimage.tooltip")));
form.add(profileImageContainer);
//updater
profileImageChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
//basicInfo privacy
WebMarkupContainer basicInfoContainer = new WebMarkupContainer("basicInfoContainer");
basicInfoContainer.add(new Label("basicInfoLabel", new ResourceModel("privacy.basicinfo")));
DropDownChoice basicInfoChoice = new DropDownChoice("basicInfo", dropDownModelStrict, new HashMapChoiceRenderer(privacySettingsStrict));
basicInfoChoice.setOutputMarkupId(true);
basicInfoContainer.add(basicInfoChoice);
//tooltip
basicInfoContainer.add(new IconWithClueTip("basicInfoToolTip", ProfileConstants.INFO_IMAGE, new ResourceModel("text.privacy.basicinfo.tooltip")));
form.add(basicInfoContainer);
//updater
basicInfoChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
//contactInfo privacy
WebMarkupContainer contactInfoContainer = new WebMarkupContainer("contactInfoContainer");
contactInfoContainer.add(new Label("contactInfoLabel", new ResourceModel("privacy.contactinfo")));
DropDownChoice contactInfoChoice = new DropDownChoice("contactInfo", dropDownModelStrict, new HashMapChoiceRenderer(privacySettingsStrict));
contactInfoChoice.setOutputMarkupId(true);
contactInfoContainer.add(contactInfoChoice);
//tooltip
contactInfoContainer.add(new IconWithClueTip("contactInfoToolTip", ProfileConstants.INFO_IMAGE, new ResourceModel("text.privacy.contactinfo.tooltip")));
form.add(contactInfoContainer);
//updater
contactInfoChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
//staffInfo privacy
WebMarkupContainer staffInfoContainer = new WebMarkupContainer("staffInfoContainer");
staffInfoContainer.add(new Label("staffInfoLabel", new ResourceModel("privacy.staffinfo")));
DropDownChoice staffInfoChoice = new DropDownChoice("staffInfo", dropDownModelStrict, new HashMapChoiceRenderer(privacySettingsStrict));
staffInfoChoice.setOutputMarkupId(true);
staffInfoContainer.add(staffInfoChoice);
//tooltip
staffInfoContainer.add(new IconWithClueTip("staffInfoToolTip", ProfileConstants.INFO_IMAGE, new ResourceModel("text.privacy.staff.tooltip")));
form.add(staffInfoContainer);
//updater
staffInfoChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
//studentInfo privacy
WebMarkupContainer studentInfoContainer = new WebMarkupContainer("studentInfoContainer");
studentInfoContainer.add(new Label("studentInfoLabel", new ResourceModel("privacy.studentinfo")));
DropDownChoice studentInfoChoice = new DropDownChoice("studentInfo", dropDownModelStrict, new HashMapChoiceRenderer(privacySettingsStrict));
studentInfoChoice.setOutputMarkupId(true);
studentInfoContainer.add(studentInfoChoice);
//tooltip
studentInfoContainer.add(new IconWithClueTip("studentInfoToolTip", ProfileConstants.INFO_IMAGE, new ResourceModel("text.privacy.student.tooltip")));
form.add(studentInfoContainer);
//updater
studentInfoChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
//businesInfo privacy
WebMarkupContainer businessInfoContainer = new WebMarkupContainer("businessInfoContainer");
businessInfoContainer.add(new Label("businessInfoLabel", new ResourceModel("privacy.businessinfo")));
DropDownChoice businessInfoChoice = new DropDownChoice("businessInfo", dropDownModelStrict, new HashMapChoiceRenderer(privacySettingsStrict));
businessInfoChoice.setOutputMarkupId(true);
businessInfoContainer.add(businessInfoChoice);
//tooltip
businessInfoContainer.add(new IconWithClueTip("businessInfoToolTip", ProfileConstants.INFO_IMAGE, new ResourceModel("text.privacy.businessinfo.tooltip")));
form.add(businessInfoContainer);
//updater
businessInfoChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
businessInfoContainer.setVisible(sakaiProxy.isBusinessProfileEnabled());
//socialNetworkingInfo privacy
WebMarkupContainer socialNetworkingInfoContainer = new WebMarkupContainer("socialNetworkingInfoContainer");
socialNetworkingInfoContainer.add(new Label("socialNetworkingInfoLabel", new ResourceModel("privacy.socialinfo")));
DropDownChoice socialNetworkingInfoChoice = new DropDownChoice("socialNetworkingInfo", dropDownModelStrict, new HashMapChoiceRenderer(privacySettingsStrict));
socialNetworkingInfoChoice.setOutputMarkupId(true);
socialNetworkingInfoContainer.add(socialNetworkingInfoChoice);
//tooltip
socialNetworkingInfoContainer.add(new IconWithClueTip("socialNetworkingInfoToolTip", ProfileConstants.INFO_IMAGE, new ResourceModel("text.privacy.socialinfo.tooltip")));
form.add(socialNetworkingInfoContainer);
//updater
socialNetworkingInfoChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
//personalInfo privacy
WebMarkupContainer personalInfoContainer = new WebMarkupContainer("personalInfoContainer");
personalInfoContainer.add(new Label("personalInfoLabel", new ResourceModel("privacy.personalinfo")));
DropDownChoice personalInfoChoice = new DropDownChoice("personalInfo", dropDownModelStrict, new HashMapChoiceRenderer(privacySettingsStrict));
personalInfoChoice.setOutputMarkupId(true);
personalInfoContainer.add(personalInfoChoice);
//tooltip
personalInfoContainer.add(new IconWithClueTip("personalInfoToolTip", ProfileConstants.INFO_IMAGE, new ResourceModel("text.privacy.personalinfo.tooltip")));
form.add(personalInfoContainer);
//updater
personalInfoChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
//birthYear privacy
WebMarkupContainer birthYearContainer = new WebMarkupContainer("birthYearContainer");
birthYearContainer.add(new Label("birthYearLabel", new ResourceModel("privacy.birthyear")));
CheckBox birthYearCheckbox = new CheckBox("birthYear", new PropertyModel(privacyModel, "showBirthYear"));
birthYearCheckbox.setOutputMarkupId(true);
birthYearContainer.add(birthYearCheckbox);
//tooltip
birthYearContainer.add(new IconWithClueTip("birthYearToolTip", ProfileConstants.INFO_IMAGE, new ResourceModel("text.privacy.birthyear.tooltip")));
form.add(birthYearContainer);
//updater
birthYearCheckbox.add(new AjaxFormComponentUpdatingBehavior("onclick") {
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
//myFriends privacy
WebMarkupContainer myFriendsContainer = new WebMarkupContainer("myFriendsContainer");
myFriendsContainer.add(new Label("myFriendsLabel", new ResourceModel("privacy.myfriends")));
DropDownChoice myFriendsChoice = new DropDownChoice("myFriends", dropDownModelStrict, new HashMapChoiceRenderer(privacySettingsStrict));
myFriendsChoice.setOutputMarkupId(true);
myFriendsContainer.add(myFriendsChoice);
//tooltip
myFriendsContainer.add(new IconWithClueTip("myFriendsToolTip", ProfileConstants.INFO_IMAGE, new ResourceModel("text.privacy.myfriends.tooltip")));
form.add(myFriendsContainer);
//updater
myFriendsChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
//myStatus privacy
WebMarkupContainer myStatusContainer = new WebMarkupContainer("myStatusContainer");
myStatusContainer.add(new Label("myStatusLabel", new ResourceModel("privacy.mystatus")));
DropDownChoice myStatusChoice = new DropDownChoice("myStatus", dropDownModelRelaxed, new HashMapChoiceRenderer(privacySettingsRelaxed));
myStatusChoice.setOutputMarkupId(true);
myStatusContainer.add(myStatusChoice);
//tooltip
myStatusContainer.add(new IconWithClueTip("myStatusToolTip", ProfileConstants.INFO_IMAGE, new ResourceModel("text.privacy.mystatus.tooltip")));
form.add(myStatusContainer);
//updater
myStatusChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
// gallery privacy
WebMarkupContainer myPicturesContainer = new WebMarkupContainer("myPicturesContainer");
myPicturesContainer.add(new Label("myPicturesLabel", new ResourceModel("privacy.mypictures")));
DropDownChoice myPicturesChoice = new DropDownChoice("myPictures", dropDownModelRelaxed, new HashMapChoiceRenderer(privacySettingsRelaxed));
myPicturesChoice.setOutputMarkupId(true);
myPicturesContainer.add(myPicturesChoice);
myPicturesContainer.add(new IconWithClueTip("myPicturesToolTip", ProfileConstants.INFO_IMAGE, new ResourceModel("text.privacy.mypictures.tooltip")));
form.add(myPicturesContainer);
myPicturesChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
myPicturesContainer.setVisible(sakaiProxy.isProfileGalleryEnabledGlobally());
// messages privacy
WebMarkupContainer messagesContainer = new WebMarkupContainer("messagesContainer");
messagesContainer.add(new Label("messagesLabel", new ResourceModel("privacy.messages")));
DropDownChoice messagesChoice = new DropDownChoice("messages", dropDownModelRelaxed, new HashMapChoiceRenderer(privacySettingsRelaxed));
messagesChoice.setOutputMarkupId(true);
messagesContainer.add(messagesChoice);
messagesContainer.add(new IconWithClueTip("messagesToolTip", ProfileConstants.INFO_IMAGE, new ResourceModel("text.privacy.messages.tooltip")));
form.add(messagesContainer);
messagesChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
// kudos privacy
WebMarkupContainer myKudosContainer = new WebMarkupContainer("myKudosContainer");
myKudosContainer.add(new Label("myKudosLabel", new ResourceModel("privacy.mykudos")));
DropDownChoice kudosChoice = new DropDownChoice("myKudos", dropDownModelRelaxed, new HashMapChoiceRenderer(privacySettingsRelaxed));
kudosChoice.setOutputMarkupId(true);
myKudosContainer.add(kudosChoice);
myKudosContainer.add(new IconWithClueTip("myKudosToolTip", ProfileConstants.INFO_IMAGE, new ResourceModel("text.privacy.mykudos.tooltip")));
form.add(myKudosContainer);
kudosChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
//submit button
IndicatingAjaxButton submitButton = new IndicatingAjaxButton("submit", form) {
protected void onSubmit(AjaxRequestTarget target, Form form) {
//save() form, show feedback. perhaps redirect back to main page after a short while?
if(save(form)){
formFeedback.setDefaultModel(new ResourceModel("success.privacy.save.ok"));
formFeedback.add(new AttributeModifier("class", true, new Model<String>("success")));
//post update event
sakaiProxy.postEvent(ProfileConstants.EVENT_PRIVACY_UPDATE, "/profile/"+userUuid, true);
} else {
formFeedback.setDefaultModel(new ResourceModel("error.privacy.save.failed"));
formFeedback.add(new AttributeModifier("class", true, new Model<String>("alertMessage")));
}
target.addComponent(formFeedback);
}
};
submitButton.setModel(new ResourceModel("button.save.settings"));
submitButton.setOutputMarkupId(true);
form.add(submitButton);
//cancel button
/*
AjaxFallbackButton cancelButton = new AjaxFallbackButton("cancel", new ResourceModel("button.cancel"), form) {
protected void onSubmit(AjaxRequestTarget target, Form form) {
setResponsePage(new MyProfile());
}
};
cancelButton.setDefaultFormProcessing(false);
form.add(cancelButton);
*/
if(!sakaiProxy.isPrivacyChangeAllowedGlobally()){
infoLocked.setDefaultModel(new ResourceModel("text.privacy.cannot.modify"));
infoLocked.setVisible(true);
profileImageChoice.setEnabled(false);
basicInfoChoice.setEnabled(false);
contactInfoChoice.setEnabled(false);
studentInfoChoice.setEnabled(false);
businessInfoChoice.setEnabled(false);
personalInfoChoice.setEnabled(false);
birthYearCheckbox.setEnabled(false);
myFriendsChoice.setEnabled(false);
myStatusChoice.setEnabled(false);
myPicturesChoice.setEnabled(false);
messagesChoice.setEnabled(false);
submitButton.setEnabled(false);
submitButton.setVisible(false);
form.setEnabled(false);
}
add(form);
}
| public MyPrivacy() {
log.debug("MyPrivacy()");
disableLink(myPrivacyLink);
//get current user
final String userUuid = sakaiProxy.getCurrentUserId();
//get the privacy record for this user from the database, or a default if none exists
profilePrivacy = privacyLogic.getPrivacyRecordForUser(userUuid, false);
//if null, throw exception
if(profilePrivacy == null) {
throw new ProfilePrivacyNotDefinedException("Couldn't retrieve privacy record for " + userUuid);
}
Label heading = new Label("heading", new ResourceModel("heading.privacy"));
add(heading);
Label infoLocked = new Label("infoLocked");
infoLocked.setOutputMarkupPlaceholderTag(true);
infoLocked.setVisible(false);
add(infoLocked);
//feedback for form submit action
final Label formFeedback = new Label("formFeedback");
formFeedback.setOutputMarkupPlaceholderTag(true);
final String formFeedbackId = formFeedback.getMarkupId();
add(formFeedback);
//create model
CompoundPropertyModel<ProfilePrivacy> privacyModel = new CompoundPropertyModel<ProfilePrivacy>(profilePrivacy);
//setup form
Form<ProfilePrivacy> form = new Form<ProfilePrivacy>("form", privacyModel);
form.setOutputMarkupId(true);
//setup LinkedHashMap of privacy options for strict things
final LinkedHashMap<String, String> privacySettingsStrict = new LinkedHashMap<String, String>();
privacySettingsStrict.put("0", new StringResourceModel("privacy.option.everyone", this,null).getString());
privacySettingsStrict.put("1", new StringResourceModel("privacy.option.onlyfriends", this,null).getString());
privacySettingsStrict.put("2", new StringResourceModel("privacy.option.onlyme", this,null).getString());
//model that wraps our options
IModel dropDownModelStrict = new Model() {
public ArrayList<String> getObject() {
return new ArrayList(privacySettingsStrict.keySet());
}
};
//setup LinkedHashMap of privacy options for more relaxed things
final LinkedHashMap<String, String> privacySettingsRelaxed = new LinkedHashMap<String, String>();
privacySettingsRelaxed.put("0", new StringResourceModel("privacy.option.everyone", this,null).getString());
privacySettingsRelaxed.put("1", new StringResourceModel("privacy.option.onlyfriends", this,null).getString());
//model that wraps our options
IModel dropDownModelRelaxed = new Model() {
public ArrayList<String> getObject() {
return new ArrayList(privacySettingsRelaxed.keySet());
}
};
//when using DDC with a compoundPropertyModel we use this constructor: DDC<T>(String,IModel<List<T>>,IChoiceRenderer<T>)
//and the ID of the DDC field maps to the field in the CompoundPropertyModel
//the AjaxFormComponentUpdatingBehavior is to allow the DDC and checkboxes to fadeaway any error/success message
//that might be visible since the form has changed and it needs to be submitted again for it to take effect
//profile image privacy
WebMarkupContainer profileImageContainer = new WebMarkupContainer("profileImageContainer");
profileImageContainer.add(new Label("profileImageLabel", new ResourceModel("privacy.profileimage")));
DropDownChoice profileImageChoice = new DropDownChoice("profileImage", dropDownModelRelaxed, new HashMapChoiceRenderer(privacySettingsRelaxed));
profileImageChoice.setOutputMarkupId(true);
profileImageContainer.add(profileImageChoice);
//tooltip
profileImageContainer.add(new IconWithClueTip("profileImageToolTip", ProfileConstants.INFO_IMAGE, new ResourceModel("text.privacy.profileimage.tooltip")));
form.add(profileImageContainer);
//updater
profileImageChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
//basicInfo privacy
WebMarkupContainer basicInfoContainer = new WebMarkupContainer("basicInfoContainer");
basicInfoContainer.add(new Label("basicInfoLabel", new ResourceModel("privacy.basicinfo")));
DropDownChoice basicInfoChoice = new DropDownChoice("basicInfo", dropDownModelStrict, new HashMapChoiceRenderer(privacySettingsStrict));
basicInfoChoice.setOutputMarkupId(true);
basicInfoContainer.add(basicInfoChoice);
//tooltip
basicInfoContainer.add(new IconWithClueTip("basicInfoToolTip", ProfileConstants.INFO_IMAGE, new ResourceModel("text.privacy.basicinfo.tooltip")));
form.add(basicInfoContainer);
//updater
basicInfoChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
//contactInfo privacy
WebMarkupContainer contactInfoContainer = new WebMarkupContainer("contactInfoContainer");
contactInfoContainer.add(new Label("contactInfoLabel", new ResourceModel("privacy.contactinfo")));
DropDownChoice contactInfoChoice = new DropDownChoice("contactInfo", dropDownModelStrict, new HashMapChoiceRenderer(privacySettingsStrict));
contactInfoChoice.setOutputMarkupId(true);
contactInfoContainer.add(contactInfoChoice);
//tooltip
contactInfoContainer.add(new IconWithClueTip("contactInfoToolTip", ProfileConstants.INFO_IMAGE, new ResourceModel("text.privacy.contactinfo.tooltip")));
form.add(contactInfoContainer);
//updater
contactInfoChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
//staffInfo privacy
WebMarkupContainer staffInfoContainer = new WebMarkupContainer("staffInfoContainer");
staffInfoContainer.add(new Label("staffInfoLabel", new ResourceModel("privacy.staffinfo")));
DropDownChoice staffInfoChoice = new DropDownChoice("staffInfo", dropDownModelStrict, new HashMapChoiceRenderer(privacySettingsStrict));
staffInfoChoice.setOutputMarkupId(true);
staffInfoContainer.add(staffInfoChoice);
//tooltip
staffInfoContainer.add(new IconWithClueTip("staffInfoToolTip", ProfileConstants.INFO_IMAGE, new ResourceModel("text.privacy.staff.tooltip")));
form.add(staffInfoContainer);
//updater
staffInfoChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
//studentInfo privacy
WebMarkupContainer studentInfoContainer = new WebMarkupContainer("studentInfoContainer");
studentInfoContainer.add(new Label("studentInfoLabel", new ResourceModel("privacy.studentinfo")));
DropDownChoice studentInfoChoice = new DropDownChoice("studentInfo", dropDownModelStrict, new HashMapChoiceRenderer(privacySettingsStrict));
studentInfoChoice.setOutputMarkupId(true);
studentInfoContainer.add(studentInfoChoice);
//tooltip
studentInfoContainer.add(new IconWithClueTip("studentInfoToolTip", ProfileConstants.INFO_IMAGE, new ResourceModel("text.privacy.student.tooltip")));
form.add(studentInfoContainer);
//updater
studentInfoChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
//businesInfo privacy
WebMarkupContainer businessInfoContainer = new WebMarkupContainer("businessInfoContainer");
businessInfoContainer.add(new Label("businessInfoLabel", new ResourceModel("privacy.businessinfo")));
DropDownChoice businessInfoChoice = new DropDownChoice("businessInfo", dropDownModelStrict, new HashMapChoiceRenderer(privacySettingsStrict));
businessInfoChoice.setOutputMarkupId(true);
businessInfoContainer.add(businessInfoChoice);
//tooltip
businessInfoContainer.add(new IconWithClueTip("businessInfoToolTip", ProfileConstants.INFO_IMAGE, new ResourceModel("text.privacy.businessinfo.tooltip")));
form.add(businessInfoContainer);
//updater
businessInfoChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
businessInfoContainer.setVisible(sakaiProxy.isBusinessProfileEnabled());
//socialNetworkingInfo privacy
WebMarkupContainer socialNetworkingInfoContainer = new WebMarkupContainer("socialNetworkingInfoContainer");
socialNetworkingInfoContainer.add(new Label("socialNetworkingInfoLabel", new ResourceModel("privacy.socialinfo")));
DropDownChoice socialNetworkingInfoChoice = new DropDownChoice("socialNetworkingInfo", dropDownModelStrict, new HashMapChoiceRenderer(privacySettingsStrict));
socialNetworkingInfoChoice.setOutputMarkupId(true);
socialNetworkingInfoContainer.add(socialNetworkingInfoChoice);
//tooltip
socialNetworkingInfoContainer.add(new IconWithClueTip("socialNetworkingInfoToolTip", ProfileConstants.INFO_IMAGE, new ResourceModel("text.privacy.socialinfo.tooltip")));
form.add(socialNetworkingInfoContainer);
//updater
socialNetworkingInfoChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
//personalInfo privacy
WebMarkupContainer personalInfoContainer = new WebMarkupContainer("personalInfoContainer");
personalInfoContainer.add(new Label("personalInfoLabel", new ResourceModel("privacy.personalinfo")));
DropDownChoice personalInfoChoice = new DropDownChoice("personalInfo", dropDownModelStrict, new HashMapChoiceRenderer(privacySettingsStrict));
personalInfoChoice.setOutputMarkupId(true);
personalInfoContainer.add(personalInfoChoice);
//tooltip
personalInfoContainer.add(new IconWithClueTip("personalInfoToolTip", ProfileConstants.INFO_IMAGE, new ResourceModel("text.privacy.personalinfo.tooltip")));
form.add(personalInfoContainer);
//updater
personalInfoChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
//birthYear privacy
WebMarkupContainer birthYearContainer = new WebMarkupContainer("birthYearContainer");
birthYearContainer.add(new Label("birthYearLabel", new ResourceModel("privacy.birthyear")));
CheckBox birthYearCheckbox = new CheckBox("birthYear", new PropertyModel(privacyModel, "showBirthYear"));
birthYearCheckbox.setOutputMarkupId(true);
birthYearContainer.add(birthYearCheckbox);
//tooltip
birthYearContainer.add(new IconWithClueTip("birthYearToolTip", ProfileConstants.INFO_IMAGE, new ResourceModel("text.privacy.birthyear.tooltip")));
form.add(birthYearContainer);
//updater
birthYearCheckbox.add(new AjaxFormComponentUpdatingBehavior("onclick") {
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
//myFriends privacy
WebMarkupContainer myFriendsContainer = new WebMarkupContainer("myFriendsContainer");
myFriendsContainer.add(new Label("myFriendsLabel", new ResourceModel("privacy.myfriends")));
DropDownChoice myFriendsChoice = new DropDownChoice("myFriends", dropDownModelStrict, new HashMapChoiceRenderer(privacySettingsStrict));
myFriendsChoice.setOutputMarkupId(true);
myFriendsContainer.add(myFriendsChoice);
//tooltip
myFriendsContainer.add(new IconWithClueTip("myFriendsToolTip", ProfileConstants.INFO_IMAGE, new ResourceModel("text.privacy.myfriends.tooltip")));
form.add(myFriendsContainer);
//updater
myFriendsChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
//myStatus privacy
WebMarkupContainer myStatusContainer = new WebMarkupContainer("myStatusContainer");
myStatusContainer.add(new Label("myStatusLabel", new ResourceModel("privacy.mystatus")));
DropDownChoice myStatusChoice = new DropDownChoice("myStatus", dropDownModelRelaxed, new HashMapChoiceRenderer(privacySettingsRelaxed));
myStatusChoice.setOutputMarkupId(true);
myStatusContainer.add(myStatusChoice);
//tooltip
myStatusContainer.add(new IconWithClueTip("myStatusToolTip", ProfileConstants.INFO_IMAGE, new ResourceModel("text.privacy.mystatus.tooltip")));
form.add(myStatusContainer);
//updater
myStatusChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
// gallery privacy
WebMarkupContainer myPicturesContainer = new WebMarkupContainer("myPicturesContainer");
myPicturesContainer.add(new Label("myPicturesLabel", new ResourceModel("privacy.mypictures")));
DropDownChoice myPicturesChoice = new DropDownChoice("myPictures", dropDownModelRelaxed, new HashMapChoiceRenderer(privacySettingsRelaxed));
myPicturesChoice.setOutputMarkupId(true);
myPicturesContainer.add(myPicturesChoice);
myPicturesContainer.add(new IconWithClueTip("myPicturesToolTip", ProfileConstants.INFO_IMAGE, new ResourceModel("text.privacy.mypictures.tooltip")));
form.add(myPicturesContainer);
myPicturesChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
myPicturesContainer.setVisible(sakaiProxy.isProfileGalleryEnabledGlobally());
// messages privacy
WebMarkupContainer messagesContainer = new WebMarkupContainer("messagesContainer");
messagesContainer.add(new Label("messagesLabel", new ResourceModel("privacy.messages")));
DropDownChoice messagesChoice = new DropDownChoice("messages", dropDownModelRelaxed, new HashMapChoiceRenderer(privacySettingsRelaxed));
messagesChoice.setOutputMarkupId(true);
messagesContainer.add(messagesChoice);
messagesContainer.add(new IconWithClueTip("messagesToolTip", ProfileConstants.INFO_IMAGE, new ResourceModel("text.privacy.messages.tooltip")));
form.add(messagesContainer);
messagesChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
// kudos privacy
WebMarkupContainer myKudosContainer = new WebMarkupContainer("myKudosContainer");
myKudosContainer.add(new Label("myKudosLabel", new ResourceModel("privacy.mykudos")));
DropDownChoice kudosChoice = new DropDownChoice("myKudos", dropDownModelRelaxed, new HashMapChoiceRenderer(privacySettingsRelaxed));
kudosChoice.setOutputMarkupId(true);
myKudosContainer.add(kudosChoice);
myKudosContainer.add(new IconWithClueTip("myKudosToolTip", ProfileConstants.INFO_IMAGE, new ResourceModel("text.privacy.mykudos.tooltip")));
form.add(myKudosContainer);
kudosChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
//submit button
IndicatingAjaxButton submitButton = new IndicatingAjaxButton("submit", form) {
protected void onSubmit(AjaxRequestTarget target, Form form) {
//save() form, show feedback. perhaps redirect back to main page after a short while?
if(save(form)){
formFeedback.setDefaultModel(new ResourceModel("success.privacy.save.ok"));
formFeedback.add(new AttributeModifier("class", true, new Model<String>("success")));
//post update event
sakaiProxy.postEvent(ProfileConstants.EVENT_PRIVACY_UPDATE, "/profile/"+userUuid, true);
} else {
formFeedback.setDefaultModel(new ResourceModel("error.privacy.save.failed"));
formFeedback.add(new AttributeModifier("class", true, new Model<String>("alertMessage")));
}
target.addComponent(formFeedback);
}
};
submitButton.setModel(new ResourceModel("button.save.settings"));
submitButton.setOutputMarkupId(true);
form.add(submitButton);
//cancel button
/*
AjaxFallbackButton cancelButton = new AjaxFallbackButton("cancel", new ResourceModel("button.cancel"), form) {
protected void onSubmit(AjaxRequestTarget target, Form form) {
setResponsePage(new MyProfile());
}
};
cancelButton.setDefaultFormProcessing(false);
form.add(cancelButton);
*/
if(!sakaiProxy.isPrivacyChangeAllowedGlobally()){
infoLocked.setDefaultModel(new ResourceModel("text.privacy.cannot.modify"));
infoLocked.setVisible(true);
profileImageChoice.setEnabled(false);
basicInfoChoice.setEnabled(false);
contactInfoChoice.setEnabled(false);
studentInfoChoice.setEnabled(false);
businessInfoChoice.setEnabled(false);
personalInfoChoice.setEnabled(false);
birthYearCheckbox.setEnabled(false);
myFriendsChoice.setEnabled(false);
myStatusChoice.setEnabled(false);
myPicturesChoice.setEnabled(false);
messagesChoice.setEnabled(false);
submitButton.setEnabled(false);
submitButton.setVisible(false);
form.setEnabled(false);
}
add(form);
}
|
diff --git a/src/main/java/com/philihp/weblabora/action/ShowBoard.java b/src/main/java/com/philihp/weblabora/action/ShowBoard.java
index 1efafef..8c19fc5 100644
--- a/src/main/java/com/philihp/weblabora/action/ShowBoard.java
+++ b/src/main/java/com/philihp/weblabora/action/ShowBoard.java
@@ -1,61 +1,61 @@
package com.philihp.weblabora.action;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.philihp.weblabora.form.GameForm;
import com.philihp.weblabora.jpa.Game;
import com.philihp.weblabora.jpa.User;
import com.philihp.weblabora.model.Board;
import com.philihp.weblabora.model.MoveProcessor;
import com.philihp.weblabora.util.EntityManagerManager;
import com.philihp.weblabora.util.FacebookCredentials;
public class ShowBoard extends BaseAction {
@Override
public ActionForward execute(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request,
HttpServletResponse response, User user) throws Exception {
request.setAttribute("myGames", findGamesForUser(user));
request.setAttribute("game", user.getActiveGame());
Board board = null;
if(user.getActiveGame() != null) {
board = new Board();
board.populateDetails(user.getActiveGame());
MoveProcessor.processMoves(board, user.getActiveGame().getMoves());
+ board.preMove(); //upkeep stuff before player makes a move
request.setAttribute("board", board);
}
- board.preMove(); //upkeep stuff before player makes a move
return mapping.findForward("view");
}
private List<Game> findGamesForUser(User user) {
EntityManager em = EntityManagerManager.get();
TypedQuery<Game> query = em
.createQuery(
"SELECT g " +
"FROM Game g " +
"WHERE g.player1.user = :user " +
"OR g.player2.user = :user " +
"OR g.player3.user = :user " +
"OR g.player4.user = :user",
Game.class);
query.setParameter("user", user);
List<Game> results = query.getResultList();
return results;
}
}
| false | true | public ActionForward execute(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request,
HttpServletResponse response, User user) throws Exception {
request.setAttribute("myGames", findGamesForUser(user));
request.setAttribute("game", user.getActiveGame());
Board board = null;
if(user.getActiveGame() != null) {
board = new Board();
board.populateDetails(user.getActiveGame());
MoveProcessor.processMoves(board, user.getActiveGame().getMoves());
request.setAttribute("board", board);
}
board.preMove(); //upkeep stuff before player makes a move
return mapping.findForward("view");
}
| public ActionForward execute(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request,
HttpServletResponse response, User user) throws Exception {
request.setAttribute("myGames", findGamesForUser(user));
request.setAttribute("game", user.getActiveGame());
Board board = null;
if(user.getActiveGame() != null) {
board = new Board();
board.populateDetails(user.getActiveGame());
MoveProcessor.processMoves(board, user.getActiveGame().getMoves());
board.preMove(); //upkeep stuff before player makes a move
request.setAttribute("board", board);
}
return mapping.findForward("view");
}
|
diff --git a/pmd/src/test/java/net/sourceforge/pmd/lang/java/rule/controversial/ControversialRulesTest.java b/pmd/src/test/java/net/sourceforge/pmd/lang/java/rule/controversial/ControversialRulesTest.java
index dec8b823a..fe1094fe4 100644
--- a/pmd/src/test/java/net/sourceforge/pmd/lang/java/rule/controversial/ControversialRulesTest.java
+++ b/pmd/src/test/java/net/sourceforge/pmd/lang/java/rule/controversial/ControversialRulesTest.java
@@ -1,42 +1,41 @@
package net.sourceforge.pmd.lang.java.rule.controversial;
import net.sourceforge.pmd.testframework.SimpleAggregatorTst;
import org.junit.Before;
public class ControversialRulesTest extends SimpleAggregatorTst {
private static final String RULESET = "java-controversial";
@Before
public void setUp() {
addRule(RULESET, "AssignmentInOperand");
- addRule(RULESET, "AvoidFinalLocalVariable");
addRule(RULESET, "AvoidLiteralsInIfCondition");
addRule(RULESET, "AvoidPrefixingMethodParameters");
addRule(RULESET, "AvoidUsingNativeCode");
addRule(RULESET, "AvoidUsingShortType");
addRule(RULESET, "AvoidUsingVolatile");
addRule(RULESET, "AtLeastOneConstructor");
addRule(RULESET, "AvoidFinalLocalVariable");
addRule(RULESET, "BooleanInversion");
addRule(RULESET, "CallSuperInConstructor");
addRule(RULESET, "DataflowAnomalyAnalysis");
addRule(RULESET, "DefaultPackage");
addRule(RULESET, "DontImportSun");
addRule(RULESET, "DoNotCallGarbageCollectionExplicitly");
addRule(RULESET, "NullAssignment");
addRule(RULESET, "OnlyOneReturn");
addRule(RULESET, "OneDeclarationPerLine");
addRule(RULESET, "SuspiciousOctalEscape");
addRule(RULESET, "UnnecessaryConstructor");
addRule(RULESET, "UnnecessaryParentheses");
addRule(RULESET, "UseConcurrentHashMap");
addRule(RULESET, "UseObjectForClearerAPI");
}
public static junit.framework.Test suite() {
return new junit.framework.JUnit4TestAdapter(ControversialRulesTest.class);
}
}
| true | true | public void setUp() {
addRule(RULESET, "AssignmentInOperand");
addRule(RULESET, "AvoidFinalLocalVariable");
addRule(RULESET, "AvoidLiteralsInIfCondition");
addRule(RULESET, "AvoidPrefixingMethodParameters");
addRule(RULESET, "AvoidUsingNativeCode");
addRule(RULESET, "AvoidUsingShortType");
addRule(RULESET, "AvoidUsingVolatile");
addRule(RULESET, "AtLeastOneConstructor");
addRule(RULESET, "AvoidFinalLocalVariable");
addRule(RULESET, "BooleanInversion");
addRule(RULESET, "CallSuperInConstructor");
addRule(RULESET, "DataflowAnomalyAnalysis");
addRule(RULESET, "DefaultPackage");
addRule(RULESET, "DontImportSun");
addRule(RULESET, "DoNotCallGarbageCollectionExplicitly");
addRule(RULESET, "NullAssignment");
addRule(RULESET, "OnlyOneReturn");
addRule(RULESET, "OneDeclarationPerLine");
addRule(RULESET, "SuspiciousOctalEscape");
addRule(RULESET, "UnnecessaryConstructor");
addRule(RULESET, "UnnecessaryParentheses");
addRule(RULESET, "UseConcurrentHashMap");
addRule(RULESET, "UseObjectForClearerAPI");
}
| public void setUp() {
addRule(RULESET, "AssignmentInOperand");
addRule(RULESET, "AvoidLiteralsInIfCondition");
addRule(RULESET, "AvoidPrefixingMethodParameters");
addRule(RULESET, "AvoidUsingNativeCode");
addRule(RULESET, "AvoidUsingShortType");
addRule(RULESET, "AvoidUsingVolatile");
addRule(RULESET, "AtLeastOneConstructor");
addRule(RULESET, "AvoidFinalLocalVariable");
addRule(RULESET, "BooleanInversion");
addRule(RULESET, "CallSuperInConstructor");
addRule(RULESET, "DataflowAnomalyAnalysis");
addRule(RULESET, "DefaultPackage");
addRule(RULESET, "DontImportSun");
addRule(RULESET, "DoNotCallGarbageCollectionExplicitly");
addRule(RULESET, "NullAssignment");
addRule(RULESET, "OnlyOneReturn");
addRule(RULESET, "OneDeclarationPerLine");
addRule(RULESET, "SuspiciousOctalEscape");
addRule(RULESET, "UnnecessaryConstructor");
addRule(RULESET, "UnnecessaryParentheses");
addRule(RULESET, "UseConcurrentHashMap");
addRule(RULESET, "UseObjectForClearerAPI");
}
|
diff --git a/compiler/src/main/java/org/robovm/compiler/target/AbstractTarget.java b/compiler/src/main/java/org/robovm/compiler/target/AbstractTarget.java
index 84b3107b8..91b92dd8f 100644
--- a/compiler/src/main/java/org/robovm/compiler/target/AbstractTarget.java
+++ b/compiler/src/main/java/org/robovm/compiler/target/AbstractTarget.java
@@ -1,344 +1,345 @@
/*
* Copyright (C) 2012 Trillian AB
*
* 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, see <http://www.gnu.org/licenses/gpl-2.0.html>.
*/
package org.robovm.compiler.target;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.robovm.compiler.clazz.Path;
import org.robovm.compiler.config.Config;
import org.robovm.compiler.config.OS;
import org.robovm.compiler.config.Resource;
import org.robovm.compiler.config.Resource.Walker;
import org.robovm.compiler.util.Executor;
import org.robovm.compiler.util.ToolchainUtil;
import org.simpleframework.xml.Transient;
/**
* @author niklas
*
*/
public abstract class AbstractTarget implements Target {
@Transient
protected Config config;
protected AbstractTarget() {
}
@Override
public void init(Config config) {
this.config = config;
}
@Override
public LaunchParameters createLaunchParameters() {
return new LaunchParameters();
}
public String getInstallRelativeArchivePath(Path path) {
String name = config.getArchiveName(path);
if (path.isInBootClasspath()) {
return "lib" + File.separator + "boot" + File.separator + name;
}
return "lib" + File.separator + name;
}
public boolean canLaunchInPlace() {
return true;
}
public void build(List<File> objectFiles) throws IOException {
File outFile = new File(config.getTmpDir(), config.getExecutableName());
config.getLogger().debug("Building executable %s", outFile);
LinkedList<String> ccArgs = new LinkedList<String>();
LinkedList<String> libs = new LinkedList<String>();
String libSuffix = config.isUseDebugLibs() ? "-dbg" : "";
libs.add("-lrobovm-bc" + libSuffix);
if (config.getOs().getFamily() == OS.Family.darwin) {
libs.add("-force_load");
libs.add(new File(config.getOsArchDepLibDir(), "librobovm-rt" + libSuffix + ".a").getAbsolutePath());
} else {
libs.addAll(Arrays.asList("-Wl,--whole-archive", "-lrobovm-rt" + libSuffix, "-Wl,--no-whole-archive"));
}
if (config.isSkipInstall()) {
libs.add("-lrobovm-debug" + libSuffix);
}
libs.addAll(Arrays.asList(
"-lrobovm-core" + libSuffix, "-lgc" + libSuffix, "-lpthread", "-ldl", "-lm", "-lstdc++"));
if (config.getOs().getFamily() == OS.Family.linux) {
libs.add("-lrt");
}
if (config.getOs().getFamily() == OS.Family.darwin) {
+ libs.add("-lc++");
libs.add("-liconv");
libs.add("-lsqlite3");
libs.add("-framework");
libs.add("Foundation");
}
ccArgs.add("-L");
ccArgs.add(config.getOsArchDepLibDir().getAbsolutePath());
if (config.getOs().getFamily() == OS.Family.linux) {
ccArgs.add("-Wl,-rpath=$ORIGIN");
ccArgs.add("-Wl,--gc-sections");
// ccArgs.add("-Wl,--print-gc-sections");
} else if (config.getOs().getFamily() == OS.Family.darwin) {
File exportedSymbolsFile = new File(config.getTmpDir(), "exported_symbols");
List<String> exportedSymbols = new ArrayList<String>();
if (config.isSkipInstall()) {
exportedSymbols.add("catch_exception_raise");
}
exportedSymbols.addAll(config.getExportedSymbols());
for (int i = 0; i < exportedSymbols.size(); i++) {
// On Darwin symbols are always prefixed with a '_'. We'll prepend
// '_' to each symbol here so the user won't have to.
exportedSymbols.set(i, "_" + exportedSymbols.get(i));
}
FileUtils.writeLines(exportedSymbolsFile, "ASCII", exportedSymbols);
ccArgs.add("-exported_symbols_list");
ccArgs.add(exportedSymbolsFile.getAbsolutePath());
ccArgs.add("-Wl,-no_implicit_dylibs");
ccArgs.add("-Wl,-dead_strip");
}
if (config.getOs().getFamily() == OS.Family.darwin && !config.getFrameworks().isEmpty()) {
for (String p : config.getFrameworks()) {
libs.add("-framework");
libs.add(p);
}
}
if (!config.getLibs().isEmpty()) {
objectFiles = new ArrayList<File>(objectFiles);
for (String p : config.getLibs()) {
if (p.endsWith(".o")) {
objectFiles.add(new File(p));
} else if(p.endsWith(".a")) {
// .a file
if (config.getOs().getFamily() == OS.Family.darwin) {
libs.add("-force_load");
libs.add(new File(p).getAbsolutePath());
} else {
libs.addAll(Arrays.asList("-Wl,--whole-archive", new File(p).getAbsolutePath(), "-Wl,--no-whole-archive"));
}
} else {
// link via -l if suffix is omitted
libs.add("-l" + p);
}
}
}
doBuild(outFile, ccArgs, objectFiles, libs);
}
protected void doBuild(File outFile, List<String> ccArgs, List<File> objectFiles,
List<String> libs) throws IOException {
ToolchainUtil.link(config, ccArgs, objectFiles, libs, outFile);
}
protected void copyResources(File destDir) throws IOException {
for (Resource res : config.getResources()) {
res.walk(new Walker() {
@Override
public void process(Resource resource, File file, File destDir)
throws IOException {
copyFile(resource, file, destDir);
}
}, destDir);
}
}
protected void copyFile(Resource resource, File file, File destDir) throws IOException {
config.getLogger().debug("Copying resource %s to %s", file, destDir);
FileUtils.copyFileToDirectory(file, destDir, true);
}
public void install() throws IOException {
config.getLogger().debug("Installing executable to %s", config.getInstallDir());
config.getInstallDir().mkdirs();
doInstall(config.getInstallDir(), config.getExecutableName());
}
protected void doInstall(File installDir, String executable) throws IOException {
if (!config.getTmpDir().equals(installDir) || !executable.equals(config.getExecutableName())) {
File destFile = new File(installDir, executable);
FileUtils.copyFile(new File(config.getTmpDir(), config.getExecutableName()), destFile);
destFile.setExecutable(true, false);
}
for (File f : config.getOsArchDepLibDir().listFiles()) {
if (f.getName().matches(".*\\.(so|dylib)(\\.1)?")) {
FileUtils.copyFileToDirectory(f, installDir);
}
}
stripArchives(installDir);
copyResources(installDir);
}
public Process launch(LaunchParameters launchParameters) throws IOException {
if (config.isSkipLinking()) {
throw new IllegalStateException("Cannot skip linking if target should be run");
}
// Add -rvm:log=warn to command line arguments if no logging level has been set explicitly
boolean add = true;
for (String arg : launchParameters.getArguments()) {
if (arg.startsWith("-rvm:log=")) {
add = false;
break;
}
}
if (add) {
List<String> args = new ArrayList<String>(launchParameters.getArguments());
args.add(0, "-rvm:log=warn");
launchParameters.setArguments(args);
}
return doLaunch(launchParameters);
}
protected Process doLaunch(LaunchParameters launchParameters) throws IOException {
return createExecutor(launchParameters).execAsync();
}
protected Executor createExecutor(LaunchParameters launchParameters) throws IOException {
File dir = config.getTmpDir();
if (!config.isSkipInstall()) {
dir = config.getInstallDir();
}
return createExecutor(launchParameters, new File(dir,
config.getExecutableName()).getAbsolutePath(),
launchParameters.getArguments());
}
protected Executor createExecutor(LaunchParameters launchParameters, String cmd, List<? extends Object> args) throws IOException {
Map<String, String> env = launchParameters.getEnvironment();
return new Executor(config.getLogger(), cmd)
.args(args)
.wd(launchParameters.getWorkingDirectory())
.inheritEnv(env == null)
.env(env == null ? Collections.<String, String>emptyMap() : env);
}
protected Target build(Config config) {
return this;
}
protected void stripArchives(File installDir) throws IOException {
List<Path> allPaths = new ArrayList<Path>();
allPaths.addAll(config.getClazzes().getPaths());
allPaths.addAll(config.getResourcesPaths());
for (Path path : allPaths) {
File destJar = new File(installDir, getInstallRelativeArchivePath(path));
if (!destJar.getParentFile().exists()) {
destJar.getParentFile().mkdirs();
}
stripArchive(path, destJar);
}
}
protected void stripArchive(Path path, File output) throws IOException {
if (!config.isClean() && output.exists() && !path.hasChangedSince(output.lastModified())) {
config.getLogger().debug("Not creating stripped archive file %s for unchanged path %s",
output, path.getFile());
return;
}
config.getLogger().debug("Creating stripped archive file %s", output);
ZipOutputStream out = null;
try {
out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(output)));
if (path.getFile().isFile()) {
ZipFile archive = null;
try {
archive = new ZipFile(path.getFile());
Enumeration<? extends ZipEntry> entries = archive.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
if (entry.getName().toLowerCase().endsWith(".class")) {
continue;
}
ZipEntry newEntry = new ZipEntry(entry.getName());
newEntry.setTime(entry.getTime());
out.putNextEntry(newEntry);
InputStream in = null;
try {
in = archive.getInputStream(entry);
IOUtils.copy(in, out);
out.closeEntry();
} finally {
IOUtils.closeQuietly(in);
}
}
} finally {
try {
archive.close();
} catch (Throwable t) {}
}
} else {
String basePath = path.getFile().getAbsolutePath();
@SuppressWarnings("unchecked")
Collection<File> files = FileUtils.listFiles(path.getFile(), null, true);
for (File f : files) {
if (f.getName().toLowerCase().endsWith(".class")) {
continue;
}
ZipEntry newEntry = new ZipEntry(f.getAbsolutePath().substring(basePath.length() + 1));
newEntry.setTime(f.lastModified());
out.putNextEntry(newEntry);
InputStream in = null;
try {
in = new FileInputStream(f);
IOUtils.copy(in, out);
out.closeEntry();
} finally {
IOUtils.closeQuietly(in);
}
}
}
} catch (IOException e) {
IOUtils.closeQuietly(out);
output.delete();
} finally {
IOUtils.closeQuietly(out);
}
}
}
| true | true | public void build(List<File> objectFiles) throws IOException {
File outFile = new File(config.getTmpDir(), config.getExecutableName());
config.getLogger().debug("Building executable %s", outFile);
LinkedList<String> ccArgs = new LinkedList<String>();
LinkedList<String> libs = new LinkedList<String>();
String libSuffix = config.isUseDebugLibs() ? "-dbg" : "";
libs.add("-lrobovm-bc" + libSuffix);
if (config.getOs().getFamily() == OS.Family.darwin) {
libs.add("-force_load");
libs.add(new File(config.getOsArchDepLibDir(), "librobovm-rt" + libSuffix + ".a").getAbsolutePath());
} else {
libs.addAll(Arrays.asList("-Wl,--whole-archive", "-lrobovm-rt" + libSuffix, "-Wl,--no-whole-archive"));
}
if (config.isSkipInstall()) {
libs.add("-lrobovm-debug" + libSuffix);
}
libs.addAll(Arrays.asList(
"-lrobovm-core" + libSuffix, "-lgc" + libSuffix, "-lpthread", "-ldl", "-lm", "-lstdc++"));
if (config.getOs().getFamily() == OS.Family.linux) {
libs.add("-lrt");
}
if (config.getOs().getFamily() == OS.Family.darwin) {
libs.add("-liconv");
libs.add("-lsqlite3");
libs.add("-framework");
libs.add("Foundation");
}
ccArgs.add("-L");
ccArgs.add(config.getOsArchDepLibDir().getAbsolutePath());
if (config.getOs().getFamily() == OS.Family.linux) {
ccArgs.add("-Wl,-rpath=$ORIGIN");
ccArgs.add("-Wl,--gc-sections");
// ccArgs.add("-Wl,--print-gc-sections");
} else if (config.getOs().getFamily() == OS.Family.darwin) {
File exportedSymbolsFile = new File(config.getTmpDir(), "exported_symbols");
List<String> exportedSymbols = new ArrayList<String>();
if (config.isSkipInstall()) {
exportedSymbols.add("catch_exception_raise");
}
exportedSymbols.addAll(config.getExportedSymbols());
for (int i = 0; i < exportedSymbols.size(); i++) {
// On Darwin symbols are always prefixed with a '_'. We'll prepend
// '_' to each symbol here so the user won't have to.
exportedSymbols.set(i, "_" + exportedSymbols.get(i));
}
FileUtils.writeLines(exportedSymbolsFile, "ASCII", exportedSymbols);
ccArgs.add("-exported_symbols_list");
ccArgs.add(exportedSymbolsFile.getAbsolutePath());
ccArgs.add("-Wl,-no_implicit_dylibs");
ccArgs.add("-Wl,-dead_strip");
}
if (config.getOs().getFamily() == OS.Family.darwin && !config.getFrameworks().isEmpty()) {
for (String p : config.getFrameworks()) {
libs.add("-framework");
libs.add(p);
}
}
if (!config.getLibs().isEmpty()) {
objectFiles = new ArrayList<File>(objectFiles);
for (String p : config.getLibs()) {
if (p.endsWith(".o")) {
objectFiles.add(new File(p));
} else if(p.endsWith(".a")) {
// .a file
if (config.getOs().getFamily() == OS.Family.darwin) {
libs.add("-force_load");
libs.add(new File(p).getAbsolutePath());
} else {
libs.addAll(Arrays.asList("-Wl,--whole-archive", new File(p).getAbsolutePath(), "-Wl,--no-whole-archive"));
}
} else {
// link via -l if suffix is omitted
libs.add("-l" + p);
}
}
}
doBuild(outFile, ccArgs, objectFiles, libs);
}
| public void build(List<File> objectFiles) throws IOException {
File outFile = new File(config.getTmpDir(), config.getExecutableName());
config.getLogger().debug("Building executable %s", outFile);
LinkedList<String> ccArgs = new LinkedList<String>();
LinkedList<String> libs = new LinkedList<String>();
String libSuffix = config.isUseDebugLibs() ? "-dbg" : "";
libs.add("-lrobovm-bc" + libSuffix);
if (config.getOs().getFamily() == OS.Family.darwin) {
libs.add("-force_load");
libs.add(new File(config.getOsArchDepLibDir(), "librobovm-rt" + libSuffix + ".a").getAbsolutePath());
} else {
libs.addAll(Arrays.asList("-Wl,--whole-archive", "-lrobovm-rt" + libSuffix, "-Wl,--no-whole-archive"));
}
if (config.isSkipInstall()) {
libs.add("-lrobovm-debug" + libSuffix);
}
libs.addAll(Arrays.asList(
"-lrobovm-core" + libSuffix, "-lgc" + libSuffix, "-lpthread", "-ldl", "-lm", "-lstdc++"));
if (config.getOs().getFamily() == OS.Family.linux) {
libs.add("-lrt");
}
if (config.getOs().getFamily() == OS.Family.darwin) {
libs.add("-lc++");
libs.add("-liconv");
libs.add("-lsqlite3");
libs.add("-framework");
libs.add("Foundation");
}
ccArgs.add("-L");
ccArgs.add(config.getOsArchDepLibDir().getAbsolutePath());
if (config.getOs().getFamily() == OS.Family.linux) {
ccArgs.add("-Wl,-rpath=$ORIGIN");
ccArgs.add("-Wl,--gc-sections");
// ccArgs.add("-Wl,--print-gc-sections");
} else if (config.getOs().getFamily() == OS.Family.darwin) {
File exportedSymbolsFile = new File(config.getTmpDir(), "exported_symbols");
List<String> exportedSymbols = new ArrayList<String>();
if (config.isSkipInstall()) {
exportedSymbols.add("catch_exception_raise");
}
exportedSymbols.addAll(config.getExportedSymbols());
for (int i = 0; i < exportedSymbols.size(); i++) {
// On Darwin symbols are always prefixed with a '_'. We'll prepend
// '_' to each symbol here so the user won't have to.
exportedSymbols.set(i, "_" + exportedSymbols.get(i));
}
FileUtils.writeLines(exportedSymbolsFile, "ASCII", exportedSymbols);
ccArgs.add("-exported_symbols_list");
ccArgs.add(exportedSymbolsFile.getAbsolutePath());
ccArgs.add("-Wl,-no_implicit_dylibs");
ccArgs.add("-Wl,-dead_strip");
}
if (config.getOs().getFamily() == OS.Family.darwin && !config.getFrameworks().isEmpty()) {
for (String p : config.getFrameworks()) {
libs.add("-framework");
libs.add(p);
}
}
if (!config.getLibs().isEmpty()) {
objectFiles = new ArrayList<File>(objectFiles);
for (String p : config.getLibs()) {
if (p.endsWith(".o")) {
objectFiles.add(new File(p));
} else if(p.endsWith(".a")) {
// .a file
if (config.getOs().getFamily() == OS.Family.darwin) {
libs.add("-force_load");
libs.add(new File(p).getAbsolutePath());
} else {
libs.addAll(Arrays.asList("-Wl,--whole-archive", new File(p).getAbsolutePath(), "-Wl,--no-whole-archive"));
}
} else {
// link via -l if suffix is omitted
libs.add("-l" + p);
}
}
}
doBuild(outFile, ccArgs, objectFiles, libs);
}
|
diff --git a/dvn-app/trunk/src/DVN-web/src/edu/harvard/iq/dvn/core/web/study/SetUpDataExplorationPage.java b/dvn-app/trunk/src/DVN-web/src/edu/harvard/iq/dvn/core/web/study/SetUpDataExplorationPage.java
index c7390cc99..02900600d 100644
--- a/dvn-app/trunk/src/DVN-web/src/edu/harvard/iq/dvn/core/web/study/SetUpDataExplorationPage.java
+++ b/dvn-app/trunk/src/DVN-web/src/edu/harvard/iq/dvn/core/web/study/SetUpDataExplorationPage.java
@@ -1,3101 +1,3101 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.harvard.iq.dvn.core.web.study;
import com.icesoft.faces.async.render.SessionRenderer;
import com.icesoft.faces.component.ext.HtmlCommandButton;
import edu.harvard.iq.dvn.core.study.DataTable;
import com.icesoft.faces.component.ext.HtmlInputText;
import com.icesoft.faces.component.ext.HtmlCommandLink;
import com.icesoft.faces.component.ext.HtmlSelectBooleanCheckbox;
import com.icesoft.faces.component.ext.HtmlSelectOneMenu;
import com.icesoft.faces.component.paneltabset.TabChangeEvent;
import edu.harvard.iq.dvn.core.study.DataVariable;
import edu.harvard.iq.dvn.core.study.EditStudyFilesService;
import edu.harvard.iq.dvn.core.study.FileMetadata;
import edu.harvard.iq.dvn.core.study.Metadata;
import edu.harvard.iq.dvn.core.study.Study;
import edu.harvard.iq.dvn.core.study.StudyFile;
import edu.harvard.iq.dvn.core.study.StudyVersion;
import edu.harvard.iq.dvn.core.study.VariableServiceLocal;
import edu.harvard.iq.dvn.core.visualization.DataVariableMapping;
import edu.harvard.iq.dvn.core.visualization.VarGroup;
import edu.harvard.iq.dvn.core.visualization.VarGroupType;
import edu.harvard.iq.dvn.core.visualization.VarGrouping;
import edu.harvard.iq.dvn.core.visualization.VarGrouping.GroupingType;
import edu.harvard.iq.dvn.core.visualization.VisualizationDisplay;
import edu.harvard.iq.dvn.core.visualization.VisualizationServiceLocal;
import edu.harvard.iq.dvn.core.web.DataVariableUI;
import edu.harvard.iq.dvn.core.web.VarGroupTypeUI;
import edu.harvard.iq.dvn.core.web.VarGroupUI;
import edu.harvard.iq.dvn.core.web.VarGroupUIList;
import edu.harvard.iq.dvn.core.web.VarGroupingUI;
import edu.harvard.iq.dvn.core.web.common.VDCBaseBean;
import edu.harvard.iq.dvn.ingest.dsb.FieldCutter;
import edu.harvard.iq.dvn.ingest.dsb.impl.DvnJavaFieldCutter;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ViewScoped;
import javax.faces.component.UIComponent;
import javax.faces.component.html.HtmlDataTable;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;
import javax.inject.Named;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
/**
*
* @author skraffmiller
*/
@EJB(name="visualizationService", beanInterface=edu.harvard.iq.dvn.core.visualization.VisualizationServiceBean.class)
@ViewScoped
@Named("SetUpDataExplorationPage")
public class SetUpDataExplorationPage extends VDCBaseBean implements java.io.Serializable {
@EJB
VisualizationServiceLocal visualizationService;
@EJB
VariableServiceLocal varService;
private EditStudyFilesService editStudyFilesService;
private List <VarGrouping> varGroupings = new ArrayList();;
private List <DataVariable> dvList = new ArrayList();
private List <DataVariable> dvFilteredList = new ArrayList();
private List <DataVariableUI> dvGenericListUI = new ArrayList();
private List <DataVariableUI> dvDateListUI = new ArrayList();
private List <DataVariableUI> dvNumericListUI = new ArrayList();
private List <DataVariableUI> dvGenericFilteredListUI = new ArrayList();
private VarGroupingUI measureGrouping = new VarGroupingUI();
private VarGroupUIList measureGroupList;
private List <VarGroupUIList> filterGroupList;
private VarGroupingUI sourceGrouping = new VarGroupingUI();
private List <VarGroupingUI> filterGroupings = new ArrayList();
private List <SelectItem> studyFileIdSelectItems = new ArrayList();
private VisualizationDisplay visualizationDisplay;
private DataVariable xAxisVariable = new DataVariable();
private Long xAxisVariableId = new Long(0);
private StudyVersion studyVersion;
private Study study;
private StudyUI studyUI;
private Long studyFileId = new Long(0);
private Long studyId ;
private Metadata metadata;
private String xAxisUnits = "";
DataTable dataTable;
private boolean showCommands = false;
private boolean showMeasureVariables = false;
private boolean editXAxis = false;
private boolean editMeasure = false;
private boolean editSource = false;
private boolean editFilterGroup = false;
private boolean editMeasureGrouping = false;
private boolean addMeasureType = false;
private boolean addFilterType = false;
private boolean addMeasureGroup = false;
private boolean addFilterGroup = false;
private boolean addSourceGroup = false;
private boolean addFilterGrouping = false;
private boolean manageMeasureTypes = false;
private boolean manageFilterTypes = false;
private boolean editMeasureType = false;
private boolean editFilterType = false;
private boolean editFilterGrouping = false;
private String studyFileName = "";
private boolean xAxisSet = false;
private boolean hasMeasureGroups = false;
private boolean hasFilterGroupings = false;
private boolean hasFilterGroups = false;
private boolean edited = false;
private VarGroupUI editFragmentVarGroup = new VarGroupUI();
private VarGroupUI editFilterVarGroup = new VarGroupUI();
private VarGroupUI editMeasureVarGroup = new VarGroupUI();
private VarGroupUI editSourceVarGroup = new VarGroupUI();
private VarGroupingUI editFilterVarGrouping = new VarGroupingUI();
private boolean showFilterVariables = false;
private boolean selectFile = true;
public SetUpDataExplorationPage(){
}
public void init() {
super.init();
if (studyId == null){
studyId = new Long( getVDCRequestBean().getRequestParam("studyId"));
}
try {
Context ctx = new InitialContext();
editStudyFilesService = (EditStudyFilesService) ctx.lookup("java:comp/env/editStudyFiles");
} catch (NamingException e) {
e.printStackTrace();
FacesContext context = FacesContext.getCurrentInstance();
FacesMessage errMessage = new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), null);
context.addMessage(null, errMessage);
}
if (getStudyId() != null) {
editStudyFilesService.setStudyVersion(studyId);
study = editStudyFilesService.getStudyVersion().getStudy();
studyVersion = study.getEditVersion();
metadata = editStudyFilesService.getStudyVersion().getMetadata();
setFiles(editStudyFilesService.getCurrentFiles());
}
else {
FacesContext context = FacesContext.getCurrentInstance();
FacesMessage errMessage = new FacesMessage(FacesMessage.SEVERITY_ERROR, "The Study ID is null", null);
context.addMessage(null, errMessage);
//Should not get here.
//Must always be in a study to get to this page.
}
studyUI = new StudyUI(studyVersion, null);
studyFileIdSelectItems = loadStudyFileSelectItems();
}
public void resetStudyFileId(){
Object value= this.selectStudyFile.getValue();
studyFileName = this.selectStudyFile.getLabel();
Iterator iterator = study.getStudyFiles().iterator();
while (iterator.hasNext() ){
StudyFile studyFile = (StudyFile) iterator.next();
if (studyFile.getId().equals((Long) value)){
studyFileName = studyFile.getFileName();
}
}
studyFileId = (Long) value;
if (!studyFileId.equals(new Long(0))) {
loadDataTable();
showCommands = true;
selectFile = false;
}
}
private void loadDataTable(){
dataTable = new DataTable();
visualizationService.setDataTableFromStudyFileId(studyFileId);
dataTable = visualizationService.getDataTable();
varGroupings = dataTable.getVarGroupings();
dvList = dataTable.getDataVariables();
measureGrouping = new VarGroupingUI();
sourceGrouping = new VarGroupingUI();
loadVarGroupingUIs();
dvNumericListUI = loadDvListUIs(false);
dvDateListUI = loadDvListUIs(true);
xAxisVariable = visualizationService.getXAxisVariable(dataTable.getId());
xAxisVariableId = xAxisVariable.getId();
if (xAxisVariableId.intValue() > 0) {
xAxisSet = true;
} else {
xAxisSet = false;
editXAxisAction();
}
if (xAxisSet) {
for (DataVariableMapping mapping : xAxisVariable.getDataVariableMappings()) {
if (mapping.isX_axis()) {
xAxisUnits = mapping.getLabel();
}
}
}
if (measureGrouping.getVarGrouping() == null) {
addNewGrouping(measureGrouping, GroupingType.MEASURE);
} else {
if (!measureGrouping.getVarGroupUI().isEmpty()) {
hasMeasureGroups = true;
}
}
if (sourceGrouping.getVarGrouping() == null) {
addNewGrouping(sourceGrouping, GroupingType.SOURCE);
}
if (!filterGroupings.isEmpty()) {
hasFilterGroupings = true;
}
visualizationDisplay = dataTable.getVisualizationDisplay();
if (visualizationDisplay == null) {
visualizationDisplay = getDefaultVisualizationDisplay();
dataTable.setVisualizationDisplay(visualizationDisplay);
}
edited = false;
}
private VisualizationDisplay getDefaultVisualizationDisplay(){
VisualizationDisplay retVal = new VisualizationDisplay();
retVal.setDataTable(dataTable);
retVal.setShowDataTable(true);
retVal.setShowFlashGraph(true);
retVal.setShowImageGraph(true);
retVal.setDefaultDisplay(0);
retVal.setSourceInfoLabel("Source Info");
return retVal;
}
private void loadVarGroupingUIs(){
for (VarGrouping varGrouping: varGroupings ){
VarGroupingUI vgLocalUI = new VarGroupingUI();
vgLocalUI.setVarGrouping(varGrouping);
loadGroupingGroupTypes(vgLocalUI);
vgLocalUI.setVarGroupTypesUI();
setVarGroupUI(vgLocalUI);
if (varGrouping.getGroupingType().equals(GroupingType.MEASURE)){
measureGrouping = vgLocalUI;
} else if (varGrouping.getGroupingType().equals(GroupingType.SOURCE)){
sourceGrouping = vgLocalUI;
} else {
filterGroupings.add(vgLocalUI);
}
setVarGroupUIList(vgLocalUI);
}
}
public List<VarGrouping> getVarGroupings() {
return varGroupings;
}
public void setVarGroupings(List<VarGrouping> varGroupings) {
this.varGroupings = varGroupings;
}
public void loadGroupingGroupTypes(VarGroupingUI varGroupingUIIn) {
varGroupingUIIn.setVarGroupTypesUI(new ArrayList());
for (VarGroupType varGroupType: varGroupingUIIn.getVarGrouping().getVarGroupTypes()){
VarGroupTypeUI varGroupTypeUI = new VarGroupTypeUI();
varGroupTypeUI.setVarGroupType(varGroupType);
varGroupTypeUI.setEditMode(false);
varGroupingUIIn.getVarGroupTypesUI().add(varGroupTypeUI);
}
}
public void setMeasureGroups(){}
public void setMeasureGroupTypes(){}
public List<VarGroupTypeUI> getMeasureGroupTypes() {
if (measureGrouping == null) return null;
return (List) measureGrouping.getVarGroupTypesUI();
}
public List <DataVariableUI> loadDvListUIs(boolean isDate){
List <DataVariableUI> dvListUILocG = new ArrayList();
for (DataVariable dataVariable : dvList){
if ((isDate && ("date".equals(dataVariable.getFormatCategory()) || "time".equals(dataVariable.getFormatCategory()))
&& !hasGapsInTimeVariable(dataVariable) ) ||
(!isDate && dataVariable.getVariableFormatType().getName().equals("numeric"))) {
DataVariableUI dataVariableUI = new DataVariableUI();
dataVariableUI.setDataVariable(dataVariable);
dataVariableUI.setSelected(false);
dataVariableUI.setDisplay(true);
dvListUILocG.add(dataVariableUI);
}
}
return dvListUILocG;
}
public boolean hasGapsInTimeVariable(DataVariable timeVariable){
StudyFile sf = dataTable.getStudyFile();
try {
File tmpSubsetFile = File.createTempFile("tempsubsetfile.", ".tab");
Set<Integer> fields = new LinkedHashSet<Integer>();
fields.add(timeVariable.getFileOrder());
FieldCutter fc = new DvnJavaFieldCutter();
fc.subsetFile(
sf.getFileSystemLocation(),
tmpSubsetFile.getAbsolutePath(),
fields,
dataTable.getCaseQuantity() );
if (tmpSubsetFile.exists()) {
List <String> fileList = new ArrayList();
BufferedReader reader = new BufferedReader(new FileReader(tmpSubsetFile));
String line = null;
while ((line=reader.readLine()) != null) {
String check = line.toString();
fileList.add(check);
}
for (Object inObj: fileList){
String nextStr = (String) inObj;
String[] columnDetail = nextStr.split("\t");
String[] test = columnDetail;
if (test.length == 0){
return true;
}
if (test[0].isEmpty()){
return true;
}
}
}
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
private void setVarGroupUI(VarGroupingUI varGroupingUI) {
List<VarGroupUI> varGroupUIList = new ArrayList();
VarGrouping varGroupingIn = varGroupingUI.getVarGrouping();
varGroupingIn.getVarGroupTypes();
List<VarGroup> varGroups = new ArrayList();
varGroups = (List<VarGroup>) varGroupingIn.getVarGroups();
if (varGroups != null) {
for (VarGroup varGroup : varGroups) {
VarGroupUI varGroupUILoc = new VarGroupUI();
varGroupUILoc.setVarGroup(varGroup);
varGroupUILoc.getVarGroup().getName();
varGroupUILoc.setVarGroupTypes(new ArrayList());
varGroupUILoc.setVarGroupTypesSelectItems(new ArrayList());
varGroupUILoc.setDataVariablesSelected(new ArrayList());
List<VarGroupType> varGroupTypes = new ArrayList();
List<DataVariable> dataVariables = new ArrayList();
dataVariables = (List<DataVariable>) visualizationService.getDataVariableMappingsFromDataTableGroup(dataTable, varGroup);
int selectedVariables = 0;
if (dataVariables != null) {
for (DataVariable dataVariable : dataVariables) {
varGroupUILoc.getDataVariablesSelected().add(new Long(dataVariable.getId()));
selectedVariables++;
}
}
varGroupUILoc.setNumberOfVariablesSelected(new Long(selectedVariables));
varGroupTypes = (List<VarGroupType>) varGroupUILoc.getVarGroup().getGroupTypes();
String groupTypesSelectedString = "";
if (varGroupTypes != null) {
for (VarGroupType varGroupType : varGroupTypes) {
VarGroupTypeUI varGroupTypeUI = new VarGroupTypeUI();
varGroupTypeUI.setVarGroupType(varGroupType);
varGroupTypeUI.getVarGroupType().getName();
varGroupType.getName();
varGroupUILoc.getVarGroupTypesSelectItems().add(varGroupTypeUI);
if (groupTypesSelectedString.isEmpty()) {
groupTypesSelectedString += varGroupTypeUI.getVarGroupType().getName();
} else {
groupTypesSelectedString = groupTypesSelectedString + ", " + varGroupTypeUI.getVarGroupType().getName();
}
}
varGroupUILoc.setGroupTypesSelectedString(groupTypesSelectedString);
}
hasFilterGroups = true;
varGroupUIList.add(varGroupUILoc);
}
}
varGroupingUI.setVarGroupUI(varGroupUIList);
}
public VarGroupUIList getMeasureGroups() {
return measureGrouping.getVarGroupUIList();
}
public List<VarGroupUIList> getFilterGroupList() {
return filterGroupList;
}
public void setFilterGroupList(List<VarGroupUIList> filterGroupList) {
this.filterGroupList = filterGroupList;
}
public VarGroupUIList getMeasureGroupList() {
return measureGroupList;
}
public void setMeasureGroupList(VarGroupUIList measureGroupList) {
this.measureGroupList = measureGroupList;
}
public List<VarGroupUI> getSourceGroups() {
return (List) sourceGrouping.getVarGroupUI();
}
public VarGroupingUI getMeasureGrouping() {
return measureGrouping;
}
private boolean hasAssignedGroups(VarGroupType varGroupTypeIn){
VarGrouping varGrouping = varGroupTypeIn.getVarGrouping();
if (varGrouping != null) {
if (varGrouping.getGroupingType().equals(GroupingType.FILTER)) {
for (VarGroupingUI testGrouping : filterGroupings) {
if (testGrouping.getVarGrouping().getName().equals(varGrouping.getName())) {
for (VarGroup varGroup : varGrouping.getVarGroups()) {
for (VarGroupType testGroupType : varGroup.getGroupTypes()) {
if (testGroupType.getName().equals(varGroupTypeIn.getName())) {
return true;
}
}
}
}
}
}
if (varGrouping.getGroupingType().equals(GroupingType.MEASURE)) {
for (VarGroup varGroup : measureGrouping.getVarGrouping().getVarGroups()) {
for (VarGroupType testGroupType : varGroup.getGroupTypes()) {
if (testGroupType.getName().equals(varGroupTypeIn.getName())) {
return true;
}
}
}
}
}
return false;
}
private boolean hasAssignedGroupTypes(VarGroup varGroupIn) {
if (!varGroupIn.getGroupTypes().isEmpty()) {
return true;
}
return false;
}
public void deleteGroupType(ActionEvent ae) {
boolean measure = false;
boolean filter = false;
UIComponent uiComponent = ae.getComponent().getParent();
while (!(uiComponent instanceof HtmlDataTable)) {
uiComponent = uiComponent.getParent();
}
HtmlDataTable dataTable2 = (HtmlDataTable) uiComponent;
if (uiComponent.equals(dataTableManageMeasureGroupType)) {
measure = true;
}
if (uiComponent.equals(dataTableMeasureGroupType)) {
measure = true;
}
if (uiComponent.equals(dataTableManageFilterGroupType)) {
filter = true;
}
if (uiComponent.equals(dataTableFilterGroupType)) {
filter = true;
}
if (dataTable2.getRowCount() > 0) {
VarGroupTypeUI varGroupTypeUI2 = (VarGroupTypeUI) dataTable2.getRowData();
VarGroupType varGroupType = varGroupTypeUI2.getVarGroupType();
List varGroupTypeList = (List) dataTable2.getValue();
if (hasAssignedGroups(varGroupType)) {
FacesMessage message = new FacesMessage("You may not delete a type that is assigned to a measure or filter.");
FacesContext fc = FacesContext.getCurrentInstance();
fc.addMessage(validateButton.getClientId(fc), message);
return;
}
Iterator iterator = varGroupTypeList.iterator();
List deleteList = new ArrayList();
while (iterator.hasNext()) {
VarGroupTypeUI varGroupTypeUI = (VarGroupTypeUI) iterator.next();
VarGroupType data = varGroupTypeUI.getVarGroupType();
deleteList.add(data);
}
visualizationService.removeCollectionElement(deleteList, dataTable2.getRowIndex());
if (filter) {
for (VarGroupingUI varGroupingUI : filterGroupings) {
if (varGroupingUI.getVarGrouping() == (varGroupType.getVarGrouping())) {
varGroupingUI.getVarGroupTypesUI().remove(varGroupTypeUI2);
varGroupingUI.getVarGrouping().getVarGroupTypes().remove(varGroupType);
}
}
if (editFilterVarGroup != null && editFilterVarGroup.getVarGroup() != null) {
removeTypeFromGroupUI(editFilterVarGroup, varGroupTypeUI2);
}
}
if (measure) {
measureGrouping.getVarGroupTypesUI().remove(varGroupTypeUI2);
measureGrouping.getVarGrouping().getVarGroupTypes().remove(varGroupType);
if (editMeasureVarGroup != null && editMeasureVarGroup.getVarGroup() != null) {
removeTypeFromGroupUI(editMeasureVarGroup, varGroupTypeUI2);
}
}
}
edited = true;
}
private void resetDataVariableListForVarGroupUI(VarGroupUI varGroupUIin){
dvGenericFilteredListUI.clear();
dvGenericListUI = dvNumericListUI;
for (DataVariableUI dataVariableUI : dvGenericListUI) {
dataVariableUI.setSelected(false);
if (varGroupUIin.getDataVariablesSelected() != null) {
for (Object dv : varGroupUIin.getDataVariablesSelected()) {
Long testId = (Long) dv;
if (testId.equals(dataVariableUI.getDataVariable().getId())) {
dataVariableUI.setSelected(true);
}
}
}
dvGenericFilteredListUI.add(dataVariableUI);
}
}
private List<VarGroupTypeUI> resetVarGroupTypesUIForVarGroupUI(VarGroupUI varGroupUIin, VarGroupingUI varGroupingUIin){
List<VarGroupTypeUI> returnList = new ArrayList<VarGroupTypeUI>();
List<VarGroupTypeUI> allVarGroupTypes = (List<VarGroupTypeUI>) varGroupingUIin.getVarGroupTypesUI();
for (VarGroupTypeUI varGroupTypeUI : allVarGroupTypes) {
varGroupTypeUI.setSelected(false);
List<VarGroupType> varGroupTypes = new ArrayList();
varGroupTypes = (List<VarGroupType>) varGroupUIin.getVarGroup().getGroupTypes();
if (varGroupTypes != null) {
for (VarGroupType varGroupType : varGroupTypes) {
if (varGroupType == varGroupTypeUI.getVarGroupType()) {
varGroupTypeUI.setSelected(true);
}
}
}
returnList.add(varGroupTypeUI);
}
return returnList;
}
public void editMeasureGroup(ActionEvent ae) {
UIComponent uiComponent = ae.getComponent().getParent();
while (!(uiComponent instanceof HtmlDataTable)) {
uiComponent = uiComponent.getParent();
}
HtmlDataTable tempTable = (HtmlDataTable) uiComponent;
VarGroupUI varGroupUI = (VarGroupUI) tempTable.getRowData();
resetDataVariableListForVarGroupUI(varGroupUI);
varGroupUI.setVarGroupTypes(resetVarGroupTypesUIForVarGroupUI(varGroupUI, measureGrouping));
editMeasureVarGroup = new VarGroupUI();
editMeasureVarGroup = varGroupUI;
cancelAddEdit();
getInputMeasureName().setValue(editMeasureVarGroup.getVarGroup().getName());
getInputMeasureUnits().setValue(editMeasureVarGroup.getVarGroup().getUnits());
editMeasure = true;
}
public void editSourceGroup (ActionEvent ae){
UIComponent uiComponent = ae.getComponent().getParent();
while (!(uiComponent instanceof HtmlDataTable)){
uiComponent = uiComponent.getParent();
}
HtmlDataTable tempTable = (HtmlDataTable) uiComponent;
VarGroupUI varGroupUI = (VarGroupUI) tempTable.getRowData();
resetDataVariableListForVarGroupUI(varGroupUI);
varGroupUI.setVarGroupTypes(new ArrayList());
editSourceVarGroup = varGroupUI;
cancelAddEdit();
getInputSourceName().setValue(editSourceVarGroup.getVarGroup().getName());
editSource = true;
}
public void editMeasureTypeAction(ActionEvent ae){
UIComponent uiComponent = ae.getComponent().getParent();
while (!(uiComponent instanceof HtmlDataTable)){
uiComponent = uiComponent.getParent();
}
HtmlDataTable tempTable = (HtmlDataTable) uiComponent;
VarGroupTypeUI varGroupTypeUI = (VarGroupTypeUI) tempTable.getRowData();
getEditMeasureGroupTypeName().setValue(varGroupTypeUI.getVarGroupType().getName());
getEditManageMeasureGroupTypeName().setValue(varGroupTypeUI.getVarGroupType().getName());
varGroupTypeUI.setEditMode(true);
editMeasureType = true;
}
public void editFilterType(ActionEvent ae){
UIComponent uiComponent = ae.getComponent().getParent();
while (!(uiComponent instanceof HtmlDataTable)){
uiComponent = uiComponent.getParent();
}
HtmlDataTable tempTable = (HtmlDataTable) uiComponent;
VarGroupTypeUI varGroupTypeUI = (VarGroupTypeUI) tempTable.getRowData();
varGroupTypeUI.setEditMode(true);
getEditFilterGroupTypeName().setValue(varGroupTypeUI.getVarGroupType().getName());
getEditManageFilterGroupTypeName().setValue(varGroupTypeUI.getVarGroupType().getName());
editFilterType = true;
}
public void editManageFilterType(ActionEvent ae){
UIComponent uiComponent = ae.getComponent().getParent();
while (!(uiComponent instanceof HtmlDataTable)){
uiComponent = uiComponent.getParent();
}
HtmlDataTable tempTable = (HtmlDataTable) uiComponent;
VarGroupTypeUI varGroupTypeUI = (VarGroupTypeUI) tempTable.getRowData();
varGroupTypeUI.setEditMode(true);
getEditManageFilterGroupTypeName().setValue(varGroupTypeUI.getVarGroupType().getName());
editFilterType = true;
}
public void saveFilterType(ActionEvent ae){
UIComponent uiComponent = ae.getComponent().getParent();
while (!(uiComponent instanceof HtmlDataTable)){
uiComponent = uiComponent.getParent();
}
HtmlDataTable tempTable = (HtmlDataTable) uiComponent;
VarGroupTypeUI varGroupTypeUI = (VarGroupTypeUI) tempTable.getRowData();
String getName = "";
if (tempTable.equals(dataTableManageFilterGroupType)) {
getName = (String) getEditManageFilterGroupTypeName().getValue();
} else {
getName = (String) getEditFilterGroupTypeName().getValue();
}
if (checkForDuplicateEntries(varGroupTypeUI.getVarGroupType().getVarGrouping(), getName, false, varGroupTypeUI.getVarGroupType() )){
return;
}
varGroupTypeUI.getVarGroupType().setName(getName);
varGroupTypeUI.setEditMode(false);
getEditManageFilterGroupTypeName().setValue("");
getEditFilterGroupTypeName().setValue("");
edited = true;
}
public void saveMeasureType(ActionEvent ae){
UIComponent uiComponent = ae.getComponent().getParent();
while (!(uiComponent instanceof HtmlDataTable)){
uiComponent = uiComponent.getParent();
}
HtmlDataTable tempTable = (HtmlDataTable) uiComponent;
VarGroupTypeUI varGroupTypeUI = (VarGroupTypeUI) tempTable.getRowData();
String getName = "";
if (tempTable.equals(dataTableManageMeasureGroupType)) {
getName = (String) getEditManageMeasureGroupTypeName().getValue();
} else {
getName = (String) ((String) getEditMeasureGroupTypeName().getValue());
}
if (checkForDuplicateEntries(varGroupTypeUI.getVarGroupType().getVarGrouping(), getName, false, varGroupTypeUI.getVarGroupType() )){
return;
}
varGroupTypeUI.getVarGroupType().setName(getName);
varGroupTypeUI.setEditMode(false);
edited = true;
}
public void editFilterGroup(ActionEvent ae ) {
UIComponent uiComponent = ae.getComponent().getParent();
while (!(uiComponent instanceof HtmlDataTable)) {
uiComponent = uiComponent.getParent();
}
HtmlDataTable tempTable = (HtmlDataTable) uiComponent;
/*
* We're getting the row index because passing in the filter was not working.
* we should have been able to get the varGroupUI in question directly from the table
* but the icefaces datatable inside an h:datatable was causing problems
* VarGroupUI varGroupUI = (VarGroupUI) tempTable.getRowData();
*
* SEK
*/
int index = tempTable.getRowIndex();
VarGroupingUI varGroupingUIin = (VarGroupingUI) ae.getComponent().getAttributes().get("grouping");
VarGroupUI varGroupUI = varGroupingUIin.getVarGroupUIList().getVarGroupUIList().get(index);
resetDataVariableListForVarGroupUI(varGroupUI);
varGroupUI.setVarGroupTypes(new ArrayList());
for (VarGroupingUI varGroupingUI : filterGroupings) {
if (varGroupingUI.getVarGrouping() == (varGroupUI.getVarGroup().getGroupAssociation())) {
varGroupUI.setVarGroupTypes(resetVarGroupTypesUIForVarGroupUI(varGroupUI, varGroupingUI));
}
}
editFilterVarGroup = varGroupUI;
cancelAddEdit();
getInputFilterGroupName().setValue(editFilterVarGroup.getVarGroup().getName());
editFilterGroup = true;
}
public void editFilterGroupingAction (ActionEvent ae){
UIComponent uiComponent = ae.getComponent().getParent();
while (!(uiComponent instanceof HtmlDataTable)){
uiComponent = uiComponent.getParent();
}
HtmlDataTable tempTable = (HtmlDataTable) uiComponent;
VarGroupingUI varGroupingUI = (VarGroupingUI) tempTable.getRowData();
editFilterVarGrouping = varGroupingUI;
cancelAddEdit();
getInputFilterGroupingName().setValue(editFilterVarGrouping.getVarGrouping().getName());
editFilterGrouping = true;
}
public void manageFilterGroupTypeAction (ActionEvent ae){
UIComponent uiComponent = ae.getComponent().getParent();
while (!(uiComponent instanceof HtmlDataTable)){
uiComponent = uiComponent.getParent();
}
HtmlDataTable tempTable = (HtmlDataTable) uiComponent;
VarGroupingUI varGroupingUI = (VarGroupingUI) tempTable.getRowData();
editFilterVarGrouping = varGroupingUI;
cancelAddEdit();
manageFilterTypes = true;
}
public void manageMeasureGroupTypeAction (){
cancelAddEdit();
manageMeasureTypes = true;
}
public void editMeasureGroupingAction (){
cancelAddEdit();
editMeasureGrouping = true;
getInputMeasureGroupingName().setValue(measureGrouping.getVarGrouping().getName());
}
public void editXAxisAction (){
dvGenericListUI = dvDateListUI;
Iterator iterator = dvGenericListUI.iterator();
dvGenericFilteredListUI.clear();
while (iterator.hasNext() ){
DataVariableUI dataVariableUI = (DataVariableUI) iterator.next();
dataVariableUI.setSelected(false);
if (dataVariableUI.getDataVariable().getId().equals(xAxisVariableId)){
dataVariableUI.setSelected(true);
}
dvGenericFilteredListUI.add(dataVariableUI);
}
cancelAddEdit();
getInputXAxisUnits().setValue(xAxisUnits);
editXAxis = true;
}
public void removeXAxisAction (){
xAxisVariable = new DataVariable();
xAxisVariableId = new Long(0);
xAxisSet = false;
xAxisUnits = "";
resetDVMappingsXAxis();
cancelAddEdit();
}
public void cancelFragment(){
cancelAddEdit();
}
public void saveXAxis(){
xAxisUnits = (String) getInputXAxisUnits().getValue();
Long SelectedId = new Long(0);
for(DataVariableUI dataVariableUI:dvGenericListUI){
for(DataVariableUI dvTest: dvGenericFilteredListUI){
if (dvTest.getDataVariable().equals(dataVariableUI.getDataVariable())){
dataVariableUI.setSelected(dvTest.isSelected());
}
}
}
int countSelected = 0;
for (DataVariableUI dataVariableUI: dvGenericListUI){
if (dataVariableUI.isSelected()){
SelectedId = dataVariableUI.getDataVariable().getId();
countSelected++;
}
}
if (countSelected > 1) {
FacesMessage message = new FacesMessage("You may not select more than one variable.");
FacesContext fc = FacesContext.getCurrentInstance();
fc.addMessage(validateButton.getClientId(fc), message);
}
if (countSelected == 1){
xAxisVariableId = SelectedId;
xAxisVariable = varService.getDataVariable(SelectedId);
resetDVMappingsXAxis();
xAxisSet = true;
}
if (countSelected == 0){
xAxisVariableId = SelectedId;
xAxisVariable = new DataVariable();
resetDVMappingsXAxis();
xAxisSet = false;
}
cancelAddEdit();
edited = true;
}
public void saveMeasureGrouping(){
String chkGroupName = (String) getInputMeasureGroupingName().getValue();
if (chkGroupName.isEmpty() || chkGroupName.trim().equals("") ) {
FacesMessage message = new FacesMessage("Please enter a Measure Label.");
FacesContext fc = FacesContext.getCurrentInstance();
fc.addMessage(validateButton.getClientId(fc), message);
return;
}
if (!getInputMeasureGroupingName().getValue().equals("")){
measureGrouping.getVarGrouping().setName((String) getInputMeasureGroupingName().getValue());
}
cancelAddEdit();
edited = true;
}
public void cancelMeasureGrouping(){
cancelAddEdit();
}
public void saveSourceFragment(){
String chkGroupName = (String) getInputSourceName().getValue();
if (chkGroupName.isEmpty() || chkGroupName.trim().equals("") ) {
FacesMessage message = new FacesMessage("Please enter a Source Name.");
FacesContext fc = FacesContext.getCurrentInstance();
fc.addMessage(validateButton.getClientId(fc), message);
return;
}
if(addSourceGroup){
if (checkForDuplicateEntries(editSourceVarGroup.getVarGroup().getGroupAssociation(), chkGroupName, true, null )){
return;
}
editSourceVarGroup.getVarGroup().setName(chkGroupName);
addSourceGroupSave();
} else {
if (checkForDuplicateEntries(editSourceVarGroup.getVarGroup().getGroupAssociation(), chkGroupName, true, editSourceVarGroup.getVarGroup() )){
return;
}
editSourceVarGroup.getVarGroup().setName(chkGroupName);
}
editSourceVarGroup.getVarGroup().setGroupAssociation(sourceGrouping.getVarGrouping());
saveGroupFragment(editSourceVarGroup);
editSourceVarGroup = null;
cancelAddEdit();
edited = true;
}
public void saveMeasureFragment(){
String chkGroupName = (String) getInputMeasureName().getValue();
if (chkGroupName.isEmpty() || chkGroupName.trim().equals("") ) {
FacesMessage message = new FacesMessage("Please enter a Measure Name.");
FacesContext fc = FacesContext.getCurrentInstance();
fc.addMessage(validateButton.getClientId(fc), message);
return;
}
if(addMeasureGroup){
if (checkForDuplicateEntries(editMeasureVarGroup.getVarGroup().getGroupAssociation(), chkGroupName, true, null )){
return;
}
editMeasureVarGroup.getVarGroup().setName(chkGroupName);
editMeasureVarGroup.getVarGroup().setUnits((String) getInputMeasureUnits().getValue());
addMeasureGroupSave();
} else {
if (checkForDuplicateEntries(editMeasureVarGroup.getVarGroup().getGroupAssociation(), chkGroupName, true, editMeasureVarGroup.getVarGroup() )){
return;
}
editMeasureVarGroup.getVarGroup().setName(chkGroupName);
editMeasureVarGroup.getVarGroup().setUnits((String) getInputMeasureUnits().getValue());
}
saveGroupFragment(editMeasureVarGroup);
saveGroupTypes(editMeasureVarGroup);
setVarGroupUIList(measureGrouping);
editMeasureVarGroup = null;
cancelAddEdit();
edited = true;
}
private void setVarGroupUIList(VarGroupingUI varGroupingUI){
varGroupingUI.setVarGroupUIList( new VarGroupUIList ((List)varGroupingUI.getVarGroupUI(), true));
}
public void saveFilterFragment(ActionEvent ae){
String chkGroupName = (String) getInputFilterGroupName().getValue();
if (chkGroupName.isEmpty() || chkGroupName.trim().equals("")) {
FacesMessage message = new FacesMessage("Please enter a Filter Name.");
FacesContext fc = FacesContext.getCurrentInstance();
fc.addMessage(validateButton.getClientId(fc), message);
return;
}
if(addFilterGroup){
if (checkForDuplicateEntries(editFilterVarGroup.getVarGroup().getGroupAssociation(), chkGroupName, true, null )){
return;
}
addFilterGroupSave();
} else {
if (checkForDuplicateEntries(editFilterVarGroup.getVarGroup().getGroupAssociation(), chkGroupName, true, editFilterVarGroup.getVarGroup() )){
return;
}
}
editFilterVarGroup.getVarGroup().setName(chkGroupName);
saveGroupFragment(editFilterVarGroup);
saveGroupTypes(editFilterVarGroup);
if (editFilterVarGrouping!=null){
setVarGroupUIList(editFilterVarGrouping);
}
editFilterVarGroup = null;
getInputFilterGroupName().setValue("");
cancelAddEdit();
edited = true;
}
private void saveGroupFragment(VarGroupUI varGroupIn){
updateVariablesByGroup(varGroupIn);
updateGroupTypesByGroup(varGroupIn);
}
private void saveGroupTypes(VarGroupUI varGroupIn){
List <VarGroupType> removeList = new ArrayList();
for (VarGroupTypeUI varGroupTypeTest : varGroupIn.getVarGroupTypes()){
if (!varGroupTypeTest.isSelected()){
VarGroupType varGroupTypeRemove = varGroupTypeTest.getVarGroupType();{
for (VarGroupType varGroupType :varGroupIn.getVarGroup().getGroupTypes()){
if (varGroupTypeRemove.getName().equals(varGroupType.getName())){
removeList.add(varGroupTypeRemove);
}
}
}
}
}
if (removeList.size() > 0){
for (VarGroupType removeType: removeList){
varGroupIn.getVarGroup().getGroupTypes().remove(removeType);
}
}
}
private void updateVariablesByGroup(VarGroupUI varGroupUIin) {
List<Long> priorVariablesSelected = new ArrayList();
List<Long> newVariablesSelected = new ArrayList();
List<Long> variablesToDelete = new ArrayList();
List<Long> variablesToAdd = new ArrayList();
if (varGroupUIin.getDataVariablesSelected() != null) {
for (Long id : varGroupUIin.getDataVariablesSelected()) {
priorVariablesSelected.add(id);
}
varGroupUIin.getDataVariablesSelected().clear();
} else {
varGroupUIin.setDataVariablesSelected(new ArrayList());
}
for (DataVariableUI dataVariableUI : dvGenericListUI) {
for (DataVariableUI dvTest : dvGenericFilteredListUI) {
if (dvTest.getDataVariable().equals(dataVariableUI.getDataVariable())) {
dataVariableUI.setSelected(dvTest.isSelected());
}
}
}
int countSelected = 0;
for (DataVariableUI dataVariableUI : dvGenericListUI) {
if (dataVariableUI.isSelected()) {
newVariablesSelected.add(dataVariableUI.getDataVariable().getId());
varGroupUIin.getDataVariablesSelected().add(dataVariableUI.getDataVariable().getId());
countSelected++;
}
}
varGroupUIin.setNumberOfVariablesSelected(new Long(countSelected));
for (int i = 0; i < priorVariablesSelected.size(); i++) {
boolean match = false;
for (int j = 0; j < newVariablesSelected.size(); j++) {
if (priorVariablesSelected.get(i).equals(newVariablesSelected.get(j))) {
match = true;
}
}
if (!match) {
variablesToDelete.add(priorVariablesSelected.get(i));
}
}
for (int i = 0; i < newVariablesSelected.size(); i++) {
boolean match = false;
for (int j = 0; j < priorVariablesSelected.size(); j++) {
if (newVariablesSelected.get(i).equals(priorVariablesSelected.get(j))) {
match = true;
}
}
if (!match) {
variablesToAdd.add(newVariablesSelected.get(i));
}
}
if (!variablesToDelete.isEmpty()) {
deleteVariablesFromGroup(varGroupUIin.getVarGroup(), variablesToDelete);
}
if (!variablesToAdd.isEmpty()) {
addDVMappingsByGroup(varGroupUIin, variablesToAdd);
}
}
private void updateGroupTypesByGroup(VarGroupUI varGroupUIin) {
if (varGroupUIin.getVarGroupTypesSelectItems() != null) {
varGroupUIin.getVarGroupTypesSelectItems().clear();
} else {
varGroupUIin.setVarGroupTypesSelectItems(new ArrayList());
}
for (VarGroupTypeUI varGroupTypeUI : varGroupUIin.getVarGroupTypes()) {
if (varGroupTypeUI.isSelected()) {
varGroupUIin.getVarGroupTypesSelectItems().add(varGroupTypeUI);
}
}
VarGroup varGroup = varGroupUIin.getVarGroup();
varGroup.getGroupTypes().clear();
String groupTypesSelectedString = "";
for (VarGroupTypeUI vgtUI : varGroupUIin.getVarGroupTypesSelectItems()) {
varGroup.getGroupTypes().add(vgtUI.getVarGroupType());
if (groupTypesSelectedString.isEmpty()) {
groupTypesSelectedString += vgtUI.getVarGroupType().getName();
} else {
groupTypesSelectedString = groupTypesSelectedString + ", " + vgtUI.getVarGroupType().getName();
}
}
varGroupUIin.setGroupTypesSelectedString(groupTypesSelectedString);
}
public void saveFilterGrouping(){
String testString = (String) getInputFilterGroupingName().getValue();
boolean duplicates = false;
if (!testString.isEmpty()){
List filterVarGroupings = new ArrayList();
for (VarGroupingUI varGroupingUI : filterGroupings){
filterVarGroupings.add(varGroupingUI.getVarGrouping());
}
if (addFilterGrouping){
duplicates = visualizationService.checkForDuplicateGroupings(filterVarGroupings, testString, null );
} else {
duplicates = visualizationService.checkForDuplicateGroupings(filterVarGroupings, testString, editFilterVarGrouping.getVarGrouping());
}
if (duplicates) {
FacesContext fc = FacesContext.getCurrentInstance();
String fullErrorMessage = "This name already exists. Please enter another.<br></br>" ;
FacesMessage message = new FacesMessage(fullErrorMessage);
fc.addMessage(validateButton.getClientId(fc), message);
return;
}
if (addFilterGrouping) {
addFilterGroupingSave(testString);
cancelAddEdit();
} else {
if (!getInputFilterGroupingName().getValue().equals("")) {
editFilterVarGrouping.getVarGrouping().setName(testString);
}
cancelAddEdit();
}
editFilterVarGrouping = null;
} else {
FacesMessage message = new FacesMessage("Please enter a Filter Group Name.");
FacesContext fc = FacesContext.getCurrentInstance();
fc.addMessage(validateButton.getClientId(fc), message);
return;
}
edited = true;
}
public void addFilterGroupAction(ActionEvent ae) {
UIComponent uiComponent = ae.getComponent().getParent();
while (!(uiComponent instanceof HtmlDataTable)){
uiComponent = uiComponent.getParent();
}
editFilterVarGrouping = (VarGroupingUI) dataTableFilterGrouping.getRowData();
editFilterVarGroup = null;
editFilterVarGroup = addGroupingGroup(editFilterVarGrouping);
SessionRenderer.addCurrentSession("editFilterVarGroup");
SessionRenderer.render("editFilterVarGroup");
cancelAddEdit();
editFilterGroup = true;
addFilterGroup = true;
}
public void addMeasureGroup() {
editMeasureVarGroup = new VarGroupUI();
editMeasureVarGroup = addGroupingGroup(measureGrouping);
cancelAddEdit();
editMeasure = true;
addMeasureGroup = true;
}
public void addSourceGroup() {
editSourceVarGroup = addGroupingGroup(sourceGrouping);
cancelAddEdit();
editSource = true;
addSourceGroup = true;
}
private VarGroupUI addGroupingGroup(VarGroupingUI varGroupingUIIn){
VarGroupUI newElem = new VarGroupUI();
newElem.setVarGroup(new VarGroup());
newElem.getVarGroup().setGroupAssociation(varGroupingUIIn.getVarGrouping());
newElem.getVarGroup().setGroupTypes(new ArrayList());
newElem.setVarGroupTypes(new ArrayList());
newElem.getVarGroupTypes().clear();
List <VarGroupTypeUI> allVarGroupTypes = (List<VarGroupTypeUI>) varGroupingUIIn.getVarGroupTypesUI();
if (!allVarGroupTypes.isEmpty()){
for (VarGroupTypeUI varGroupTypeUI : allVarGroupTypes) {
varGroupTypeUI.setSelected(false);
newElem.getVarGroupTypes().add(varGroupTypeUI);
}
} else {
newElem.setVarGroupTypes(new ArrayList());
newElem.getVarGroupTypes().clear();
}
dvGenericListUI = dvNumericListUI;
loadEmptyVariableList();
return newElem;
}
private void loadEmptyVariableList(){
Iterator iterator = dvGenericListUI.iterator();
dvGenericFilteredListUI.clear();
while (iterator.hasNext() ){
DataVariableUI dataVariableUI = (DataVariableUI) iterator.next();
dataVariableUI.setSelected(false);
dvGenericFilteredListUI.add(dataVariableUI);
}
}
private void addMeasureGroupSave() {
int i = measureGrouping.getVarGrouping().getVarGroups().size();
measureGrouping.getVarGrouping().getVarGroups().add(i, editMeasureVarGroup.getVarGroup());
measureGrouping.getVarGroupUI().add(editMeasureVarGroup);
cancelAddEdit();
editMeasure = false;
addMeasureGroup = false;
}
private void addSourceGroupSave() {
int i = sourceGrouping.getVarGrouping().getVarGroups().size();
sourceGrouping.getVarGrouping().getVarGroups().add(i, editSourceVarGroup.getVarGroup());
sourceGrouping.getVarGroupUI().add(editSourceVarGroup);
cancelAddEdit();
editSource = false;
addSourceGroup = false;
}
private void addFilterGroupSave() {
editFilterVarGrouping.getVarGroupUI().add(editFilterVarGroup);
editFilterVarGrouping.getVarGrouping().getVarGroups().add(editFilterVarGroup.getVarGroup());
cancelAddEdit();
}
public void addMeasureTypeButton(){
addMeasureType = true;
}
public void addFilterTypeButton(){
addFilterType = true;
}
public void saveFilterTypeButton(){
boolean groupEdit = false;
VarGroupType newElem = new VarGroupType();
VarGrouping varGroupingTest = new VarGrouping();
if (editFilterVarGroup != null && editFilterVarGroup.getVarGroup() != null ) {
newElem.setVarGrouping(editFilterVarGroup.getVarGroup().getGroupAssociation());
varGroupingTest = editFilterVarGroup.getVarGroup().getGroupAssociation();
groupEdit = true;
} else {
newElem.setVarGrouping(editFilterVarGrouping.getVarGrouping());
varGroupingTest = editFilterVarGrouping.getVarGrouping();
}
newElem.setName((String)getInputFilterGroupTypeName().getValue());
if (newElem.getName().isEmpty()){
newElem.setName((String)getInputManageFilterGroupTypeName().getValue());
}
if (checkForDuplicateEntries(varGroupingTest, newElem.getName(), false, null )){
return;
}
for(VarGrouping varGrouping: varGroupings){
if (varGrouping == newElem.getVarGrouping()){
varGrouping.getVarGroupTypes().add(newElem);
}
}
VarGroupTypeUI varGroupTypeUI = new VarGroupTypeUI();
varGroupTypeUI.setVarGroupType(newElem);
for(VarGroupingUI varGroupingUI: filterGroupings){
if (varGroupingUI.getVarGrouping() == newElem.getVarGrouping()){
varGroupingUI.getVarGroupTypesUI().add(varGroupTypeUI);
varGroupingUI.getVarGrouping().getVarGroupTypes().add(newElem);
}
}
if (groupEdit){
addNewTypeToGroupUI(editFilterVarGroup, varGroupTypeUI);
}
addFilterType = false;
edited = true;
}
public void saveMeasureTypeButton(){
boolean groupEdit = false;
VarGroupType newElem = new VarGroupType();
if (editMeasureVarGroup != null && editMeasureVarGroup.getVarGroup() != null ) {
groupEdit = true;
}
newElem.setVarGrouping(measureGrouping.getVarGrouping());
newElem.setName((String)getInputMeasureGroupTypeName().getValue());
if (newElem.getName().isEmpty()){
newElem.setName((String)getInputManageMeasureGroupTypeName().getValue());
}
VarGrouping varGroupingTest = new VarGrouping();
if (editMeasureVarGroup != null && editMeasureVarGroup.getVarGroup() != null ) {
newElem.setVarGrouping(editMeasureVarGroup.getVarGroup().getGroupAssociation());
varGroupingTest = editMeasureVarGroup.getVarGroup().getGroupAssociation();
groupEdit = true;
} else {
newElem.setVarGrouping(measureGrouping.getVarGrouping());
varGroupingTest = measureGrouping.getVarGrouping();
}
if (checkForDuplicateEntries(varGroupingTest, newElem.getName(), false, null )){
return;
}
measureGrouping.getVarGrouping().getVarGroupTypes().add(newElem);
VarGroupTypeUI varGroupTypeUI = new VarGroupTypeUI();
varGroupTypeUI.setVarGroupType(newElem);
if (measureGrouping.getVarGroupTypesUI() == null){
measureGrouping.setVarGroupTypesUI(new ArrayList());
}
measureGrouping.getVarGroupTypesUI().add(varGroupTypeUI);
if (groupEdit){
addNewTypeToGroupUI(editMeasureVarGroup, varGroupTypeUI);
}
addMeasureType = false;
edited = true;
}
private boolean checkForDuplicateEntries(VarGrouping varGrouping, String name, boolean group, Object testObject){
boolean duplicates = visualizationService.checkForDuplicateEntries(varGrouping, name, group, testObject);
if (duplicates) {
FacesContext fc = FacesContext.getCurrentInstance();
String fullErrorMessage = "This name already exists. Please enter another.<br></br>" ;
FacesMessage message = new FacesMessage(fullErrorMessage);
fc.addMessage(validateButton.getClientId(fc), message);
}
return duplicates;
}
private void addNewTypeToGroupUI(VarGroupUI varGroupUI, VarGroupTypeUI varGroupTypeUI ){
varGroupUI.getVarGroupTypes().add(varGroupTypeUI);
}
private void removeTypeFromGroupUI(VarGroupUI varGroupUI, VarGroupTypeUI varGroupTypeUI ){
varGroupUI.getVarGroupTypes().remove(varGroupTypeUI);
}
public void cancelMeasureTypeButton(){
addMeasureType = false;
manageMeasureTypes = true;
}
public void cancelFilterTypeButton(){
addFilterType = false;
manageFilterTypes = true;
}
public void addMeasureGroupType() {
cancelAddEdit();
VarGroupType newElem = new VarGroupType();
newElem.setVarGrouping(measureGrouping.getVarGrouping());
measureGrouping.getVarGrouping().getVarGroupTypes().add(newElem);
VarGroupTypeUI varGroupTypeUI = new VarGroupTypeUI();
varGroupTypeUI.setVarGroupType(newElem);
varGroupTypeUI.setEditMode(true);
if (measureGrouping.getVarGroupTypesUI() == null){
measureGrouping.setVarGroupTypesUI(new ArrayList());
}
measureGrouping.getVarGroupTypesUI().add(varGroupTypeUI);
}
public void addFilterGroupType(ActionEvent ae) {
VarGroupType newElem = new VarGroupType();
newElem.setVarGrouping(editFilterVarGrouping.getVarGrouping());
editFilterVarGrouping.getVarGrouping().getVarGroupTypes().add(newElem);
VarGroupTypeUI varGroupTypeUI = new VarGroupTypeUI();
varGroupTypeUI.setVarGroupType(newElem);
varGroupTypeUI.setEditMode(true);
editFilterVarGrouping.getVarGroupTypesUI().add(varGroupTypeUI);
}
private void addNewGrouping(VarGroupingUI varGroupingUIin, GroupingType groupingType) {
VarGrouping varGrouping = new VarGrouping();
varGrouping.setGroupingType(groupingType);
varGrouping.setDataTable(dataTable);
varGrouping.setDataVariableMappings(new ArrayList());
varGrouping.setGroups(new ArrayList());
varGrouping.setVarGroupTypes(new ArrayList());
varGroupingUIin.setVarGrouping(varGrouping);
varGroupingUIin.setSelectedGroupId(new Long(0));
varGroupingUIin.setVarGroupTypesUI(new ArrayList());
varGroupingUIin.setVarGroupUI(new ArrayList());
if (groupingType.equals(GroupingType.MEASURE) || groupingType.equals(GroupingType.FILTER)){
loadGroupingGroupTypes(varGroupingUIin);
}
if (groupingType.equals(GroupingType.MEASURE) ){
varGrouping.setName("Measure");
}
if (groupingType.equals(GroupingType.SOURCE) ){
varGrouping.setName("Source");
}
dataTable.getVarGroupings().add(varGrouping);
varGroupingUIin.setVarGrouping(varGrouping);
}
public void addFilterGroupingAction() {
cancelAddEdit();
VarGrouping newElem = new VarGrouping();
newElem.setDataTable(dataTable);
addFilterGrouping = true;
editFilterGrouping = true;
}
private void addFilterGroupingSave(String name){
VarGroupingUI varGroupingUI = new VarGroupingUI();
addNewGrouping(varGroupingUI, GroupingType.FILTER);
varGroupingUI.getVarGrouping().setName(name);
filterGroupings.add(varGroupingUI);
}
public void deleteFilterGroup(ActionEvent ae) {
HtmlDataTable dataTable2 = dataTableFilterGroup;
/*
* Getting filter group from outer grouping
* similiar to issue with editFilterGroup with and outer h:datatable
* and inner ice datatable
* original code was
* VarGroupUI varGroupUI2 = (VarGroupUI) dataTable2.getRowData();
*/
int index = dataTable2.getRowIndex();
VarGroupingUI varGroupingUIin = (VarGroupingUI) ae.getComponent().getAttributes().get("grouping");
VarGroupUI varGroupUIin = varGroupingUIin.getVarGroupUIList().getVarGroupUIList().get(index);
if (dataTable2.getRowCount() > 0) {
VarGroupUI varGroupUI2 = varGroupUIin;
VarGroup varGroup = varGroupUI2.getVarGroup();
if (hasAssignedGroupTypes(varGroup)) {
FacesMessage message = new FacesMessage("You may not delete a group that is assigned to a type.");
FacesContext fc = FacesContext.getCurrentInstance();
fc.addMessage(validateButton.getClientId(fc), message);
return;
}
deleteVariablesFromGroup(varGroup);
List varGroupList = (List) dataTable2.getValue();
Iterator iterator = varGroupList.iterator();
List deleteList = new ArrayList();
while (iterator.hasNext()) {
VarGroupUI varGroupUI = (VarGroupUI) iterator.next();
VarGroup data = varGroupUI.getVarGroup();
deleteList.add(data);
}
visualizationService.removeCollectionElement(deleteList, dataTable2.getRowIndex());
for (VarGroupingUI varGroupingUI : filterGroupings) {
if (varGroupingUI.getVarGrouping() == (varGroup.getGroupAssociation())) {
varGroupingUI.getVarGroupUI().remove(varGroupUI2);
varGroupingUI.getVarGrouping().getVarGroups().remove(varGroup);;
setVarGroupUIList(varGroupingUI);
}
}
}
edited = true;
}
public void deleteMeasureGroup(){
HtmlDataTable dataTable2 = dataTableVarGroup;
if (dataTable2.getRowCount()>0) {
VarGroupUI varGroupUI2 = (VarGroupUI) dataTable2.getRowData();
VarGroup varGroup = varGroupUI2.getVarGroup();
if(hasAssignedGroupTypes(varGroup)){
FacesMessage message = new FacesMessage("You may not delete a group that is assigned to a type.");
FacesContext fc = FacesContext.getCurrentInstance();
fc.addMessage(validateButton.getClientId(fc), message);
return;
}
deleteVariablesFromGroup(varGroup);
List varGroupList = (List) dataTable2.getValue();
Iterator iterator = varGroupList.iterator();
List deleteList = new ArrayList();
while (iterator.hasNext() ){
VarGroupUI varGroupUI = (VarGroupUI) iterator.next();
VarGroup data = varGroupUI.getVarGroup();
deleteList.add(data);
}
visualizationService.removeCollectionElement(deleteList,dataTable2.getRowIndex());
measureGrouping.getVarGroupUI().remove(varGroupUI2);
measureGrouping.getVarGrouping().getVarGroups().remove(varGroup);
setVarGroupUIList(measureGrouping);
edited = true;
}
}
public void deleteSourceGroup(){
HtmlDataTable dataTable2 = dataTableSourceVarGroup;
if (dataTable2.getRowCount()>0) {
VarGroupUI varGroupUI2 = (VarGroupUI) dataTable2.getRowData();
VarGroup varGroup = varGroupUI2.getVarGroup();
deleteVariablesFromGroup(varGroup);
List varGroupList = (List) dataTable2.getValue();
Iterator iterator = varGroupList.iterator();
List deleteList = new ArrayList();
while (iterator.hasNext() ){
VarGroupUI varGroupUI = (VarGroupUI) iterator.next();
VarGroup data = varGroupUI.getVarGroup();
deleteList.add(data);
}
visualizationService.removeCollectionElement(deleteList,dataTable2.getRowIndex());
sourceGrouping.getVarGroupUI().remove(varGroupUI2);
sourceGrouping.getVarGrouping().getVarGroups().remove(varGroup);
edited = true;
}
}
public void deleteFilterGrouping(ActionEvent ae){
List <VarGroupType> removeListGroupType = new ArrayList();
List <VarGroup> removeListGroup= new ArrayList();
List <VarGroupType> typeList;
List <VarGroup> groupList;
HtmlDataTable dataTable2 = dataTableFilterGrouping;
VarGroupingUI varGroupingUI2 = (VarGroupingUI) dataTable2.getRowData();
for (VarGroupType groupType: varGroupingUI2.getVarGrouping().getVarGroupTypes()){
removeListGroupType.add(groupType);
}
typeList = new ArrayList(varGroupingUI2.getVarGrouping().getVarGroupTypes());
for (VarGroup group: varGroupingUI2.getVarGrouping().getVarGroups()){
removeListGroup.add(group);
}
groupList = new ArrayList(varGroupingUI2.getVarGrouping().getVarGroups());
if (dataTable2.getRowCount()>0) {
filterGroupings.remove(varGroupingUI2);
varGroupings.remove(varGroupingUI2.getVarGrouping());
}
for (VarGroupUI groupUI: varGroupingUI2.getVarGroupUI() ){
for (VarGroupTypeUI varGroupTypeTest : groupUI.getVarGroupTypes()) {
varGroupTypeTest.setSelected(false);
}
saveGroupTypes(groupUI);
}
for (VarGroup group: removeListGroup ){
visualizationService.removeCollectionElement(groupList,group);
}
for (VarGroupType groupType: removeListGroupType ){
visualizationService.removeCollectionElement(typeList,groupType);
}
visualizationService.removeCollectionElement(varGroupings,varGroupingUI2.getVarGrouping());
edited = true;
}
public String exit(){
if (edited){
setShowInProgressPopup(true);
return "";
}
return cancel();
}
public String cancel() {
visualizationService.cancel();
return returnToStudy();
}
private String returnToStudy() {
Long redirectVersionNumber = new Long(0);
if (studyVersion.getId() == null) {
redirectVersionNumber = study.getReleasedVersion().getVersionNumber();
} else {
redirectVersionNumber = studyVersion.getVersionNumber();
}
return "/study/StudyPage?faces-redirect=true&studyId=" + study.getId() + "&versionNumber=" + redirectVersionNumber + "&tab=files&vdcId=" + getVDCRequestBean().getCurrentVDCId();
}
boolean showInProgressPopup = false;
public boolean isShowInProgressPopup() {
return showInProgressPopup;
}
public void setShowInProgressPopup(boolean showInProgressPopup) {
this.showInProgressPopup = showInProgressPopup;
}
public void togglePopup(javax.faces.event.ActionEvent event) {
showInProgressPopup = !showInProgressPopup;
}
private void cancelAddEdit(){
getInputFilterGroupName().setValue("");
getInputFilterGroupTypeName().setValue("");
getInputFilterGroupingName().setValue("");
getInputMeasureGroupTypeName().setValue("");
getInputMeasureName().setValue("");
getInputMeasureGroupingName().setValue("");
getInputMeasureUnits().setValue("");
getInputVariableFilter().setValue("");
getInputVariableMeasure().setValue("");
getInputVariableGeneric().setValue("");
getMeasureCheckBox().setValue(false);
getFilterCheckBox().setValue(false);
editXAxis = false;
editMeasure = false;
editSource = false;
editFilterGroup = false;
editMeasureGrouping = false;
addMeasureType = false;
addFilterType = false;
addMeasureGroup = false;
addSourceGroup = false;
addFilterGroup = false;
addFilterGrouping = false;
editMeasureType = false;
editFilterType = false;
editFilterGrouping = false;
manageFilterTypes = false;
manageMeasureTypes = false;
}
public boolean validateForRelease(boolean messages) {
boolean valid = true;;
List returnListOfErrors = new ArrayList();
List duplicateVariables = new ArrayList();
String fullErrorMessage = "";
if (!visualizationService.validateDisplayOptions(dataTable)) {
if (messages) {
fullErrorMessage += "<br></br>Please select at least one view and the default view must be selected.<br></br>";
}
valid = false;
}
if (!xAxisSet || !visualizationService.validateXAxisMapping(dataTable, xAxisVariableId)) {
if (messages) {
fullErrorMessage += "<br></br>You must select one X-axis variable and it cannot be mapped to any Measure or Filter.<br></br>";
}
valid = false;
}
if (!visualizationService.validateAtLeastOneFilterMapping(dataTable, returnListOfErrors)) {
if (messages) {
if (!returnListOfErrors.isEmpty()) {
fullErrorMessage += "<br></br>Measure-filter combinations were found that would result in multiple variables selected at visualization. ";
boolean newgroup = false;
boolean firstVar = true;
for (Object errorObject : returnListOfErrors) {
if (errorObject instanceof VarGroup) {
firstVar = true;
if (newgroup) {
fullErrorMessage += "</li></ul>";
}
VarGroup vg = (VarGroup) errorObject;
fullErrorMessage += "<ul>";
fullErrorMessage += "<li>" + "Measure " + vg.getName() + " contains at least one variable with no associated filter.</li> ";
}
if (errorObject instanceof DataVariable) {
DataVariable dv = (DataVariable) errorObject;
if (firstVar) {
fullErrorMessage += "<li>Affected Variables: " + dv.getName();
} else {
fullErrorMessage += ", " + dv.getName();
}
newgroup = true;
firstVar = false;
}
}
fullErrorMessage += "</li></ul>";
fullErrorMessage += "To correct this, create filters to limit each measure filter combination to a single variable or assign only one variable to each measure.<br></br>";
}
}
valid = false;
}
returnListOfErrors.clear();
if (!visualizationService.validateAllGroupsAreMapped(dataTable, returnListOfErrors)) {
if (messages) {
if (!returnListOfErrors.isEmpty()) {
- fullErrorMessage += "<br></br>Measure-filter combinations were found that would result in no variables selected at visualization.<br></br>";
+ fullErrorMessage += "<br></br>Measure-filter combinations were found that would result in no variables selected at visualization.";
fullErrorMessage += "<ul>";
String filterErrorMessage = "";
int filterCount = 0;
String measureErrorMessage = "";
int measureCount = 0;
for (Object varGroupIn : returnListOfErrors) {
VarGroup varGroup = (VarGroup) varGroupIn;
VarGrouping varGrouping = varGroup.getGroupAssociation();
if (varGrouping.getGroupingType().equals(GroupingType.FILTER)) {
if (filterCount == 0) {
filterErrorMessage += varGroup.getName();
} else {
filterErrorMessage = filterErrorMessage + ", " + varGroup.getName();
}
filterCount++;
}
if (varGrouping.getGroupingType().equals(GroupingType.MEASURE)) {
if (measureCount == 0) {
measureErrorMessage += varGroup.getName();
} else {
measureErrorMessage = measureErrorMessage + ", " + varGroup.getName();
}
measureCount++;
}
}
if (filterCount == 1) {
fullErrorMessage = fullErrorMessage + "<li>Filter " + filterErrorMessage + " contains no variables.</li>";
}
if (filterCount > 1) {
fullErrorMessage = fullErrorMessage + "<li>Filters " + filterErrorMessage + " contain no variables.</li>";
}
if (measureCount == 1) {
fullErrorMessage = fullErrorMessage + "<li>Measure " + measureErrorMessage + " contains no variables.</li>";
}
if (measureCount > 1) {
fullErrorMessage = fullErrorMessage + "<li>Measures " + measureErrorMessage + " contain no variables.</li>";
}
fullErrorMessage += "</ul>";
fullErrorMessage += "To correct this, assign at least one variable or remove the empty measures or filters.<br></br>";
}
}
valid = false;
}
returnListOfErrors.clear();
if (!visualizationService.validateMoreThanZeroMeasureMapping(dataTable, returnListOfErrors)) {
if (messages) {
if (!returnListOfErrors.isEmpty()) {
- fullErrorMessage += "<br></br>At least one filter was found that is not mapped to any measures.<br></br>";;
+ fullErrorMessage += "<br></br>At least one filter was found that is not mapped to any measures.";;
boolean firstVar = true;
boolean newgroup = false;
for (Object errorObject : returnListOfErrors) {
if (errorObject instanceof VarGroup) {
firstVar = true;
VarGroup vg = (VarGroup) errorObject;
if (newgroup) {
fullErrorMessage += "</li></ul>";
}
fullErrorMessage += "<ul>";
fullErrorMessage += "<li>Filter " + vg.getName() + " contains at least one variable that is not assigned to any measure.</li>";
}
if (errorObject instanceof DataVariable) {
DataVariable dv = (DataVariable) errorObject;
if (firstVar) {
fullErrorMessage += "<li>Affected Variables: " + dv.getName();
} else {
fullErrorMessage += ", " + dv.getName();
}
newgroup = true;
firstVar = false;
}
}
fullErrorMessage += "</li></ul>";
fullErrorMessage += "To correct this, remove unassigned variables or assign them to measures.<br></br>";
}
}
valid = false;
}
returnListOfErrors.clear();
if (!visualizationService.validateOneMeasureMapping(dataTable, returnListOfErrors)) {
if (messages) {
if (!returnListOfErrors.isEmpty()) {
fullErrorMessage += "<br></br>Variables were found that are mapped to multiple measures. ";
boolean firstGroup = true;
boolean newvar = false;
for (Object dataVariableIn : returnListOfErrors) {
if (dataVariableIn instanceof DataVariable) {
if (newvar) {
fullErrorMessage += "</li></ul>";
}
fullErrorMessage += "<ul>";
DataVariable dataVariable = (DataVariable) dataVariableIn;
fullErrorMessage += "<li>Variable: " + dataVariable.getName() + "</li>";
firstGroup = true;
}
if (dataVariableIn instanceof VarGroup) {
VarGroup varGroup = (VarGroup) dataVariableIn;
if (firstGroup) {
fullErrorMessage += "<li>Measures: " + varGroup.getName();
} else {
fullErrorMessage += " , " + varGroup.getName();
}
newvar = true;
firstGroup = false;
}
}
}
fullErrorMessage += "</li></ul>";
fullErrorMessage += "To correct this, map each variable to a single measure.<br></br>";
}
valid = false;
}
returnListOfErrors.clear();
if (!visualizationService.validateOneFilterPerGrouping(dataTable, returnListOfErrors)) {
if (messages) {
if (!returnListOfErrors.isEmpty()) {
fullErrorMessage += "<br></br>Variables were found that are mapped to multiple filters within a single filter group. ";
boolean firstGroup = true;
boolean newvar = false;
for (Object dataVariableIn : returnListOfErrors) {
if (dataVariableIn instanceof DataVariable) {
DataVariable dataVariable = (DataVariable) dataVariableIn;
if (newvar) {
fullErrorMessage += "</li></ul>";
}
fullErrorMessage += "<ul>";
fullErrorMessage += "<li>Variable: " + dataVariable.getName() + "</li>";
firstGroup = true;
}
if (dataVariableIn instanceof VarGroup) {
VarGroup varGroup = (VarGroup) dataVariableIn;
if (firstGroup) {
fullErrorMessage += "<li>Filters: " + varGroup.getName();
} else {
fullErrorMessage += " , " + varGroup.getName();
}
firstGroup = false;
newvar = true;
}
}
}
fullErrorMessage += "</li></ul>";
fullErrorMessage += "To correct this, map each variable to a single filter within each group.<br></br>";
}
valid = false;
}
if (!visualizationService.validateAtLeastOneMeasureMapping(dataTable)) {
if (messages) {
fullErrorMessage += "<br></br>Measure-filter combinations were found that would result in no variables selected at visualization.<br></br>";
fullErrorMessage += " No Measures or filters configured.<br></br>";
fullErrorMessage += "To correct this, configure at least one measure or one measure-filter combination.<br></br>";
}
valid = false;
}
returnListOfErrors.clear();
duplicateVariables = visualizationService.getDuplicateMappings(dataTable, returnListOfErrors);
if (duplicateVariables.size() > 0) {
if (messages) {
if (!returnListOfErrors.isEmpty()) {
fullErrorMessage += "<br></br>Measure-filter combinations were found that would result in multiple variables selected at visualization. ";
boolean firstVar = true;
boolean newgroup = false;;
for (Object errorObject : returnListOfErrors) {
if (errorObject instanceof VarGroup) {
if (newgroup) {
fullErrorMessage += "</li></ul>";
}
fullErrorMessage += "<ul>";
firstVar = true;
VarGroup vg = (VarGroup) errorObject;
fullErrorMessage += "<li>Measure " + vg.getName() + " contains multiple variables with insufficient filters to make them uniquely selectable.</li>";
}
if (errorObject instanceof DataVariable) {
DataVariable dv = (DataVariable) errorObject;
if (firstVar) {
fullErrorMessage += "<li>Affected Variables: " + dv.getName();
} else {
fullErrorMessage += ", " + dv.getName();
}
newgroup = true;
firstVar = false;
}
}
fullErrorMessage += "</li></ul>";
fullErrorMessage += "To correct this, for measures where multiple variables are assigned, also assign each variable to a filter where the measure-filter combinations result in a single variable selected at visualization.<br></br>";
}
}
returnListOfErrors.clear();
valid = false;
}
if (valid && messages) {
getVDCRenderBean().getFlash().put("successMessage", "The Data Visualization is valid for release.");
}
if (!valid && messages) {
// add rounded corners to the validation message box
- fullErrorMessage = "This configuration is invalid so it cannot be released. " + fullErrorMessage;
+ fullErrorMessage = "This configuration is invalid so it cannot be released. <br></br>" + fullErrorMessage;
getVDCRenderBean().getFlash().put("warningMessage", fullErrorMessage);
}
return valid;
}
public String validate(){
validateForRelease(true);
return "";
}
public String release(){
if (validateForRelease(true)) {
dataTable.setVisualizationEnabled(true);
saveAndContinue();
return "";
}
return "";
}
public String unRelease(){
dataTable.setVisualizationEnabled(false);
saveAndContinue();
return "";
}
/*
public String saveAndExit(){
if (dataTable.isVisualizationEnabled()){
if (!validateForRelease(false)) {
FacesMessage message = new FacesMessage("Your current changes are invalid. Correct these issues or unrelease your visualization before saving. Click Validate button to get a full list of validation issues.");
FacesContext fc = FacesContext.getCurrentInstance();
fc.addMessage(validateButton.getClientId(fc), message);
return "";
}
}
save();
return ruturnToStudy();
}
*/
public String saveAndContinue(){
boolean successMessage = true;
if (dataTable.isVisualizationEnabled()){
if (!validateForRelease(false)) {
dataTable.setVisualizationEnabled(false);
FacesContext fc = FacesContext.getCurrentInstance();
getVDCRenderBean().getFlash().put("warningMessage","Your current changes are invalid. This visualization has been set to 'unreleased'. Click Validate button to get a full list of validation issues.");
successMessage = false;
}
}
visualizationService.saveAndContinue();
if (successMessage){
FacesContext fc = FacesContext.getCurrentInstance();
getVDCRenderBean().getFlash().put("successMessage","Successfully saved changes. You may exit or continue editing.");
}
edited = false;
return "";
}
//Removed unused private method
private void addDVMappingsByGroup(VarGroupUI varGroupUI, List addList){
if (!addList.isEmpty()){
for(Object dataVariableId: addList){
String id = dataVariableId.toString();
for(DataVariable dataVariable: dvList){
if (dataVariable.getId() !=null && dataVariable.getId().equals(new Long(id))){
DataVariableMapping dataVariableMapping = new DataVariableMapping();
dataVariableMapping.setDataTable(dataTable);
dataVariableMapping.setDataVariable(dataVariable);
dataVariableMapping.setGroup(varGroupUI.getVarGroup());
dataVariableMapping.setVarGrouping(varGroupUI.getVarGroup().getGroupAssociation());
dataVariableMapping.setX_axis(false);
dataVariable.getDataVariableMappings().add(dataVariableMapping);
for(VarGrouping varGrouping : varGroupings){
if (varGrouping.equals(varGroupUI.getVarGroup().getGroupAssociation())){
varGrouping.getDataVariableMappings().add(dataVariableMapping);
}
}
}
}
}
}
}
private void deleteVariablesFromGroup(VarGroup varGroup, List <Long> longList){
List <DataVariableMapping> removeList = new ArrayList();
List <DataVariable> checkList = new ArrayList(dvList);
List <DataVariable> dvRemoveList = new ArrayList();
List <DataVariableMapping> groupingRemoveList = new ArrayList();
for (DataVariable dataVariable: checkList){
for (Long id: longList){
if(id.equals(dataVariable.getId())){
dvRemoveList.add(dataVariable);
}
}
}
for (DataVariable dataVariable: dvRemoveList){
List <DataVariableMapping> deleteList = (List <DataVariableMapping>) dataVariable.getDataVariableMappings();
for (DataVariableMapping dataVariableMapping : deleteList ){
if (dataVariableMapping.getGroup() != null && !dataVariableMapping.isX_axis()
&& dataVariableMapping.getGroup().equals(varGroup) ) {
removeList.add(dataVariableMapping);
groupingRemoveList.add(dataVariableMapping);
}
}
}
for(DataVariableMapping dataVarMappingRemove : removeList){
visualizationService.removeCollectionElement(dataVarMappingRemove.getDataVariable().getDataVariableMappings(),dataVarMappingRemove);
}
for(DataVariableMapping dataVarMappingRemove : groupingRemoveList){
visualizationService.removeCollectionElement(dataVarMappingRemove.getVarGrouping().getDataVariableMappings(),dataVarMappingRemove);
}
}
private void deleteVariablesFromGroup(VarGroup varGroup){
List <DataVariableMapping> removeList = new ArrayList();
List <DataVariable> tempList = new ArrayList(dvList);
List <DataVariableMapping> groupingRemoveList = new ArrayList();
for (DataVariable dataVariable: tempList){
List <DataVariableMapping> deleteList = (List <DataVariableMapping>) dataVariable.getDataVariableMappings();
for (DataVariableMapping dataVariableMapping : deleteList ){
if (dataVariableMapping.getGroup() != null && !dataVariableMapping.isX_axis()
&& dataVariableMapping.getGroup().getName().equals(varGroup.getName())
&& dataVariableMapping.getVarGrouping().getGroupingType().equals(varGroup.getGroupAssociation().getGroupingType()))
removeList.add(dataVariableMapping);
}
for (DataVariableMapping dataVariableMapping : deleteList ){
if (dataVariableMapping.getGroup() != null && !dataVariableMapping.isX_axis()
&& dataVariableMapping.getGroup().getName().equals(varGroup.getName())
&& dataVariableMapping.getVarGrouping().getGroupingType().equals(varGroup.getGroupAssociation().getGroupingType()))
groupingRemoveList.add(dataVariableMapping);
}
}
for(DataVariableMapping dataVarMappingRemove : removeList){
visualizationService.removeCollectionElement(dataVarMappingRemove.getDataVariable().getDataVariableMappings(),dataVarMappingRemove);
}
for(DataVariableMapping dataVarMappingRemove : groupingRemoveList){
visualizationService.removeCollectionElement(dataVarMappingRemove.getVarGrouping().getDataVariableMappings(),dataVarMappingRemove);
}
}
private void resetDVMappingsXAxis(){
List <DataVariableMapping> removeList = new ArrayList();
List <DataVariable> tempList = new ArrayList(dvList);
for(DataVariable dataVariable: tempList){
List <DataVariableMapping> deleteList = (List <DataVariableMapping>) dataVariable.getDataVariableMappings();
for (DataVariableMapping dataVariableMapping : deleteList ){
if (dataVariableMapping.getGroup() == null) removeList.add(dataVariableMapping);
}
}
for(DataVariableMapping dataVarMappingRemove : removeList){
if (dataVarMappingRemove.getDataVariable() != null ){
visualizationService.removeCollectionElement(dataVarMappingRemove.getDataVariable().getDataVariableMappings(),dataVarMappingRemove);
}
}
if (xAxisVariableId != null && !xAxisVariableId.equals(new Long(0))){
for(DataVariable dataVariable: dvList){
if (dataVariable.getId() !=null && dataVariable.getId().equals(xAxisVariableId)){
DataVariableMapping dataVariableMapping = new DataVariableMapping();
dataVariableMapping.setDataTable(dataTable);
dataVariableMapping.setDataVariable(dataVariable);
dataVariableMapping.setGroup(null);
dataVariableMapping.setVarGrouping(null);
dataVariableMapping.setX_axis(true);
dataVariableMapping.setLabel(xAxisUnits);
dataVariable.getDataVariableMappings().add(dataVariableMapping);
}
}
}
}
public String save() {
visualizationService.saveAll();
return "";
}
private HtmlInputText inputXAxisUnits;
public HtmlInputText getInputXAxisUnits() {
return this.inputXAxisUnits;
}
public void setInputXAxisUnits(HtmlInputText inputXAxisUnits) {
this.inputXAxisUnits = inputXAxisUnits;
}
private HtmlInputText inputVariableGeneric;
public HtmlInputText getInputVariableGeneric() {
return this.inputVariableGeneric;
}
public void setInputVariableGeneric(HtmlInputText inputVariableGeneric) {
this.inputVariableGeneric = inputVariableGeneric;
}
private HtmlInputText inputVariableFilter;
public HtmlInputText getInputVariableFilter() {
return this.inputVariableFilter;
}
public void setInputVariableFilter(HtmlInputText inputVariableFilter) {
this.inputVariableFilter = inputVariableFilter;
}
private HtmlInputText inputVariableMeasure;
public HtmlInputText getInputVariableMeasure() {
return this.inputVariableMeasure;
}
public void setInputVariableMeasure(HtmlInputText inputVariableMeasure) {
this.inputVariableMeasure = inputVariableMeasure;
}
private HtmlInputText inputVariableSource;
public HtmlInputText getInputVariableSource() {
return this.inputVariableSource;
}
public void setInputVariableSource(HtmlInputText inputVariableSource) {
this.inputVariableSource = inputVariableSource;
}
private HtmlInputText inputMeasureName;
public HtmlInputText getInputMeasureName() {
return this.inputMeasureName;
}
public void setInputMeasureName(HtmlInputText inputMeasureName) {
this.inputMeasureName = inputMeasureName;
}
private HtmlInputText inputSourceName;
public HtmlInputText getInputSourceName() {
return this.inputSourceName;
}
public void setInputSourceName(HtmlInputText inputSourceName) {
this.inputSourceName = inputSourceName;
}
private HtmlInputText inputMeasureUnits;
public HtmlInputText getInputMeasureUnits() {
return this.inputMeasureUnits;
}
public void setInputMeasureUnits(HtmlInputText inputMeasureUnits) {
this.inputMeasureUnits = inputMeasureUnits;
}
private HtmlInputText inputGroupTypeName;
public HtmlInputText getInputGroupTypeName() {
return this.inputGroupTypeName;
}
public void setInputGroupTypeName(HtmlInputText inputGroupTypeName) {
this.inputGroupTypeName = inputGroupTypeName;
}
private HtmlInputText inputFilterGroupTypeName;
public HtmlInputText getInputFilterGroupTypeName() {
return this.inputFilterGroupTypeName;
}
public void setInputFilterGroupTypeName(HtmlInputText inputFilterGroupTypeName) {
this.inputFilterGroupTypeName = inputFilterGroupTypeName;
}
private HtmlInputText inputMeasureGroupTypeName;
public HtmlInputText getInputMeasureGroupTypeName() {
return this.inputMeasureGroupTypeName;
}
public void setInputMeasureGroupTypeName(HtmlInputText inputMeasureGroupTypeName) {
this.inputMeasureGroupTypeName = inputMeasureGroupTypeName;
}
private HtmlInputText inputManageMeasureGroupTypeName;
public HtmlInputText getInputManageMeasureGroupTypeName() {
return this.inputManageMeasureGroupTypeName;
}
public void setInputManageMeasureGroupTypeName(HtmlInputText inputMeasureGroupTypeName) {
this.inputManageMeasureGroupTypeName = inputMeasureGroupTypeName;
}
private HtmlInputText inputManageFilterGroupTypeName;
public HtmlInputText getInputManageFilterGroupTypeName() {
return this.inputManageFilterGroupTypeName;
}
public void setInputManageFilterGroupTypeName(HtmlInputText inputFilterGroupTypeName) {
this.inputManageFilterGroupTypeName = inputFilterGroupTypeName;
}
private HtmlInputText inputMeasureGroupingName;
public HtmlInputText getInputMeasureGroupingName() {
return this.inputMeasureGroupingName;
}
public void setInputMeasureGroupingName(HtmlInputText inputMeasureGroupingName) {
this.inputMeasureGroupingName = inputMeasureGroupingName;
}
private HtmlInputText editGroupTypeName;
public HtmlInputText getEditGroupTypeName() {
return this.editGroupTypeName;
}
public void setEditGroupTypeName(HtmlInputText editGroupTypeName) {
this.editGroupTypeName = editGroupTypeName;
}
private HtmlInputText editFilterGroupTypeName;
public HtmlInputText getEditFilterGroupTypeName() {
return this.editFilterGroupTypeName;
}
public void setEditFilterGroupTypeName(HtmlInputText editFilterGroupTypeName) {
this.editFilterGroupTypeName = editFilterGroupTypeName;
}
private HtmlInputText editMeasureGroupTypeName;
public HtmlInputText getEditMeasureGroupTypeName() {
return this.editMeasureGroupTypeName;
}
public void setEditMeasureGroupTypeName(HtmlInputText editMeasureGroupTypeName) {
this.editMeasureGroupTypeName = editMeasureGroupTypeName;
}
private HtmlInputText editManageFilterGroupTypeName;
public HtmlInputText getEditManageFilterGroupTypeName() {
return this.editManageFilterGroupTypeName;
}
public void setEditManageFilterGroupTypeName(HtmlInputText editManageFilterGroupTypeName) {
this.editManageFilterGroupTypeName = editManageFilterGroupTypeName;
}
private HtmlInputText editManageMeasureGroupTypeName;
public HtmlInputText getEditManageMeasureGroupTypeName() {
return this.editManageMeasureGroupTypeName;
}
public void setEditManageMeasureGroupTypeName(HtmlInputText editManageMeasureGroupTypeName) {
this.editManageMeasureGroupTypeName = editManageMeasureGroupTypeName;
}
public List<SelectItem> loadStudyFileSelectItems(){
List selectItems = new ArrayList<SelectItem>();
selectItems.add(new SelectItem(0, "Select a File"));
for (FileMetadata fileMetaData: studyVersion.getFileMetadatas()){
if (fileMetaData.getStudyFile().isSubsettable()){
selectItems.add(new SelectItem(fileMetaData.getStudyFile().getId(), fileMetaData.getStudyFile().getFileName()));
}
}
return selectItems;
}
public void updateGenericGroupVariableList (String checkString){
for(DataVariableUI dataVariableUI:dvGenericListUI){
for(DataVariableUI dvTest: dvGenericFilteredListUI){
if (dvTest.getDataVariable().equals(dataVariableUI.getDataVariable())){
dataVariableUI.setSelected(dvTest.isSelected());
}
}
}
dvGenericFilteredListUI.clear();
for(DataVariableUI dataVariableUI:dvGenericListUI){
dataVariableUI.setDisplay(false);
if (dataVariableUI.getDataVariable().getName().contains(checkString)) {
dataVariableUI.setDisplay(true);
DataVariableUI dvAdd = new DataVariableUI();
dvAdd.setDataVariable(dataVariableUI.getDataVariable());
dvAdd.setSelected(dataVariableUI.isSelected());
dvAdd.setDisplay(true);
dvGenericFilteredListUI.add(dvAdd);
}
}
}
public String updateMeasureList(){
String checkString = (String) getInputVariableMeasure().getValue();
updateGenericGroupVariableList(checkString);
selectOneMeasureVariableClick();
return "";
}
public String updateFilterList(){
String checkString = (String) getInputVariableFilter().getValue();
updateGenericGroupVariableList(checkString);
selectOneFilterVariableClick();
return "";
}
public String updateXAxisList(){
String checkString = (String) getInputVariableGeneric().getValue();
updateGenericGroupVariableList(checkString);
return "";
}
public String updateSourceList(){
String checkString = (String) getInputVariableSource().getValue();
updateGenericGroupVariableList(checkString);
return "";
}
public void selectAllMeasureVariables(ValueChangeEvent ce){
selectAllVariablesPrivate((Boolean)measureCheckBox.getValue());
forceRender(ce);
}
public void selectAllFilterVariables(ValueChangeEvent ce){
selectAllVariablesPrivate((Boolean)filterCheckBox.getValue());
forceRender(ce);
}
public void selectAllFilterVariablesClick(){
boolean value = (Boolean)filterCheckBox.getValue();
selectAllVariablesPrivate(value);
}
public void selectAllMeasureVariablesClick(){
boolean value = (Boolean)measureCheckBox.getValue();
selectAllVariablesPrivate(value);
}
public void selectAllSourceVariablesClick(){
boolean value = (Boolean)sourceCheckBox.getValue();
selectAllVariablesPrivate(value);
}
public void selectOneFilterVariableClick(){
boolean setSelected = checkSelectAllVariablesPrivate();
filterCheckBox.setSelected(setSelected) ;
}
public void selectOneMeasureVariableClick(){
boolean setSelected = checkSelectAllVariablesPrivate();
measureCheckBox.setSelected(setSelected) ;
}
public void selectOneSourceVariableClick(){
boolean setSelected = checkSelectAllVariablesPrivate();
sourceCheckBox.setSelected(setSelected) ;
}
public void setEdited(){
edited = true;
}
private void selectAllVariablesPrivate(boolean check){
Iterator iterator = dvGenericFilteredListUI.iterator();
while (iterator.hasNext() ){
DataVariableUI dataVariableUI = (DataVariableUI) iterator.next();
if (dataVariableUI.isDisplay()){
dataVariableUI.setSelected(check);
}
}
}
public void checkSelectAllFilterVariables(ValueChangeEvent ce){
boolean setSelected = checkSelectAllVariablesPrivate();
filterCheckBox.setSelected(setSelected) ;
forceRender(ce);
}
private boolean checkSelectAllVariablesPrivate(){
boolean allSelected = true;
Iterator iterator = dvGenericFilteredListUI.iterator();
while (iterator.hasNext() ){
DataVariableUI dataVariableUI = (DataVariableUI) iterator.next();
if (!dataVariableUI.isSelected()){
allSelected = false;
}
}
return allSelected;
}
private void forceRender(ValueChangeEvent ce){
PhaseId phase = ce.getPhaseId();
if (phase.equals(PhaseId.INVOKE_APPLICATION)) {
FacesContext.getCurrentInstance().renderResponse();
} else {
ce.setPhaseId(PhaseId.INVOKE_APPLICATION);
ce.queue();
}
}
public void selectAllMeasureButton(){
Iterator iterator = dvGenericFilteredListUI.iterator();
boolean selectMeasureVariables = (Boolean)measureCheckBox.getValue();
while (iterator.hasNext() ){
DataVariableUI dataVariableUI = (DataVariableUI) iterator.next();
dataVariableUI.setSelected(selectMeasureVariables);
}
}
private HtmlDataTable dataTableVarGroup;
public HtmlDataTable getDataTableVarGroup() {
return this.dataTableVarGroup;
}
public void setDataTableVarGroup(HtmlDataTable dataTableVarGroup) {
this.dataTableVarGroup = dataTableVarGroup;
}
private HtmlDataTable dataTableSourceVarGroup;
public HtmlDataTable getDataTableSourceVarGroup() {
return this.dataTableSourceVarGroup;
}
public void setDataTableSourceVarGroup(HtmlDataTable dataTableSourceVarGroup) {
this.dataTableSourceVarGroup = dataTableSourceVarGroup;
}
private HtmlDataTable dataTableXAxis;
public HtmlDataTable getDataTableXAxis() {
return this.dataTableXAxis;
}
public void setDataTableXAxis(HtmlDataTable dataTableXAxis) {
this.dataTableXAxis = dataTableXAxis;
}
private HtmlDataTable dataTableFilterGroup;
public HtmlDataTable getDataTableFilterGroup() {
return this.dataTableFilterGroup;
}
public void setDataTableFilterGroup(HtmlDataTable dataTableFilterGroup) {
this.dataTableFilterGroup = dataTableFilterGroup;
}
private HtmlDataTable dataTableFilterGrouping;
public HtmlDataTable getDataTableFilterGrouping() {
return this.dataTableFilterGrouping;
}
public void setDataTableFilterGrouping(HtmlDataTable dataTableFilterGrouping) {
this.dataTableFilterGrouping = dataTableFilterGrouping;
}
private HtmlDataTable dataTableFilterGroupType;
public HtmlDataTable getDataTableFilterGroupType() {
return this.dataTableFilterGroupType;
}
public void setDataTableFilterGroupType(HtmlDataTable dataTableFilterGroupType) {
this.dataTableFilterGroupType = dataTableFilterGroupType;
}
private HtmlDataTable dataTableManageFilterGroupType;
public HtmlDataTable getDataTableManageFilterGroupType() {
return this.dataTableManageFilterGroupType;
}
public void setDataTableManageFilterGroupType(HtmlDataTable dataTableManageFilterGroupType) {
this.dataTableManageFilterGroupType = dataTableManageFilterGroupType;
}
private HtmlDataTable dataTableManageMeasureGroupType;
public HtmlDataTable getDataTableManageMeasureGroupType() {
return this.dataTableManageMeasureGroupType;
}
public void setDataTableManageMeasureGroupType(HtmlDataTable dataTableManageMeasureGroupType) {
this.dataTableManageMeasureGroupType = dataTableManageMeasureGroupType;
}
private HtmlDataTable dataTableMeasureGroupType;
public HtmlDataTable getDataTableMeasureGroupType() {
return this.dataTableMeasureGroupType;
}
public void setDataTableMeasureGroupType(HtmlDataTable dataTableMeasureGroupType) {
this.dataTableMeasureGroupType = dataTableMeasureGroupType;
}
public List<VarGroupingUI> getFilterGroupings() {
return filterGroupings;
}
public void setFilterGroupings(List<VarGroupingUI> filterGroupings) {
this.filterGroupings = filterGroupings;
}
private HtmlInputText inputFilterGroupingName;
public HtmlInputText getInputFilterGroupingName() {
return this.inputFilterGroupingName;
}
public void setInputFilterGroupingName(HtmlInputText inputFilterGroupingName) {
this.inputFilterGroupingName = inputFilterGroupingName;
}
private HtmlDataTable dataTableFilterGroups;
public HtmlDataTable getDataTableFilterGroups() {
return dataTableFilterGroups;
}
public void setDataTableFilterGroups(HtmlDataTable dataTableFilterGroups) {
this.dataTableFilterGroups = dataTableFilterGroups;
}
private HtmlInputText inputFilterGroupName;
public HtmlInputText getInputFilterGroupName() {
return this.inputFilterGroupName;
}
public void setInputFilterGroupName(HtmlInputText inputFilterGroupName) {
this.inputFilterGroupName = inputFilterGroupName;
}
private HtmlCommandLink addFilterGroupLink;
public HtmlCommandLink getAddFilterGroupLink() {
return this.addFilterGroupLink;
}
public void setAddFilterGroupLink(HtmlCommandLink addFilterGroupLink) {
this.addFilterGroupLink = addFilterGroupLink;
}
private HtmlCommandLink addFilterGroupTypeLink;
public HtmlCommandLink getAddFilterGroupTypeLink() {
return this.addFilterGroupTypeLink;
}
public void setAddFilterGroupTypeLink(HtmlCommandLink addFilterGroupTypeLink) {
this.addFilterGroupTypeLink = addFilterGroupTypeLink;
}
private HtmlCommandLink addSecondFilterGroupTypeLink;
public HtmlCommandLink getAddSecondFilterGroupTypeLink() {
return this.addSecondFilterGroupTypeLink;
}
public void setAddSecondFilterGroupTypeLink(HtmlCommandLink addFilterGroupTypeLink) {
this.addSecondFilterGroupTypeLink = addFilterGroupTypeLink;
}
private HtmlCommandLink deleteFilterGroupLink;
public HtmlCommandLink getDeleteFilterGroupLink() {
return this.deleteFilterGroupLink;
}
public void setDeleteFilterGroupLink(HtmlCommandLink deleteFilterGroupLink) {
this.deleteFilterGroupLink = deleteFilterGroupLink;
}
public DataVariable getxAxisVariable() {
return xAxisVariable;
}
public void setxAxisVariable(DataVariable xAxisVariable) {
this.xAxisVariable = xAxisVariable;
}
public Study getStudy() {
return study;
}
public void setStudy(Study study) {
this.study = study;
}
public Long getStudyFileId() {
return studyFileId;
}
public void setStudyFileId(Long studyFileId) {
this.studyFileId = studyFileId;
}
private List files;
public List getFiles() {
return files;
}
public void setFiles(List files) {
this.files = files;
}
public List<SelectItem> getStudyFileIdSelectItems() {
return studyFileIdSelectItems;
}
public void setStudyFileIdSelectItems(List<SelectItem> studyFileIdSelectItems) {
this.studyFileIdSelectItems = studyFileIdSelectItems;
}
public Long getStudyId() {
return studyId;
}
public void setStudyId(Long studyId) {
this.studyId = studyId;
}
public Long getxAxisVariableId() {
return xAxisVariableId;
}
public void setxAxisVariableId(Long xAxisVariableId) {
this.xAxisVariableId = xAxisVariableId;
}
HtmlSelectOneMenu selectStudyFile;
public HtmlSelectOneMenu getSelectStudyFile() {
return selectStudyFile;
}
public void setSelectStudyFile(HtmlSelectOneMenu selectStudyFile) {
this.selectStudyFile = selectStudyFile;
}
public DataTable getDataTable() {
return dataTable;
}
public void setDataTable(DataTable dataTable) {
this.dataTable = dataTable;
}
private HtmlCommandButton validateButton = new HtmlCommandButton();
private HtmlCommandButton releaseButton = new HtmlCommandButton();
public HtmlCommandButton getValidateButton() {
return validateButton;
}
public void setValidateButton(HtmlCommandButton hit) {
this.validateButton = hit;
}
public HtmlCommandButton getReleaseButton() {
return releaseButton;
}
public void setReleaseButton(HtmlCommandButton releaseButton) {
this.releaseButton = releaseButton;
}
public boolean isShowCommands() {
return showCommands;
}
public void setShowCommands(boolean showCommands) {
this.showCommands = showCommands;
}
public boolean isSelectFile() {
return selectFile;
}
public void setSelectFile(boolean selectFile) {
this.selectFile = selectFile;
}
public List<DataVariable> getDvList() {
return dvList;
}
public void setDvList(List<DataVariable> dvList) {
this.dvList = dvList;
}
public String getxAxisUnits() {
return xAxisUnits;
}
public void setxAxisUnits(String xAxisUnits) {
this.xAxisUnits = xAxisUnits;
}
public List<DataVariable> getDvFilteredList() {
if (getInputVariableFilter() == null) return dvList;
if (getInputVariableFilter().getValue() == null) return dvList;
if (getInputVariableFilter().getValue().equals("")) return dvList;
return dvFilteredList;
}
public void setDvFilteredList(List<DataVariable> dvFilteredList) {
this.dvFilteredList = dvFilteredList;
}
public List<DataVariableUI> getDvGenericListUI() {
return dvGenericListUI;
}
public boolean isShowFilterVariables() {
return showFilterVariables;
}
public void setShowFilterVariables(boolean showFilterVariables) {
this.showFilterVariables = showFilterVariables;
}
public boolean isShowMeasureVariables() {
return showMeasureVariables;
}
public void setShowMeasureVariables(boolean showMeasureVariables) {
this.showMeasureVariables = showMeasureVariables;
}
public boolean isEditXAxis() {
return editXAxis;
}
public void setEditXAxis(boolean editXAxis) {
this.editXAxis = editXAxis;
}
public void setDvGenericFilteredListUI(List<DataVariableUI> dvGenericFilteredListUI) {
this.dvGenericFilteredListUI = dvGenericFilteredListUI;
}
public List<DataVariableUI> getDvGenericFilteredListUI() {
List <DataVariableUI> returnList = new ArrayList();
Iterator iterator = dvGenericListUI.iterator();
iterator = dvGenericListUI.iterator();
while (iterator.hasNext() ){
DataVariableUI dataVariableUI = (DataVariableUI) iterator.next();
if (dataVariableUI.isDisplay()){
DataVariableUI dvAdd = new DataVariableUI();
dvAdd.setDataVariable(dataVariableUI.getDataVariable());
dvAdd.setSelected(dataVariableUI.isSelected());
dvAdd.setDisplay(true);
returnList.add(dvAdd);
}
}
return dvGenericFilteredListUI;
//return returnList;
}
public VarGroupUI getEditFragmentVarGroup() {
return editFragmentVarGroup;
}
public void setEditFragmentVarGroup(VarGroupUI editFragmentVarGroup) {
this.editFragmentVarGroup = editFragmentVarGroup;
}
public boolean isEditFilterGroup() {
return editFilterGroup;
}
public void setEditFilter(boolean editFilterGroup) {
this.editFilterGroup = editFilterGroup;
}
public boolean isEditMeasure() {
return editMeasure;
}
public void setEditMeasure(boolean editMeasure) {
this.editMeasure = editMeasure;
}
public VarGroupUI getEditFilterVarGroup() {
return editFilterVarGroup;
}
public void setEditFilterVarGroup(VarGroupUI editFilterVarGroup) {
this.editFilterVarGroup = editFilterVarGroup;
}
public VarGroupUI getEditMeasureVarGroup() {
return editMeasureVarGroup;
}
public void setEditMeasureVarGroup(VarGroupUI editMeasureVarGroup) {
this.editMeasureVarGroup = editMeasureVarGroup;
}
public boolean isxAxisSet() {
return xAxisSet;
}
public boolean isAddFilterType() {
return addFilterType;
}
public void setAddFilterType(boolean addFilterType) {
this.addFilterType = addFilterType;
}
public boolean isAddMeasureType() {
return addMeasureType;
}
public void setAddMeasureType(boolean addMeasureType) {
this.addMeasureType = addMeasureType;
}
public boolean isHasFilterGroupings() {
return hasFilterGroupings;
}
public void setHasFilterGroupings(boolean hasFilterGroupings) {
this.hasFilterGroupings = hasFilterGroupings;
}
public boolean isHasFilterGroups() {
return hasFilterGroups;
}
public void setHasFilterGroups(boolean hasFilterGroups) {
this.hasFilterGroups = hasFilterGroups;
}
public boolean isHasMeasureGroups() {
return hasMeasureGroups;
}
public void setHasMeasureGroups(boolean hasMeasureGroups) {
this.hasMeasureGroups = hasMeasureGroups;
}
public boolean isEditMeasureType() {
return editMeasureType;
}
public void setEditMeasureType(boolean editMeasureType) {
this.editMeasureType = editMeasureType;
}
public boolean isEditFilterType() {
return editFilterType;
}
public void setEditFilterType(boolean editFilterType) {
this.editFilterType = editFilterType;
}
public boolean isEditFilterGrouping() {
return editFilterGrouping;
}
public void setEditFilterGrouping(boolean editFilterGrouping) {
this.editFilterGrouping = editFilterGrouping;
}
public VarGroupingUI getEditFilterVarGrouping() {
return editFilterVarGrouping;
}
public void setEditFilterVarGrouping(VarGroupingUI editFilterVarGrouping) {
this.editFilterVarGrouping = editFilterVarGrouping;
}
public String getStudyFileName() {
return studyFileName;
}
public void setStudyFileName(String studyFileName) {
this.studyFileName = studyFileName;
}
public boolean isEditMeasureGrouping() {
return editMeasureGrouping;
}
public boolean isManageMeasureTypes() {
return manageMeasureTypes;
}
public boolean isAddFilterGroup() {
return addFilterGroup;
}
public boolean isAddMeasureGroup() {
return addMeasureGroup;
}
public boolean isAddFilterGrouping() {
return addFilterGrouping;
}
public boolean isManageFilterTypes() {
return manageFilterTypes;
}
private HtmlSelectBooleanCheckbox sourceCheckBox;
public HtmlSelectBooleanCheckbox getSourceCheckBox() {
return sourceCheckBox;
}
public void setSourceCheckBox(HtmlSelectBooleanCheckbox sourceCheckBox) {
this.sourceCheckBox = sourceCheckBox;
}
private HtmlSelectBooleanCheckbox measureCheckBox;
public HtmlSelectBooleanCheckbox getMeasureCheckBox() {
return measureCheckBox;
}
public void setMeasureCheckBox(HtmlSelectBooleanCheckbox measureCheckBox) {
this.measureCheckBox = measureCheckBox;
}
private HtmlSelectBooleanCheckbox filterCheckBox;
public HtmlSelectBooleanCheckbox getFilterCheckBox() {
return filterCheckBox;
}
public void setFilterCheckBox(HtmlSelectBooleanCheckbox filterCheckBox) {
this.filterCheckBox = filterCheckBox;
}
public StudyUI getStudyUI() {
return studyUI;
}
public void setStudyUI(StudyUI studyUI) {
this.studyUI = studyUI;
}
public boolean isEditSource() {
return editSource;
}
public void setEditSource(boolean editSource) {
this.editSource = editSource;
}
public boolean isAddSourceGroup() {
return addSourceGroup;
}
public void setAddSourceGroup(boolean addSource) {
this.addSourceGroup = addSource;
}
public void changeTab(TabChangeEvent te){
cancelAddEdit();
}
}
| false | true | public boolean validateForRelease(boolean messages) {
boolean valid = true;;
List returnListOfErrors = new ArrayList();
List duplicateVariables = new ArrayList();
String fullErrorMessage = "";
if (!visualizationService.validateDisplayOptions(dataTable)) {
if (messages) {
fullErrorMessage += "<br></br>Please select at least one view and the default view must be selected.<br></br>";
}
valid = false;
}
if (!xAxisSet || !visualizationService.validateXAxisMapping(dataTable, xAxisVariableId)) {
if (messages) {
fullErrorMessage += "<br></br>You must select one X-axis variable and it cannot be mapped to any Measure or Filter.<br></br>";
}
valid = false;
}
if (!visualizationService.validateAtLeastOneFilterMapping(dataTable, returnListOfErrors)) {
if (messages) {
if (!returnListOfErrors.isEmpty()) {
fullErrorMessage += "<br></br>Measure-filter combinations were found that would result in multiple variables selected at visualization. ";
boolean newgroup = false;
boolean firstVar = true;
for (Object errorObject : returnListOfErrors) {
if (errorObject instanceof VarGroup) {
firstVar = true;
if (newgroup) {
fullErrorMessage += "</li></ul>";
}
VarGroup vg = (VarGroup) errorObject;
fullErrorMessage += "<ul>";
fullErrorMessage += "<li>" + "Measure " + vg.getName() + " contains at least one variable with no associated filter.</li> ";
}
if (errorObject instanceof DataVariable) {
DataVariable dv = (DataVariable) errorObject;
if (firstVar) {
fullErrorMessage += "<li>Affected Variables: " + dv.getName();
} else {
fullErrorMessage += ", " + dv.getName();
}
newgroup = true;
firstVar = false;
}
}
fullErrorMessage += "</li></ul>";
fullErrorMessage += "To correct this, create filters to limit each measure filter combination to a single variable or assign only one variable to each measure.<br></br>";
}
}
valid = false;
}
returnListOfErrors.clear();
if (!visualizationService.validateAllGroupsAreMapped(dataTable, returnListOfErrors)) {
if (messages) {
if (!returnListOfErrors.isEmpty()) {
fullErrorMessage += "<br></br>Measure-filter combinations were found that would result in no variables selected at visualization.<br></br>";
fullErrorMessage += "<ul>";
String filterErrorMessage = "";
int filterCount = 0;
String measureErrorMessage = "";
int measureCount = 0;
for (Object varGroupIn : returnListOfErrors) {
VarGroup varGroup = (VarGroup) varGroupIn;
VarGrouping varGrouping = varGroup.getGroupAssociation();
if (varGrouping.getGroupingType().equals(GroupingType.FILTER)) {
if (filterCount == 0) {
filterErrorMessage += varGroup.getName();
} else {
filterErrorMessage = filterErrorMessage + ", " + varGroup.getName();
}
filterCount++;
}
if (varGrouping.getGroupingType().equals(GroupingType.MEASURE)) {
if (measureCount == 0) {
measureErrorMessage += varGroup.getName();
} else {
measureErrorMessage = measureErrorMessage + ", " + varGroup.getName();
}
measureCount++;
}
}
if (filterCount == 1) {
fullErrorMessage = fullErrorMessage + "<li>Filter " + filterErrorMessage + " contains no variables.</li>";
}
if (filterCount > 1) {
fullErrorMessage = fullErrorMessage + "<li>Filters " + filterErrorMessage + " contain no variables.</li>";
}
if (measureCount == 1) {
fullErrorMessage = fullErrorMessage + "<li>Measure " + measureErrorMessage + " contains no variables.</li>";
}
if (measureCount > 1) {
fullErrorMessage = fullErrorMessage + "<li>Measures " + measureErrorMessage + " contain no variables.</li>";
}
fullErrorMessage += "</ul>";
fullErrorMessage += "To correct this, assign at least one variable or remove the empty measures or filters.<br></br>";
}
}
valid = false;
}
returnListOfErrors.clear();
if (!visualizationService.validateMoreThanZeroMeasureMapping(dataTable, returnListOfErrors)) {
if (messages) {
if (!returnListOfErrors.isEmpty()) {
fullErrorMessage += "<br></br>At least one filter was found that is not mapped to any measures.<br></br>";;
boolean firstVar = true;
boolean newgroup = false;
for (Object errorObject : returnListOfErrors) {
if (errorObject instanceof VarGroup) {
firstVar = true;
VarGroup vg = (VarGroup) errorObject;
if (newgroup) {
fullErrorMessage += "</li></ul>";
}
fullErrorMessage += "<ul>";
fullErrorMessage += "<li>Filter " + vg.getName() + " contains at least one variable that is not assigned to any measure.</li>";
}
if (errorObject instanceof DataVariable) {
DataVariable dv = (DataVariable) errorObject;
if (firstVar) {
fullErrorMessage += "<li>Affected Variables: " + dv.getName();
} else {
fullErrorMessage += ", " + dv.getName();
}
newgroup = true;
firstVar = false;
}
}
fullErrorMessage += "</li></ul>";
fullErrorMessage += "To correct this, remove unassigned variables or assign them to measures.<br></br>";
}
}
valid = false;
}
returnListOfErrors.clear();
if (!visualizationService.validateOneMeasureMapping(dataTable, returnListOfErrors)) {
if (messages) {
if (!returnListOfErrors.isEmpty()) {
fullErrorMessage += "<br></br>Variables were found that are mapped to multiple measures. ";
boolean firstGroup = true;
boolean newvar = false;
for (Object dataVariableIn : returnListOfErrors) {
if (dataVariableIn instanceof DataVariable) {
if (newvar) {
fullErrorMessage += "</li></ul>";
}
fullErrorMessage += "<ul>";
DataVariable dataVariable = (DataVariable) dataVariableIn;
fullErrorMessage += "<li>Variable: " + dataVariable.getName() + "</li>";
firstGroup = true;
}
if (dataVariableIn instanceof VarGroup) {
VarGroup varGroup = (VarGroup) dataVariableIn;
if (firstGroup) {
fullErrorMessage += "<li>Measures: " + varGroup.getName();
} else {
fullErrorMessage += " , " + varGroup.getName();
}
newvar = true;
firstGroup = false;
}
}
}
fullErrorMessage += "</li></ul>";
fullErrorMessage += "To correct this, map each variable to a single measure.<br></br>";
}
valid = false;
}
returnListOfErrors.clear();
if (!visualizationService.validateOneFilterPerGrouping(dataTable, returnListOfErrors)) {
if (messages) {
if (!returnListOfErrors.isEmpty()) {
fullErrorMessage += "<br></br>Variables were found that are mapped to multiple filters within a single filter group. ";
boolean firstGroup = true;
boolean newvar = false;
for (Object dataVariableIn : returnListOfErrors) {
if (dataVariableIn instanceof DataVariable) {
DataVariable dataVariable = (DataVariable) dataVariableIn;
if (newvar) {
fullErrorMessage += "</li></ul>";
}
fullErrorMessage += "<ul>";
fullErrorMessage += "<li>Variable: " + dataVariable.getName() + "</li>";
firstGroup = true;
}
if (dataVariableIn instanceof VarGroup) {
VarGroup varGroup = (VarGroup) dataVariableIn;
if (firstGroup) {
fullErrorMessage += "<li>Filters: " + varGroup.getName();
} else {
fullErrorMessage += " , " + varGroup.getName();
}
firstGroup = false;
newvar = true;
}
}
}
fullErrorMessage += "</li></ul>";
fullErrorMessage += "To correct this, map each variable to a single filter within each group.<br></br>";
}
valid = false;
}
if (!visualizationService.validateAtLeastOneMeasureMapping(dataTable)) {
if (messages) {
fullErrorMessage += "<br></br>Measure-filter combinations were found that would result in no variables selected at visualization.<br></br>";
fullErrorMessage += " No Measures or filters configured.<br></br>";
fullErrorMessage += "To correct this, configure at least one measure or one measure-filter combination.<br></br>";
}
valid = false;
}
returnListOfErrors.clear();
duplicateVariables = visualizationService.getDuplicateMappings(dataTable, returnListOfErrors);
if (duplicateVariables.size() > 0) {
if (messages) {
if (!returnListOfErrors.isEmpty()) {
fullErrorMessage += "<br></br>Measure-filter combinations were found that would result in multiple variables selected at visualization. ";
boolean firstVar = true;
boolean newgroup = false;;
for (Object errorObject : returnListOfErrors) {
if (errorObject instanceof VarGroup) {
if (newgroup) {
fullErrorMessage += "</li></ul>";
}
fullErrorMessage += "<ul>";
firstVar = true;
VarGroup vg = (VarGroup) errorObject;
fullErrorMessage += "<li>Measure " + vg.getName() + " contains multiple variables with insufficient filters to make them uniquely selectable.</li>";
}
if (errorObject instanceof DataVariable) {
DataVariable dv = (DataVariable) errorObject;
if (firstVar) {
fullErrorMessage += "<li>Affected Variables: " + dv.getName();
} else {
fullErrorMessage += ", " + dv.getName();
}
newgroup = true;
firstVar = false;
}
}
fullErrorMessage += "</li></ul>";
fullErrorMessage += "To correct this, for measures where multiple variables are assigned, also assign each variable to a filter where the measure-filter combinations result in a single variable selected at visualization.<br></br>";
}
}
returnListOfErrors.clear();
valid = false;
}
if (valid && messages) {
getVDCRenderBean().getFlash().put("successMessage", "The Data Visualization is valid for release.");
}
if (!valid && messages) {
// add rounded corners to the validation message box
fullErrorMessage = "This configuration is invalid so it cannot be released. " + fullErrorMessage;
getVDCRenderBean().getFlash().put("warningMessage", fullErrorMessage);
}
return valid;
}
| public boolean validateForRelease(boolean messages) {
boolean valid = true;;
List returnListOfErrors = new ArrayList();
List duplicateVariables = new ArrayList();
String fullErrorMessage = "";
if (!visualizationService.validateDisplayOptions(dataTable)) {
if (messages) {
fullErrorMessage += "<br></br>Please select at least one view and the default view must be selected.<br></br>";
}
valid = false;
}
if (!xAxisSet || !visualizationService.validateXAxisMapping(dataTable, xAxisVariableId)) {
if (messages) {
fullErrorMessage += "<br></br>You must select one X-axis variable and it cannot be mapped to any Measure or Filter.<br></br>";
}
valid = false;
}
if (!visualizationService.validateAtLeastOneFilterMapping(dataTable, returnListOfErrors)) {
if (messages) {
if (!returnListOfErrors.isEmpty()) {
fullErrorMessage += "<br></br>Measure-filter combinations were found that would result in multiple variables selected at visualization. ";
boolean newgroup = false;
boolean firstVar = true;
for (Object errorObject : returnListOfErrors) {
if (errorObject instanceof VarGroup) {
firstVar = true;
if (newgroup) {
fullErrorMessage += "</li></ul>";
}
VarGroup vg = (VarGroup) errorObject;
fullErrorMessage += "<ul>";
fullErrorMessage += "<li>" + "Measure " + vg.getName() + " contains at least one variable with no associated filter.</li> ";
}
if (errorObject instanceof DataVariable) {
DataVariable dv = (DataVariable) errorObject;
if (firstVar) {
fullErrorMessage += "<li>Affected Variables: " + dv.getName();
} else {
fullErrorMessage += ", " + dv.getName();
}
newgroup = true;
firstVar = false;
}
}
fullErrorMessage += "</li></ul>";
fullErrorMessage += "To correct this, create filters to limit each measure filter combination to a single variable or assign only one variable to each measure.<br></br>";
}
}
valid = false;
}
returnListOfErrors.clear();
if (!visualizationService.validateAllGroupsAreMapped(dataTable, returnListOfErrors)) {
if (messages) {
if (!returnListOfErrors.isEmpty()) {
fullErrorMessage += "<br></br>Measure-filter combinations were found that would result in no variables selected at visualization.";
fullErrorMessage += "<ul>";
String filterErrorMessage = "";
int filterCount = 0;
String measureErrorMessage = "";
int measureCount = 0;
for (Object varGroupIn : returnListOfErrors) {
VarGroup varGroup = (VarGroup) varGroupIn;
VarGrouping varGrouping = varGroup.getGroupAssociation();
if (varGrouping.getGroupingType().equals(GroupingType.FILTER)) {
if (filterCount == 0) {
filterErrorMessage += varGroup.getName();
} else {
filterErrorMessage = filterErrorMessage + ", " + varGroup.getName();
}
filterCount++;
}
if (varGrouping.getGroupingType().equals(GroupingType.MEASURE)) {
if (measureCount == 0) {
measureErrorMessage += varGroup.getName();
} else {
measureErrorMessage = measureErrorMessage + ", " + varGroup.getName();
}
measureCount++;
}
}
if (filterCount == 1) {
fullErrorMessage = fullErrorMessage + "<li>Filter " + filterErrorMessage + " contains no variables.</li>";
}
if (filterCount > 1) {
fullErrorMessage = fullErrorMessage + "<li>Filters " + filterErrorMessage + " contain no variables.</li>";
}
if (measureCount == 1) {
fullErrorMessage = fullErrorMessage + "<li>Measure " + measureErrorMessage + " contains no variables.</li>";
}
if (measureCount > 1) {
fullErrorMessage = fullErrorMessage + "<li>Measures " + measureErrorMessage + " contain no variables.</li>";
}
fullErrorMessage += "</ul>";
fullErrorMessage += "To correct this, assign at least one variable or remove the empty measures or filters.<br></br>";
}
}
valid = false;
}
returnListOfErrors.clear();
if (!visualizationService.validateMoreThanZeroMeasureMapping(dataTable, returnListOfErrors)) {
if (messages) {
if (!returnListOfErrors.isEmpty()) {
fullErrorMessage += "<br></br>At least one filter was found that is not mapped to any measures.";;
boolean firstVar = true;
boolean newgroup = false;
for (Object errorObject : returnListOfErrors) {
if (errorObject instanceof VarGroup) {
firstVar = true;
VarGroup vg = (VarGroup) errorObject;
if (newgroup) {
fullErrorMessage += "</li></ul>";
}
fullErrorMessage += "<ul>";
fullErrorMessage += "<li>Filter " + vg.getName() + " contains at least one variable that is not assigned to any measure.</li>";
}
if (errorObject instanceof DataVariable) {
DataVariable dv = (DataVariable) errorObject;
if (firstVar) {
fullErrorMessage += "<li>Affected Variables: " + dv.getName();
} else {
fullErrorMessage += ", " + dv.getName();
}
newgroup = true;
firstVar = false;
}
}
fullErrorMessage += "</li></ul>";
fullErrorMessage += "To correct this, remove unassigned variables or assign them to measures.<br></br>";
}
}
valid = false;
}
returnListOfErrors.clear();
if (!visualizationService.validateOneMeasureMapping(dataTable, returnListOfErrors)) {
if (messages) {
if (!returnListOfErrors.isEmpty()) {
fullErrorMessage += "<br></br>Variables were found that are mapped to multiple measures. ";
boolean firstGroup = true;
boolean newvar = false;
for (Object dataVariableIn : returnListOfErrors) {
if (dataVariableIn instanceof DataVariable) {
if (newvar) {
fullErrorMessage += "</li></ul>";
}
fullErrorMessage += "<ul>";
DataVariable dataVariable = (DataVariable) dataVariableIn;
fullErrorMessage += "<li>Variable: " + dataVariable.getName() + "</li>";
firstGroup = true;
}
if (dataVariableIn instanceof VarGroup) {
VarGroup varGroup = (VarGroup) dataVariableIn;
if (firstGroup) {
fullErrorMessage += "<li>Measures: " + varGroup.getName();
} else {
fullErrorMessage += " , " + varGroup.getName();
}
newvar = true;
firstGroup = false;
}
}
}
fullErrorMessage += "</li></ul>";
fullErrorMessage += "To correct this, map each variable to a single measure.<br></br>";
}
valid = false;
}
returnListOfErrors.clear();
if (!visualizationService.validateOneFilterPerGrouping(dataTable, returnListOfErrors)) {
if (messages) {
if (!returnListOfErrors.isEmpty()) {
fullErrorMessage += "<br></br>Variables were found that are mapped to multiple filters within a single filter group. ";
boolean firstGroup = true;
boolean newvar = false;
for (Object dataVariableIn : returnListOfErrors) {
if (dataVariableIn instanceof DataVariable) {
DataVariable dataVariable = (DataVariable) dataVariableIn;
if (newvar) {
fullErrorMessage += "</li></ul>";
}
fullErrorMessage += "<ul>";
fullErrorMessage += "<li>Variable: " + dataVariable.getName() + "</li>";
firstGroup = true;
}
if (dataVariableIn instanceof VarGroup) {
VarGroup varGroup = (VarGroup) dataVariableIn;
if (firstGroup) {
fullErrorMessage += "<li>Filters: " + varGroup.getName();
} else {
fullErrorMessage += " , " + varGroup.getName();
}
firstGroup = false;
newvar = true;
}
}
}
fullErrorMessage += "</li></ul>";
fullErrorMessage += "To correct this, map each variable to a single filter within each group.<br></br>";
}
valid = false;
}
if (!visualizationService.validateAtLeastOneMeasureMapping(dataTable)) {
if (messages) {
fullErrorMessage += "<br></br>Measure-filter combinations were found that would result in no variables selected at visualization.<br></br>";
fullErrorMessage += " No Measures or filters configured.<br></br>";
fullErrorMessage += "To correct this, configure at least one measure or one measure-filter combination.<br></br>";
}
valid = false;
}
returnListOfErrors.clear();
duplicateVariables = visualizationService.getDuplicateMappings(dataTable, returnListOfErrors);
if (duplicateVariables.size() > 0) {
if (messages) {
if (!returnListOfErrors.isEmpty()) {
fullErrorMessage += "<br></br>Measure-filter combinations were found that would result in multiple variables selected at visualization. ";
boolean firstVar = true;
boolean newgroup = false;;
for (Object errorObject : returnListOfErrors) {
if (errorObject instanceof VarGroup) {
if (newgroup) {
fullErrorMessage += "</li></ul>";
}
fullErrorMessage += "<ul>";
firstVar = true;
VarGroup vg = (VarGroup) errorObject;
fullErrorMessage += "<li>Measure " + vg.getName() + " contains multiple variables with insufficient filters to make them uniquely selectable.</li>";
}
if (errorObject instanceof DataVariable) {
DataVariable dv = (DataVariable) errorObject;
if (firstVar) {
fullErrorMessage += "<li>Affected Variables: " + dv.getName();
} else {
fullErrorMessage += ", " + dv.getName();
}
newgroup = true;
firstVar = false;
}
}
fullErrorMessage += "</li></ul>";
fullErrorMessage += "To correct this, for measures where multiple variables are assigned, also assign each variable to a filter where the measure-filter combinations result in a single variable selected at visualization.<br></br>";
}
}
returnListOfErrors.clear();
valid = false;
}
if (valid && messages) {
getVDCRenderBean().getFlash().put("successMessage", "The Data Visualization is valid for release.");
}
if (!valid && messages) {
// add rounded corners to the validation message box
fullErrorMessage = "This configuration is invalid so it cannot be released. <br></br>" + fullErrorMessage;
getVDCRenderBean().getFlash().put("warningMessage", fullErrorMessage);
}
return valid;
}
|
diff --git a/org/nyet/mappack/Map.java b/org/nyet/mappack/Map.java
index 8f8c667..d1d09f5 100644
--- a/org/nyet/mappack/Map.java
+++ b/org/nyet/mappack/Map.java
@@ -1,563 +1,563 @@
package org.nyet.mappack;
import java.util.Arrays;
import java.nio.ByteBuffer;
import org.nyet.util.Strings;
import org.nyet.logfile.CSVRow;
public class Map {
private class Enm implements Comparable {
protected int enm;
public String[] legend;
public Enm(ByteBuffer b) { enm=b.getInt(); }
public Enm(int enm) { this.enm=enm; }
public String toString() {
if(enm<0 || enm>legend.length-1)
return String.format("(len %d) %x", legend.length, enm);
return legend[enm];
}
public int compareTo(Object o) {
return (new Integer(enm).compareTo(((Enm)o).enm));
}
}
private class Organization extends Enm {
public Organization(ByteBuffer b) {
super(b);
final String[] l= {
"??", // 0
"??", // 1
"Single value", // 2
"Onedimensional", // 3
"Twodimensional", // 4
"2d Inverse" // 5
};
legend = l;
}
public boolean isTable() {
return this.enm>2 && this.enm<6;
}
public boolean is1D() {
return this.enm == 3;
}
}
public class ValueType extends Enm {
private int width;
public ValueType(int width, int enm) {
super(enm);
this.width = width;
}
public ValueType(ByteBuffer b) {
super(b);
final String[] l= {
"??", // 0
"8 Bit", // 1
"16 Bit (HiLo)", // 2
"16 Bit (LoHi)", // 3
"32 Bit (HiLoHilo)", // 4
"32 Bit (LoHiLoHi)", // 5
"32 BitFloat (HiLoHiLo)", // 6
"32 BitFloat (LoHiLoHi)" // 7
};
legend = l;
switch(this.enm) {
case 1: width=1; break;
case 2:
case 3: width=2; break;
case 4:
case 5:
case 6:
case 7: width=4; break;
default: width=0;
}
}
public boolean isLE() {
return (this.enm>1 && (this.enm & 1)==1);
}
public int width() { return this.width; }
}
private class DataSource extends Enm {
public DataSource(ByteBuffer b) {
super(b);
final String[] l = {
"1,2,3", // 0
"Eprom", // 1
"Eprom, add", // 2
"Eprom, subtract", // 3
"Free editable" // 4
};
legend = l;
}
public boolean isEeprom() {
return this.enm>0 && this.enm<4;
}
public boolean isOrdinal() {
return this.enm == 0;
}
}
public class Dimension implements Comparable {
public int x;
public int y;
public Dimension(int xx, int yy) { x = xx; y = yy; }
public Dimension(ByteBuffer b) { x = b.getInt(); y = b.getInt(); }
public String toString() { return x + "x" + y; }
public int compareTo(Object o) {
return (new Integer(areaOf())).compareTo(((Dimension)o).areaOf());
}
public int areaOf() { return this.x*this.y; }
}
public class Value {
public String description;
public String units;
public double factor;
public double offset;
public String toString() {
return "(" + description + ")/" + units + " - f/o: " + factor + "/" + offset;
}
public Value(ByteBuffer b) throws ParserException {
description = Parse.string(b);
units = Parse.string(b);
factor = b.getDouble();
offset = b.getDouble();
}
public double convert(double in) { return in*factor+offset; }
public String eqXDF (int off, String tag) {
String out="";
if(this.factor != 1 || this.offset != 0) {
out += String.format(XDF_LBL+"%f * X", off, tag, this.factor);
if(this.offset!=0)
out += String.format("+ %f",this.offset);
out+=",TH|0|0|0|0|\n";
}
return out;
}
}
private class Axis extends Value {
public DataSource datasource;
public HexValue addr = null;
public ValueType valueType;
private int[] header1 = new int[2]; // unk
private byte header1a;
public boolean reciprocal = false; // todo (find)
public boolean sign = false; // todo (find)
public byte precision;
private byte[] header2 = new byte[3];
private int count;
private int[] header3;
private int header4;
public HexValue signature;
public Axis(ByteBuffer b) throws ParserException {
super(b);
datasource = new DataSource(b);
// always read addr, so we advance pointer regardless of datasource
addr = new HexValue(b);
if(!datasource.isEeprom()) addr = null;
valueType = new ValueType(b);
Parse.buffer(b, header1); // unk
header1a = b.get(); // unk
reciprocal = b.get()==1;
precision = b.get();
Parse.buffer(b, header2); // unk
sign = b.get()==1;
count = b.getInt(); // unk
header3 = new int[count/4];
Parse.buffer(b, header3); // unk
header4 = b.getInt(); // unk
signature = new HexValue(b);
}
public String toString() {
String out = super.toString() + "\n";
out += "\t ds: " + datasource + "\n";
out += "\t addr: " + addr + " " + valueType + "\n";
out += "\t h1: " + Arrays.toString(header1) + "\n";
out += "\t h1a: " + header1a + " (short)\n";
out += "\tflags: ";
if(reciprocal) out += "R";
if(sign) out += "S";
out += "\n";
out += "\t prec: " + precision + " (byte)\n";
out += "\t h2: " + Arrays.toString(header2) + "\n";
out += "\tcount: " + count + "\n";
out += "\t h3: " + Arrays.toString(header3) + "\n";
out += "\t h4: " + header4 + "\n";
if(signature.v!=-1)
out += "\t sig: " + signature + "\n";
return out;
}
}
private byte header0;
public String name;
public Organization organization;
private int header; //unk
public ValueType valueType;
private int[] headera = new int[2]; // unk
public int folderId;
public String id;
private int header1; // unk
private byte header1a; // unk
public int[] range = new int[4];
private HexValue[] header2 = new HexValue[8]; // unk
public boolean reciprocal;
public boolean sign;
public boolean difference;
public boolean percent;
public Dimension size;
private int[] header3 = new int[2]; // unk
public int precision;
public Value value;
public HexValue[] extent = new HexValue[2];
private HexValue[] header4 = new HexValue[2]; // unk
private int[] header5 = new int[2]; // unk
private HexValue header6;
private int header7; // unk
public Axis x_axis;
public Axis y_axis;
private int header8; // unk
private short header8a; // unk
private int[] header9 = new int[8]; // unk
private short header9a; // unk
private int header9b; // unk
private byte header9c; // unk
private HexValue[] header10 = new HexValue[6];// unk
private HexValue[] header11 = new HexValue[2];// unk
public byte[] term2 = new byte[3];
public Map(ByteBuffer b) throws ParserException {
header0 = b.get(); // unk
name = Parse.string(b);
organization = new Organization(b);
header = b.getInt();
valueType = new ValueType(b);
Parse.buffer(b, headera); // unk
folderId = b.getInt();
id = Parse.string(b);
header1 = b.getInt(); // unk
header1a = b.get(); // unk
Parse.buffer(b, range);
Parse.buffer(b, header2); // unk
reciprocal = b.get()==1;
sign = b.get()==1;
difference = b.get()==1;
percent = b.get()==1;
size = new Dimension(b);
Parse.buffer(b, header3); // unk
precision = b.getInt();
value = new Value(b);
Parse.buffer(b, extent);
Parse.buffer(b, header4); // unk
Parse.buffer(b, header5); // unk
header6 = new HexValue(b);
header7 = b.getInt();
x_axis = new Axis(b);
y_axis = new Axis(b);
header8 = b.getInt(); // unk
header8a = b.getShort(); // unk
Parse.buffer(b, header9); // unk
header9a = b.getShort(); // unk
header9b = b.getInt(); // unk
header9c = b.get(); // unk
Parse.buffer(b, header10); // unk
Parse.buffer(b, header11); // unk
b.get(term2);
// System.out.println(this);
}
// generate a 1d map for an axis
public Map(Axis axis, int size) {
this.extent[0] = axis.addr;
this.size = new Dimension(1, size);
this.valueType = axis.valueType;
this.value = axis;
this.precision = axis.precision;
}
public static final String CSVHeader() {
final String[] header = {
"ID","Address","Name","Size","Organization","Description",
"Units","X Units","Y Units",
"Scale","X Scale","Y Scale",
"Value min","Value max","Value min*1", "Value max*1"
};
final CSVRow out = new CSVRow(header);
return out.toString();
}
public boolean equals(Map map) {
String stem=map.id.split("[? ]")[0];
if(stem.length()==0) return false;
return equals(stem);
}
public boolean equals(String id) {
if(id.length()==0 || this.id.length() == 0) return false;
return (id.equals(this.id.split("[? ]")[0]));
}
public static final int FORMAT_DUMP = 0;
public static final int FORMAT_CSV = 1;
public static final int FORMAT_XDF = 2;
public static final String XDF_LBL = "\t%06d %-17s=";
public String toString(int format, ByteBuffer image)
throws Exception {
switch(format) {
case FORMAT_DUMP: return toString();
case FORMAT_CSV: return toStringCSV(image);
case FORMAT_XDF: return toStringXDF(image);
}
return "";
}
private String toStringCSV(ByteBuffer image) throws Exception {
CSVRow row = new CSVRow();
row.add(this.id);
row.add(this.extent[0]);
row.add(this.name);
row.add(this.size);
row.add(this.valueType);
row.add(this.value.description);
row.add(this.value.units);
row.add(this.x_axis.units);
row.add(this.y_axis.units);
row.add(this.value.factor);
row.add(this.x_axis.factor);
row.add(this.y_axis.factor);
if(image!=null && image.limit()>0) {
MapData mapdata = new MapData(this, image);
row.add(mapdata.getMinimumValue());
row.add(mapdata.getMaximumValue());
row.add(String.format("0x%x", mapdata.getMinimum()));
row.add(String.format("0x%x", mapdata.getMaximum()));
} else {
row.add("");
row.add("");
}
return row.toString();
}
private static String ordinalArray(int len) {
Integer out[] = new Integer[len];
for(int i=0;i<len;i++) out[i]=i+1;
return Strings.join(",", out);
}
private String toStringXDF(ByteBuffer image) throws Exception {
boolean table = this.organization.isTable();
boolean oneD = this.organization.is1D() || this.size.y<=1;
String out = table?"%%TABLE%%\n":"%%CONSTANT%%\n";
out += String.format(XDF_LBL+"0x%X\n",100,"Cat0ID",this.folderId+1);
int off = table?40000:20000;
String title = "";
String desc = "";
if(this.id.length()>0) {
title = this.id.split(" ")[0]; // HACK: drop the junk
desc = this.name;
} else {
title = this.name;
}
out += String.format(XDF_LBL+"\"%s\"\n",off+5,"Title",title);
if(desc.length()>0) {
out += String.format(XDF_LBL+"\"%s\"\n",off+10,"Desc",desc);
out += String.format(XDF_LBL+"0x%X\n",off+11,"DescSize",
desc.length()+1);
}
if(this.value.units.length()>0) {
if(table)
out += String.format(XDF_LBL+"\"%s\"\n",off+330,"ZUnits",
this.value.units);
else
out += String.format(XDF_LBL+"\"%s\"\n",off+20,"Units",
this.value.units);
}
if(this.valueType.width()>1) {
out += String.format(XDF_LBL+"0x%X\n",off+50,"SizeInBits",
this.valueType.width()*8);
}
// XDF "Flags"
// -----------
// 0x001 - z value signed
// 0x002 - z value LE
// 0x040 - x axis signed
// 0x100 - x axis LE
// 0x080 - y axis signed
// 0x200 - y axis LE
int flags = this.sign?1:0;
if (this.valueType.isLE()) flags |= 2;
out += String.format(XDF_LBL+"0x%X\n",off+100,"Address",
this.extent[0].v);
out += this.value.eqXDF(off+200, table?"ZEq":"Equation");
if(table) {
if (this.size.x > 0x100 && this.size.y <= 0x100) {
// swap x and y; tunerpro crashes on Cols > 256
Axis tmpa = this.y_axis;
this.y_axis = this.x_axis;
this.x_axis = tmpa;
int tmp = this.size.y;
this.size.y = this.size.x;
this.size.x = tmp;
}
// X (columns)
if (this.x_axis.sign) flags |= 0x40;
if (this.x_axis.valueType.isLE()) flags |= 0x100;
// 300s
out += String.format(XDF_LBL+"0x%X\n", off+305, "Cols",
this.size.x);
out += String.format(XDF_LBL+"\"%s\"\n", off+320, "XUnits",
this.x_axis.units);
out += String.format(XDF_LBL+"0x%X\n", off+352,
"XLabelType", x_axis.precision==0?2:1);
if(this.x_axis.datasource.isOrdinal() && this.size.x>1) {
out += String.format(XDF_LBL+"%s\n", off+350, "XLabels",
ordinalArray(this.size.x));
out += String.format(XDF_LBL+"0x%X\n", off+352, "XLabelType", 2);
} else if(this.x_axis.addr!=null) {
out += this.x_axis.eqXDF(off+354, "XEq");
// 500s
out += String.format(XDF_LBL+"0x%X\n", off+505, "XLabelSource", 1);
// 600s
out += String.format(XDF_LBL+"0x%X\n", off+600, "XAddress",
this.x_axis.addr.v);
out += String.format(XDF_LBL+"%d\n", off+610, "XDataSize",
this.x_axis.valueType.width());
out += String.format(XDF_LBL+"%d\n", off+620, "XAddrStep",
this.x_axis.valueType.width());
if(x_axis.precision!=2) {
out += String.format(XDF_LBL+"0x%X\n", off+650,
"XOutputDig", x_axis.precision);
}
}
// Y (rows)
if (this.y_axis.sign) flags |= 0x80;
if (this.y_axis.valueType.isLE()) flags |= 0x200;
// 300s
out += String.format(XDF_LBL+"0x%X\n", off+300, "Rows",
this.size.y);
out += String.format(XDF_LBL+"\"%s\"\n", off+325, "YUnits",
this.y_axis.units);
// LabelType 0x1 = float, 0x2 = integer, 0x4 = string
out += String.format(XDF_LBL+"0x%X\n", off+362,
"YLabelType", y_axis.precision==0?2:1);
if(this.y_axis.datasource.isOrdinal() && this.size.y>1 ) {
out += String.format(XDF_LBL+"%s\n", off+360, "YLabels",
ordinalArray(this.size.y));
out += String.format(XDF_LBL+"0x%X\n", off+362, "YLabelType", 2);
} else if(this.y_axis.addr!=null) {
out += this.y_axis.eqXDF(off+364, "YEq");
// 500s
out += String.format(XDF_LBL+"0x%X\n", off+515, "YLabelSource", 1);
// 700s
out += String.format(XDF_LBL+"0x%X\n", off+700, "YAddress",
this.y_axis.addr.v);
out += String.format(XDF_LBL+"%d\n", off+710, "YDataSize",
this.y_axis.valueType.width());
out += String.format(XDF_LBL+"%d\n", off+720, "YAddrStep",
this.y_axis.valueType.width());
if(y_axis.precision!=2) {
out += String.format(XDF_LBL+"0x%X\n", off+750,
- "YOutputDig", x_axis.precision);
+ "YOutputDig", y_axis.precision);
}
}
}
out += String.format(XDF_LBL+"0x%X\n",off+150,"Flags", flags);
if(false && image!=null && image.limit()>0) {
MapData mapdata = new MapData(this, image);
if(table && this.x_axis.addr!=null) {
MapData xaxis = new MapData(new Map(this.x_axis, this.size.x),
image);
out += String.format(XDF_LBL+"%s\n", off+350, "XLabels",
xaxis.toString());
// LabelType 0x1 = float, 0x2 = integer, 0x4 = string
out += String.format(XDF_LBL+"0x%X\n", off+352,
"XLabelType", x_axis.precision==0?2:1);
if(!oneD && this.y_axis.addr!=null) {
MapData yaxis = new MapData(new Map(this.y_axis,
this.size.y), image);
out += String.format(XDF_LBL+"%s\n", off+360, "YLabels",
yaxis.toString());
}
}
/*
out += String.format(XDF_LBL+"%f\n", off+230, "RangeLow",
mapdata.getMinimumValue());
out += String.format(XDF_LBL+"%f\n", off+240, "RangeHigh",
mapdata.getMaximumValue());
*/
}
if(oneD) {
// LabelType 0x1 = float, 0x2 = integer, 0x4 = string
out += String.format(XDF_LBL+"%s\n", off+360, "YLabels",
this.y_axis.units);
out += String.format(XDF_LBL+"0x%X\n", off+362,
"YLabelType", 4);
}
return out + "%%END%%\n";
}
public String toString() {
String out = " h0: " + header0 + "\n";
out += " map: " + name + " [" + id + "] " + valueType + "\n";
out += " org: " + organization + "\n";
out += " h: " + header + "\n";
out += " ha: " + Arrays.toString(headera) + "\n";
out += "fdrId: " + folderId + "\n";
out += " h1: " + header1 + "\n";
out += " h1a: " + header1a + " (byte)\n";
out += "range: " + range[0] + "-" + range[2]+ "\n";
out += " h2: " + Arrays.toString(header2) + "\n";
out += "flags: ";
if(reciprocal) out += "R";
if(sign) out += "S";
if(difference) out += "D";
if(percent) out += "P";
out += "\n";
out += " size: " + size + "\n";
out += " h3: " + Arrays.toString(header3) + "\n";
out += " prec: " + precision + "\n";
out += "value: " + value + "\n";
out += " addr: " + Arrays.toString(extent) + "\n";
out += " h4: " + Arrays.toString(header4) + "\n";
out += " h5: " + Arrays.toString(header5) + "\n";
out += " h6: " + header6 + "\n";
out += " h7: " + header7 + "\n";
out += "xaxis: " + x_axis + "\n";
out += "yaxis: " + y_axis + "\n";
out += " h8: " + header8 + "\n";
out += " h8a: " + header8a + " (short)\n";
out += " h9: " + Arrays.toString(header9) + "\n";
out += " h9a: " + header9a + " (short)\n";
out += " h9b: " + header9b + "\n";
out += " h9c: " + header9c + " (byte)\n";
out += " h10: " + Arrays.toString(header10) + "\n";
out += " h11: " + Arrays.toString(header11) + "\n";
out += " term2: " + Arrays.toString(term2) + "\n";
return out;
}
}
| true | true | private String toStringXDF(ByteBuffer image) throws Exception {
boolean table = this.organization.isTable();
boolean oneD = this.organization.is1D() || this.size.y<=1;
String out = table?"%%TABLE%%\n":"%%CONSTANT%%\n";
out += String.format(XDF_LBL+"0x%X\n",100,"Cat0ID",this.folderId+1);
int off = table?40000:20000;
String title = "";
String desc = "";
if(this.id.length()>0) {
title = this.id.split(" ")[0]; // HACK: drop the junk
desc = this.name;
} else {
title = this.name;
}
out += String.format(XDF_LBL+"\"%s\"\n",off+5,"Title",title);
if(desc.length()>0) {
out += String.format(XDF_LBL+"\"%s\"\n",off+10,"Desc",desc);
out += String.format(XDF_LBL+"0x%X\n",off+11,"DescSize",
desc.length()+1);
}
if(this.value.units.length()>0) {
if(table)
out += String.format(XDF_LBL+"\"%s\"\n",off+330,"ZUnits",
this.value.units);
else
out += String.format(XDF_LBL+"\"%s\"\n",off+20,"Units",
this.value.units);
}
if(this.valueType.width()>1) {
out += String.format(XDF_LBL+"0x%X\n",off+50,"SizeInBits",
this.valueType.width()*8);
}
// XDF "Flags"
// -----------
// 0x001 - z value signed
// 0x002 - z value LE
// 0x040 - x axis signed
// 0x100 - x axis LE
// 0x080 - y axis signed
// 0x200 - y axis LE
int flags = this.sign?1:0;
if (this.valueType.isLE()) flags |= 2;
out += String.format(XDF_LBL+"0x%X\n",off+100,"Address",
this.extent[0].v);
out += this.value.eqXDF(off+200, table?"ZEq":"Equation");
if(table) {
if (this.size.x > 0x100 && this.size.y <= 0x100) {
// swap x and y; tunerpro crashes on Cols > 256
Axis tmpa = this.y_axis;
this.y_axis = this.x_axis;
this.x_axis = tmpa;
int tmp = this.size.y;
this.size.y = this.size.x;
this.size.x = tmp;
}
// X (columns)
if (this.x_axis.sign) flags |= 0x40;
if (this.x_axis.valueType.isLE()) flags |= 0x100;
// 300s
out += String.format(XDF_LBL+"0x%X\n", off+305, "Cols",
this.size.x);
out += String.format(XDF_LBL+"\"%s\"\n", off+320, "XUnits",
this.x_axis.units);
out += String.format(XDF_LBL+"0x%X\n", off+352,
"XLabelType", x_axis.precision==0?2:1);
if(this.x_axis.datasource.isOrdinal() && this.size.x>1) {
out += String.format(XDF_LBL+"%s\n", off+350, "XLabels",
ordinalArray(this.size.x));
out += String.format(XDF_LBL+"0x%X\n", off+352, "XLabelType", 2);
} else if(this.x_axis.addr!=null) {
out += this.x_axis.eqXDF(off+354, "XEq");
// 500s
out += String.format(XDF_LBL+"0x%X\n", off+505, "XLabelSource", 1);
// 600s
out += String.format(XDF_LBL+"0x%X\n", off+600, "XAddress",
this.x_axis.addr.v);
out += String.format(XDF_LBL+"%d\n", off+610, "XDataSize",
this.x_axis.valueType.width());
out += String.format(XDF_LBL+"%d\n", off+620, "XAddrStep",
this.x_axis.valueType.width());
if(x_axis.precision!=2) {
out += String.format(XDF_LBL+"0x%X\n", off+650,
"XOutputDig", x_axis.precision);
}
}
// Y (rows)
if (this.y_axis.sign) flags |= 0x80;
if (this.y_axis.valueType.isLE()) flags |= 0x200;
// 300s
out += String.format(XDF_LBL+"0x%X\n", off+300, "Rows",
this.size.y);
out += String.format(XDF_LBL+"\"%s\"\n", off+325, "YUnits",
this.y_axis.units);
// LabelType 0x1 = float, 0x2 = integer, 0x4 = string
out += String.format(XDF_LBL+"0x%X\n", off+362,
"YLabelType", y_axis.precision==0?2:1);
if(this.y_axis.datasource.isOrdinal() && this.size.y>1 ) {
out += String.format(XDF_LBL+"%s\n", off+360, "YLabels",
ordinalArray(this.size.y));
out += String.format(XDF_LBL+"0x%X\n", off+362, "YLabelType", 2);
} else if(this.y_axis.addr!=null) {
out += this.y_axis.eqXDF(off+364, "YEq");
// 500s
out += String.format(XDF_LBL+"0x%X\n", off+515, "YLabelSource", 1);
// 700s
out += String.format(XDF_LBL+"0x%X\n", off+700, "YAddress",
this.y_axis.addr.v);
out += String.format(XDF_LBL+"%d\n", off+710, "YDataSize",
this.y_axis.valueType.width());
out += String.format(XDF_LBL+"%d\n", off+720, "YAddrStep",
this.y_axis.valueType.width());
if(y_axis.precision!=2) {
out += String.format(XDF_LBL+"0x%X\n", off+750,
"YOutputDig", x_axis.precision);
}
}
}
out += String.format(XDF_LBL+"0x%X\n",off+150,"Flags", flags);
if(false && image!=null && image.limit()>0) {
MapData mapdata = new MapData(this, image);
if(table && this.x_axis.addr!=null) {
MapData xaxis = new MapData(new Map(this.x_axis, this.size.x),
image);
out += String.format(XDF_LBL+"%s\n", off+350, "XLabels",
xaxis.toString());
// LabelType 0x1 = float, 0x2 = integer, 0x4 = string
out += String.format(XDF_LBL+"0x%X\n", off+352,
"XLabelType", x_axis.precision==0?2:1);
if(!oneD && this.y_axis.addr!=null) {
MapData yaxis = new MapData(new Map(this.y_axis,
this.size.y), image);
out += String.format(XDF_LBL+"%s\n", off+360, "YLabels",
yaxis.toString());
}
}
/*
out += String.format(XDF_LBL+"%f\n", off+230, "RangeLow",
mapdata.getMinimumValue());
out += String.format(XDF_LBL+"%f\n", off+240, "RangeHigh",
mapdata.getMaximumValue());
*/
}
if(oneD) {
// LabelType 0x1 = float, 0x2 = integer, 0x4 = string
out += String.format(XDF_LBL+"%s\n", off+360, "YLabels",
this.y_axis.units);
out += String.format(XDF_LBL+"0x%X\n", off+362,
"YLabelType", 4);
}
return out + "%%END%%\n";
}
| private String toStringXDF(ByteBuffer image) throws Exception {
boolean table = this.organization.isTable();
boolean oneD = this.organization.is1D() || this.size.y<=1;
String out = table?"%%TABLE%%\n":"%%CONSTANT%%\n";
out += String.format(XDF_LBL+"0x%X\n",100,"Cat0ID",this.folderId+1);
int off = table?40000:20000;
String title = "";
String desc = "";
if(this.id.length()>0) {
title = this.id.split(" ")[0]; // HACK: drop the junk
desc = this.name;
} else {
title = this.name;
}
out += String.format(XDF_LBL+"\"%s\"\n",off+5,"Title",title);
if(desc.length()>0) {
out += String.format(XDF_LBL+"\"%s\"\n",off+10,"Desc",desc);
out += String.format(XDF_LBL+"0x%X\n",off+11,"DescSize",
desc.length()+1);
}
if(this.value.units.length()>0) {
if(table)
out += String.format(XDF_LBL+"\"%s\"\n",off+330,"ZUnits",
this.value.units);
else
out += String.format(XDF_LBL+"\"%s\"\n",off+20,"Units",
this.value.units);
}
if(this.valueType.width()>1) {
out += String.format(XDF_LBL+"0x%X\n",off+50,"SizeInBits",
this.valueType.width()*8);
}
// XDF "Flags"
// -----------
// 0x001 - z value signed
// 0x002 - z value LE
// 0x040 - x axis signed
// 0x100 - x axis LE
// 0x080 - y axis signed
// 0x200 - y axis LE
int flags = this.sign?1:0;
if (this.valueType.isLE()) flags |= 2;
out += String.format(XDF_LBL+"0x%X\n",off+100,"Address",
this.extent[0].v);
out += this.value.eqXDF(off+200, table?"ZEq":"Equation");
if(table) {
if (this.size.x > 0x100 && this.size.y <= 0x100) {
// swap x and y; tunerpro crashes on Cols > 256
Axis tmpa = this.y_axis;
this.y_axis = this.x_axis;
this.x_axis = tmpa;
int tmp = this.size.y;
this.size.y = this.size.x;
this.size.x = tmp;
}
// X (columns)
if (this.x_axis.sign) flags |= 0x40;
if (this.x_axis.valueType.isLE()) flags |= 0x100;
// 300s
out += String.format(XDF_LBL+"0x%X\n", off+305, "Cols",
this.size.x);
out += String.format(XDF_LBL+"\"%s\"\n", off+320, "XUnits",
this.x_axis.units);
out += String.format(XDF_LBL+"0x%X\n", off+352,
"XLabelType", x_axis.precision==0?2:1);
if(this.x_axis.datasource.isOrdinal() && this.size.x>1) {
out += String.format(XDF_LBL+"%s\n", off+350, "XLabels",
ordinalArray(this.size.x));
out += String.format(XDF_LBL+"0x%X\n", off+352, "XLabelType", 2);
} else if(this.x_axis.addr!=null) {
out += this.x_axis.eqXDF(off+354, "XEq");
// 500s
out += String.format(XDF_LBL+"0x%X\n", off+505, "XLabelSource", 1);
// 600s
out += String.format(XDF_LBL+"0x%X\n", off+600, "XAddress",
this.x_axis.addr.v);
out += String.format(XDF_LBL+"%d\n", off+610, "XDataSize",
this.x_axis.valueType.width());
out += String.format(XDF_LBL+"%d\n", off+620, "XAddrStep",
this.x_axis.valueType.width());
if(x_axis.precision!=2) {
out += String.format(XDF_LBL+"0x%X\n", off+650,
"XOutputDig", x_axis.precision);
}
}
// Y (rows)
if (this.y_axis.sign) flags |= 0x80;
if (this.y_axis.valueType.isLE()) flags |= 0x200;
// 300s
out += String.format(XDF_LBL+"0x%X\n", off+300, "Rows",
this.size.y);
out += String.format(XDF_LBL+"\"%s\"\n", off+325, "YUnits",
this.y_axis.units);
// LabelType 0x1 = float, 0x2 = integer, 0x4 = string
out += String.format(XDF_LBL+"0x%X\n", off+362,
"YLabelType", y_axis.precision==0?2:1);
if(this.y_axis.datasource.isOrdinal() && this.size.y>1 ) {
out += String.format(XDF_LBL+"%s\n", off+360, "YLabels",
ordinalArray(this.size.y));
out += String.format(XDF_LBL+"0x%X\n", off+362, "YLabelType", 2);
} else if(this.y_axis.addr!=null) {
out += this.y_axis.eqXDF(off+364, "YEq");
// 500s
out += String.format(XDF_LBL+"0x%X\n", off+515, "YLabelSource", 1);
// 700s
out += String.format(XDF_LBL+"0x%X\n", off+700, "YAddress",
this.y_axis.addr.v);
out += String.format(XDF_LBL+"%d\n", off+710, "YDataSize",
this.y_axis.valueType.width());
out += String.format(XDF_LBL+"%d\n", off+720, "YAddrStep",
this.y_axis.valueType.width());
if(y_axis.precision!=2) {
out += String.format(XDF_LBL+"0x%X\n", off+750,
"YOutputDig", y_axis.precision);
}
}
}
out += String.format(XDF_LBL+"0x%X\n",off+150,"Flags", flags);
if(false && image!=null && image.limit()>0) {
MapData mapdata = new MapData(this, image);
if(table && this.x_axis.addr!=null) {
MapData xaxis = new MapData(new Map(this.x_axis, this.size.x),
image);
out += String.format(XDF_LBL+"%s\n", off+350, "XLabels",
xaxis.toString());
// LabelType 0x1 = float, 0x2 = integer, 0x4 = string
out += String.format(XDF_LBL+"0x%X\n", off+352,
"XLabelType", x_axis.precision==0?2:1);
if(!oneD && this.y_axis.addr!=null) {
MapData yaxis = new MapData(new Map(this.y_axis,
this.size.y), image);
out += String.format(XDF_LBL+"%s\n", off+360, "YLabels",
yaxis.toString());
}
}
/*
out += String.format(XDF_LBL+"%f\n", off+230, "RangeLow",
mapdata.getMinimumValue());
out += String.format(XDF_LBL+"%f\n", off+240, "RangeHigh",
mapdata.getMaximumValue());
*/
}
if(oneD) {
// LabelType 0x1 = float, 0x2 = integer, 0x4 = string
out += String.format(XDF_LBL+"%s\n", off+360, "YLabels",
this.y_axis.units);
out += String.format(XDF_LBL+"0x%X\n", off+362,
"YLabelType", 4);
}
return out + "%%END%%\n";
}
|
diff --git a/Toolbox/src/biz/shadowservices/DegreesToolbox/DataFetcher.java b/Toolbox/src/biz/shadowservices/DegreesToolbox/DataFetcher.java
index f259f15..b90cf24 100644
--- a/Toolbox/src/biz/shadowservices/DegreesToolbox/DataFetcher.java
+++ b/Toolbox/src/biz/shadowservices/DegreesToolbox/DataFetcher.java
@@ -1,436 +1,428 @@
/*******************************************************************************
* Copyright (c) 2011 Jordan Thoms.
*
* 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 biz.shadowservices.DegreesToolbox;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.message.BasicNameValuePair;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import de.quist.app.errorreporter.ExceptionReporter;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.preference.PreferenceManager;
import android.util.Log;
public class DataFetcher {
// This class handles the actual fetching of the data from 2Degrees.
public double result;
public static final String LASTMONTHCHARGES = "Your last month's charges";
private static String TAG = "2DegreesDataFetcher";
private ExceptionReporter exceptionReporter;
public enum FetchResult {
SUCCESS,
NOTONLINE,
LOGINFAILED,
USERNAMEPASSWORDNOTSET,
NETWORKERROR,
NOTALLOWED
}
public DataFetcher(ExceptionReporter e) {
exceptionReporter = e;
}
public boolean isOnline(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info == null) {
return false;
} else {
return info.isConnected();
}
}
public boolean isWifi(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (info == null) {
return false;
} else {
return info.isConnected();
}
}
public boolean isRoaming(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (info == null) {
return false;
} else {
return info.isRoaming();
}
}
public boolean isBackgroundDataEnabled(Context context) {
ConnectivityManager mgr = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
return(mgr.getBackgroundDataSetting());
}
public boolean isAutoSyncEnabled() {
// Get the autosync setting, if on a phone which has one.
// There are better ways of doing this than reflection, but it's easy in this case
// since then we can keep linking against the 1.6 SDK.
if (android.os.Build.VERSION.SDK_INT >= 5) {
Class<ContentResolver> contentResolverClass = ContentResolver.class;
try {
Method m = contentResolverClass.getMethod("getMasterSyncAutomatically", null);
Log.d(TAG, m.toString());
Log.d(TAG, m.invoke(null, null).toString());
boolean bool = ((Boolean)m.invoke(null, null)).booleanValue();
return bool;
} catch (Exception e) {
Log.d(TAG, "could not determine if autosync is enabled, assuming yes");
return true;
}
} else {
return true;
}
}
public FetchResult updateData(Context context, boolean force) {
//Open database
DBOpenHelper dbhelper = new DBOpenHelper(context);
SQLiteDatabase db = dbhelper.getWritableDatabase();
// check for internet connectivity
try {
if (!isOnline(context)) {
Log.d(TAG, "We do not seem to be online. Skipping Update.");
return FetchResult.NOTONLINE;
}
} catch (Exception e) {
exceptionReporter.reportException(Thread.currentThread(), e, "Exception during isOnline()");
}
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
if (!force) {
try {
if (sp.getBoolean("loginFailed", false) == true) {
Log.d(TAG, "Previous login failed. Skipping Update.");
DBLog.insertMessage(context, "i", TAG, "Previous login failed. Skipping Update.");
return FetchResult.LOGINFAILED;
}
if(sp.getBoolean("autoupdates", true) == false) {
Log.d(TAG, "Automatic updates not enabled. Skipping Update.");
DBLog.insertMessage(context, "i", TAG, "Automatic updates not enabled. Skipping Update.");
return FetchResult.NOTALLOWED;
}
if (!isBackgroundDataEnabled(context) && sp.getBoolean("obeyBackgroundData", true)) {
Log.d(TAG, "Background data not enabled. Skipping Update.");
DBLog.insertMessage(context, "i", TAG, "Background data not enabled. Skipping Update.");
return FetchResult.NOTALLOWED;
}
if (!isAutoSyncEnabled() && sp.getBoolean("obeyAutoSync", true) && sp.getBoolean("obeyBackgroundData", true)) {
Log.d(TAG, "Auto sync not enabled. Skipping Update.");
DBLog.insertMessage(context, "i", TAG, "Auto sync not enabled. Skipping Update.");
return FetchResult.NOTALLOWED;
}
if (isWifi(context) && !sp.getBoolean("wifiUpdates", true)) {
Log.d(TAG, "On wifi, and wifi auto updates not allowed. Skipping Update");
DBLog.insertMessage(context, "i", TAG, "On wifi, and wifi auto updates not allowed. Skipping Update");
return FetchResult.NOTALLOWED;
} else if (!isWifi(context)){
Log.d(TAG, "We are not on wifi.");
if (!isRoaming(context) && !sp.getBoolean("2DData", true)) {
Log.d(TAG, "Automatic updates on 2Degrees data not enabled. Skipping Update.");
DBLog.insertMessage(context, "i", TAG, "Automatic updates on 2Degrees data not enabled. Skipping Update.");
return FetchResult.NOTALLOWED;
} else if (isRoaming(context) && !sp.getBoolean("roamingData", false)) {
Log.d(TAG, "Automatic updates on roaming mobile data not enabled. Skipping Update.");
DBLog.insertMessage(context, "i", TAG, "Automatic updates on roaming mobile data not enabled. Skipping Update.");
return FetchResult.NOTALLOWED;
}
}
} catch (Exception e) {
exceptionReporter.reportException(Thread.currentThread(), e, "Exception while finding if to update.");
}
} else {
Log.d(TAG, "Update Forced");
}
try {
String username = sp.getString("username", null);
String password = sp.getString("password", null);
if(username == null || password == null) {
DBLog.insertMessage(context, "i", TAG, "Username or password not set.");
return FetchResult.USERNAMEPASSWORDNOTSET;
}
// Find the URL of the page to send login data to.
Log.d(TAG, "Finding Action. ");
HttpGetter loginPageGet = new HttpGetter("https://secure.2degreesmobile.co.nz/web/ip/login");
String loginPageString = loginPageGet.execute();
if (loginPageString != null) {
Document loginPage = Jsoup.parse(loginPageString, "https://secure.2degreesmobile.co.nz/web/ip/login");
Element loginForm = loginPage.getElementsByAttributeValue("name", "loginFrm").first();
String loginAction = loginForm.attr("action");
// Send login form
List<NameValuePair> loginValues = new ArrayList <NameValuePair>();
loginValues.add(new BasicNameValuePair("externalURLRedirect", ""));
loginValues.add(new BasicNameValuePair("hdnAction", "login_userlogin"));
loginValues.add(new BasicNameValuePair("hdnAuthenticationType", "M"));
loginValues.add(new BasicNameValuePair("hdnlocale", ""));
loginValues.add(new BasicNameValuePair("userid", username));
loginValues.add(new BasicNameValuePair("password", password));
Log.d(TAG, "Sending Login ");
HttpPoster sendLoginPoster = new HttpPoster(loginAction, loginValues);
// Parse result
Document homePage = Jsoup.parse(sendLoginPoster.execute());
// Determine if this is a pre-pay or post-paid account.
boolean postPaid;
if (homePage.getElementById("p_p_id_PostPaidHomePage_WAR_Homepage_") == null) {
Log.d(TAG, "Pre-pay account or no account.");
postPaid = false;
} else {
Log.d(TAG, "Post-paid account.");
postPaid = true;
}
Element accountSummary = homePage.getElementById("accountSummary");
if (accountSummary == null) {
Log.d(TAG, "Login failed.");
return FetchResult.LOGINFAILED;
}
db.delete("cache", "", null);
/* This code fetched some extra details for postpaid users, but on reflection they aren't that useful.
* Might reconsider this.
*
if (postPaid) {
Element accountBalanceSummaryTable = accountSummary.getElementsByClass("tableBillSummary").first();
Elements rows = accountBalanceSummaryTable.getElementsByTag("tr");
int rowno = 0;
for (Element row : rows) {
if (rowno > 1) {
break;
}
//Log.d(TAG, "Starting row");
//Log.d(TAG, row.html());
Double value;
try {
Element amount = row.getElementsByClass("tableBillamount").first();
String amountHTML = amount.html();
Log.d(TAG, amountHTML.substring(1));
value = Double.parseDouble(amountHTML.substring(1));
} catch (Exception e) {
Log.d(TAG, "Failed to parse amount from row.");
value = null;
}
String expiresDetails = "";
String expiresDate = null;
String name = null;
try {
Element details = row.getElementsByClass("tableBilldetail").first();
name = details.ownText();
Element expires = details.getElementsByTag("em").first();
if (expires != null) {
expiresDetails = expires.text();
}
Log.d(TAG, expiresDetails);
Pattern pattern;
pattern = Pattern.compile("\\(payment is due (.*)\\)");
Matcher matcher = pattern.matcher(expiresDetails);
if (matcher.find()) {
/*Log.d(TAG, "matched expires");
Log.d(TAG, "group 0:" + matcher.group(0));
Log.d(TAG, "group 1:" + matcher.group(1));
Log.d(TAG, "group 2:" + matcher.group(2)); *
String expiresDateString = matcher.group(1);
Date expiresDateObj;
if (expiresDateString != null) {
if (expiresDateString.length() > 0) {
try {
expiresDateObj = DateFormatters.EXPIRESDATE.parse(expiresDateString);
expiresDate = DateFormatters.ISO8601DATEONLYFORMAT.format(expiresDateObj);
} catch (java.text.ParseException e) {
Log.d(TAG, "Could not parse date: " + expiresDateString);
}
}
}
}
} catch (Exception e) {
Log.d(TAG, "Failed to parse details from row.");
}
String expirev = null;
ContentValues values = new ContentValues();
values.put("name", name);
values.put("value", value);
values.put("units", "$NZ");
values.put("expires_value", expirev );
values.put("expires_date", expiresDate);
db.insert("cache", "value", values );
rowno++;
}
} */
Element accountSummaryTable = accountSummary.getElementsByClass("tableAccountSummary").first();
Elements rows = accountSummaryTable.getElementsByTag("tr");
for (Element row : rows) {
// We are now looking at each of the rows in the data table.
//Log.d(TAG, "Starting row");
//Log.d(TAG, row.html());
Double value;
String units;
try {
Element amount = row.getElementsByClass("tableBillamount").first();
String amountHTML = amount.html();
//Log.d(TAG, amountHTML);
String[] amountParts = amountHTML.split(" ", 2);
//Log.d(TAG, amountParts[0]);
//Log.d(TAG, amountParts[1]);
if (amountParts[0].contains("Included") || amountParts[0].equals("All You Need")) {
value = Values.INCLUDED;
} else {
try {
value = Double.parseDouble(amountParts[0]);
} catch (NumberFormatException e) {
exceptionReporter.reportException(Thread.currentThread(), e, "Decoding value.");
value = 0.0;
}
}
units = amountParts[1];
} catch (NullPointerException e) {
//Log.d(TAG, "Failed to parse amount from row.");
value = null;
units = null;
}
Element details = row.getElementsByClass("tableBilldetail").first();
String name = details.getElementsByTag("strong").first().text();
Element expires = details.getElementsByTag("em").first();
String expiresDetails = "";
if (expires != null) {
expiresDetails = expires.text();
}
Log.d(TAG, expiresDetails);
Pattern pattern;
if (postPaid == false) {
pattern = Pattern.compile("\\(([\\d\\.]*) ?\\w*? ?expiring on (.*)\\)");
} else {
pattern = Pattern.compile("\\(([\\d\\.]*) ?\\w*? ?will expire on (.*)\\)");
}
Matcher matcher = pattern.matcher(expiresDetails);
Double expiresValue = null;
String expiresDate = null;
if (matcher.find()) {
/*Log.d(TAG, "matched expires");
Log.d(TAG, "group 0:" + matcher.group(0));
Log.d(TAG, "group 1:" + matcher.group(1));
Log.d(TAG, "group 2:" + matcher.group(2)); */
try {
expiresValue = Double.parseDouble(matcher.group(1));
} catch (NumberFormatException e) {
expiresValue = null;
}
String expiresDateString = matcher.group(2);
Date expiresDateObj;
if (expiresDateString != null) {
if (expiresDateString.length() > 0) {
try {
expiresDateObj = DateFormatters.EXPIRESDATE.parse(expiresDateString);
expiresDate = DateFormatters.ISO8601DATEONLYFORMAT.format(expiresDateObj);
} catch (java.text.ParseException e) {
Log.d(TAG, "Could not parse date: " + expiresDateString);
}
}
}
}
ContentValues values = new ContentValues();
values.put("name", name);
values.put("value", value);
values.put("units", units);
values.put("expires_value", expiresValue);
values.put("expires_date", expiresDate);
db.insert("cache", "value", values );
}
if(postPaid == false) {
Log.d(TAG, "Getting Value packs...");
// Find value packs
HttpGetter valuePacksPageGet = new HttpGetter("https://secure.2degreesmobile.co.nz/group/ip/prevaluepack");
String valuePacksPageString = valuePacksPageGet.execute();
//DBLog.insertMessage(context, "d", "", valuePacksPageString);
if(valuePacksPageString != null) {
Document valuePacksPage = Jsoup.parse(valuePacksPageString);
Elements enabledPacks = valuePacksPage.getElementsByClass("yellow");
for (Element enabledPack : enabledPacks) {
Element offerNameElemt = enabledPack.getElementsByAttributeValueStarting("name", "offername").first();
- String offerName = offerNameElemt.val();
- DBLog.insertMessage(context, "d", "", "Got element: " + offerName);
- ValuePack[] packs = Values.valuePacks.get(offerName);
- if (packs == null) {
- DBLog.insertMessage(context, "d", "", "Offer name: " + offerName + " not matched.");
- } else {
- for (ValuePack pack: packs) {
- // Cursor csr = db.query("cache", null, "name = '" + pack.type.id + "'", null, null, null, null);
- // if (csr.getCount() == 1) {
- // csr.moveToFirst();
+ if (offerNameElemt != null) {
+ String offerName = offerNameElemt.val();
+ DBLog.insertMessage(context, "d", "", "Got element: " + offerName);
+ ValuePack[] packs = Values.valuePacks.get(offerName);
+ if (packs == null) {
+ DBLog.insertMessage(context, "d", "", "Offer name: " + offerName + " not matched.");
+ } else {
+ for (ValuePack pack: packs) {
ContentValues values = new ContentValues();
- // Not sure why adding on the previous value?
- //values.put("plan_startamount", csr.getDouble(4) + pack.value);
- //DBLog.insertMessage(context, "d", "", "Pack " + pack.type.id + " start value set to " + csr.getDouble(4) + pack.value);
values.put("plan_startamount", pack.value);
values.put("plan_name", offerName);
DBLog.insertMessage(context, "d", "", "Pack " + pack.type.id + " start value set to " + pack.value);
db.update("cache", values, "name = '" + pack.type.id + "'", null);
- // } else {
- // DBLog.insertMessage(context, "d", "", "Pack " + pack.type.id + " Couldn't find item to add to");
- // }
- // csr.close();
+ }
}
}
}
}
}
SharedPreferences.Editor prefedit = sp.edit();
Date now = new Date();
prefedit.putString("updateDate", DateFormatters.ISO8601FORMAT.format(now));
prefedit.putBoolean("loginFailed", false);
prefedit.putBoolean("networkError", false);
prefedit.commit();
DBLog.insertMessage(context, "i", TAG, "Update Successful");
return FetchResult.SUCCESS;
}
} catch (ClientProtocolException e) {
DBLog.insertMessage(context, "w", TAG, "Network error: " + e.getMessage());
return FetchResult.NETWORKERROR;
} catch (IOException e) {
DBLog.insertMessage(context, "w", TAG, "Network error: " + e.getMessage());
return FetchResult.NETWORKERROR;
}
finally {
db.close();
}
return null;
}
}
| false | true | public FetchResult updateData(Context context, boolean force) {
//Open database
DBOpenHelper dbhelper = new DBOpenHelper(context);
SQLiteDatabase db = dbhelper.getWritableDatabase();
// check for internet connectivity
try {
if (!isOnline(context)) {
Log.d(TAG, "We do not seem to be online. Skipping Update.");
return FetchResult.NOTONLINE;
}
} catch (Exception e) {
exceptionReporter.reportException(Thread.currentThread(), e, "Exception during isOnline()");
}
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
if (!force) {
try {
if (sp.getBoolean("loginFailed", false) == true) {
Log.d(TAG, "Previous login failed. Skipping Update.");
DBLog.insertMessage(context, "i", TAG, "Previous login failed. Skipping Update.");
return FetchResult.LOGINFAILED;
}
if(sp.getBoolean("autoupdates", true) == false) {
Log.d(TAG, "Automatic updates not enabled. Skipping Update.");
DBLog.insertMessage(context, "i", TAG, "Automatic updates not enabled. Skipping Update.");
return FetchResult.NOTALLOWED;
}
if (!isBackgroundDataEnabled(context) && sp.getBoolean("obeyBackgroundData", true)) {
Log.d(TAG, "Background data not enabled. Skipping Update.");
DBLog.insertMessage(context, "i", TAG, "Background data not enabled. Skipping Update.");
return FetchResult.NOTALLOWED;
}
if (!isAutoSyncEnabled() && sp.getBoolean("obeyAutoSync", true) && sp.getBoolean("obeyBackgroundData", true)) {
Log.d(TAG, "Auto sync not enabled. Skipping Update.");
DBLog.insertMessage(context, "i", TAG, "Auto sync not enabled. Skipping Update.");
return FetchResult.NOTALLOWED;
}
if (isWifi(context) && !sp.getBoolean("wifiUpdates", true)) {
Log.d(TAG, "On wifi, and wifi auto updates not allowed. Skipping Update");
DBLog.insertMessage(context, "i", TAG, "On wifi, and wifi auto updates not allowed. Skipping Update");
return FetchResult.NOTALLOWED;
} else if (!isWifi(context)){
Log.d(TAG, "We are not on wifi.");
if (!isRoaming(context) && !sp.getBoolean("2DData", true)) {
Log.d(TAG, "Automatic updates on 2Degrees data not enabled. Skipping Update.");
DBLog.insertMessage(context, "i", TAG, "Automatic updates on 2Degrees data not enabled. Skipping Update.");
return FetchResult.NOTALLOWED;
} else if (isRoaming(context) && !sp.getBoolean("roamingData", false)) {
Log.d(TAG, "Automatic updates on roaming mobile data not enabled. Skipping Update.");
DBLog.insertMessage(context, "i", TAG, "Automatic updates on roaming mobile data not enabled. Skipping Update.");
return FetchResult.NOTALLOWED;
}
}
} catch (Exception e) {
exceptionReporter.reportException(Thread.currentThread(), e, "Exception while finding if to update.");
}
} else {
Log.d(TAG, "Update Forced");
}
try {
String username = sp.getString("username", null);
String password = sp.getString("password", null);
if(username == null || password == null) {
DBLog.insertMessage(context, "i", TAG, "Username or password not set.");
return FetchResult.USERNAMEPASSWORDNOTSET;
}
// Find the URL of the page to send login data to.
Log.d(TAG, "Finding Action. ");
HttpGetter loginPageGet = new HttpGetter("https://secure.2degreesmobile.co.nz/web/ip/login");
String loginPageString = loginPageGet.execute();
if (loginPageString != null) {
Document loginPage = Jsoup.parse(loginPageString, "https://secure.2degreesmobile.co.nz/web/ip/login");
Element loginForm = loginPage.getElementsByAttributeValue("name", "loginFrm").first();
String loginAction = loginForm.attr("action");
// Send login form
List<NameValuePair> loginValues = new ArrayList <NameValuePair>();
loginValues.add(new BasicNameValuePair("externalURLRedirect", ""));
loginValues.add(new BasicNameValuePair("hdnAction", "login_userlogin"));
loginValues.add(new BasicNameValuePair("hdnAuthenticationType", "M"));
loginValues.add(new BasicNameValuePair("hdnlocale", ""));
loginValues.add(new BasicNameValuePair("userid", username));
loginValues.add(new BasicNameValuePair("password", password));
Log.d(TAG, "Sending Login ");
HttpPoster sendLoginPoster = new HttpPoster(loginAction, loginValues);
// Parse result
Document homePage = Jsoup.parse(sendLoginPoster.execute());
// Determine if this is a pre-pay or post-paid account.
boolean postPaid;
if (homePage.getElementById("p_p_id_PostPaidHomePage_WAR_Homepage_") == null) {
Log.d(TAG, "Pre-pay account or no account.");
postPaid = false;
} else {
Log.d(TAG, "Post-paid account.");
postPaid = true;
}
Element accountSummary = homePage.getElementById("accountSummary");
if (accountSummary == null) {
Log.d(TAG, "Login failed.");
return FetchResult.LOGINFAILED;
}
db.delete("cache", "", null);
/* This code fetched some extra details for postpaid users, but on reflection they aren't that useful.
* Might reconsider this.
*
if (postPaid) {
Element accountBalanceSummaryTable = accountSummary.getElementsByClass("tableBillSummary").first();
Elements rows = accountBalanceSummaryTable.getElementsByTag("tr");
int rowno = 0;
for (Element row : rows) {
if (rowno > 1) {
break;
}
//Log.d(TAG, "Starting row");
//Log.d(TAG, row.html());
Double value;
try {
Element amount = row.getElementsByClass("tableBillamount").first();
String amountHTML = amount.html();
Log.d(TAG, amountHTML.substring(1));
value = Double.parseDouble(amountHTML.substring(1));
} catch (Exception e) {
Log.d(TAG, "Failed to parse amount from row.");
value = null;
}
String expiresDetails = "";
String expiresDate = null;
String name = null;
try {
Element details = row.getElementsByClass("tableBilldetail").first();
name = details.ownText();
Element expires = details.getElementsByTag("em").first();
if (expires != null) {
expiresDetails = expires.text();
}
Log.d(TAG, expiresDetails);
Pattern pattern;
pattern = Pattern.compile("\\(payment is due (.*)\\)");
Matcher matcher = pattern.matcher(expiresDetails);
if (matcher.find()) {
/*Log.d(TAG, "matched expires");
Log.d(TAG, "group 0:" + matcher.group(0));
Log.d(TAG, "group 1:" + matcher.group(1));
Log.d(TAG, "group 2:" + matcher.group(2)); *
String expiresDateString = matcher.group(1);
Date expiresDateObj;
if (expiresDateString != null) {
if (expiresDateString.length() > 0) {
try {
expiresDateObj = DateFormatters.EXPIRESDATE.parse(expiresDateString);
expiresDate = DateFormatters.ISO8601DATEONLYFORMAT.format(expiresDateObj);
} catch (java.text.ParseException e) {
Log.d(TAG, "Could not parse date: " + expiresDateString);
}
}
}
}
} catch (Exception e) {
Log.d(TAG, "Failed to parse details from row.");
}
String expirev = null;
ContentValues values = new ContentValues();
values.put("name", name);
values.put("value", value);
values.put("units", "$NZ");
values.put("expires_value", expirev );
values.put("expires_date", expiresDate);
db.insert("cache", "value", values );
rowno++;
}
} */
Element accountSummaryTable = accountSummary.getElementsByClass("tableAccountSummary").first();
Elements rows = accountSummaryTable.getElementsByTag("tr");
for (Element row : rows) {
// We are now looking at each of the rows in the data table.
//Log.d(TAG, "Starting row");
//Log.d(TAG, row.html());
Double value;
String units;
try {
Element amount = row.getElementsByClass("tableBillamount").first();
String amountHTML = amount.html();
//Log.d(TAG, amountHTML);
String[] amountParts = amountHTML.split(" ", 2);
//Log.d(TAG, amountParts[0]);
//Log.d(TAG, amountParts[1]);
if (amountParts[0].contains("Included") || amountParts[0].equals("All You Need")) {
value = Values.INCLUDED;
} else {
try {
value = Double.parseDouble(amountParts[0]);
} catch (NumberFormatException e) {
exceptionReporter.reportException(Thread.currentThread(), e, "Decoding value.");
value = 0.0;
}
}
units = amountParts[1];
} catch (NullPointerException e) {
//Log.d(TAG, "Failed to parse amount from row.");
value = null;
units = null;
}
Element details = row.getElementsByClass("tableBilldetail").first();
String name = details.getElementsByTag("strong").first().text();
Element expires = details.getElementsByTag("em").first();
String expiresDetails = "";
if (expires != null) {
expiresDetails = expires.text();
}
Log.d(TAG, expiresDetails);
Pattern pattern;
if (postPaid == false) {
pattern = Pattern.compile("\\(([\\d\\.]*) ?\\w*? ?expiring on (.*)\\)");
} else {
pattern = Pattern.compile("\\(([\\d\\.]*) ?\\w*? ?will expire on (.*)\\)");
}
Matcher matcher = pattern.matcher(expiresDetails);
Double expiresValue = null;
String expiresDate = null;
if (matcher.find()) {
/*Log.d(TAG, "matched expires");
Log.d(TAG, "group 0:" + matcher.group(0));
Log.d(TAG, "group 1:" + matcher.group(1));
Log.d(TAG, "group 2:" + matcher.group(2)); */
try {
expiresValue = Double.parseDouble(matcher.group(1));
} catch (NumberFormatException e) {
expiresValue = null;
}
String expiresDateString = matcher.group(2);
Date expiresDateObj;
if (expiresDateString != null) {
if (expiresDateString.length() > 0) {
try {
expiresDateObj = DateFormatters.EXPIRESDATE.parse(expiresDateString);
expiresDate = DateFormatters.ISO8601DATEONLYFORMAT.format(expiresDateObj);
} catch (java.text.ParseException e) {
Log.d(TAG, "Could not parse date: " + expiresDateString);
}
}
}
}
ContentValues values = new ContentValues();
values.put("name", name);
values.put("value", value);
values.put("units", units);
values.put("expires_value", expiresValue);
values.put("expires_date", expiresDate);
db.insert("cache", "value", values );
}
if(postPaid == false) {
Log.d(TAG, "Getting Value packs...");
// Find value packs
HttpGetter valuePacksPageGet = new HttpGetter("https://secure.2degreesmobile.co.nz/group/ip/prevaluepack");
String valuePacksPageString = valuePacksPageGet.execute();
//DBLog.insertMessage(context, "d", "", valuePacksPageString);
if(valuePacksPageString != null) {
Document valuePacksPage = Jsoup.parse(valuePacksPageString);
Elements enabledPacks = valuePacksPage.getElementsByClass("yellow");
for (Element enabledPack : enabledPacks) {
Element offerNameElemt = enabledPack.getElementsByAttributeValueStarting("name", "offername").first();
String offerName = offerNameElemt.val();
DBLog.insertMessage(context, "d", "", "Got element: " + offerName);
ValuePack[] packs = Values.valuePacks.get(offerName);
if (packs == null) {
DBLog.insertMessage(context, "d", "", "Offer name: " + offerName + " not matched.");
} else {
for (ValuePack pack: packs) {
// Cursor csr = db.query("cache", null, "name = '" + pack.type.id + "'", null, null, null, null);
// if (csr.getCount() == 1) {
// csr.moveToFirst();
ContentValues values = new ContentValues();
// Not sure why adding on the previous value?
//values.put("plan_startamount", csr.getDouble(4) + pack.value);
//DBLog.insertMessage(context, "d", "", "Pack " + pack.type.id + " start value set to " + csr.getDouble(4) + pack.value);
values.put("plan_startamount", pack.value);
values.put("plan_name", offerName);
DBLog.insertMessage(context, "d", "", "Pack " + pack.type.id + " start value set to " + pack.value);
db.update("cache", values, "name = '" + pack.type.id + "'", null);
// } else {
// DBLog.insertMessage(context, "d", "", "Pack " + pack.type.id + " Couldn't find item to add to");
// }
// csr.close();
}
}
}
}
}
SharedPreferences.Editor prefedit = sp.edit();
Date now = new Date();
prefedit.putString("updateDate", DateFormatters.ISO8601FORMAT.format(now));
prefedit.putBoolean("loginFailed", false);
prefedit.putBoolean("networkError", false);
prefedit.commit();
DBLog.insertMessage(context, "i", TAG, "Update Successful");
return FetchResult.SUCCESS;
}
} catch (ClientProtocolException e) {
DBLog.insertMessage(context, "w", TAG, "Network error: " + e.getMessage());
return FetchResult.NETWORKERROR;
} catch (IOException e) {
DBLog.insertMessage(context, "w", TAG, "Network error: " + e.getMessage());
return FetchResult.NETWORKERROR;
}
finally {
db.close();
}
return null;
}
| public FetchResult updateData(Context context, boolean force) {
//Open database
DBOpenHelper dbhelper = new DBOpenHelper(context);
SQLiteDatabase db = dbhelper.getWritableDatabase();
// check for internet connectivity
try {
if (!isOnline(context)) {
Log.d(TAG, "We do not seem to be online. Skipping Update.");
return FetchResult.NOTONLINE;
}
} catch (Exception e) {
exceptionReporter.reportException(Thread.currentThread(), e, "Exception during isOnline()");
}
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
if (!force) {
try {
if (sp.getBoolean("loginFailed", false) == true) {
Log.d(TAG, "Previous login failed. Skipping Update.");
DBLog.insertMessage(context, "i", TAG, "Previous login failed. Skipping Update.");
return FetchResult.LOGINFAILED;
}
if(sp.getBoolean("autoupdates", true) == false) {
Log.d(TAG, "Automatic updates not enabled. Skipping Update.");
DBLog.insertMessage(context, "i", TAG, "Automatic updates not enabled. Skipping Update.");
return FetchResult.NOTALLOWED;
}
if (!isBackgroundDataEnabled(context) && sp.getBoolean("obeyBackgroundData", true)) {
Log.d(TAG, "Background data not enabled. Skipping Update.");
DBLog.insertMessage(context, "i", TAG, "Background data not enabled. Skipping Update.");
return FetchResult.NOTALLOWED;
}
if (!isAutoSyncEnabled() && sp.getBoolean("obeyAutoSync", true) && sp.getBoolean("obeyBackgroundData", true)) {
Log.d(TAG, "Auto sync not enabled. Skipping Update.");
DBLog.insertMessage(context, "i", TAG, "Auto sync not enabled. Skipping Update.");
return FetchResult.NOTALLOWED;
}
if (isWifi(context) && !sp.getBoolean("wifiUpdates", true)) {
Log.d(TAG, "On wifi, and wifi auto updates not allowed. Skipping Update");
DBLog.insertMessage(context, "i", TAG, "On wifi, and wifi auto updates not allowed. Skipping Update");
return FetchResult.NOTALLOWED;
} else if (!isWifi(context)){
Log.d(TAG, "We are not on wifi.");
if (!isRoaming(context) && !sp.getBoolean("2DData", true)) {
Log.d(TAG, "Automatic updates on 2Degrees data not enabled. Skipping Update.");
DBLog.insertMessage(context, "i", TAG, "Automatic updates on 2Degrees data not enabled. Skipping Update.");
return FetchResult.NOTALLOWED;
} else if (isRoaming(context) && !sp.getBoolean("roamingData", false)) {
Log.d(TAG, "Automatic updates on roaming mobile data not enabled. Skipping Update.");
DBLog.insertMessage(context, "i", TAG, "Automatic updates on roaming mobile data not enabled. Skipping Update.");
return FetchResult.NOTALLOWED;
}
}
} catch (Exception e) {
exceptionReporter.reportException(Thread.currentThread(), e, "Exception while finding if to update.");
}
} else {
Log.d(TAG, "Update Forced");
}
try {
String username = sp.getString("username", null);
String password = sp.getString("password", null);
if(username == null || password == null) {
DBLog.insertMessage(context, "i", TAG, "Username or password not set.");
return FetchResult.USERNAMEPASSWORDNOTSET;
}
// Find the URL of the page to send login data to.
Log.d(TAG, "Finding Action. ");
HttpGetter loginPageGet = new HttpGetter("https://secure.2degreesmobile.co.nz/web/ip/login");
String loginPageString = loginPageGet.execute();
if (loginPageString != null) {
Document loginPage = Jsoup.parse(loginPageString, "https://secure.2degreesmobile.co.nz/web/ip/login");
Element loginForm = loginPage.getElementsByAttributeValue("name", "loginFrm").first();
String loginAction = loginForm.attr("action");
// Send login form
List<NameValuePair> loginValues = new ArrayList <NameValuePair>();
loginValues.add(new BasicNameValuePair("externalURLRedirect", ""));
loginValues.add(new BasicNameValuePair("hdnAction", "login_userlogin"));
loginValues.add(new BasicNameValuePair("hdnAuthenticationType", "M"));
loginValues.add(new BasicNameValuePair("hdnlocale", ""));
loginValues.add(new BasicNameValuePair("userid", username));
loginValues.add(new BasicNameValuePair("password", password));
Log.d(TAG, "Sending Login ");
HttpPoster sendLoginPoster = new HttpPoster(loginAction, loginValues);
// Parse result
Document homePage = Jsoup.parse(sendLoginPoster.execute());
// Determine if this is a pre-pay or post-paid account.
boolean postPaid;
if (homePage.getElementById("p_p_id_PostPaidHomePage_WAR_Homepage_") == null) {
Log.d(TAG, "Pre-pay account or no account.");
postPaid = false;
} else {
Log.d(TAG, "Post-paid account.");
postPaid = true;
}
Element accountSummary = homePage.getElementById("accountSummary");
if (accountSummary == null) {
Log.d(TAG, "Login failed.");
return FetchResult.LOGINFAILED;
}
db.delete("cache", "", null);
/* This code fetched some extra details for postpaid users, but on reflection they aren't that useful.
* Might reconsider this.
*
if (postPaid) {
Element accountBalanceSummaryTable = accountSummary.getElementsByClass("tableBillSummary").first();
Elements rows = accountBalanceSummaryTable.getElementsByTag("tr");
int rowno = 0;
for (Element row : rows) {
if (rowno > 1) {
break;
}
//Log.d(TAG, "Starting row");
//Log.d(TAG, row.html());
Double value;
try {
Element amount = row.getElementsByClass("tableBillamount").first();
String amountHTML = amount.html();
Log.d(TAG, amountHTML.substring(1));
value = Double.parseDouble(amountHTML.substring(1));
} catch (Exception e) {
Log.d(TAG, "Failed to parse amount from row.");
value = null;
}
String expiresDetails = "";
String expiresDate = null;
String name = null;
try {
Element details = row.getElementsByClass("tableBilldetail").first();
name = details.ownText();
Element expires = details.getElementsByTag("em").first();
if (expires != null) {
expiresDetails = expires.text();
}
Log.d(TAG, expiresDetails);
Pattern pattern;
pattern = Pattern.compile("\\(payment is due (.*)\\)");
Matcher matcher = pattern.matcher(expiresDetails);
if (matcher.find()) {
/*Log.d(TAG, "matched expires");
Log.d(TAG, "group 0:" + matcher.group(0));
Log.d(TAG, "group 1:" + matcher.group(1));
Log.d(TAG, "group 2:" + matcher.group(2)); *
String expiresDateString = matcher.group(1);
Date expiresDateObj;
if (expiresDateString != null) {
if (expiresDateString.length() > 0) {
try {
expiresDateObj = DateFormatters.EXPIRESDATE.parse(expiresDateString);
expiresDate = DateFormatters.ISO8601DATEONLYFORMAT.format(expiresDateObj);
} catch (java.text.ParseException e) {
Log.d(TAG, "Could not parse date: " + expiresDateString);
}
}
}
}
} catch (Exception e) {
Log.d(TAG, "Failed to parse details from row.");
}
String expirev = null;
ContentValues values = new ContentValues();
values.put("name", name);
values.put("value", value);
values.put("units", "$NZ");
values.put("expires_value", expirev );
values.put("expires_date", expiresDate);
db.insert("cache", "value", values );
rowno++;
}
} */
Element accountSummaryTable = accountSummary.getElementsByClass("tableAccountSummary").first();
Elements rows = accountSummaryTable.getElementsByTag("tr");
for (Element row : rows) {
// We are now looking at each of the rows in the data table.
//Log.d(TAG, "Starting row");
//Log.d(TAG, row.html());
Double value;
String units;
try {
Element amount = row.getElementsByClass("tableBillamount").first();
String amountHTML = amount.html();
//Log.d(TAG, amountHTML);
String[] amountParts = amountHTML.split(" ", 2);
//Log.d(TAG, amountParts[0]);
//Log.d(TAG, amountParts[1]);
if (amountParts[0].contains("Included") || amountParts[0].equals("All You Need")) {
value = Values.INCLUDED;
} else {
try {
value = Double.parseDouble(amountParts[0]);
} catch (NumberFormatException e) {
exceptionReporter.reportException(Thread.currentThread(), e, "Decoding value.");
value = 0.0;
}
}
units = amountParts[1];
} catch (NullPointerException e) {
//Log.d(TAG, "Failed to parse amount from row.");
value = null;
units = null;
}
Element details = row.getElementsByClass("tableBilldetail").first();
String name = details.getElementsByTag("strong").first().text();
Element expires = details.getElementsByTag("em").first();
String expiresDetails = "";
if (expires != null) {
expiresDetails = expires.text();
}
Log.d(TAG, expiresDetails);
Pattern pattern;
if (postPaid == false) {
pattern = Pattern.compile("\\(([\\d\\.]*) ?\\w*? ?expiring on (.*)\\)");
} else {
pattern = Pattern.compile("\\(([\\d\\.]*) ?\\w*? ?will expire on (.*)\\)");
}
Matcher matcher = pattern.matcher(expiresDetails);
Double expiresValue = null;
String expiresDate = null;
if (matcher.find()) {
/*Log.d(TAG, "matched expires");
Log.d(TAG, "group 0:" + matcher.group(0));
Log.d(TAG, "group 1:" + matcher.group(1));
Log.d(TAG, "group 2:" + matcher.group(2)); */
try {
expiresValue = Double.parseDouble(matcher.group(1));
} catch (NumberFormatException e) {
expiresValue = null;
}
String expiresDateString = matcher.group(2);
Date expiresDateObj;
if (expiresDateString != null) {
if (expiresDateString.length() > 0) {
try {
expiresDateObj = DateFormatters.EXPIRESDATE.parse(expiresDateString);
expiresDate = DateFormatters.ISO8601DATEONLYFORMAT.format(expiresDateObj);
} catch (java.text.ParseException e) {
Log.d(TAG, "Could not parse date: " + expiresDateString);
}
}
}
}
ContentValues values = new ContentValues();
values.put("name", name);
values.put("value", value);
values.put("units", units);
values.put("expires_value", expiresValue);
values.put("expires_date", expiresDate);
db.insert("cache", "value", values );
}
if(postPaid == false) {
Log.d(TAG, "Getting Value packs...");
// Find value packs
HttpGetter valuePacksPageGet = new HttpGetter("https://secure.2degreesmobile.co.nz/group/ip/prevaluepack");
String valuePacksPageString = valuePacksPageGet.execute();
//DBLog.insertMessage(context, "d", "", valuePacksPageString);
if(valuePacksPageString != null) {
Document valuePacksPage = Jsoup.parse(valuePacksPageString);
Elements enabledPacks = valuePacksPage.getElementsByClass("yellow");
for (Element enabledPack : enabledPacks) {
Element offerNameElemt = enabledPack.getElementsByAttributeValueStarting("name", "offername").first();
if (offerNameElemt != null) {
String offerName = offerNameElemt.val();
DBLog.insertMessage(context, "d", "", "Got element: " + offerName);
ValuePack[] packs = Values.valuePacks.get(offerName);
if (packs == null) {
DBLog.insertMessage(context, "d", "", "Offer name: " + offerName + " not matched.");
} else {
for (ValuePack pack: packs) {
ContentValues values = new ContentValues();
values.put("plan_startamount", pack.value);
values.put("plan_name", offerName);
DBLog.insertMessage(context, "d", "", "Pack " + pack.type.id + " start value set to " + pack.value);
db.update("cache", values, "name = '" + pack.type.id + "'", null);
}
}
}
}
}
}
SharedPreferences.Editor prefedit = sp.edit();
Date now = new Date();
prefedit.putString("updateDate", DateFormatters.ISO8601FORMAT.format(now));
prefedit.putBoolean("loginFailed", false);
prefedit.putBoolean("networkError", false);
prefedit.commit();
DBLog.insertMessage(context, "i", TAG, "Update Successful");
return FetchResult.SUCCESS;
}
} catch (ClientProtocolException e) {
DBLog.insertMessage(context, "w", TAG, "Network error: " + e.getMessage());
return FetchResult.NETWORKERROR;
} catch (IOException e) {
DBLog.insertMessage(context, "w", TAG, "Network error: " + e.getMessage());
return FetchResult.NETWORKERROR;
}
finally {
db.close();
}
return null;
}
|
diff --git a/coin-selfservice-war/src/main/java/nl/surfnet/coin/selfservice/control/SpDetailController.java b/coin-selfservice-war/src/main/java/nl/surfnet/coin/selfservice/control/SpDetailController.java
index 632474d8..a05481ff 100644
--- a/coin-selfservice-war/src/main/java/nl/surfnet/coin/selfservice/control/SpDetailController.java
+++ b/coin-selfservice-war/src/main/java/nl/surfnet/coin/selfservice/control/SpDetailController.java
@@ -1,186 +1,185 @@
/*
* Copyright 2012 SURFnet bv, The Netherlands
*
* 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 nl.surfnet.coin.selfservice.control;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import nl.surfnet.coin.selfservice.command.LinkRequest;
import nl.surfnet.coin.selfservice.command.Question;
import nl.surfnet.coin.selfservice.domain.IdentityProvider;
import nl.surfnet.coin.selfservice.domain.JiraTask;
import nl.surfnet.coin.selfservice.domain.ServiceProvider;
import nl.surfnet.coin.selfservice.service.JiraService;
import nl.surfnet.coin.selfservice.service.ServiceProviderService;
/**
* Controller for SP detail pages
*/
@Controller
@RequestMapping("/sp")
public class SpDetailController {
@Resource(name="providerService")
private ServiceProviderService providerService;
@Resource(name="jiraService")
private JiraService jiraService;
private static final Logger LOG = LoggerFactory.getLogger(SpDetailController.class);
/**
* Controller for detail page.
*
* @param spEntityId the entity id
* @return ModelAndView
*/
@RequestMapping(value="/detail.shtml")
public ModelAndView spDetail(@RequestParam String spEntityId,
@ModelAttribute(value = "selectedidp") IdentityProvider selectedidp) {
Map<String, Object> m = new HashMap<String, Object>();
final ServiceProvider sp = providerService.getServiceProvider(spEntityId, selectedidp.getId());
m.put("sp", sp);
return new ModelAndView("sp-detail", m);
}
/**
* Controller for question form page.
*
* @param spEntityId the entity id
* @return ModelAndView
*/
@RequestMapping(value="/question.shtml", method= RequestMethod.GET)
public ModelAndView spQuestion(@RequestParam String spEntityId,
@ModelAttribute(value = "selectedidp") IdentityProvider selectedidp) {
Map<String, Object> m = new HashMap<String, Object>();
final ServiceProvider sp = providerService.getServiceProvider(spEntityId, selectedidp.getId());
m.put("question", new Question());
m.put("sp", sp);
return new ModelAndView("sp-question", m);
}
@RequestMapping(value="/question.shtml", method= RequestMethod.POST)
public ModelAndView spQuestionSubmit(@RequestParam String spEntityId,
@ModelAttribute(value = "selectedidp") IdentityProvider selectedidp,
@Valid @ModelAttribute("question") Question question, BindingResult result) {
Map<String, Object> m = new HashMap<String, Object>();
m.put("sp", providerService.getServiceProvider(spEntityId, selectedidp.getId()));
if (result.hasErrors()) {
LOG.debug("Errors in data binding, will return to form view: {}", result.getAllErrors());
return new ModelAndView("sp-question", m);
} else {
final JiraTask task = new JiraTask.Builder()
.body(question.getSubject() + ("\n\n" + question.getBody()))
// TODO: add a separate field 'subject' in JiraTask?
.identityProvider(SpListController.getCurrentUser().getIdp())
.serviceProvider(spEntityId)
.institution(SpListController.getCurrentUser().getInstitutionId())
.issueType(JiraTask.Type.QUESTION)
.status(JiraTask.Status.OPEN)
.build();
try {
final String issueKey = jiraService.create(task);
// TODO: log action
m.put("issueKey", issueKey);
return new ModelAndView("sp-question-thanks", m);
} catch (IOException e) {
LOG.debug("Error while trying to create Jira issue. Will return to form view",
e);
m.put("jiraError", e.getMessage());
return new ModelAndView("sp-question", m);
}
}
}
/**
* Controller for request form page.
*
* @param spEntityId the entity id
* @return ModelAndView
*/
@RequestMapping(value="/linkrequest.shtml", method= RequestMethod.GET)
public ModelAndView spRequest(@RequestParam String spEntityId,
@ModelAttribute(value = "selectedidp") IdentityProvider selectedidp) {
Map<String, Object> m = new HashMap<String, Object>();
final ServiceProvider sp = providerService.getServiceProvider(spEntityId, selectedidp.getId());
m.put("sp", sp);
m.put("linkrequest", new LinkRequest());
return new ModelAndView("sp-linkrequest", m);
}
@RequestMapping(value="/linkrequest.shtml", method= RequestMethod.POST)
public ModelAndView spRequestSubmit(@RequestParam String spEntityId,
- @ModelAttribute(value = "selectedidp") IdentityProvider selectedidp,
@Valid @ModelAttribute("linkrequest") LinkRequest linkrequest,
BindingResult result,
@ModelAttribute(value = "selectedidp") IdentityProvider selectedidp
) {
Map<String, Object> m = new HashMap<String, Object>();
m.put("sp", providerService.getServiceProvider(spEntityId, selectedidp.getId()));
if (result.hasErrors()) {
LOG.debug("Errors in data binding, will return to form view: {}", result.getAllErrors());
return new ModelAndView("sp-linkrequest", m);
} else {
final JiraTask task = new JiraTask.Builder()
.body(linkrequest.getEmailAddress() + ("\n\n" + linkrequest.getEmailAddress()))
// TODO: add a separate field 'subject' in JiraTask?
.identityProvider(SpListController.getCurrentUser().getIdp())
.serviceProvider(spEntityId)
.institution(SpListController.getCurrentUser().getInstitutionId())
.issueType(JiraTask.Type.REQUEST)
.status(JiraTask.Status.OPEN)
.build();
try {
final String issueKey = jiraService.create(task);
// TODO: log action
m.put("issueKey", issueKey);
return new ModelAndView("sp-linkrequest-thanks", m);
} catch (IOException e) {
LOG.debug("Error while trying to create Jira issue. Will return to form view",
e);
m.put("jiraError", e.getMessage());
return new ModelAndView("sp-linkrequest", m);
}
}
}
}
| true | true | public ModelAndView spRequestSubmit(@RequestParam String spEntityId,
@ModelAttribute(value = "selectedidp") IdentityProvider selectedidp,
@Valid @ModelAttribute("linkrequest") LinkRequest linkrequest,
BindingResult result,
@ModelAttribute(value = "selectedidp") IdentityProvider selectedidp
) {
Map<String, Object> m = new HashMap<String, Object>();
m.put("sp", providerService.getServiceProvider(spEntityId, selectedidp.getId()));
if (result.hasErrors()) {
LOG.debug("Errors in data binding, will return to form view: {}", result.getAllErrors());
return new ModelAndView("sp-linkrequest", m);
} else {
final JiraTask task = new JiraTask.Builder()
.body(linkrequest.getEmailAddress() + ("\n\n" + linkrequest.getEmailAddress()))
// TODO: add a separate field 'subject' in JiraTask?
.identityProvider(SpListController.getCurrentUser().getIdp())
.serviceProvider(spEntityId)
.institution(SpListController.getCurrentUser().getInstitutionId())
.issueType(JiraTask.Type.REQUEST)
.status(JiraTask.Status.OPEN)
.build();
try {
final String issueKey = jiraService.create(task);
// TODO: log action
m.put("issueKey", issueKey);
return new ModelAndView("sp-linkrequest-thanks", m);
} catch (IOException e) {
LOG.debug("Error while trying to create Jira issue. Will return to form view",
e);
m.put("jiraError", e.getMessage());
return new ModelAndView("sp-linkrequest", m);
}
}
}
| public ModelAndView spRequestSubmit(@RequestParam String spEntityId,
@Valid @ModelAttribute("linkrequest") LinkRequest linkrequest,
BindingResult result,
@ModelAttribute(value = "selectedidp") IdentityProvider selectedidp
) {
Map<String, Object> m = new HashMap<String, Object>();
m.put("sp", providerService.getServiceProvider(spEntityId, selectedidp.getId()));
if (result.hasErrors()) {
LOG.debug("Errors in data binding, will return to form view: {}", result.getAllErrors());
return new ModelAndView("sp-linkrequest", m);
} else {
final JiraTask task = new JiraTask.Builder()
.body(linkrequest.getEmailAddress() + ("\n\n" + linkrequest.getEmailAddress()))
// TODO: add a separate field 'subject' in JiraTask?
.identityProvider(SpListController.getCurrentUser().getIdp())
.serviceProvider(spEntityId)
.institution(SpListController.getCurrentUser().getInstitutionId())
.issueType(JiraTask.Type.REQUEST)
.status(JiraTask.Status.OPEN)
.build();
try {
final String issueKey = jiraService.create(task);
// TODO: log action
m.put("issueKey", issueKey);
return new ModelAndView("sp-linkrequest-thanks", m);
} catch (IOException e) {
LOG.debug("Error while trying to create Jira issue. Will return to form view",
e);
m.put("jiraError", e.getMessage());
return new ModelAndView("sp-linkrequest", m);
}
}
}
|
diff --git a/javasrc/src/org/ccnx/ccn/io/CCNOutputStream.java b/javasrc/src/org/ccnx/ccn/io/CCNOutputStream.java
index 0fe361281..aa4e66bb8 100644
--- a/javasrc/src/org/ccnx/ccn/io/CCNOutputStream.java
+++ b/javasrc/src/org/ccnx/ccn/io/CCNOutputStream.java
@@ -1,557 +1,558 @@
/*
* Part of the CCNx Java Library.
*
* Copyright (C) 2008, 2009, 2010, 2011 Palo Alto Research Center, Inc.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 2.1
* as published by the Free Software Foundation.
* This 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.ccnx.ccn.io;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.util.logging.Level;
import org.ccnx.ccn.CCNHandle;
import org.ccnx.ccn.impl.CCNFlowControl;
import org.ccnx.ccn.impl.CCNSegmenter;
import org.ccnx.ccn.impl.CCNFlowControl.Shape;
import org.ccnx.ccn.impl.security.crypto.CCNDigestHelper;
import org.ccnx.ccn.impl.security.crypto.ContentKeys;
import org.ccnx.ccn.impl.support.Log;
import org.ccnx.ccn.profiles.SegmentationProfile;
import org.ccnx.ccn.protocol.CCNTime;
import org.ccnx.ccn.protocol.ContentName;
import org.ccnx.ccn.protocol.KeyLocator;
import org.ccnx.ccn.protocol.PublisherPublicKeyDigest;
import org.ccnx.ccn.protocol.SignedInfo.ContentType;
/**
* Basic output stream class which generates segmented content under a given
* name prefix. Segment naming is generated according to the SegmentationProfile;
* by default names are sequentially numbered. Name prefixes are taken as specified
* (no versions or other information is added by this class). Segments are
* fixed length (see CCNBlockOutputStream for non fixed-length segments).
*/
public class CCNOutputStream extends CCNAbstractOutputStream {
/**
* Amount of data we keep around prior to forced flush to segmenter, in terms of segmenter
* blocks. We write to a limit lower than the maximum, to allow for expansion
* due to encryption. We believe we want a low number here to allow for effective interleaving
* of threading in read/write/repo running within the same JVM. We have to have at least one
* extra block to allow for holding back data for final block writing etc (see notes about this
* below). In practice most flushing to the segmenter will result in in creating BLOCK_BUF_COUNT - 1
* ContentObjects in the segmenter.
*/
public static final int BLOCK_BUF_COUNT = 128; // Must be at least 2
/**
* elapsed length written
*/
protected long _totalLength = 0;
/**
* write pointer - offset into the current write buffer at which to write
*/
protected int _blockOffset = 0;
/**
* write pointer - current write buffer at which to write
*/
protected int _blockIndex = 0;
/**
* write buffers
*/
protected byte [][] _buffers = null;
/**
* base name index of the current set of data to output;
* incremented according to the segmentation profile.
*/
protected long _baseNameIndex;
/**
* // timestamp we use for writing, set to time first segment is written
*/
protected CCNTime _timestamp;
protected Integer _freshnessSeconds; // if null, use default
protected CCNDigestHelper _dh;
protected boolean _nameSpaceAdded = false;
protected boolean _flushed = false; // Used to avoid double writes of final block
// on redundant close calls
/**
* Constructor for a simple CCN output stream.
* @param baseName name prefix under which to write content segments
* @param handle if null, new handle created with CCNHandle#open()
* @throws IOException if stream setup fails
*/
public CCNOutputStream(ContentName baseName, CCNHandle handle) throws IOException {
this(baseName, (PublisherPublicKeyDigest)null, handle);
}
/**
* Constructor for a simple CCN output stream.
* @param baseName name prefix under which to write content segments
* @param publisher key to use to sign the segments, if null, default for user is used.
* @param handle if null, new handle created with CCNHandle#open()
* @throws IOException if stream setup fails
*/
public CCNOutputStream(ContentName baseName,
PublisherPublicKeyDigest publisher,
CCNHandle handle) throws IOException {
this(baseName, null, publisher, null, null, handle);
}
/**
* Constructor for a simple CCN output stream.
* @param baseName name prefix under which to write content segments
* @param keys keys with which to encrypt content, if null content either unencrypted
* or keys retrieved according to local policy
* @param handle if null, new handle created with CCNHandle#open()
* @throws IOException if stream setup fails
*/
public CCNOutputStream(ContentName baseName, ContentKeys keys, CCNHandle handle) throws IOException {
this(baseName, null, null, null, keys, handle);
}
/**
* Constructor for a simple CCN output stream.
* @param baseName name prefix under which to write content segments
* @param locator key locator to use, if null, default for key is used.
* @param publisher key to use to sign the segments, if null, default for user is used.
* @param keys keys with which to encrypt content, if null content either unencrypted
* or keys retrieved according to local policy
* @param handle if null, new handle created with CCNHandle#open()
* @throws IOException if stream setup fails
*/
public CCNOutputStream(ContentName baseName,
KeyLocator locator,
PublisherPublicKeyDigest publisher,
ContentKeys keys,
CCNHandle handle) throws IOException {
this(baseName, locator, publisher, null, keys, handle);
}
/**
* Constructor for a simple CCN output stream.
* @param baseName name prefix under which to write content segments
* @param locator key locator to use, if null, default for key is used.
* @param publisher key to use to sign the segments, if null, default for user is used.
* @param type type to mark content (see ContentType), if null, DATA is used; if
* content encrypted, ENCR is used.
* @param keys keys with which to encrypt content, if null content either unencrypted
* or keys retrieved according to local policy
* @param handle if null, new handle created with CCNHandle#open()
* @throws IOException if stream setup fails
*/
public CCNOutputStream(ContentName baseName,
KeyLocator locator,
PublisherPublicKeyDigest publisher,
ContentType type,
ContentKeys keys,
CCNHandle handle) throws IOException {
this(baseName, locator, publisher, type, keys, new CCNFlowControl(baseName, handle));
}
/**
* Special purpose constructor.
*/
protected CCNOutputStream() {}
/**
* Low-level constructor used by clients that need to specify flow control behavior.
* @param baseName name prefix under which to write content segments
* @param locator key locator to use, if null, default for key is used.
* @param publisher key to use to sign the segments, if null, default for user is used.
* @param type type to mark content (see ContentType), if null, DATA is used; if
* content encrypted, ENCR is used.
* @param keys keys with which to encrypt content, if null content either unencrypted
* or keys retrieved according to local policy
* @param flowControl flow controller used to buffer output content
* @throws IOException if flow controller setup fails
*/
public CCNOutputStream(ContentName baseName,
KeyLocator locator,
PublisherPublicKeyDigest publisher,
ContentType type,
ContentKeys keys,
CCNFlowControl flowControl) throws IOException {
this(baseName, locator, publisher, type, keys, new CCNSegmenter(flowControl, null));
}
/**
* Low-level constructor used by subclasses that need to specify segmenter behavior.
* @param baseName name prefix under which to write content segments
* @param locator key locator to use, if null, default for key is used.
* @param publisher key to use to sign the segments, if null, default for user is used.
* @param type type to mark content (see ContentType), if null, DATA is used; if
* content encrypted, ENCR is used.
* @param keys the ContentKeys to use to encrypt, or null if unencrypted or access
* controlled (keys automatically retrieved)
* @param segmenter segmenter used to segment and sign content
* @throws IOException if flow controller setup fails
*/
protected CCNOutputStream(ContentName baseName,
KeyLocator locator,
PublisherPublicKeyDigest publisher,
ContentType type,
ContentKeys keys,
CCNSegmenter segmenter) throws IOException {
super((SegmentationProfile.isSegment(baseName) ? SegmentationProfile.segmentRoot(baseName) : baseName),
locator, publisher, type, keys, segmenter);
_buffers = new byte[BLOCK_BUF_COUNT][];
// Always make the first one; it simplifies error handling later and only is superfluous if we
// attempt to write an empty stream, which is rare.
_buffers[0] = new byte[_segmenter.getBlockSize()];
_baseNameIndex = SegmentationProfile.baseSegment();
_dh = new CCNDigestHelper();
startWrite(); // set up flow controller to write
}
@Override
protected void startWrite() throws IOException {
super.startWrite();
_segmenter.getFlowControl().startWrite(_baseName, Shape.STREAM);
}
/**
* Set the segmentation block size to use. Constraints: needs to be
* a multiple of the likely encryption block size (which is, conservatively, 32 bytes).
* Default is 4096.
* @param blockSize in bytes
*/
public synchronized void setBlockSize(int blockSize) throws IOException {
if (blockSize <= 0) {
throw new IllegalArgumentException("Cannot set negative or zero block size!");
}
if (blockSize == getBlockSize()) {
// doing nothing, return
return;
}
if (_totalLength > 0) {
throw new IOException("Cannot set block size after writing");
}
getSegmenter().setBlockSize(blockSize);
// Nothing written, throw away first buffer and replace it with one of the right size
_buffers[0] = new byte[blockSize];
}
/**
* Get segmentation block size.
* @return block size in bytes
*/
public int getBlockSize() {
return getSegmenter().getBlockSize();
}
public void setFreshnessSeconds(Integer freshnessSeconds) {
_freshnessSeconds = freshnessSeconds;
}
@Override
public void close() throws IOException {
try {
_segmenter.getFlowControl().beforeClose();
closeNetworkData();
_segmenter.getFlowControl().afterClose();
Log.info(Log.FAC_IO, "CCNOutputStream close: {0}", _baseName);
} catch (InvalidKeyException e) {
Log.logStackTrace(Level.WARNING, e);
throw new IOException("Cannot sign content -- invalid key!: " + e.getMessage());
} catch (SignatureException e) {
Log.logStackTrace(Level.WARNING, e);
throw new IOException("Cannot sign content -- signature failure!: " + e.getMessage());
} catch (NoSuchAlgorithmException e) {
throw new IOException("Cannot sign content -- unknown algorithm!: " + e.getMessage());
} catch (InterruptedException e) {
Log.logStackTrace(Level.WARNING, e);
throw new IOException("Low-level network failure!: " + e.getMessage());
}
}
@Override
public void flush() throws IOException {
flush(false); // if there is a partial block, don't flush it
}
/**
* Internal flush.
* @param flushLastBlock Should we flush the last (partial) block, or hold it back
* for it to be filled.
* @throws IOException on a variety of types of error.
*/
protected void flush(boolean flushLastBlock) throws IOException {
try {
flushToNetwork(flushLastBlock);
} catch (InvalidKeyException e) {
throw new IOException("Cannot sign content -- invalid key!: " + e.getMessage());
} catch (SignatureException e) {
throw new IOException("Cannot sign content -- signature failure!: " + e.getMessage());
} catch (NoSuchAlgorithmException e) {
throw new IOException("Cannot sign content -- unknown algorithm!: " + e.getMessage());
} catch (InterruptedException e) {
throw new IOException("Low-level network failure!: " + e.getMessage());
} catch (InvalidAlgorithmParameterException e) {
throw new IOException("Cannot encrypt content -- bad algorithm parameter!: " + e.getMessage());
}
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
try {
writeToNetwork(b, off, len);
} catch (InvalidKeyException e) {
throw new IOException("Cannot sign content -- invalid key!: " + e.getMessage());
} catch (SignatureException e) {
throw new IOException("Cannot sign content -- signature failure!: " + e.getMessage());
} catch (NoSuchAlgorithmException e) {
throw new IOException("Cannot sign content -- unknown algorithm!: " + e.getMessage());
} catch (InvalidAlgorithmParameterException e) {
throw new IOException("Cannot sign content -- Invalid algorithm parameter!: " + e.getMessage());
}
}
/**
* Actually write bytes to the network.
* @param buf as in write(byte[], int, int)
* @param offset as in write(byte[], int, int)
* @param len as in write(byte[])
* @throws IOException on network errors
* @throws InvalidKeyException if we cannot encrypt content as specified
* @throws SignatureException if we cannot sign content
* @throws NoSuchAlgorithmException if encryption requests invalid algorithm
* @throws InvalidAlgorithmParameterException
*/
protected synchronized void writeToNetwork(byte[] buf, long offset, long len) throws IOException, InvalidKeyException, SignatureException, NoSuchAlgorithmException, InvalidAlgorithmParameterException {
if ((len < 0) || (null == buf) || ((offset + len) > buf.length))
throw new IllegalArgumentException("Invalid argument!");
long bytesToWrite = len;
int blockSize = getBlockSize();
// Fill up to a buffer if we can to align the writes
if (_blockOffset % blockSize != 0 && (_blockOffset + bytesToWrite) > blockSize) {
int copySize = blockSize - _blockOffset;
System.arraycopy(buf, (int)offset, _buffers[_blockIndex], (int)_blockOffset, copySize);
+ _dh.update(buf, (int) offset, (int)copySize); // add to running digest of data
offset += copySize;
_blockOffset = blockSize;
bytesToWrite -= copySize;
}
if (_blockOffset % blockSize == 0 && bytesToWrite > 0) {
// Flush all complete blocks we have to the segmenter
if (_blockIndex > 0 || _blockOffset > 0) {
_baseNameIndex =
_segmenter.fragmentedPut(_baseName, _baseNameIndex, _buffers, _blockIndex+1,
0, blockSize,
_type, _timestamp, _freshnessSeconds, null,
_locator, _publisher, _keys);
_blockOffset = _blockIndex = 0;
}
// Now if we have more than a blocksize worth of data, we can avoid copying by
// sending all full blocks we have directly to the sequencer
- if (len >= blockSize) {
- long contiguousBytesToWrite = (len / blockSize) * blockSize;
+ if (bytesToWrite >= blockSize) {
+ long contiguousBytesToWrite = (bytesToWrite / blockSize) * blockSize;
bytesToWrite -= contiguousBytesToWrite;
_dh.update(buf, (int) offset, (int)contiguousBytesToWrite); // add to running digest of data
if (!_nameSpaceAdded) {
if( Log.isLoggable(Level.INFO))
Log.info("Adding namespace in writeToNetwork. Namespace: {0}", _baseName);
_segmenter.getFlowControl().addNameSpace(_baseName);
_nameSpaceAdded = true;
}
_baseNameIndex = _segmenter.fragmentedPut(_baseName, _baseNameIndex,
buf, (int)offset, (int)contiguousBytesToWrite, blockSize, _type, null,
_freshnessSeconds, null, _locator, _publisher, _keys);
offset += contiguousBytesToWrite;
_totalLength += contiguousBytesToWrite;
}
}
// Here's an advantage of the old, complicated way -- with that, only had to allocate
// as many blocks as you were going to write.
while (bytesToWrite > 0) {
if (null == _buffers[_blockIndex]) {
_buffers[_blockIndex] = new byte[blockSize];
}
// Increment _blockIndex here, if do it at end of loop gets confusing
// Already checked for need to flush and flush at end of last loop
if (_blockOffset >= blockSize) {
_blockIndex++;
_blockOffset = 0;
if (null == _buffers[_blockIndex]) {
_buffers[_blockIndex] = new byte[blockSize];
}
}
long thisBufAvail = blockSize - _blockOffset;
long toWriteNow = (thisBufAvail > bytesToWrite) ? bytesToWrite : thisBufAvail;
System.arraycopy(buf, (int)offset, _buffers[_blockIndex], (int)_blockOffset, (int)toWriteNow);
_dh.update(buf, (int) offset, (int)toWriteNow); // add to running digest of data
bytesToWrite -= toWriteNow; // amount of data left to write in current call
_blockOffset += toWriteNow; // write offset into current block buffer
offset += toWriteNow; // read offset into input buffer
_totalLength += toWriteNow; // increment here so we can write log entries on partial writes
if (Log.isLoggable(Log.FAC_IO, Level.FINEST ))
Log.finest(Log.FAC_IO, "write: added " + toWriteNow + " bytes to buffer. blockOffset: " + _blockOffset + "( " + (thisBufAvail - toWriteNow) + " left in block), " + _totalLength + " written.");
if ((_blockOffset >= blockSize) && ((_blockIndex+1) >= _buffers.length)) {
// We're out of buffers. Time to flush to the network.
Log.fine(Log.FAC_IO, "write: about to sync one tree's worth of blocks (" + BLOCK_BUF_COUNT +") to the network.");
flush(); // will reset _blockIndex and _blockOffset
}
}
}
/**
* Flush partial hanging block if we have one.
* @throws InvalidKeyException
* @throws SignatureException
* @throws NoSuchAlgorithmException
* @throws IOException
* @throws InterruptedException
*/
protected void closeNetworkData() throws InvalidKeyException, SignatureException, NoSuchAlgorithmException, IOException, InterruptedException {
// flush last partial buffers. Remove previous code to specially handle
// small data objects (written as single blocks without headers); instead
// write them as single-fragment files. Subclasses will determine whether or not
// to write a header.
if(Log.isLoggable(Log.FAC_IO, Level.FINE))
Log.fine(Log.FAC_IO, "closeNetworkData: final flush, wrote " + _totalLength + " bytes, base index " + _baseNameIndex);
flush(true); // true means write out the partial last block, if there is one
}
/**
* @param flushLastBlock Do we flush a partially-filled last block in the current set
* of blocks? Not normally, we want to fill blocks. So if a user calls a manual
* flush(), we want to flush all full blocks, but not a last partial -- readers of
* this block-fragmented content (other streams make other sorts of fragments, this one
* is designed for files of same block size) expect all fragments but the last to be
* the same size. The only time we flush a last partial is on close(), when it is the
* last block of the data. This flag, passed in only by internal methods, tells us it's
* time to do that.
* @throws InvalidKeyException
* @throws SignatureException
* @throws NoSuchAlgorithmException
* @throws InterruptedException
* @throws IOException
* @throws InvalidAlgorithmParameterException
*/
protected synchronized void flushToNetwork(boolean flushLastBlock) throws InvalidKeyException, SignatureException, NoSuchAlgorithmException, InterruptedException, IOException, InvalidAlgorithmParameterException {
if (_flushed)
return;
int blockSize = getBlockSize();
/**
* XXX - Can the blockbuffers have holes?
* DKS: no. The blockCount argument to putMerkleTree is intended to tell
* it how many of the blockBuffers array it should touch (are non-null).
* If there are holes, there is a bigger problem.
*/
/**
* Partial last block handling. If we are in the middle of writing a file, we only
* flush complete blocks; up to _blockOffset % blockSize. The only time
* we emit a 0-length block is if we've been told to flush the last block (i.e.
* we're closing the file) without having written anything at all. So for
* 0-length files we emit a single block with 0-length content (which has
* a Content element, but no contained BLOB).
*/
if (0 == _blockIndex) {
if ((_blockOffset <= blockSize) && (!flushLastBlock)) {
// We've written only a single block's worth of data (or less),
// but we are not forcing a flush of the last block, so don't write anything.
// We don't put out partial blocks until
// close is called (or otherwise have flushLastBlock=true), so it's
// easy to understand holding in that case. However, if we want to
// set finalBlockID, we can't do that till we know it -- till close is
// called. So we should hold off on writing the last full block as well,
// until we are closed. Unfortunately that means if you call flush()
// right before close(), you'll tend to sign all but the last block,
// and sign that last one separately when you actually flush it.
return;
}
}
if (flushLastBlock)
_flushed = true;
if (null == _timestamp)
_timestamp = CCNTime.now();
boolean preservePartial = false;
int saveBytes = 0;
if (!flushLastBlock) {
saveBytes = _blockOffset;
preservePartial = true;
} // otherwise saveBytes = 0, so ok
if (Log.isLoggable(Log.FAC_IO, Level.INFO))
Log.info(Log.FAC_IO, "flush: outputting to the segmenter, baseName " + _baseName +
" basenameindex " + ContentName.componentPrintURI(SegmentationProfile.getSegmentNumberNameComponent(_baseNameIndex)) + "; "
+ _blockOffset +
" bytes written, holding back " + saveBytes + " flushing final blocks? " + flushLastBlock + ".");
// Flush to segmenter to generate ContentObjects, sign when appropriate, and output to flow controller
// We always flush all the blocks starting from 0, so the baseBlockIndex is always 0.
// Two cases:
// no partial, write all blocks including potentially short last block
// don't write last block (whole or partial), write n-1 full blocks
_baseNameIndex = _segmenter.fragmentedPut(_baseName, _baseNameIndex, _buffers,
(preservePartial && !flushLastBlock ? _blockIndex : _blockIndex+1),
0,
(preservePartial && !flushLastBlock ? blockSize : _blockOffset),
_type, _timestamp, _freshnessSeconds,
(flushLastBlock ? CCNSegmenter.LAST_SEGMENT : null),
_locator, _publisher, _keys);
if (preservePartial) {
//System.arraycopy(_buffers[_blockIndex], _blockOffset-saveBytes, _buffers[0], 0, saveBytes);
byte[] tmp = _buffers[_blockIndex];
_buffers[_blockIndex] = _buffers[0];
_buffers[0] = tmp;
_blockOffset = saveBytes;
} else {
_blockOffset = 0;
}
_blockIndex = 0;
if (Log.isLoggable(Log.FAC_IO, Level.INFO))
Log.info(Log.FAC_IO, "HEADER: CCNOutputStream: flushToNetwork: new _baseNameIndex {0}", _baseNameIndex);
}
/**
* @return number of bytes that have been written on this stream.
*/
protected long lengthWritten() {
return _totalLength;
}
}
| false | true | protected synchronized void writeToNetwork(byte[] buf, long offset, long len) throws IOException, InvalidKeyException, SignatureException, NoSuchAlgorithmException, InvalidAlgorithmParameterException {
if ((len < 0) || (null == buf) || ((offset + len) > buf.length))
throw new IllegalArgumentException("Invalid argument!");
long bytesToWrite = len;
int blockSize = getBlockSize();
// Fill up to a buffer if we can to align the writes
if (_blockOffset % blockSize != 0 && (_blockOffset + bytesToWrite) > blockSize) {
int copySize = blockSize - _blockOffset;
System.arraycopy(buf, (int)offset, _buffers[_blockIndex], (int)_blockOffset, copySize);
offset += copySize;
_blockOffset = blockSize;
bytesToWrite -= copySize;
}
if (_blockOffset % blockSize == 0 && bytesToWrite > 0) {
// Flush all complete blocks we have to the segmenter
if (_blockIndex > 0 || _blockOffset > 0) {
_baseNameIndex =
_segmenter.fragmentedPut(_baseName, _baseNameIndex, _buffers, _blockIndex+1,
0, blockSize,
_type, _timestamp, _freshnessSeconds, null,
_locator, _publisher, _keys);
_blockOffset = _blockIndex = 0;
}
// Now if we have more than a blocksize worth of data, we can avoid copying by
// sending all full blocks we have directly to the sequencer
if (len >= blockSize) {
long contiguousBytesToWrite = (len / blockSize) * blockSize;
bytesToWrite -= contiguousBytesToWrite;
_dh.update(buf, (int) offset, (int)contiguousBytesToWrite); // add to running digest of data
if (!_nameSpaceAdded) {
if( Log.isLoggable(Level.INFO))
Log.info("Adding namespace in writeToNetwork. Namespace: {0}", _baseName);
_segmenter.getFlowControl().addNameSpace(_baseName);
_nameSpaceAdded = true;
}
_baseNameIndex = _segmenter.fragmentedPut(_baseName, _baseNameIndex,
buf, (int)offset, (int)contiguousBytesToWrite, blockSize, _type, null,
_freshnessSeconds, null, _locator, _publisher, _keys);
offset += contiguousBytesToWrite;
_totalLength += contiguousBytesToWrite;
}
}
// Here's an advantage of the old, complicated way -- with that, only had to allocate
// as many blocks as you were going to write.
while (bytesToWrite > 0) {
if (null == _buffers[_blockIndex]) {
_buffers[_blockIndex] = new byte[blockSize];
}
// Increment _blockIndex here, if do it at end of loop gets confusing
// Already checked for need to flush and flush at end of last loop
if (_blockOffset >= blockSize) {
_blockIndex++;
_blockOffset = 0;
if (null == _buffers[_blockIndex]) {
_buffers[_blockIndex] = new byte[blockSize];
}
}
long thisBufAvail = blockSize - _blockOffset;
long toWriteNow = (thisBufAvail > bytesToWrite) ? bytesToWrite : thisBufAvail;
System.arraycopy(buf, (int)offset, _buffers[_blockIndex], (int)_blockOffset, (int)toWriteNow);
_dh.update(buf, (int) offset, (int)toWriteNow); // add to running digest of data
bytesToWrite -= toWriteNow; // amount of data left to write in current call
_blockOffset += toWriteNow; // write offset into current block buffer
offset += toWriteNow; // read offset into input buffer
_totalLength += toWriteNow; // increment here so we can write log entries on partial writes
if (Log.isLoggable(Log.FAC_IO, Level.FINEST ))
Log.finest(Log.FAC_IO, "write: added " + toWriteNow + " bytes to buffer. blockOffset: " + _blockOffset + "( " + (thisBufAvail - toWriteNow) + " left in block), " + _totalLength + " written.");
if ((_blockOffset >= blockSize) && ((_blockIndex+1) >= _buffers.length)) {
// We're out of buffers. Time to flush to the network.
Log.fine(Log.FAC_IO, "write: about to sync one tree's worth of blocks (" + BLOCK_BUF_COUNT +") to the network.");
flush(); // will reset _blockIndex and _blockOffset
}
}
}
| protected synchronized void writeToNetwork(byte[] buf, long offset, long len) throws IOException, InvalidKeyException, SignatureException, NoSuchAlgorithmException, InvalidAlgorithmParameterException {
if ((len < 0) || (null == buf) || ((offset + len) > buf.length))
throw new IllegalArgumentException("Invalid argument!");
long bytesToWrite = len;
int blockSize = getBlockSize();
// Fill up to a buffer if we can to align the writes
if (_blockOffset % blockSize != 0 && (_blockOffset + bytesToWrite) > blockSize) {
int copySize = blockSize - _blockOffset;
System.arraycopy(buf, (int)offset, _buffers[_blockIndex], (int)_blockOffset, copySize);
_dh.update(buf, (int) offset, (int)copySize); // add to running digest of data
offset += copySize;
_blockOffset = blockSize;
bytesToWrite -= copySize;
}
if (_blockOffset % blockSize == 0 && bytesToWrite > 0) {
// Flush all complete blocks we have to the segmenter
if (_blockIndex > 0 || _blockOffset > 0) {
_baseNameIndex =
_segmenter.fragmentedPut(_baseName, _baseNameIndex, _buffers, _blockIndex+1,
0, blockSize,
_type, _timestamp, _freshnessSeconds, null,
_locator, _publisher, _keys);
_blockOffset = _blockIndex = 0;
}
// Now if we have more than a blocksize worth of data, we can avoid copying by
// sending all full blocks we have directly to the sequencer
if (bytesToWrite >= blockSize) {
long contiguousBytesToWrite = (bytesToWrite / blockSize) * blockSize;
bytesToWrite -= contiguousBytesToWrite;
_dh.update(buf, (int) offset, (int)contiguousBytesToWrite); // add to running digest of data
if (!_nameSpaceAdded) {
if( Log.isLoggable(Level.INFO))
Log.info("Adding namespace in writeToNetwork. Namespace: {0}", _baseName);
_segmenter.getFlowControl().addNameSpace(_baseName);
_nameSpaceAdded = true;
}
_baseNameIndex = _segmenter.fragmentedPut(_baseName, _baseNameIndex,
buf, (int)offset, (int)contiguousBytesToWrite, blockSize, _type, null,
_freshnessSeconds, null, _locator, _publisher, _keys);
offset += contiguousBytesToWrite;
_totalLength += contiguousBytesToWrite;
}
}
// Here's an advantage of the old, complicated way -- with that, only had to allocate
// as many blocks as you were going to write.
while (bytesToWrite > 0) {
if (null == _buffers[_blockIndex]) {
_buffers[_blockIndex] = new byte[blockSize];
}
// Increment _blockIndex here, if do it at end of loop gets confusing
// Already checked for need to flush and flush at end of last loop
if (_blockOffset >= blockSize) {
_blockIndex++;
_blockOffset = 0;
if (null == _buffers[_blockIndex]) {
_buffers[_blockIndex] = new byte[blockSize];
}
}
long thisBufAvail = blockSize - _blockOffset;
long toWriteNow = (thisBufAvail > bytesToWrite) ? bytesToWrite : thisBufAvail;
System.arraycopy(buf, (int)offset, _buffers[_blockIndex], (int)_blockOffset, (int)toWriteNow);
_dh.update(buf, (int) offset, (int)toWriteNow); // add to running digest of data
bytesToWrite -= toWriteNow; // amount of data left to write in current call
_blockOffset += toWriteNow; // write offset into current block buffer
offset += toWriteNow; // read offset into input buffer
_totalLength += toWriteNow; // increment here so we can write log entries on partial writes
if (Log.isLoggable(Log.FAC_IO, Level.FINEST ))
Log.finest(Log.FAC_IO, "write: added " + toWriteNow + " bytes to buffer. blockOffset: " + _blockOffset + "( " + (thisBufAvail - toWriteNow) + " left in block), " + _totalLength + " written.");
if ((_blockOffset >= blockSize) && ((_blockIndex+1) >= _buffers.length)) {
// We're out of buffers. Time to flush to the network.
Log.fine(Log.FAC_IO, "write: about to sync one tree's worth of blocks (" + BLOCK_BUF_COUNT +") to the network.");
flush(); // will reset _blockIndex and _blockOffset
}
}
}
|
diff --git a/src/main/java/be/Balor/Manager/Commands/CommandArgs.java b/src/main/java/be/Balor/Manager/Commands/CommandArgs.java
index 728a51dd..731ad8e2 100644
--- a/src/main/java/be/Balor/Manager/Commands/CommandArgs.java
+++ b/src/main/java/be/Balor/Manager/Commands/CommandArgs.java
@@ -1,241 +1,247 @@
/*
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* 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 be.Balor.Manager.Commands;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
* @author Balor (aka Antoine Aflalo)
*
*/
public class CommandArgs implements Iterable<String> {
protected final List<String> parsedArgs;
protected final Map<Character, String> valueFlags = new HashMap<Character, String>();
protected final Set<Character> booleanFlags = new HashSet<Character>();
public int length;
public CommandArgs(final String args) {
this(args.split(" "));
}
/**
*
*/
public CommandArgs(final String[] args) {
final List<Integer> argIndexList = new ArrayList<Integer>(args.length);
final List<String> argList = new ArrayList<String>(args.length);
for (int i = 0; i < args.length; ++i) {
String arg = args[i];
if (arg.length() == 0) {
continue;
}
argIndexList.add(i);
switch (arg.charAt(0)) {
case '\'':
case '"':
final StringBuilder build = new StringBuilder();
final char quotedChar = arg.charAt(0);
int endIndex;
for (endIndex = i; endIndex < args.length; ++endIndex) {
final String arg2 = args[endIndex];
+ if (arg2.isEmpty()) {
+ continue;
+ }
if (arg2.charAt(arg2.length() - 1) == quotedChar) {
if (endIndex != i) {
build.append(' ');
}
+ if (endIndex == i && arg2.length() == 1) {
+ continue;
+ }
build.append(arg2.substring(endIndex == i ? 1 : 0, arg2.length() - 1));
break;
} else if (endIndex == i) {
build.append(arg2.substring(1));
} else {
build.append(' ').append(arg2);
}
}
if (endIndex < args.length) {
arg = build.toString();
i = endIndex;
}
// In case there is an empty quoted string
if (arg.length() == 0) {
continue;
}
// else raise exception about hanging quotes?
}
argList.add(arg);
}
// Then flags
final List<Integer> originalArgIndices = new ArrayList<Integer>(argIndexList.size());
this.parsedArgs = new ArrayList<String>(argList.size());
for (int nextArg = 0; nextArg < argList.size();) {
// Fetch argument
final String arg = argList.get(nextArg++);
if (arg.charAt(0) == '-' && arg.length() > 1 && arg.matches("^-[a-zA-Z]+$")) {
for (int i = 1; i < arg.length(); ++i) {
final char flagName = arg.charAt(i);
if (this.valueFlags.containsKey(flagName)) {
continue;
}
if (nextArg >= argList.size()) {
this.booleanFlags.add(flagName);
} else {
this.valueFlags.put(flagName, argList.get(nextArg));
}
}
continue;
}
originalArgIndices.add(argIndexList.get(nextArg - 1));
parsedArgs.add(arg);
}
this.length = parsedArgs.size();
}
public String getString(final int index) {
try {
final String result = parsedArgs.get(index);
if (result == null) {
return null;
}
return result;
} catch (final IndexOutOfBoundsException e) {
return null;
}
}
/**
* Try to parse the argument to an int
*
* @param index
* @return
* @throws NumberFormatException
*/
public int getInt(final int index) throws NumberFormatException {
return Integer.parseInt(getString(index));
}
/**
* Try to parse the argument to a float
*
* @param index
* @return
* @throws NumberFormatException
*/
public float getFloat(final int index) throws NumberFormatException {
return Float.parseFloat(getString(index));
}
/**
* Try to parse the argument to a double
*
* @param index
* @return
* @throws NumberFormatException
*/
public double getDouble(final int index) throws NumberFormatException {
return Double.parseDouble(getString(index));
}
/**
* Try to parse the argument to a long
*
* @param index
* @return
* @throws NumberFormatException
*/
public long getLong(final int index) throws NumberFormatException {
return Long.parseLong(getString(index));
}
/**
* Check if the arguments contain the wanted flagF
*
* @param ch
* flag to be searched
* @return true if found.
*/
public boolean hasFlag(final char ch) {
return booleanFlags.contains(ch) || valueFlags.containsKey(ch);
}
/**
* Get the Value associated with the given flag and remove the flag from the
* normal arguments.
*
* @param flag
* flag to look for.
* @return null if not found else the value of the flag
*/
public String getValueFlag(final char flag) {
final String result = valueFlags.get(flag);
if (result == null) {
return null;
}
if (parsedArgs.remove(result)) {
length--;
}
return result;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return Arrays.toString(parsedArgs.toArray(new String[] {})) + " BoolFlags : "
+ Arrays.toString(booleanFlags.toArray(new Character[] {})) + " ValFlags : "
+ (valueFlags.isEmpty() ? "[]" : "[" + valueFlagsToString() + "]");
}
private String valueFlagsToString() {
final StringBuffer buffer = new StringBuffer();
for (final Entry<Character, String> entry : valueFlags.entrySet()) {
buffer.append(entry.getKey()).append("->").append(entry.getValue()).append(", ");
}
buffer.deleteCharAt(buffer.length() - 1).deleteCharAt(buffer.length() - 1);
return buffer.toString();
}
/*
* (non-Javadoc)
*
* @see java.lang.Iterable#iterator()
*/
@Override
public Iterator<String> iterator() {
return parsedArgs.iterator();
}
}
| false | true | public CommandArgs(final String[] args) {
final List<Integer> argIndexList = new ArrayList<Integer>(args.length);
final List<String> argList = new ArrayList<String>(args.length);
for (int i = 0; i < args.length; ++i) {
String arg = args[i];
if (arg.length() == 0) {
continue;
}
argIndexList.add(i);
switch (arg.charAt(0)) {
case '\'':
case '"':
final StringBuilder build = new StringBuilder();
final char quotedChar = arg.charAt(0);
int endIndex;
for (endIndex = i; endIndex < args.length; ++endIndex) {
final String arg2 = args[endIndex];
if (arg2.charAt(arg2.length() - 1) == quotedChar) {
if (endIndex != i) {
build.append(' ');
}
build.append(arg2.substring(endIndex == i ? 1 : 0, arg2.length() - 1));
break;
} else if (endIndex == i) {
build.append(arg2.substring(1));
} else {
build.append(' ').append(arg2);
}
}
if (endIndex < args.length) {
arg = build.toString();
i = endIndex;
}
// In case there is an empty quoted string
if (arg.length() == 0) {
continue;
}
// else raise exception about hanging quotes?
}
argList.add(arg);
}
// Then flags
final List<Integer> originalArgIndices = new ArrayList<Integer>(argIndexList.size());
this.parsedArgs = new ArrayList<String>(argList.size());
for (int nextArg = 0; nextArg < argList.size();) {
// Fetch argument
final String arg = argList.get(nextArg++);
if (arg.charAt(0) == '-' && arg.length() > 1 && arg.matches("^-[a-zA-Z]+$")) {
for (int i = 1; i < arg.length(); ++i) {
final char flagName = arg.charAt(i);
if (this.valueFlags.containsKey(flagName)) {
continue;
}
if (nextArg >= argList.size()) {
this.booleanFlags.add(flagName);
} else {
this.valueFlags.put(flagName, argList.get(nextArg));
}
}
continue;
}
originalArgIndices.add(argIndexList.get(nextArg - 1));
parsedArgs.add(arg);
}
this.length = parsedArgs.size();
}
| public CommandArgs(final String[] args) {
final List<Integer> argIndexList = new ArrayList<Integer>(args.length);
final List<String> argList = new ArrayList<String>(args.length);
for (int i = 0; i < args.length; ++i) {
String arg = args[i];
if (arg.length() == 0) {
continue;
}
argIndexList.add(i);
switch (arg.charAt(0)) {
case '\'':
case '"':
final StringBuilder build = new StringBuilder();
final char quotedChar = arg.charAt(0);
int endIndex;
for (endIndex = i; endIndex < args.length; ++endIndex) {
final String arg2 = args[endIndex];
if (arg2.isEmpty()) {
continue;
}
if (arg2.charAt(arg2.length() - 1) == quotedChar) {
if (endIndex != i) {
build.append(' ');
}
if (endIndex == i && arg2.length() == 1) {
continue;
}
build.append(arg2.substring(endIndex == i ? 1 : 0, arg2.length() - 1));
break;
} else if (endIndex == i) {
build.append(arg2.substring(1));
} else {
build.append(' ').append(arg2);
}
}
if (endIndex < args.length) {
arg = build.toString();
i = endIndex;
}
// In case there is an empty quoted string
if (arg.length() == 0) {
continue;
}
// else raise exception about hanging quotes?
}
argList.add(arg);
}
// Then flags
final List<Integer> originalArgIndices = new ArrayList<Integer>(argIndexList.size());
this.parsedArgs = new ArrayList<String>(argList.size());
for (int nextArg = 0; nextArg < argList.size();) {
// Fetch argument
final String arg = argList.get(nextArg++);
if (arg.charAt(0) == '-' && arg.length() > 1 && arg.matches("^-[a-zA-Z]+$")) {
for (int i = 1; i < arg.length(); ++i) {
final char flagName = arg.charAt(i);
if (this.valueFlags.containsKey(flagName)) {
continue;
}
if (nextArg >= argList.size()) {
this.booleanFlags.add(flagName);
} else {
this.valueFlags.put(flagName, argList.get(nextArg));
}
}
continue;
}
originalArgIndices.add(argIndexList.get(nextArg - 1));
parsedArgs.add(arg);
}
this.length = parsedArgs.size();
}
|
diff --git a/src/web/org/codehaus/groovy/grails/web/servlet/mvc/SimpleGrailsControllerHelper.java b/src/web/org/codehaus/groovy/grails/web/servlet/mvc/SimpleGrailsControllerHelper.java
index 5e6940c05..3ec0294c3 100644
--- a/src/web/org/codehaus/groovy/grails/web/servlet/mvc/SimpleGrailsControllerHelper.java
+++ b/src/web/org/codehaus/groovy/grails/web/servlet/mvc/SimpleGrailsControllerHelper.java
@@ -1,622 +1,622 @@
/*
* Copyright 2004-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.codehaus.groovy.grails.web.servlet.mvc;
import groovy.lang.Closure;
import groovy.lang.GroovyObject;
import groovy.lang.MissingPropertyException;
import groovy.util.Proxy;
import org.apache.commons.beanutils.BeanMap;
import org.apache.commons.collections.map.CompositeMap;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.groovy.grails.commons.ControllerArtefactHandler;
import org.codehaus.groovy.grails.commons.GrailsApplication;
import org.codehaus.groovy.grails.commons.GrailsClassUtils;
import org.codehaus.groovy.grails.commons.GrailsControllerClass;
import org.codehaus.groovy.grails.scaffolding.GrailsScaffolder;
import org.codehaus.groovy.grails.web.metaclass.ChainDynamicMethod;
import org.codehaus.groovy.grails.web.metaclass.ControllerDynamicMethods;
import org.codehaus.groovy.grails.web.servlet.DefaultGrailsApplicationAttributes;
import org.codehaus.groovy.grails.web.servlet.FlashScope;
import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes;
import org.codehaus.groovy.grails.web.servlet.mvc.exceptions.ControllerExecutionException;
import org.codehaus.groovy.grails.web.servlet.mvc.exceptions.NoClosurePropertyForURIException;
import org.codehaus.groovy.grails.web.servlet.mvc.exceptions.NoViewNameDefinedException;
import org.codehaus.groovy.grails.web.servlet.mvc.exceptions.UnknownControllerException;
import org.codehaus.groovy.grails.webflow.executor.support.GrailsConventionsFlowExecutorArgumentHandler;
import org.springframework.context.ApplicationContext;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import org.springframework.web.util.WebUtils;
import org.springframework.web.util.UrlPathHelper;
import org.springframework.webflow.context.servlet.ServletExternalContext;
import org.springframework.webflow.execution.support.ApplicationView;
import org.springframework.webflow.execution.support.ExternalRedirect;
import org.springframework.webflow.execution.support.FlowDefinitionRedirect;
import org.springframework.webflow.execution.support.FlowExecutionRedirect;
import org.springframework.webflow.executor.FlowExecutor;
import org.springframework.webflow.executor.ResponseInstruction;
import org.springframework.webflow.executor.support.FlowExecutorArgumentHandler;
import org.springframework.webflow.executor.support.FlowRequestHandler;
import org.springframework.webflow.executor.support.ResponseInstructionHandler;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
/**
* <p>This is a helper class that does the main job of dealing with Grails web requests
*
* @author Graeme Rocher
* @since 0.1
*
* Created: 12-Jan-2006
*/
public class SimpleGrailsControllerHelper implements GrailsControllerHelper {
private static final String SCAFFOLDER = "Scaffolder";
private GrailsApplication application;
private ApplicationContext applicationContext;
private Map chainModel = Collections.EMPTY_MAP;
private ServletContext servletContext;
private GrailsApplicationAttributes grailsAttributes;
private GrailsWebRequest webRequest;
private static final Log LOG = LogFactory.getLog(SimpleGrailsControllerHelper.class);
private static final char SLASH = '/';
private static final String DISPATCH_ACTION_PARAMETER = "_action_";
private static final String FLOW_EXECUTOR_BEAN = "flowExecutor";
private String id;
private String controllerName;
private String actionName;
private String controllerActionURI;
public SimpleGrailsControllerHelper(GrailsApplication application, ApplicationContext context, ServletContext servletContext) {
super();
this.application = application;
this.applicationContext = context;
this.servletContext = servletContext;
this.grailsAttributes = new DefaultGrailsApplicationAttributes(this.servletContext);
}
public ServletContext getServletContext() {
return this.servletContext;
}
/* (non-Javadoc)
* @see org.codehaus.groovy.grails.web.servlet.mvc.GrailsControllerHelper#getControllerClassByName(java.lang.String)
*/
public GrailsControllerClass getControllerClassByName(String name) {
return (GrailsControllerClass) this.application.getArtefact(
ControllerArtefactHandler.TYPE, name);
}
/* (non-Javadoc)
* @see org.codehaus.groovy.grails.web.servlet.mvc.GrailsControllerHelper#getControllerClassByURI(java.lang.String)
*/
public GrailsControllerClass getControllerClassByURI(String uri) {
return (GrailsControllerClass) this.application.getArtefactForFeature(
ControllerArtefactHandler.TYPE, uri);
}
/* (non-Javadoc)
* @see org.codehaus.groovy.grails.web.servlet.mvc.GrailsControllerHelper#getControllerInstance(org.codehaus.groovy.grails.commons.GrailsControllerClass)
*/
public GroovyObject getControllerInstance(GrailsControllerClass controllerClass) {
return (GroovyObject)this.applicationContext.getBean(controllerClass.getFullName());
}
/**
* If in Proxy's are used in the Groovy context, unproxy (is that a word?) them by setting
* the adaptee as the value in the map so that they can be used in non-groovy view technologies
*
* @param model The model as a map
*/
private void removeProxiesFromModelObjects(Map model) {
for (Iterator keyIter = model.keySet().iterator(); keyIter.hasNext();) {
Object current = keyIter.next();
Object modelObject = model.get(current);
if(modelObject instanceof Proxy) {
model.put( current, ((Proxy)modelObject).getAdaptee() );
}
}
}
public ModelAndView handleURI(String uri, GrailsWebRequest webRequest) {
return handleURI(uri, webRequest, Collections.EMPTY_MAP);
}
/* (non-Javadoc)
* @see org.codehaus.groovy.grails.web.servlet.mvc.GrailsControllerHelper#handleURI(java.lang.String, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.util.Map)
*/
public ModelAndView handleURI(String uri, GrailsWebRequest webRequest, Map params) {
if(uri == null) {
throw new IllegalArgumentException("Controller URI [" + uri + "] cannot be null!");
}
HttpServletRequest request = webRequest.getCurrentRequest();
HttpServletResponse response = webRequest.getCurrentResponse();
configureStateForWebRequest(webRequest, request);
// if the action name is blank check its included as dispatch parameter
if(StringUtils.isBlank(actionName)) {
uri = checkDispatchAction(request, uri);
}
if(uri.endsWith("/")) {
uri = uri.substring(0,uri.length() - 1);
}
// if the id is blank check if its a request parameter
// Step 2: lookup the controller in the application.
GrailsControllerClass controllerClass = getControllerClassByURI(uri);
if (controllerClass == null) {
throw new UnknownControllerException("No controller found for URI [" + uri + "]!");
}
actionName = controllerClass.getClosurePropertyName(uri);
webRequest.setActionName(actionName);
if(LOG.isDebugEnabled()) {
LOG.debug("Processing request for controller ["+controllerName+"], action ["+actionName+"], and id ["+id+"]");
}
controllerActionURI = SLASH + controllerName + SLASH + actionName + SLASH;
// Step 3: load controller from application context.
GroovyObject controller = getControllerInstance(controllerClass);
if(!controllerClass.isHttpMethodAllowedForAction(controller, request.getMethod(), actionName)) {
try {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return null;
} catch (IOException e) {
throw new ControllerExecutionException("I/O error sending 403 error",e);
}
}
request.setAttribute( GrailsApplicationAttributes.CONTROLLER, controller );
// Step 3: if scaffolding retrieve scaffolder
GrailsScaffolder scaffolder = obtainScaffolder(controllerClass);
if (StringUtils.isBlank(actionName)) {
// Step 4a: Check if scaffolding
if( controllerClass.isScaffolding() && !scaffolder.supportsAction(actionName))
throw new NoClosurePropertyForURIException("Could not find closure property for URI [" + uri + "] for controller [" + controllerClass.getFullName() + "]!");
}
// Step 4: Set grails attributes in request scope
request.setAttribute(GrailsApplicationAttributes.REQUEST_SCOPE_ID,this.grailsAttributes);
// Step 5: get the view name for this URI.
String viewName = controllerClass.getViewByURI(uri);
boolean executeAction = invokeBeforeInterceptor(controller, controllerClass);
// if the interceptor returned false don't execute the action
if(!executeAction)
return null;
ModelAndView mv;
if(controllerClass.isFlowAction(actionName)) {
mv = executeFlow(webRequest,request, response);
}
else {
mv = executeAction(controller, controllerClass, viewName, request, response, params);
}
- boolean returnModelAndView = invokeAfterInterceptor(controllerClass, controller, mv);
+ boolean returnModelAndView = invokeAfterInterceptor(controllerClass, controller, mv) && !response.isCommitted();
return returnModelAndView ? mv : null;
}
/**
* This method is responsible for execution of a flow based on the currently executing GrailsWebRequest
*
* @param webRequest The GrailsWebRequest
* @param request The HttpServletRequest instance
* @param response The HttpServletResponse instance
* @return A Spring ModelAndView
*/
protected ModelAndView executeFlow(GrailsWebRequest webRequest, final HttpServletRequest request, HttpServletResponse response) {
final Thread currentThread = Thread.currentThread();
ClassLoader cl = currentThread.getContextClassLoader();
try {
currentThread.setContextClassLoader(application.getClassLoader());
FlowExecutorArgumentHandler argumentHandler = new GrailsConventionsFlowExecutorArgumentHandler(webRequest);
FlowExecutor flowExecutor = getFlowExecutor();
if(flowExecutor == null) {
throw new ControllerExecutionException("No [flowExecutor] found. This is likely a configuration problem, check your version of Grails.");
}
ServletExternalContext externalContext = new ServletExternalContext(getServletContext(), request, response) {
public String getDispatcherPath() {
String forwardURI = (String)request.getAttribute(WebUtils.FORWARD_REQUEST_URI_ATTRIBUTE);
UrlPathHelper pathHelper = new UrlPathHelper();
String contextPath = pathHelper.getContextPath(request);
if(forwardURI.startsWith(contextPath)) {
return forwardURI.substring(contextPath.length(),forwardURI.length());
}
else {
return forwardURI;
}
}
};
ResponseInstruction responseInstruction = createRequestHandler(argumentHandler).handleFlowRequest(externalContext);
return toModelAndView(responseInstruction, externalContext, argumentHandler);
}
finally {
currentThread.setContextClassLoader(cl);
}
}
/**
* Deals with translating a WebFlow ResponseInstruction instance into an appropriate Spring ModelAndView
*
* @param responseInstruction The ResponseInstruction instance
* @param context The ExternalContext for the webflow
* @param argumentHandler The FlowExecutorArgumentHandler instance
* @return A Spring ModelAndView instance
*/
protected ModelAndView toModelAndView(final ResponseInstruction responseInstruction, final ServletExternalContext context, final FlowExecutorArgumentHandler argumentHandler) {
return (ModelAndView)new ResponseInstructionHandler() {
protected void handleApplicationView(ApplicationView view) throws Exception {
// forward to a view as part of an active conversation
Map model = new HashMap(view.getModel());
argumentHandler.exposeFlowExecutionContext(responseInstruction.getFlowExecutionKey(),
responseInstruction.getFlowExecutionContext(), model);
final String viewName = view.getViewName();
if(viewName.startsWith("/"))
setResult(new ModelAndView(viewName, model));
else
setResult(new ModelAndView(controllerActionURI + viewName, model));
}
protected void handleFlowDefinitionRedirect(FlowDefinitionRedirect redirect) throws Exception {
// restart the flow by redirecting to flow launch URL
if(LOG.isDebugEnabled())
LOG.debug("Flow definition redirect issued to flow with id " + redirect.getFlowDefinitionId());
String flowUrl = argumentHandler.createFlowDefinitionUrl(redirect, context);
setResult(new ModelAndView(new RedirectView(flowUrl)));
}
protected void handleFlowExecutionRedirect(FlowExecutionRedirect redirect) throws Exception {
if(LOG.isDebugEnabled())
LOG.debug("Flow execution redirect issued " + redirect);
// redirect to active flow execution URL
String flowExecutionUrl = argumentHandler.createFlowExecutionUrl(
responseInstruction.getFlowExecutionKey(),
responseInstruction.getFlowExecutionContext(), context);
setResult(new ModelAndView(new RedirectView(flowExecutionUrl)));
}
protected void handleExternalRedirect(ExternalRedirect redirect) throws Exception {
if(LOG.isDebugEnabled())
LOG.debug("External redirect issued from flow with URL " + redirect.getUrl());
// redirect to external URL
String externalUrl = argumentHandler.createExternalUrl(redirect,
responseInstruction.getFlowExecutionKey(), context);
setResult(new ModelAndView(new RedirectView(externalUrl)));
}
protected void handleNull() throws Exception {
// no response to issue
setResult(null);
}
}.handleQuietly(responseInstruction).getResult();
}
/**
* Factory method that creates a new helper for processing a request into
* this flow controller. The handler is a basic template encapsulating
* reusable flow execution request handling workflow.
* This implementation just creates a new {@link FlowRequestHandler}.
* @param argumentHandler The FlowExecutorArgumentHandler to use
*
* @return the controller helper
*/
protected FlowRequestHandler createRequestHandler(FlowExecutorArgumentHandler argumentHandler ) {
return new FlowRequestHandler(getFlowExecutor(), argumentHandler);
}
/**
* Invokes the action defined by the webRequest for the given arguments
*
* @param controller The controller instance
* @param controllerClass The GrailsControllerClass that defines the conventions within the controller
* @param viewName The name of the view to delegate to if necessary
* @param request The HttpServletRequest object
* @param response The HttpServletResponse object
* @param params A map of parameters
* @return A Spring ModelAndView instance
*/
protected ModelAndView executeAction(GroovyObject controller, GrailsControllerClass controllerClass, String viewName, HttpServletRequest request, HttpServletResponse response, Map params) {
// Step 5a: Check if there is a before interceptor if there is execute it
ClassLoader cl = Thread.currentThread().getContextClassLoader();
try {
// Step 6: get closure from closure property
Closure action;
try {
action = (Closure)controller.getProperty(actionName);
}
catch(MissingPropertyException mpe) {
if(controllerClass.isScaffolding())
throw new IllegalStateException("Scaffolder supports action ["+actionName +"] for controller ["+controllerClass.getFullName()+"] but getAction returned null!");
else {
try {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return null;
} catch (IOException e) {
throw new ControllerExecutionException("I/O error sending 404 error",e);
}
}
}
// Step 7: process the action
Object returnValue = handleAction( controller,action,request,response,params );
// Step 8: determine return value type and handle accordingly
initChainModel(controller);
if(response.isCommitted()) {
if(LOG.isDebugEnabled()) {
LOG.debug("Response has been redirected, returning null model and view");
}
return null;
}
else {
if(LOG.isDebugEnabled()) {
LOG.debug("Action ["+actionName+"] executed with result ["+returnValue+"] and view name ["+viewName+"]");
}
ModelAndView mv = handleActionResponse(controller,returnValue,actionName,viewName);
if(LOG.isDebugEnabled()) {
LOG.debug("Action ["+actionName+"] handled, created Spring model and view ["+mv+"]");
}
return mv;
}
} finally {
Thread.currentThread().setContextClassLoader(cl);
}
}
private boolean invokeBeforeInterceptor(GroovyObject controller, GrailsControllerClass controllerClass) {
boolean executeAction = true;
if(controllerClass.isInterceptedBefore(controller,actionName)) {
Closure beforeInterceptor = controllerClass.getBeforeInterceptor(controller);
if(beforeInterceptor!= null) {
if(beforeInterceptor.getDelegate() != controller) {
beforeInterceptor.setDelegate(controller);
beforeInterceptor.setResolveStrategy(Closure.DELEGATE_FIRST);
}
Object interceptorResult = beforeInterceptor.call();
if(interceptorResult instanceof Boolean) {
executeAction = ((Boolean)interceptorResult).booleanValue();
}
}
}
return executeAction;
}
private GrailsScaffolder obtainScaffolder(GrailsControllerClass controllerClass) {
GrailsScaffolder scaffolder = null;
if(controllerClass.isScaffolding()) {
scaffolder = (GrailsScaffolder)applicationContext.getBean( controllerClass.getFullName() + SCAFFOLDER );
if(scaffolder == null)
throw new IllegalStateException("Scaffolding set to true for controller ["+controllerClass.getFullName()+"] but no scaffolder available!");
}
return scaffolder;
}
private void configureStateForWebRequest(GrailsWebRequest webRequest, HttpServletRequest request) {
this.webRequest = webRequest;
this.actionName = webRequest.getActionName();
this.controllerName = webRequest.getControllerName();
this.id = webRequest.getId();
if(StringUtils.isBlank(id) && request.getParameter(GrailsWebRequest.ID_PARAMETER) != null) {
id = request.getParameter(GrailsWebRequest.ID_PARAMETER);
}
}
private boolean invokeAfterInterceptor(GrailsControllerClass controllerClass, GroovyObject controller, ModelAndView mv) {
// Step 9: Check if there is after interceptor
Object interceptorResult = null;
if(controllerClass.isInterceptedAfter(controller,actionName)) {
Closure afterInterceptor = controllerClass.getAfterInterceptor(controller);
if(afterInterceptor.getDelegate() != controller) {
afterInterceptor.setDelegate(controller);
afterInterceptor.setResolveStrategy(Closure.DELEGATE_FIRST);
}
Map model = new HashMap();
if(mv != null) {
model = mv.getModel() != null ? mv.getModel() : new HashMap();
}
switch(afterInterceptor.getMaximumNumberOfParameters()){
case 1:
interceptorResult = afterInterceptor.call(new Object[]{ model });
break;
case 2:
interceptorResult = afterInterceptor.call(new Object[]{ model, mv });
break;
default:
throw new ControllerExecutionException("AfterInterceptor closure must accept one or two parameters");
}
}
return !(interceptorResult != null && interceptorResult instanceof Boolean) || ((Boolean) interceptorResult).booleanValue();
}
private String checkDispatchAction(HttpServletRequest request, String uri) {
for(Enumeration e = request.getParameterNames(); e.hasMoreElements();) {
String name = (String)e.nextElement();
if(name.startsWith(DISPATCH_ACTION_PARAMETER)) {
// remove .x suffix in case of submit image
if (name.endsWith(".x") || name.endsWith(".y")) {
name = name.substring(0, name.length()-2);
}
actionName = GrailsClassUtils.getPropertyNameRepresentation(name.substring((DISPATCH_ACTION_PARAMETER).length()));
StringBuffer sb = new StringBuffer();
sb.append('/').append(controllerName).append('/').append(actionName);
uri = sb.toString();
break;
}
}
return uri;
}
public GrailsApplicationAttributes getGrailsAttributes() {
return this.grailsAttributes;
}
public Object handleAction(GroovyObject controller,Closure action, HttpServletRequest request, HttpServletResponse response) {
return handleAction(controller,action,request,response,Collections.EMPTY_MAP);
}
public Object handleAction(GroovyObject controller,Closure action, HttpServletRequest request, HttpServletResponse response, Map params) {
GrailsParameterMap paramsMap = (GrailsParameterMap)controller.getProperty("params");
// if there are additional params add them to the params dynamic property
if(params != null && !params.isEmpty()) {
paramsMap.putAll( params );
}
Object returnValue = action.call();
// Step 8: add any errors to the request
request.setAttribute( GrailsApplicationAttributes.ERRORS, controller.getProperty(ControllerDynamicMethods.ERRORS_PROPERTY) );
return returnValue;
}
/* (non-Javadoc)
* @see org.codehaus.groovy.grails.web.servlet.mvc.GrailsControllerHelper#handleActionResponse(org.codehaus.groovy.grails.commons.GrailsControllerClass, java.lang.Object, java.lang.String, java.lang.String)
*/
public ModelAndView handleActionResponse( GroovyObject controller,Object returnValue,String closurePropertyName, String viewName) {
boolean viewNameBlank = (viewName == null || viewName.length() == 0);
// reset the metaclass
ModelAndView explicityModelAndView = (ModelAndView)controller.getProperty(ControllerDynamicMethods.MODEL_AND_VIEW_PROPERTY);
if(!webRequest.isRenderView()) {
return null;
}
else if(explicityModelAndView != null) {
return explicityModelAndView;
}
else if (returnValue == null) {
if (viewNameBlank) {
return null;
} else {
Map model;
if(!this.chainModel.isEmpty()) {
model = new CompositeMap(this.chainModel, new BeanMap(controller));
}
else {
model = new BeanMap(controller);
}
return new ModelAndView(viewName, model);
}
} else if (returnValue instanceof Map) {
// remove any Proxy wrappers and set the adaptee as the value
Map returnModel = (Map)returnValue;
removeProxiesFromModelObjects(returnModel);
if(!this.chainModel.isEmpty()) {
returnModel.putAll(this.chainModel);
}
return new ModelAndView(viewName, returnModel);
} else if (returnValue instanceof ModelAndView) {
ModelAndView modelAndView = (ModelAndView)returnValue;
// remove any Proxy wrappers and set the adaptee as the value
Map modelMap = modelAndView.getModel();
removeProxiesFromModelObjects(modelMap);
if(!this.chainModel.isEmpty()) {
modelAndView.addAllObjects(this.chainModel);
}
if (modelAndView.getView() == null && modelAndView.getViewName() == null) {
if (viewNameBlank) {
throw new NoViewNameDefinedException("ModelAndView instance returned by and no view name defined by nor for closure on property [" + closurePropertyName + "] in controller [" + controller.getClass() + "]!");
} else {
modelAndView.setViewName(viewName);
}
}
return modelAndView;
}
else {
Map model;
if(!this.chainModel.isEmpty()) {
model = new CompositeMap(this.chainModel, new BeanMap(controller));
}
else {
model = new BeanMap(controller);
}
return new ModelAndView(viewName, model);
}
}
private void initChainModel(GroovyObject controller) {
FlashScope fs = this.grailsAttributes.getFlashScope((HttpServletRequest)controller.getProperty(ControllerDynamicMethods.REQUEST_PROPERTY));
if(fs.containsKey(ChainDynamicMethod.PROPERTY_CHAIN_MODEL)) {
this.chainModel = (Map)fs.get(ChainDynamicMethod.PROPERTY_CHAIN_MODEL);
if(this.chainModel == null)
this.chainModel = Collections.EMPTY_MAP;
}
}
/**
* Retrieves the FlowExecutor instance stored in the ApplicationContext
*
* @return The FlowExecution
*/
protected FlowExecutor getFlowExecutor() {
if(applicationContext.containsBean(FLOW_EXECUTOR_BEAN)) {
return (FlowExecutor)applicationContext.getBean(FLOW_EXECUTOR_BEAN);
}
return null;
}
}
| true | true | public ModelAndView handleURI(String uri, GrailsWebRequest webRequest, Map params) {
if(uri == null) {
throw new IllegalArgumentException("Controller URI [" + uri + "] cannot be null!");
}
HttpServletRequest request = webRequest.getCurrentRequest();
HttpServletResponse response = webRequest.getCurrentResponse();
configureStateForWebRequest(webRequest, request);
// if the action name is blank check its included as dispatch parameter
if(StringUtils.isBlank(actionName)) {
uri = checkDispatchAction(request, uri);
}
if(uri.endsWith("/")) {
uri = uri.substring(0,uri.length() - 1);
}
// if the id is blank check if its a request parameter
// Step 2: lookup the controller in the application.
GrailsControllerClass controllerClass = getControllerClassByURI(uri);
if (controllerClass == null) {
throw new UnknownControllerException("No controller found for URI [" + uri + "]!");
}
actionName = controllerClass.getClosurePropertyName(uri);
webRequest.setActionName(actionName);
if(LOG.isDebugEnabled()) {
LOG.debug("Processing request for controller ["+controllerName+"], action ["+actionName+"], and id ["+id+"]");
}
controllerActionURI = SLASH + controllerName + SLASH + actionName + SLASH;
// Step 3: load controller from application context.
GroovyObject controller = getControllerInstance(controllerClass);
if(!controllerClass.isHttpMethodAllowedForAction(controller, request.getMethod(), actionName)) {
try {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return null;
} catch (IOException e) {
throw new ControllerExecutionException("I/O error sending 403 error",e);
}
}
request.setAttribute( GrailsApplicationAttributes.CONTROLLER, controller );
// Step 3: if scaffolding retrieve scaffolder
GrailsScaffolder scaffolder = obtainScaffolder(controllerClass);
if (StringUtils.isBlank(actionName)) {
// Step 4a: Check if scaffolding
if( controllerClass.isScaffolding() && !scaffolder.supportsAction(actionName))
throw new NoClosurePropertyForURIException("Could not find closure property for URI [" + uri + "] for controller [" + controllerClass.getFullName() + "]!");
}
// Step 4: Set grails attributes in request scope
request.setAttribute(GrailsApplicationAttributes.REQUEST_SCOPE_ID,this.grailsAttributes);
// Step 5: get the view name for this URI.
String viewName = controllerClass.getViewByURI(uri);
boolean executeAction = invokeBeforeInterceptor(controller, controllerClass);
// if the interceptor returned false don't execute the action
if(!executeAction)
return null;
ModelAndView mv;
if(controllerClass.isFlowAction(actionName)) {
mv = executeFlow(webRequest,request, response);
}
else {
mv = executeAction(controller, controllerClass, viewName, request, response, params);
}
boolean returnModelAndView = invokeAfterInterceptor(controllerClass, controller, mv);
return returnModelAndView ? mv : null;
}
| public ModelAndView handleURI(String uri, GrailsWebRequest webRequest, Map params) {
if(uri == null) {
throw new IllegalArgumentException("Controller URI [" + uri + "] cannot be null!");
}
HttpServletRequest request = webRequest.getCurrentRequest();
HttpServletResponse response = webRequest.getCurrentResponse();
configureStateForWebRequest(webRequest, request);
// if the action name is blank check its included as dispatch parameter
if(StringUtils.isBlank(actionName)) {
uri = checkDispatchAction(request, uri);
}
if(uri.endsWith("/")) {
uri = uri.substring(0,uri.length() - 1);
}
// if the id is blank check if its a request parameter
// Step 2: lookup the controller in the application.
GrailsControllerClass controllerClass = getControllerClassByURI(uri);
if (controllerClass == null) {
throw new UnknownControllerException("No controller found for URI [" + uri + "]!");
}
actionName = controllerClass.getClosurePropertyName(uri);
webRequest.setActionName(actionName);
if(LOG.isDebugEnabled()) {
LOG.debug("Processing request for controller ["+controllerName+"], action ["+actionName+"], and id ["+id+"]");
}
controllerActionURI = SLASH + controllerName + SLASH + actionName + SLASH;
// Step 3: load controller from application context.
GroovyObject controller = getControllerInstance(controllerClass);
if(!controllerClass.isHttpMethodAllowedForAction(controller, request.getMethod(), actionName)) {
try {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return null;
} catch (IOException e) {
throw new ControllerExecutionException("I/O error sending 403 error",e);
}
}
request.setAttribute( GrailsApplicationAttributes.CONTROLLER, controller );
// Step 3: if scaffolding retrieve scaffolder
GrailsScaffolder scaffolder = obtainScaffolder(controllerClass);
if (StringUtils.isBlank(actionName)) {
// Step 4a: Check if scaffolding
if( controllerClass.isScaffolding() && !scaffolder.supportsAction(actionName))
throw new NoClosurePropertyForURIException("Could not find closure property for URI [" + uri + "] for controller [" + controllerClass.getFullName() + "]!");
}
// Step 4: Set grails attributes in request scope
request.setAttribute(GrailsApplicationAttributes.REQUEST_SCOPE_ID,this.grailsAttributes);
// Step 5: get the view name for this URI.
String viewName = controllerClass.getViewByURI(uri);
boolean executeAction = invokeBeforeInterceptor(controller, controllerClass);
// if the interceptor returned false don't execute the action
if(!executeAction)
return null;
ModelAndView mv;
if(controllerClass.isFlowAction(actionName)) {
mv = executeFlow(webRequest,request, response);
}
else {
mv = executeAction(controller, controllerClass, viewName, request, response, params);
}
boolean returnModelAndView = invokeAfterInterceptor(controllerClass, controller, mv) && !response.isCommitted();
return returnModelAndView ? mv : null;
}
|
diff --git a/org.eclipse.mylyn.java.ui/src/org/eclipse/mylyn/java/MylarChangeSetManager.java b/org.eclipse.mylyn.java.ui/src/org/eclipse/mylyn/java/MylarChangeSetManager.java
index c8dd34119..c418da5b9 100644
--- a/org.eclipse.mylyn.java.ui/src/org/eclipse/mylyn/java/MylarChangeSetManager.java
+++ b/org.eclipse.mylyn.java.ui/src/org/eclipse/mylyn/java/MylarChangeSetManager.java
@@ -1,154 +1,154 @@
/*******************************************************************************
* Copyright (c) 2004 - 2005 University Of British Columbia 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:
* University Of British Columbia - initial API and implementation
*******************************************************************************/
package org.eclipse.mylar.java;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.mylar.core.IMylarContext;
import org.eclipse.mylar.core.IMylarContextListener;
import org.eclipse.mylar.core.IMylarElement;
import org.eclipse.mylar.core.IMylarStructureBridge;
import org.eclipse.mylar.core.MylarPlugin;
import org.eclipse.mylar.ide.MylarIdePlugin;
import org.eclipse.mylar.tasklist.ITask;
import org.eclipse.mylar.tasklist.MylarTasklistPlugin;
import org.eclipse.team.internal.ccvs.ui.CVSUIPlugin;
import org.eclipse.team.internal.core.subscribers.SubscriberChangeSetCollector;
/**
* @author Mik Kersten
*/
public class MylarChangeSetManager implements IMylarContextListener {
private SubscriberChangeSetCollector collector;
private Map<String, MylarContextChangeSet> changeSets = new HashMap<String, MylarContextChangeSet>();
public MylarChangeSetManager() {
collector = CVSUIPlugin.getPlugin().getChangeSetManager();
// collector.addListener(new InterestInducingChangeSetListener());
}
public IResource[] getResources(ITask task) {
MylarContextChangeSet changeSet = changeSets.get(task);
if (changeSet != null) {
return changeSet.getResources();
} else {
return null;
}
}
public void contextActivated(IMylarContext context) {
try {
ITask task = getTask(context);
if (task == null) {
MylarPlugin.log("could not resolve task for context", this);
} else if (!changeSets.containsKey(task.getHandleIdentifier())) {
MylarContextChangeSet changeSet = new MylarContextChangeSet(task, collector);
changeSet.add(changeSet.getResources());
changeSets.put(task.getHandleIdentifier(), changeSet);
if (!collector.contains(changeSet)) collector.add(changeSet);
}
} catch (Exception e) {
MylarPlugin.fail(e, "could not update change set", false);
}
}
public void contextDeactivated(IMylarContext context) {
// TODO: support multiple tasks
for (String taskHandle : changeSets.keySet()) {
collector.remove(changeSets.get(taskHandle));
}
changeSets.clear();
}
public List<MylarContextChangeSet> getChangeSets() {
return new ArrayList<MylarContextChangeSet>(changeSets.values());
}
private ITask getTask(IMylarContext context) {
List<ITask> activeTasks = MylarTasklistPlugin.getTaskListManager().getTaskList().getActiveTasks();
// TODO: support multiple tasks
if (activeTasks.size() > 0) {
return activeTasks.get(0);
} else {
return null;
}
}
public void interestChanged(IMylarElement element) {
IMylarStructureBridge bridge = MylarPlugin.getDefault().getStructureBridge(element.getContentType());
if (bridge.isDocument(element.getHandleIdentifier())) {
IResource resource = MylarIdePlugin.getDefault().getResourceForElement(element);
- if (resource != null) {
+ if (resource != null && resource.exists()) {
for (MylarContextChangeSet changeSet: getChangeSets()) {
try {
if (!changeSet.contains(resource)) {
if (element.getInterest().isInteresting()) {
changeSet.add(new IResource[] { resource });
}
} else if (!element.getInterest().isInteresting()){
changeSet.remove(resource);
// HACK: touching ensures file is added outside of set
- if (resource instanceof IFile && resource.exists()) {
+ if (resource instanceof IFile) {
((IFile)resource).touch(new NullProgressMonitor());
}
if (!collector.contains(changeSet)) {
collector.add(changeSet);
}
}
} catch (Exception e) {
MylarPlugin.fail(e, "could not add resource to change set", false);
}
}
}
}
}
public void interestChanged(List<IMylarElement> elements) {
for (IMylarElement element : elements) {
interestChanged(element);
}
}
public void nodeDeleted(IMylarElement node) {
// ignore
}
public void landmarkAdded(IMylarElement node) {
// ignore
}
public void landmarkRemoved(IMylarElement node) {
// ignore
}
public void edgesChanged(IMylarElement node) {
// ignore
}
public void presentationSettingsChanging(UpdateKind kind) {
// ignore
}
public void presentationSettingsChanged(UpdateKind kind) {
// ignore
}
}
| false | true | public void interestChanged(IMylarElement element) {
IMylarStructureBridge bridge = MylarPlugin.getDefault().getStructureBridge(element.getContentType());
if (bridge.isDocument(element.getHandleIdentifier())) {
IResource resource = MylarIdePlugin.getDefault().getResourceForElement(element);
if (resource != null) {
for (MylarContextChangeSet changeSet: getChangeSets()) {
try {
if (!changeSet.contains(resource)) {
if (element.getInterest().isInteresting()) {
changeSet.add(new IResource[] { resource });
}
} else if (!element.getInterest().isInteresting()){
changeSet.remove(resource);
// HACK: touching ensures file is added outside of set
if (resource instanceof IFile && resource.exists()) {
((IFile)resource).touch(new NullProgressMonitor());
}
if (!collector.contains(changeSet)) {
collector.add(changeSet);
}
}
} catch (Exception e) {
MylarPlugin.fail(e, "could not add resource to change set", false);
}
}
}
}
}
| public void interestChanged(IMylarElement element) {
IMylarStructureBridge bridge = MylarPlugin.getDefault().getStructureBridge(element.getContentType());
if (bridge.isDocument(element.getHandleIdentifier())) {
IResource resource = MylarIdePlugin.getDefault().getResourceForElement(element);
if (resource != null && resource.exists()) {
for (MylarContextChangeSet changeSet: getChangeSets()) {
try {
if (!changeSet.contains(resource)) {
if (element.getInterest().isInteresting()) {
changeSet.add(new IResource[] { resource });
}
} else if (!element.getInterest().isInteresting()){
changeSet.remove(resource);
// HACK: touching ensures file is added outside of set
if (resource instanceof IFile) {
((IFile)resource).touch(new NullProgressMonitor());
}
if (!collector.contains(changeSet)) {
collector.add(changeSet);
}
}
} catch (Exception e) {
MylarPlugin.fail(e, "could not add resource to change set", false);
}
}
}
}
}
|
diff --git a/LambTracker_V2/src/com/weyr_associates/lambtracker/CreateSheepEvaluation.java b/LambTracker_V2/src/com/weyr_associates/lambtracker/CreateSheepEvaluation.java
index cef68da3..a9f9c2ef 100644
--- a/LambTracker_V2/src/com/weyr_associates/lambtracker/CreateSheepEvaluation.java
+++ b/LambTracker_V2/src/com/weyr_associates/lambtracker/CreateSheepEvaluation.java
@@ -1,582 +1,582 @@
package com.weyr_associates.lambtracker;
import java.util.List;
import android.database.Cursor;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import com.weyr_associates.lambtracker.MainActivity.SpinnerActivity;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import java.util.ArrayList;
import java.util.List;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.util.Log;
import android.content.Context;
import android.content.res.Resources;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import com.weyr_associates.lambtracker.MainActivity.SpinnerActivity;
public class CreateSheepEvaluation extends Activity {
private DatabaseHandler dbh;
private Cursor cursor;
public Button button;
public int trait01, trait02, trait03, trait04, trait05, trait06, trait07, trait06_unitid, trait07_unitid;
public String trait01_label, trait02_label, trait03_label, trait04_label, trait05_label;
public String trait06_label, trait07_label, trait06_units, trait07_units;
public Spinner trait01_spinner, trait02_spinner, trait03_spinner, trait04_spinner,
trait05_spinner, trait06_spinner, trait07_spinner;
public Spinner trait06_units_spinner, trait07_units_spinner;
public List<String> scored_evaluation_traits, data_evaluation_traits, trait_units;
ArrayAdapter<String> dataAdapter;
String cmd;
Integer i;
@Override
public void onCreate(Bundle savedInstanceState) {
setTitle(R.string.app_name_long);
super.onCreate(savedInstanceState);
setContentView(R.layout.create_sheep_evaluation);
String dbname = getString(R.string.real_database_file);
dbh = new DatabaseHandler( this, dbname );
scored_evaluation_traits = new ArrayList<String>();
// enable the Create an evaluation button when we come in to start this task
Button btn2 = (Button) findViewById( R.id.create_evaluation_task_btn );
btn2.setEnabled(true);
// Select All fields from trait table that are scored type and get set to fill the spinners
cmd = "select * from evaluation_trait_table where trait_type = 1";
Object crsr = dbh.exec( cmd ); ;
Log.i("testing", "executed command " + cmd);
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
scored_evaluation_traits.add("Select a Trait");
Log.i("testinterface", "in onCreate below got evaluation straits table");
// looping through all rows and adding to list all the scored evaluation types
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
scored_evaluation_traits.add(cursor.getString(1));
}
cursor.close();
dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, scored_evaluation_traits);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Fill the 5 scored spinners from the same list of evaluation traits.
trait01_spinner = (Spinner) findViewById(R.id.trait01_spinner);
trait01_spinner.setAdapter (dataAdapter);
trait01_spinner.setSelection(0);
trait02_spinner = (Spinner) findViewById(R.id.trait02_spinner);
trait02_spinner.setAdapter (dataAdapter);
trait02_spinner.setSelection(0);
trait03_spinner = (Spinner) findViewById(R.id.trait03_spinner);
trait03_spinner.setAdapter (dataAdapter);
trait03_spinner.setSelection(0);
trait04_spinner = (Spinner) findViewById(R.id.trait04_spinner);
trait04_spinner.setAdapter (dataAdapter);
trait04_spinner.setSelection(0);
trait05_spinner = (Spinner) findViewById(R.id.trait05_spinner);
trait05_spinner.setAdapter (dataAdapter);
trait05_spinner.setSelection(0);
Log.i("create eval", "got score spinners initialized");
// Now set up for the two real data traits
data_evaluation_traits = new ArrayList<String>();
// Select All fields from trait table that are real data type and get set to fill the spinners
cmd = "select * from evaluation_trait_table where trait_type = 2";
crsr = dbh.exec( cmd );
// Log.i("testing", "executed command " + cmd);
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
data_evaluation_traits.add("Select a Trait");
// Log.i("testinterface", "in onCreate below got evaluation traits table");
// looping through all rows and adding to list
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
data_evaluation_traits.add(cursor.getString(1));
}
cursor.close();
// Log.i("createEval ", "below got eval traits");
dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, data_evaluation_traits);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
trait06_spinner = (Spinner) findViewById(R.id.trait06_spinner);
trait06_spinner.setAdapter (dataAdapter);
trait06_spinner.setSelection(0);
trait07_spinner = (Spinner) findViewById(R.id.trait07_spinner);
trait07_spinner.setAdapter (dataAdapter);
trait07_spinner.setSelection(0);
Log.i("create eval", "got real spinners initialized");
trait_units = new ArrayList<String>();
// Select All fields from trait units table and get set to fill the spinners
cmd = "select * from units_table ";
crsr = dbh.exec( cmd );
Log.i("units ", "executed command " + cmd);
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
- trait_units.add("Select a Unit");
+ trait_units.add("Select Measurement Units");
// looping through all rows and adding to list
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
trait_units.add(cursor.getString(1));
}
cursor.close();
dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, trait_units);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
trait06_units_spinner = (Spinner) findViewById(R.id.trait06_units_spinner);
trait06_units_spinner.setAdapter (dataAdapter);
trait06_units_spinner.setSelection(0);
trait07_units_spinner = (Spinner) findViewById(R.id.trait07_units_spinner);
trait07_units_spinner.setAdapter (dataAdapter);
trait07_units_spinner.setSelection(0);
Log.i("create eval", "got units spinners initialized");
cmd = "select * from last_eval_table";
crsr = dbh.exec( cmd );
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
trait01 = dbh.getInt(1);
cursor.moveToNext();
trait02 = dbh.getInt(1);
cursor.moveToNext();
trait03 = dbh.getInt(1);
cursor.moveToNext();
trait04 = dbh.getInt(1);
cursor.moveToNext();
trait05 = dbh.getInt(1);
cursor.moveToNext();
trait06 = dbh.getInt(1);
trait06_unitid = dbh.getInt(2);
cursor.moveToNext();
trait07 = dbh.getInt(1);
trait07_unitid = dbh.getInt(2);
cursor.moveToNext();
cursor.close();
Log.i("results last ","eval trait01 "+String.valueOf(trait01));
Log.i("results last ","eval trait02 "+String.valueOf(trait02));
Log.i("results last ","eval trait03 "+String.valueOf(trait03));
Log.i("results last ","eval trait04 "+String.valueOf(trait04));
Log.i("results last ","eval trait05 "+String.valueOf(trait05));
Log.i("results last ","eval trait06 "+String.valueOf(trait06));
Log.i("results last ","eval trait06 units "+String.valueOf(trait06_unitid));
Log.i("results last ","eval trait07 "+String.valueOf(trait07));
Log.i("results last ","eval trait07 units "+String.valueOf(trait07_unitid));
// need to get what position within the current scored_evaluation_traits this trait is
// and set the spinner position to be that position
if (trait01!=0) {
cmd = String.format("select evaluation_trait_table.trait_name from evaluation_trait_table " +
"where id_traitid='%s'", trait01);
crsr = dbh.exec( cmd );
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
trait01_label = dbh.getStr(0);
i = scored_evaluation_traits.indexOf(trait01_label);
trait01_spinner.setSelection(i);
cursor.close();
}
if (trait02!=0) {
cmd = String.format("select evaluation_trait_table.trait_name from evaluation_trait_table " +
"where id_traitid='%s'", trait02);
crsr = dbh.exec( cmd );
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
trait02_label = dbh.getStr(0);
i = scored_evaluation_traits.indexOf(trait02_label);
trait02_spinner.setSelection(i);
cursor.close();
}
if (trait03!=0) {
cmd = String.format("select evaluation_trait_table.trait_name from evaluation_trait_table " +
"where id_traitid='%s'", trait03);
crsr = dbh.exec( cmd );
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
trait03_label = dbh.getStr(0);
i = scored_evaluation_traits.indexOf(trait03_label);
trait03_spinner.setSelection(i);
cursor.close();
}
if (trait04!=0) {
cmd = String.format("select evaluation_trait_table.trait_name from evaluation_trait_table " +
"where id_traitid='%s'", trait04);
crsr = dbh.exec( cmd );
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
trait04_label = dbh.getStr(0);
i = scored_evaluation_traits.indexOf(trait04_label);
trait04_spinner.setSelection(i);
cursor.close();
}
if (trait05!=0) {
cmd = String.format("select evaluation_trait_table.trait_name from evaluation_trait_table " +
"where id_traitid='%s'", trait05);
crsr = dbh.exec( cmd );
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
trait05_label = dbh.getStr(0);
i = scored_evaluation_traits.indexOf(trait05_label);
trait05_spinner.setSelection(i);
cursor.close();
}
if (trait06!=0) {
cmd = String.format("select evaluation_trait_table.trait_name from evaluation_trait_table " +
"where id_traitid='%s'", trait06);
crsr = dbh.exec( cmd );
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
trait06_label = dbh.getStr(0);
i = data_evaluation_traits.indexOf(trait06_label);
trait06_spinner.setSelection(i);
cursor.close();
// need to also get the units for stored trait06
cmd = String.format("select units_table.units_name from units_table where " +
"id_unitsid='%s'", trait06_unitid);
crsr = dbh.exec( cmd );
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
trait06_units = dbh.getStr(0);
i = trait_units.indexOf(trait06_units) ;
trait06_units_spinner.setSelection(i);
cursor.close();
}
if (trait07!=0) {
cmd = String.format("select evaluation_trait_table.trait_name from evaluation_trait_table " +
"where id_traitid='%s'", trait07);
crsr = dbh.exec( cmd );
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
trait07_label = dbh.getStr(0);
i = data_evaluation_traits.indexOf(trait07_label);
trait07_spinner.setSelection(i);
cursor.close();
// need to also get the units for stored trait07
cmd = String.format("select units_table.units_name from units_table where " +
"id_unitsid='%s'", trait07_unitid);
crsr = dbh.exec( cmd );
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
trait07_units = dbh.getStr(0);
i = trait_units.indexOf(trait07_units) ;
trait07_units_spinner.setSelection(i);
cursor.close();
}
Log.i("Create eval", "The selected traits are: ");
Log.i("Create eval", "trait01 " + trait01_label);
Log.i("Create eval", "trait02 " + trait02_label);
Log.i("Create eval", "trait03 " + trait03_label);
Log.i("Create eval", "trait04 " + trait04_label);
Log.i("Create eval", "trait05 " + trait05_label);
Log.i("Create eval", "trait06 " + trait06_label);
Log.i("Create eval", "trait07 " + trait07_label);
}
// private class SpinnerActivity extends Activity implements OnItemSelectedListener {
// because we only get the spinner data when the user selects the create an evaluation
// this class is not needed.
// }
// @Override
// public void onNothingSelected(AdapterView<?> arg0) {
//
// }
// }
// user clicked the 'back' button
public void backBtn( View v )
{
dbh.closeDB();
finish();
}
public void helpBtn( View v )
{
// Display help here
AlertDialog.Builder builder = new AlertDialog.Builder( this );
builder.setMessage( R.string.help_create_evaluate )
.setTitle( R.string.help_warning );
builder.setPositiveButton( R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int idx) {
// User clicked OK button
clearBtn( null );
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
// user clicked 'clear' button
public void clearBtn( View v )
{
// clear out the display of everything
}
public void createEval( View v )
{
Object crsr;
String cmd;
// Need to get the position and text for every spinner and the real data points and use
// this to fill the actual evaluation task screen with what we are looking at.
trait01_spinner = (Spinner) findViewById(R.id.trait01_spinner);
trait02_spinner = (Spinner) findViewById(R.id.trait02_spinner);
trait03_spinner = (Spinner) findViewById(R.id.trait03_spinner);
trait04_spinner = (Spinner) findViewById(R.id.trait04_spinner);
trait05_spinner = (Spinner) findViewById(R.id.trait05_spinner);
trait06_spinner = (Spinner) findViewById(R.id.trait06_spinner);
trait07_spinner = (Spinner) findViewById(R.id.trait07_spinner);
trait06_units_spinner = (Spinner) findViewById(R.id.trait06_units_spinner);
trait07_units_spinner = (Spinner) findViewById(R.id.trait07_units_spinner);
// fill the labels with the contents of the various spinners
trait01_label = trait01_spinner.getSelectedItem().toString();
trait02_label = trait02_spinner.getSelectedItem().toString();
trait03_label = trait03_spinner.getSelectedItem().toString();
trait04_label = trait04_spinner.getSelectedItem().toString();
trait05_label = trait05_spinner.getSelectedItem().toString();
trait06_label = trait06_spinner.getSelectedItem().toString();
trait07_label = trait07_spinner.getSelectedItem().toString();
trait06_units = trait06_units_spinner.getSelectedItem().toString();
trait07_units = trait07_units_spinner.getSelectedItem().toString();
Log.i("Create eval", "The selected traits are: ");
Log.i("Create eval", "trait01 " + trait01_label);
Log.i("Create eval", "trait02 " + trait02_label);
Log.i("Create eval", "trait03 " + trait03_label);
Log.i("Create eval", "trait04 " + trait04_label);
Log.i("Create eval", "trait05 " + trait05_label);
Log.i("Create eval", "trait06 " + trait06_label);
Log.i("Create eval", "trait06 units " + trait06_units);
Log.i("Create eval", "trait07 " + trait07_label);
Log.i("Create eval", "trait07 units " + trait07_units);
// Need to get the id_traitid from the evaluation trait table and store
// that as the actual thing we reference in the evaluate sheep section since it won't change
// from time to time
// Should be able to enclose each of these into an IF statement to see if a trait was selected
// and if not then do not do the database lookup but not implemented yet
if (trait01_label == "Select a Trait") {
trait01 = 0;
}else
{
cmd = String.format("select evaluation_trait_table.id_traitid from evaluation_trait_table " +
"where trait_name='%s'", trait01_label);
// Log.i("query trait1", cmd);
crsr = dbh.exec( cmd );
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
trait01 = dbh.getInt(0);
}
if (trait02_label == "Select a Trait") {
trait02 = 0;
}else
{
cmd = String.format("select evaluation_trait_table.id_traitid from evaluation_trait_table " +
"where trait_name='%s'", trait02_label);
// Log.i("query trait2", cmd);
crsr = dbh.exec( cmd );
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
trait02 = dbh.getInt(0);
}
if (trait03_label == "Select a Trait") {
trait03 = 0;
}else
{
cmd = String.format("select evaluation_trait_table.id_traitid from evaluation_trait_table " +
"where trait_name='%s'", trait03_label);
// Log.i("query trait3", cmd);
crsr = dbh.exec( cmd );
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
trait03 = dbh.getInt(0);
}
if (trait04_label == "Select a Trait") {
trait04 = 0;
}else
{
cmd = String.format("select evaluation_trait_table.id_traitid from evaluation_trait_table " +
"where trait_name='%s'", trait04_label);
// Log.i("query trait4", cmd);
crsr = dbh.exec( cmd );
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
trait04 = dbh.getInt(0);
}
if (trait05_label == "Select a Trait") {
trait05 = 0;
}else
{
cmd = String.format("select evaluation_trait_table.id_traitid from evaluation_trait_table " +
"where trait_name='%s'", trait05_label);
// Log.i("query trait5", cmd);
crsr = dbh.exec( cmd );
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
trait05 = dbh.getInt(0);
}
if (trait06_label == "Select a Trait") {
trait06 = 0;
}else
{
cmd = String.format("select evaluation_trait_table.id_traitid from evaluation_trait_table " +
"where trait_name='%s'", trait06_label);
// Log.i("query trait6", cmd);
crsr = dbh.exec( cmd );
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
trait06 = dbh.getInt(0);
}
if (trait07_label == "Select a Trait") {
trait07 = 0;
}else
{
cmd = String.format("select evaluation_trait_table.id_traitid from evaluation_trait_table " +
"where trait_name='%s'", trait07_label);
// Log.i("query trait7", cmd);
crsr = dbh.exec( cmd );
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
trait07 = dbh.getInt(0);
}
// Now get the units the user selected as well
if (trait06_units == "Select a Unit") {
trait06_unitid = 0;
}else
{
cmd = String.format("select units_table.id_unitsid from units_table " +
"where units_name='%s'", trait06_units);
crsr = dbh.exec( cmd );
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
trait06_unitid = dbh.getInt(0);
}
if (trait07_units == "Select a Unit") {
trait07_unitid = 0;
}else
{
cmd = String.format("select units_table.id_unitsid from units_table " +
"where units_name='%s'", trait07_units);
Log.i("query trait7", cmd);
crsr = dbh.exec( cmd );
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
trait07_unitid = dbh.getInt(0);
}
Log.i("results new ","eval trait01 "+String.valueOf(trait01));
Log.i("results new ","eval trait02 "+String.valueOf(trait02));
Log.i("results new ","eval trait03 "+String.valueOf(trait03));
Log.i("results new ","eval trait04 "+String.valueOf(trait04));
Log.i("results new ","eval trait05 "+String.valueOf(trait05));
Log.i("results new ","eval trait06 "+String.valueOf(trait06));
Log.i("results new ","units trait06 "+String.valueOf(trait06_unitid));
Log.i("results new ","eval trait07 "+String.valueOf(trait07));
Log.i("results new ","units trait07 "+String.valueOf(trait07_unitid));
// We have all the actual traits now to save their id_traitid and store it for look-up later
cmd = String.format( "update last_eval_table set id_traitid=%s where id_lastevalid=1", trait01 );
dbh.exec( cmd );
cmd = String.format( "update last_eval_table set id_traitid=%s where id_lastevalid=2", trait02 );
dbh.exec( cmd );
cmd = String.format( "update last_eval_table set id_traitid=%s where id_lastevalid=3", trait03 );
dbh.exec( cmd );
cmd = String.format( "update last_eval_table set id_traitid=%s where id_lastevalid=4", trait04 );
dbh.exec( cmd );
cmd = String.format( "update last_eval_table set id_traitid=%s where id_lastevalid=5", trait05 );
dbh.exec( cmd );
cmd = String.format( "update last_eval_table set id_traitid=%s where id_lastevalid=6", trait06);
dbh.exec( cmd );
cmd = String.format( "update last_eval_table set id_unitsid=%s where id_lastevalid=6", trait06_unitid );
dbh.exec( cmd );
cmd = String.format( "update last_eval_table set id_traitid=%s where id_lastevalid=7", trait07);
dbh.exec( cmd );
cmd = String.format( "update last_eval_table set id_unitsid=%s where id_lastevalid=7", trait07_unitid );
dbh.exec( cmd );
// verify what we stored used in debugging
cmd = "select * from last_eval_table ";
crsr = dbh.exec( cmd );
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
trait01 = dbh.getInt(1);
cursor.moveToNext();
trait02 = dbh.getInt(1);
cursor.moveToNext();
trait03 = dbh.getInt(1);
cursor.moveToNext();
trait04 = dbh.getInt(1);
cursor.moveToNext();
trait05 = dbh.getInt(1);
cursor.moveToNext();
trait06 = dbh.getInt(1);
trait06_unitid = dbh.getInt(2);
cursor.moveToNext();
trait07 = dbh.getInt(1);
trait07_unitid = dbh.getInt(2);
cursor.close();
Log.i("results saved ","eval trait01 "+String.valueOf(trait01));
Log.i("results saved ","eval trait02 "+String.valueOf(trait02));
Log.i("results saved ","eval trait03 "+String.valueOf(trait03));
Log.i("results saved ","eval trait04 "+String.valueOf(trait04));
Log.i("results saved ","eval trait05 "+String.valueOf(trait05));
Log.i("results saved ","eval trait06 "+String.valueOf(trait06));
Log.i("results saved ","units trait06 "+String.valueOf(trait06_unitid));
Log.i("results saved ","eval trait07 "+String.valueOf(trait07));
Log.i("results saved ","units trait07 "+String.valueOf(trait07_unitid));
// All done need to disable the create create_evaluation_task_btn so we don't do it twice
Button btn2 = (Button) findViewById( R.id.create_evaluation_task_btn );
btn2.setEnabled(false);
}
}
| true | true | public void onCreate(Bundle savedInstanceState) {
setTitle(R.string.app_name_long);
super.onCreate(savedInstanceState);
setContentView(R.layout.create_sheep_evaluation);
String dbname = getString(R.string.real_database_file);
dbh = new DatabaseHandler( this, dbname );
scored_evaluation_traits = new ArrayList<String>();
// enable the Create an evaluation button when we come in to start this task
Button btn2 = (Button) findViewById( R.id.create_evaluation_task_btn );
btn2.setEnabled(true);
// Select All fields from trait table that are scored type and get set to fill the spinners
cmd = "select * from evaluation_trait_table where trait_type = 1";
Object crsr = dbh.exec( cmd ); ;
Log.i("testing", "executed command " + cmd);
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
scored_evaluation_traits.add("Select a Trait");
Log.i("testinterface", "in onCreate below got evaluation straits table");
// looping through all rows and adding to list all the scored evaluation types
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
scored_evaluation_traits.add(cursor.getString(1));
}
cursor.close();
dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, scored_evaluation_traits);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Fill the 5 scored spinners from the same list of evaluation traits.
trait01_spinner = (Spinner) findViewById(R.id.trait01_spinner);
trait01_spinner.setAdapter (dataAdapter);
trait01_spinner.setSelection(0);
trait02_spinner = (Spinner) findViewById(R.id.trait02_spinner);
trait02_spinner.setAdapter (dataAdapter);
trait02_spinner.setSelection(0);
trait03_spinner = (Spinner) findViewById(R.id.trait03_spinner);
trait03_spinner.setAdapter (dataAdapter);
trait03_spinner.setSelection(0);
trait04_spinner = (Spinner) findViewById(R.id.trait04_spinner);
trait04_spinner.setAdapter (dataAdapter);
trait04_spinner.setSelection(0);
trait05_spinner = (Spinner) findViewById(R.id.trait05_spinner);
trait05_spinner.setAdapter (dataAdapter);
trait05_spinner.setSelection(0);
Log.i("create eval", "got score spinners initialized");
// Now set up for the two real data traits
data_evaluation_traits = new ArrayList<String>();
// Select All fields from trait table that are real data type and get set to fill the spinners
cmd = "select * from evaluation_trait_table where trait_type = 2";
crsr = dbh.exec( cmd );
// Log.i("testing", "executed command " + cmd);
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
data_evaluation_traits.add("Select a Trait");
// Log.i("testinterface", "in onCreate below got evaluation traits table");
// looping through all rows and adding to list
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
data_evaluation_traits.add(cursor.getString(1));
}
cursor.close();
// Log.i("createEval ", "below got eval traits");
dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, data_evaluation_traits);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
trait06_spinner = (Spinner) findViewById(R.id.trait06_spinner);
trait06_spinner.setAdapter (dataAdapter);
trait06_spinner.setSelection(0);
trait07_spinner = (Spinner) findViewById(R.id.trait07_spinner);
trait07_spinner.setAdapter (dataAdapter);
trait07_spinner.setSelection(0);
Log.i("create eval", "got real spinners initialized");
trait_units = new ArrayList<String>();
// Select All fields from trait units table and get set to fill the spinners
cmd = "select * from units_table ";
crsr = dbh.exec( cmd );
Log.i("units ", "executed command " + cmd);
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
trait_units.add("Select a Unit");
// looping through all rows and adding to list
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
trait_units.add(cursor.getString(1));
}
cursor.close();
dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, trait_units);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
trait06_units_spinner = (Spinner) findViewById(R.id.trait06_units_spinner);
trait06_units_spinner.setAdapter (dataAdapter);
trait06_units_spinner.setSelection(0);
trait07_units_spinner = (Spinner) findViewById(R.id.trait07_units_spinner);
trait07_units_spinner.setAdapter (dataAdapter);
trait07_units_spinner.setSelection(0);
Log.i("create eval", "got units spinners initialized");
cmd = "select * from last_eval_table";
crsr = dbh.exec( cmd );
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
trait01 = dbh.getInt(1);
cursor.moveToNext();
trait02 = dbh.getInt(1);
cursor.moveToNext();
trait03 = dbh.getInt(1);
cursor.moveToNext();
trait04 = dbh.getInt(1);
cursor.moveToNext();
trait05 = dbh.getInt(1);
cursor.moveToNext();
trait06 = dbh.getInt(1);
trait06_unitid = dbh.getInt(2);
cursor.moveToNext();
trait07 = dbh.getInt(1);
trait07_unitid = dbh.getInt(2);
cursor.moveToNext();
cursor.close();
Log.i("results last ","eval trait01 "+String.valueOf(trait01));
Log.i("results last ","eval trait02 "+String.valueOf(trait02));
Log.i("results last ","eval trait03 "+String.valueOf(trait03));
Log.i("results last ","eval trait04 "+String.valueOf(trait04));
Log.i("results last ","eval trait05 "+String.valueOf(trait05));
Log.i("results last ","eval trait06 "+String.valueOf(trait06));
Log.i("results last ","eval trait06 units "+String.valueOf(trait06_unitid));
Log.i("results last ","eval trait07 "+String.valueOf(trait07));
Log.i("results last ","eval trait07 units "+String.valueOf(trait07_unitid));
// need to get what position within the current scored_evaluation_traits this trait is
// and set the spinner position to be that position
if (trait01!=0) {
cmd = String.format("select evaluation_trait_table.trait_name from evaluation_trait_table " +
"where id_traitid='%s'", trait01);
crsr = dbh.exec( cmd );
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
trait01_label = dbh.getStr(0);
i = scored_evaluation_traits.indexOf(trait01_label);
trait01_spinner.setSelection(i);
cursor.close();
}
if (trait02!=0) {
cmd = String.format("select evaluation_trait_table.trait_name from evaluation_trait_table " +
"where id_traitid='%s'", trait02);
crsr = dbh.exec( cmd );
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
trait02_label = dbh.getStr(0);
i = scored_evaluation_traits.indexOf(trait02_label);
trait02_spinner.setSelection(i);
cursor.close();
}
if (trait03!=0) {
cmd = String.format("select evaluation_trait_table.trait_name from evaluation_trait_table " +
"where id_traitid='%s'", trait03);
crsr = dbh.exec( cmd );
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
trait03_label = dbh.getStr(0);
i = scored_evaluation_traits.indexOf(trait03_label);
trait03_spinner.setSelection(i);
cursor.close();
}
if (trait04!=0) {
cmd = String.format("select evaluation_trait_table.trait_name from evaluation_trait_table " +
"where id_traitid='%s'", trait04);
crsr = dbh.exec( cmd );
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
trait04_label = dbh.getStr(0);
i = scored_evaluation_traits.indexOf(trait04_label);
trait04_spinner.setSelection(i);
cursor.close();
}
if (trait05!=0) {
cmd = String.format("select evaluation_trait_table.trait_name from evaluation_trait_table " +
"where id_traitid='%s'", trait05);
crsr = dbh.exec( cmd );
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
trait05_label = dbh.getStr(0);
i = scored_evaluation_traits.indexOf(trait05_label);
trait05_spinner.setSelection(i);
cursor.close();
}
if (trait06!=0) {
cmd = String.format("select evaluation_trait_table.trait_name from evaluation_trait_table " +
"where id_traitid='%s'", trait06);
crsr = dbh.exec( cmd );
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
trait06_label = dbh.getStr(0);
i = data_evaluation_traits.indexOf(trait06_label);
trait06_spinner.setSelection(i);
cursor.close();
// need to also get the units for stored trait06
cmd = String.format("select units_table.units_name from units_table where " +
"id_unitsid='%s'", trait06_unitid);
crsr = dbh.exec( cmd );
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
trait06_units = dbh.getStr(0);
i = trait_units.indexOf(trait06_units) ;
trait06_units_spinner.setSelection(i);
cursor.close();
}
if (trait07!=0) {
cmd = String.format("select evaluation_trait_table.trait_name from evaluation_trait_table " +
"where id_traitid='%s'", trait07);
crsr = dbh.exec( cmd );
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
trait07_label = dbh.getStr(0);
i = data_evaluation_traits.indexOf(trait07_label);
trait07_spinner.setSelection(i);
cursor.close();
// need to also get the units for stored trait07
cmd = String.format("select units_table.units_name from units_table where " +
"id_unitsid='%s'", trait07_unitid);
crsr = dbh.exec( cmd );
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
trait07_units = dbh.getStr(0);
i = trait_units.indexOf(trait07_units) ;
trait07_units_spinner.setSelection(i);
cursor.close();
}
Log.i("Create eval", "The selected traits are: ");
Log.i("Create eval", "trait01 " + trait01_label);
Log.i("Create eval", "trait02 " + trait02_label);
Log.i("Create eval", "trait03 " + trait03_label);
Log.i("Create eval", "trait04 " + trait04_label);
Log.i("Create eval", "trait05 " + trait05_label);
Log.i("Create eval", "trait06 " + trait06_label);
Log.i("Create eval", "trait07 " + trait07_label);
}
| public void onCreate(Bundle savedInstanceState) {
setTitle(R.string.app_name_long);
super.onCreate(savedInstanceState);
setContentView(R.layout.create_sheep_evaluation);
String dbname = getString(R.string.real_database_file);
dbh = new DatabaseHandler( this, dbname );
scored_evaluation_traits = new ArrayList<String>();
// enable the Create an evaluation button when we come in to start this task
Button btn2 = (Button) findViewById( R.id.create_evaluation_task_btn );
btn2.setEnabled(true);
// Select All fields from trait table that are scored type and get set to fill the spinners
cmd = "select * from evaluation_trait_table where trait_type = 1";
Object crsr = dbh.exec( cmd ); ;
Log.i("testing", "executed command " + cmd);
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
scored_evaluation_traits.add("Select a Trait");
Log.i("testinterface", "in onCreate below got evaluation straits table");
// looping through all rows and adding to list all the scored evaluation types
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
scored_evaluation_traits.add(cursor.getString(1));
}
cursor.close();
dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, scored_evaluation_traits);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Fill the 5 scored spinners from the same list of evaluation traits.
trait01_spinner = (Spinner) findViewById(R.id.trait01_spinner);
trait01_spinner.setAdapter (dataAdapter);
trait01_spinner.setSelection(0);
trait02_spinner = (Spinner) findViewById(R.id.trait02_spinner);
trait02_spinner.setAdapter (dataAdapter);
trait02_spinner.setSelection(0);
trait03_spinner = (Spinner) findViewById(R.id.trait03_spinner);
trait03_spinner.setAdapter (dataAdapter);
trait03_spinner.setSelection(0);
trait04_spinner = (Spinner) findViewById(R.id.trait04_spinner);
trait04_spinner.setAdapter (dataAdapter);
trait04_spinner.setSelection(0);
trait05_spinner = (Spinner) findViewById(R.id.trait05_spinner);
trait05_spinner.setAdapter (dataAdapter);
trait05_spinner.setSelection(0);
Log.i("create eval", "got score spinners initialized");
// Now set up for the two real data traits
data_evaluation_traits = new ArrayList<String>();
// Select All fields from trait table that are real data type and get set to fill the spinners
cmd = "select * from evaluation_trait_table where trait_type = 2";
crsr = dbh.exec( cmd );
// Log.i("testing", "executed command " + cmd);
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
data_evaluation_traits.add("Select a Trait");
// Log.i("testinterface", "in onCreate below got evaluation traits table");
// looping through all rows and adding to list
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
data_evaluation_traits.add(cursor.getString(1));
}
cursor.close();
// Log.i("createEval ", "below got eval traits");
dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, data_evaluation_traits);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
trait06_spinner = (Spinner) findViewById(R.id.trait06_spinner);
trait06_spinner.setAdapter (dataAdapter);
trait06_spinner.setSelection(0);
trait07_spinner = (Spinner) findViewById(R.id.trait07_spinner);
trait07_spinner.setAdapter (dataAdapter);
trait07_spinner.setSelection(0);
Log.i("create eval", "got real spinners initialized");
trait_units = new ArrayList<String>();
// Select All fields from trait units table and get set to fill the spinners
cmd = "select * from units_table ";
crsr = dbh.exec( cmd );
Log.i("units ", "executed command " + cmd);
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
trait_units.add("Select Measurement Units");
// looping through all rows and adding to list
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
trait_units.add(cursor.getString(1));
}
cursor.close();
dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, trait_units);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
trait06_units_spinner = (Spinner) findViewById(R.id.trait06_units_spinner);
trait06_units_spinner.setAdapter (dataAdapter);
trait06_units_spinner.setSelection(0);
trait07_units_spinner = (Spinner) findViewById(R.id.trait07_units_spinner);
trait07_units_spinner.setAdapter (dataAdapter);
trait07_units_spinner.setSelection(0);
Log.i("create eval", "got units spinners initialized");
cmd = "select * from last_eval_table";
crsr = dbh.exec( cmd );
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
trait01 = dbh.getInt(1);
cursor.moveToNext();
trait02 = dbh.getInt(1);
cursor.moveToNext();
trait03 = dbh.getInt(1);
cursor.moveToNext();
trait04 = dbh.getInt(1);
cursor.moveToNext();
trait05 = dbh.getInt(1);
cursor.moveToNext();
trait06 = dbh.getInt(1);
trait06_unitid = dbh.getInt(2);
cursor.moveToNext();
trait07 = dbh.getInt(1);
trait07_unitid = dbh.getInt(2);
cursor.moveToNext();
cursor.close();
Log.i("results last ","eval trait01 "+String.valueOf(trait01));
Log.i("results last ","eval trait02 "+String.valueOf(trait02));
Log.i("results last ","eval trait03 "+String.valueOf(trait03));
Log.i("results last ","eval trait04 "+String.valueOf(trait04));
Log.i("results last ","eval trait05 "+String.valueOf(trait05));
Log.i("results last ","eval trait06 "+String.valueOf(trait06));
Log.i("results last ","eval trait06 units "+String.valueOf(trait06_unitid));
Log.i("results last ","eval trait07 "+String.valueOf(trait07));
Log.i("results last ","eval trait07 units "+String.valueOf(trait07_unitid));
// need to get what position within the current scored_evaluation_traits this trait is
// and set the spinner position to be that position
if (trait01!=0) {
cmd = String.format("select evaluation_trait_table.trait_name from evaluation_trait_table " +
"where id_traitid='%s'", trait01);
crsr = dbh.exec( cmd );
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
trait01_label = dbh.getStr(0);
i = scored_evaluation_traits.indexOf(trait01_label);
trait01_spinner.setSelection(i);
cursor.close();
}
if (trait02!=0) {
cmd = String.format("select evaluation_trait_table.trait_name from evaluation_trait_table " +
"where id_traitid='%s'", trait02);
crsr = dbh.exec( cmd );
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
trait02_label = dbh.getStr(0);
i = scored_evaluation_traits.indexOf(trait02_label);
trait02_spinner.setSelection(i);
cursor.close();
}
if (trait03!=0) {
cmd = String.format("select evaluation_trait_table.trait_name from evaluation_trait_table " +
"where id_traitid='%s'", trait03);
crsr = dbh.exec( cmd );
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
trait03_label = dbh.getStr(0);
i = scored_evaluation_traits.indexOf(trait03_label);
trait03_spinner.setSelection(i);
cursor.close();
}
if (trait04!=0) {
cmd = String.format("select evaluation_trait_table.trait_name from evaluation_trait_table " +
"where id_traitid='%s'", trait04);
crsr = dbh.exec( cmd );
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
trait04_label = dbh.getStr(0);
i = scored_evaluation_traits.indexOf(trait04_label);
trait04_spinner.setSelection(i);
cursor.close();
}
if (trait05!=0) {
cmd = String.format("select evaluation_trait_table.trait_name from evaluation_trait_table " +
"where id_traitid='%s'", trait05);
crsr = dbh.exec( cmd );
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
trait05_label = dbh.getStr(0);
i = scored_evaluation_traits.indexOf(trait05_label);
trait05_spinner.setSelection(i);
cursor.close();
}
if (trait06!=0) {
cmd = String.format("select evaluation_trait_table.trait_name from evaluation_trait_table " +
"where id_traitid='%s'", trait06);
crsr = dbh.exec( cmd );
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
trait06_label = dbh.getStr(0);
i = data_evaluation_traits.indexOf(trait06_label);
trait06_spinner.setSelection(i);
cursor.close();
// need to also get the units for stored trait06
cmd = String.format("select units_table.units_name from units_table where " +
"id_unitsid='%s'", trait06_unitid);
crsr = dbh.exec( cmd );
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
trait06_units = dbh.getStr(0);
i = trait_units.indexOf(trait06_units) ;
trait06_units_spinner.setSelection(i);
cursor.close();
}
if (trait07!=0) {
cmd = String.format("select evaluation_trait_table.trait_name from evaluation_trait_table " +
"where id_traitid='%s'", trait07);
crsr = dbh.exec( cmd );
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
trait07_label = dbh.getStr(0);
i = data_evaluation_traits.indexOf(trait07_label);
trait07_spinner.setSelection(i);
cursor.close();
// need to also get the units for stored trait07
cmd = String.format("select units_table.units_name from units_table where " +
"id_unitsid='%s'", trait07_unitid);
crsr = dbh.exec( cmd );
cursor = ( Cursor ) crsr;
dbh.moveToFirstRecord();
trait07_units = dbh.getStr(0);
i = trait_units.indexOf(trait07_units) ;
trait07_units_spinner.setSelection(i);
cursor.close();
}
Log.i("Create eval", "The selected traits are: ");
Log.i("Create eval", "trait01 " + trait01_label);
Log.i("Create eval", "trait02 " + trait02_label);
Log.i("Create eval", "trait03 " + trait03_label);
Log.i("Create eval", "trait04 " + trait04_label);
Log.i("Create eval", "trait05 " + trait05_label);
Log.i("Create eval", "trait06 " + trait06_label);
Log.i("Create eval", "trait07 " + trait07_label);
}
|
diff --git a/src/main/java/hudson/plugins/deploy/DeployPublisher.java b/src/main/java/hudson/plugins/deploy/DeployPublisher.java
index d32d5c9..6f64e67 100644
--- a/src/main/java/hudson/plugins/deploy/DeployPublisher.java
+++ b/src/main/java/hudson/plugins/deploy/DeployPublisher.java
@@ -1,81 +1,82 @@
package hudson.plugins.deploy;
import hudson.FilePath;
import hudson.Launcher;
import hudson.Extension;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.BuildListener;
import hudson.model.Result;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.BuildStepMonitor;
import hudson.tasks.Notifier;
import hudson.tasks.Publisher;
import java.io.IOException;
import java.io.Serializable;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import org.kohsuke.stapler.DataBoundConstructor;
/**
* Deploys WAR to a continer.
*
* @author Kohsuke Kawaguchi
*/
public class DeployPublisher extends Notifier implements Serializable {
public final ContainerAdapter adapter;
public final String war;
public final boolean onFailure;
@DataBoundConstructor
public DeployPublisher(ContainerAdapter adapter, String war, boolean onFailure) {
this.adapter = adapter;
this.war = war;
this.onFailure = onFailure;
}
public boolean perform(AbstractBuild<?,?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
if (build.getResult().equals(Result.SUCCESS) || onFailure) {
- FilePath warFile = build.getWorkspace().child(this.war);
- if(!adapter.redeploy(warFile,build,launcher,listener))
- build.setResult(Result.FAILURE);
+ for (FilePath warFile : build.getWorkspace().list(this.war)) {
+ if(!adapter.redeploy(warFile,build,launcher,listener))
+ build.setResult(Result.FAILURE);
+ }
}
return true;
}
public BuildStepMonitor getRequiredMonitorService() {
return BuildStepMonitor.BUILD;
}
@Extension
public static final class DescriptorImpl extends BuildStepDescriptor<Publisher> {
public boolean isApplicable(Class<? extends AbstractProject> jobType) {
return true;
}
public String getDisplayName() {
return Messages.DeployPublisher_DisplayName();
}
/**
* Sort the descriptors so that the order they are displayed is more predictable
*/
public List<ContainerAdapterDescriptor> getContainerAdapters() {
List<ContainerAdapterDescriptor> r = new ArrayList<ContainerAdapterDescriptor>(ContainerAdapter.all());
Collections.sort(r,new Comparator<ContainerAdapterDescriptor>() {
public int compare(ContainerAdapterDescriptor o1, ContainerAdapterDescriptor o2) {
return o1.getDisplayName().compareTo(o2.getDisplayName());
}
});
return r;
}
}
private static final long serialVersionUID = 1L;
}
| true | true | public boolean perform(AbstractBuild<?,?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
if (build.getResult().equals(Result.SUCCESS) || onFailure) {
FilePath warFile = build.getWorkspace().child(this.war);
if(!adapter.redeploy(warFile,build,launcher,listener))
build.setResult(Result.FAILURE);
}
return true;
}
| public boolean perform(AbstractBuild<?,?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
if (build.getResult().equals(Result.SUCCESS) || onFailure) {
for (FilePath warFile : build.getWorkspace().list(this.war)) {
if(!adapter.redeploy(warFile,build,launcher,listener))
build.setResult(Result.FAILURE);
}
}
return true;
}
|
diff --git a/java/de/dfki/lt/mary/modules/HTSContextTranslator.java b/java/de/dfki/lt/mary/modules/HTSContextTranslator.java
index 1eeeeabec..3f38c97c3 100644
--- a/java/de/dfki/lt/mary/modules/HTSContextTranslator.java
+++ b/java/de/dfki/lt/mary/modules/HTSContextTranslator.java
@@ -1,567 +1,573 @@
/**
* Copyright 2000-2007 DFKI GmbH.
* All Rights Reserved. Use is subject to license terms.
*
* Permission is hereby granted, free of charge, to use and distribute
* this software and its documentation without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of this work, and to
* permit persons to whom this work is furnished to do so, subject to
* the following conditions:
*
* 1. The code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* 2. Any modifications must be clearly marked as such.
* 3. Original authors' names are not deleted.
* 4. The authors' names are not used to endorse or promote products
* derived from this software without specific prior written
* permission.
*
* DFKI GMBH AND THE CONTRIBUTORS TO THIS WORK DISCLAIM ALL WARRANTIES WITH
* REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL DFKI GMBH NOR THE
* CONTRIBUTORS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
* PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
* ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
* THIS SOFTWARE.
*/
package de.dfki.lt.mary.modules;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Vector;
import de.dfki.lt.mary.MaryData;
import de.dfki.lt.mary.MaryDataType;
import de.dfki.lt.mary.MaryProperties;
import de.dfki.lt.mary.htsengine.HMMVoice;
import de.dfki.lt.mary.modules.InternalModule;
import de.dfki.lt.mary.unitselection.featureprocessors.FeatureDefinition;
import de.dfki.lt.mary.unitselection.featureprocessors.FeatureProcessorManager;
import de.dfki.lt.mary.unitselection.featureprocessors.FeatureVector;
import de.dfki.lt.mary.unitselection.featureprocessors.TargetFeatureComputer;
import de.dfki.lt.mary.modules.synthesis.Voice;
/**
* Translates TARGETFEATURES --> HTSCONTEXT used in HMM synthesis.
*
* Java port of make_labels_full.pl and common_routines.pl developed in Perl
* by Sacha Krstulovic.
* @author Marc Schröder, Marcela Charfuelan
*/
public class HTSContextTranslator extends InternalModule {
private String contextFeatureFile;
private Map<String,String> feat2shortFeat = new HashMap<String, String>();
public HTSContextTranslator()
{
super("HTSContextTranslator",
MaryDataType.get("TARGETFEATURES"),
MaryDataType.get("HTSCONTEXT")
);
}
/**
* This module is actually tested as part of the HMMSynthesizer test,
* for which reason this method does nothing.
*/
public synchronized void powerOnSelfTest() throws Error
{
}
/**
* Translate TARGETFEATURES to HTSCONTEXT
* @param MaryData type.
*/
public MaryData process(MaryData d)
throws Exception
{
MaryData output = new MaryData(outputType());
Voice v = d.getDefaultVoice(); /* This is the way of getting a Voice through a MaryData type */
assert v instanceof HMMVoice : v.getName()+" is not an HMM voice!";
HMMVoice hmmv = (HMMVoice)v;
String lab;
lab = _process(d.getPlainText(), hmmv.getFeatureList());
output.setPlainText(lab);
return output;
}
public void setContextFeatureFile(String str){ contextFeatureFile = str; }
/**Translate TARGETFEATURES to HTSCONTEXT
* @param String d
* @return String
* @throws Exception
*/
private String _process(String d, Vector<String> featureList)
throws Exception
{
Hashtable<String,Integer> maryPfeats = new Hashtable<String,Integer>();
ArrayList< Vector<String> > currentPfeats = new ArrayList< Vector<String> >();
int i,j;
int num_phoneme = 0;
int num_mary_pfeats = 0;
/* These .._phoneme variables indicate when to convert tricky phonemes */
int index_mary_phoneme = 0;
int index_mary_prev_phoneme = 0;
int index_mary_next_phoneme = 0;
int index_mary_sentence_punc = 0;
int index_mary_prev_punctuation = 0;
int index_mary_next_punctuation = 0;
int index_mary_tobi_accent = 0;
Integer index;
boolean first_blank_line = false;
String pfeats, fea_out;
String lab = "";
Vector<String> v, n_v, nn_v;
pfeats = d;
Scanner s = null;
String line;
s = new Scanner(pfeats).useDelimiter("\n");
/* Create a hash table with the mary_ pfeats context feature names and possible values. */
while(s.hasNext()) {
line = s.next();
//System.out.println("length=" + line.length() + " line= " + line);
if( line.contains("mary_") ) {
String[] elem = line.split(" ");
if( elem.length > 1) {
maryPfeats.put(elem[0], new Integer(num_mary_pfeats));
if(elem[0].contentEquals("mary_phoneme"))
index_mary_phoneme = num_mary_pfeats;
else if(elem[0].contentEquals("mary_prev_phoneme"))
index_mary_prev_phoneme = num_mary_pfeats;
else if(elem[0].contentEquals("mary_next_phoneme"))
index_mary_next_phoneme = num_mary_pfeats;
else if(elem[0].contentEquals("mary_sentence_punc"))
index_mary_sentence_punc = num_mary_pfeats;
else if(elem[0].contentEquals("mary_prev_punctuation"))
index_mary_prev_punctuation = num_mary_pfeats;
else if(elem[0].contentEquals("mary_next_punctuation"))
index_mary_next_punctuation = num_mary_pfeats;
else if(elem[0].contentEquals("mary_tobi_accent"))
index_mary_tobi_accent = num_mary_pfeats;
num_mary_pfeats++;
}
}
/* after "mary_" lines there are two lines more containing:
ShortValuedFeatureProcessors
ContinuousFeatureProcessors and then an empty line */
if( line.length()==0 && !first_blank_line) {
first_blank_line = true;
//System.out.println("first blank line length=" + line.length());
} else if( first_blank_line ) {
String[] elem = line.split(" ");
if( elem.length > 1) {
currentPfeats.add(new Vector<String>());
v = currentPfeats.get(num_phoneme);
/* create a vector with the elements of this line */
for(i=0; i<elem.length; i++) {
//System.out.println("elem " + i + ": " + elem[i]);
/* i need to convert tricky phonemes */
if( i == index_mary_phoneme || i == index_mary_prev_phoneme || i == index_mary_next_phoneme ) {
v.addElement(replaceTrickyPhones(elem[i]));
}
else if(i == index_mary_sentence_punc || i == index_mary_prev_punctuation || i == index_mary_next_punctuation) {
v.addElement(replacePunc(elem[i]));
}
else if(i == index_mary_tobi_accent )
v.addElement(replaceToBI(elem[i]));
else
v.addElement(elem[i]);
}
num_phoneme++;
}else /* just copy the block between the first and second blank line */
break;
}
} /* while scanner mary_ pfeats */
if (s != null)
s.close();
/* produce output with phonemes in context */
+ /* A context feature vector can be created with at least 3 phonemes */
+ if( num_phoneme >= 3 ) {
String pp_phn, p_phn, cur_phn, n_phn, nn_phn;
v = currentPfeats.get(0);
n_v = currentPfeats.get(1);
nn_v = currentPfeats.get(2);
pp_phn = v.elementAt(0);
p_phn = v.elementAt(0);
cur_phn = v.elementAt(0);
n_phn = n_v.elementAt(0);
nn_phn = nn_v.elementAt(0);
for(i=0; i<currentPfeats.size(); i++){
lab += pp_phn + "^" + p_phn + "-" + cur_phn + "+" + n_phn + "=" + nn_phn + "||";
//System.out.print(pp_phn + "^" + p_phn + "-" + cur_phn + "+" + n_phn + "=" + nn_phn + "||");
pp_phn = p_phn;
p_phn = cur_phn;
cur_phn = n_phn;
n_phn = nn_phn;
if( (i+3) < currentPfeats.size() ) {
nn_v = currentPfeats.get(i+3);
nn_phn = nn_v.elementAt(0);
} else {
nn_v = currentPfeats.get(currentPfeats.size()-1);
nn_phn = nn_v.elementAt(0);
}
v = currentPfeats.get(i);
for(j=0; j<featureList.size(); j++) {
fea_out = featureList.elementAt(j);
/* check if the feature is in maryPfeats list */
if( maryPfeats.containsKey(fea_out) ) {
index = maryPfeats.get(fea_out);
/* now I should look for this index in currentPfeats vector */
/* maybe i need to check first if the value is allowed ??? in the hash table */
/* that is the value should exist in mary_v */
fea_out = shortenPfeat(fea_out);
lab += fea_out + "=" + v.get(index.intValue()) + "|";
//System.out.print(fea_out + "=" + v.get(index.intValue()) + "|");
} else {
logger.debug("HTSContextTranslator: error featureList element " + fea_out + " is not in maryPfeats.");
throw new Exception("HTSContextTranslator: error featureList element " + fea_out + " is not in maryPfeats.");
}
}
lab += "\n";
//System.out.println();
+ }
+ } else { /* there are less than 3 phonemes */
+ logger.debug("HTSContextTranslator: error no sampa symbols to process.");
+ throw new Exception("HTSContextTranslator: error no sampa symbols to process.");
}
//logger.debug("\nLAB:\n" + lab);
return lab;
} /* method _process */
/**Translate TARGETFEATURES to HTSCONTEXT
* (I have put this method public so I can use it from MaryClientHMM)
* This implementation is based on the FeatureDefinition class.
* @param String d text of a TARGETFEATURES data
* @return String
* @throws Exception
*/
public String processTargetFeatures(String d, Vector<String> featureList)
throws Exception
{
FeatureDefinition def = new FeatureDefinition(new BufferedReader(new StringReader(d)), false);
Scanner lines = new Scanner(d).useDelimiter("\n");
// skip up to the first empty line
while (lines.hasNext()) {
String line = lines.next();
if (line.trim().equals("")) break;
}
// Now each of the following lines is a feature vector, up to the next empty line
StringBuffer output = new StringBuffer();
while (lines.hasNext()) {
String line = lines.next();
if (line.trim().equals("")) break;
FeatureVector fv = def.toFeatureVector(0, line);
String context = features2context(def, fv, featureList);
output.append(context);
output.append("\n");
}
return output.toString();
}
/**
* Convert the feature vector into a context model name to be used by HTS/HTK.
* @param def a feature definition
* @param featureVector a feature vector which must be consistent with the Feature definition
* @param featureList a list of features to use in constructing the context model name. If missing, all features in the feature definition are used.
* @return the string representation of one context name.
*/
public String features2context(FeatureDefinition def, FeatureVector featureVector, Vector<String> featureList)
{
if (featureList == null) {
featureList = new Vector<String>(Arrays.asList(def.getFeatureNames().split("\\s+")));
}
// construct quint-phone models:
int iPhoneme = def.getFeatureIndex("mary_phoneme");
int iPrevPhoneme = def.getFeatureIndex("mary_prev_phoneme");
int iNextPhoneme = def.getFeatureIndex("mary_next_phoneme");
String mary_phoneme = replaceTrickyPhones(
def.getFeatureValueAsString(iPhoneme, featureVector.getFeatureAsInt(iPhoneme))
);
String mary_prev_phoneme = replaceTrickyPhones(
def.getFeatureValueAsString(iPrevPhoneme, featureVector.getFeatureAsInt(iPrevPhoneme))
);
String mary_next_phoneme = replaceTrickyPhones(
def.getFeatureValueAsString(iNextPhoneme, featureVector.getFeatureAsInt(iNextPhoneme))
);
String mary_prev_prev_phoneme = "0";
if (def.hasFeature("mary_prev_prev_phoneme")) {
int ipp = def.getFeatureIndex("mary_prev_prev_phoneme");
mary_prev_prev_phoneme = replaceTrickyPhones(
def.getFeatureValueAsString(ipp, featureVector.getFeatureAsInt(ipp))
);
}
String mary_next_next_phoneme = "0";
if (def.hasFeature("mary_next_next_phoneme")) {
int inn = def.getFeatureIndex("mary_next_next_phoneme");
mary_next_next_phoneme = replaceTrickyPhones(
def.getFeatureValueAsString(inn, featureVector.getFeatureAsInt(inn))
);
}
StringBuffer contextName = new StringBuffer();
contextName.append(mary_prev_prev_phoneme);
contextName.append("^");
contextName.append(mary_prev_phoneme);
contextName.append("-");
contextName.append(mary_phoneme);
contextName.append("+");
contextName.append(mary_next_phoneme);
contextName.append("=");
contextName.append(mary_next_next_phoneme);
contextName.append("||");
for (String f : featureList) {
if (!def.hasFeature(f)) {
throw new IllegalArgumentException("Feature '"+f+"' is not known in the feature definition. Valid features are: "+def.getFeatureNames());
}
String shortF = shortenPfeat(f);
contextName.append(shortF);
contextName.append("=");
String value = def.getFeatureValueAsString(f, featureVector);
if (f.contains("sentence_punc") || f.contains("punctuation"))
value = replacePunc(value);
else if (f.contains("tobi"))
value = replaceToBI(value);
contextName.append(value);
contextName.append("|");
}
return contextName.toString();
} /* method features2context */
/**
* Convert the feature vector into a context model name to be used by HTS/HTK.
* @param def a feature definition
* @param featureVector a feature vector which must be consistent with the Feature definition
* @param featureList a list of features to use in constructing the context model name. If missing, all features in the feature definition are used.
* @return the string representation of one context name.
*/
public String features2LongContext(FeatureDefinition def, FeatureVector featureVector, Vector<String> featureList)
{
if (featureList == null) {
featureList = new Vector<String>(Arrays.asList(def.getFeatureNames().split("\\s+")));
}
StringBuffer contextName = new StringBuffer();
contextName.append("|");
for (String f : featureList) {
if (!def.hasFeature(f)) {
throw new IllegalArgumentException("Feature '"+f+"' is not known in the feature definition. Valid features are: "+def.getFeatureNames());
}
contextName.append(f);
contextName.append("=");
String value = def.getFeatureValueAsString(f, featureVector);
if (f.endsWith("phoneme"))
value = replaceTrickyPhones(value);
else if (f.contains("sentence_punc") || f.contains("punctuation"))
value = replacePunc(value);
else if (f.contains("tobi"))
value = replaceToBI(value);
contextName.append(value);
contextName.append("|");
}
return contextName.toString();
} /* method features2context */
/** Translation table for labels which are incompatible with HTK or shell filenames
* See common_routines.pl in HTS training.
* @param lab
* @return String
*/
public String replaceTrickyPhones(String lab){
String s = lab;
/** the replace is done for the labels: mary_phoneme, mary_prev_phoneme and mary_next_phoneme */
/** DE (replacements in German phoneme set) */
if(lab.contentEquals("6") )
s = "ER6";
else if (lab.contentEquals("=6") )
s = "ER6";
else if (lab.contentEquals("2:") )
s = "EU2";
else if (lab.contentEquals("9") )
s = "EU9";
else if (lab.contentEquals("9~") )
s = "UM9";
else if (lab.contentEquals("e~") )
s = "IMe";
else if (lab.contentEquals("a~") )
s = "ANa";
else if (lab.contentEquals("o~") )
s = "ONo";
else if (lab.contentEquals("?") )
s = "gstop";
/** EN (replacements in English phoneme set) */
else if (lab.contentEquals("r=") )
s = "rr";
//System.out.println("LAB=" + s);
return s;
}
/** Translation table for labels which are incompatible with HTK or shell filenames
* See common_routines.pl in HTS training.
* In this function the phonemes as used internally in HTSEngine are changed
* back to the Mary TTS set, this function is necessary when correcting the
* actual durations of AcousticPhonemes.
* @param lab
* @return String
*/
public String replaceBackTrickyPhones(String lab){
String s = lab;
/** DE (replacements in German phoneme set) */
if(lab.contentEquals("ER6") )
s = "6";
//else if (lab.contentEquals("ER6") ) /* CHECK ??? */
// s = "6";
else if (lab.contentEquals("EU2") )
s = "2:";
else if (lab.contentEquals("EU9") )
s = "9";
else if (lab.contentEquals("UM9") )
s = "9~";
else if (lab.contentEquals("IMe") )
s = "e~";
else if (lab.contentEquals("ANa") )
s = "a~";
else if (lab.contentEquals("ONo") )
s = "o~";
else if (lab.contentEquals("gstop") )
s = "?";
/** EN (replacements in English phoneme set) */
else if (lab.contentEquals("rr") )
s = "r=";
//System.out.println("LAB=" + s);
return s;
}
/** Shorten the key name (to make the full context names shorter)
* See common_routines.pl in HTS training.
*/
private String shortenPfeat(String fea) {
// look up the feature in a table:
String s = feat2shortFeat.get(fea);
if (s!=null) return s;
// First time: need to do the shortening:
// s = s.replace("^mary_pos$/POS/g; /* ??? */
s = fea.replace("mary_", "");
s = s.replace("phoneme","phn");
s = s.replace("prev","p");
s = s.replace("next","n");
s = s.replace("sentence","snt");
s = s.replace("phrase","phr");
s = s.replace("word","wrd");
s = s.replace("from_","");
s = s.replace("to_","");
s = s.replace("in_","");
s = s.replace("is_","");
s = s.replace("break","brk");
s = s.replace("start","stt");
s = s.replace("accented","acc");
s = s.replace("accent","acc");
s = s.replace("stressed","str");
s = s.replace("punctuation","punc");
s = s.replace("frequency","freq");
s = s.replace("position","pos");
s = s.replace("halfphone_lr", "lr");
feat2shortFeat.put(fea, s);
return s;
}
private String replacePunc(String lab){
String s = lab;
if(lab.contentEquals(".") )
s = "pt";
else if (lab.contentEquals(",") )
s = "cm";
else if (lab.contentEquals("(") )
s = "op";
else if (lab.contentEquals(")") )
s = "cp";
else if (lab.contentEquals("?") )
s = "in";
else if (lab.contentEquals("\"") )
s = "qt";
return s;
}
private String replaceToBI(String lab){
String s = lab;
if(lab.contains("*") )
s = s.replace("*", "st");
if(lab.contains("%") )
s = s.replace("%", "pc");
if(lab.contains("^") )
s = s.replace("^", "ht");
return s;
}
} /* class HTSContextTranslator*/
| false | true | private String _process(String d, Vector<String> featureList)
throws Exception
{
Hashtable<String,Integer> maryPfeats = new Hashtable<String,Integer>();
ArrayList< Vector<String> > currentPfeats = new ArrayList< Vector<String> >();
int i,j;
int num_phoneme = 0;
int num_mary_pfeats = 0;
/* These .._phoneme variables indicate when to convert tricky phonemes */
int index_mary_phoneme = 0;
int index_mary_prev_phoneme = 0;
int index_mary_next_phoneme = 0;
int index_mary_sentence_punc = 0;
int index_mary_prev_punctuation = 0;
int index_mary_next_punctuation = 0;
int index_mary_tobi_accent = 0;
Integer index;
boolean first_blank_line = false;
String pfeats, fea_out;
String lab = "";
Vector<String> v, n_v, nn_v;
pfeats = d;
Scanner s = null;
String line;
s = new Scanner(pfeats).useDelimiter("\n");
/* Create a hash table with the mary_ pfeats context feature names and possible values. */
while(s.hasNext()) {
line = s.next();
//System.out.println("length=" + line.length() + " line= " + line);
if( line.contains("mary_") ) {
String[] elem = line.split(" ");
if( elem.length > 1) {
maryPfeats.put(elem[0], new Integer(num_mary_pfeats));
if(elem[0].contentEquals("mary_phoneme"))
index_mary_phoneme = num_mary_pfeats;
else if(elem[0].contentEquals("mary_prev_phoneme"))
index_mary_prev_phoneme = num_mary_pfeats;
else if(elem[0].contentEquals("mary_next_phoneme"))
index_mary_next_phoneme = num_mary_pfeats;
else if(elem[0].contentEquals("mary_sentence_punc"))
index_mary_sentence_punc = num_mary_pfeats;
else if(elem[0].contentEquals("mary_prev_punctuation"))
index_mary_prev_punctuation = num_mary_pfeats;
else if(elem[0].contentEquals("mary_next_punctuation"))
index_mary_next_punctuation = num_mary_pfeats;
else if(elem[0].contentEquals("mary_tobi_accent"))
index_mary_tobi_accent = num_mary_pfeats;
num_mary_pfeats++;
}
}
/* after "mary_" lines there are two lines more containing:
ShortValuedFeatureProcessors
ContinuousFeatureProcessors and then an empty line */
if( line.length()==0 && !first_blank_line) {
first_blank_line = true;
//System.out.println("first blank line length=" + line.length());
} else if( first_blank_line ) {
String[] elem = line.split(" ");
if( elem.length > 1) {
currentPfeats.add(new Vector<String>());
v = currentPfeats.get(num_phoneme);
/* create a vector with the elements of this line */
for(i=0; i<elem.length; i++) {
//System.out.println("elem " + i + ": " + elem[i]);
/* i need to convert tricky phonemes */
if( i == index_mary_phoneme || i == index_mary_prev_phoneme || i == index_mary_next_phoneme ) {
v.addElement(replaceTrickyPhones(elem[i]));
}
else if(i == index_mary_sentence_punc || i == index_mary_prev_punctuation || i == index_mary_next_punctuation) {
v.addElement(replacePunc(elem[i]));
}
else if(i == index_mary_tobi_accent )
v.addElement(replaceToBI(elem[i]));
else
v.addElement(elem[i]);
}
num_phoneme++;
}else /* just copy the block between the first and second blank line */
break;
}
} /* while scanner mary_ pfeats */
if (s != null)
s.close();
/* produce output with phonemes in context */
String pp_phn, p_phn, cur_phn, n_phn, nn_phn;
v = currentPfeats.get(0);
n_v = currentPfeats.get(1);
nn_v = currentPfeats.get(2);
pp_phn = v.elementAt(0);
p_phn = v.elementAt(0);
cur_phn = v.elementAt(0);
n_phn = n_v.elementAt(0);
nn_phn = nn_v.elementAt(0);
for(i=0; i<currentPfeats.size(); i++){
lab += pp_phn + "^" + p_phn + "-" + cur_phn + "+" + n_phn + "=" + nn_phn + "||";
//System.out.print(pp_phn + "^" + p_phn + "-" + cur_phn + "+" + n_phn + "=" + nn_phn + "||");
pp_phn = p_phn;
p_phn = cur_phn;
cur_phn = n_phn;
n_phn = nn_phn;
if( (i+3) < currentPfeats.size() ) {
nn_v = currentPfeats.get(i+3);
nn_phn = nn_v.elementAt(0);
} else {
nn_v = currentPfeats.get(currentPfeats.size()-1);
nn_phn = nn_v.elementAt(0);
}
v = currentPfeats.get(i);
for(j=0; j<featureList.size(); j++) {
fea_out = featureList.elementAt(j);
/* check if the feature is in maryPfeats list */
if( maryPfeats.containsKey(fea_out) ) {
index = maryPfeats.get(fea_out);
/* now I should look for this index in currentPfeats vector */
/* maybe i need to check first if the value is allowed ??? in the hash table */
/* that is the value should exist in mary_v */
fea_out = shortenPfeat(fea_out);
lab += fea_out + "=" + v.get(index.intValue()) + "|";
//System.out.print(fea_out + "=" + v.get(index.intValue()) + "|");
} else {
logger.debug("HTSContextTranslator: error featureList element " + fea_out + " is not in maryPfeats.");
throw new Exception("HTSContextTranslator: error featureList element " + fea_out + " is not in maryPfeats.");
}
}
lab += "\n";
//System.out.println();
}
//logger.debug("\nLAB:\n" + lab);
return lab;
} /* method _process */
| private String _process(String d, Vector<String> featureList)
throws Exception
{
Hashtable<String,Integer> maryPfeats = new Hashtable<String,Integer>();
ArrayList< Vector<String> > currentPfeats = new ArrayList< Vector<String> >();
int i,j;
int num_phoneme = 0;
int num_mary_pfeats = 0;
/* These .._phoneme variables indicate when to convert tricky phonemes */
int index_mary_phoneme = 0;
int index_mary_prev_phoneme = 0;
int index_mary_next_phoneme = 0;
int index_mary_sentence_punc = 0;
int index_mary_prev_punctuation = 0;
int index_mary_next_punctuation = 0;
int index_mary_tobi_accent = 0;
Integer index;
boolean first_blank_line = false;
String pfeats, fea_out;
String lab = "";
Vector<String> v, n_v, nn_v;
pfeats = d;
Scanner s = null;
String line;
s = new Scanner(pfeats).useDelimiter("\n");
/* Create a hash table with the mary_ pfeats context feature names and possible values. */
while(s.hasNext()) {
line = s.next();
//System.out.println("length=" + line.length() + " line= " + line);
if( line.contains("mary_") ) {
String[] elem = line.split(" ");
if( elem.length > 1) {
maryPfeats.put(elem[0], new Integer(num_mary_pfeats));
if(elem[0].contentEquals("mary_phoneme"))
index_mary_phoneme = num_mary_pfeats;
else if(elem[0].contentEquals("mary_prev_phoneme"))
index_mary_prev_phoneme = num_mary_pfeats;
else if(elem[0].contentEquals("mary_next_phoneme"))
index_mary_next_phoneme = num_mary_pfeats;
else if(elem[0].contentEquals("mary_sentence_punc"))
index_mary_sentence_punc = num_mary_pfeats;
else if(elem[0].contentEquals("mary_prev_punctuation"))
index_mary_prev_punctuation = num_mary_pfeats;
else if(elem[0].contentEquals("mary_next_punctuation"))
index_mary_next_punctuation = num_mary_pfeats;
else if(elem[0].contentEquals("mary_tobi_accent"))
index_mary_tobi_accent = num_mary_pfeats;
num_mary_pfeats++;
}
}
/* after "mary_" lines there are two lines more containing:
ShortValuedFeatureProcessors
ContinuousFeatureProcessors and then an empty line */
if( line.length()==0 && !first_blank_line) {
first_blank_line = true;
//System.out.println("first blank line length=" + line.length());
} else if( first_blank_line ) {
String[] elem = line.split(" ");
if( elem.length > 1) {
currentPfeats.add(new Vector<String>());
v = currentPfeats.get(num_phoneme);
/* create a vector with the elements of this line */
for(i=0; i<elem.length; i++) {
//System.out.println("elem " + i + ": " + elem[i]);
/* i need to convert tricky phonemes */
if( i == index_mary_phoneme || i == index_mary_prev_phoneme || i == index_mary_next_phoneme ) {
v.addElement(replaceTrickyPhones(elem[i]));
}
else if(i == index_mary_sentence_punc || i == index_mary_prev_punctuation || i == index_mary_next_punctuation) {
v.addElement(replacePunc(elem[i]));
}
else if(i == index_mary_tobi_accent )
v.addElement(replaceToBI(elem[i]));
else
v.addElement(elem[i]);
}
num_phoneme++;
}else /* just copy the block between the first and second blank line */
break;
}
} /* while scanner mary_ pfeats */
if (s != null)
s.close();
/* produce output with phonemes in context */
/* A context feature vector can be created with at least 3 phonemes */
if( num_phoneme >= 3 ) {
String pp_phn, p_phn, cur_phn, n_phn, nn_phn;
v = currentPfeats.get(0);
n_v = currentPfeats.get(1);
nn_v = currentPfeats.get(2);
pp_phn = v.elementAt(0);
p_phn = v.elementAt(0);
cur_phn = v.elementAt(0);
n_phn = n_v.elementAt(0);
nn_phn = nn_v.elementAt(0);
for(i=0; i<currentPfeats.size(); i++){
lab += pp_phn + "^" + p_phn + "-" + cur_phn + "+" + n_phn + "=" + nn_phn + "||";
//System.out.print(pp_phn + "^" + p_phn + "-" + cur_phn + "+" + n_phn + "=" + nn_phn + "||");
pp_phn = p_phn;
p_phn = cur_phn;
cur_phn = n_phn;
n_phn = nn_phn;
if( (i+3) < currentPfeats.size() ) {
nn_v = currentPfeats.get(i+3);
nn_phn = nn_v.elementAt(0);
} else {
nn_v = currentPfeats.get(currentPfeats.size()-1);
nn_phn = nn_v.elementAt(0);
}
v = currentPfeats.get(i);
for(j=0; j<featureList.size(); j++) {
fea_out = featureList.elementAt(j);
/* check if the feature is in maryPfeats list */
if( maryPfeats.containsKey(fea_out) ) {
index = maryPfeats.get(fea_out);
/* now I should look for this index in currentPfeats vector */
/* maybe i need to check first if the value is allowed ??? in the hash table */
/* that is the value should exist in mary_v */
fea_out = shortenPfeat(fea_out);
lab += fea_out + "=" + v.get(index.intValue()) + "|";
//System.out.print(fea_out + "=" + v.get(index.intValue()) + "|");
} else {
logger.debug("HTSContextTranslator: error featureList element " + fea_out + " is not in maryPfeats.");
throw new Exception("HTSContextTranslator: error featureList element " + fea_out + " is not in maryPfeats.");
}
}
lab += "\n";
//System.out.println();
}
} else { /* there are less than 3 phonemes */
logger.debug("HTSContextTranslator: error no sampa symbols to process.");
throw new Exception("HTSContextTranslator: error no sampa symbols to process.");
}
//logger.debug("\nLAB:\n" + lab);
return lab;
} /* method _process */
|
diff --git a/gui/src/main/java/org/jboss/as/console/client/domain/profiles/SubsystemSection.java b/gui/src/main/java/org/jboss/as/console/client/domain/profiles/SubsystemSection.java
index 08c25513..242e4cdb 100644
--- a/gui/src/main/java/org/jboss/as/console/client/domain/profiles/SubsystemSection.java
+++ b/gui/src/main/java/org/jboss/as/console/client/domain/profiles/SubsystemSection.java
@@ -1,82 +1,81 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @author tags. All rights reserved.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* 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 Lesser General Public License, v. 2.1.
* 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 Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License,
* v.2.1 along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.jboss.as.console.client.domain.profiles;
import com.google.gwt.user.client.ui.DisclosurePanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import org.jboss.as.console.client.Console;
import org.jboss.ballroom.client.layout.LHSNavTree;
import org.jboss.as.console.client.shared.model.SubsystemRecord;
import org.jboss.as.console.client.shared.subsys.SubsystemTreeBuilder;
import org.jboss.ballroom.client.widgets.stack.DisclosureStackPanel;
import java.util.ArrayList;
import java.util.List;
/**
* @author Heiko Braun
* @date 2/15/11
*/
class SubsystemSection {
private LHSNavTree subsysTree;
private DisclosurePanel panel;
private ProfileSelector profileSelector;
public SubsystemSection() {
panel = new DisclosureStackPanel(Console.CONSTANTS.common_label_subsystems()).asWidget();
subsysTree = new LHSNavTree("profiles");
VerticalPanel layout = new VerticalPanel();
layout.setStyleName("fill-layout-width");
// ------------
profileSelector = new ProfileSelector();
Widget selectorWidget = profileSelector.asWidget();
- selectorWidget.getElement().setAttribute("style", "padding-left:5px; padding-top:5px; padding-bottom:5px");
layout.add(selectorWidget);
// ------------
layout.add(subsysTree);
panel.setContent(layout);
}
public Widget asWidget()
{
return panel;
}
public void updateSubsystems(List<SubsystemRecord> subsystems) {
subsysTree.removeItems();
SubsystemTreeBuilder.build("domain/profile/", subsysTree, subsystems);
}
public void setProfiles(List<String> profileNames) {
profileSelector.setProfiles(profileNames);
}
}
| true | true | public SubsystemSection() {
panel = new DisclosureStackPanel(Console.CONSTANTS.common_label_subsystems()).asWidget();
subsysTree = new LHSNavTree("profiles");
VerticalPanel layout = new VerticalPanel();
layout.setStyleName("fill-layout-width");
// ------------
profileSelector = new ProfileSelector();
Widget selectorWidget = profileSelector.asWidget();
selectorWidget.getElement().setAttribute("style", "padding-left:5px; padding-top:5px; padding-bottom:5px");
layout.add(selectorWidget);
// ------------
layout.add(subsysTree);
panel.setContent(layout);
}
| public SubsystemSection() {
panel = new DisclosureStackPanel(Console.CONSTANTS.common_label_subsystems()).asWidget();
subsysTree = new LHSNavTree("profiles");
VerticalPanel layout = new VerticalPanel();
layout.setStyleName("fill-layout-width");
// ------------
profileSelector = new ProfileSelector();
Widget selectorWidget = profileSelector.asWidget();
layout.add(selectorWidget);
// ------------
layout.add(subsysTree);
panel.setContent(layout);
}
|
diff --git a/src/com/gsoltis/androidchat/FirebaseListAdapter.java b/src/com/gsoltis/androidchat/FirebaseListAdapter.java
index b7909a0..c02a08f 100644
--- a/src/com/gsoltis/androidchat/FirebaseListAdapter.java
+++ b/src/com/gsoltis/androidchat/FirebaseListAdapter.java
@@ -1,138 +1,139 @@
package com.gsoltis.androidchat;
import android.app.Activity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import com.firebase.client.ChildEventListener;
import com.firebase.client.DataSnapshot;
import com.firebase.client.Query;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* User: greg
* Date: 6/21/13
* Time: 1:47 PM
*/
public abstract class FirebaseListAdapter<T> extends BaseAdapter {
private Query ref;
private Class<T> modelClass;
private int layout;
private LayoutInflater inflater;
private List<T> models;
private Map<String, T> modelNames;
private ChildEventListener listener;
public FirebaseListAdapter(Query ref, Class<T> modelClass, int layout, Activity activity) {
this.ref = ref;
this.modelClass = modelClass;
this.layout = layout;
inflater = activity.getLayoutInflater();
models = new ArrayList<T>();
modelNames = new HashMap<String, T>();
listener = this.ref.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
System.out.println("out: " + System.currentTimeMillis());
long start = System.currentTimeMillis();
T model = dataSnapshot.getValue(FirebaseListAdapter.this.modelClass);
long postParse = System.currentTimeMillis();
models.add(model);
modelNames.put(dataSnapshot.getName(), model);
notifyDataSetChanged();
long end = System.currentTimeMillis();
Log.i("FirebaseListAdapter", "Child added took " + (end - start) + "ms, " + (postParse - start) + "ms parsing, " +
(end - postParse) + "ms notifying"
);
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
String modelName = dataSnapshot.getName();
T oldModel = modelNames.get(modelName);
T newModel = dataSnapshot.getValue(FirebaseListAdapter.this.modelClass);
int index = models.indexOf(oldModel);
models.set(index, newModel);
+ modelNames.put(modelName, newModel);
notifyDataSetChanged();
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
String modelName = dataSnapshot.getName();
T oldModel = modelNames.get(modelName);
models.remove(oldModel);
modelNames.remove(modelName);
notifyDataSetChanged();
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {
String modelName = dataSnapshot.getName();
T oldModel = modelNames.get(modelName);
T newModel = dataSnapshot.getValue(FirebaseListAdapter.this.modelClass);
int index = models.indexOf(oldModel);
models.remove(index);
if (previousChildName == null) {
models.add(0, newModel);
} else {
T previousModel = modelNames.get(previousChildName);
int previousIndex = models.indexOf(previousModel);
int nextIndex = previousIndex + 1;
if (nextIndex == models.size()) {
models.add(newModel);
} else {
models.add(nextIndex, newModel);
}
}
}
@Override
public void onCancelled() {
Log.e("FirebaseListAdapter", "Listen was cancelled, no more updates will occur");
}
});
}
public void cleanup() {
ref.removeEventListener(listener);
}
@Override
public int getCount() {
return models.size();
}
@Override
public Object getItem(int i) {
return models.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (view == null) {
view = inflater.inflate(layout, viewGroup, false);
}
T model = models.get(i);
populateView(view, model);
return view;
}
protected abstract void populateView(View v, T model);
}
| true | true | public FirebaseListAdapter(Query ref, Class<T> modelClass, int layout, Activity activity) {
this.ref = ref;
this.modelClass = modelClass;
this.layout = layout;
inflater = activity.getLayoutInflater();
models = new ArrayList<T>();
modelNames = new HashMap<String, T>();
listener = this.ref.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
System.out.println("out: " + System.currentTimeMillis());
long start = System.currentTimeMillis();
T model = dataSnapshot.getValue(FirebaseListAdapter.this.modelClass);
long postParse = System.currentTimeMillis();
models.add(model);
modelNames.put(dataSnapshot.getName(), model);
notifyDataSetChanged();
long end = System.currentTimeMillis();
Log.i("FirebaseListAdapter", "Child added took " + (end - start) + "ms, " + (postParse - start) + "ms parsing, " +
(end - postParse) + "ms notifying"
);
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
String modelName = dataSnapshot.getName();
T oldModel = modelNames.get(modelName);
T newModel = dataSnapshot.getValue(FirebaseListAdapter.this.modelClass);
int index = models.indexOf(oldModel);
models.set(index, newModel);
notifyDataSetChanged();
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
String modelName = dataSnapshot.getName();
T oldModel = modelNames.get(modelName);
models.remove(oldModel);
modelNames.remove(modelName);
notifyDataSetChanged();
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {
String modelName = dataSnapshot.getName();
T oldModel = modelNames.get(modelName);
T newModel = dataSnapshot.getValue(FirebaseListAdapter.this.modelClass);
int index = models.indexOf(oldModel);
models.remove(index);
if (previousChildName == null) {
models.add(0, newModel);
} else {
T previousModel = modelNames.get(previousChildName);
int previousIndex = models.indexOf(previousModel);
int nextIndex = previousIndex + 1;
if (nextIndex == models.size()) {
models.add(newModel);
} else {
models.add(nextIndex, newModel);
}
}
}
@Override
public void onCancelled() {
Log.e("FirebaseListAdapter", "Listen was cancelled, no more updates will occur");
}
});
}
| public FirebaseListAdapter(Query ref, Class<T> modelClass, int layout, Activity activity) {
this.ref = ref;
this.modelClass = modelClass;
this.layout = layout;
inflater = activity.getLayoutInflater();
models = new ArrayList<T>();
modelNames = new HashMap<String, T>();
listener = this.ref.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
System.out.println("out: " + System.currentTimeMillis());
long start = System.currentTimeMillis();
T model = dataSnapshot.getValue(FirebaseListAdapter.this.modelClass);
long postParse = System.currentTimeMillis();
models.add(model);
modelNames.put(dataSnapshot.getName(), model);
notifyDataSetChanged();
long end = System.currentTimeMillis();
Log.i("FirebaseListAdapter", "Child added took " + (end - start) + "ms, " + (postParse - start) + "ms parsing, " +
(end - postParse) + "ms notifying"
);
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
String modelName = dataSnapshot.getName();
T oldModel = modelNames.get(modelName);
T newModel = dataSnapshot.getValue(FirebaseListAdapter.this.modelClass);
int index = models.indexOf(oldModel);
models.set(index, newModel);
modelNames.put(modelName, newModel);
notifyDataSetChanged();
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
String modelName = dataSnapshot.getName();
T oldModel = modelNames.get(modelName);
models.remove(oldModel);
modelNames.remove(modelName);
notifyDataSetChanged();
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {
String modelName = dataSnapshot.getName();
T oldModel = modelNames.get(modelName);
T newModel = dataSnapshot.getValue(FirebaseListAdapter.this.modelClass);
int index = models.indexOf(oldModel);
models.remove(index);
if (previousChildName == null) {
models.add(0, newModel);
} else {
T previousModel = modelNames.get(previousChildName);
int previousIndex = models.indexOf(previousModel);
int nextIndex = previousIndex + 1;
if (nextIndex == models.size()) {
models.add(newModel);
} else {
models.add(nextIndex, newModel);
}
}
}
@Override
public void onCancelled() {
Log.e("FirebaseListAdapter", "Listen was cancelled, no more updates will occur");
}
});
}
|
diff --git a/src/erki/xpeter/parsers/rss/RssFeed.java b/src/erki/xpeter/parsers/rss/RssFeed.java
index 2027c7a..f4aea8c 100644
--- a/src/erki/xpeter/parsers/rss/RssFeed.java
+++ b/src/erki/xpeter/parsers/rss/RssFeed.java
@@ -1,232 +1,233 @@
/*
* © Copyright 2008–2010 by Edgar Kalkowski <[email protected]>
*
* This file is part of the chatbot xpeter.
*
* The chatbot xpeter 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 erki.xpeter.parsers.rss;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.LinkedList;
import java.util.TreeMap;
import org.gnu.stealthp.rsslib.RSSChannel;
import org.gnu.stealthp.rsslib.RSSException;
import org.gnu.stealthp.rsslib.RSSHandler;
import org.gnu.stealthp.rsslib.RSSItem;
import org.gnu.stealthp.rsslib.RSSParser;
import erki.api.storage.Storage;
import erki.api.util.Log;
import erki.api.util.Observer;
import erki.xpeter.Bot;
import erki.xpeter.msg.Message;
import erki.xpeter.msg.TextMessage;
import erki.xpeter.parsers.Parser;
import erki.xpeter.util.BotApi;
import erki.xpeter.util.Keys;
import erki.xpeter.util.StorageKey;
/**
* Allows the bot to reports news received from rss feeds.
*
* @author Edgar Kalkowski
*/
public class RssFeed implements Parser, Observer<TextMessage> {
private static final StorageKey<TreeMap<String, FeedData>> key = new StorageKey<TreeMap<String, FeedData>>(
Keys.RSS_FEEDS);
private Storage<Keys> storage;
private TreeMap<String, FeedData> feeds;
private UpdateThread updateThread;
@Override
public void init(Bot bot) {
storage = bot.getStorage();
if (storage.contains(key)) {
feeds = storage.get(key);
Log.info("Stored feeds successfully loaded.");
} else {
feeds = new TreeMap<String, FeedData>();
Log.info("No stored feeds found.");
}
updateThread = new UpdateThread(feeds, bot, key, storage);
updateThread.start();
bot.register(TextMessage.class, this);
}
@Override
public void destroy(Bot bot) {
bot.deregister(TextMessage.class, this);
updateThread.kill();
}
@SuppressWarnings("unchecked")
@Override
public void inform(TextMessage msg) {
String text = msg.getText();
String botNick = msg.getBotNick();
if (!BotApi.addresses(text, botNick)) {
return;
}
text = BotApi.trimNick(text, botNick);
String match = "[Nn]euer [fF]eed:? (.*)";
if (text.matches(match)) {
String url = text.replaceAll(match, "$1");
Log.debug("Recognized feed url: “" + url + "”.");
RSSHandler handler = new RSSHandler();
try {
RSSParser.parseXmlFile(new URL(url), handler, false);
RSSChannel channel = handler.getRSSChannel();
LinkedList<RSSItem> items = channel.getItems();
LinkedList<String> knownItems = new LinkedList<String>();
for (RSSItem item : items) {
knownItems.add(item.toString());
}
FeedData feed = new FeedData(channel.getTitle(), channel.getDescription(), url,
knownItems);
feeds.put(url, feed);
storage.add(key, feeds);
msg.respond(new Message("Ok, ist gespeichert."));
} catch (MalformedURLException e) {
Log.error(e);
msg.respond(new Message("Die URL scheint ungültig zu sein. :("));
} catch (RSSException e) {
Log.error(e);
msg.respond(new Message("Ich komm mit dem Feed nicht ganz klar … :("));
}
}
match = "(([wW]elche|[wW]as f(ue|ü)r) [fF]eeds (hast|kennst) "
+ "[dD]u( so)?\\??|[fF]eed-?[dD]etails\\.?\\??!?)";
if (text.matches(match)) {
if (feeds.isEmpty()) {
msg.respond(new Message("Ich kenne leider gar keinen Feed. :("));
} else if (feeds.size() == 1) {
FeedData feed = feeds.get(feeds.keySet().iterator().next());
if (feed.getDescription().equals("")) {
msg
.respond(new Message("Ich kenne nur den einen Feed " + feed.getTitle()
+ "."));
} else {
msg.respond(new Message("Ich kenne nur den einen Feed „" + feed.getTitle()
+ " (" + feed.getDescription() + ")“."));
}
} else {
String response = "Ich kenne die folgenden Feeds: ";
for (String url : feeds.keySet()) {
FeedData feed = feeds.get(url);
if (feed.isVerbose()) {
response += "\n – (mit Details) ";
} else {
response += "\n – (ohne Details) ";
}
if (feed.getDescription().equals("")) {
response += feed.getTitle();
} else {
response += feed.getTitle() + " (" + feed.getDescription() + ")";
}
}
msg.respond(new Message(response));
}
}
match = "[fF]eed-?[Dd]etails (an|on|aus|off):? (.*)";
if (text.matches(match)) {
String mode = text.replaceAll(match, "$1");
String identifier = text.replaceAll(match, "$2");
Log.debug("Recognized feed identifier: “" + identifier + "”.");
LinkedList<String> matches = new LinkedList<String>();
for (String url : feeds.keySet()) {
FeedData feed = feeds.get(url);
if (feed.getTitle().contains(identifier)
|| feed.getDescription().contains(identifier)) {
matches.add(feed.getTitle());
if (mode.equals("an") || mode.equals("on")) {
feed.setVerbose(true);
} else {
feed.setVerbose(false);
}
}
}
if (matches.isEmpty()) {
msg.respond(new Message("Ich konnte leider keinen passenden Feed finden. :("));
} else if (matches.size() == 1) {
msg.respond(new Message("Ok. Ab sofort werden die Details des Feeds „"
+ matches.get(0) + "“ angezeigt."));
storage.add(key, feeds);
} else {
msg.respond(new Message("Ok. Ab sofort werden die Details der Feeds "
+ BotApi.enumerate(matches) + " angezeigt."));
storage.add(key, feeds);
}
}
match = "([Vv]ergiss|[Ll](oe|ö)sche) (den )?[fF]eed:? (.*)";
if (text.matches(match)) {
String identifier = text.replaceAll(match, "$4");
Log.debug("Recognized feed identifier: “" + identifier + "”.");
LinkedList<String> matches = new LinkedList<String>();
+ String[] feedArray = feeds.keySet().toArray(new String[0]);
- for (String url : feeds.keySet()) {
+ for (String url : feedArray) {
FeedData feed = feeds.get(url);
if (feed.getTitle().contains(identifier)
|| feed.getDescription().contains(identifier)) {
matches.add(feed.getTitle());
feeds.remove(url);
}
}
if (matches.isEmpty()) {
msg.respond(new Message("Ich konnte leider keinen passenden Feed finden. :("));
} else if (matches.size() == 1) {
msg.respond(new Message("Ok. Der Feed „" + matches.get(0) + "“ wurde gelöscht."));
storage.add(key, feeds);
} else {
msg.respond(new Message("Ok. Die Feeds " + BotApi.enumerate(matches)
+ " wurden gelöscht."));
storage.add(key, feeds);
}
}
}
}
| false | true | public void inform(TextMessage msg) {
String text = msg.getText();
String botNick = msg.getBotNick();
if (!BotApi.addresses(text, botNick)) {
return;
}
text = BotApi.trimNick(text, botNick);
String match = "[Nn]euer [fF]eed:? (.*)";
if (text.matches(match)) {
String url = text.replaceAll(match, "$1");
Log.debug("Recognized feed url: “" + url + "”.");
RSSHandler handler = new RSSHandler();
try {
RSSParser.parseXmlFile(new URL(url), handler, false);
RSSChannel channel = handler.getRSSChannel();
LinkedList<RSSItem> items = channel.getItems();
LinkedList<String> knownItems = new LinkedList<String>();
for (RSSItem item : items) {
knownItems.add(item.toString());
}
FeedData feed = new FeedData(channel.getTitle(), channel.getDescription(), url,
knownItems);
feeds.put(url, feed);
storage.add(key, feeds);
msg.respond(new Message("Ok, ist gespeichert."));
} catch (MalformedURLException e) {
Log.error(e);
msg.respond(new Message("Die URL scheint ungültig zu sein. :("));
} catch (RSSException e) {
Log.error(e);
msg.respond(new Message("Ich komm mit dem Feed nicht ganz klar … :("));
}
}
match = "(([wW]elche|[wW]as f(ue|ü)r) [fF]eeds (hast|kennst) "
+ "[dD]u( so)?\\??|[fF]eed-?[dD]etails\\.?\\??!?)";
if (text.matches(match)) {
if (feeds.isEmpty()) {
msg.respond(new Message("Ich kenne leider gar keinen Feed. :("));
} else if (feeds.size() == 1) {
FeedData feed = feeds.get(feeds.keySet().iterator().next());
if (feed.getDescription().equals("")) {
msg
.respond(new Message("Ich kenne nur den einen Feed " + feed.getTitle()
+ "."));
} else {
msg.respond(new Message("Ich kenne nur den einen Feed „" + feed.getTitle()
+ " (" + feed.getDescription() + ")“."));
}
} else {
String response = "Ich kenne die folgenden Feeds: ";
for (String url : feeds.keySet()) {
FeedData feed = feeds.get(url);
if (feed.isVerbose()) {
response += "\n – (mit Details) ";
} else {
response += "\n – (ohne Details) ";
}
if (feed.getDescription().equals("")) {
response += feed.getTitle();
} else {
response += feed.getTitle() + " (" + feed.getDescription() + ")";
}
}
msg.respond(new Message(response));
}
}
match = "[fF]eed-?[Dd]etails (an|on|aus|off):? (.*)";
if (text.matches(match)) {
String mode = text.replaceAll(match, "$1");
String identifier = text.replaceAll(match, "$2");
Log.debug("Recognized feed identifier: “" + identifier + "”.");
LinkedList<String> matches = new LinkedList<String>();
for (String url : feeds.keySet()) {
FeedData feed = feeds.get(url);
if (feed.getTitle().contains(identifier)
|| feed.getDescription().contains(identifier)) {
matches.add(feed.getTitle());
if (mode.equals("an") || mode.equals("on")) {
feed.setVerbose(true);
} else {
feed.setVerbose(false);
}
}
}
if (matches.isEmpty()) {
msg.respond(new Message("Ich konnte leider keinen passenden Feed finden. :("));
} else if (matches.size() == 1) {
msg.respond(new Message("Ok. Ab sofort werden die Details des Feeds „"
+ matches.get(0) + "“ angezeigt."));
storage.add(key, feeds);
} else {
msg.respond(new Message("Ok. Ab sofort werden die Details der Feeds "
+ BotApi.enumerate(matches) + " angezeigt."));
storage.add(key, feeds);
}
}
match = "([Vv]ergiss|[Ll](oe|ö)sche) (den )?[fF]eed:? (.*)";
if (text.matches(match)) {
String identifier = text.replaceAll(match, "$4");
Log.debug("Recognized feed identifier: “" + identifier + "”.");
LinkedList<String> matches = new LinkedList<String>();
for (String url : feeds.keySet()) {
FeedData feed = feeds.get(url);
if (feed.getTitle().contains(identifier)
|| feed.getDescription().contains(identifier)) {
matches.add(feed.getTitle());
feeds.remove(url);
}
}
if (matches.isEmpty()) {
msg.respond(new Message("Ich konnte leider keinen passenden Feed finden. :("));
} else if (matches.size() == 1) {
msg.respond(new Message("Ok. Der Feed „" + matches.get(0) + "“ wurde gelöscht."));
storage.add(key, feeds);
} else {
msg.respond(new Message("Ok. Die Feeds " + BotApi.enumerate(matches)
+ " wurden gelöscht."));
storage.add(key, feeds);
}
}
}
| public void inform(TextMessage msg) {
String text = msg.getText();
String botNick = msg.getBotNick();
if (!BotApi.addresses(text, botNick)) {
return;
}
text = BotApi.trimNick(text, botNick);
String match = "[Nn]euer [fF]eed:? (.*)";
if (text.matches(match)) {
String url = text.replaceAll(match, "$1");
Log.debug("Recognized feed url: “" + url + "”.");
RSSHandler handler = new RSSHandler();
try {
RSSParser.parseXmlFile(new URL(url), handler, false);
RSSChannel channel = handler.getRSSChannel();
LinkedList<RSSItem> items = channel.getItems();
LinkedList<String> knownItems = new LinkedList<String>();
for (RSSItem item : items) {
knownItems.add(item.toString());
}
FeedData feed = new FeedData(channel.getTitle(), channel.getDescription(), url,
knownItems);
feeds.put(url, feed);
storage.add(key, feeds);
msg.respond(new Message("Ok, ist gespeichert."));
} catch (MalformedURLException e) {
Log.error(e);
msg.respond(new Message("Die URL scheint ungültig zu sein. :("));
} catch (RSSException e) {
Log.error(e);
msg.respond(new Message("Ich komm mit dem Feed nicht ganz klar … :("));
}
}
match = "(([wW]elche|[wW]as f(ue|ü)r) [fF]eeds (hast|kennst) "
+ "[dD]u( so)?\\??|[fF]eed-?[dD]etails\\.?\\??!?)";
if (text.matches(match)) {
if (feeds.isEmpty()) {
msg.respond(new Message("Ich kenne leider gar keinen Feed. :("));
} else if (feeds.size() == 1) {
FeedData feed = feeds.get(feeds.keySet().iterator().next());
if (feed.getDescription().equals("")) {
msg
.respond(new Message("Ich kenne nur den einen Feed " + feed.getTitle()
+ "."));
} else {
msg.respond(new Message("Ich kenne nur den einen Feed „" + feed.getTitle()
+ " (" + feed.getDescription() + ")“."));
}
} else {
String response = "Ich kenne die folgenden Feeds: ";
for (String url : feeds.keySet()) {
FeedData feed = feeds.get(url);
if (feed.isVerbose()) {
response += "\n – (mit Details) ";
} else {
response += "\n – (ohne Details) ";
}
if (feed.getDescription().equals("")) {
response += feed.getTitle();
} else {
response += feed.getTitle() + " (" + feed.getDescription() + ")";
}
}
msg.respond(new Message(response));
}
}
match = "[fF]eed-?[Dd]etails (an|on|aus|off):? (.*)";
if (text.matches(match)) {
String mode = text.replaceAll(match, "$1");
String identifier = text.replaceAll(match, "$2");
Log.debug("Recognized feed identifier: “" + identifier + "”.");
LinkedList<String> matches = new LinkedList<String>();
for (String url : feeds.keySet()) {
FeedData feed = feeds.get(url);
if (feed.getTitle().contains(identifier)
|| feed.getDescription().contains(identifier)) {
matches.add(feed.getTitle());
if (mode.equals("an") || mode.equals("on")) {
feed.setVerbose(true);
} else {
feed.setVerbose(false);
}
}
}
if (matches.isEmpty()) {
msg.respond(new Message("Ich konnte leider keinen passenden Feed finden. :("));
} else if (matches.size() == 1) {
msg.respond(new Message("Ok. Ab sofort werden die Details des Feeds „"
+ matches.get(0) + "“ angezeigt."));
storage.add(key, feeds);
} else {
msg.respond(new Message("Ok. Ab sofort werden die Details der Feeds "
+ BotApi.enumerate(matches) + " angezeigt."));
storage.add(key, feeds);
}
}
match = "([Vv]ergiss|[Ll](oe|ö)sche) (den )?[fF]eed:? (.*)";
if (text.matches(match)) {
String identifier = text.replaceAll(match, "$4");
Log.debug("Recognized feed identifier: “" + identifier + "”.");
LinkedList<String> matches = new LinkedList<String>();
String[] feedArray = feeds.keySet().toArray(new String[0]);
for (String url : feedArray) {
FeedData feed = feeds.get(url);
if (feed.getTitle().contains(identifier)
|| feed.getDescription().contains(identifier)) {
matches.add(feed.getTitle());
feeds.remove(url);
}
}
if (matches.isEmpty()) {
msg.respond(new Message("Ich konnte leider keinen passenden Feed finden. :("));
} else if (matches.size() == 1) {
msg.respond(new Message("Ok. Der Feed „" + matches.get(0) + "“ wurde gelöscht."));
storage.add(key, feeds);
} else {
msg.respond(new Message("Ok. Die Feeds " + BotApi.enumerate(matches)
+ " wurden gelöscht."));
storage.add(key, feeds);
}
}
}
|
diff --git a/src/net/java/dev/rapt/sam/AsAptProcessor.java b/src/net/java/dev/rapt/sam/AsAptProcessor.java
index 43a64d0..278b17a 100644
--- a/src/net/java/dev/rapt/sam/AsAptProcessor.java
+++ b/src/net/java/dev/rapt/sam/AsAptProcessor.java
@@ -1,275 +1,276 @@
/*
Copyright (c) 2004, Bruce Chapman
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 Rapt Library 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.java.dev.rapt.sam;
import com.sun.mirror.apt.*;
import com.sun.mirror.declaration.*;
import com.sun.mirror.type.*;
import com.sun.mirror.util.*;
import java.io.*;
import java.util.*;
import net.java.dev.rapt.generator.*;
import net.java.dev.rapt.util.*;
class AsAptProcessor implements AnnotationProcessor {
AnnotationProcessorEnvironment env;
AsAptProcessor(AnnotationProcessorEnvironment env) {
this.env = env;
}
public void process() {
Map3List<PackageDeclaration, //target's package
TypeMirror, // @As.value() ClassType or InterfaceType
ClassDeclaration, // target's class
MethodDeclaration> // targets
taggedMethods = new Map3List<PackageDeclaration,TypeMirror,ClassDeclaration, MethodDeclaration>(10);
final AnnotationTypeDeclaration asDecl =
(AnnotationTypeDeclaration)env.getTypeDeclaration(As.class.getName());
for(Declaration d : env.getDeclarationsAnnotatedWith(asDecl)) {
MethodDeclaration md = (MethodDeclaration)d;
// get the Declaration (of class) corresponding to the value of the annotation
As ann = md.getAnnotation(As.class);
TypeMirror asType=null;
try {
ann.value(); // always fails - nominally returns Class<?>
} catch (MirroredTypeException mte) {
asType = mte.getTypeMirror();
}
ClassDeclaration owner = (ClassDeclaration)md.getDeclaringType();
PackageDeclaration pkg = owner.getPackage();
taggedMethods.put(pkg,asType,owner,md);
}
for(PackageDeclaration pkg : taggedMethods.keys()) {
for(TypeMirror asType : taggedMethods.keys(pkg)) {
try {
// open source file for this AsType in package
TypeDeclaration asWhat = asType instanceof ClassType
? ((ClassType)asType).getDeclaration()
: ((InterfaceType)asType).getDeclaration() ;
String fname = pkg.getQualifiedName();
if(fname.length() == 0) {
fname = asWhat.getSimpleName();
} else {
fname = fname + "." + asWhat.getSimpleName();
}
fname += "s";
PrintWriter src = env.getFiler().createSourceFile(fname);
// write package declaration
if(! pkg.getQualifiedName().equals("")) {
src.format("package %s;%n", pkg.getQualifiedName());
}
// write importsAndHeader
src.format(importsAndHeader, asWhat.getSimpleName());
for(ClassDeclaration owner : taggedMethods.keys(pkg,asType)) {
- String finalOwner = owner.toString()+" owner";
+ //String finalOwner = owner.toString()+" owner";
for(NameSpace ns : matchUpMethods(asWhat, taggedMethods.values(pkg,asType,owner))) {
+ String finalOwner = owner.toString()+" owner";
StringBuilder methodSrc = new StringBuilder();
for(MethodPair pair : ns.methods) {
// generate the method eg
// public void run() { owner.doSomething(); }
methodSrc.append(" public ");
methodSrc.append(pair.impl.getReturnType()).append(" ");
methodSrc.append(pair.impl.getSimpleName()).append("(");
boolean first = true;
for(ParameterDeclaration pd : pair.impl.getParameters()) {
if(! first) {
methodSrc.append(", ");
first = false;
}
methodSrc.append(pd.getType()).append(" ").append(pd.getSimpleName());
}
methodSrc.append(") {\n ");
if(! pair.impl.getReturnType().equals(env.getTypeUtils().getVoidType())) {
methodSrc.append("return ");
}
methodSrc.append("owner.");
methodSrc.append(pair.target.getSimpleName()).append('(');
first=true;
boolean anyAdditional= false;
for(ParameterDeclaration pd : pair.target.getParameters()) {
if(! first) {
methodSrc.append(", ");
first = false;
}
if (pd.getAnnotation(As.Additional.class) != null) {
anyAdditional=true;
finalOwner = finalOwner+", final " + pd.getType()+ " "+pd.getSimpleName();
methodSrc.append(pd.getSimpleName());
}
}
if (pair.impl.getParameters().size() != 0 && anyAdditional) methodSrc.append(",");
for(ParameterDeclaration pd : pair.impl.getParameters()) {
if(! first) {
methodSrc.append(", ");
first = false;
}
methodSrc.append(pd.getSimpleName());
}
methodSrc.append(");\n }\n");
}
src.format(methodTemplate,asWhat, ns.name, finalOwner, "", methodSrc);
}
}
src.println("}");
src.close();
} catch (Exception ioe) {
env.getMessager().printError("internal");
ioe.printStackTrace();
}
}
}
}
// %%1 is asType
/**
class %1$ss {
*/
@LongString
private static String importsAndHeader = LongStrings.importsAndHeader();
// %%1 is asType, %%2 is methodname %%3 is owner class
// %%4 is LocalArgumentList, %%5 is method Chainer calls
/**
static final %1$s %2$s(final %3$s) {
return new %1$s() {
%5$s
};
}
*/
@LongString
private static String methodTemplate = LongStrings.methodTemplate();
// %%1 is target method name, %%2 is arg list, %%3 is return type ( empty for void)
/**
%3$s owner.%1$s(%2$s);
*/
@LongString static String methodChainer = LongStrings.methodChainer();
/** a namespace is used to group targetted methods into a single anonymous
object. Each targetted method should have a corresponding method which it implements
, this is determined by matching args and return type, and where those are not unique
by matching the string left when the namespace is removed from the target method name, with part
of the As method names.
*/
static private class NameSpace {
NameSpace(String name) {
this.name = name;
}
String name;
List<MethodPair> methods = new ArrayList<MethodPair>();
}
static private class MethodPair {
MethodPair(MethodDeclaration target) {
this.target = target;
}
MethodDeclaration target;
MethodDeclaration impl;
}
List<NameSpace> matchUpMethods(TypeDeclaration asWhat, Iterable<MethodDeclaration> targets) {
Types typeUtils = env.getTypeUtils();
Collection<? extends MethodDeclaration> implMethods = asWhat.getMethods();
Map<String,NameSpace> namespaces = new HashMap<String,NameSpace>(10);
// sort targets into name spaces
for(MethodDeclaration target : targets) {
// what is the namespace - initially the method name as tho @As(X.class, ns="*" /* default */)
As ann = target.getAnnotation(As.class);
String nsname=ann.ns();
if(nsname.equals("*")) nsname=target.getSimpleName();
if(! namespaces.containsKey(nsname)) namespaces.put(nsname,new NameSpace(nsname));
namespaces.get(nsname).methods.add(new MethodPair(target));
}
List<NameSpace> result = new ArrayList<NameSpace>();
for(NameSpace ns : namespaces.values()) {
// for each target method, find the implMethod
boolean faulty = false;
for(MethodPair pair : ns.methods) { // A sse below
MethodDeclaration tm = pair.target;
int matchCounter = 0;
MethodDeclaration match = null;
String matchNames = "";
try {
implMethods:
for(MethodDeclaration im : implMethods) { // SHOULD invert with A so we can check if
// any abstract im's are not matched.
String remainingName = tm.getSimpleName().replace(ns.name,"");
if(im.getSimpleName().indexOf(remainingName) == -1) continue;
if(! tm.getReturnType().equals(im.getReturnType())) continue;
Collection<ParameterDeclaration> targetParams = tm.getParameters();
Collection<ParameterDeclaration> implParams = im.getParameters();
//count additional params
int numberOfAdditionalParams=0;
for (ParameterDeclaration param: targetParams) {
if (param.getAnnotation(As.Additional.class) != null) numberOfAdditionalParams++;
}
//compare number of params
if( (targetParams.size() - numberOfAdditionalParams) != implParams.size() ) continue;
Iterator<ParameterDeclaration> ips = implParams.iterator();
for(ParameterDeclaration tpd : targetParams) {
if (tpd.getAnnotation(As.Additional.class) == null) {
if( ! ips.next().getType().equals(tpd.getType()) ) continue implMethods;
}
}
// found 1 match
matchCounter++;
match = im;
matchNames += ", " + im.getSimpleName();
}
} catch (Exception ex) {
env.getMessager().printError(tm.getPosition(), ex.toString());
}
// did we just find one?
if(matchCounter == 1) {
pair.impl=match;
} else if(matchCounter == 0) {
env.getMessager().printError(tm.getPosition(), " cannot find matching method in " + asWhat);
} else {
env.getMessager().printError(tm.getPosition(),
"matches several methods (" + matchNames.substring(2) + ") in " + asWhat);
}
faulty |= matchCounter != 1;
}
if(! faulty) result.add(ns);
}
return result;
}
}
| false | true | public void process() {
Map3List<PackageDeclaration, //target's package
TypeMirror, // @As.value() ClassType or InterfaceType
ClassDeclaration, // target's class
MethodDeclaration> // targets
taggedMethods = new Map3List<PackageDeclaration,TypeMirror,ClassDeclaration, MethodDeclaration>(10);
final AnnotationTypeDeclaration asDecl =
(AnnotationTypeDeclaration)env.getTypeDeclaration(As.class.getName());
for(Declaration d : env.getDeclarationsAnnotatedWith(asDecl)) {
MethodDeclaration md = (MethodDeclaration)d;
// get the Declaration (of class) corresponding to the value of the annotation
As ann = md.getAnnotation(As.class);
TypeMirror asType=null;
try {
ann.value(); // always fails - nominally returns Class<?>
} catch (MirroredTypeException mte) {
asType = mte.getTypeMirror();
}
ClassDeclaration owner = (ClassDeclaration)md.getDeclaringType();
PackageDeclaration pkg = owner.getPackage();
taggedMethods.put(pkg,asType,owner,md);
}
for(PackageDeclaration pkg : taggedMethods.keys()) {
for(TypeMirror asType : taggedMethods.keys(pkg)) {
try {
// open source file for this AsType in package
TypeDeclaration asWhat = asType instanceof ClassType
? ((ClassType)asType).getDeclaration()
: ((InterfaceType)asType).getDeclaration() ;
String fname = pkg.getQualifiedName();
if(fname.length() == 0) {
fname = asWhat.getSimpleName();
} else {
fname = fname + "." + asWhat.getSimpleName();
}
fname += "s";
PrintWriter src = env.getFiler().createSourceFile(fname);
// write package declaration
if(! pkg.getQualifiedName().equals("")) {
src.format("package %s;%n", pkg.getQualifiedName());
}
// write importsAndHeader
src.format(importsAndHeader, asWhat.getSimpleName());
for(ClassDeclaration owner : taggedMethods.keys(pkg,asType)) {
String finalOwner = owner.toString()+" owner";
for(NameSpace ns : matchUpMethods(asWhat, taggedMethods.values(pkg,asType,owner))) {
StringBuilder methodSrc = new StringBuilder();
for(MethodPair pair : ns.methods) {
// generate the method eg
// public void run() { owner.doSomething(); }
methodSrc.append(" public ");
methodSrc.append(pair.impl.getReturnType()).append(" ");
methodSrc.append(pair.impl.getSimpleName()).append("(");
boolean first = true;
for(ParameterDeclaration pd : pair.impl.getParameters()) {
if(! first) {
methodSrc.append(", ");
first = false;
}
methodSrc.append(pd.getType()).append(" ").append(pd.getSimpleName());
}
methodSrc.append(") {\n ");
if(! pair.impl.getReturnType().equals(env.getTypeUtils().getVoidType())) {
methodSrc.append("return ");
}
methodSrc.append("owner.");
methodSrc.append(pair.target.getSimpleName()).append('(');
first=true;
boolean anyAdditional= false;
for(ParameterDeclaration pd : pair.target.getParameters()) {
if(! first) {
methodSrc.append(", ");
first = false;
}
if (pd.getAnnotation(As.Additional.class) != null) {
anyAdditional=true;
finalOwner = finalOwner+", final " + pd.getType()+ " "+pd.getSimpleName();
methodSrc.append(pd.getSimpleName());
}
}
if (pair.impl.getParameters().size() != 0 && anyAdditional) methodSrc.append(",");
for(ParameterDeclaration pd : pair.impl.getParameters()) {
if(! first) {
methodSrc.append(", ");
first = false;
}
methodSrc.append(pd.getSimpleName());
}
methodSrc.append(");\n }\n");
}
src.format(methodTemplate,asWhat, ns.name, finalOwner, "", methodSrc);
}
}
src.println("}");
src.close();
} catch (Exception ioe) {
env.getMessager().printError("internal");
ioe.printStackTrace();
}
}
}
}
| public void process() {
Map3List<PackageDeclaration, //target's package
TypeMirror, // @As.value() ClassType or InterfaceType
ClassDeclaration, // target's class
MethodDeclaration> // targets
taggedMethods = new Map3List<PackageDeclaration,TypeMirror,ClassDeclaration, MethodDeclaration>(10);
final AnnotationTypeDeclaration asDecl =
(AnnotationTypeDeclaration)env.getTypeDeclaration(As.class.getName());
for(Declaration d : env.getDeclarationsAnnotatedWith(asDecl)) {
MethodDeclaration md = (MethodDeclaration)d;
// get the Declaration (of class) corresponding to the value of the annotation
As ann = md.getAnnotation(As.class);
TypeMirror asType=null;
try {
ann.value(); // always fails - nominally returns Class<?>
} catch (MirroredTypeException mte) {
asType = mte.getTypeMirror();
}
ClassDeclaration owner = (ClassDeclaration)md.getDeclaringType();
PackageDeclaration pkg = owner.getPackage();
taggedMethods.put(pkg,asType,owner,md);
}
for(PackageDeclaration pkg : taggedMethods.keys()) {
for(TypeMirror asType : taggedMethods.keys(pkg)) {
try {
// open source file for this AsType in package
TypeDeclaration asWhat = asType instanceof ClassType
? ((ClassType)asType).getDeclaration()
: ((InterfaceType)asType).getDeclaration() ;
String fname = pkg.getQualifiedName();
if(fname.length() == 0) {
fname = asWhat.getSimpleName();
} else {
fname = fname + "." + asWhat.getSimpleName();
}
fname += "s";
PrintWriter src = env.getFiler().createSourceFile(fname);
// write package declaration
if(! pkg.getQualifiedName().equals("")) {
src.format("package %s;%n", pkg.getQualifiedName());
}
// write importsAndHeader
src.format(importsAndHeader, asWhat.getSimpleName());
for(ClassDeclaration owner : taggedMethods.keys(pkg,asType)) {
//String finalOwner = owner.toString()+" owner";
for(NameSpace ns : matchUpMethods(asWhat, taggedMethods.values(pkg,asType,owner))) {
String finalOwner = owner.toString()+" owner";
StringBuilder methodSrc = new StringBuilder();
for(MethodPair pair : ns.methods) {
// generate the method eg
// public void run() { owner.doSomething(); }
methodSrc.append(" public ");
methodSrc.append(pair.impl.getReturnType()).append(" ");
methodSrc.append(pair.impl.getSimpleName()).append("(");
boolean first = true;
for(ParameterDeclaration pd : pair.impl.getParameters()) {
if(! first) {
methodSrc.append(", ");
first = false;
}
methodSrc.append(pd.getType()).append(" ").append(pd.getSimpleName());
}
methodSrc.append(") {\n ");
if(! pair.impl.getReturnType().equals(env.getTypeUtils().getVoidType())) {
methodSrc.append("return ");
}
methodSrc.append("owner.");
methodSrc.append(pair.target.getSimpleName()).append('(');
first=true;
boolean anyAdditional= false;
for(ParameterDeclaration pd : pair.target.getParameters()) {
if(! first) {
methodSrc.append(", ");
first = false;
}
if (pd.getAnnotation(As.Additional.class) != null) {
anyAdditional=true;
finalOwner = finalOwner+", final " + pd.getType()+ " "+pd.getSimpleName();
methodSrc.append(pd.getSimpleName());
}
}
if (pair.impl.getParameters().size() != 0 && anyAdditional) methodSrc.append(",");
for(ParameterDeclaration pd : pair.impl.getParameters()) {
if(! first) {
methodSrc.append(", ");
first = false;
}
methodSrc.append(pd.getSimpleName());
}
methodSrc.append(");\n }\n");
}
src.format(methodTemplate,asWhat, ns.name, finalOwner, "", methodSrc);
}
}
src.println("}");
src.close();
} catch (Exception ioe) {
env.getMessager().printError("internal");
ioe.printStackTrace();
}
}
}
}
|
diff --git a/TitoCC/src/titocc/compiler/elements/BinaryExpression.java b/TitoCC/src/titocc/compiler/elements/BinaryExpression.java
index 1f87002..f99985e 100644
--- a/TitoCC/src/titocc/compiler/elements/BinaryExpression.java
+++ b/TitoCC/src/titocc/compiler/elements/BinaryExpression.java
@@ -1,374 +1,374 @@
package titocc.compiler.elements;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import titocc.compiler.Assembler;
import titocc.compiler.Registers;
import titocc.compiler.Scope;
import titocc.compiler.types.CType;
import titocc.compiler.types.IntType;
import titocc.compiler.types.VoidType;
import titocc.tokenizer.SyntaxException;
import titocc.tokenizer.TokenStream;
import titocc.util.Position;
/**
* Expression formed by a binary operator and two operands.
*
* <p> EBNF Definition:
*
* <br> BINARY_EXPRESSION = [BINARY_EXPRESSION "||"] BINARY_EXPRESSION2
*
* <br> BINARY_EXPRESSION2 = [BINARY_EXPRESSION2 "&&"] BINARY_EXPRESSION3
*
* <br> BINARY_EXPRESSION3 = [BINARY_EXPRESSION3 "|"] BINARY_EXPRESSION4
*
* <br> BINARY_EXPRESSION4 = [BINARY_EXPRESSION4 "^"] BINARY_EXPRESSION5
*
* <br> BINARY_EXPRESSION5 = [BINARY_EXPRESSION5 "&"] BINARY_EXPRESSION6
*
* <br> BINARY_EXPRESSION6 = [BINARY_EXPRESSION6 "=="] BINARY_EXPRESSION7
*
* <br> BINARY_EXPRESSION7 = [BINARY_EXPRESSION7 "!=") BINARY_EXPRESSION8
*
* <br> BINARY_EXPRESSION8 = [BINARY_EXPRESSION8 ("<" | "<=" | ">" | ">=")] BINARY_EXPRESSION9
*
* <br> BINARY_EXPRESSION9 = [BINARY_EXPRESSION9 ("<<" | ">>")] BINARY_EXPRESSION10
*
* <br> BINARY_EXPRESSION10 = [BINARY_EXPRESSION10 ("+" | "-")] BINARY_EXPRESSION11
*
* <br> BINARY_EXPRESSION11 = [BINARY_EXPRESSION11 ("*" | "/" | "%")] PREFIX_EXPRESSION
*/
public class BinaryExpression extends Expression
{
private enum Type
{
BITWISE, ARITHMETIC, EQUALITY, RELATIONAL, LOGICAL
};
/**
* Binary operator with mnemonic and operation type.
*/
private static class Operator
{
public String mnemonic;
public Type type;
int priority;
public Operator(String mnemonic, Type type, int priority)
{
this.mnemonic = mnemonic;
this.type = type;
this.priority = priority;
}
}
/**
* Binary operators, their main instructions and priorities.
*/
static final Map<String, Operator> binaryOperators = new HashMap<String, Operator>()
{
{
put("||", new Operator("jnzer", Type.LOGICAL, 1));
put("&&", new Operator("jzer", Type.LOGICAL, 2));
put("|", new Operator("or", Type.BITWISE, 3));
put("^", new Operator("xor", Type.BITWISE, 4));
put("&", new Operator("and", Type.BITWISE, 5));
put("==", new Operator("jequ", Type.EQUALITY, 6));
put("!=", new Operator("jnequ", Type.EQUALITY, 7));
put("<", new Operator("jles", Type.RELATIONAL, 8));
put("<=", new Operator("jngre", Type.RELATIONAL, 8));
put(">", new Operator("jgre", Type.RELATIONAL, 8));
put(">=", new Operator("jnles", Type.RELATIONAL, 8));
put("<<", new Operator("shl", Type.BITWISE, 9));
put(">>", new Operator("shr", Type.BITWISE, 9));
put("+", new Operator("add", Type.ARITHMETIC, 10));
put("-", new Operator("sub", Type.ARITHMETIC, 10));
put("*", new Operator("mul", Type.ARITHMETIC, 11));
put("/", new Operator("div", Type.ARITHMETIC, 11));
put("%", new Operator("mod", Type.ARITHMETIC, 11));
}
};
/**
* Binary operator as a string.
*/
private final String operator;
/**
* Left hand side expression;
*/
private final Expression left;
/**
* Right hand side expression.
*/
private final Expression right;
/**
* Constructs a BinaryExpression.
*
* @param operator operator as string
* @param left left operand
* @param right right operand
* @param position starting position of the binary expression
*/
public BinaryExpression(String operator, Expression left, Expression right,
Position position)
{
super(position);
this.operator = operator;
this.left = left;
this.right = right;
}
/**
* Returns the operator.
*
* @return the operator
*/
public String getOperator()
{
return operator;
}
/**
* Returns the left operand.
*
* @return the left operand
*/
public Expression getLeft()
{
return left;
}
/**
* Returns the right operand
*
* @return the right operand
*/
public Expression getRight()
{
return right;
}
@Override
public void compile(Assembler asm, Scope scope, Registers regs)
throws IOException, SyntaxException
{
checkTypes(scope);
// Evaluate LHS; load value to 1st register.
left.compile(asm, scope, regs);
// Allocate a second register for right operand.
regs.allocate(asm);
// Compile right expression and the operator.
Type opType = binaryOperators.get(operator).type;
if (opType == Type.BITWISE || opType == Type.ARITHMETIC)
compileSimpleOperator(asm, scope, regs);
else if (opType == Type.LOGICAL)
compileLogicalOperator(asm, scope, regs);
else if (opType == Type.RELATIONAL || opType == Type.EQUALITY)
compileComparisonOperator(asm, scope, regs);
// Deallocate the second register.
regs.deallocate(asm);
}
private void compileRight(Assembler asm, Scope scope, Registers regs)
throws SyntaxException, IOException
{
// Evaluate RHS; load to second register;
regs.removeFirst();
right.compile(asm, scope, regs);
regs.addFirst();
}
private void compileSimpleOperator(Assembler asm, Scope scope, Registers regs)
throws IOException, SyntaxException
{
int leftIncrSize = left.getType(scope).decay().getIncrementSize();
int rightIncrSize = right.getType(scope).decay().getIncrementSize();
if (leftIncrSize > 1 && rightIncrSize > 1) {
// POINTER - POINTER.
compileRight(asm, scope, regs);
asm.emit(binaryOperators.get(operator).mnemonic, regs.get(0).toString(),
regs.get(1).toString());
asm.emit("div", regs.get(0).toString(), "=" + leftIncrSize);
} else if (leftIncrSize > 1) {
// POINTER + INTEGER or POINTER - INTEGER.
compileRight(asm, scope, regs);
asm.emit("mul", regs.get(1).toString(), "=" + leftIncrSize);
asm.emit(binaryOperators.get(operator).mnemonic, regs.get(0).toString(),
regs.get(1).toString());
} else if (rightIncrSize > 1) {
// INTEGER + POINTER.
asm.emit("mul", regs.get(0).toString(), "=" + rightIncrSize);
compileRight(asm, scope, regs);
asm.emit(binaryOperators.get(operator).mnemonic, regs.get(0).toString(),
regs.get(1).toString());
} else {
compileRight(asm, scope, regs);
asm.emit(binaryOperators.get(operator).mnemonic, regs.get(0).toString(),
regs.get(1).toString());
}
}
private void compileComparisonOperator(Assembler asm, Scope scope, Registers regs)
throws IOException, SyntaxException
{
compileRight(asm, scope, regs);
String jumpLabel = scope.makeGloballyUniqueName("lbl");
asm.emit("comp", regs.get(0).toString(), regs.get(1).toString());
asm.emit("load", regs.get(0).toString(), "=1");
asm.emit(binaryOperators.get(operator).mnemonic, regs.get(0).toString(), jumpLabel);
asm.emit("load", regs.get(0).toString(), "=0");
asm.addLabel(jumpLabel);
}
private void compileLogicalOperator(Assembler asm, Scope scope, Registers regs)
throws IOException, SyntaxException
{
// Short circuit evaluation; only evaluate RHS if necessary.
String jumpLabel = scope.makeGloballyUniqueName("lbl");
String jumpLabel2 = scope.makeGloballyUniqueName("lbl");
asm.emit(binaryOperators.get(operator).mnemonic, regs.get(0).toString(), jumpLabel);
compileRight(asm, scope, regs);
asm.emit(binaryOperators.get(operator).mnemonic, regs.get(1).toString(), jumpLabel);
asm.emit("load", regs.get(0).toString(), operator.equals("||") ? "=0" : "=1");
asm.emit("jump", regs.get(0).toString(), jumpLabel2);
asm.addLabel(jumpLabel);
asm.emit("load", regs.get(0).toString(), operator.equals("||") ? "=1" : "=0");
asm.addLabel(jumpLabel2);
}
@Override
public Integer getCompileTimeValue()
{
// Compile time evaluation of binary operators could be implemented here.
return null;
}
@Override
public CType getType(Scope scope) throws SyntaxException
{
return checkTypes(scope);
}
@Override
public String toString()
{
return "(BIN_EXPR " + operator + " " + left + " " + right + ")";
}
private CType checkTypes(Scope scope) throws SyntaxException
{
Operator op = binaryOperators.get(operator);
CType leftType = left.getType(scope).decay();
CType rightType = right.getType(scope).decay();
CType leftDeref = leftType.dereference();
CType rightDeref = rightType.dereference();
if (op.type == Type.LOGICAL) {
if (leftType.isScalar() && rightType.isScalar())
return new IntType();
} else if (op.type == Type.EQUALITY) {
if (leftType.isArithmetic() && rightType.isArithmetic())
return new IntType();
if (leftDeref.equals(rightDeref))
return new IntType();
if (leftDeref instanceof VoidType && (rightDeref.isObject()
|| rightDeref.isIncomplete()))
return new IntType();
if (rightDeref instanceof VoidType && (leftDeref.isObject()
|| leftDeref.isIncomplete()))
return new IntType();
if (leftType.isPointer() && rightType.isInteger()
&& new Integer(0).equals(right.getCompileTimeValue()))
return new IntType();
if (rightType.isPointer() && leftType.isInteger()
&& new Integer(0).equals(left.getCompileTimeValue()))
return new IntType();
} else if (op.type == Type.RELATIONAL) {
- if (leftType.isArithmetic() && rightType.isArithmetic())
+ if (leftType.isArithmetic() && rightType.isArithmetic()) //TODO arithmetic->real
return new IntType();
- if (leftDeref.equals(rightDeref))
+ if (leftDeref.equals(rightDeref) && (leftDeref.isObject() || leftDeref.isIncomplete()))
return new IntType();
} else if (operator.equals("+")) {
if (leftType.isArithmetic() && rightType.isArithmetic())
return new IntType();
if (leftDeref.isObject() && rightType.isInteger())
return leftType;
if (leftType.isInteger() && rightDeref.isObject())
return rightType;
} else if (operator.equals("-")) {
if (leftType.isArithmetic() && rightType.isArithmetic())
return new IntType();
if (leftDeref.isObject() && rightType.isInteger())
return leftType;
if (leftDeref.isObject() && rightDeref.equals(leftDeref))
return new IntType();
} else if (op.type == Type.BITWISE) {
if (leftType.isInteger() && rightType.isInteger())
return new IntType();
} else if (op.type == Type.ARITHMETIC) {
if (leftType.isArithmetic() && (rightType.isInteger()
|| (!operator.equals("%") && rightType.isArithmetic())))
return new IntType();
}
throw new SyntaxException("Incompatible operands for operator " + operator + ".",
getPosition());
}
/**
* Attempts to parse a syntactic binary expression from token stream. If parsing fails the
* stream is reset to its initial position.
*
* @param tokens source token stream
* @return Expression object or null if tokens don't form a valid expression
*/
public static Expression parse(TokenStream tokens)
{
return parseImpl(tokens, 0);
}
/**
* Recursive implementation of the parsing method. Each call parses one
* priority level of binary operators.
*/
private static Expression parseImpl(TokenStream tokens, int priority)
{
if (priority == 12)
return PrefixExpression.parse(tokens);
Position pos = tokens.getPosition();
tokens.pushMark();
Expression expr = parseImpl(tokens, priority + 1);
if (expr != null) {
while (true) {
tokens.pushMark();
Expression right = null;
String op = tokens.read().toString();
if (binaryOperators.containsKey(op) && binaryOperators.get(op).priority == priority)
right = parseImpl(tokens, priority + 1);
tokens.popMark(right == null);
if (right != null)
expr = new BinaryExpression(op, expr, right, pos);
else
break;
}
}
tokens.popMark(expr == null);
return expr;
}
}
| false | true | private CType checkTypes(Scope scope) throws SyntaxException
{
Operator op = binaryOperators.get(operator);
CType leftType = left.getType(scope).decay();
CType rightType = right.getType(scope).decay();
CType leftDeref = leftType.dereference();
CType rightDeref = rightType.dereference();
if (op.type == Type.LOGICAL) {
if (leftType.isScalar() && rightType.isScalar())
return new IntType();
} else if (op.type == Type.EQUALITY) {
if (leftType.isArithmetic() && rightType.isArithmetic())
return new IntType();
if (leftDeref.equals(rightDeref))
return new IntType();
if (leftDeref instanceof VoidType && (rightDeref.isObject()
|| rightDeref.isIncomplete()))
return new IntType();
if (rightDeref instanceof VoidType && (leftDeref.isObject()
|| leftDeref.isIncomplete()))
return new IntType();
if (leftType.isPointer() && rightType.isInteger()
&& new Integer(0).equals(right.getCompileTimeValue()))
return new IntType();
if (rightType.isPointer() && leftType.isInteger()
&& new Integer(0).equals(left.getCompileTimeValue()))
return new IntType();
} else if (op.type == Type.RELATIONAL) {
if (leftType.isArithmetic() && rightType.isArithmetic())
return new IntType();
if (leftDeref.equals(rightDeref))
return new IntType();
} else if (operator.equals("+")) {
if (leftType.isArithmetic() && rightType.isArithmetic())
return new IntType();
if (leftDeref.isObject() && rightType.isInteger())
return leftType;
if (leftType.isInteger() && rightDeref.isObject())
return rightType;
} else if (operator.equals("-")) {
if (leftType.isArithmetic() && rightType.isArithmetic())
return new IntType();
if (leftDeref.isObject() && rightType.isInteger())
return leftType;
if (leftDeref.isObject() && rightDeref.equals(leftDeref))
return new IntType();
} else if (op.type == Type.BITWISE) {
if (leftType.isInteger() && rightType.isInteger())
return new IntType();
} else if (op.type == Type.ARITHMETIC) {
if (leftType.isArithmetic() && (rightType.isInteger()
|| (!operator.equals("%") && rightType.isArithmetic())))
return new IntType();
}
throw new SyntaxException("Incompatible operands for operator " + operator + ".",
getPosition());
}
| private CType checkTypes(Scope scope) throws SyntaxException
{
Operator op = binaryOperators.get(operator);
CType leftType = left.getType(scope).decay();
CType rightType = right.getType(scope).decay();
CType leftDeref = leftType.dereference();
CType rightDeref = rightType.dereference();
if (op.type == Type.LOGICAL) {
if (leftType.isScalar() && rightType.isScalar())
return new IntType();
} else if (op.type == Type.EQUALITY) {
if (leftType.isArithmetic() && rightType.isArithmetic())
return new IntType();
if (leftDeref.equals(rightDeref))
return new IntType();
if (leftDeref instanceof VoidType && (rightDeref.isObject()
|| rightDeref.isIncomplete()))
return new IntType();
if (rightDeref instanceof VoidType && (leftDeref.isObject()
|| leftDeref.isIncomplete()))
return new IntType();
if (leftType.isPointer() && rightType.isInteger()
&& new Integer(0).equals(right.getCompileTimeValue()))
return new IntType();
if (rightType.isPointer() && leftType.isInteger()
&& new Integer(0).equals(left.getCompileTimeValue()))
return new IntType();
} else if (op.type == Type.RELATIONAL) {
if (leftType.isArithmetic() && rightType.isArithmetic()) //TODO arithmetic->real
return new IntType();
if (leftDeref.equals(rightDeref) && (leftDeref.isObject() || leftDeref.isIncomplete()))
return new IntType();
} else if (operator.equals("+")) {
if (leftType.isArithmetic() && rightType.isArithmetic())
return new IntType();
if (leftDeref.isObject() && rightType.isInteger())
return leftType;
if (leftType.isInteger() && rightDeref.isObject())
return rightType;
} else if (operator.equals("-")) {
if (leftType.isArithmetic() && rightType.isArithmetic())
return new IntType();
if (leftDeref.isObject() && rightType.isInteger())
return leftType;
if (leftDeref.isObject() && rightDeref.equals(leftDeref))
return new IntType();
} else if (op.type == Type.BITWISE) {
if (leftType.isInteger() && rightType.isInteger())
return new IntType();
} else if (op.type == Type.ARITHMETIC) {
if (leftType.isArithmetic() && (rightType.isInteger()
|| (!operator.equals("%") && rightType.isArithmetic())))
return new IntType();
}
throw new SyntaxException("Incompatible operands for operator " + operator + ".",
getPosition());
}
|
diff --git a/bennu-core/src/myorg/_development/MultiProperty.java b/bennu-core/src/myorg/_development/MultiProperty.java
index 4def491e..f1f66c1e 100644
--- a/bennu-core/src/myorg/_development/MultiProperty.java
+++ b/bennu-core/src/myorg/_development/MultiProperty.java
@@ -1,29 +1,31 @@
package myorg._development;
import java.util.Properties;
public class MultiProperty extends Properties {
@Override
public synchronized Object put(final Object key, final Object value) {
final StringBuilder result = new StringBuilder();
final String property = getProperty((String) key);
addValues(result, property);
addValues(result, (String) value);
return super.put(key, result.toString());
}
private void addValues(final StringBuilder result, final String value) {
if (value != null && !value.isEmpty()) {
final String[] properties = value.split(",");
for (final String property : properties) {
final String trimmed = property.trim();
if (result.indexOf(trimmed) < 0) {
- result.append(",");
+ if (result.length() > 0) {
+ result.append(",");
+ }
result.append(trimmed);
}
}
}
}
}
| true | true | private void addValues(final StringBuilder result, final String value) {
if (value != null && !value.isEmpty()) {
final String[] properties = value.split(",");
for (final String property : properties) {
final String trimmed = property.trim();
if (result.indexOf(trimmed) < 0) {
result.append(",");
result.append(trimmed);
}
}
}
}
| private void addValues(final StringBuilder result, final String value) {
if (value != null && !value.isEmpty()) {
final String[] properties = value.split(",");
for (final String property : properties) {
final String trimmed = property.trim();
if (result.indexOf(trimmed) < 0) {
if (result.length() > 0) {
result.append(",");
}
result.append(trimmed);
}
}
}
}
|
diff --git a/gitools-core/src/main/java/org/gitools/core/heatmap/drawer/header/HeatmapColoredLabelsDrawer.java b/gitools-core/src/main/java/org/gitools/core/heatmap/drawer/header/HeatmapColoredLabelsDrawer.java
index a0d13f3b..d5877a6d 100644
--- a/gitools-core/src/main/java/org/gitools/core/heatmap/drawer/header/HeatmapColoredLabelsDrawer.java
+++ b/gitools-core/src/main/java/org/gitools/core/heatmap/drawer/header/HeatmapColoredLabelsDrawer.java
@@ -1,146 +1,147 @@
/*
* #%L
* gitools-core
* %%
* Copyright (C) 2013 Universitat Pompeu Fabra - Biomedical Genomics group
* %%
* 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/gpl-3.0.html>.
* #L%
*/
package org.gitools.core.heatmap.drawer.header;
import org.gitools.core.heatmap.Heatmap;
import org.gitools.core.heatmap.HeatmapDimension;
import org.gitools.core.heatmap.drawer.AbstractHeatmapHeaderDrawer;
import org.gitools.core.heatmap.header.ColoredLabel;
import org.gitools.core.heatmap.header.HeatmapColoredLabelsHeader;
import org.gitools.core.heatmap.header.HeatmapHeader;
import org.gitools.core.model.decorator.Decoration;
import org.jetbrains.annotations.NotNull;
import java.awt.*;
import java.awt.geom.AffineTransform;
public class HeatmapColoredLabelsDrawer extends AbstractHeatmapHeaderDrawer<HeatmapColoredLabelsHeader> {
private static final double radianAngle90 = (90.0 / 180.0) * Math.PI;
public HeatmapColoredLabelsDrawer(Heatmap heatmap, HeatmapDimension heatmapDimension, HeatmapColoredLabelsHeader header) {
super(heatmap, heatmapDimension, header);
}
public void draw(Graphics2D g, Rectangle box, Rectangle clip) {
prepareDraw(g, box);
Font previousFont = rotateFont(g);
HeatmapColoredLabelsHeader header = getHeader();
int firstIndex = firstVisibleIndex(box, clip);
int lastIndex = lastVisibleIndex(box, clip);
Decoration decoration = new Decoration();
int cellWidth = header.getSize();
int startGroupIndex = firstIndex;
int endGroupIndex = firstIndex;
while (startGroupIndex < lastIndex) {
ColoredLabel groupLabel = header.getColoredLabel(startGroupIndex);
while (endGroupIndex + 1 < lastIndex && groupLabel.equals(header.getColoredLabel(endGroupIndex + 1))) {
endGroupIndex++;
}
+ decoration.reset();
header.decorate(decoration, groupLabel);
int fullSize = getHeatmapDimension().getCellSize() + getHeatmapDimension().getGridSize();
paintCell(
decoration,
getHeatmapDimension().getGridColor(),
getHeatmapDimension().getGridSize(),
- 0, startGroupIndex*fullSize,
+ 0, startGroupIndex * fullSize,
cellWidth,
(fullSize * (endGroupIndex - startGroupIndex + 1)) - getHeatmapDimension().getGridSize(),
g,
box
);
startGroupIndex = endGroupIndex + 1;
}
g.setFont(previousFont);
}
private Font rotateFont(Graphics2D g) {
Font previousFont = g.getFont();
Font headerFont = getHeader().getLabelFont();
g.setFont(headerFont);
AffineTransform fontAT = new AffineTransform();
fontAT.rotate(radianAngle90);
g.setFont(getHeader().getLabelFont().deriveFont(fontAT));
return previousFont;
}
@Override
public void drawHeaderLegend(@NotNull Graphics2D g, @NotNull Rectangle rect, @NotNull HeatmapHeader oppositeHeatmapHeader) {
/*TODO
int gridSize;
int height;
int width;
int margin;
int oppositeMargin;
int y = isHorizontal() ? rect.y : rect.y + rect.height;
int x = rect.x;
String[] annValues = oppositeHeatmapHeader.getAnnotationValues(isHorizontal());
ColoredLabel[] clusters = getHeader().getClusters();
gridSize = 1;
oppositeMargin = oppositeHeatmapHeader.getMargin();
margin = getHeader().getMargin();
height = (oppositeHeatmapHeader.getSize() - oppositeMargin - gridSize * annValues.length) / annValues.length;
width = getHeader().getSize() - margin;
for (String v : annValues) {
for (ColoredLabel cl : clusters) {
if (cl.getValue().equals(v)) {
// paint
g.setColor(cl.getColor());
if (isHorizontal()) {
g.fillRect(x + oppositeMargin, y, height, width);
x += gridSize + height;
} else {
y -= height;
g.fillRect(x, y - oppositeMargin, width, height);
y -= gridSize;
}
}
}
}
*/
}
}
| false | true | public void draw(Graphics2D g, Rectangle box, Rectangle clip) {
prepareDraw(g, box);
Font previousFont = rotateFont(g);
HeatmapColoredLabelsHeader header = getHeader();
int firstIndex = firstVisibleIndex(box, clip);
int lastIndex = lastVisibleIndex(box, clip);
Decoration decoration = new Decoration();
int cellWidth = header.getSize();
int startGroupIndex = firstIndex;
int endGroupIndex = firstIndex;
while (startGroupIndex < lastIndex) {
ColoredLabel groupLabel = header.getColoredLabel(startGroupIndex);
while (endGroupIndex + 1 < lastIndex && groupLabel.equals(header.getColoredLabel(endGroupIndex + 1))) {
endGroupIndex++;
}
header.decorate(decoration, groupLabel);
int fullSize = getHeatmapDimension().getCellSize() + getHeatmapDimension().getGridSize();
paintCell(
decoration,
getHeatmapDimension().getGridColor(),
getHeatmapDimension().getGridSize(),
0, startGroupIndex*fullSize,
cellWidth,
(fullSize * (endGroupIndex - startGroupIndex + 1)) - getHeatmapDimension().getGridSize(),
g,
box
);
startGroupIndex = endGroupIndex + 1;
}
g.setFont(previousFont);
}
| public void draw(Graphics2D g, Rectangle box, Rectangle clip) {
prepareDraw(g, box);
Font previousFont = rotateFont(g);
HeatmapColoredLabelsHeader header = getHeader();
int firstIndex = firstVisibleIndex(box, clip);
int lastIndex = lastVisibleIndex(box, clip);
Decoration decoration = new Decoration();
int cellWidth = header.getSize();
int startGroupIndex = firstIndex;
int endGroupIndex = firstIndex;
while (startGroupIndex < lastIndex) {
ColoredLabel groupLabel = header.getColoredLabel(startGroupIndex);
while (endGroupIndex + 1 < lastIndex && groupLabel.equals(header.getColoredLabel(endGroupIndex + 1))) {
endGroupIndex++;
}
decoration.reset();
header.decorate(decoration, groupLabel);
int fullSize = getHeatmapDimension().getCellSize() + getHeatmapDimension().getGridSize();
paintCell(
decoration,
getHeatmapDimension().getGridColor(),
getHeatmapDimension().getGridSize(),
0, startGroupIndex * fullSize,
cellWidth,
(fullSize * (endGroupIndex - startGroupIndex + 1)) - getHeatmapDimension().getGridSize(),
g,
box
);
startGroupIndex = endGroupIndex + 1;
}
g.setFont(previousFont);
}
|
diff --git a/src/com/itmill/toolkit/tests/TestBench.java b/src/com/itmill/toolkit/tests/TestBench.java
index 963c31488..52c041422 100644
--- a/src/com/itmill/toolkit/tests/TestBench.java
+++ b/src/com/itmill/toolkit/tests/TestBench.java
@@ -1,240 +1,240 @@
/*
@ITMillApache2LicenseForJavaFiles@
*/
package com.itmill.toolkit.tests;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import com.itmill.toolkit.Application;
import com.itmill.toolkit.data.Property;
import com.itmill.toolkit.data.util.HierarchicalContainer;
import com.itmill.toolkit.ui.Component;
import com.itmill.toolkit.ui.CustomComponent;
import com.itmill.toolkit.ui.ExpandLayout;
import com.itmill.toolkit.ui.Label;
import com.itmill.toolkit.ui.Layout;
import com.itmill.toolkit.ui.Panel;
import com.itmill.toolkit.ui.SplitPanel;
import com.itmill.toolkit.ui.Tree;
import com.itmill.toolkit.ui.Window;
/**
* TestBench finds out testable classes within given java packages and adds them
* to menu from where they can be executed. Class is considered testable if it
* is of class Application or CustomComponent.
*
* Note: edit TestBench.testablePackages array
*
* @author IT Mill Ltd.
*
*/
public class TestBench extends com.itmill.toolkit.Application implements
Property.ValueChangeListener {
// Add here packages which are used for finding testable classes
String[] testablePackages = { "com.itmill.toolkit.tests",
"com.itmill.toolkit.demo", "com.itmill.toolkit.demo.colorpicker",
"com.itmill.toolkit.demo.reservation",
"com.itmill.toolkit.demo.features",
"com.itmill.toolkit.tests.tickets" };
HierarchicalContainer testables = new HierarchicalContainer();
Window mainWindow = new Window("TestBench window");
// Main layout consists of tree menu and body layout
SplitPanel mainLayout = new SplitPanel(SplitPanel.ORIENTATION_HORIZONTAL);
Tree menu;
Panel bodyLayout = new Panel();
HashMap itemCaptions = new HashMap();
public void init() {
// Add testable classes to hierarchical container
for (int p = 0; p < testablePackages.length; p++) {
testables.addItem(testablePackages[p]);
try {
final List testableClasses = getTestableClassesForPackage(testablePackages[p]);
for (final Iterator it = testableClasses.iterator(); it
.hasNext();) {
final Class t = (Class) it.next();
// ignore TestBench itself
if (t.equals(TestBench.class)) {
continue;
}
try {
testables.addItem(t);
itemCaptions.put(t, t.getName());
testables.setParent(t, testablePackages[p]);
testables.setChildrenAllowed(t, false);
continue;
} catch (final Exception e) {
try {
testables.addItem(t);
itemCaptions.put(t, t.getName());
testables.setParent(t, testablePackages[p]);
testables.setChildrenAllowed(t, false);
continue;
} catch (final Exception e1) {
e1.printStackTrace();
}
}
}
} catch (final Exception e) {
e.printStackTrace();
}
}
menu = new Tree("Testables", testables);
for (final Iterator i = itemCaptions.keySet().iterator(); i.hasNext();) {
final Class testable = (Class) i.next();
// simplify captions
final String name = testable.getName().substring(
testable.getName().lastIndexOf('.') + 1);
menu.setItemCaption(testable, name);
}
// expand all root items
for (final Iterator i = menu.rootItemIds().iterator(); i.hasNext();) {
menu.expandItemsRecursively(i.next());
}
menu.addListener(this);
menu.setImmediate(true);
menu.setNullSelectionAllowed(false);
mainLayout.addComponent(menu);
bodyLayout.addStyleName("light");
- bodyLayout.setHeight(100, Component.UNITS_PERCENTAGE);
+ bodyLayout.setSizeFull();
bodyLayout.setLayout(new ExpandLayout());
mainLayout.addComponent(bodyLayout);
mainLayout.setSplitPosition(30);
mainWindow.setLayout(mainLayout);
setMainWindow(mainWindow);
}
private Component createTestable(Class c) {
try {
final Application app = (Application) c.newInstance();
app.init();
Layout lo = app.getMainWindow().getLayout();
lo.setParent(null);
return lo;
} catch (final Exception e) {
try {
final CustomComponent cc = (CustomComponent) c.newInstance();
cc.setSizeFull();
return cc;
} catch (final Exception e1) {
e1.printStackTrace();
return new Label(
"Cannot create application / custom component: "
+ e1.toString());
}
}
}
// Handle menu selection and update body
public void valueChange(Property.ValueChangeEvent event) {
bodyLayout.removeAllComponents();
bodyLayout.setCaption(null);
final Object o = menu.getValue();
if (o != null && o instanceof Class) {
final Class c = (Class) o;
final String title = c.getName();
bodyLayout.setCaption(title);
bodyLayout.addComponent(createTestable(c));
} else {
// NOP node selected or deselected tree item
}
}
/**
* Return all testable classes within given package. Class is considered
* testable if it's superclass is Application or CustomComponent.
*
* @param packageName
* @return
* @throws ClassNotFoundException
*/
public static List getTestableClassesForPackage(String packageName)
throws Exception {
final ArrayList directories = new ArrayList();
try {
final ClassLoader cld = Thread.currentThread()
.getContextClassLoader();
if (cld == null) {
throw new ClassNotFoundException("Can't get class loader.");
}
final String path = packageName.replace('.', '/');
// Ask for all resources for the path
final Enumeration resources = cld.getResources(path);
while (resources.hasMoreElements()) {
final URL url = (URL) resources.nextElement();
directories.add(new File(url.getFile()));
}
} catch (final Exception x) {
throw new Exception(packageName
+ " does not appear to be a valid package.");
}
final ArrayList classes = new ArrayList();
// For every directory identified capture all the .class files
for (final Iterator it = directories.iterator(); it.hasNext();) {
final File directory = (File) it.next();
if (directory.exists()) {
// Get the list of the files contained in the package
final String[] files = directory.list();
for (int j = 0; j < files.length; j++) {
// we are only interested in .class files
if (files[j].endsWith(".class")) {
// removes the .class extension
final String p = packageName + '.'
+ files[j].substring(0, files[j].length() - 6);
final Class c = Class.forName(p);
if (c.getSuperclass() != null) {
if ((c.getSuperclass()
.equals(com.itmill.toolkit.Application.class))) {
classes.add(c);
} else if ((c.getSuperclass()
.equals(com.itmill.toolkit.ui.CustomComponent.class))) {
classes.add(c);
}
}
// for (int i = 0; i < c.getInterfaces().length; i++) {
// Class cc = c.getInterfaces()[i];
// if (c.getInterfaces()[i].equals(Testable.class)) {
// // Class is testable
// classes.add(c);
// }
// }
}
}
} else {
throw new ClassNotFoundException(packageName + " ("
+ directory.getPath()
+ ") does not appear to be a valid package");
}
}
return classes;
}
}
| true | true | public void init() {
// Add testable classes to hierarchical container
for (int p = 0; p < testablePackages.length; p++) {
testables.addItem(testablePackages[p]);
try {
final List testableClasses = getTestableClassesForPackage(testablePackages[p]);
for (final Iterator it = testableClasses.iterator(); it
.hasNext();) {
final Class t = (Class) it.next();
// ignore TestBench itself
if (t.equals(TestBench.class)) {
continue;
}
try {
testables.addItem(t);
itemCaptions.put(t, t.getName());
testables.setParent(t, testablePackages[p]);
testables.setChildrenAllowed(t, false);
continue;
} catch (final Exception e) {
try {
testables.addItem(t);
itemCaptions.put(t, t.getName());
testables.setParent(t, testablePackages[p]);
testables.setChildrenAllowed(t, false);
continue;
} catch (final Exception e1) {
e1.printStackTrace();
}
}
}
} catch (final Exception e) {
e.printStackTrace();
}
}
menu = new Tree("Testables", testables);
for (final Iterator i = itemCaptions.keySet().iterator(); i.hasNext();) {
final Class testable = (Class) i.next();
// simplify captions
final String name = testable.getName().substring(
testable.getName().lastIndexOf('.') + 1);
menu.setItemCaption(testable, name);
}
// expand all root items
for (final Iterator i = menu.rootItemIds().iterator(); i.hasNext();) {
menu.expandItemsRecursively(i.next());
}
menu.addListener(this);
menu.setImmediate(true);
menu.setNullSelectionAllowed(false);
mainLayout.addComponent(menu);
bodyLayout.addStyleName("light");
bodyLayout.setHeight(100, Component.UNITS_PERCENTAGE);
bodyLayout.setLayout(new ExpandLayout());
mainLayout.addComponent(bodyLayout);
mainLayout.setSplitPosition(30);
mainWindow.setLayout(mainLayout);
setMainWindow(mainWindow);
}
| public void init() {
// Add testable classes to hierarchical container
for (int p = 0; p < testablePackages.length; p++) {
testables.addItem(testablePackages[p]);
try {
final List testableClasses = getTestableClassesForPackage(testablePackages[p]);
for (final Iterator it = testableClasses.iterator(); it
.hasNext();) {
final Class t = (Class) it.next();
// ignore TestBench itself
if (t.equals(TestBench.class)) {
continue;
}
try {
testables.addItem(t);
itemCaptions.put(t, t.getName());
testables.setParent(t, testablePackages[p]);
testables.setChildrenAllowed(t, false);
continue;
} catch (final Exception e) {
try {
testables.addItem(t);
itemCaptions.put(t, t.getName());
testables.setParent(t, testablePackages[p]);
testables.setChildrenAllowed(t, false);
continue;
} catch (final Exception e1) {
e1.printStackTrace();
}
}
}
} catch (final Exception e) {
e.printStackTrace();
}
}
menu = new Tree("Testables", testables);
for (final Iterator i = itemCaptions.keySet().iterator(); i.hasNext();) {
final Class testable = (Class) i.next();
// simplify captions
final String name = testable.getName().substring(
testable.getName().lastIndexOf('.') + 1);
menu.setItemCaption(testable, name);
}
// expand all root items
for (final Iterator i = menu.rootItemIds().iterator(); i.hasNext();) {
menu.expandItemsRecursively(i.next());
}
menu.addListener(this);
menu.setImmediate(true);
menu.setNullSelectionAllowed(false);
mainLayout.addComponent(menu);
bodyLayout.addStyleName("light");
bodyLayout.setSizeFull();
bodyLayout.setLayout(new ExpandLayout());
mainLayout.addComponent(bodyLayout);
mainLayout.setSplitPosition(30);
mainWindow.setLayout(mainLayout);
setMainWindow(mainWindow);
}
|
diff --git a/libraries/javalib/java/text/SimpleDateFormat.java b/libraries/javalib/java/text/SimpleDateFormat.java
index dc6a27498..a99792927 100644
--- a/libraries/javalib/java/text/SimpleDateFormat.java
+++ b/libraries/javalib/java/text/SimpleDateFormat.java
@@ -1,1221 +1,1225 @@
/* SimpleDateFormat.java -- A class for parsing/formating simple
date constructs
Copyright (C) 1998, 1999, 2000, 2001, 2003, 2004, 2005
Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath 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.
GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.text;
import gnu.java.text.AttributedFormatBuffer;
import gnu.java.text.FormatBuffer;
import gnu.java.text.FormatCharacterIterator;
import gnu.java.text.StringFormatBuffer;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.Locale;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* SimpleDateFormat provides convenient methods for parsing and formatting
* dates using Gregorian calendars (see java.util.GregorianCalendar).
*/
public class SimpleDateFormat extends DateFormat
{
/**
* This class is used by <code>SimpleDateFormat</code> as a
* compiled representation of a format string. The field
* ID, size, and character used are stored for each sequence
* of pattern characters.
*/
private class CompiledField
{
/**
* The ID of the field within the local pattern characters,
*/
private int field;
/**
* The size of the character sequence.
*/
private int size;
/**
* The character used.
*/
private char character;
/**
* Constructs a compiled field using the
* the given field ID, size and character
* values.
*
* @param f the field ID.
* @param s the size of the field.
* @param c the character used.
*/
public CompiledField(int f, int s, char c)
{
field = f;
size = s;
character = c;
}
/**
* Retrieves the ID of the field relative to
* the local pattern characters.
*/
public int getField()
{
return field;
}
/**
* Retrieves the size of the character sequence.
*/
public int getSize()
{
return size;
}
/**
* Retrieves the character used in the sequence.
*/
public char getCharacter()
{
return character;
}
/**
* Returns a <code>String</code> representation
* of the compiled field, primarily for debugging
* purposes.
*
* @return a <code>String</code> representation.
*/
public String toString()
{
StringBuilder builder;
builder = new StringBuilder(getClass().getName());
builder.append("[field=");
builder.append(field);
builder.append(", size=");
builder.append(size);
builder.append(", character=");
builder.append(character);
builder.append("]");
return builder.toString();
}
}
/**
* A list of <code>CompiledField</code>s,
* representing the compiled version of the pattern.
*
* @see CompiledField
* @serial Ignored.
*/
private transient ArrayList tokens;
/**
* The localised data used in formatting,
* such as the day and month names in the local
* language, and the localized pattern characters.
*
* @see DateFormatSymbols
* @serial The localisation data. May not be null.
*/
private DateFormatSymbols formatData;
/**
* The date representing the start of the century
* used for interpreting two digit years. For
* example, 24/10/2004 would cause two digit
* years to be interpreted as representing
* the years between 2004 and 2104.
*
* @see get2DigitYearStart()
* @see set2DigitYearStart(java.util.Date)
* @see Date
* @serial The start date of the century for parsing two digit years.
* May not be null.
*/
private Date defaultCenturyStart;
/**
* The year at which interpretation of two
* digit years starts.
*
* @see get2DigitYearStart()
* @see set2DigitYearStart(java.util.Date)
* @serial Ignored.
*/
private transient int defaultCentury;
/**
* The non-localized pattern string. This
* only ever contains the pattern characters
* stored in standardChars. Localized patterns
* are translated to this form.
*
* @see applyPattern(String)
* @see applyLocalizedPattern(String)
* @see toPattern()
* @see toLocalizedPattern()
* @serial The non-localized pattern string. May not be null.
*/
private String pattern;
/**
* The version of serialized data used by this class.
* Version 0 only includes the pattern and formatting
* data. Version 1 adds the start date for interpreting
* two digit years.
*
* @serial This specifies the version of the data being serialized.
* Version 0 (or no version) specifies just <code>pattern</code>
* and <code>formatData</code>. Version 1 adds
* the <code>defaultCenturyStart</code>. This implementation
* always writes out version 1 data.
*/
private int serialVersionOnStream = 1; // 0 indicates JDK1.1.3 or earlier
/**
* For compatability.
*/
private static final long serialVersionUID = 4774881970558875024L;
// This string is specified in the root of the CLDR. We set it here
// rather than doing a DateFormatSymbols(Locale.US).getLocalPatternChars()
// since someone could theoretically change those values (though unlikely).
private static final String standardChars = "GyMdkHmsSEDFwWahKzYeugAZ";
/**
* Reads the serialized version of this object.
* If the serialized data is only version 0,
* then the date for the start of the century
* for interpreting two digit years is computed.
* The pattern is parsed and compiled following the process
* of reading in the serialized data.
*
* @param stream the object stream to read the data from.
* @throws IOException if an I/O error occurs.
* @throws ClassNotFoundException if the class of the serialized data
* could not be found.
* @throws InvalidObjectException if the pattern is invalid.
*/
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException
{
stream.defaultReadObject();
if (serialVersionOnStream < 1)
{
computeCenturyStart ();
serialVersionOnStream = 1;
}
else
// Ensure that defaultCentury gets set.
set2DigitYearStart(defaultCenturyStart);
// Set up items normally taken care of by the constructor.
tokens = new ArrayList();
try
{
compileFormat(pattern);
}
catch (IllegalArgumentException e)
{
throw new InvalidObjectException("The stream pattern was invalid.");
}
}
/**
* Compiles the supplied non-localized pattern into a form
* from which formatting and parsing can be performed.
* This also detects errors in the pattern, which will
* be raised on later use of the compiled data.
*
* @param pattern the non-localized pattern to compile.
* @throws IllegalArgumentException if the pattern is invalid.
*/
private void compileFormat(String pattern)
{
// Any alphabetical characters are treated as pattern characters
// unless enclosed in single quotes.
char thisChar;
int pos;
int field;
CompiledField current = null;
for (int i=0; i<pattern.length(); i++) {
thisChar = pattern.charAt(i);
field = standardChars.indexOf(thisChar);
if (field == -1) {
current = null;
if ((thisChar >= 'A' && thisChar <= 'Z')
|| (thisChar >= 'a' && thisChar <= 'z')) {
// Not a valid letter
throw new IllegalArgumentException("Invalid letter " + thisChar +
"encountered at character " + i
+ ".");
} else if (thisChar == '\'') {
// Quoted text section; skip to next single quote
pos = pattern.indexOf('\'',i+1);
if (pos == -1) {
throw new IllegalArgumentException("Quotes starting at character "
+ i + " not closed.");
}
if ((pos+1 < pattern.length()) && (pattern.charAt(pos+1) == '\'')) {
tokens.add(pattern.substring(i+1,pos+1));
} else {
tokens.add(pattern.substring(i+1,pos));
}
i = pos;
} else {
// A special character
tokens.add(new Character(thisChar));
}
} else {
// A valid field
if ((current != null) && (field == current.field)) {
current.size++;
} else {
current = new CompiledField(field,1,thisChar);
tokens.add(current);
}
}
}
}
/**
* Returns a string representation of this
* class.
*
* @return a string representation of the <code>SimpleDateFormat</code>
* instance.
*/
public String toString()
{
StringBuilder output = new StringBuilder(getClass().getName());
output.append("[tokens=");
output.append(tokens);
output.append(", formatData=");
output.append(formatData);
output.append(", defaultCenturyStart=");
output.append(defaultCenturyStart);
output.append(", defaultCentury=");
output.append(defaultCentury);
output.append(", pattern=");
output.append(pattern);
output.append(", serialVersionOnStream=");
output.append(serialVersionOnStream);
output.append(", standardChars=");
output.append(standardChars);
output.append("]");
return output.toString();
}
/**
* Constructs a SimpleDateFormat using the default pattern for
* the default locale.
*/
public SimpleDateFormat()
{
/*
* There does not appear to be a standard API for determining
* what the default pattern for a locale is, so use package-scope
* variables in DateFormatSymbols to encapsulate this.
*/
super();
Locale locale = Locale.getDefault();
calendar = new GregorianCalendar(locale);
computeCenturyStart();
tokens = new ArrayList();
formatData = new DateFormatSymbols(locale);
pattern = (formatData.dateFormats[DEFAULT] + ' '
+ formatData.timeFormats[DEFAULT]);
compileFormat(pattern);
numberFormat = NumberFormat.getInstance(locale);
numberFormat.setGroupingUsed (false);
numberFormat.setParseIntegerOnly (true);
numberFormat.setMaximumFractionDigits (0);
}
/**
* Creates a date formatter using the specified non-localized pattern,
* with the default DateFormatSymbols for the default locale.
*
* @param pattern the pattern to use.
* @throws NullPointerException if the pattern is null.
* @throws IllegalArgumentException if the pattern is invalid.
*/
public SimpleDateFormat(String pattern)
{
this(pattern, Locale.getDefault());
}
/**
* Creates a date formatter using the specified non-localized pattern,
* with the default DateFormatSymbols for the given locale.
*
* @param pattern the non-localized pattern to use.
* @param locale the locale to use for the formatting symbols.
* @throws NullPointerException if the pattern is null.
* @throws IllegalArgumentException if the pattern is invalid.
*/
public SimpleDateFormat(String pattern, Locale locale)
{
super();
calendar = new GregorianCalendar(locale);
computeCenturyStart();
tokens = new ArrayList();
formatData = new DateFormatSymbols(locale);
compileFormat(pattern);
this.pattern = pattern;
numberFormat = NumberFormat.getInstance(locale);
numberFormat.setGroupingUsed (false);
numberFormat.setParseIntegerOnly (true);
numberFormat.setMaximumFractionDigits (0);
}
/**
* Creates a date formatter using the specified non-localized
* pattern. The specified DateFormatSymbols will be used when
* formatting.
*
* @param pattern the non-localized pattern to use.
* @param formatData the formatting symbols to use.
* @throws NullPointerException if the pattern or formatData is null.
* @throws IllegalArgumentException if the pattern is invalid.
*/
public SimpleDateFormat(String pattern, DateFormatSymbols formatData)
{
super();
calendar = new GregorianCalendar();
computeCenturyStart ();
tokens = new ArrayList();
if (formatData == null)
throw new NullPointerException("formatData");
this.formatData = formatData;
compileFormat(pattern);
this.pattern = pattern;
numberFormat = NumberFormat.getInstance();
numberFormat.setGroupingUsed (false);
numberFormat.setParseIntegerOnly (true);
numberFormat.setMaximumFractionDigits (0);
}
/**
* This method returns a string with the formatting pattern being used
* by this object. This string is unlocalized.
*
* @return The format string.
*/
public String toPattern()
{
return pattern;
}
/**
* This method returns a string with the formatting pattern being used
* by this object. This string is localized.
*
* @return The format string.
*/
public String toLocalizedPattern()
{
String localChars = formatData.getLocalPatternChars();
return translateLocalizedPattern(pattern, standardChars, localChars);
}
/**
* This method sets the formatting pattern that should be used by this
* object. This string is not localized.
*
* @param pattern The new format pattern.
* @throws NullPointerException if the pattern is null.
* @throws IllegalArgumentException if the pattern is invalid.
*/
public void applyPattern(String pattern)
{
tokens = new ArrayList();
compileFormat(pattern);
this.pattern = pattern;
}
/**
* This method sets the formatting pattern that should be used by this
* object. This string is localized.
*
* @param pattern The new format pattern.
* @throws NullPointerException if the pattern is null.
* @throws IllegalArgumentException if the pattern is invalid.
*/
public void applyLocalizedPattern(String pattern)
{
String localChars = formatData.getLocalPatternChars();
pattern = translateLocalizedPattern(pattern, localChars, standardChars);
applyPattern(pattern);
}
/**
* Translates either from or to a localized variant of the pattern
* string. For example, in the German locale, 't' (for 'tag') is
* used instead of 'd' (for 'date'). This method translates
* a localized pattern (such as 'ttt') to a non-localized pattern
* (such as 'ddd'), or vice versa. Non-localized patterns use
* a standard set of characters, which match those of the U.S. English
* locale.
*
* @param pattern the pattern to translate.
* @param oldChars the old set of characters (used in the pattern).
* @param newChars the new set of characters (which will be used in the
* pattern).
* @return a version of the pattern using the characters in
* <code>newChars</code>.
*/
private String translateLocalizedPattern(String pattern,
String oldChars, String newChars)
{
int len = pattern.length();
StringBuffer buf = new StringBuffer(len);
boolean quoted = false;
for (int i = 0; i < len; i++)
{
char ch = pattern.charAt(i);
if (ch == '\'')
quoted = ! quoted;
if (! quoted)
{
int j = oldChars.indexOf(ch);
if (j >= 0)
ch = newChars.charAt(j);
}
buf.append(ch);
}
return buf.toString();
}
/**
* Returns the start of the century used for two digit years.
*
* @return A <code>Date</code> representing the start of the century
* for two digit years.
*/
public Date get2DigitYearStart()
{
return defaultCenturyStart;
}
/**
* Sets the start of the century used for two digit years.
*
* @param date A <code>Date</code> representing the start of the century for
* two digit years.
*/
public void set2DigitYearStart(Date date)
{
defaultCenturyStart = date;
calendar.clear();
calendar.setTime(date);
int year = calendar.get(Calendar.YEAR);
defaultCentury = year - (year % 100);
}
/**
* This method returns a copy of the format symbol information used
* for parsing and formatting dates.
*
* @return a copy of the date format symbols.
*/
public DateFormatSymbols getDateFormatSymbols()
{
return (DateFormatSymbols) formatData.clone();
}
/**
* This method sets the format symbols information used for parsing
* and formatting dates.
*
* @param formatData The date format symbols.
* @throws NullPointerException if <code>formatData</code> is null.
*/
public void setDateFormatSymbols(DateFormatSymbols formatData)
{
if (formatData == null)
{
throw new
NullPointerException("The supplied format data was null.");
}
this.formatData = formatData;
}
/**
* This methods tests whether the specified object is equal to this
* object. This will be true if and only if the specified object:
* <p>
* <ul>
* <li>Is not <code>null</code>.</li>
* <li>Is an instance of <code>SimpleDateFormat</code>.</li>
* <li>Is equal to this object at the superclass (i.e., <code>DateFormat</code>)
* level.</li>
* <li>Has the same formatting pattern.</li>
* <li>Is using the same formatting symbols.</li>
* <li>Is using the same century for two digit years.</li>
* </ul>
*
* @param obj The object to compare for equality against.
*
* @return <code>true</code> if the specified object is equal to this object,
* <code>false</code> otherwise.
*/
public boolean equals(Object o)
{
if (!super.equals(o))
return false;
if (!(o instanceof SimpleDateFormat))
return false;
SimpleDateFormat sdf = (SimpleDateFormat)o;
if (defaultCentury != sdf.defaultCentury)
return false;
if (!toPattern().equals(sdf.toPattern()))
return false;
if (!getDateFormatSymbols().equals(sdf.getDateFormatSymbols()))
return false;
return true;
}
/**
* This method returns a hash value for this object.
*
* @return A hash value for this object.
*/
public int hashCode()
{
return super.hashCode() ^ toPattern().hashCode() ^ defaultCentury ^
getDateFormatSymbols().hashCode();
}
/**
* Formats the date input according to the format string in use,
* appending to the specified StringBuffer. The input StringBuffer
* is returned as output for convenience.
*/
private void formatWithAttribute(Date date, FormatBuffer buffer, FieldPosition pos)
{
String temp;
AttributedCharacterIterator.Attribute attribute;
calendar.setTime(date);
// go through vector, filling in fields where applicable, else toString
Iterator iter = tokens.iterator();
while (iter.hasNext())
{
Object o = iter.next();
if (o instanceof CompiledField)
{
CompiledField cf = (CompiledField) o;
int beginIndex = buffer.length();
switch (cf.getField())
{
case ERA_FIELD:
buffer.append (formatData.eras[calendar.get (Calendar.ERA)], DateFormat.Field.ERA);
break;
case YEAR_FIELD:
// If we have two digits, then we truncate. Otherwise, we
// use the size of the pattern, and zero pad.
buffer.setDefaultAttribute (DateFormat.Field.YEAR);
if (cf.getSize() == 2)
{
temp = String.valueOf (calendar.get (Calendar.YEAR));
buffer.append (temp.substring (temp.length() - 2));
}
else
withLeadingZeros (calendar.get (Calendar.YEAR), cf.getSize(), buffer);
break;
case MONTH_FIELD:
buffer.setDefaultAttribute (DateFormat.Field.MONTH);
if (cf.getSize() < 3)
withLeadingZeros (calendar.get (Calendar.MONTH) + 1, cf.getSize(), buffer);
else if (cf.getSize() < 4)
buffer.append (formatData.shortMonths[calendar.get (Calendar.MONTH)]);
else
buffer.append (formatData.months[calendar.get (Calendar.MONTH)]);
break;
case DATE_FIELD:
buffer.setDefaultAttribute (DateFormat.Field.DAY_OF_MONTH);
withLeadingZeros (calendar.get (Calendar.DATE), cf.getSize(), buffer);
break;
case HOUR_OF_DAY1_FIELD: // 1-24
buffer.setDefaultAttribute(DateFormat.Field.HOUR_OF_DAY1);
withLeadingZeros ( ((calendar.get (Calendar.HOUR_OF_DAY) + 23) % 24) + 1,
cf.getSize(), buffer);
break;
case HOUR_OF_DAY0_FIELD: // 0-23
buffer.setDefaultAttribute (DateFormat.Field.HOUR_OF_DAY0);
withLeadingZeros (calendar.get (Calendar.HOUR_OF_DAY), cf.getSize(), buffer);
break;
case MINUTE_FIELD:
buffer.setDefaultAttribute (DateFormat.Field.MINUTE);
withLeadingZeros (calendar.get (Calendar.MINUTE),
cf.getSize(), buffer);
break;
case SECOND_FIELD:
buffer.setDefaultAttribute (DateFormat.Field.SECOND);
withLeadingZeros(calendar.get (Calendar.SECOND),
cf.getSize(), buffer);
break;
case MILLISECOND_FIELD:
buffer.setDefaultAttribute (DateFormat.Field.MILLISECOND);
withLeadingZeros (calendar.get (Calendar.MILLISECOND), cf.getSize(), buffer);
break;
case DAY_OF_WEEK_FIELD:
buffer.setDefaultAttribute (DateFormat.Field.DAY_OF_WEEK);
if (cf.getSize() < 4)
buffer.append (formatData.shortWeekdays[calendar.get (Calendar.DAY_OF_WEEK)]);
else
buffer.append (formatData.weekdays[calendar.get (Calendar.DAY_OF_WEEK)]);
break;
case DAY_OF_YEAR_FIELD:
buffer.setDefaultAttribute (DateFormat.Field.DAY_OF_YEAR);
withLeadingZeros (calendar.get (Calendar.DAY_OF_YEAR), cf.getSize(), buffer);
break;
case DAY_OF_WEEK_IN_MONTH_FIELD:
buffer.setDefaultAttribute (DateFormat.Field.DAY_OF_WEEK_IN_MONTH);
withLeadingZeros (calendar.get (Calendar.DAY_OF_WEEK_IN_MONTH),
cf.getSize(), buffer);
break;
case WEEK_OF_YEAR_FIELD:
buffer.setDefaultAttribute (DateFormat.Field.WEEK_OF_YEAR);
withLeadingZeros (calendar.get (Calendar.WEEK_OF_YEAR),
cf.getSize(), buffer);
break;
case WEEK_OF_MONTH_FIELD:
buffer.setDefaultAttribute (DateFormat.Field.WEEK_OF_MONTH);
withLeadingZeros (calendar.get (Calendar.WEEK_OF_MONTH),
cf.getSize(), buffer);
break;
case AM_PM_FIELD:
buffer.setDefaultAttribute (DateFormat.Field.AM_PM);
buffer.append (formatData.ampms[calendar.get (Calendar.AM_PM)]);
break;
case HOUR1_FIELD: // 1-12
buffer.setDefaultAttribute (DateFormat.Field.HOUR1);
withLeadingZeros (((calendar.get (Calendar.HOUR) + 11) % 12) + 1,
cf.getSize(), buffer);
break;
case HOUR0_FIELD: // 0-11
buffer.setDefaultAttribute (DateFormat.Field.HOUR0);
withLeadingZeros (calendar.get (Calendar.HOUR), cf.getSize(), buffer);
break;
case TIMEZONE_FIELD:
buffer.setDefaultAttribute (DateFormat.Field.TIME_ZONE);
TimeZone zone = calendar.getTimeZone();
boolean isDST = calendar.get (Calendar.DST_OFFSET) != 0;
// FIXME: XXX: This should be a localized time zone.
String zoneID = zone.getDisplayName
(isDST, cf.getSize() > 3 ? TimeZone.LONG : TimeZone.SHORT);
buffer.append (zoneID);
break;
case RFC822_TIMEZONE_FIELD:
buffer.setDefaultAttribute(DateFormat.Field.RFC822_TIME_ZONE);
int pureMinutes = (calendar.get(Calendar.ZONE_OFFSET) +
calendar.get(Calendar.DST_OFFSET)) / (1000 * 60);
String sign = (pureMinutes < 0) ? "-" : "+";
int hours = pureMinutes / 60;
int minutes = pureMinutes % 60;
buffer.append(sign);
withLeadingZeros(hours, 2, buffer);
withLeadingZeros(minutes, 2, buffer);
break;
default:
throw new IllegalArgumentException ("Illegal pattern character " +
cf.getCharacter());
}
if (pos != null && (buffer.getDefaultAttribute() == pos.getFieldAttribute()
|| cf.getField() == pos.getField()))
{
pos.setBeginIndex(beginIndex);
pos.setEndIndex(buffer.length());
}
}
else
{
buffer.append(o.toString(), null);
}
}
}
public StringBuffer format(Date date, StringBuffer buffer, FieldPosition pos)
{
formatWithAttribute(date, new StringFormatBuffer (buffer), pos);
return buffer;
}
public AttributedCharacterIterator formatToCharacterIterator(Object date)
throws IllegalArgumentException
{
if (date == null)
throw new NullPointerException("null argument");
if (!(date instanceof Date))
throw new IllegalArgumentException("argument should be an instance of java.util.Date");
AttributedFormatBuffer buf = new AttributedFormatBuffer();
formatWithAttribute((Date)date, buf,
null);
buf.sync();
return new FormatCharacterIterator(buf.getBuffer().toString(),
buf.getRanges(),
buf.getAttributes());
}
private void withLeadingZeros(int value, int length, FormatBuffer buffer)
{
String valStr = String.valueOf(value);
for (length -= valStr.length(); length > 0; length--)
buffer.append('0');
buffer.append(valStr);
}
private boolean expect(String source, ParsePosition pos, char ch)
{
int x = pos.getIndex();
boolean r = x < source.length() && source.charAt(x) == ch;
if (r)
pos.setIndex(x + 1);
else
pos.setErrorIndex(x);
return r;
}
/**
* This method parses the specified string into a date.
*
* @param dateStr The date string to parse.
* @param pos The input and output parse position
*
* @return The parsed date, or <code>null</code> if the string cannot be
* parsed.
*/
public Date parse (String dateStr, ParsePosition pos)
{
int fmt_index = 0;
int fmt_max = pattern.length();
calendar.clear();
boolean saw_timezone = false;
int quote_start = -1;
boolean is2DigitYear = false;
try
{
for (; fmt_index < fmt_max; ++fmt_index)
{
char ch = pattern.charAt(fmt_index);
if (ch == '\'')
{
int index = pos.getIndex();
if (fmt_index < fmt_max - 1
&& pattern.charAt(fmt_index + 1) == '\'')
{
if (! expect (dateStr, pos, ch))
return null;
++fmt_index;
}
else
quote_start = quote_start < 0 ? fmt_index : -1;
continue;
}
if (quote_start != -1
|| ((ch < 'a' || ch > 'z')
&& (ch < 'A' || ch > 'Z')))
{
if (! expect (dateStr, pos, ch))
return null;
continue;
}
// We've arrived at a potential pattern character in the
// pattern.
int fmt_count = 1;
while (++fmt_index < fmt_max && pattern.charAt(fmt_index) == ch)
{
++fmt_count;
}
// We might need to limit the number of digits to parse in
// some cases. We look to the next pattern character to
// decide.
boolean limit_digits = false;
if (fmt_index < fmt_max
&& standardChars.indexOf(pattern.charAt(fmt_index)) >= 0)
limit_digits = true;
--fmt_index;
// We can handle most fields automatically: most either are
// numeric or are looked up in a string vector. In some cases
// we need an offset. When numeric, `offset' is added to the
// resulting value. When doing a string lookup, offset is the
// initial index into the string array.
int calendar_field;
boolean is_numeric = true;
int offset = 0;
boolean maybe2DigitYear = false;
Integer simpleOffset;
String[] set1 = null;
String[] set2 = null;
switch (ch)
{
case 'd':
calendar_field = Calendar.DATE;
break;
case 'D':
calendar_field = Calendar.DAY_OF_YEAR;
break;
case 'F':
calendar_field = Calendar.DAY_OF_WEEK_IN_MONTH;
break;
case 'E':
is_numeric = false;
offset = 1;
calendar_field = Calendar.DAY_OF_WEEK;
set1 = formatData.getWeekdays();
set2 = formatData.getShortWeekdays();
break;
case 'w':
calendar_field = Calendar.WEEK_OF_YEAR;
break;
case 'W':
calendar_field = Calendar.WEEK_OF_MONTH;
break;
case 'M':
calendar_field = Calendar.MONTH;
if (fmt_count <= 2)
offset = -1;
else
{
is_numeric = false;
set1 = formatData.getMonths();
set2 = formatData.getShortMonths();
}
break;
case 'y':
calendar_field = Calendar.YEAR;
if (fmt_count <= 2)
maybe2DigitYear = true;
break;
case 'K':
calendar_field = Calendar.HOUR;
break;
case 'h':
calendar_field = Calendar.HOUR;
break;
case 'H':
calendar_field = Calendar.HOUR_OF_DAY;
break;
case 'k':
calendar_field = Calendar.HOUR_OF_DAY;
break;
case 'm':
calendar_field = Calendar.MINUTE;
break;
case 's':
calendar_field = Calendar.SECOND;
break;
case 'S':
calendar_field = Calendar.MILLISECOND;
break;
case 'a':
is_numeric = false;
calendar_field = Calendar.AM_PM;
set1 = formatData.getAmPmStrings();
break;
case 'z':
case 'Z':
// We need a special case for the timezone, because it
// uses a different data structure than the other cases.
is_numeric = false;
calendar_field = Calendar.ZONE_OFFSET;
String[][] zoneStrings = formatData.getZoneStrings();
int zoneCount = zoneStrings.length;
int index = pos.getIndex();
boolean found_zone = false;
simpleOffset = computeOffset(dateStr.substring(index));
if (simpleOffset != null)
{
found_zone = true;
saw_timezone = true;
calendar.set(Calendar.DST_OFFSET, 0);
offset = simpleOffset.intValue();
}
else
{
for (int j = 0; j < zoneCount; j++)
{
String[] strings = zoneStrings[j];
int k;
for (k = 0; k < strings.length; ++k)
{
if (dateStr.startsWith(strings[k], index))
break;
}
if (k != strings.length)
{
found_zone = true;
saw_timezone = true;
TimeZone tz = TimeZone.getTimeZone (strings[0]);
- calendar.set (Calendar.DST_OFFSET, tz.getDSTSavings());
+ // Check if it's a DST zone or ordinary
+ if(k == 3 || k == 4)
+ calendar.set (Calendar.DST_OFFSET, tz.getDSTSavings());
+ else
+ calendar.set (Calendar.DST_OFFSET, 0);
offset = tz.getRawOffset ();
pos.setIndex(index + strings[k].length());
break;
}
}
}
if (! found_zone)
{
pos.setErrorIndex(pos.getIndex());
return null;
}
break;
default:
pos.setErrorIndex(pos.getIndex());
return null;
}
// Compute the value we should assign to the field.
int value;
int index = -1;
if (is_numeric)
{
numberFormat.setMinimumIntegerDigits(fmt_count);
if (limit_digits)
numberFormat.setMaximumIntegerDigits(fmt_count);
if (maybe2DigitYear)
index = pos.getIndex();
Number n = numberFormat.parse(dateStr, pos);
if (pos == null || ! (n instanceof Long))
return null;
value = n.intValue() + offset;
}
else if (set1 != null)
{
index = pos.getIndex();
int i;
boolean found = false;
for (i = offset; i < set1.length; ++i)
{
if (set1[i] != null)
if (dateStr.toUpperCase().startsWith(set1[i].toUpperCase(),
index))
{
found = true;
pos.setIndex(index + set1[i].length());
break;
}
}
if (!found && set2 != null)
{
for (i = offset; i < set2.length; ++i)
{
if (set2[i] != null)
if (dateStr.toUpperCase().startsWith(set2[i].toUpperCase(),
index))
{
found = true;
pos.setIndex(index + set2[i].length());
break;
}
}
}
if (!found)
{
pos.setErrorIndex(index);
return null;
}
value = i;
}
else
value = offset;
if (maybe2DigitYear)
{
// Parse into default century if the numeric year string has
// exactly 2 digits.
int digit_count = pos.getIndex() - index;
if (digit_count == 2)
{
is2DigitYear = true;
value += defaultCentury;
}
}
// Assign the value and move on.
calendar.set(calendar_field, value);
}
if (is2DigitYear)
{
// Apply the 80-20 heuristic to dermine the full year based on
// defaultCenturyStart.
int year = calendar.get(Calendar.YEAR);
if (calendar.getTime().compareTo(defaultCenturyStart) < 0)
calendar.set(Calendar.YEAR, year + 100);
}
if (! saw_timezone)
{
// Use the real rules to determine whether or not this
// particular time is in daylight savings.
calendar.clear (Calendar.DST_OFFSET);
calendar.clear (Calendar.ZONE_OFFSET);
}
return calendar.getTime();
}
catch (IllegalArgumentException x)
{
pos.setErrorIndex(pos.getIndex());
return null;
}
}
/**
* <p>
* Computes the time zone offset in milliseconds
* relative to GMT, based on the supplied
* <code>String</code> representation.
* </p>
* <p>
* The supplied <code>String</code> must be a three
* or four digit signed number, with an optional 'GMT'
* prefix. The first one or two digits represents the hours,
* while the last two represent the minutes. The
* two sets of digits can optionally be separated by
* ':'. The mandatory sign prefix (either '+' or '-')
* indicates the direction of the offset from GMT.
* </p>
* <p>
* For example, 'GMT+0200' specifies 2 hours after
* GMT, while '-05:00' specifies 5 hours prior to
* GMT. The special case of 'GMT' alone can be used
* to represent the offset, 0.
* </p>
* <p>
* If the <code>String</code> can not be parsed,
* the result will be null. The resulting offset
* is wrapped in an <code>Integer</code> object, in
* order to allow such failure to be represented.
* </p>
*
* @param zoneString a string in the form
* (GMT)? sign hours : minutes
* where sign = '+' or '-', hours
* is a one or two digits representing
* a number between 0 and 23, and
* minutes is two digits representing
* a number between 0 and 59.
* @return the parsed offset, or null if parsing
* failed.
*/
private Integer computeOffset(String zoneString)
{
Pattern pattern =
Pattern.compile("(GMT)?([+-])([012])?([0-9]):?([0-9]{2})");
Matcher matcher = pattern.matcher(zoneString);
if (matcher.matches())
{
int sign = matcher.group(2).equals("+") ? 1 : -1;
int hour = (Integer.parseInt(matcher.group(3)) * 10)
+ Integer.parseInt(matcher.group(4));
int minutes = Integer.parseInt(matcher.group(5));
if (hour > 23)
return null;
int offset = sign * ((hour * 60) + minutes) * 60000;
return new Integer(offset);
}
else if (zoneString.startsWith("GMT"))
{
return new Integer(0);
}
return null;
}
// Compute the start of the current century as defined by
// get2DigitYearStart.
private void computeCenturyStart()
{
int year = calendar.get(Calendar.YEAR);
calendar.set(Calendar.YEAR, year - 80);
set2DigitYearStart(calendar.getTime());
}
/**
* Returns a copy of this instance of
* <code>SimpleDateFormat</code>. The copy contains
* clones of the formatting symbols and the 2-digit
* year century start date.
*/
public Object clone()
{
SimpleDateFormat clone = (SimpleDateFormat) super.clone();
clone.setDateFormatSymbols((DateFormatSymbols) formatData.clone());
clone.set2DigitYearStart((Date) defaultCenturyStart.clone());
return clone;
}
}
| true | true | public Date parse (String dateStr, ParsePosition pos)
{
int fmt_index = 0;
int fmt_max = pattern.length();
calendar.clear();
boolean saw_timezone = false;
int quote_start = -1;
boolean is2DigitYear = false;
try
{
for (; fmt_index < fmt_max; ++fmt_index)
{
char ch = pattern.charAt(fmt_index);
if (ch == '\'')
{
int index = pos.getIndex();
if (fmt_index < fmt_max - 1
&& pattern.charAt(fmt_index + 1) == '\'')
{
if (! expect (dateStr, pos, ch))
return null;
++fmt_index;
}
else
quote_start = quote_start < 0 ? fmt_index : -1;
continue;
}
if (quote_start != -1
|| ((ch < 'a' || ch > 'z')
&& (ch < 'A' || ch > 'Z')))
{
if (! expect (dateStr, pos, ch))
return null;
continue;
}
// We've arrived at a potential pattern character in the
// pattern.
int fmt_count = 1;
while (++fmt_index < fmt_max && pattern.charAt(fmt_index) == ch)
{
++fmt_count;
}
// We might need to limit the number of digits to parse in
// some cases. We look to the next pattern character to
// decide.
boolean limit_digits = false;
if (fmt_index < fmt_max
&& standardChars.indexOf(pattern.charAt(fmt_index)) >= 0)
limit_digits = true;
--fmt_index;
// We can handle most fields automatically: most either are
// numeric or are looked up in a string vector. In some cases
// we need an offset. When numeric, `offset' is added to the
// resulting value. When doing a string lookup, offset is the
// initial index into the string array.
int calendar_field;
boolean is_numeric = true;
int offset = 0;
boolean maybe2DigitYear = false;
Integer simpleOffset;
String[] set1 = null;
String[] set2 = null;
switch (ch)
{
case 'd':
calendar_field = Calendar.DATE;
break;
case 'D':
calendar_field = Calendar.DAY_OF_YEAR;
break;
case 'F':
calendar_field = Calendar.DAY_OF_WEEK_IN_MONTH;
break;
case 'E':
is_numeric = false;
offset = 1;
calendar_field = Calendar.DAY_OF_WEEK;
set1 = formatData.getWeekdays();
set2 = formatData.getShortWeekdays();
break;
case 'w':
calendar_field = Calendar.WEEK_OF_YEAR;
break;
case 'W':
calendar_field = Calendar.WEEK_OF_MONTH;
break;
case 'M':
calendar_field = Calendar.MONTH;
if (fmt_count <= 2)
offset = -1;
else
{
is_numeric = false;
set1 = formatData.getMonths();
set2 = formatData.getShortMonths();
}
break;
case 'y':
calendar_field = Calendar.YEAR;
if (fmt_count <= 2)
maybe2DigitYear = true;
break;
case 'K':
calendar_field = Calendar.HOUR;
break;
case 'h':
calendar_field = Calendar.HOUR;
break;
case 'H':
calendar_field = Calendar.HOUR_OF_DAY;
break;
case 'k':
calendar_field = Calendar.HOUR_OF_DAY;
break;
case 'm':
calendar_field = Calendar.MINUTE;
break;
case 's':
calendar_field = Calendar.SECOND;
break;
case 'S':
calendar_field = Calendar.MILLISECOND;
break;
case 'a':
is_numeric = false;
calendar_field = Calendar.AM_PM;
set1 = formatData.getAmPmStrings();
break;
case 'z':
case 'Z':
// We need a special case for the timezone, because it
// uses a different data structure than the other cases.
is_numeric = false;
calendar_field = Calendar.ZONE_OFFSET;
String[][] zoneStrings = formatData.getZoneStrings();
int zoneCount = zoneStrings.length;
int index = pos.getIndex();
boolean found_zone = false;
simpleOffset = computeOffset(dateStr.substring(index));
if (simpleOffset != null)
{
found_zone = true;
saw_timezone = true;
calendar.set(Calendar.DST_OFFSET, 0);
offset = simpleOffset.intValue();
}
else
{
for (int j = 0; j < zoneCount; j++)
{
String[] strings = zoneStrings[j];
int k;
for (k = 0; k < strings.length; ++k)
{
if (dateStr.startsWith(strings[k], index))
break;
}
if (k != strings.length)
{
found_zone = true;
saw_timezone = true;
TimeZone tz = TimeZone.getTimeZone (strings[0]);
calendar.set (Calendar.DST_OFFSET, tz.getDSTSavings());
offset = tz.getRawOffset ();
pos.setIndex(index + strings[k].length());
break;
}
}
}
if (! found_zone)
{
pos.setErrorIndex(pos.getIndex());
return null;
}
break;
default:
pos.setErrorIndex(pos.getIndex());
return null;
}
// Compute the value we should assign to the field.
int value;
int index = -1;
if (is_numeric)
{
numberFormat.setMinimumIntegerDigits(fmt_count);
if (limit_digits)
numberFormat.setMaximumIntegerDigits(fmt_count);
if (maybe2DigitYear)
index = pos.getIndex();
Number n = numberFormat.parse(dateStr, pos);
if (pos == null || ! (n instanceof Long))
return null;
value = n.intValue() + offset;
}
else if (set1 != null)
{
index = pos.getIndex();
int i;
boolean found = false;
for (i = offset; i < set1.length; ++i)
{
if (set1[i] != null)
if (dateStr.toUpperCase().startsWith(set1[i].toUpperCase(),
index))
{
found = true;
pos.setIndex(index + set1[i].length());
break;
}
}
if (!found && set2 != null)
{
for (i = offset; i < set2.length; ++i)
{
if (set2[i] != null)
if (dateStr.toUpperCase().startsWith(set2[i].toUpperCase(),
index))
{
found = true;
pos.setIndex(index + set2[i].length());
break;
}
}
}
if (!found)
{
pos.setErrorIndex(index);
return null;
}
value = i;
}
else
value = offset;
if (maybe2DigitYear)
{
// Parse into default century if the numeric year string has
// exactly 2 digits.
int digit_count = pos.getIndex() - index;
if (digit_count == 2)
{
is2DigitYear = true;
value += defaultCentury;
}
}
// Assign the value and move on.
calendar.set(calendar_field, value);
}
if (is2DigitYear)
{
// Apply the 80-20 heuristic to dermine the full year based on
// defaultCenturyStart.
int year = calendar.get(Calendar.YEAR);
if (calendar.getTime().compareTo(defaultCenturyStart) < 0)
calendar.set(Calendar.YEAR, year + 100);
}
if (! saw_timezone)
{
// Use the real rules to determine whether or not this
// particular time is in daylight savings.
calendar.clear (Calendar.DST_OFFSET);
calendar.clear (Calendar.ZONE_OFFSET);
}
return calendar.getTime();
}
catch (IllegalArgumentException x)
{
pos.setErrorIndex(pos.getIndex());
return null;
}
}
| public Date parse (String dateStr, ParsePosition pos)
{
int fmt_index = 0;
int fmt_max = pattern.length();
calendar.clear();
boolean saw_timezone = false;
int quote_start = -1;
boolean is2DigitYear = false;
try
{
for (; fmt_index < fmt_max; ++fmt_index)
{
char ch = pattern.charAt(fmt_index);
if (ch == '\'')
{
int index = pos.getIndex();
if (fmt_index < fmt_max - 1
&& pattern.charAt(fmt_index + 1) == '\'')
{
if (! expect (dateStr, pos, ch))
return null;
++fmt_index;
}
else
quote_start = quote_start < 0 ? fmt_index : -1;
continue;
}
if (quote_start != -1
|| ((ch < 'a' || ch > 'z')
&& (ch < 'A' || ch > 'Z')))
{
if (! expect (dateStr, pos, ch))
return null;
continue;
}
// We've arrived at a potential pattern character in the
// pattern.
int fmt_count = 1;
while (++fmt_index < fmt_max && pattern.charAt(fmt_index) == ch)
{
++fmt_count;
}
// We might need to limit the number of digits to parse in
// some cases. We look to the next pattern character to
// decide.
boolean limit_digits = false;
if (fmt_index < fmt_max
&& standardChars.indexOf(pattern.charAt(fmt_index)) >= 0)
limit_digits = true;
--fmt_index;
// We can handle most fields automatically: most either are
// numeric or are looked up in a string vector. In some cases
// we need an offset. When numeric, `offset' is added to the
// resulting value. When doing a string lookup, offset is the
// initial index into the string array.
int calendar_field;
boolean is_numeric = true;
int offset = 0;
boolean maybe2DigitYear = false;
Integer simpleOffset;
String[] set1 = null;
String[] set2 = null;
switch (ch)
{
case 'd':
calendar_field = Calendar.DATE;
break;
case 'D':
calendar_field = Calendar.DAY_OF_YEAR;
break;
case 'F':
calendar_field = Calendar.DAY_OF_WEEK_IN_MONTH;
break;
case 'E':
is_numeric = false;
offset = 1;
calendar_field = Calendar.DAY_OF_WEEK;
set1 = formatData.getWeekdays();
set2 = formatData.getShortWeekdays();
break;
case 'w':
calendar_field = Calendar.WEEK_OF_YEAR;
break;
case 'W':
calendar_field = Calendar.WEEK_OF_MONTH;
break;
case 'M':
calendar_field = Calendar.MONTH;
if (fmt_count <= 2)
offset = -1;
else
{
is_numeric = false;
set1 = formatData.getMonths();
set2 = formatData.getShortMonths();
}
break;
case 'y':
calendar_field = Calendar.YEAR;
if (fmt_count <= 2)
maybe2DigitYear = true;
break;
case 'K':
calendar_field = Calendar.HOUR;
break;
case 'h':
calendar_field = Calendar.HOUR;
break;
case 'H':
calendar_field = Calendar.HOUR_OF_DAY;
break;
case 'k':
calendar_field = Calendar.HOUR_OF_DAY;
break;
case 'm':
calendar_field = Calendar.MINUTE;
break;
case 's':
calendar_field = Calendar.SECOND;
break;
case 'S':
calendar_field = Calendar.MILLISECOND;
break;
case 'a':
is_numeric = false;
calendar_field = Calendar.AM_PM;
set1 = formatData.getAmPmStrings();
break;
case 'z':
case 'Z':
// We need a special case for the timezone, because it
// uses a different data structure than the other cases.
is_numeric = false;
calendar_field = Calendar.ZONE_OFFSET;
String[][] zoneStrings = formatData.getZoneStrings();
int zoneCount = zoneStrings.length;
int index = pos.getIndex();
boolean found_zone = false;
simpleOffset = computeOffset(dateStr.substring(index));
if (simpleOffset != null)
{
found_zone = true;
saw_timezone = true;
calendar.set(Calendar.DST_OFFSET, 0);
offset = simpleOffset.intValue();
}
else
{
for (int j = 0; j < zoneCount; j++)
{
String[] strings = zoneStrings[j];
int k;
for (k = 0; k < strings.length; ++k)
{
if (dateStr.startsWith(strings[k], index))
break;
}
if (k != strings.length)
{
found_zone = true;
saw_timezone = true;
TimeZone tz = TimeZone.getTimeZone (strings[0]);
// Check if it's a DST zone or ordinary
if(k == 3 || k == 4)
calendar.set (Calendar.DST_OFFSET, tz.getDSTSavings());
else
calendar.set (Calendar.DST_OFFSET, 0);
offset = tz.getRawOffset ();
pos.setIndex(index + strings[k].length());
break;
}
}
}
if (! found_zone)
{
pos.setErrorIndex(pos.getIndex());
return null;
}
break;
default:
pos.setErrorIndex(pos.getIndex());
return null;
}
// Compute the value we should assign to the field.
int value;
int index = -1;
if (is_numeric)
{
numberFormat.setMinimumIntegerDigits(fmt_count);
if (limit_digits)
numberFormat.setMaximumIntegerDigits(fmt_count);
if (maybe2DigitYear)
index = pos.getIndex();
Number n = numberFormat.parse(dateStr, pos);
if (pos == null || ! (n instanceof Long))
return null;
value = n.intValue() + offset;
}
else if (set1 != null)
{
index = pos.getIndex();
int i;
boolean found = false;
for (i = offset; i < set1.length; ++i)
{
if (set1[i] != null)
if (dateStr.toUpperCase().startsWith(set1[i].toUpperCase(),
index))
{
found = true;
pos.setIndex(index + set1[i].length());
break;
}
}
if (!found && set2 != null)
{
for (i = offset; i < set2.length; ++i)
{
if (set2[i] != null)
if (dateStr.toUpperCase().startsWith(set2[i].toUpperCase(),
index))
{
found = true;
pos.setIndex(index + set2[i].length());
break;
}
}
}
if (!found)
{
pos.setErrorIndex(index);
return null;
}
value = i;
}
else
value = offset;
if (maybe2DigitYear)
{
// Parse into default century if the numeric year string has
// exactly 2 digits.
int digit_count = pos.getIndex() - index;
if (digit_count == 2)
{
is2DigitYear = true;
value += defaultCentury;
}
}
// Assign the value and move on.
calendar.set(calendar_field, value);
}
if (is2DigitYear)
{
// Apply the 80-20 heuristic to dermine the full year based on
// defaultCenturyStart.
int year = calendar.get(Calendar.YEAR);
if (calendar.getTime().compareTo(defaultCenturyStart) < 0)
calendar.set(Calendar.YEAR, year + 100);
}
if (! saw_timezone)
{
// Use the real rules to determine whether or not this
// particular time is in daylight savings.
calendar.clear (Calendar.DST_OFFSET);
calendar.clear (Calendar.ZONE_OFFSET);
}
return calendar.getTime();
}
catch (IllegalArgumentException x)
{
pos.setErrorIndex(pos.getIndex());
return null;
}
}
|
diff --git a/test/unit/src/net/colar/netbeans/fan/test/FantomStructureAnalyzerTest.java b/test/unit/src/net/colar/netbeans/fan/test/FantomStructureAnalyzerTest.java
index 9aaf930..5039798 100644
--- a/test/unit/src/net/colar/netbeans/fan/test/FantomStructureAnalyzerTest.java
+++ b/test/unit/src/net/colar/netbeans/fan/test/FantomStructureAnalyzerTest.java
@@ -1,91 +1,91 @@
/*
* Thibaut Colar Mar 10, 2010
*/
package net.colar.netbeans.fan.test;
import java.io.File;
import java.util.List;
import net.colar.netbeans.fan.FanParserTask;
import net.colar.netbeans.fan.structure.FanStructureAnalyzer;
import net.jot.testing.JOTTester;
import org.netbeans.modules.parsing.api.Snapshot;
/**
* Test the structure analyzer
*
* @author thibautc
*/
public class FantomStructureAnalyzerTest extends FantomCSLTest
{
public void cslTest() throws Throwable
{
testAllFanFilesUnder(FantomParserTest.FAN_HOME + "/examples/");
testAllFanFilesUnder(FantomParserTest.FAN_HOME + "/src/");
}
private static void testAllFanFilesUnder(String folderPath) throws Exception
{
List<File> files = NBTestUtilities.listAllFanFilesUnder(folderPath);
for (File f : files)
{
Exception e = null;
try
{
analyzeFile(f);
} catch (Exception ex)
{
e = ex;
e.printStackTrace();
}
JOTTester.checkIf("StructureAnalysis of: " + f.getAbsolutePath(), e == null);
}
}
public static FanParserTask analyzeFile(File file) throws Exception
{
Snapshot snap = NBTestUtilities.fileToSnapshot(file);
FanParserTask task = new FanParserTask(snap);
task.parse();
- task.parseScope();
+ task.parseGlobalScope();
if (task.getParsingResult().hasErrors())
{
for (org.netbeans.modules.csl.api.Error err : task.getDiagnostics())
{
System.err.println("Error: " + err);
throw new Exception("Parsing errors");
}
}
FanStructureAnalyzer analyzer = new FanStructureAnalyzer();
analyzer.scan(task);
if (task.getDiagnostics().size() > 0)
{
boolean hasErr = false;
for (org.netbeans.modules.csl.api.Error err : task.getDiagnostics())
{
String desc = err.getDisplayName();
// Avoid known false positives (we don't index java.awt & javax.swing by default)
if (!desc.contains("java.awt") && !desc.contains("javax.swing") && !desc.contains("javax.script") && !desc.contains("ScriptEngine"))
{
hasErr = true;
System.err.println("Error: " + err);
}
}
if (hasErr)
{
throw new Exception("Structure analyzer errors");
}
}
return task;
}
public static void main(String[] args)
{
try
{
JOTTester.singleTest(new FantomStructureAnalyzerTest(), false);
} catch (Throwable t)
{
t.printStackTrace();
}
}
}
| true | true | public static FanParserTask analyzeFile(File file) throws Exception
{
Snapshot snap = NBTestUtilities.fileToSnapshot(file);
FanParserTask task = new FanParserTask(snap);
task.parse();
task.parseScope();
if (task.getParsingResult().hasErrors())
{
for (org.netbeans.modules.csl.api.Error err : task.getDiagnostics())
{
System.err.println("Error: " + err);
throw new Exception("Parsing errors");
}
}
FanStructureAnalyzer analyzer = new FanStructureAnalyzer();
analyzer.scan(task);
if (task.getDiagnostics().size() > 0)
{
boolean hasErr = false;
for (org.netbeans.modules.csl.api.Error err : task.getDiagnostics())
{
String desc = err.getDisplayName();
// Avoid known false positives (we don't index java.awt & javax.swing by default)
if (!desc.contains("java.awt") && !desc.contains("javax.swing") && !desc.contains("javax.script") && !desc.contains("ScriptEngine"))
{
hasErr = true;
System.err.println("Error: " + err);
}
}
if (hasErr)
{
throw new Exception("Structure analyzer errors");
}
}
return task;
}
| public static FanParserTask analyzeFile(File file) throws Exception
{
Snapshot snap = NBTestUtilities.fileToSnapshot(file);
FanParserTask task = new FanParserTask(snap);
task.parse();
task.parseGlobalScope();
if (task.getParsingResult().hasErrors())
{
for (org.netbeans.modules.csl.api.Error err : task.getDiagnostics())
{
System.err.println("Error: " + err);
throw new Exception("Parsing errors");
}
}
FanStructureAnalyzer analyzer = new FanStructureAnalyzer();
analyzer.scan(task);
if (task.getDiagnostics().size() > 0)
{
boolean hasErr = false;
for (org.netbeans.modules.csl.api.Error err : task.getDiagnostics())
{
String desc = err.getDisplayName();
// Avoid known false positives (we don't index java.awt & javax.swing by default)
if (!desc.contains("java.awt") && !desc.contains("javax.swing") && !desc.contains("javax.script") && !desc.contains("ScriptEngine"))
{
hasErr = true;
System.err.println("Error: " + err);
}
}
if (hasErr)
{
throw new Exception("Structure analyzer errors");
}
}
return task;
}
|
diff --git a/src/main/java/eu/kyotoproject/kafannotator/AnnotatorFrame.java b/src/main/java/eu/kyotoproject/kafannotator/AnnotatorFrame.java
index 903da0e..8d951d0 100644
--- a/src/main/java/eu/kyotoproject/kafannotator/AnnotatorFrame.java
+++ b/src/main/java/eu/kyotoproject/kafannotator/AnnotatorFrame.java
@@ -1,3642 +1,3644 @@
package eu.kyotoproject.kafannotator;
import eu.kyotoproject.kaf.*;
import eu.kyotoproject.kafannotator.io.*;
import eu.kyotoproject.kafannotator.objects.Lexicon;
import eu.kyotoproject.kafannotator.objects.WordTag;
import eu.kyotoproject.kafannotator.sensetags.MostCommonSubsumer;
import eu.kyotoproject.kafannotator.tableware.AnnotationTable;
import eu.kyotoproject.kafannotator.tableware.AnnotationTableModel;
import eu.kyotoproject.kafannotator.tableware.CacheData;
import eu.kyotoproject.kafannotator.tableware.TableSettings;
import eu.kyotoproject.kafannotator.triple.TagToTriples;
import eu.kyotoproject.kafannotator.triple.TripleConfig;
import eu.kyotoproject.kafannotator.util.Colors;
import eu.kyotoproject.kafannotator.util.Util;
import vu.tripleevaluation.objects.Triple;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Created by IntelliJ IDEA.
* User: kyoto
* Date: Aug 5, 2010
* Time: 4:51:57 PM
* To change this template use File | Settings | File Templates.
* This file is part of KafAnnotator.
KafAnnotator 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.
KafAnnotator 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 KafAnnotator. If not, see <http://www.gnu.org/licenses/>.
*/
public class AnnotatorFrame extends JFrame
{
static public AnnotatorFrame instance;
static boolean OPINION = false;
static boolean SYNSET = false;
public static String RESOURCESFOLDER = "../resources";
public static String TripleCONFIGFILE = RESOURCESFOLDER+"/triple.cfg";
public static String TAGSETFILE = RESOURCESFOLDER+"/tagset.txt";
public static String LEXICONFILE = RESOURCESFOLDER+"/taglexicon.xml";
public static String LOCATIONFILE = RESOURCESFOLDER+"/locations.xml";
public static String THETAGFILE = "";
public static ArrayList<String> theTag1Set;
public static ArrayList<String> theTag2Set;
public static ArrayList<String> theTag3Set;
public static ArrayList<String> theTag4Set;
public static ArrayList<String> theTag5Set;
public static ArrayList<String> theTag6Set;
public static ArrayList<String> theTag7Set;
public static ArrayList<String> theTag8Set;
public static Lexicon tagLexicon;
public static TableSettings tableSettings;
static public String inputName;
ArrayList<WordTag> taggedWordList;
public KafSaxParser parser;
ArrayList<CacheData> cache;
ArrayList<CacheData> cacheBu;
TripleConfig TripleConfig;
public String clipboardTag;
public Integer clipboardTagId;
JMenuBar menuButtons;
JMenu fileMenu;
JMenuItem openMenuItem;
JMenuItem readTagFileMenuItem;
JMenuItem readTagSetMenuItem;
JMenuItem readLexiconMenuItem;
JMenu saveAsMenu;
JMenuItem saveLexiconAsMenuItem;
JMenuItem saveTagMenuItem;
JMenuItem saveTagAsMenuItem;
JMenuItem saveTrainMenuItem;
JMenuItem convertTagsToTriples;
JMenuItem outputMostCommonSubsumer;
JMenuItem quitMenuItem;
JMenu tag1Menu;
JMenu tag1TokenMenu;
JMenu tag1LemmaMenu;
JMenu tag1ConstituentMenu;
JMenu tag1SentenceMenu;
JMenuItem newTag1MenuItem;
JMenu tag2Menu;
JMenu tag2TokenMenu;
JMenu tag2LemmaMenu;
JMenu tag2ConstituentMenu;
JMenu tag2SentenceMenu;
JMenuItem newTag2MenuItem;
JMenu tag3Menu;
JMenu tag3TokenMenu;
JMenu tag3LemmaMenu;
JMenu tag3ConstituentMenu;
JMenu tag3SentenceMenu;
JMenuItem newTag3MenuItem;
JMenu tag4Menu;
JMenu tag4TokenMenu;
JMenu tag4LemmaMenu;
JMenu tag4ConstituentMenu;
JMenu tag4SentenceMenu;
JMenuItem newTag4MenuItem;
JMenu tag5Menu;
JMenu tag5TokenMenu;
JMenu tag5LemmaMenu;
JMenu tag5ConstituentMenu;
JMenu tag5SentenceMenu;
JMenuItem newTag5MenuItem;
JMenu tag6Menu;
JMenu tag6TokenMenu;
JMenu tag6LemmaMenu;
JMenu tag6ConstituentMenu;
JMenu tag6SentenceMenu;
JMenuItem newTag6MenuItem;
JMenu tag7Menu;
JMenu tag7TokenMenu;
JMenu tag7LemmaMenu;
JMenu tag7ConstituentMenu;
JMenu tag7SentenceMenu;
JMenuItem newTag7MenuItem;
JMenu tag8Menu;
JMenu tag8TokenMenu;
JMenu tag8LemmaMenu;
JMenu tag8ConstituentMenu;
JMenu tag8SentenceMenu;
JMenuItem newTag8MenuItem;
JMenu lexiconMenu;
JMenuItem updateLexiconMenuItem;
JMenuItem saveLexiconMenuItem;
JMenu otherMenu;
JMenuItem confirmMenuItem;
JMenuItem unconfirmMenuItem;
JMenuItem undoMenuItem;
JMenuItem removeAllTagsMenuItem;
JMenu searchMenu;
JMenuItem searchWordMenuItem;
JMenuItem searchTagMenuItem;
JMenuItem searchLastTagMenuItem;
JMenuItem searchWordAgainMenuItem;
JMenuItem searchTagAgainMenuItem;
JMenuItem searchNotDoneMenuItem;
String lastTag = "";
String lastWord = "word";
JPanel contentPanel;
AnnotationTable table;
JPanel messagePanel;
JTextArea fullTextField;
JTextField kafFileField;
JTextField tagFileField;
JTextField tagSetFileField;
JTextField messageField;
JLabel fullTextLabel;
JLabel kafFileLabel;
JLabel tagFileLabel;
JLabel tagSetFileLabel;
JLabel messageLabel;
static public AnnotatorFrame getInstance(TableSettings settings) {
if (instance == null) {
instance = new AnnotatorFrame(settings);
}
return instance;
}
public AnnotatorFrame (TableSettings settings) {
File resource = new File (RESOURCESFOLDER);
if (!resource.exists()) {
resource.mkdir();
}
File locations = new File (LOCATIONFILE);
if (!locations.exists()) {
try {
locations.createNewFile();
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
tableSettings = settings;
cache = new ArrayList<CacheData>();
cacheBu = new ArrayList<CacheData>();
parser = new KafSaxParser();
tagLexicon = new Lexicon();
tagLexicon.parseFile(LEXICONFILE);
TripleConfig = new TripleConfig(TripleCONFIGFILE);
theTag1Set = new ArrayList<String>();
theTag2Set = new ArrayList<String>();
theTag3Set = new ArrayList<String>();
theTag4Set = new ArrayList<String>();
theTag5Set = new ArrayList<String>();
theTag6Set = new ArrayList<String>();
theTag7Set = new ArrayList<String>();
theTag8Set = new ArrayList<String>();
clipboardTag = "";
clipboardTagId = -1;
inputName = "";
/// Message field
messagePanel = new JPanel();
messagePanel.setMinimumSize(new Dimension(400, 320));
messagePanel.setPreferredSize(new Dimension(400, 320));
messagePanel.setMaximumSize(new Dimension(400, 320));
messageLabel = new JLabel("Messages:");
messageLabel.setMinimumSize(new Dimension(80, 25));
messageLabel.setPreferredSize(new Dimension(80, 25));
messageField = new JTextField();
messageField.setEditable(false);
messageField.setMinimumSize(new Dimension(300, 25));
messageField.setPreferredSize(new Dimension(300, 25));
messageField.setMaximumSize(new Dimension(400, 30));
fullTextLabel = new JLabel("Text:");
fullTextLabel.setMinimumSize(new Dimension(80, 25));
fullTextLabel.setPreferredSize(new Dimension(80, 25));
fullTextField = new JTextArea();
fullTextField.setEditable(false);
fullTextField.setBackground(Colors.BackGroundColor);
+/*
fullTextField.setMinimumSize(new Dimension(300, 200));
fullTextField.setPreferredSize(new Dimension(300, 200));
fullTextField.setMaximumSize(new Dimension(400, 200));
+*/
fullTextField.setLineWrap(true);
fullTextField.setWrapStyleWord(true);
fullTextField.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
switch(e.getModifiers()) {
case InputEvent.BUTTON3_MASK: {
String word = fullTextField.getSelectedText();
table.searchForString(AnnotationTableModel.ROWWORDTOKEN, word);
}
}
}
});
JScrollPane scrollableTextArea = new JScrollPane (fullTextField,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollableTextArea.setMinimumSize(new Dimension(300, 200));
scrollableTextArea.setPreferredSize(new Dimension(300, 200));
scrollableTextArea.setMaximumSize(new Dimension(400, 200));
kafFileLabel = new JLabel("KAF file:");
kafFileLabel.setMinimumSize(new Dimension(80, 25));
kafFileLabel.setPreferredSize(new Dimension(80, 25));
kafFileField = new JTextField();
kafFileField.setEditable(false);
kafFileField.setBackground(Colors.BackGroundColor);
kafFileField.setMinimumSize(new Dimension(300, 25));
kafFileField.setPreferredSize(new Dimension(300, 25));
kafFileField.setMaximumSize(new Dimension(400, 30));
tagFileLabel = new JLabel("TAG file:");
tagFileLabel.setMinimumSize(new Dimension(80, 25));
tagFileLabel.setPreferredSize(new Dimension(80, 25));
tagFileField = new JTextField();
tagFileField.setEditable(false);
tagFileField.setBackground(Colors.BackGroundColor);
tagFileField.setMinimumSize(new Dimension(300, 25));
tagFileField.setPreferredSize(new Dimension(300, 25));
tagFileField.setMaximumSize(new Dimension(400, 30));
tagSetFileLabel = new JLabel("TAG set:");
tagSetFileLabel.setMinimumSize(new Dimension(80, 25));
tagSetFileLabel.setPreferredSize(new Dimension(80, 25));
tagSetFileField = new JTextField();
tagSetFileField.setEditable(false);
tagSetFileField.setBackground(Colors.BackGroundColor);
tagSetFileField.setMinimumSize(new Dimension(300, 25));
tagSetFileField.setPreferredSize(new Dimension(300, 25));
tagSetFileField.setMaximumSize(new Dimension(400, 30));
messagePanel.setLayout(new GridBagLayout());
messagePanel.add(fullTextLabel, new GridBagConstraints(0, 0, 1, 1, 0, 0
,GridBagConstraints.NORTH, GridBagConstraints.NONE, new Insets(10, 1, 1, 1), 0, 0));
messagePanel.add(scrollableTextArea, new GridBagConstraints(1, 0, 1, 1, 0.3, 0.3
, GridBagConstraints.NORTH, GridBagConstraints.BOTH, new Insets(10, 1, 1, 1), 0, 0));
messagePanel.add(messageLabel, new GridBagConstraints(0, 1, 1, 1, 0, 0
,GridBagConstraints.NORTH, GridBagConstraints.NONE, new Insets(10, 1, 1, 1), 0, 0));
messagePanel.add(messageField, new GridBagConstraints(1, 1, 1, 1, 0.3, 0.3
, GridBagConstraints.NORTH, GridBagConstraints.BOTH, new Insets(10, 1, 1, 1), 0, 0));
messagePanel.add(kafFileLabel, new GridBagConstraints(0, 2, 1, 1, 0, 0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(1, 1, 1, 1), 0, 0));
messagePanel.add(kafFileField, new GridBagConstraints(1, 2, 1, 1, 0.3, 0.3
, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(1, 1, 1, 1), 0, 0));
messagePanel.add(tagFileLabel, new GridBagConstraints(0, 3, 1, 1, 0, 0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(1, 1, 1, 1), 0, 0));
messagePanel.add(tagFileField, new GridBagConstraints(1, 3, 1, 1, 0.3, 0.3
, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(1, 1, 1, 1), 0, 0));
messagePanel.add(tagSetFileLabel, new GridBagConstraints(0, 4, 1, 1, 0, 0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(1, 1, 1, 1), 0, 0));
messagePanel.add(tagSetFileField, new GridBagConstraints(1, 4, 1, 1, 0.3, 0.3
,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(1, 1, 1, 1), 0, 0));
/// Menus
menuButtons = new JMenuBar();
fileMenu = new JMenu("File");
fileMenu.setMnemonic('f');
////
openMenuItem = new JMenuItem("Open KAF file",'o');
openMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_loadKafFile();
setCursor(current_cursor);
}
});
fileMenu.add(openMenuItem);
readTagFileMenuItem = new JMenuItem("Load TAG file",'l');
readTagFileMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_loadTagFile();
setCursor(current_cursor);
}
});
fileMenu.add(readTagFileMenuItem);
readTagSetMenuItem = new JMenuItem("Load TAG set", 't');
readTagSetMenuItem.setMnemonic('t');
readTagSetMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_readTagSet();
setCursor(current_cursor);
}
});
fileMenu.add(readTagSetMenuItem);
readLexiconMenuItem = new JMenuItem("Load lexicon file", 'x');
readLexiconMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_readLexicon();
setCursor(current_cursor);
}
});
fileMenu.add(readLexiconMenuItem);
////
saveTagMenuItem = new JMenuItem("Save tagging",'s');
saveTagMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
int ok = -1;
ok = DO_saveTagFile();
DO_saveLexiconFile();
if (ok==0) {
messageField.setText("Tagging data saved");
}
else {
messageField.setText("Warning! Tagging data NOT saved");
}
setCursor(current_cursor);
}
});
fileMenu.add(saveTagMenuItem);
////////////////////////////////////////
saveAsMenu = new JMenu("Save as");
saveAsMenu.setMnemonic('a');
saveTagAsMenuItem = new JMenuItem("Tagging",'t');
saveTagAsMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_saveTagFileAs();
setCursor(current_cursor);
}
});
saveAsMenu.add(saveTagAsMenuItem);
saveLexiconAsMenuItem = new JMenuItem("Lexicon",'l');
saveLexiconAsMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_saveLexiconFileAs();
setCursor(current_cursor);
}
});
saveAsMenu.add(saveLexiconAsMenuItem);
fileMenu.add(saveAsMenu);
////
saveTrainMenuItem = new JMenuItem("Export tags to train format",'e');
saveTrainMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_saveTrainFile();
setCursor(current_cursor);
}
});
fileMenu.add(saveTrainMenuItem);
convertTagsToTriples = new JMenuItem("Export to Triples",'e');
convertTagsToTriples.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_exportToTriples();
setCursor(current_cursor);
}
});
fileMenu.add(convertTagsToTriples);
outputMostCommonSubsumer = new JMenuItem("Export wordnet classes",'w');
outputMostCommonSubsumer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_exportMostCommonSubsumers();
setCursor(current_cursor);
}
});
fileMenu.add(outputMostCommonSubsumer);
quitMenuItem = new JMenuItem("Quit",'q');
quitMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (DO_checkSave()==2) {
System.exit(0);
}
}
});
fileMenu.add(quitMenuItem);
menuButtons.add(fileMenu);
////////////////////////////////////////
searchMenu = new JMenu("Search");
searchMenu.setMnemonic('s');
////
searchWordMenuItem = new JMenuItem("Word",'w');
searchWordMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_searchWord();
setCursor(current_cursor);
}
});
searchMenu.add(searchWordMenuItem);
////
searchLastTagMenuItem = new JMenuItem("Last tag",'l');
searchLastTagMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_searchLastTag();
setCursor(current_cursor);
}
});
searchMenu.add(searchLastTagMenuItem);
searchTagMenuItem = new JMenuItem("Tag",'t');
searchTagMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_searchTag();
setCursor(current_cursor);
}
});
searchMenu.add(searchTagMenuItem);
searchWordAgainMenuItem = new JMenuItem("Next Word",'n');
searchWordAgainMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_searchWordAgain();
setCursor(current_cursor);
}
});
searchMenu.add(searchWordAgainMenuItem);
////
searchTagAgainMenuItem = new JMenuItem("Next Tag",'x');
searchTagAgainMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_searchTagAgain();
setCursor(current_cursor);
}
});
searchMenu.add(searchTagAgainMenuItem);
////
searchNotDoneMenuItem = new JMenuItem("No Confirm",'c');
searchNotDoneMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_notDone();
setCursor(current_cursor);
}
});
searchMenu.add(searchNotDoneMenuItem);
menuButtons.add(searchMenu);
/////////////////////////////////////////////////
otherMenu = new JMenu("Other");
otherMenu.setMnemonic('o');
////
confirmMenuItem = new JMenuItem("Do Confirm",'d');
confirmMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor(Cursor.WAIT_CURSOR));
DO_Selected();
setCursor(current_cursor);
}
});
otherMenu.add(confirmMenuItem);
////
unconfirmMenuItem = new JMenuItem("Undo Confirm",'u');
unconfirmMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_Unselected();
setCursor(current_cursor);
}
});
otherMenu.add(unconfirmMenuItem);
removeAllTagsMenuItem = new JMenuItem("Remove all annotations",'r');
removeAllTagsMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_unTagAllTokens();
setCursor(current_cursor);
}
});
otherMenu.add(removeAllTagsMenuItem);
undoMenuItem = new JMenuItem("Undo",'u');
// undoMenuItem.setMaximumSize(new Dimension(70, 150));
// undoMenuItem.setBorder(BorderFactory.createLineBorder(Color.gray));
undoMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_undo();
setCursor(current_cursor);
}
});
otherMenu.add(undoMenuItem);
menuButtons.add(otherMenu);
////////////////////////////////////////////////////////
////
/////////////////////
tag1Menu = new JMenu("Tag level 1");
tag1Menu.setMnemonic('1');
tag1TokenMenu = new JMenu("Tag tokens");
tag1TokenMenu.setMnemonic('t');
tag1Menu.add(tag1TokenMenu);
tag1LemmaMenu = new JMenu("Tag types");
tag1LemmaMenu.setMnemonic('y');
tag1Menu.add(tag1LemmaMenu);
tag1ConstituentMenu = new JMenu("Tag constituent");
tag1ConstituentMenu.setMnemonic('c');
tag1Menu.add(tag1ConstituentMenu);
tag1SentenceMenu = new JMenu("Tag sentence");
tag1SentenceMenu.setMnemonic('s');
tag1Menu.add(tag1SentenceMenu);
// popup.add(tag1Menu); // just trying
JMenuItem untagItem = new JMenuItem ("UNTAG", 'u');
untagItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_unTagTokens(1);
setCursor(current_cursor);
}
});
tag1Menu.add(untagItem);
JMenuItem mergeTagIdsItem = new JMenuItem ("Merge Tag Ids", 'm');
mergeTagIdsItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_mergeTagIds(1);
setCursor(current_cursor);
}
});
tag1Menu.add(mergeTagIdsItem);
JMenuItem separateTagIdsItem = new JMenuItem ("Separate Tag Ids", 's');
separateTagIdsItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_separateTagIds(1);
setCursor(current_cursor);
}
});
tag1Menu.add(separateTagIdsItem);
JMenuItem editTagIdsItem = new JMenuItem ("Edit Tag Id", 'e');
editTagIdsItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_editTagIds(1);
setCursor(current_cursor);
}
});
tag1Menu.add(editTagIdsItem);
JMenuItem copyTagItem = new JMenuItem ("Copy Tag & Id", 'c');
copyTagItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_copyTag(1);
setCursor(current_cursor);
}
});
tag1Menu.add(copyTagItem);
JMenuItem pastTagItem = new JMenuItem ("Past Tag & Id", 'p');
pastTagItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_pastTag(1);
setCursor(current_cursor);
}
});
tag1Menu.add(pastTagItem);
JMenuItem selectLexTagMenuItem = new JMenuItem("Dominant Tag",'l');
selectLexTagMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_selectLexicalTag();
setCursor(current_cursor);
}
});
tag1Menu.add(selectLexTagMenuItem);
newTag1MenuItem = new JMenuItem("Add Tag",'a');
newTag1MenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_makeNewTag1();
setCursor(current_cursor);
}
});
tag1Menu.add(newTag1MenuItem);
menuButtons.add(tag1Menu);
//////////////////////////////////
tag2Menu = new JMenu("Tag level 2");
tag2Menu.setMnemonic('2');
tag2TokenMenu = new JMenu("Tag tokens");
tag2TokenMenu.setMnemonic('t');
tag2Menu.add(tag2TokenMenu);
tag2LemmaMenu = new JMenu("Tag types");
tag2LemmaMenu.setMnemonic('y');
tag2Menu.add(tag2LemmaMenu);
tag2ConstituentMenu = new JMenu("Tag constituent");
tag2ConstituentMenu.setMnemonic('c');
tag2Menu.add(tag2ConstituentMenu);
tag2SentenceMenu = new JMenu("Tag sentence");
tag2SentenceMenu.setMnemonic('s');
tag2Menu.add(tag2SentenceMenu);
JMenuItem untagItem2 = new JMenuItem ("UNTAG", 'u');
untagItem2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_unTagTokens(2);
setCursor(current_cursor);
}
});
tag2Menu.add(untagItem2);
JMenuItem mergeTagIdsItem2 = new JMenuItem ("Merge Tag Ids", 'm');
mergeTagIdsItem2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_mergeTagIds(2);
setCursor(current_cursor);
}
});
tag2Menu.add(mergeTagIdsItem2);
JMenuItem separateTagIdsItem2 = new JMenuItem ("Separate Tag Ids", 's');
separateTagIdsItem2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_separateTagIds(2);
setCursor(current_cursor);
}
});
tag2Menu.add(separateTagIdsItem2);
JMenuItem editTagIdsItem2 = new JMenuItem ("Edit Tag Id", 'e');
editTagIdsItem2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_editTagIds(2);
setCursor(current_cursor);
}
});
tag2Menu.add(editTagIdsItem2);
JMenuItem copyTagItem2 = new JMenuItem ("Copy Tag & Id", 'c');
copyTagItem2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_copyTag(2);
setCursor(current_cursor);
}
});
tag2Menu.add(copyTagItem2);
JMenuItem pastTagItem2 = new JMenuItem ("Past Tag & Id", 'p');
pastTagItem2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_pastTag(2);
setCursor(current_cursor);
}
});
tag2Menu.add(pastTagItem2);
newTag2MenuItem = new JMenuItem("Add Tag",'a');
newTag2MenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_makeNewTag2();
setCursor(current_cursor);
}
});
tag2Menu.add(newTag2MenuItem);
if (!tableSettings.hideTag2) {
menuButtons.add(tag2Menu);
}
/////////////////#################
tag3Menu = new JMenu("Tag level 3");
tag3Menu.setMnemonic('3');
tag3TokenMenu = new JMenu("Tag tokens");
tag3Menu.add(tag3TokenMenu);
tag3LemmaMenu = new JMenu("Tag types");
tag3LemmaMenu.setMnemonic('y');
tag3Menu.add(tag3LemmaMenu);
tag3ConstituentMenu = new JMenu("Tag constituent");
tag3ConstituentMenu.setMnemonic('c');
tag3Menu.add(tag3ConstituentMenu);
tag3SentenceMenu = new JMenu("Tag sentence");
tag3SentenceMenu.setMnemonic('s');
tag3Menu.add(tag3SentenceMenu);
JMenuItem untagItem3 = new JMenuItem ("UNTAG", 'u');
untagItem3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_unTagTokens(3);
setCursor(current_cursor);
}
});
tag3Menu.add(untagItem3);
JMenuItem mergeTagIdsItem3 = new JMenuItem ("Merge Tag Ids", 'm');
mergeTagIdsItem3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_mergeTagIds(3);
setCursor(current_cursor);
}
});
tag3Menu.add(mergeTagIdsItem3);
JMenuItem separateTagIdsItem3 = new JMenuItem ("Separate Tag Ids", 's');
separateTagIdsItem3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_separateTagIds(3);
setCursor(current_cursor);
}
});
tag3Menu.add(separateTagIdsItem3);
JMenuItem editTagIdsItem3 = new JMenuItem ("Edit Tag Id", 'e');
editTagIdsItem3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_editTagIds(3);
setCursor(current_cursor);
}
});
tag3Menu.add(editTagIdsItem3);
JMenuItem copyTagItem3 = new JMenuItem ("Copy Tag & Id", 'c');
copyTagItem3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_copyTag(3);
setCursor(current_cursor);
}
});
tag3Menu.add(copyTagItem3);
JMenuItem pastTagItem3 = new JMenuItem ("Past Tag & Id", 'p');
pastTagItem3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_pastTag(3);
setCursor(current_cursor);
}
});
tag3Menu.add(pastTagItem3);
newTag3MenuItem = new JMenuItem("Add Tag",'a');
newTag3MenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_makeNewTag3();
setCursor(current_cursor);
}
});
tag3Menu.add(newTag3MenuItem);
if (!tableSettings.hideTag3){
menuButtons.add(tag3Menu);
}
/////////////////////
tag4Menu = new JMenu("Tag level 4");
tag4Menu.setMnemonic('4');
tag4TokenMenu = new JMenu("Tag tokens");
tag4Menu.add(tag4TokenMenu);
tag4LemmaMenu = new JMenu("Tag types");
tag4LemmaMenu.setMnemonic('y');
tag4Menu.add(tag4LemmaMenu);
tag4ConstituentMenu = new JMenu("Tag constituent");
tag4ConstituentMenu.setMnemonic('c');
tag4Menu.add(tag4ConstituentMenu);
tag4SentenceMenu = new JMenu("Tag sentence");
tag4SentenceMenu.setMnemonic('s');
tag4Menu.add(tag4SentenceMenu);
JMenuItem untagItem4 = new JMenuItem ("UNTAG", 'u');
untagItem4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_unTagTokens(4);
setCursor(current_cursor);
}
});
tag4Menu.add(untagItem4);
JMenuItem mergeTagIdsItem4 = new JMenuItem ("Merge Tag Ids", 'm');
mergeTagIdsItem4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_mergeTagIds(4);
setCursor(current_cursor);
}
});
tag4Menu.add(mergeTagIdsItem4);
JMenuItem separateTagIdsItem4 = new JMenuItem ("Separate Tag Ids", 's');
separateTagIdsItem4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_separateTagIds(4);
setCursor(current_cursor);
}
});
tag4Menu.add(separateTagIdsItem4);
JMenuItem editTagIdsItem4 = new JMenuItem ("Edit Tag Id", 'e');
editTagIdsItem4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_editTagIds(4);
setCursor(current_cursor);
}
});
tag4Menu.add(editTagIdsItem4);
JMenuItem copyTagItem4 = new JMenuItem ("Copy Tag & Id", 'c');
copyTagItem4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_copyTag(4);
setCursor(current_cursor);
}
});
tag4Menu.add(copyTagItem4);
JMenuItem pastTagItem4 = new JMenuItem ("Past Tag & Id", 'p');
pastTagItem4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_pastTag(4);
setCursor(current_cursor);
}
});
tag4Menu.add(pastTagItem4);
newTag4MenuItem = new JMenuItem("Add Tag",'a');
newTag4MenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_makeNewTag4();
setCursor(current_cursor);
}
});
tag4Menu.add(newTag4MenuItem);
if (!tableSettings.hideTag4) {
menuButtons.add(tag4Menu);
}
/////////////////#################
tag5Menu = new JMenu("Tag level 5");
tag5Menu.setMnemonic('5');
tag5TokenMenu = new JMenu("Tag tokens");
tag5Menu.add(tag5TokenMenu);
tag5LemmaMenu = new JMenu("Tag types");
tag5LemmaMenu.setMnemonic('y');
tag5Menu.add(tag5LemmaMenu);
tag5ConstituentMenu = new JMenu("Tag constituent");
tag5ConstituentMenu.setMnemonic('c');
tag5Menu.add(tag5ConstituentMenu);
tag5SentenceMenu = new JMenu("Tag sentence");
tag5SentenceMenu.setMnemonic('s');
tag5Menu.add(tag5SentenceMenu);
JMenuItem untagItem5 = new JMenuItem ("UNTAG", 'u');
untagItem5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_unTagTokens(5);
setCursor(current_cursor);
}
});
tag5Menu.add(untagItem5);
JMenuItem mergeTagIdsItem5 = new JMenuItem ("Merge Tag Ids", 'm');
mergeTagIdsItem5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_mergeTagIds(5);
setCursor(current_cursor);
}
});
tag5Menu.add(mergeTagIdsItem5);
JMenuItem separateTagIdsItem5 = new JMenuItem ("Separate Tag Ids", 's');
separateTagIdsItem5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_separateTagIds(5);
setCursor(current_cursor);
}
});
tag5Menu.add(separateTagIdsItem5);
JMenuItem editTagIdsItem5 = new JMenuItem ("Edit Tag Id", 'e');
editTagIdsItem5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_editTagIds(5);
setCursor(current_cursor);
}
});
tag5Menu.add(editTagIdsItem5);
JMenuItem copyTagItem5 = new JMenuItem ("Copy Tag & Id", 'c');
copyTagItem5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_copyTag(5);
setCursor(current_cursor);
}
});
tag5Menu.add(copyTagItem5);
JMenuItem pastTagItem5 = new JMenuItem ("Past Tag & Id", 'p');
pastTagItem5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_pastTag(5);
setCursor(current_cursor);
}
});
tag5Menu.add(pastTagItem5);
newTag5MenuItem = new JMenuItem("Add Tag",'a');
newTag5MenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_makeNewTag5();
setCursor(current_cursor);
}
});
tag5Menu.add(newTag5MenuItem);
if (!tableSettings.hideTag5) {
menuButtons.add(tag5Menu);
}
/////////////////#################
tag6Menu = new JMenu("Tag level 6");
tag6Menu.setMnemonic('6');
tag6TokenMenu = new JMenu("Tag tokens");
tag6Menu.add(tag6TokenMenu);
tag6LemmaMenu = new JMenu("Tag types");
tag6LemmaMenu.setMnemonic('y');
tag6Menu.add(tag6LemmaMenu);
tag6ConstituentMenu = new JMenu("Tag constituent");
tag6ConstituentMenu.setMnemonic('c');
tag6Menu.add(tag6ConstituentMenu);
tag6SentenceMenu = new JMenu("Tag sentence");
tag6SentenceMenu.setMnemonic('s');
tag6Menu.add(tag6SentenceMenu);
JMenuItem untagItem6 = new JMenuItem ("UNTAG", 'u');
untagItem6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_unTagTokens(6);
setCursor(current_cursor);
}
});
tag6Menu.add(untagItem6);
JMenuItem mergeTagIdsItem6 = new JMenuItem ("Merge Tag Ids", 'm');
mergeTagIdsItem6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_mergeTagIds(6);
setCursor(current_cursor);
}
});
tag6Menu.add(mergeTagIdsItem6);
JMenuItem separateTagIdsItem6 = new JMenuItem ("Separate Tag Ids", 's');
separateTagIdsItem6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_separateTagIds(6);
setCursor(current_cursor);
}
});
tag6Menu.add(separateTagIdsItem6);
JMenuItem editTagIdsItem6 = new JMenuItem ("Edit Tag Id", 'e');
editTagIdsItem6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_editTagIds(6);
setCursor(current_cursor);
}
});
tag6Menu.add(editTagIdsItem6);
JMenuItem copyTagItem6 = new JMenuItem ("Copy Tag & Id", 'c');
copyTagItem6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_copyTag(6);
setCursor(current_cursor);
}
});
tag6Menu.add(copyTagItem6);
JMenuItem pastTagItem6 = new JMenuItem ("Past Tag & Id", 'p');
pastTagItem6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_pastTag(6);
setCursor(current_cursor);
}
});
tag6Menu.add(pastTagItem6);
newTag6MenuItem = new JMenuItem("Add Tag",'a');
newTag6MenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_makeNewTag6();
setCursor(current_cursor);
}
});
tag6Menu.add(newTag6MenuItem);
if (!tableSettings.hideTag6) {
menuButtons.add(tag6Menu);
}
/////////////////#################
tag7Menu = new JMenu("Tag level 7");
tag7Menu.setMnemonic('7');
tag7TokenMenu = new JMenu("Tag tokens");
tag7Menu.add(tag7TokenMenu);
tag7LemmaMenu = new JMenu("Tag types");
tag7LemmaMenu.setMnemonic('y');
tag7Menu.add(tag7LemmaMenu);
tag7ConstituentMenu = new JMenu("Tag constituent");
tag7ConstituentMenu.setMnemonic('c');
tag7Menu.add(tag7ConstituentMenu);
tag7SentenceMenu = new JMenu("Tag sentence");
tag7SentenceMenu.setMnemonic('s');
tag7Menu.add(tag7SentenceMenu);
JMenuItem untagItem7 = new JMenuItem ("UNTAG", 'u');
untagItem6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_unTagTokens(7);
setCursor(current_cursor);
}
});
tag7Menu.add(untagItem7);
JMenuItem mergeTagIdsItem7 = new JMenuItem ("Merge Tag Ids", 'm');
mergeTagIdsItem6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_mergeTagIds(7);
setCursor(current_cursor);
}
});
tag7Menu.add(mergeTagIdsItem7);
JMenuItem separateTagIdsItem7 = new JMenuItem ("Separate Tag Ids", 's');
separateTagIdsItem6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_separateTagIds(7);
setCursor(current_cursor);
}
});
tag7Menu.add(separateTagIdsItem7);
JMenuItem editTagIdsItem7 = new JMenuItem ("Edit Tag Id", 'e');
editTagIdsItem7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_editTagIds(7);
setCursor(current_cursor);
}
});
tag7Menu.add(editTagIdsItem7);
JMenuItem copyTagItem7 = new JMenuItem ("Copy Tag & Id", 'c');
copyTagItem7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_copyTag(7);
setCursor(current_cursor);
}
});
tag7Menu.add(copyTagItem7);
JMenuItem pastTagItem7 = new JMenuItem ("Past Tag & Id", 'p');
pastTagItem7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_pastTag(7);
setCursor(current_cursor);
}
});
tag7Menu.add(pastTagItem7);
newTag7MenuItem = new JMenuItem("Add Tag",'a');
newTag7MenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_makeNewTag7();
setCursor(current_cursor);
}
});
tag7Menu.add(newTag7MenuItem);
if (!tableSettings.hideTag7) {
menuButtons.add(tag7Menu);
}
/////////////////#################
tag8Menu = new JMenu("Tag level 8");
tag8Menu.setMnemonic('8');
tag8TokenMenu = new JMenu("Tag tokens");
tag8Menu.add(tag8TokenMenu);
tag8LemmaMenu = new JMenu("Tag types");
tag8LemmaMenu.setMnemonic('y');
tag8Menu.add(tag8LemmaMenu);
tag8ConstituentMenu = new JMenu("Tag constituent");
tag8ConstituentMenu.setMnemonic('c');
tag8Menu.add(tag8ConstituentMenu);
tag8SentenceMenu = new JMenu("Tag sentence");
tag8SentenceMenu.setMnemonic('s');
tag8Menu.add(tag8SentenceMenu);
JMenuItem untagItem8 = new JMenuItem ("UNTAG", 'u');
untagItem8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_unTagTokens(8);
setCursor(current_cursor);
}
});
tag8Menu.add(untagItem8);
JMenuItem mergeTagIdsItem8 = new JMenuItem ("Merge Tag Ids", 'm');
mergeTagIdsItem8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_mergeTagIds(8);
setCursor(current_cursor);
}
});
tag8Menu.add(mergeTagIdsItem8);
JMenuItem separateTagIdsItem8 = new JMenuItem ("Separate Tag Ids", 's');
separateTagIdsItem8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_separateTagIds(8);
setCursor(current_cursor);
}
});
tag8Menu.add(separateTagIdsItem8);
JMenuItem editTagIdsItem8 = new JMenuItem ("Edit Tag Id", 'e');
editTagIdsItem8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_editTagIds(8);
setCursor(current_cursor);
}
});
tag8Menu.add(editTagIdsItem8);
JMenuItem copyTagItem8 = new JMenuItem ("Copy Tag & Id", 'c');
copyTagItem8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_copyTag(8);
setCursor(current_cursor);
}
});
tag8Menu.add(copyTagItem8);
JMenuItem pastTagItem8 = new JMenuItem ("Past Tag & Id", 'p');
pastTagItem8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_pastTag(8);
setCursor(current_cursor);
}
});
tag8Menu.add(pastTagItem8);
newTag8MenuItem = new JMenuItem("Add Tag",'a');
newTag8MenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_makeNewTag8();
setCursor(current_cursor);
}
});
tag8Menu.add(newTag8MenuItem);
if (!tableSettings.hideTag8) {
menuButtons.add(tag8Menu);
}
/// Text Area
table = new AnnotationTable(tableSettings);
///////////////////////
contentPanel = new JPanel();
setContentPane(contentPanel);
contentPanel.setLayout(new GridBagLayout());
contentPanel.add(menuButtons, new GridBagConstraints(0, 0, 1, 1, 0, 0
,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(10, 10, 10, 10), 15, 15));
contentPanel.add(table, new GridBagConstraints(0, 1, 1, 1, 0.3, 0.3
,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(10, 10, 10, 10), 0, 0));
contentPanel.add(messagePanel, new GridBagConstraints(0, 3, 1, 1, 0.3, 0.3
,GridBagConstraints.SOUTH, GridBagConstraints.HORIZONTAL, new Insets(10, 10, 10, 10), 0, 0));
}
JMenu getMenu(String c, JMenu p) {
for (int i = 0; i < p.getMenuComponentCount(); i++) {
Component comp = p.getMenuComponent(i);
// System.out.println("comp.getClass() = " + comp.getClass().getSimpleName());
if (comp.getClass().getSimpleName().equals("JMenu")) {
JMenu pItem = (JMenu) comp;
// System.out.println("pItem.getText() = " + pItem.getText());
if (pItem.getText().equals(c)) {
return pItem;
}
}
}
JMenu item = new JMenu (c);
item.setMnemonic(c.charAt(0));
p.add(item);
return item;
}
void addTagsAsTokenMenu (JMenu jmenu, ArrayList<String> tagSet, final int level) {
jmenu.removeAll();
for (int i = 0; i < tagSet.size(); i++) {
String menu = tagSet.get(i);
String [] fields = menu.split("#");
if (fields.length>1) {
JMenu tagGroupItem = new JMenu();
for (int j = 0; j < fields.length; j++) {
String tagString = fields[j].trim();
if (j==0) {
//// first level added to jmenu
tagGroupItem = getMenu(tagString, jmenu);
}
else if (j<fields.length-1) {
//// intermediate level added to previous
tagGroupItem = getMenu(tagString, tagGroupItem);
}
else {
//// final level becomes a JMenuItem
final String s = fields[j].trim();
JMenuItem tagMenuItem = new JMenuItem (s, s.charAt(0));
tagMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_applyTagToTokens(s, level);
setCursor(current_cursor);
}
});
tagGroupItem.add(tagMenuItem);
}
}
}
else {
final String s = menu;
JMenuItem tagItem = new JMenuItem (s, s.charAt(0));
tagItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_applyTagToTokens(s, level);
setCursor(current_cursor);
}
});
jmenu.add(tagItem);
}
}
}
void addTagsAsTypeMenu (JMenu jmenu, ArrayList<String> tagSet, final int level) {
jmenu.removeAll();
for (int i = 0; i < tagSet.size(); i++) {
String menu = tagSet.get(i);
String [] fields = menu.split("#");
if (fields.length>1) {
JMenu tagGroupItem = new JMenu();
for (int j = 0; j < fields.length; j++) {
String tagString = fields[j].trim();
if (j==0) {
//// first level added to jmenu
tagGroupItem = getMenu(tagString, jmenu);
}
else if (j<fields.length-1) {
//// intermediate level added to previous
tagGroupItem = getMenu(tagString, tagGroupItem);
}
else {
//// final level becomes a JMenuItem
final String s = fields[j].trim();
JMenuItem tagMenuItem = new JMenuItem (s, s.charAt(0));
tagMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_applyTagToTypes(s, level);
setCursor(current_cursor);
}
});
tagGroupItem.add(tagMenuItem);
}
}
}
else {
final String s = menu;
JMenuItem tagItem = new JMenuItem (s, s.charAt(0));
tagItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_applyTagToTypes(s, level);
setCursor(current_cursor);
}
});
jmenu.add(tagItem);
}
}
}
void addTagsAsConstituentMenu (JMenu jmenu, ArrayList<String> tagSet, final int level) {
jmenu.removeAll();
for (int i = 0; i < tagSet.size(); i++) {
String menu = tagSet.get(i);
String [] fields = menu.split("#");
if (fields.length>1) {
JMenu tagGroupItem = new JMenu();
for (int j = 0; j < fields.length; j++) {
String tagString = fields[j].trim();
if (j==0) {
//// first level added to jmenu
tagGroupItem = getMenu(tagString, jmenu);
}
else if (j<fields.length-1) {
//// intermediate level added to previous
tagGroupItem = getMenu(tagString, tagGroupItem);
}
else {
//// final level becomes a JMenuItem
final String s = fields[j].trim();
JMenuItem tagMenuItem = new JMenuItem (s, s.charAt(0));
tagMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_applyTagToConstituents(s, level);
setCursor(current_cursor);
}
});
tagGroupItem.add(tagMenuItem);
}
}
}
else {
final String s = menu;
JMenuItem tagItem = new JMenuItem (s, s.charAt(0));
tagItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_applyTagToConstituents(s, level);
setCursor(current_cursor);
}
});
jmenu.add(tagItem);
}
}
}
void addTagsAsSentenceMenu (JMenu jmenu, ArrayList<String> tagSet, final int level) {
jmenu.removeAll();
for (int i = 0; i < tagSet.size(); i++) {
String menu = tagSet.get(i);
String [] fields = menu.split("#");
if (fields.length>1) {
JMenu tagGroupItem = new JMenu();
for (int j = 0; j < fields.length; j++) {
String tagString = fields[j].trim();
if (j==0) {
//// first level added to jmenu
tagGroupItem = getMenu(tagString, jmenu);
}
else if (j<fields.length-1) {
//// intermediate level added to previous
tagGroupItem = getMenu(tagString, tagGroupItem);
}
else {
//// final level becomes a JMenuItem
final String s = fields[j].trim();
JMenuItem tagMenuItem = new JMenuItem (s, s.charAt(0));
tagMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_applyTagToSentences(s, level);
setCursor(current_cursor);
}
});
tagGroupItem.add(tagMenuItem);
}
}
}
else {
final String s = menu;
JMenuItem tagItem = new JMenuItem (s, s.charAt(0));
tagItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_applyTagToSentences(s, level);
setCursor(current_cursor);
}
});
jmenu.add(tagItem);
}
}
}
void makeTagSet1Menus () {
addTagsAsTokenMenu(tag1TokenMenu,theTag1Set, 1);
addTagsAsTypeMenu(tag1LemmaMenu,theTag1Set, 1);
addTagsAsConstituentMenu(tag1ConstituentMenu,theTag1Set, 1);
addTagsAsSentenceMenu(tag1SentenceMenu,theTag1Set, 1);
}
void makeTagSet2Menus () {
addTagsAsTokenMenu(tag2TokenMenu,theTag2Set, 2);
addTagsAsTypeMenu(tag2LemmaMenu,theTag2Set, 2);
addTagsAsConstituentMenu(tag2ConstituentMenu,theTag2Set, 2);
addTagsAsSentenceMenu(tag2SentenceMenu,theTag2Set, 2);
}
void makeTagSet3Menus () {
addTagsAsTokenMenu(tag3TokenMenu,theTag3Set, 3);
addTagsAsTypeMenu(tag3LemmaMenu,theTag3Set, 3);
addTagsAsConstituentMenu(tag3ConstituentMenu,theTag3Set, 3);
addTagsAsSentenceMenu(tag3SentenceMenu,theTag3Set, 3);
}
void makeTagSet4Menus () {
addTagsAsTokenMenu(tag4TokenMenu,theTag4Set, 4);
addTagsAsTypeMenu(tag4LemmaMenu,theTag4Set, 4);
addTagsAsConstituentMenu(tag4ConstituentMenu,theTag4Set, 4);
addTagsAsSentenceMenu(tag4SentenceMenu,theTag4Set, 4);
}
void makeTagSet5Menus () {
addTagsAsTokenMenu(tag5TokenMenu,theTag5Set, 5);
addTagsAsTypeMenu(tag5LemmaMenu,theTag5Set, 5);
addTagsAsConstituentMenu(tag5ConstituentMenu,theTag5Set, 5);
addTagsAsSentenceMenu(tag5SentenceMenu,theTag5Set, 5);
}
void makeTagSet6Menus () {
addTagsAsTokenMenu(tag6TokenMenu,theTag6Set, 6);
addTagsAsTypeMenu(tag6LemmaMenu,theTag6Set, 6);
addTagsAsConstituentMenu(tag6ConstituentMenu,theTag6Set, 6);
addTagsAsSentenceMenu(tag6SentenceMenu,theTag6Set, 6);
}
void makeTagSet7Menus () {
addTagsAsTokenMenu(tag7TokenMenu,theTag7Set, 7);
addTagsAsTypeMenu(tag7LemmaMenu,theTag7Set, 7);
addTagsAsConstituentMenu(tag7ConstituentMenu,theTag7Set, 7);
addTagsAsSentenceMenu(tag7SentenceMenu,theTag7Set, 7);
}
void makeTagSet8Menus () {
addTagsAsTokenMenu(tag8TokenMenu,theTag8Set, 8);
addTagsAsTypeMenu(tag8LemmaMenu,theTag8Set, 8);
addTagsAsConstituentMenu(tag8ConstituentMenu,theTag8Set, 8);
addTagsAsSentenceMenu(tag8SentenceMenu,theTag8Set, 8);
}
void DO_loadKafFile() {
String kafFile = selectInputFileDialog(this, ".kaf");
DO_loadKafFile(kafFile);
}
public void DO_loadKafFile(String inputFile) {
messageField.setText("");
contentPanel.remove(table);
inputName = inputFile;
if (inputName!=null && inputName.length()>0) {
kafFileField.setText(inputName);
THETAGFILE = "";
//// WE ASSUME THIS IS A KAF FILE
parser.parseFile(inputName);
fullTextField.setText(parser.getFullText());
taggedWordList= new ArrayList<WordTag>();
for (int i = 0; i < parser.kafWordFormList.size(); i++) {
KafWordForm nextWord = parser.kafWordFormList.get(i);
WordTag wordTag = null;
KafTerm kafTerm = null;
if (parser.WordFormToTerm.containsKey(nextWord.getWid())) {
String termId = parser.WordFormToTerm.get(nextWord.getWid());
//System.out.println("termId = " + termId);
kafTerm = parser.getTerm(termId);
//System.out.println("kafTerm = " + kafTerm.getTid());
}
if (kafTerm != null) {
String synset = "";
if (SYNSET) {
if (kafTerm.getSenseTags().size()>=1) {
KafSense sense = kafTerm.getSenseTags().get(0);
synset = sense.getSensecode()+":"+sense.getConfidence();
}
}
else if (OPINION) {
ArrayList<String> opinions = parser.TermToOpinions.get(kafTerm.getTid());
if (opinions!=null && opinions.size()>0) {
for (int j = 0; j < opinions.size(); j++) {
String oid = opinions.get(j);
KafOpinion kafOpinion = parser.getOpinion(oid);
for (int k = 0; k < kafOpinion.getSpansOpinionTarget().size(); k++) {
String termId = kafOpinion.getSpansOpinionTarget().get(k);
if (termId.equals(kafTerm.getTid())) {
synset = oid+":O-TARGET";
break;
}
}
for (int k = 0; k < kafOpinion.getSpansOpinionHolder().size(); k++) {
String termId = kafOpinion.getSpansOpinionHolder().get(k);
if (termId.equals(kafTerm.getTid())) {
synset = oid+":O-HOLDER";
break;
}
}
for (int k = 0; k < kafOpinion.getSpansOpinionExpression().size(); k++) {
String termId = kafOpinion.getSpansOpinionExpression().get(k);
if (termId.equals(kafTerm.getTid())) {
synset = oid+":O-"+kafOpinion.getOpinionSentiment().getPolarity();
break;
}
}
}
}
}
Integer sentenceId = Util.makeInt(nextWord.getSent());
wordTag = new WordTag(sentenceId, nextWord.getWid(), nextWord.getWf(), kafTerm.getLemma(), kafTerm.getPos(), synset, i);
}
else {
wordTag = new WordTag(0, nextWord.getWid(),nextWord.getWf(),"","","",i);
wordTag.setMark(true);
}
if (wordTag!=null) {
taggedWordList.add(wordTag);
}
}
table = new AnnotationTable(taggedWordList, tableSettings);
table.setBackground();
contentPanel.add(table, new GridBagConstraints(0, 1, 1, 1, 0.9, 0.9
,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(10, 10, 10, 10), 0, 0));
// table.theTable.printDebugData();
// table.setColumnSize();
contentPanel.repaint();
contentPanel.setVisible(true);
setContentPane(contentPanel);
this.repaint();
messageField.setText("Loaded from:"+inputName+". Nr of wordtokens="+taggedWordList.size());
table.READFILE = false;
int idx = inputName.lastIndexOf(".");
String tagFileForKafFile = inputName;
if (idx>-1) {
tagFileForKafFile = inputName.substring(0, idx)+".tag";
}
else {
tagFileForKafFile += ".tag";
}
DO_loadTagFile(tagFileForKafFile);
}
this.repaint();
}
void DO_loadTagFile() {
messageField.setText("");
if (THETAGFILE.length()==0) {
int idx = inputName.lastIndexOf(".");
if (idx>-1) {
THETAGFILE = inputName.substring(0, idx)+".tag";
THETAGFILE = selectInputFileDialog(this, THETAGFILE, ".tag");
}
else {
THETAGFILE = selectInputFileDialog(this, ".tag");
}
}
else {
THETAGFILE = selectInputFileDialog(this, THETAGFILE, ".tag");
}
DO_loadTagFile(THETAGFILE);
}
public void DO_loadTagFile(String tagFile) {
//table.init();
this.DO_unTagAllTokens();
messageField.setText("");
THETAGFILE = tagFile;
if (THETAGFILE.length()>0) {
tagFileField.setText(THETAGFILE);
int nAnnos = 0;
if (new File (THETAGFILE).exists()) {
table.READFILE = true;
if ((taggedWordList!=null) && (taggedWordList.size()>0)) {
nAnnos = table.theTable.addAnnotations(THETAGFILE);
}
else {
nAnnos = table.theTable.addJustAnnotations(THETAGFILE);
}
messageField.setText("Loaded from:"+THETAGFILE+". Nr of annotated tokens="+nAnnos);
table.READFILE = false;
}
else {
System.out.println("NO TAG FILE");
}
}
else {
messageField.setText("No tag file loaded!");
}
//table.table.setRowSorter(table.rowSorter);
//table.hideUntaggedRows();
this.repaint();
}
void DO_readLexicon() {
messageField.setText("");
LEXICONFILE = selectInputFileDialog(this,RESOURCESFOLDER, ".xml");
if (LEXICONFILE.length()>0) {
if (new File(LEXICONFILE).exists()) {
tagLexicon.parseFile(LEXICONFILE);
String txt = "Load lexicon from:"+LEXICONFILE+". Nr of entries="+tagLexicon.data.size();
messageField.setText(txt);
}
}
else {
messageField.setText("No lexicon file loaded!");
}
}
void DO_readTagSet() {
TAGSETFILE = selectInputFileDialog(this,RESOURCESFOLDER, ".txt");
DO_readTagSet(TAGSETFILE);
}
public void DO_readTagSet(String inputFile) {
messageField.setText("");
String error = "";
String level = "";
String tag = "";
int nTags = 0;
TAGSETFILE = inputFile;
if (TAGSETFILE.length()>0) {
tagSetFileField.setText(TAGSETFILE);
if (!new File(TAGSETFILE).exists()) {
theTag1Set = new ArrayList<String>();
theTag2Set = new ArrayList<String>();
theTag3Set = new ArrayList<String>();
theTag4Set = new ArrayList<String>();
theTag5Set = new ArrayList<String>();
theTag6Set = new ArrayList<String>();
theTag7Set = new ArrayList<String>();
theTag8Set = new ArrayList<String>();
String txt = "The file does not exist:"+TAGSETFILE+". Tag menus have been cleared. Please add tags manually";
messageField.setText(txt);
makeTagSet1Menus();
makeTagSet2Menus();
makeTagSet3Menus();
makeTagSet4Menus();
makeTagSet5Menus();
makeTagSet6Menus();
makeTagSet7Menus();
makeTagSet8Menus();
}
else {
try {
theTag1Set = new ArrayList<String>();
theTag2Set = new ArrayList<String>();
theTag3Set = new ArrayList<String>();
theTag4Set = new ArrayList<String>();
theTag5Set = new ArrayList<String>();
theTag6Set = new ArrayList<String>();
theTag7Set = new ArrayList<String>();
theTag8Set = new ArrayList<String>();
FileInputStream fis = new FileInputStream(TAGSETFILE);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader in = new BufferedReader(isr);
String inputLine;
while ((inputLine = in.readLine()) != null) {
String[] fields = inputLine.trim().split(";");
if (fields.length==2) {
nTags++;
level = fields[0];
tag = fields[1];
if (tag.length()>0) {
if (level.equals("1")) {
if (!theTag1Set.contains(tag)) {
theTag1Set.add(tag);
}
}
else if (level.equals("2")) {
if (!theTag2Set.contains(tag)) {
theTag2Set.add(tag);
}
}
else if (level.equals("3")) {
if (!theTag3Set.contains(tag)) {
theTag3Set.add(tag);
}
}
else if (level.equals("4")) {
if (!theTag4Set.contains(tag)) {
theTag4Set.add(tag);
}
}
else if (level.equals("5")) {
if (!theTag5Set.contains(tag)) {
theTag5Set.add(tag);
}
}
else if (level.equals("6")) {
if (!theTag6Set.contains(tag)) {
theTag6Set.add(tag);
}
}
else if (level.equals("7")) {
if (!theTag7Set.contains(tag)) {
theTag7Set.add(tag);
}
}
else if (level.equals("8")) {
if (!theTag8Set.contains(tag)) {
theTag8Set.add(tag);
}
}
}
}
}
in.close();
String txt = "Loaded tags from:"+TAGSETFILE+". Nr of tags="+nTags;
messageField.setText(txt);
makeTagSet1Menus();
makeTagSet2Menus();
makeTagSet3Menus();
makeTagSet4Menus();
makeTagSet5Menus();
makeTagSet6Menus();
makeTagSet7Menus();
makeTagSet8Menus();
}
catch (Exception eee) {
error += "\nException --"+eee.getMessage();
System.out.println(error);
}
}
}
else {
messageField.setText("No tags loaded for level 1!");
}
}
void DO_makeNewTag1() {
GetStringDialog dia = new GetStringDialog("TAG", "");
dia.setSize(250,200);
dia.pack();
dia.setVisible(true);
final String tag = dia.field.getText().trim();
if (tag.length()>0) {
if (!theTag1Set.contains(tag)) {
theTag1Set.add(tag);
DO_saveTagSetFile(TAGSETFILE);
//DO_saveTagSetFile(TAGSET1FILE, theTag1Set);
//table.initTagCombo();
makeTagSet1Menus();
}
}
}
void DO_makeNewTag2() {
GetStringDialog dia = new GetStringDialog("TAG", "");
dia.setSize(250,200);
dia.pack();
dia.setVisible(true);
final String tag = dia.field.getText().trim();
if (tag.length()>0) {
if (!theTag2Set.contains(tag)) {
theTag2Set.add(tag);
DO_saveTagSetFile(TAGSETFILE);
//DO_saveTagSetFile(TAGSET2FILE, theTag2Set);
//table.initTagCombo();
makeTagSet2Menus();
}
}
}
void DO_makeNewTag3() {
GetStringDialog dia = new GetStringDialog("TAG", "");
dia.setSize(250,200);
dia.pack();
dia.setVisible(true);
final String tag = dia.field.getText().trim();
if (tag.length()>0) {
if (!theTag3Set.contains(tag)) {
theTag3Set.add(tag);
DO_saveTagSetFile(TAGSETFILE);
//DO_saveTagSetFile(TAGSET3FILE, theTag3Set);
//table.initTagCombo();
makeTagSet3Menus();
}
}
}
void DO_makeNewTag4() {
GetStringDialog dia = new GetStringDialog("TAG", "");
dia.setSize(250,200);
dia.pack();
dia.setVisible(true);
final String tag = dia.field.getText().trim();
if (tag.length()>0) {
if (!theTag4Set.contains(tag)) {
theTag4Set.add(tag);
DO_saveTagSetFile(TAGSETFILE);
//DO_saveTagSetFile(TAGSET4FILE, theTag4Set);
//table.initTagCombo();
makeTagSet4Menus();
}
}
}
void DO_makeNewTag5() {
GetStringDialog dia = new GetStringDialog("TAG", "");
dia.setSize(250,200);
dia.pack();
dia.setVisible(true);
final String tag = dia.field.getText().trim();
if (tag.length()>0) {
if (!theTag5Set.contains(tag)) {
theTag5Set.add(tag);
DO_saveTagSetFile(TAGSETFILE);
//DO_saveTagSetFile(TAGSET5FILE, theTag5Set);
//table.initTagCombo();
makeTagSet5Menus();
}
}
}
void DO_makeNewTag6() {
GetStringDialog dia = new GetStringDialog("TAG", "");
dia.setSize(250,200);
dia.pack();
dia.setVisible(true);
final String tag = dia.field.getText().trim();
if (tag.length()>0) {
if (!theTag6Set.contains(tag)) {
theTag6Set.add(tag);
DO_saveTagSetFile(TAGSETFILE);
//DO_saveTagSetFile(TAGSET6FILE, theTag6Set);
//table.initTagCombo();
makeTagSet6Menus();
}
}
}
void DO_makeNewTag7() {
GetStringDialog dia = new GetStringDialog("TAG", "");
dia.setSize(250,200);
dia.pack();
dia.setVisible(true);
final String tag = dia.field.getText().trim();
if (tag.length()>0) {
if (!theTag7Set.contains(tag)) {
theTag7Set.add(tag);
DO_saveTagSetFile(TAGSETFILE);
//DO_saveTagSetFile(TAGSET7FILE, theTag7Set);
//table.initTagCombo();
makeTagSet7Menus();
}
}
}
void DO_makeNewTag8() {
GetStringDialog dia = new GetStringDialog("TAG", "");
dia.setSize(250,200);
dia.pack();
dia.setVisible(true);
final String tag = dia.field.getText().trim();
if (tag.length()>0) {
if (!theTag8Set.contains(tag)) {
theTag8Set.add(tag);
DO_saveTagSetFile(TAGSETFILE);
//DO_saveTagSetFile(TAGSET8FILE, theTag8Set);
//table.initTagCombo();
makeTagSet8Menus();
}
}
}
String selectInputFileDialog(JFrame parent, final String extension) {
String theFile = "";
Locations adjLoc = new Locations(LOCATIONFILE);
LocationsParser parser = new LocationsParser(LOCATIONFILE);
adjLoc.inputs = parser.input;
String inputPath = "";
if (adjLoc.inputs.size()>0) {
inputPath = ((String)adjLoc.inputs.elementAt(0)).trim();
}
JFileChooser fc = new JFileChooser(inputPath);
fc.setFileFilter(new javax.swing.filechooser.FileFilter() {
public boolean accept(File f) {
return
(
f.getName().toLowerCase().endsWith(extension) ||
f.isDirectory()
);
}
public String getDescription() {
return extension;
}
});
int returnVal = fc.showDialog(parent, "Select a file");
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
theFile = file.getPath();
if (new File (LOCATIONFILE).exists()) {
adjLoc.inputs.insertElementAt(theFile,0);
//serializations of the databases
try{
adjLoc.serialization(LOCATIONFILE);
}
catch(IOException io){
io.printStackTrace();
}
}
}
return theFile;
}
String selectInputFileDialog(JFrame parent, String inputPath, final String extension) {
File inputFile = new File (inputPath);
String theFile = "";
JFileChooser fc = new JFileChooser();
if (inputFile.isDirectory()) {
fc = new JFileChooser(inputFile);
}
else {
fc = new JFileChooser(inputFile.getParent());
} fc.setFileFilter(new javax.swing.filechooser.FileFilter() {
public boolean accept(File f) {
return
(
f.getName().toLowerCase().endsWith(extension) ||
f.isDirectory()
);
}
public String getDescription() {
return "Input file";
}
});
int returnVal = fc.showDialog(parent, "Select a file");
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
theFile = file.getPath();
}
return theFile;
}
String selectOutputFileDialog(JFrame parent, String inputPath, final String extension, final String textLabel) {
File inputFile = new File (inputPath);
String outputPath = "";
JFileChooser fc = new JFileChooser();
if (inputFile.isDirectory()) {
fc = new JFileChooser(inputFile);
}
else {
fc = new JFileChooser(inputFile.getParent());
}
fc.setDialogTitle(textLabel);
fc.setDialogType(JFileChooser.SAVE_DIALOG);
fc.setFileFilter(new javax.swing.filechooser.FileFilter() {
public boolean accept(File f) {
return (f.getName().toLowerCase().endsWith(extension) ||
f.isDirectory());
}
public String getDescription() {
return (extension);
}
});
int returnVal = fc.showSaveDialog(parent);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
outputPath = file.getAbsolutePath();
}
fc.setVisible(false);
return outputPath;
}
int DO_saveTagFile() {
messageField.setText("");
if (THETAGFILE.length()==0) {
int idx = inputName.lastIndexOf(".");
if (idx>-1) {
THETAGFILE = inputName.substring(0, idx)+".tag";
THETAGFILE = selectOutputFileDialog(this, THETAGFILE, ".tag", "Save KAF tags in file");
}
else {
THETAGFILE = selectOutputFileDialog(this, inputName, ".tag", "Save KAF tags in file");
}
}
if (THETAGFILE.length()>0) {
tagFileField.setText(THETAGFILE);
table.theTable.writeTableToTagFile(THETAGFILE);
messageField.setText("Saved to:"+THETAGFILE);
return 0;
}
return -1;
}
int DO_saveTagFileAs() {
messageField.setText("");
if (THETAGFILE.length()==0) {
int idx = inputName.lastIndexOf(".");
if (idx>-1) {
THETAGFILE = inputName.substring(0, idx)+".tag";
THETAGFILE = selectOutputFileDialog(this, THETAGFILE, ".tag", "Save KAF tags in file");
}
else {
THETAGFILE = selectOutputFileDialog(this, inputName, ".tag", "Save KAF tags in file");
}
}
else {
THETAGFILE = selectOutputFileDialog(this, THETAGFILE, ".tag","Save KAF tags in file");
}
if (THETAGFILE.length()>0) {
tagFileField.setText(THETAGFILE);
table.theTable.writeTableToTagFile(THETAGFILE);
messageField.setText("Saved to:"+THETAGFILE);
return 0;
}
return -1;
}
int DO_saveLexiconFile() {
messageField.setText("");
if (LEXICONFILE.length()==0) {
LEXICONFILE = selectOutputFileDialog(this, RESOURCESFOLDER, ".xml","Save lexicon with tags in file");
}
if (LEXICONFILE.length()>0) {
instance.tagLexicon.saveLexicon(LEXICONFILE);
String txt = "Saved to lexicon file:"+LEXICONFILE+". Nr of entries="+instance.tagLexicon.data.size();
messageField.setText(txt);
return 0;
}
return -1;
}
int DO_saveLexiconFileAs() {
messageField.setText("");
if (LEXICONFILE.length()==0) {
LEXICONFILE = selectOutputFileDialog(this, RESOURCESFOLDER, ".xml","Save lexicon with tags in file");
}
else {
LEXICONFILE = selectOutputFileDialog(this, LEXICONFILE, ".xml", "Save lexicon with tags in file");
}
if (LEXICONFILE.length()>0) {
instance.tagLexicon.saveLexicon(LEXICONFILE);
String txt = "Saved to lexicon file:"+LEXICONFILE+". Nr of entries="+instance.tagLexicon.data.size();
messageField.setText(txt);
return 0;
}
return -1;
}
void DO_saveTagSetFile(String outputFile, ArrayList<String> theTagSet) {
try {
File theFile = new File (outputFile);
if (theFile.exists()) {
String outputPath = outputFile+".bu";
File input = new File(outputFile);
input.renameTo(new File(outputPath));
}
FileOutputStream fos = new FileOutputStream(outputFile);
for (int i = 0; i < theTagSet.size(); i++) {
String s = theTagSet.get(i)+"\n";
// System.out.println("s = " + s);
fos.write(s.getBytes());
}
fos.close();
}
catch (Exception e){ e.printStackTrace();}
}
void DO_saveTagSetFile(String outputFile) {
try {
File theFile = new File (outputFile);
if (theFile.exists()) {
String outputPath = outputFile+".bu";
File input = new File(outputFile);
input.renameTo(new File(outputPath));
}
FileOutputStream fos = new FileOutputStream(outputFile);
for (int i = 0; i < theTag1Set.size(); i++) {
String s = "1;"+theTag1Set.get(i)+"\n";
fos.write(s.getBytes());
}
for (int i = 0; i < theTag2Set.size(); i++) {
String s = "2;"+theTag2Set.get(i)+"\n";
fos.write(s.getBytes());
}
for (int i = 0; i < theTag3Set.size(); i++) {
String s = "3;"+theTag3Set.get(i)+"\n";
fos.write(s.getBytes());
}
for (int i = 0; i < theTag4Set.size(); i++) {
String s = "4;"+theTag4Set.get(i)+"\n";
fos.write(s.getBytes());
}
for (int i = 0; i < theTag5Set.size(); i++) {
String s = "5;"+theTag5Set.get(i)+"\n";
fos.write(s.getBytes());
}
for (int i = 0; i < theTag6Set.size(); i++) {
String s = "6;"+theTag6Set.get(i)+"\n";
fos.write(s.getBytes());
}
for (int i = 0; i < theTag7Set.size(); i++) {
String s = "7;"+theTag7Set.get(i)+"\n";
fos.write(s.getBytes());
}
for (int i = 0; i < theTag8Set.size(); i++) {
String s = "8;"+theTag8Set.get(i)+"\n";
fos.write(s.getBytes());
}
fos.close();
}
catch (Exception e){ e.printStackTrace();}
}
void DO_saveTrainFile() {
messageField.setText("");
int idx = inputName.lastIndexOf(".");
String outputName = inputName.substring(0,idx)+".train";
table.theTable.writeTableToTrainFile(outputName);
messageField.setText("Saved to:"+outputName);
}
void DO_searchWord() {
GetStringDialog dia = new GetStringDialog("Word", lastWord);
dia.setSize(250,200);
dia.pack();
dia.setVisible(true);
lastWord = dia.field.getText();
messageField.setText(table.searchForString(AnnotationTableModel.ROWWORDTOKEN,lastWord));
}
void DO_searchWordAgain() {
messageField.setText(table.searchForString(AnnotationTableModel.ROWWORDTOKEN,lastWord));
}
void DO_searchLastTag() {
messageField.setText(table.searchForLastString(AnnotationTableModel.TAGROWS));
}
void DO_searchTag() {
GetStringDialog dia = new GetStringDialog("TAG", lastTag);
dia.setSize(250,200);
dia.pack();
dia.setVisible(true);
lastTag = dia.field.getText();
messageField.setText(table.searchForString(AnnotationTableModel.TAGROWS,lastTag));
}
void DO_searchTagAgain() {
messageField.setText(table.searchForString(AnnotationTableModel.TAGROWS,lastTag));
}
void DO_notDone() {
messageField.setText(table.searchForBoolean(AnnotationTableModel.ROWSTATUS,false));
}
void DO_applyTagToTokens(String tag, int level) {
messageField.setText("");
Integer tagId = table.theTable.generateTagId();
int [] rows = table.table.getSelectedRows();
if (rows.length>0) {
/*
for (int i = 0; i < cacheBu.size(); i++) {
CacheData cacheData = cacheBu.get(i);
System.out.println("BU cacheData.toString() = " + cacheData.toString());
}
*/
cacheBu = cache;
/*
for (int i = 0; i < cacheBu.size(); i++) {
CacheData cacheData = cacheBu.get(i);
System.out.println("BU cacheData.toString() = " + cacheData.toString());
}
*/
cache = new ArrayList<CacheData>();
for (int i = 0; i<rows.length;i++) {
int theRow = rows[i];
addRowToCache(theRow, level);
if (level==1) {
table.sorter.setValueAt(tag, theRow, AnnotationTableModel.ROWTAG1);
table.sorter.setValueAt(tagId, theRow, AnnotationTableModel.ROWTAGID1);
}
else if (level==2) {
table.sorter.setValueAt(tag, theRow, AnnotationTableModel.ROWTAG2);
table.sorter.setValueAt(tagId, theRow, AnnotationTableModel.ROWTAGID2);
}
else if (level==3) {
table.sorter.setValueAt(tag, theRow, AnnotationTableModel.ROWTAG3);
table.sorter.setValueAt(tagId, theRow, AnnotationTableModel.ROWTAGID3);
}
else if (level==4) {
table.sorter.setValueAt(tag, theRow, AnnotationTableModel.ROWTAG4);
table.sorter.setValueAt(tagId, theRow, AnnotationTableModel.ROWTAGID4);
}
else if (level==5) {
table.sorter.setValueAt(tag, theRow, AnnotationTableModel.ROWTAG5);
table.sorter.setValueAt(tagId, theRow, AnnotationTableModel.ROWTAGID5);
}
else if (level==6) {
table.sorter.setValueAt(tag, theRow, AnnotationTableModel.ROWTAG6);
table.sorter.setValueAt(tagId, theRow, AnnotationTableModel.ROWTAGID6);
}
else if (level==7) {
table.sorter.setValueAt(tag, theRow, AnnotationTableModel.ROWTAG7);
table.sorter.setValueAt(tagId, theRow, AnnotationTableModel.ROWTAGID7);
}
else if (level==8) {
table.sorter.setValueAt(tag, theRow, AnnotationTableModel.ROWTAG8);
table.sorter.setValueAt(tagId, theRow, AnnotationTableModel.ROWTAGID8);
}
}
}
/*
for (int i = 0; i < cache.size(); i++) {
CacheData cacheData = cache.get(i);
System.out.println("cache cacheData.toString() = " + cacheData.toString());
}
*/
this.repaint();
if (cache.size()==0) {
cache = cacheBu;
}
}
void DO_unTagTokens(int level) {
messageField.setText("");
int [] rows = table.table.getSelectedRows();
if (rows.length>0) {
cacheBu = cache;
cache = new ArrayList<CacheData>();
for (int i = 0; i<rows.length;i++) {
int theRow = rows[i];
String wordForm = (String) table.sorter.getValueAt(theRow, AnnotationTableModel.ROWWORDTOKEN);
String tag = (String) table.sorter.getValueAt(theRow, AnnotationTableModel.ROWTAG1);
addRowToCache(theRow, level);
if (level==1) {
tagLexicon.decrementEntry(wordForm, tag);
table.sorter.setValueAt("", theRow, AnnotationTableModel.ROWTAG1);
table.sorter.setValueAt(0, theRow, AnnotationTableModel.ROWTAGID1);
if (table.theTable.hasTagValue(theRow)) {
table.sorter.setValueAt(new Boolean(false), theRow, AnnotationTableModel.ROWSTATUS);
}
}
else if (level==2) {
table.sorter.setValueAt("", theRow, AnnotationTableModel.ROWTAG2);
table.sorter.setValueAt(0, theRow, AnnotationTableModel.ROWTAGID2);
if (table.theTable.hasTagValue(theRow)) {
table.sorter.setValueAt(new Boolean(false), theRow, AnnotationTableModel.ROWSTATUS);
}
}
else if (level==3) {
table.sorter.setValueAt("", theRow, AnnotationTableModel.ROWTAG3);
table.sorter.setValueAt(0, theRow, AnnotationTableModel.ROWTAGID3);
if (table.theTable.hasTagValue(theRow)) {
table.sorter.setValueAt(new Boolean(false), theRow, AnnotationTableModel.ROWSTATUS);
}
}
else if (level==4) {
table.sorter.setValueAt("", theRow, AnnotationTableModel.ROWTAG4);
table.sorter.setValueAt(0, theRow, AnnotationTableModel.ROWTAGID4);
if (table.theTable.hasTagValue(theRow)) {
table.sorter.setValueAt(new Boolean(false), theRow, AnnotationTableModel.ROWSTATUS);
}
}
else if (level==5) {
table.sorter.setValueAt(0, theRow, AnnotationTableModel.ROWTAGID5);
table.sorter.setValueAt("", theRow, AnnotationTableModel.ROWTAG5);
if (table.theTable.hasTagValue(theRow)) {
table.sorter.setValueAt(new Boolean(false), theRow, AnnotationTableModel.ROWSTATUS);
}
}
else if (level==6) {
table.sorter.setValueAt("", theRow, AnnotationTableModel.ROWTAG6);
table.sorter.setValueAt(0, theRow, AnnotationTableModel.ROWTAGID6);
if (table.theTable.hasTagValue(theRow)) {
table.sorter.setValueAt(new Boolean(false), theRow, AnnotationTableModel.ROWSTATUS);
}
}
else if (level==7) {
table.sorter.setValueAt("", theRow, AnnotationTableModel.ROWTAG7);
table.sorter.setValueAt(0, theRow, AnnotationTableModel.ROWTAGID7);
if (table.theTable.hasTagValue(theRow)) {
table.sorter.setValueAt(new Boolean(false), theRow, AnnotationTableModel.ROWSTATUS);
}
}
else if (level==8) {
table.sorter.setValueAt("", theRow, AnnotationTableModel.ROWTAG8);
table.sorter.setValueAt(0, theRow, AnnotationTableModel.ROWTAGID8);
if (table.theTable.hasTagValue(theRow)) {
table.sorter.setValueAt(new Boolean(false), theRow, AnnotationTableModel.ROWSTATUS);
}
}
}
this.repaint();
if (cache.size()==0) {
cache = cacheBu;
}
}
}
void DO_unTagAllTokens() {
messageField.setText("");
cacheBu = cache;
table.removeAllTags();
this.repaint();
}
void DO_mergeTagIds(int level) {
messageField.setText("");
int [] rows = table.table.getSelectedRows();
if (rows.length>0) {
cacheBu = cache;
cache = new ArrayList<CacheData>();
int theRow = rows[0];
Integer id = table.theTable.generateTagId();
if (level==1) {
id = (Integer) table.sorter.getValueAt(theRow,AnnotationTableModel.ROWTAGID1);
}
if (level==2) {
id = (Integer) table.sorter.getValueAt(theRow,AnnotationTableModel.ROWTAGID2);
}
if (level==3) {
id = (Integer) table.sorter.getValueAt(theRow,AnnotationTableModel.ROWTAGID3);
}
if (level==4) {
id = (Integer) table.sorter.getValueAt(theRow,AnnotationTableModel.ROWTAGID4);
}
if (level==5) {
id = (Integer) table.sorter.getValueAt(theRow,AnnotationTableModel.ROWTAGID5);
}
if (level==6) {
id = (Integer) table.sorter.getValueAt(theRow,AnnotationTableModel.ROWTAGID6);
}
if (level==7) {
id = (Integer) table.sorter.getValueAt(theRow,AnnotationTableModel.ROWTAGID7);
}
if (level==8) {
id = (Integer) table.sorter.getValueAt(theRow,AnnotationTableModel.ROWTAGID8);
}
for (int i = 0; i<rows.length;i++) {
theRow = rows[i];
addRowToCache(theRow, level);
if (level==1) {
table.sorter.setValueAt(id, theRow, AnnotationTableModel.ROWTAGID1);
}
else if (level==2) {
table.sorter.setValueAt(id, theRow, AnnotationTableModel.ROWTAGID2);
}
else if (level==3) {
table.sorter.setValueAt(id, theRow, AnnotationTableModel.ROWTAGID3);
}
else if (level==4) {
table.sorter.setValueAt(id, theRow, AnnotationTableModel.ROWTAGID4);
}
else if (level==5) {
table.sorter.setValueAt(id, theRow, AnnotationTableModel.ROWTAGID5);
}
else if (level==6) {
table.sorter.setValueAt(id, theRow, AnnotationTableModel.ROWTAGID6);
}
else if (level==7) {
table.sorter.setValueAt(id, theRow, AnnotationTableModel.ROWTAGID7);
}
else if (level==8) {
table.sorter.setValueAt(id, theRow, AnnotationTableModel.ROWTAGID8);
}
}
this.repaint();
if (cache.size()==0) {
cache = cacheBu;
}
}
}
void DO_separateTagIds(int level) {
messageField.setText("");
int [] rows = table.table.getSelectedRows();
if (rows.length>0) {
cacheBu = cache;
cache = new ArrayList<CacheData>();
for (int i = 0; i<rows.length;i++) {
int theRow = rows[i];
Integer id = table.theTable.generateTagId();
addRowToCache(theRow, level);
if (level==1) {
table.sorter.setValueAt(id, theRow, AnnotationTableModel.ROWTAGID1);
}
else if (level==2) {
table.sorter.setValueAt(id, theRow, AnnotationTableModel.ROWTAGID2);
}
else if (level==3) {
table.sorter.setValueAt(id, theRow, AnnotationTableModel.ROWTAGID3);
}
else if (level==4) {
table.sorter.setValueAt(id, theRow, AnnotationTableModel.ROWTAGID4);
}
else if (level==5) {
table.sorter.setValueAt(id, theRow, AnnotationTableModel.ROWTAGID5);
}
else if (level==6) {
table.sorter.setValueAt(id, theRow, AnnotationTableModel.ROWTAGID6);
}
else if (level==7) {
table.sorter.setValueAt(id, theRow, AnnotationTableModel.ROWTAGID7);
}
else if (level==8) {
table.sorter.setValueAt(id, theRow, AnnotationTableModel.ROWTAGID8);
}
}
this.repaint();
}
}
void DO_editTagIds(int level) {
messageField.setText("");
int [] rows = table.table.getSelectedRows();
if (rows.length>0) {
GetIntegerDialog dia = new GetIntegerDialog("Id", "0");
dia.setSize(250,200);
dia.pack();
dia.setVisible(true);
if (dia.DOIT) {
Integer id = null;
try {
id = Integer.parseInt(dia.field.getText());
} catch (NumberFormatException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
cacheBu = cache;
cache = new ArrayList<CacheData>();
for (int i = 0; i<rows.length;i++) {
int theRow = rows[i];
addRowToCache(theRow, level);
if (level==1) {
table.sorter.setValueAt(id, theRow, AnnotationTableModel.ROWTAGID1);
}
else if (level==2) {
table.sorter.setValueAt(id, theRow, AnnotationTableModel.ROWTAGID2);
}
else if (level==3) {
table.sorter.setValueAt(id, theRow, AnnotationTableModel.ROWTAGID3);
}
else if (level==4) {
table.sorter.setValueAt(id, theRow, AnnotationTableModel.ROWTAGID4);
}
else if (level==5) {
table.sorter.setValueAt(id, theRow, AnnotationTableModel.ROWTAGID5);
}
else if (level==6) {
table.sorter.setValueAt(id, theRow, AnnotationTableModel.ROWTAGID6);
}
else if (level==7) {
table.sorter.setValueAt(id, theRow, AnnotationTableModel.ROWTAGID7);
}
else if (level==8) {
table.sorter.setValueAt(id, theRow, AnnotationTableModel.ROWTAGID8);
}
}
this.repaint();
}
dia.dispose();
}
}
void DO_copyTag(int level) {
messageField.setText("");
int [] rows = table.table.getSelectedRows();
if (rows.length==1) {
if (level==1) {
this.clipboardTag = (String) table.sorter.getValueAt(rows[0], AnnotationTableModel.ROWTAG1);
this.clipboardTagId = (Integer) table.sorter.getValueAt(rows[0], AnnotationTableModel.ROWTAGID1);
// System.out.println("this.clipboardTag = " + this.clipboardTag);
// System.out.println("this.clipboardTagId = " + this.clipboardTagId);
}
else if (level==2) {
this.clipboardTag = (String) table.sorter.getValueAt(rows[0], AnnotationTableModel.ROWTAG2);
this.clipboardTagId = (Integer) table.sorter.getValueAt(rows[0], AnnotationTableModel.ROWTAGID2);
}
else if (level==3) {
this.clipboardTag = (String) table.sorter.getValueAt(rows[0], AnnotationTableModel.ROWTAG3);
this.clipboardTagId = (Integer) table.sorter.getValueAt(rows[0], AnnotationTableModel.ROWTAGID3);
}
else if (level==4) {
this.clipboardTag = (String) table.sorter.getValueAt(rows[0], AnnotationTableModel.ROWTAG4);
this.clipboardTagId = (Integer) table.sorter.getValueAt(rows[0], AnnotationTableModel.ROWTAGID4);
}
else if (level==5) {
this.clipboardTag = (String) table.sorter.getValueAt(rows[0], AnnotationTableModel.ROWTAG5);
this.clipboardTagId = (Integer) table.sorter.getValueAt(rows[0], AnnotationTableModel.ROWTAGID5);
}
else if (level==6) {
this.clipboardTag = (String) table.sorter.getValueAt(rows[0], AnnotationTableModel.ROWTAG6);
this.clipboardTagId = (Integer) table.sorter.getValueAt(rows[0], AnnotationTableModel.ROWTAGID6);
}
else if (level==7) {
this.clipboardTag = (String) table.sorter.getValueAt(rows[0], AnnotationTableModel.ROWTAG7);
this.clipboardTagId = (Integer) table.sorter.getValueAt(rows[0], AnnotationTableModel.ROWTAGID7);
}
else if (level==8) {
this.clipboardTag = (String) table.sorter.getValueAt(rows[0], AnnotationTableModel.ROWTAG8);
this.clipboardTagId = (Integer) table.sorter.getValueAt(rows[0], AnnotationTableModel.ROWTAGID8);
}
}
// System.out.println("rows.length = " + rows.length);
}
void DO_pastTag(int level) {
messageField.setText("");
if (this.clipboardTag.length()>0) {
int [] rows = table.table.getSelectedRows();
if (rows.length>0) {
cacheBu = cache;
cache = new ArrayList<CacheData>();
for (int i = 0; i<rows.length;i++) {
int theRow = rows[i];
addRowToCache(theRow, level);
if (level==1) {
table.sorter.setValueAt(this.clipboardTag, theRow, AnnotationTableModel.ROWTAG1);
table.sorter.setValueAt(this.clipboardTagId, theRow, AnnotationTableModel.ROWTAGID1);
}
else if (level==2) {
table.sorter.setValueAt(this.clipboardTag, theRow, AnnotationTableModel.ROWTAG2);
table.sorter.setValueAt(this.clipboardTagId, theRow, AnnotationTableModel.ROWTAGID2);
}
else if (level==3) {
table.sorter.setValueAt(this.clipboardTag, theRow, AnnotationTableModel.ROWTAG3);
table.sorter.setValueAt(this.clipboardTagId, theRow, AnnotationTableModel.ROWTAGID3);
}
else if (level==4) {
table.sorter.setValueAt(this.clipboardTag, theRow, AnnotationTableModel.ROWTAG4);
table.sorter.setValueAt(this.clipboardTagId, theRow, AnnotationTableModel.ROWTAGID4);
}
else if (level==5) {
table.sorter.setValueAt(this.clipboardTag, theRow, AnnotationTableModel.ROWTAG5);
table.sorter.setValueAt(this.clipboardTagId, theRow, AnnotationTableModel.ROWTAGID5);
}
else if (level==6) {
table.sorter.setValueAt(this.clipboardTag, theRow, AnnotationTableModel.ROWTAG6);
table.sorter.setValueAt(this.clipboardTagId, theRow, AnnotationTableModel.ROWTAGID6);
}
else if (level==7) {
table.sorter.setValueAt(this.clipboardTag, theRow, AnnotationTableModel.ROWTAG7);
table.sorter.setValueAt(this.clipboardTagId, theRow, AnnotationTableModel.ROWTAGID7);
}
else if (level==8) {
table.sorter.setValueAt(this.clipboardTag, theRow, AnnotationTableModel.ROWTAG8);
table.sorter.setValueAt(this.clipboardTagId, theRow, AnnotationTableModel.ROWTAGID8);
}
}
this.repaint();
}
}
}
void DO_applyTagToTypes(String tag, int level) {
messageField.setText("");
int [] rows = table.table.getSelectedRows();
Integer tagId = table.theTable.generateTagId();
ArrayList<String> taggedTokens = new ArrayList<String>();
if (rows.length>0) {
cache = new ArrayList<CacheData>();
for (int i = 0; i<rows.length;i++) {
int theRow = rows[i];
String tokenId = (String) table.sorter.getValueAt(theRow, AnnotationTableModel.ROWID);
KafTerm term = null;
if (parser.WordFormToTerm.containsKey(tokenId)) {
String termId = parser.WordFormToTerm.get(tokenId);
term = parser.getTerm(termId);
}
if (term!=null) {
ArrayList<String> spans = term.getSpans();
for (int j = 0; j < spans.size(); j++) {
String s = spans.get(j);
if (!taggedTokens.contains(s)) {
// System.out.println("s = " + s);
table.searchForString(AnnotationTableModel.ROWID,s);
int currentRow = table.table.getSelectedRow();
// System.out.println("currentRow = " + currentRow);
addRowToCache(currentRow, level);
if (level==1) {
table.sorter.setValueAt(tag, currentRow, AnnotationTableModel.ROWTAG1);
table.sorter.setValueAt(tagId, currentRow, AnnotationTableModel.ROWTAGID1);
}
else if (level==2) {
table.sorter.setValueAt(tag, currentRow, AnnotationTableModel.ROWTAG2);
table.sorter.setValueAt(tagId, currentRow, AnnotationTableModel.ROWTAGID2);
}
else if (level==3) {
table.sorter.setValueAt(tag, currentRow, AnnotationTableModel.ROWTAG3);
table.sorter.setValueAt(tagId, currentRow, AnnotationTableModel.ROWTAGID3);
}
else if (level==4) {
table.sorter.setValueAt(tag, currentRow, AnnotationTableModel.ROWTAG4);
table.sorter.setValueAt(tagId, currentRow, AnnotationTableModel.ROWTAGID4);
}
else if (level==5) {
table.sorter.setValueAt(tag, currentRow, AnnotationTableModel.ROWTAG5);
table.sorter.setValueAt(tagId, currentRow, AnnotationTableModel.ROWTAGID5);
}
else if (level==6) {
table.sorter.setValueAt(tag, currentRow, AnnotationTableModel.ROWTAG6);
table.sorter.setValueAt(tagId, currentRow, AnnotationTableModel.ROWTAGID6);
}
else if (level==7) {
table.sorter.setValueAt(tag, currentRow, AnnotationTableModel.ROWTAG7);
table.sorter.setValueAt(tagId, currentRow, AnnotationTableModel.ROWTAGID7);
}
else if (level==8) {
table.sorter.setValueAt(tag, currentRow, AnnotationTableModel.ROWTAG8);
table.sorter.setValueAt(tagId, currentRow, AnnotationTableModel.ROWTAGID8);
}
taggedTokens.add(s);
}
}
}
else {
messageField.setText("Could not fine the type. Please annotate at the token level");
}
}
this.repaint();
if (cache.size()==0) {
cache = cacheBu;
}
}
}
void addChunk (ArrayList<KafChunk> chunks, KafChunk chunk) {
if (chunks.size()==0) {
chunks.add(chunk);
}
else {
ArrayList<String> termIds = chunk.getSpans();
for (int j = 0; j < termIds.size(); j++) {
String s = termIds.get(j);
for (int i = 0; i < chunks.size(); i++) {
KafChunk kafChunk = chunks.get(i);
if (kafChunk.getSpans().contains(s)) {
if (chunk.getSpans().size()<kafChunk.getSpans().size()) {
if (!chunks.contains(chunk)) {
// we swap the chunks
chunks.set(i, chunk);
// System.out.println("substituting kafChunk.getPhrase() = " + kafChunk.getPhrase());
// System.out.println("for chunk.getPhrase() = " + chunk.getPhrase());
return;
}
}
else {
// we are done since there is already a smaller chunk
// System.out.println("Keeping kafChunk.getPhrase() = " + kafChunk.getPhrase());
// System.out.println("instead of chunk.getPhrase() = " + chunk.getPhrase());
return;
}
}
}
}
}
}
void DO_applyTagToConstituents(String tag, int level) {
messageField.setText("");
int [] rows = table.table.getSelectedRows();
if (rows.length==0) {
messageField.setText("No rows selected");
return;
}
else {
cacheBu = cache;
cache = new ArrayList<CacheData>();
Integer tagId = table.theTable.generateTagId();
ArrayList<String> taggedTokens = new ArrayList<String>();
for (int i = 0; i<rows.length;i++) {
int theRow = rows[i];
String tokenId = (String) table.sorter.getValueAt(theRow, AnnotationTableModel.ROWID);
ArrayList<KafTerm> terms = new ArrayList<KafTerm>();
if (parser.WordFormToTerm.containsKey(tokenId)) {
String termId = parser.WordFormToTerm.get(tokenId);
if (parser.TermToChunk.containsKey(termId)) {
ArrayList<KafChunk> theChunks = new ArrayList<KafChunk>();
ArrayList<String> chunkIds = parser.TermToChunk.get(termId);
for (int j = 0; j < chunkIds.size(); j++) {
String cid = chunkIds.get(j);
// System.out.println("cid = " + cid);
KafChunk chunk = parser.getChunks(cid);
// System.out.println("theChunks before adding = " + theChunks.size());
addChunk (theChunks, chunk);
// System.out.println("theChunks after adding = " + theChunks.size());
}
for (int j = 0; j < theChunks.size(); j++) {
KafChunk kafChunk = theChunks.get(j);
ArrayList<String> termdIds = kafChunk.getSpans();
for (int k = 0; k < termdIds.size(); k++) {
String tid = termdIds.get(k);
KafTerm term = parser.getTerm(tid);
if (term!=null) {
terms.add(term);
}
}
}
}
else {
messageField.setText("There is no constituent for this token. Please annotate at the token level");
return;
}
}
if (terms.size()>0) {
for (int t = 0; t < terms.size(); t++) {
KafTerm kafTerm = terms.get(t);
// System.out.println("kafTerm.getTid() = " + kafTerm.getTid());
ArrayList<String> spans = kafTerm.getSpans();
for (int j = 0; j < spans.size(); j++) {
String s = spans.get(j);
if (!taggedTokens.contains(s)) {
// System.out.println("s = " + s);
table.searchForString(AnnotationTableModel.ROWID,s);
int currentRow = table.table.getSelectedRow();
// System.out.println("currentRow = " + currentRow);
addRowToCache(currentRow, level);
if (level==1) {
table.sorter.setValueAt(tag, currentRow, AnnotationTableModel.ROWTAG1);
table.sorter.setValueAt(tagId, currentRow, AnnotationTableModel.ROWTAGID1);
}
else if (level==2) {
table.sorter.setValueAt(tag, currentRow, AnnotationTableModel.ROWTAG2);
table.sorter.setValueAt(tagId, currentRow, AnnotationTableModel.ROWTAGID2);
}
else if (level==3) {
table.sorter.setValueAt(tag, currentRow, AnnotationTableModel.ROWTAG3);
table.sorter.setValueAt(tagId, currentRow, AnnotationTableModel.ROWTAGID3);
}
else if (level==4) {
table.sorter.setValueAt(tag, currentRow, AnnotationTableModel.ROWTAG4);
table.sorter.setValueAt(tagId, currentRow, AnnotationTableModel.ROWTAGID4);
}
else if (level==5) {
table.sorter.setValueAt(tag, currentRow, AnnotationTableModel.ROWTAG5);
table.sorter.setValueAt(tagId, currentRow, AnnotationTableModel.ROWTAGID5);
}
else if (level==6) {
table.sorter.setValueAt(tag, currentRow, AnnotationTableModel.ROWTAG6);
table.sorter.setValueAt(tagId, currentRow, AnnotationTableModel.ROWTAGID6);
}
else if (level==7) {
table.sorter.setValueAt(tag, currentRow, AnnotationTableModel.ROWTAG7);
table.sorter.setValueAt(tagId, currentRow, AnnotationTableModel.ROWTAGID7);
}
else if (level==8) {
table.sorter.setValueAt(tag, currentRow, AnnotationTableModel.ROWTAG8);
table.sorter.setValueAt(tagId, currentRow, AnnotationTableModel.ROWTAGID8);
}
taggedTokens.add(s);
}
}
}
}
else {
messageField.setText("Could not fine the constituent terms. Please annotate at the token level");
}
}
this.repaint();
if (cache.size()==0) {
cache = cacheBu;
}
}
}
void DO_applyTagToAlllConstituents(String tag, int level) {
messageField.setText("");
int [] rows = table.table.getSelectedRows();
if (rows.length==0) {
messageField.setText("No rows selected");
return;
}
else {
cacheBu = cache;
cache = new ArrayList<CacheData>();
Integer tagId = table.theTable.generateTagId();
ArrayList<String> taggedTokens = new ArrayList<String>();
for (int i = 0; i<rows.length;i++) {
int theRow = rows[i];
String tokenId = (String) table.sorter.getValueAt(theRow, AnnotationTableModel.ROWID);
ArrayList<KafTerm> terms = new ArrayList<KafTerm>();
if (parser.WordFormToTerm.containsKey(tokenId)) {
String termId = parser.WordFormToTerm.get(tokenId);
if (parser.TermToChunk.containsKey(termId)) {
ArrayList<String> chunkIds = parser.TermToChunk.get(termId);
for (int j = 0; j < chunkIds.size(); j++) {
String cid = chunkIds.get(j);
// System.out.println("cid = " + cid);
KafChunk chunk = parser.getChunks(cid);
ArrayList<String> termdIds = chunk.getSpans();
for (int k = 0; k < termdIds.size(); k++) {
String tid = termdIds.get(k);
KafTerm term = parser.getTerm(tid);
if (term!=null) {
terms.add(term);
}
}
}
}
else {
messageField.setText("There is no constituent for this token. Please annotate at the token level");
return;
}
}
if (terms.size()>0) {
for (int t = 0; t < terms.size(); t++) {
KafTerm kafTerm = terms.get(t);
// System.out.println("kafTerm.getTid() = " + kafTerm.getTid());
ArrayList<String> spans = kafTerm.getSpans();
for (int j = 0; j < spans.size(); j++) {
String s = spans.get(j);
if (!taggedTokens.contains(s)) {
// System.out.println("s = " + s);
table.searchForString(AnnotationTableModel.ROWID,s);
int currentRow = table.table.getSelectedRow();
// System.out.println("currentRow = " + currentRow);
addRowToCache(currentRow, level);
if (level==1) {
table.sorter.setValueAt(tag, currentRow, AnnotationTableModel.ROWTAG1);
table.sorter.setValueAt(tagId, currentRow, AnnotationTableModel.ROWTAGID1);
}
else if (level==2) {
table.sorter.setValueAt(tag, currentRow, AnnotationTableModel.ROWTAG2);
table.sorter.setValueAt(tagId, currentRow, AnnotationTableModel.ROWTAGID2);
}
else if (level==3) {
table.sorter.setValueAt(tag, currentRow, AnnotationTableModel.ROWTAG3);
table.sorter.setValueAt(tagId, currentRow, AnnotationTableModel.ROWTAGID3);
}
else if (level==4) {
table.sorter.setValueAt(tag, currentRow, AnnotationTableModel.ROWTAG4);
table.sorter.setValueAt(tagId, currentRow, AnnotationTableModel.ROWTAGID4);
}
else if (level==5) {
table.sorter.setValueAt(tag, currentRow, AnnotationTableModel.ROWTAG5);
table.sorter.setValueAt(tagId, currentRow, AnnotationTableModel.ROWTAGID5);
}
else if (level==6) {
table.sorter.setValueAt(tag, currentRow, AnnotationTableModel.ROWTAG6);
table.sorter.setValueAt(tagId, currentRow, AnnotationTableModel.ROWTAGID6);
}
else if (level==7) {
table.sorter.setValueAt(tag, currentRow, AnnotationTableModel.ROWTAG7);
table.sorter.setValueAt(tagId, currentRow, AnnotationTableModel.ROWTAGID7);
}
else if (level==8) {
table.sorter.setValueAt(tag, currentRow, AnnotationTableModel.ROWTAG8);
table.sorter.setValueAt(tagId, currentRow, AnnotationTableModel.ROWTAGID8);
}
taggedTokens.add(s);
}
}
}
}
else {
messageField.setText("Could not fine the constituent terms. Please annotate at the token level");
}
}
this.repaint();
if (cache.size()==0) {
cache = cacheBu;
}
}
}
void DO_applyTagToSentences(String tag, int level) {
messageField.setText("");
int [] rows = table.table.getSelectedRows();
Integer tagId = table.theTable.generateTagId();
ArrayList<String> taggedTokens = new ArrayList<String>();
if (rows.length>0) {
cacheBu = cache;
cache = new ArrayList<CacheData>();
for (int i = 0; i<rows.length;i++) {
int theRow = rows[i];
String tokenId = (String) table.sorter.getValueAt(theRow, AnnotationTableModel.ROWID);
KafWordForm wf = parser.getWordForm(tokenId);
if (wf!=null) {
String sentence = wf.getSent();
if (parser.SentenceToWord.containsKey(sentence)) {
ArrayList<String> tokenIds = parser.SentenceToWord.get(sentence);
if (tokenIds.size()==0) {
messageField.setText("Could not fine tokens for the sentence: "+sentence+". Please annotate at the token level");
return;
}
for (int j = 0; j < tokenIds.size(); j++) {
String s = tokenIds.get(j);
if (!taggedTokens.contains(s)) {
// System.out.println("s = " + s);
table.searchForString(AnnotationTableModel.ROWID,s);
int currentRow = table.table.getSelectedRow();
addRowToCache (currentRow, level);
// System.out.println("currentRow = " + currentRow);
if (level==1) {
table.sorter.setValueAt(tag, currentRow, AnnotationTableModel.ROWTAG1);
table.sorter.setValueAt(tagId, currentRow, AnnotationTableModel.ROWTAGID1);
}
else if (level==2) {
table.sorter.setValueAt(tag, currentRow, AnnotationTableModel.ROWTAG2);
table.sorter.setValueAt(tagId, currentRow, AnnotationTableModel.ROWTAGID2);
}
else if (level==3) {
table.sorter.setValueAt(tag, currentRow, AnnotationTableModel.ROWTAG3);
table.sorter.setValueAt(tagId, currentRow, AnnotationTableModel.ROWTAGID3);
}
else if (level==4) {
table.sorter.setValueAt(tag, currentRow, AnnotationTableModel.ROWTAG4);
table.sorter.setValueAt(tagId, currentRow, AnnotationTableModel.ROWTAGID4);
}
else if (level==5) {
table.sorter.setValueAt(tag, currentRow, AnnotationTableModel.ROWTAG5);
table.sorter.setValueAt(tagId, currentRow, AnnotationTableModel.ROWTAGID5);
}
else if (level==6) {
table.sorter.setValueAt(tag, currentRow, AnnotationTableModel.ROWTAG6);
table.sorter.setValueAt(tagId, currentRow, AnnotationTableModel.ROWTAGID6);
}
else if (level==7) {
table.sorter.setValueAt(tag, currentRow, AnnotationTableModel.ROWTAG7);
table.sorter.setValueAt(tagId, currentRow, AnnotationTableModel.ROWTAGID7);
}
else if (level==8) {
table.sorter.setValueAt(tag, currentRow, AnnotationTableModel.ROWTAG8);
table.sorter.setValueAt(tagId, currentRow, AnnotationTableModel.ROWTAGID8);
}
taggedTokens.add(s);
}
}
}
else {
messageField.setText("Could not fine the sentence. Please annotate at the token level");
}
}
}
this.repaint();
if (cache.size()==0) {
cache = cacheBu;
}
}
}
void DO_selectLexicalTag() {
messageField.setText("");
//// GETS THE MOST FREQUENT TAG FROM THE TAG LEXICON
String tag = "";
int [] rows = table.table.getSelectedRows();
// System.out.println("rows.length = " + rows.length);
Integer tagId = table.theTable.generateTagId();
if (rows.length>0) {
cacheBu = cache;
cache = new ArrayList<CacheData>();
for (int i = 0; i<rows.length;i++) {
int theRow = rows[i];
addRowToCache(theRow, 1); ///level 1
String word = (String) table.sorter.getValueAt(theRow, AnnotationTableModel.ROWWORDTOKEN);
// System.out.println("word = " + word);
tag = tagLexicon.getTag(word);
if (tag.length()>0) {
table.sorter.setValueAt(tag, theRow, AnnotationTableModel.ROWTAG1);
table.sorter.setValueAt(tagId, theRow, AnnotationTableModel.ROWTAGID1);
// System.out.println("tag = " + tag);
}
else {
messageField.setText("This word has not been tagged yet:"+word);
}
}
this.repaint();
if (cache.size()==0) {
cache = cacheBu;
}
}
}
public void DO_Selected() {
messageField.setText("");
int [] rows = table.table.getSelectedRows();
if (rows.length>0) {
cacheBu = cache;
cache = new ArrayList<CacheData> ();
for (int i = 0; i<rows.length;i++) {
int theRow = rows[i];
addRowToCache(theRow, -1);
table.sorter.setValueAt(new Boolean(true),theRow,AnnotationTableModel.ROWSTATUS);
}
table.repaint();
this.repaint();
if (cache.size()==0) {
cache = cacheBu;
}
this.repaint();
}
}
public void DO_Unselected() {
messageField.setText("");
int [] rows = table.table.getSelectedRows();
if (rows.length>0) {
cacheBu = cache;
cache = new ArrayList<CacheData> ();
for (int i = 0; i<rows.length;i++) {
int theRow = rows[i];
addRowToCache(theRow, -1);
table.sorter.setValueAt(new Boolean(false),theRow,AnnotationTableModel.ROWSTATUS);
}
table.repaint();
this.repaint();
if (cache.size()==0) {
cache = cacheBu;
}
this.repaint();
}
}
public void DO_undo(){
messageField.setText("");
if (cache.size()>0) {
for (int i = 0; i < cache.size(); i++) {
CacheData cacheData = cache.get(i);
if (cacheData.getTagLevel()==-1) {
table.sorter.setValueAt(new Boolean(cacheData.isStatus()),cacheData.getnRow(),AnnotationTableModel.ROWSTATUS);
}
else if (cacheData.getTagLevel()==1) {
table.sorter.setValueAt(cacheData.getTag(),cacheData.getnRow(),AnnotationTableModel.ROWTAG1);
table.sorter.setValueAt(cacheData.getTagId(),cacheData.getnRow(),AnnotationTableModel.ROWTAGID1);
}
else if (cacheData.getTagLevel()==2) {
table.sorter.setValueAt(cacheData.getTag(),cacheData.getnRow(),AnnotationTableModel.ROWTAG2);
table.sorter.setValueAt(cacheData.getTagId(),cacheData.getnRow(),AnnotationTableModel.ROWTAGID2);
}
else if (cacheData.getTagLevel()==3) {
table.sorter.setValueAt(cacheData.getTag(),cacheData.getnRow(),AnnotationTableModel.ROWTAG3);
table.sorter.setValueAt(cacheData.getTagId(),cacheData.getnRow(),AnnotationTableModel.ROWTAGID3);
}
else if (cacheData.getTagLevel()==4) {
table.sorter.setValueAt(cacheData.getTag(),cacheData.getnRow(),AnnotationTableModel.ROWTAG4);
table.sorter.setValueAt(cacheData.getTagId(),cacheData.getnRow(),AnnotationTableModel.ROWTAGID4);
}
else if (cacheData.getTagLevel()==5) {
table.sorter.setValueAt(cacheData.getTag(),cacheData.getnRow(),AnnotationTableModel.ROWTAG5);
table.sorter.setValueAt(cacheData.getTagId(),cacheData.getnRow(),AnnotationTableModel.ROWTAGID5);
}
else if (cacheData.getTagLevel()==6) {
table.sorter.setValueAt(cacheData.getTag(),cacheData.getnRow(),AnnotationTableModel.ROWTAG6);
table.sorter.setValueAt(cacheData.getTagId(),cacheData.getnRow(),AnnotationTableModel.ROWTAGID6);
}
else if (cacheData.getTagLevel()==7) {
table.sorter.setValueAt(cacheData.getTag(),cacheData.getnRow(),AnnotationTableModel.ROWTAG7);
table.sorter.setValueAt(cacheData.getTagId(),cacheData.getnRow(),AnnotationTableModel.ROWTAGID7);
}
else if (cacheData.getTagLevel()==8) {
table.sorter.setValueAt(cacheData.getTag(),cacheData.getnRow(),AnnotationTableModel.ROWTAG8);
table.sorter.setValueAt(cacheData.getTagId(),cacheData.getnRow(),AnnotationTableModel.ROWTAGID8);
}
}
cache = cacheBu;
cacheBu = new ArrayList<CacheData>();
this.repaint();
}
else {
messageField.setText("Cannot UNDO tagging!!!!");
}
}
void addRowToCache (int theRow, int level) {
CacheData data = null;
if (level==-1) {
data = new CacheData(theRow, (String) table.sorter.getValueAt(theRow, AnnotationTableModel.ROWID),
(String) table.sorter.getValueAt(theRow, AnnotationTableModel.ROWTAG1),
(Integer) table.sorter.getValueAt(theRow, AnnotationTableModel.ROWTAGID1),
(Boolean) table.sorter.getValueAt(theRow, AnnotationTableModel.ROWSTATUS),
level);
}
else if (level==1) {
data = new CacheData(theRow, (String) table.sorter.getValueAt(theRow, AnnotationTableModel.ROWID),
(String) table.sorter.getValueAt(theRow, AnnotationTableModel.ROWTAG1),
(Integer) table.sorter.getValueAt(theRow, AnnotationTableModel.ROWTAGID1),
(Boolean) table.sorter.getValueAt(theRow, AnnotationTableModel.ROWSTATUS),
level);
}
else if (level==2) {
data = new CacheData(theRow, (String) table.sorter.getValueAt(theRow, AnnotationTableModel.ROWID),
(String) table.sorter.getValueAt(theRow, AnnotationTableModel.ROWTAG2),
(Integer) table.sorter.getValueAt(theRow, AnnotationTableModel.ROWTAGID2),
(Boolean) table.sorter.getValueAt(theRow, AnnotationTableModel.ROWSTATUS),
level);
}
else if (level==3) {
data = new CacheData(theRow, (String) table.sorter.getValueAt(theRow, AnnotationTableModel.ROWID),
(String) table.sorter.getValueAt(theRow, AnnotationTableModel.ROWTAG3),
(Integer) table.sorter.getValueAt(theRow, AnnotationTableModel.ROWTAGID3),
(Boolean) table.sorter.getValueAt(theRow, AnnotationTableModel.ROWSTATUS),
level);
}
else if (level==4) {
data = new CacheData(theRow, (String) table.sorter.getValueAt(theRow, AnnotationTableModel.ROWID),
(String) table.sorter.getValueAt(theRow, AnnotationTableModel.ROWTAG4),
(Integer) table.sorter.getValueAt(theRow, AnnotationTableModel.ROWTAGID4),
(Boolean) table.sorter.getValueAt(theRow, AnnotationTableModel.ROWSTATUS),
level);
}
else if (level==5) {
data = new CacheData(theRow, (String) table.sorter.getValueAt(theRow, AnnotationTableModel.ROWID),
(String) table.sorter.getValueAt(theRow, AnnotationTableModel.ROWTAG5),
(Integer) table.sorter.getValueAt(theRow, AnnotationTableModel.ROWTAGID5),
(Boolean) table.sorter.getValueAt(theRow, AnnotationTableModel.ROWSTATUS),
level);
}
else if (level==6) {
data = new CacheData(theRow, (String) table.sorter.getValueAt(theRow, AnnotationTableModel.ROWID),
(String) table.sorter.getValueAt(theRow, AnnotationTableModel.ROWTAG6),
(Integer) table.sorter.getValueAt(theRow, AnnotationTableModel.ROWTAGID6),
(Boolean) table.sorter.getValueAt(theRow, AnnotationTableModel.ROWSTATUS),
level);
}
else if (level==7) {
data = new CacheData(theRow, (String) table.sorter.getValueAt(theRow, AnnotationTableModel.ROWID),
(String) table.sorter.getValueAt(theRow, AnnotationTableModel.ROWTAG7),
(Integer) table.sorter.getValueAt(theRow, AnnotationTableModel.ROWTAGID7),
(Boolean) table.sorter.getValueAt(theRow, AnnotationTableModel.ROWSTATUS),
level);
}
else if (level==8) {
data = new CacheData(theRow, (String) table.sorter.getValueAt(theRow, AnnotationTableModel.ROWID),
(String) table.sorter.getValueAt(theRow, AnnotationTableModel.ROWTAG8),
(Integer) table.sorter.getValueAt(theRow, AnnotationTableModel.ROWTAGID8),
(Boolean) table.sorter.getValueAt(theRow, AnnotationTableModel.ROWSTATUS),
level);
}
if (data!=null) {
cache.add(data);
}
}
public int DO_checkSave () {
messageField.setText("");
ConfirmDialog dia = new ConfirmDialog(this, "Do you want to save tagging before quiting?", "");
if (dia.DOIT==0) {
int ok = -1;
ok = DO_saveTagFile();
DO_saveLexiconFile();
if (ok==0) {
messageField.setText("Tagging data saved");
}
else {
messageField.setText("Warning! Tagging data NOT saved");
}
}
return dia.DOIT;
}
public void DO_exportToTriples() {
if (THETAGFILE.length()==0) {
THETAGFILE = selectInputFileDialog(this, ".tag");
}
else {
DO_saveTagFile();
}
ArrayList<Triple> Triples = null;
if (TripleConfig.pairs.size()==0) {
// Triples = TagToTriples.loadAnnotationFile(THETAGFILE);
messageField.setText("No Triple.cfg file in: "+RESOURCESFOLDER+":"+TripleCONFIGFILE);
}
else {
Triples = TagToTriples.loadAnnotationFile(TripleConfig, THETAGFILE);
}
if (Triples!=null) {
String TripleFile = selectOutputFileDialog(this, THETAGFILE, ".trp", "Specify file for storing Triples");
if ((TripleFile.length()>0)) {
TagToTriples.saveTriplesToFile(TripleFile, Triples, TripleConfig);
}
ArrayList<String> sentenceTokens = new ArrayList<String> ();
ArrayList<String> eventTokens = new ArrayList<String> ();
for (int i = 0; i < Triples.size(); i++) {
Triple Triple = Triples.get(i);
for (int j = 0; j < Triple.getElementFirstIds().size(); j++) {
String s = Triple.getElementFirstIds().get(j);
if (!sentenceTokens.contains(s)) {
sentenceTokens.add(s);
}
if (!eventTokens.contains(s)) {
eventTokens.add(s);
}
}
for (int j = 0; j < Triple.getElementSecondIds().size(); j++) {
String s = Triple.getElementSecondIds().get(j);
if (!sentenceTokens.contains(s)) {
sentenceTokens.add(s);
}
}
}
///// NEXT WE OUTPUT THE TOKEN SCOPE FOR THE SENTENCES THAT WERE ANNOTATED
ArrayList<String> sentences = new ArrayList<String>();
// System.out.println("sentenceTokens.size() = " + sentenceTokens.size());
for (int i = 0; i < sentenceTokens.size(); i++) {
String s = sentenceTokens.get(i);
if (parser.wordFormMap.containsKey(s)) {
//if (parser.kafWordFormList.contains(s)) {
//KafWordForm wf = parser.kafWordFormList.get(parser.kafWordFormList.indexOf(s));
KafWordForm wf = parser.wordFormMap.get(s);
String sentence = wf.getSent();
// System.out.println("sentence = " + sentence);
if (sentence.length()>0) {
if (!sentences.contains(sentence)) {
sentences.add(sentence);
}
}
}
}
try {
// System.out.println("sentences.size() = " + sentences.size());
// System.out.println("parser.SentenceToWord.size() = " + parser.SentenceToWord.size());
FileOutputStream fos = new FileOutputStream (TripleFile+".sentence-token-scope");
for (int i = 0; i < sentences.size(); i++) {
String s = sentences.get(i);
if (parser.SentenceToWord.containsKey(s)) {
ArrayList<String> wfs = parser.SentenceToWord.get(s);
for (int j = 0; j < wfs.size(); j++) {
String s1 = wfs.get(j)+"\n";
fos.write(s1.getBytes());
}
}
}
fos.close();
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
//////// WE OUTPUT THE TOKEN SCOPE FOR JUST THE EVENTS (MORE STRICT)
ArrayList<String> events = new ArrayList<String>();
// System.out.println("sentenceTokens.size() = " + sentenceTokens.size());
for (int i = 0; i < eventTokens.size(); i++) {
String s = eventTokens.get(i);
if (parser.wordFormMap.containsKey(s)) {
KafWordForm wf = parser.wordFormMap.get(s);
if (!events.contains(wf.getWid())) {
events.add(wf.getWid());
}
}
}
try {
FileOutputStream fos = new FileOutputStream (TripleFile+".first-element-token-scope");
for (int i = 0; i < events.size(); i++) {
String s = events.get(i)+"\n";
fos.write(s.getBytes());
}
fos.close();
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
public void DO_exportMostCommonSubsumers() {
if (THETAGFILE.length()==0) {
THETAGFILE = selectInputFileDialog(this, ".tag");
}
else {
DO_saveTagFile();
}
try {
FileOutputStream fos = new FileOutputStream (THETAGFILE+".mcs");
HashMap<String, ArrayList<String>> tagSynsetMap = new HashMap<String, ArrayList<String>>();
MostCommonSubsumer.loadAnnotationFile(tagSynsetMap, THETAGFILE);
MostCommonSubsumer.getMostCommonSubsumer(tagSynsetMap, fos);
fos.close();
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
public static void main(String[] args) {
String pathToKafFile = "";
String pathToTagFile = "";
String pathToTagSetFile = "";
TableSettings tableSettings = new TableSettings();
for (int i = 0; i < args.length; i++) {
String arg = args[i];
if ((arg.equalsIgnoreCase("--kaf-file")) && args.length>(i+1)) {
pathToKafFile = args[i+1];
}
else if ((arg.equalsIgnoreCase("--tag-file")) && args.length>(i+1)) {
pathToTagFile = args[i+1];
}
else if ((arg.equalsIgnoreCase("--tag-set")) && args.length>(i+1)) {
pathToTagSetFile = args[i+1];
}
else if (arg.equalsIgnoreCase("--opinion")) {
OPINION = true;
}
else if (arg.equalsIgnoreCase("--synset")) {
SYNSET = true;
}
else if (arg.equalsIgnoreCase("--hide-label")) {
tableSettings.hideLabel = true;
}
else if (arg.equalsIgnoreCase("--hide-pos")) {
tableSettings.hidePos = true;
}
else if (arg.equalsIgnoreCase("--hide-status")) {
tableSettings.hideStatus = true;
}
else if (arg.equalsIgnoreCase("--hide-order")) {
tableSettings.hideOrder = true;
}
else if (arg.equalsIgnoreCase("--hide-term")) {
tableSettings.hideTerms = true;
}
else if (arg.equalsIgnoreCase("--hide-tagid")) {
tableSettings.hideTagIds = true;
}
else if (arg.equalsIgnoreCase("--hide-8")) {
tableSettings.hideTag8 = true;
}
else if (arg.equalsIgnoreCase("--hide-7")) {
tableSettings.hideTag7 = true;
}
else if (arg.equalsIgnoreCase("--hide-6")) {
tableSettings.hideTag6 = true;
}
else if (arg.equalsIgnoreCase("--hide-5")) {
tableSettings.hideTag5 = true;
}
else if (arg.equalsIgnoreCase("--hide-4")) {
tableSettings.hideTag4 = true;
}
else if (arg.equalsIgnoreCase("--hide-3")) {
tableSettings.hideTag3 = true;
}
else if (arg.equalsIgnoreCase("--hide-2")) {
tableSettings.hideTag2 = true;
}
}
final AnnotatorFrame frame = AnnotatorFrame.getInstance(tableSettings);
if (!pathToKafFile.isEmpty()) {
System.out.println("pathToKafFile = " + pathToKafFile);
frame.DO_loadKafFile(pathToKafFile);
}
if (!pathToTagFile.isEmpty()) {
System.out.println("pathToTagFile = " + pathToTagFile);
frame.DO_loadTagFile(pathToTagFile);
}
if (!pathToTagSetFile.isEmpty()) {
System.out.println("pathToTagSetFile = " + pathToTagSetFile);
frame.DO_readTagSet(pathToTagSetFile);
}
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
if (frame.DO_checkSave()==2) {
System.exit(0);
}
}
});
frame.setIconImage(new ImageIcon("images/kyoto.gif").getImage());
frame.setTitle("KAF Annotation Tool");
frame.pack();
frame.setVisible(true);
}
}
| false | true | public AnnotatorFrame (TableSettings settings) {
File resource = new File (RESOURCESFOLDER);
if (!resource.exists()) {
resource.mkdir();
}
File locations = new File (LOCATIONFILE);
if (!locations.exists()) {
try {
locations.createNewFile();
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
tableSettings = settings;
cache = new ArrayList<CacheData>();
cacheBu = new ArrayList<CacheData>();
parser = new KafSaxParser();
tagLexicon = new Lexicon();
tagLexicon.parseFile(LEXICONFILE);
TripleConfig = new TripleConfig(TripleCONFIGFILE);
theTag1Set = new ArrayList<String>();
theTag2Set = new ArrayList<String>();
theTag3Set = new ArrayList<String>();
theTag4Set = new ArrayList<String>();
theTag5Set = new ArrayList<String>();
theTag6Set = new ArrayList<String>();
theTag7Set = new ArrayList<String>();
theTag8Set = new ArrayList<String>();
clipboardTag = "";
clipboardTagId = -1;
inputName = "";
/// Message field
messagePanel = new JPanel();
messagePanel.setMinimumSize(new Dimension(400, 320));
messagePanel.setPreferredSize(new Dimension(400, 320));
messagePanel.setMaximumSize(new Dimension(400, 320));
messageLabel = new JLabel("Messages:");
messageLabel.setMinimumSize(new Dimension(80, 25));
messageLabel.setPreferredSize(new Dimension(80, 25));
messageField = new JTextField();
messageField.setEditable(false);
messageField.setMinimumSize(new Dimension(300, 25));
messageField.setPreferredSize(new Dimension(300, 25));
messageField.setMaximumSize(new Dimension(400, 30));
fullTextLabel = new JLabel("Text:");
fullTextLabel.setMinimumSize(new Dimension(80, 25));
fullTextLabel.setPreferredSize(new Dimension(80, 25));
fullTextField = new JTextArea();
fullTextField.setEditable(false);
fullTextField.setBackground(Colors.BackGroundColor);
fullTextField.setMinimumSize(new Dimension(300, 200));
fullTextField.setPreferredSize(new Dimension(300, 200));
fullTextField.setMaximumSize(new Dimension(400, 200));
fullTextField.setLineWrap(true);
fullTextField.setWrapStyleWord(true);
fullTextField.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
switch(e.getModifiers()) {
case InputEvent.BUTTON3_MASK: {
String word = fullTextField.getSelectedText();
table.searchForString(AnnotationTableModel.ROWWORDTOKEN, word);
}
}
}
});
JScrollPane scrollableTextArea = new JScrollPane (fullTextField,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollableTextArea.setMinimumSize(new Dimension(300, 200));
scrollableTextArea.setPreferredSize(new Dimension(300, 200));
scrollableTextArea.setMaximumSize(new Dimension(400, 200));
kafFileLabel = new JLabel("KAF file:");
kafFileLabel.setMinimumSize(new Dimension(80, 25));
kafFileLabel.setPreferredSize(new Dimension(80, 25));
kafFileField = new JTextField();
kafFileField.setEditable(false);
kafFileField.setBackground(Colors.BackGroundColor);
kafFileField.setMinimumSize(new Dimension(300, 25));
kafFileField.setPreferredSize(new Dimension(300, 25));
kafFileField.setMaximumSize(new Dimension(400, 30));
tagFileLabel = new JLabel("TAG file:");
tagFileLabel.setMinimumSize(new Dimension(80, 25));
tagFileLabel.setPreferredSize(new Dimension(80, 25));
tagFileField = new JTextField();
tagFileField.setEditable(false);
tagFileField.setBackground(Colors.BackGroundColor);
tagFileField.setMinimumSize(new Dimension(300, 25));
tagFileField.setPreferredSize(new Dimension(300, 25));
tagFileField.setMaximumSize(new Dimension(400, 30));
tagSetFileLabel = new JLabel("TAG set:");
tagSetFileLabel.setMinimumSize(new Dimension(80, 25));
tagSetFileLabel.setPreferredSize(new Dimension(80, 25));
tagSetFileField = new JTextField();
tagSetFileField.setEditable(false);
tagSetFileField.setBackground(Colors.BackGroundColor);
tagSetFileField.setMinimumSize(new Dimension(300, 25));
tagSetFileField.setPreferredSize(new Dimension(300, 25));
tagSetFileField.setMaximumSize(new Dimension(400, 30));
messagePanel.setLayout(new GridBagLayout());
messagePanel.add(fullTextLabel, new GridBagConstraints(0, 0, 1, 1, 0, 0
,GridBagConstraints.NORTH, GridBagConstraints.NONE, new Insets(10, 1, 1, 1), 0, 0));
messagePanel.add(scrollableTextArea, new GridBagConstraints(1, 0, 1, 1, 0.3, 0.3
, GridBagConstraints.NORTH, GridBagConstraints.BOTH, new Insets(10, 1, 1, 1), 0, 0));
messagePanel.add(messageLabel, new GridBagConstraints(0, 1, 1, 1, 0, 0
,GridBagConstraints.NORTH, GridBagConstraints.NONE, new Insets(10, 1, 1, 1), 0, 0));
messagePanel.add(messageField, new GridBagConstraints(1, 1, 1, 1, 0.3, 0.3
, GridBagConstraints.NORTH, GridBagConstraints.BOTH, new Insets(10, 1, 1, 1), 0, 0));
messagePanel.add(kafFileLabel, new GridBagConstraints(0, 2, 1, 1, 0, 0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(1, 1, 1, 1), 0, 0));
messagePanel.add(kafFileField, new GridBagConstraints(1, 2, 1, 1, 0.3, 0.3
, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(1, 1, 1, 1), 0, 0));
messagePanel.add(tagFileLabel, new GridBagConstraints(0, 3, 1, 1, 0, 0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(1, 1, 1, 1), 0, 0));
messagePanel.add(tagFileField, new GridBagConstraints(1, 3, 1, 1, 0.3, 0.3
, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(1, 1, 1, 1), 0, 0));
messagePanel.add(tagSetFileLabel, new GridBagConstraints(0, 4, 1, 1, 0, 0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(1, 1, 1, 1), 0, 0));
messagePanel.add(tagSetFileField, new GridBagConstraints(1, 4, 1, 1, 0.3, 0.3
,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(1, 1, 1, 1), 0, 0));
/// Menus
menuButtons = new JMenuBar();
fileMenu = new JMenu("File");
fileMenu.setMnemonic('f');
////
openMenuItem = new JMenuItem("Open KAF file",'o');
openMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_loadKafFile();
setCursor(current_cursor);
}
});
fileMenu.add(openMenuItem);
readTagFileMenuItem = new JMenuItem("Load TAG file",'l');
readTagFileMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_loadTagFile();
setCursor(current_cursor);
}
});
fileMenu.add(readTagFileMenuItem);
readTagSetMenuItem = new JMenuItem("Load TAG set", 't');
readTagSetMenuItem.setMnemonic('t');
readTagSetMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_readTagSet();
setCursor(current_cursor);
}
});
fileMenu.add(readTagSetMenuItem);
readLexiconMenuItem = new JMenuItem("Load lexicon file", 'x');
readLexiconMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_readLexicon();
setCursor(current_cursor);
}
});
fileMenu.add(readLexiconMenuItem);
////
saveTagMenuItem = new JMenuItem("Save tagging",'s');
saveTagMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
int ok = -1;
ok = DO_saveTagFile();
DO_saveLexiconFile();
if (ok==0) {
messageField.setText("Tagging data saved");
}
else {
messageField.setText("Warning! Tagging data NOT saved");
}
setCursor(current_cursor);
}
});
fileMenu.add(saveTagMenuItem);
////////////////////////////////////////
saveAsMenu = new JMenu("Save as");
saveAsMenu.setMnemonic('a');
saveTagAsMenuItem = new JMenuItem("Tagging",'t');
saveTagAsMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_saveTagFileAs();
setCursor(current_cursor);
}
});
saveAsMenu.add(saveTagAsMenuItem);
saveLexiconAsMenuItem = new JMenuItem("Lexicon",'l');
saveLexiconAsMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_saveLexiconFileAs();
setCursor(current_cursor);
}
});
saveAsMenu.add(saveLexiconAsMenuItem);
fileMenu.add(saveAsMenu);
////
saveTrainMenuItem = new JMenuItem("Export tags to train format",'e');
saveTrainMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_saveTrainFile();
setCursor(current_cursor);
}
});
fileMenu.add(saveTrainMenuItem);
convertTagsToTriples = new JMenuItem("Export to Triples",'e');
convertTagsToTriples.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_exportToTriples();
setCursor(current_cursor);
}
});
fileMenu.add(convertTagsToTriples);
outputMostCommonSubsumer = new JMenuItem("Export wordnet classes",'w');
outputMostCommonSubsumer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_exportMostCommonSubsumers();
setCursor(current_cursor);
}
});
fileMenu.add(outputMostCommonSubsumer);
quitMenuItem = new JMenuItem("Quit",'q');
quitMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (DO_checkSave()==2) {
System.exit(0);
}
}
});
fileMenu.add(quitMenuItem);
menuButtons.add(fileMenu);
////////////////////////////////////////
searchMenu = new JMenu("Search");
searchMenu.setMnemonic('s');
////
searchWordMenuItem = new JMenuItem("Word",'w');
searchWordMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_searchWord();
setCursor(current_cursor);
}
});
searchMenu.add(searchWordMenuItem);
////
searchLastTagMenuItem = new JMenuItem("Last tag",'l');
searchLastTagMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_searchLastTag();
setCursor(current_cursor);
}
});
searchMenu.add(searchLastTagMenuItem);
searchTagMenuItem = new JMenuItem("Tag",'t');
searchTagMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_searchTag();
setCursor(current_cursor);
}
});
searchMenu.add(searchTagMenuItem);
searchWordAgainMenuItem = new JMenuItem("Next Word",'n');
searchWordAgainMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_searchWordAgain();
setCursor(current_cursor);
}
});
searchMenu.add(searchWordAgainMenuItem);
////
searchTagAgainMenuItem = new JMenuItem("Next Tag",'x');
searchTagAgainMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_searchTagAgain();
setCursor(current_cursor);
}
});
searchMenu.add(searchTagAgainMenuItem);
////
searchNotDoneMenuItem = new JMenuItem("No Confirm",'c');
searchNotDoneMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_notDone();
setCursor(current_cursor);
}
});
searchMenu.add(searchNotDoneMenuItem);
menuButtons.add(searchMenu);
/////////////////////////////////////////////////
otherMenu = new JMenu("Other");
otherMenu.setMnemonic('o');
////
confirmMenuItem = new JMenuItem("Do Confirm",'d');
confirmMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor(Cursor.WAIT_CURSOR));
DO_Selected();
setCursor(current_cursor);
}
});
otherMenu.add(confirmMenuItem);
////
unconfirmMenuItem = new JMenuItem("Undo Confirm",'u');
unconfirmMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_Unselected();
setCursor(current_cursor);
}
});
otherMenu.add(unconfirmMenuItem);
removeAllTagsMenuItem = new JMenuItem("Remove all annotations",'r');
removeAllTagsMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_unTagAllTokens();
setCursor(current_cursor);
}
});
otherMenu.add(removeAllTagsMenuItem);
undoMenuItem = new JMenuItem("Undo",'u');
// undoMenuItem.setMaximumSize(new Dimension(70, 150));
// undoMenuItem.setBorder(BorderFactory.createLineBorder(Color.gray));
undoMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_undo();
setCursor(current_cursor);
}
});
otherMenu.add(undoMenuItem);
menuButtons.add(otherMenu);
////////////////////////////////////////////////////////
////
/////////////////////
tag1Menu = new JMenu("Tag level 1");
tag1Menu.setMnemonic('1');
tag1TokenMenu = new JMenu("Tag tokens");
tag1TokenMenu.setMnemonic('t');
tag1Menu.add(tag1TokenMenu);
tag1LemmaMenu = new JMenu("Tag types");
tag1LemmaMenu.setMnemonic('y');
tag1Menu.add(tag1LemmaMenu);
tag1ConstituentMenu = new JMenu("Tag constituent");
tag1ConstituentMenu.setMnemonic('c');
tag1Menu.add(tag1ConstituentMenu);
tag1SentenceMenu = new JMenu("Tag sentence");
tag1SentenceMenu.setMnemonic('s');
tag1Menu.add(tag1SentenceMenu);
// popup.add(tag1Menu); // just trying
JMenuItem untagItem = new JMenuItem ("UNTAG", 'u');
untagItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_unTagTokens(1);
setCursor(current_cursor);
}
});
tag1Menu.add(untagItem);
JMenuItem mergeTagIdsItem = new JMenuItem ("Merge Tag Ids", 'm');
mergeTagIdsItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_mergeTagIds(1);
setCursor(current_cursor);
}
});
tag1Menu.add(mergeTagIdsItem);
JMenuItem separateTagIdsItem = new JMenuItem ("Separate Tag Ids", 's');
separateTagIdsItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_separateTagIds(1);
setCursor(current_cursor);
}
});
tag1Menu.add(separateTagIdsItem);
JMenuItem editTagIdsItem = new JMenuItem ("Edit Tag Id", 'e');
editTagIdsItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_editTagIds(1);
setCursor(current_cursor);
}
});
tag1Menu.add(editTagIdsItem);
JMenuItem copyTagItem = new JMenuItem ("Copy Tag & Id", 'c');
copyTagItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_copyTag(1);
setCursor(current_cursor);
}
});
tag1Menu.add(copyTagItem);
JMenuItem pastTagItem = new JMenuItem ("Past Tag & Id", 'p');
pastTagItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_pastTag(1);
setCursor(current_cursor);
}
});
tag1Menu.add(pastTagItem);
JMenuItem selectLexTagMenuItem = new JMenuItem("Dominant Tag",'l');
selectLexTagMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_selectLexicalTag();
setCursor(current_cursor);
}
});
tag1Menu.add(selectLexTagMenuItem);
newTag1MenuItem = new JMenuItem("Add Tag",'a');
newTag1MenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_makeNewTag1();
setCursor(current_cursor);
}
});
tag1Menu.add(newTag1MenuItem);
menuButtons.add(tag1Menu);
//////////////////////////////////
tag2Menu = new JMenu("Tag level 2");
tag2Menu.setMnemonic('2');
tag2TokenMenu = new JMenu("Tag tokens");
tag2TokenMenu.setMnemonic('t');
tag2Menu.add(tag2TokenMenu);
tag2LemmaMenu = new JMenu("Tag types");
tag2LemmaMenu.setMnemonic('y');
tag2Menu.add(tag2LemmaMenu);
tag2ConstituentMenu = new JMenu("Tag constituent");
tag2ConstituentMenu.setMnemonic('c');
tag2Menu.add(tag2ConstituentMenu);
tag2SentenceMenu = new JMenu("Tag sentence");
tag2SentenceMenu.setMnemonic('s');
tag2Menu.add(tag2SentenceMenu);
JMenuItem untagItem2 = new JMenuItem ("UNTAG", 'u');
untagItem2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_unTagTokens(2);
setCursor(current_cursor);
}
});
tag2Menu.add(untagItem2);
JMenuItem mergeTagIdsItem2 = new JMenuItem ("Merge Tag Ids", 'm');
mergeTagIdsItem2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_mergeTagIds(2);
setCursor(current_cursor);
}
});
tag2Menu.add(mergeTagIdsItem2);
JMenuItem separateTagIdsItem2 = new JMenuItem ("Separate Tag Ids", 's');
separateTagIdsItem2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_separateTagIds(2);
setCursor(current_cursor);
}
});
tag2Menu.add(separateTagIdsItem2);
JMenuItem editTagIdsItem2 = new JMenuItem ("Edit Tag Id", 'e');
editTagIdsItem2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_editTagIds(2);
setCursor(current_cursor);
}
});
tag2Menu.add(editTagIdsItem2);
JMenuItem copyTagItem2 = new JMenuItem ("Copy Tag & Id", 'c');
copyTagItem2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_copyTag(2);
setCursor(current_cursor);
}
});
tag2Menu.add(copyTagItem2);
JMenuItem pastTagItem2 = new JMenuItem ("Past Tag & Id", 'p');
pastTagItem2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_pastTag(2);
setCursor(current_cursor);
}
});
tag2Menu.add(pastTagItem2);
newTag2MenuItem = new JMenuItem("Add Tag",'a');
newTag2MenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_makeNewTag2();
setCursor(current_cursor);
}
});
tag2Menu.add(newTag2MenuItem);
if (!tableSettings.hideTag2) {
menuButtons.add(tag2Menu);
}
/////////////////#################
tag3Menu = new JMenu("Tag level 3");
tag3Menu.setMnemonic('3');
tag3TokenMenu = new JMenu("Tag tokens");
tag3Menu.add(tag3TokenMenu);
tag3LemmaMenu = new JMenu("Tag types");
tag3LemmaMenu.setMnemonic('y');
tag3Menu.add(tag3LemmaMenu);
tag3ConstituentMenu = new JMenu("Tag constituent");
tag3ConstituentMenu.setMnemonic('c');
tag3Menu.add(tag3ConstituentMenu);
tag3SentenceMenu = new JMenu("Tag sentence");
tag3SentenceMenu.setMnemonic('s');
tag3Menu.add(tag3SentenceMenu);
JMenuItem untagItem3 = new JMenuItem ("UNTAG", 'u');
untagItem3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_unTagTokens(3);
setCursor(current_cursor);
}
});
tag3Menu.add(untagItem3);
JMenuItem mergeTagIdsItem3 = new JMenuItem ("Merge Tag Ids", 'm');
mergeTagIdsItem3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_mergeTagIds(3);
setCursor(current_cursor);
}
});
tag3Menu.add(mergeTagIdsItem3);
JMenuItem separateTagIdsItem3 = new JMenuItem ("Separate Tag Ids", 's');
separateTagIdsItem3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_separateTagIds(3);
setCursor(current_cursor);
}
});
tag3Menu.add(separateTagIdsItem3);
JMenuItem editTagIdsItem3 = new JMenuItem ("Edit Tag Id", 'e');
editTagIdsItem3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_editTagIds(3);
setCursor(current_cursor);
}
});
tag3Menu.add(editTagIdsItem3);
JMenuItem copyTagItem3 = new JMenuItem ("Copy Tag & Id", 'c');
copyTagItem3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_copyTag(3);
setCursor(current_cursor);
}
});
tag3Menu.add(copyTagItem3);
JMenuItem pastTagItem3 = new JMenuItem ("Past Tag & Id", 'p');
pastTagItem3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_pastTag(3);
setCursor(current_cursor);
}
});
tag3Menu.add(pastTagItem3);
newTag3MenuItem = new JMenuItem("Add Tag",'a');
newTag3MenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_makeNewTag3();
setCursor(current_cursor);
}
});
tag3Menu.add(newTag3MenuItem);
if (!tableSettings.hideTag3){
menuButtons.add(tag3Menu);
}
/////////////////////
tag4Menu = new JMenu("Tag level 4");
tag4Menu.setMnemonic('4');
tag4TokenMenu = new JMenu("Tag tokens");
tag4Menu.add(tag4TokenMenu);
tag4LemmaMenu = new JMenu("Tag types");
tag4LemmaMenu.setMnemonic('y');
tag4Menu.add(tag4LemmaMenu);
tag4ConstituentMenu = new JMenu("Tag constituent");
tag4ConstituentMenu.setMnemonic('c');
tag4Menu.add(tag4ConstituentMenu);
tag4SentenceMenu = new JMenu("Tag sentence");
tag4SentenceMenu.setMnemonic('s');
tag4Menu.add(tag4SentenceMenu);
JMenuItem untagItem4 = new JMenuItem ("UNTAG", 'u');
untagItem4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_unTagTokens(4);
setCursor(current_cursor);
}
});
tag4Menu.add(untagItem4);
JMenuItem mergeTagIdsItem4 = new JMenuItem ("Merge Tag Ids", 'm');
mergeTagIdsItem4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_mergeTagIds(4);
setCursor(current_cursor);
}
});
tag4Menu.add(mergeTagIdsItem4);
JMenuItem separateTagIdsItem4 = new JMenuItem ("Separate Tag Ids", 's');
separateTagIdsItem4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_separateTagIds(4);
setCursor(current_cursor);
}
});
tag4Menu.add(separateTagIdsItem4);
JMenuItem editTagIdsItem4 = new JMenuItem ("Edit Tag Id", 'e');
editTagIdsItem4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_editTagIds(4);
setCursor(current_cursor);
}
});
tag4Menu.add(editTagIdsItem4);
JMenuItem copyTagItem4 = new JMenuItem ("Copy Tag & Id", 'c');
copyTagItem4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_copyTag(4);
setCursor(current_cursor);
}
});
tag4Menu.add(copyTagItem4);
JMenuItem pastTagItem4 = new JMenuItem ("Past Tag & Id", 'p');
pastTagItem4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_pastTag(4);
setCursor(current_cursor);
}
});
tag4Menu.add(pastTagItem4);
newTag4MenuItem = new JMenuItem("Add Tag",'a');
newTag4MenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_makeNewTag4();
setCursor(current_cursor);
}
});
tag4Menu.add(newTag4MenuItem);
if (!tableSettings.hideTag4) {
menuButtons.add(tag4Menu);
}
/////////////////#################
tag5Menu = new JMenu("Tag level 5");
tag5Menu.setMnemonic('5');
tag5TokenMenu = new JMenu("Tag tokens");
tag5Menu.add(tag5TokenMenu);
tag5LemmaMenu = new JMenu("Tag types");
tag5LemmaMenu.setMnemonic('y');
tag5Menu.add(tag5LemmaMenu);
tag5ConstituentMenu = new JMenu("Tag constituent");
tag5ConstituentMenu.setMnemonic('c');
tag5Menu.add(tag5ConstituentMenu);
tag5SentenceMenu = new JMenu("Tag sentence");
tag5SentenceMenu.setMnemonic('s');
tag5Menu.add(tag5SentenceMenu);
JMenuItem untagItem5 = new JMenuItem ("UNTAG", 'u');
untagItem5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_unTagTokens(5);
setCursor(current_cursor);
}
});
tag5Menu.add(untagItem5);
JMenuItem mergeTagIdsItem5 = new JMenuItem ("Merge Tag Ids", 'm');
mergeTagIdsItem5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_mergeTagIds(5);
setCursor(current_cursor);
}
});
tag5Menu.add(mergeTagIdsItem5);
JMenuItem separateTagIdsItem5 = new JMenuItem ("Separate Tag Ids", 's');
separateTagIdsItem5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_separateTagIds(5);
setCursor(current_cursor);
}
});
tag5Menu.add(separateTagIdsItem5);
JMenuItem editTagIdsItem5 = new JMenuItem ("Edit Tag Id", 'e');
editTagIdsItem5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_editTagIds(5);
setCursor(current_cursor);
}
});
tag5Menu.add(editTagIdsItem5);
JMenuItem copyTagItem5 = new JMenuItem ("Copy Tag & Id", 'c');
copyTagItem5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_copyTag(5);
setCursor(current_cursor);
}
});
tag5Menu.add(copyTagItem5);
JMenuItem pastTagItem5 = new JMenuItem ("Past Tag & Id", 'p');
pastTagItem5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_pastTag(5);
setCursor(current_cursor);
}
});
tag5Menu.add(pastTagItem5);
newTag5MenuItem = new JMenuItem("Add Tag",'a');
newTag5MenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_makeNewTag5();
setCursor(current_cursor);
}
});
tag5Menu.add(newTag5MenuItem);
if (!tableSettings.hideTag5) {
menuButtons.add(tag5Menu);
}
/////////////////#################
tag6Menu = new JMenu("Tag level 6");
tag6Menu.setMnemonic('6');
tag6TokenMenu = new JMenu("Tag tokens");
tag6Menu.add(tag6TokenMenu);
tag6LemmaMenu = new JMenu("Tag types");
tag6LemmaMenu.setMnemonic('y');
tag6Menu.add(tag6LemmaMenu);
tag6ConstituentMenu = new JMenu("Tag constituent");
tag6ConstituentMenu.setMnemonic('c');
tag6Menu.add(tag6ConstituentMenu);
tag6SentenceMenu = new JMenu("Tag sentence");
tag6SentenceMenu.setMnemonic('s');
tag6Menu.add(tag6SentenceMenu);
JMenuItem untagItem6 = new JMenuItem ("UNTAG", 'u');
untagItem6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_unTagTokens(6);
setCursor(current_cursor);
}
});
tag6Menu.add(untagItem6);
JMenuItem mergeTagIdsItem6 = new JMenuItem ("Merge Tag Ids", 'm');
mergeTagIdsItem6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_mergeTagIds(6);
setCursor(current_cursor);
}
});
tag6Menu.add(mergeTagIdsItem6);
JMenuItem separateTagIdsItem6 = new JMenuItem ("Separate Tag Ids", 's');
separateTagIdsItem6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_separateTagIds(6);
setCursor(current_cursor);
}
});
tag6Menu.add(separateTagIdsItem6);
JMenuItem editTagIdsItem6 = new JMenuItem ("Edit Tag Id", 'e');
editTagIdsItem6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_editTagIds(6);
setCursor(current_cursor);
}
});
tag6Menu.add(editTagIdsItem6);
JMenuItem copyTagItem6 = new JMenuItem ("Copy Tag & Id", 'c');
copyTagItem6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_copyTag(6);
setCursor(current_cursor);
}
});
tag6Menu.add(copyTagItem6);
JMenuItem pastTagItem6 = new JMenuItem ("Past Tag & Id", 'p');
pastTagItem6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_pastTag(6);
setCursor(current_cursor);
}
});
tag6Menu.add(pastTagItem6);
newTag6MenuItem = new JMenuItem("Add Tag",'a');
newTag6MenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_makeNewTag6();
setCursor(current_cursor);
}
});
tag6Menu.add(newTag6MenuItem);
if (!tableSettings.hideTag6) {
menuButtons.add(tag6Menu);
}
/////////////////#################
tag7Menu = new JMenu("Tag level 7");
tag7Menu.setMnemonic('7');
tag7TokenMenu = new JMenu("Tag tokens");
tag7Menu.add(tag7TokenMenu);
tag7LemmaMenu = new JMenu("Tag types");
tag7LemmaMenu.setMnemonic('y');
tag7Menu.add(tag7LemmaMenu);
tag7ConstituentMenu = new JMenu("Tag constituent");
tag7ConstituentMenu.setMnemonic('c');
tag7Menu.add(tag7ConstituentMenu);
tag7SentenceMenu = new JMenu("Tag sentence");
tag7SentenceMenu.setMnemonic('s');
tag7Menu.add(tag7SentenceMenu);
JMenuItem untagItem7 = new JMenuItem ("UNTAG", 'u');
untagItem6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_unTagTokens(7);
setCursor(current_cursor);
}
});
tag7Menu.add(untagItem7);
JMenuItem mergeTagIdsItem7 = new JMenuItem ("Merge Tag Ids", 'm');
mergeTagIdsItem6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_mergeTagIds(7);
setCursor(current_cursor);
}
});
tag7Menu.add(mergeTagIdsItem7);
JMenuItem separateTagIdsItem7 = new JMenuItem ("Separate Tag Ids", 's');
separateTagIdsItem6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_separateTagIds(7);
setCursor(current_cursor);
}
});
tag7Menu.add(separateTagIdsItem7);
JMenuItem editTagIdsItem7 = new JMenuItem ("Edit Tag Id", 'e');
editTagIdsItem7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_editTagIds(7);
setCursor(current_cursor);
}
});
tag7Menu.add(editTagIdsItem7);
JMenuItem copyTagItem7 = new JMenuItem ("Copy Tag & Id", 'c');
copyTagItem7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_copyTag(7);
setCursor(current_cursor);
}
});
tag7Menu.add(copyTagItem7);
JMenuItem pastTagItem7 = new JMenuItem ("Past Tag & Id", 'p');
pastTagItem7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_pastTag(7);
setCursor(current_cursor);
}
});
tag7Menu.add(pastTagItem7);
newTag7MenuItem = new JMenuItem("Add Tag",'a');
newTag7MenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_makeNewTag7();
setCursor(current_cursor);
}
});
tag7Menu.add(newTag7MenuItem);
if (!tableSettings.hideTag7) {
menuButtons.add(tag7Menu);
}
/////////////////#################
tag8Menu = new JMenu("Tag level 8");
tag8Menu.setMnemonic('8');
tag8TokenMenu = new JMenu("Tag tokens");
tag8Menu.add(tag8TokenMenu);
tag8LemmaMenu = new JMenu("Tag types");
tag8LemmaMenu.setMnemonic('y');
tag8Menu.add(tag8LemmaMenu);
tag8ConstituentMenu = new JMenu("Tag constituent");
tag8ConstituentMenu.setMnemonic('c');
tag8Menu.add(tag8ConstituentMenu);
tag8SentenceMenu = new JMenu("Tag sentence");
tag8SentenceMenu.setMnemonic('s');
tag8Menu.add(tag8SentenceMenu);
JMenuItem untagItem8 = new JMenuItem ("UNTAG", 'u');
untagItem8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_unTagTokens(8);
setCursor(current_cursor);
}
});
tag8Menu.add(untagItem8);
JMenuItem mergeTagIdsItem8 = new JMenuItem ("Merge Tag Ids", 'm');
mergeTagIdsItem8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_mergeTagIds(8);
setCursor(current_cursor);
}
});
tag8Menu.add(mergeTagIdsItem8);
JMenuItem separateTagIdsItem8 = new JMenuItem ("Separate Tag Ids", 's');
separateTagIdsItem8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_separateTagIds(8);
setCursor(current_cursor);
}
});
tag8Menu.add(separateTagIdsItem8);
JMenuItem editTagIdsItem8 = new JMenuItem ("Edit Tag Id", 'e');
editTagIdsItem8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_editTagIds(8);
setCursor(current_cursor);
}
});
tag8Menu.add(editTagIdsItem8);
JMenuItem copyTagItem8 = new JMenuItem ("Copy Tag & Id", 'c');
copyTagItem8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_copyTag(8);
setCursor(current_cursor);
}
});
tag8Menu.add(copyTagItem8);
JMenuItem pastTagItem8 = new JMenuItem ("Past Tag & Id", 'p');
pastTagItem8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_pastTag(8);
setCursor(current_cursor);
}
});
tag8Menu.add(pastTagItem8);
newTag8MenuItem = new JMenuItem("Add Tag",'a');
newTag8MenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_makeNewTag8();
setCursor(current_cursor);
}
});
tag8Menu.add(newTag8MenuItem);
if (!tableSettings.hideTag8) {
menuButtons.add(tag8Menu);
}
/// Text Area
table = new AnnotationTable(tableSettings);
///////////////////////
contentPanel = new JPanel();
setContentPane(contentPanel);
contentPanel.setLayout(new GridBagLayout());
contentPanel.add(menuButtons, new GridBagConstraints(0, 0, 1, 1, 0, 0
,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(10, 10, 10, 10), 15, 15));
contentPanel.add(table, new GridBagConstraints(0, 1, 1, 1, 0.3, 0.3
,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(10, 10, 10, 10), 0, 0));
contentPanel.add(messagePanel, new GridBagConstraints(0, 3, 1, 1, 0.3, 0.3
,GridBagConstraints.SOUTH, GridBagConstraints.HORIZONTAL, new Insets(10, 10, 10, 10), 0, 0));
}
| public AnnotatorFrame (TableSettings settings) {
File resource = new File (RESOURCESFOLDER);
if (!resource.exists()) {
resource.mkdir();
}
File locations = new File (LOCATIONFILE);
if (!locations.exists()) {
try {
locations.createNewFile();
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
tableSettings = settings;
cache = new ArrayList<CacheData>();
cacheBu = new ArrayList<CacheData>();
parser = new KafSaxParser();
tagLexicon = new Lexicon();
tagLexicon.parseFile(LEXICONFILE);
TripleConfig = new TripleConfig(TripleCONFIGFILE);
theTag1Set = new ArrayList<String>();
theTag2Set = new ArrayList<String>();
theTag3Set = new ArrayList<String>();
theTag4Set = new ArrayList<String>();
theTag5Set = new ArrayList<String>();
theTag6Set = new ArrayList<String>();
theTag7Set = new ArrayList<String>();
theTag8Set = new ArrayList<String>();
clipboardTag = "";
clipboardTagId = -1;
inputName = "";
/// Message field
messagePanel = new JPanel();
messagePanel.setMinimumSize(new Dimension(400, 320));
messagePanel.setPreferredSize(new Dimension(400, 320));
messagePanel.setMaximumSize(new Dimension(400, 320));
messageLabel = new JLabel("Messages:");
messageLabel.setMinimumSize(new Dimension(80, 25));
messageLabel.setPreferredSize(new Dimension(80, 25));
messageField = new JTextField();
messageField.setEditable(false);
messageField.setMinimumSize(new Dimension(300, 25));
messageField.setPreferredSize(new Dimension(300, 25));
messageField.setMaximumSize(new Dimension(400, 30));
fullTextLabel = new JLabel("Text:");
fullTextLabel.setMinimumSize(new Dimension(80, 25));
fullTextLabel.setPreferredSize(new Dimension(80, 25));
fullTextField = new JTextArea();
fullTextField.setEditable(false);
fullTextField.setBackground(Colors.BackGroundColor);
/*
fullTextField.setMinimumSize(new Dimension(300, 200));
fullTextField.setPreferredSize(new Dimension(300, 200));
fullTextField.setMaximumSize(new Dimension(400, 200));
*/
fullTextField.setLineWrap(true);
fullTextField.setWrapStyleWord(true);
fullTextField.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
switch(e.getModifiers()) {
case InputEvent.BUTTON3_MASK: {
String word = fullTextField.getSelectedText();
table.searchForString(AnnotationTableModel.ROWWORDTOKEN, word);
}
}
}
});
JScrollPane scrollableTextArea = new JScrollPane (fullTextField,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollableTextArea.setMinimumSize(new Dimension(300, 200));
scrollableTextArea.setPreferredSize(new Dimension(300, 200));
scrollableTextArea.setMaximumSize(new Dimension(400, 200));
kafFileLabel = new JLabel("KAF file:");
kafFileLabel.setMinimumSize(new Dimension(80, 25));
kafFileLabel.setPreferredSize(new Dimension(80, 25));
kafFileField = new JTextField();
kafFileField.setEditable(false);
kafFileField.setBackground(Colors.BackGroundColor);
kafFileField.setMinimumSize(new Dimension(300, 25));
kafFileField.setPreferredSize(new Dimension(300, 25));
kafFileField.setMaximumSize(new Dimension(400, 30));
tagFileLabel = new JLabel("TAG file:");
tagFileLabel.setMinimumSize(new Dimension(80, 25));
tagFileLabel.setPreferredSize(new Dimension(80, 25));
tagFileField = new JTextField();
tagFileField.setEditable(false);
tagFileField.setBackground(Colors.BackGroundColor);
tagFileField.setMinimumSize(new Dimension(300, 25));
tagFileField.setPreferredSize(new Dimension(300, 25));
tagFileField.setMaximumSize(new Dimension(400, 30));
tagSetFileLabel = new JLabel("TAG set:");
tagSetFileLabel.setMinimumSize(new Dimension(80, 25));
tagSetFileLabel.setPreferredSize(new Dimension(80, 25));
tagSetFileField = new JTextField();
tagSetFileField.setEditable(false);
tagSetFileField.setBackground(Colors.BackGroundColor);
tagSetFileField.setMinimumSize(new Dimension(300, 25));
tagSetFileField.setPreferredSize(new Dimension(300, 25));
tagSetFileField.setMaximumSize(new Dimension(400, 30));
messagePanel.setLayout(new GridBagLayout());
messagePanel.add(fullTextLabel, new GridBagConstraints(0, 0, 1, 1, 0, 0
,GridBagConstraints.NORTH, GridBagConstraints.NONE, new Insets(10, 1, 1, 1), 0, 0));
messagePanel.add(scrollableTextArea, new GridBagConstraints(1, 0, 1, 1, 0.3, 0.3
, GridBagConstraints.NORTH, GridBagConstraints.BOTH, new Insets(10, 1, 1, 1), 0, 0));
messagePanel.add(messageLabel, new GridBagConstraints(0, 1, 1, 1, 0, 0
,GridBagConstraints.NORTH, GridBagConstraints.NONE, new Insets(10, 1, 1, 1), 0, 0));
messagePanel.add(messageField, new GridBagConstraints(1, 1, 1, 1, 0.3, 0.3
, GridBagConstraints.NORTH, GridBagConstraints.BOTH, new Insets(10, 1, 1, 1), 0, 0));
messagePanel.add(kafFileLabel, new GridBagConstraints(0, 2, 1, 1, 0, 0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(1, 1, 1, 1), 0, 0));
messagePanel.add(kafFileField, new GridBagConstraints(1, 2, 1, 1, 0.3, 0.3
, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(1, 1, 1, 1), 0, 0));
messagePanel.add(tagFileLabel, new GridBagConstraints(0, 3, 1, 1, 0, 0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(1, 1, 1, 1), 0, 0));
messagePanel.add(tagFileField, new GridBagConstraints(1, 3, 1, 1, 0.3, 0.3
, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(1, 1, 1, 1), 0, 0));
messagePanel.add(tagSetFileLabel, new GridBagConstraints(0, 4, 1, 1, 0, 0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(1, 1, 1, 1), 0, 0));
messagePanel.add(tagSetFileField, new GridBagConstraints(1, 4, 1, 1, 0.3, 0.3
,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(1, 1, 1, 1), 0, 0));
/// Menus
menuButtons = new JMenuBar();
fileMenu = new JMenu("File");
fileMenu.setMnemonic('f');
////
openMenuItem = new JMenuItem("Open KAF file",'o');
openMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_loadKafFile();
setCursor(current_cursor);
}
});
fileMenu.add(openMenuItem);
readTagFileMenuItem = new JMenuItem("Load TAG file",'l');
readTagFileMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_loadTagFile();
setCursor(current_cursor);
}
});
fileMenu.add(readTagFileMenuItem);
readTagSetMenuItem = new JMenuItem("Load TAG set", 't');
readTagSetMenuItem.setMnemonic('t');
readTagSetMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_readTagSet();
setCursor(current_cursor);
}
});
fileMenu.add(readTagSetMenuItem);
readLexiconMenuItem = new JMenuItem("Load lexicon file", 'x');
readLexiconMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_readLexicon();
setCursor(current_cursor);
}
});
fileMenu.add(readLexiconMenuItem);
////
saveTagMenuItem = new JMenuItem("Save tagging",'s');
saveTagMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
int ok = -1;
ok = DO_saveTagFile();
DO_saveLexiconFile();
if (ok==0) {
messageField.setText("Tagging data saved");
}
else {
messageField.setText("Warning! Tagging data NOT saved");
}
setCursor(current_cursor);
}
});
fileMenu.add(saveTagMenuItem);
////////////////////////////////////////
saveAsMenu = new JMenu("Save as");
saveAsMenu.setMnemonic('a');
saveTagAsMenuItem = new JMenuItem("Tagging",'t');
saveTagAsMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_saveTagFileAs();
setCursor(current_cursor);
}
});
saveAsMenu.add(saveTagAsMenuItem);
saveLexiconAsMenuItem = new JMenuItem("Lexicon",'l');
saveLexiconAsMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_saveLexiconFileAs();
setCursor(current_cursor);
}
});
saveAsMenu.add(saveLexiconAsMenuItem);
fileMenu.add(saveAsMenu);
////
saveTrainMenuItem = new JMenuItem("Export tags to train format",'e');
saveTrainMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_saveTrainFile();
setCursor(current_cursor);
}
});
fileMenu.add(saveTrainMenuItem);
convertTagsToTriples = new JMenuItem("Export to Triples",'e');
convertTagsToTriples.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_exportToTriples();
setCursor(current_cursor);
}
});
fileMenu.add(convertTagsToTriples);
outputMostCommonSubsumer = new JMenuItem("Export wordnet classes",'w');
outputMostCommonSubsumer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_exportMostCommonSubsumers();
setCursor(current_cursor);
}
});
fileMenu.add(outputMostCommonSubsumer);
quitMenuItem = new JMenuItem("Quit",'q');
quitMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (DO_checkSave()==2) {
System.exit(0);
}
}
});
fileMenu.add(quitMenuItem);
menuButtons.add(fileMenu);
////////////////////////////////////////
searchMenu = new JMenu("Search");
searchMenu.setMnemonic('s');
////
searchWordMenuItem = new JMenuItem("Word",'w');
searchWordMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_searchWord();
setCursor(current_cursor);
}
});
searchMenu.add(searchWordMenuItem);
////
searchLastTagMenuItem = new JMenuItem("Last tag",'l');
searchLastTagMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_searchLastTag();
setCursor(current_cursor);
}
});
searchMenu.add(searchLastTagMenuItem);
searchTagMenuItem = new JMenuItem("Tag",'t');
searchTagMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_searchTag();
setCursor(current_cursor);
}
});
searchMenu.add(searchTagMenuItem);
searchWordAgainMenuItem = new JMenuItem("Next Word",'n');
searchWordAgainMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_searchWordAgain();
setCursor(current_cursor);
}
});
searchMenu.add(searchWordAgainMenuItem);
////
searchTagAgainMenuItem = new JMenuItem("Next Tag",'x');
searchTagAgainMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_searchTagAgain();
setCursor(current_cursor);
}
});
searchMenu.add(searchTagAgainMenuItem);
////
searchNotDoneMenuItem = new JMenuItem("No Confirm",'c');
searchNotDoneMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_notDone();
setCursor(current_cursor);
}
});
searchMenu.add(searchNotDoneMenuItem);
menuButtons.add(searchMenu);
/////////////////////////////////////////////////
otherMenu = new JMenu("Other");
otherMenu.setMnemonic('o');
////
confirmMenuItem = new JMenuItem("Do Confirm",'d');
confirmMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor(Cursor.WAIT_CURSOR));
DO_Selected();
setCursor(current_cursor);
}
});
otherMenu.add(confirmMenuItem);
////
unconfirmMenuItem = new JMenuItem("Undo Confirm",'u');
unconfirmMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_Unselected();
setCursor(current_cursor);
}
});
otherMenu.add(unconfirmMenuItem);
removeAllTagsMenuItem = new JMenuItem("Remove all annotations",'r');
removeAllTagsMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_unTagAllTokens();
setCursor(current_cursor);
}
});
otherMenu.add(removeAllTagsMenuItem);
undoMenuItem = new JMenuItem("Undo",'u');
// undoMenuItem.setMaximumSize(new Dimension(70, 150));
// undoMenuItem.setBorder(BorderFactory.createLineBorder(Color.gray));
undoMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_undo();
setCursor(current_cursor);
}
});
otherMenu.add(undoMenuItem);
menuButtons.add(otherMenu);
////////////////////////////////////////////////////////
////
/////////////////////
tag1Menu = new JMenu("Tag level 1");
tag1Menu.setMnemonic('1');
tag1TokenMenu = new JMenu("Tag tokens");
tag1TokenMenu.setMnemonic('t');
tag1Menu.add(tag1TokenMenu);
tag1LemmaMenu = new JMenu("Tag types");
tag1LemmaMenu.setMnemonic('y');
tag1Menu.add(tag1LemmaMenu);
tag1ConstituentMenu = new JMenu("Tag constituent");
tag1ConstituentMenu.setMnemonic('c');
tag1Menu.add(tag1ConstituentMenu);
tag1SentenceMenu = new JMenu("Tag sentence");
tag1SentenceMenu.setMnemonic('s');
tag1Menu.add(tag1SentenceMenu);
// popup.add(tag1Menu); // just trying
JMenuItem untagItem = new JMenuItem ("UNTAG", 'u');
untagItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_unTagTokens(1);
setCursor(current_cursor);
}
});
tag1Menu.add(untagItem);
JMenuItem mergeTagIdsItem = new JMenuItem ("Merge Tag Ids", 'm');
mergeTagIdsItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_mergeTagIds(1);
setCursor(current_cursor);
}
});
tag1Menu.add(mergeTagIdsItem);
JMenuItem separateTagIdsItem = new JMenuItem ("Separate Tag Ids", 's');
separateTagIdsItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_separateTagIds(1);
setCursor(current_cursor);
}
});
tag1Menu.add(separateTagIdsItem);
JMenuItem editTagIdsItem = new JMenuItem ("Edit Tag Id", 'e');
editTagIdsItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_editTagIds(1);
setCursor(current_cursor);
}
});
tag1Menu.add(editTagIdsItem);
JMenuItem copyTagItem = new JMenuItem ("Copy Tag & Id", 'c');
copyTagItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_copyTag(1);
setCursor(current_cursor);
}
});
tag1Menu.add(copyTagItem);
JMenuItem pastTagItem = new JMenuItem ("Past Tag & Id", 'p');
pastTagItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_pastTag(1);
setCursor(current_cursor);
}
});
tag1Menu.add(pastTagItem);
JMenuItem selectLexTagMenuItem = new JMenuItem("Dominant Tag",'l');
selectLexTagMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_selectLexicalTag();
setCursor(current_cursor);
}
});
tag1Menu.add(selectLexTagMenuItem);
newTag1MenuItem = new JMenuItem("Add Tag",'a');
newTag1MenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_makeNewTag1();
setCursor(current_cursor);
}
});
tag1Menu.add(newTag1MenuItem);
menuButtons.add(tag1Menu);
//////////////////////////////////
tag2Menu = new JMenu("Tag level 2");
tag2Menu.setMnemonic('2');
tag2TokenMenu = new JMenu("Tag tokens");
tag2TokenMenu.setMnemonic('t');
tag2Menu.add(tag2TokenMenu);
tag2LemmaMenu = new JMenu("Tag types");
tag2LemmaMenu.setMnemonic('y');
tag2Menu.add(tag2LemmaMenu);
tag2ConstituentMenu = new JMenu("Tag constituent");
tag2ConstituentMenu.setMnemonic('c');
tag2Menu.add(tag2ConstituentMenu);
tag2SentenceMenu = new JMenu("Tag sentence");
tag2SentenceMenu.setMnemonic('s');
tag2Menu.add(tag2SentenceMenu);
JMenuItem untagItem2 = new JMenuItem ("UNTAG", 'u');
untagItem2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_unTagTokens(2);
setCursor(current_cursor);
}
});
tag2Menu.add(untagItem2);
JMenuItem mergeTagIdsItem2 = new JMenuItem ("Merge Tag Ids", 'm');
mergeTagIdsItem2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_mergeTagIds(2);
setCursor(current_cursor);
}
});
tag2Menu.add(mergeTagIdsItem2);
JMenuItem separateTagIdsItem2 = new JMenuItem ("Separate Tag Ids", 's');
separateTagIdsItem2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_separateTagIds(2);
setCursor(current_cursor);
}
});
tag2Menu.add(separateTagIdsItem2);
JMenuItem editTagIdsItem2 = new JMenuItem ("Edit Tag Id", 'e');
editTagIdsItem2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_editTagIds(2);
setCursor(current_cursor);
}
});
tag2Menu.add(editTagIdsItem2);
JMenuItem copyTagItem2 = new JMenuItem ("Copy Tag & Id", 'c');
copyTagItem2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_copyTag(2);
setCursor(current_cursor);
}
});
tag2Menu.add(copyTagItem2);
JMenuItem pastTagItem2 = new JMenuItem ("Past Tag & Id", 'p');
pastTagItem2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_pastTag(2);
setCursor(current_cursor);
}
});
tag2Menu.add(pastTagItem2);
newTag2MenuItem = new JMenuItem("Add Tag",'a');
newTag2MenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_makeNewTag2();
setCursor(current_cursor);
}
});
tag2Menu.add(newTag2MenuItem);
if (!tableSettings.hideTag2) {
menuButtons.add(tag2Menu);
}
/////////////////#################
tag3Menu = new JMenu("Tag level 3");
tag3Menu.setMnemonic('3');
tag3TokenMenu = new JMenu("Tag tokens");
tag3Menu.add(tag3TokenMenu);
tag3LemmaMenu = new JMenu("Tag types");
tag3LemmaMenu.setMnemonic('y');
tag3Menu.add(tag3LemmaMenu);
tag3ConstituentMenu = new JMenu("Tag constituent");
tag3ConstituentMenu.setMnemonic('c');
tag3Menu.add(tag3ConstituentMenu);
tag3SentenceMenu = new JMenu("Tag sentence");
tag3SentenceMenu.setMnemonic('s');
tag3Menu.add(tag3SentenceMenu);
JMenuItem untagItem3 = new JMenuItem ("UNTAG", 'u');
untagItem3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_unTagTokens(3);
setCursor(current_cursor);
}
});
tag3Menu.add(untagItem3);
JMenuItem mergeTagIdsItem3 = new JMenuItem ("Merge Tag Ids", 'm');
mergeTagIdsItem3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_mergeTagIds(3);
setCursor(current_cursor);
}
});
tag3Menu.add(mergeTagIdsItem3);
JMenuItem separateTagIdsItem3 = new JMenuItem ("Separate Tag Ids", 's');
separateTagIdsItem3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_separateTagIds(3);
setCursor(current_cursor);
}
});
tag3Menu.add(separateTagIdsItem3);
JMenuItem editTagIdsItem3 = new JMenuItem ("Edit Tag Id", 'e');
editTagIdsItem3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_editTagIds(3);
setCursor(current_cursor);
}
});
tag3Menu.add(editTagIdsItem3);
JMenuItem copyTagItem3 = new JMenuItem ("Copy Tag & Id", 'c');
copyTagItem3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_copyTag(3);
setCursor(current_cursor);
}
});
tag3Menu.add(copyTagItem3);
JMenuItem pastTagItem3 = new JMenuItem ("Past Tag & Id", 'p');
pastTagItem3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_pastTag(3);
setCursor(current_cursor);
}
});
tag3Menu.add(pastTagItem3);
newTag3MenuItem = new JMenuItem("Add Tag",'a');
newTag3MenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_makeNewTag3();
setCursor(current_cursor);
}
});
tag3Menu.add(newTag3MenuItem);
if (!tableSettings.hideTag3){
menuButtons.add(tag3Menu);
}
/////////////////////
tag4Menu = new JMenu("Tag level 4");
tag4Menu.setMnemonic('4');
tag4TokenMenu = new JMenu("Tag tokens");
tag4Menu.add(tag4TokenMenu);
tag4LemmaMenu = new JMenu("Tag types");
tag4LemmaMenu.setMnemonic('y');
tag4Menu.add(tag4LemmaMenu);
tag4ConstituentMenu = new JMenu("Tag constituent");
tag4ConstituentMenu.setMnemonic('c');
tag4Menu.add(tag4ConstituentMenu);
tag4SentenceMenu = new JMenu("Tag sentence");
tag4SentenceMenu.setMnemonic('s');
tag4Menu.add(tag4SentenceMenu);
JMenuItem untagItem4 = new JMenuItem ("UNTAG", 'u');
untagItem4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_unTagTokens(4);
setCursor(current_cursor);
}
});
tag4Menu.add(untagItem4);
JMenuItem mergeTagIdsItem4 = new JMenuItem ("Merge Tag Ids", 'm');
mergeTagIdsItem4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_mergeTagIds(4);
setCursor(current_cursor);
}
});
tag4Menu.add(mergeTagIdsItem4);
JMenuItem separateTagIdsItem4 = new JMenuItem ("Separate Tag Ids", 's');
separateTagIdsItem4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_separateTagIds(4);
setCursor(current_cursor);
}
});
tag4Menu.add(separateTagIdsItem4);
JMenuItem editTagIdsItem4 = new JMenuItem ("Edit Tag Id", 'e');
editTagIdsItem4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_editTagIds(4);
setCursor(current_cursor);
}
});
tag4Menu.add(editTagIdsItem4);
JMenuItem copyTagItem4 = new JMenuItem ("Copy Tag & Id", 'c');
copyTagItem4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_copyTag(4);
setCursor(current_cursor);
}
});
tag4Menu.add(copyTagItem4);
JMenuItem pastTagItem4 = new JMenuItem ("Past Tag & Id", 'p');
pastTagItem4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_pastTag(4);
setCursor(current_cursor);
}
});
tag4Menu.add(pastTagItem4);
newTag4MenuItem = new JMenuItem("Add Tag",'a');
newTag4MenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_makeNewTag4();
setCursor(current_cursor);
}
});
tag4Menu.add(newTag4MenuItem);
if (!tableSettings.hideTag4) {
menuButtons.add(tag4Menu);
}
/////////////////#################
tag5Menu = new JMenu("Tag level 5");
tag5Menu.setMnemonic('5');
tag5TokenMenu = new JMenu("Tag tokens");
tag5Menu.add(tag5TokenMenu);
tag5LemmaMenu = new JMenu("Tag types");
tag5LemmaMenu.setMnemonic('y');
tag5Menu.add(tag5LemmaMenu);
tag5ConstituentMenu = new JMenu("Tag constituent");
tag5ConstituentMenu.setMnemonic('c');
tag5Menu.add(tag5ConstituentMenu);
tag5SentenceMenu = new JMenu("Tag sentence");
tag5SentenceMenu.setMnemonic('s');
tag5Menu.add(tag5SentenceMenu);
JMenuItem untagItem5 = new JMenuItem ("UNTAG", 'u');
untagItem5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_unTagTokens(5);
setCursor(current_cursor);
}
});
tag5Menu.add(untagItem5);
JMenuItem mergeTagIdsItem5 = new JMenuItem ("Merge Tag Ids", 'm');
mergeTagIdsItem5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_mergeTagIds(5);
setCursor(current_cursor);
}
});
tag5Menu.add(mergeTagIdsItem5);
JMenuItem separateTagIdsItem5 = new JMenuItem ("Separate Tag Ids", 's');
separateTagIdsItem5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_separateTagIds(5);
setCursor(current_cursor);
}
});
tag5Menu.add(separateTagIdsItem5);
JMenuItem editTagIdsItem5 = new JMenuItem ("Edit Tag Id", 'e');
editTagIdsItem5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_editTagIds(5);
setCursor(current_cursor);
}
});
tag5Menu.add(editTagIdsItem5);
JMenuItem copyTagItem5 = new JMenuItem ("Copy Tag & Id", 'c');
copyTagItem5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_copyTag(5);
setCursor(current_cursor);
}
});
tag5Menu.add(copyTagItem5);
JMenuItem pastTagItem5 = new JMenuItem ("Past Tag & Id", 'p');
pastTagItem5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_pastTag(5);
setCursor(current_cursor);
}
});
tag5Menu.add(pastTagItem5);
newTag5MenuItem = new JMenuItem("Add Tag",'a');
newTag5MenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_makeNewTag5();
setCursor(current_cursor);
}
});
tag5Menu.add(newTag5MenuItem);
if (!tableSettings.hideTag5) {
menuButtons.add(tag5Menu);
}
/////////////////#################
tag6Menu = new JMenu("Tag level 6");
tag6Menu.setMnemonic('6');
tag6TokenMenu = new JMenu("Tag tokens");
tag6Menu.add(tag6TokenMenu);
tag6LemmaMenu = new JMenu("Tag types");
tag6LemmaMenu.setMnemonic('y');
tag6Menu.add(tag6LemmaMenu);
tag6ConstituentMenu = new JMenu("Tag constituent");
tag6ConstituentMenu.setMnemonic('c');
tag6Menu.add(tag6ConstituentMenu);
tag6SentenceMenu = new JMenu("Tag sentence");
tag6SentenceMenu.setMnemonic('s');
tag6Menu.add(tag6SentenceMenu);
JMenuItem untagItem6 = new JMenuItem ("UNTAG", 'u');
untagItem6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_unTagTokens(6);
setCursor(current_cursor);
}
});
tag6Menu.add(untagItem6);
JMenuItem mergeTagIdsItem6 = new JMenuItem ("Merge Tag Ids", 'm');
mergeTagIdsItem6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_mergeTagIds(6);
setCursor(current_cursor);
}
});
tag6Menu.add(mergeTagIdsItem6);
JMenuItem separateTagIdsItem6 = new JMenuItem ("Separate Tag Ids", 's');
separateTagIdsItem6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_separateTagIds(6);
setCursor(current_cursor);
}
});
tag6Menu.add(separateTagIdsItem6);
JMenuItem editTagIdsItem6 = new JMenuItem ("Edit Tag Id", 'e');
editTagIdsItem6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_editTagIds(6);
setCursor(current_cursor);
}
});
tag6Menu.add(editTagIdsItem6);
JMenuItem copyTagItem6 = new JMenuItem ("Copy Tag & Id", 'c');
copyTagItem6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_copyTag(6);
setCursor(current_cursor);
}
});
tag6Menu.add(copyTagItem6);
JMenuItem pastTagItem6 = new JMenuItem ("Past Tag & Id", 'p');
pastTagItem6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_pastTag(6);
setCursor(current_cursor);
}
});
tag6Menu.add(pastTagItem6);
newTag6MenuItem = new JMenuItem("Add Tag",'a');
newTag6MenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_makeNewTag6();
setCursor(current_cursor);
}
});
tag6Menu.add(newTag6MenuItem);
if (!tableSettings.hideTag6) {
menuButtons.add(tag6Menu);
}
/////////////////#################
tag7Menu = new JMenu("Tag level 7");
tag7Menu.setMnemonic('7');
tag7TokenMenu = new JMenu("Tag tokens");
tag7Menu.add(tag7TokenMenu);
tag7LemmaMenu = new JMenu("Tag types");
tag7LemmaMenu.setMnemonic('y');
tag7Menu.add(tag7LemmaMenu);
tag7ConstituentMenu = new JMenu("Tag constituent");
tag7ConstituentMenu.setMnemonic('c');
tag7Menu.add(tag7ConstituentMenu);
tag7SentenceMenu = new JMenu("Tag sentence");
tag7SentenceMenu.setMnemonic('s');
tag7Menu.add(tag7SentenceMenu);
JMenuItem untagItem7 = new JMenuItem ("UNTAG", 'u');
untagItem6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_unTagTokens(7);
setCursor(current_cursor);
}
});
tag7Menu.add(untagItem7);
JMenuItem mergeTagIdsItem7 = new JMenuItem ("Merge Tag Ids", 'm');
mergeTagIdsItem6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_mergeTagIds(7);
setCursor(current_cursor);
}
});
tag7Menu.add(mergeTagIdsItem7);
JMenuItem separateTagIdsItem7 = new JMenuItem ("Separate Tag Ids", 's');
separateTagIdsItem6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_separateTagIds(7);
setCursor(current_cursor);
}
});
tag7Menu.add(separateTagIdsItem7);
JMenuItem editTagIdsItem7 = new JMenuItem ("Edit Tag Id", 'e');
editTagIdsItem7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_editTagIds(7);
setCursor(current_cursor);
}
});
tag7Menu.add(editTagIdsItem7);
JMenuItem copyTagItem7 = new JMenuItem ("Copy Tag & Id", 'c');
copyTagItem7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_copyTag(7);
setCursor(current_cursor);
}
});
tag7Menu.add(copyTagItem7);
JMenuItem pastTagItem7 = new JMenuItem ("Past Tag & Id", 'p');
pastTagItem7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_pastTag(7);
setCursor(current_cursor);
}
});
tag7Menu.add(pastTagItem7);
newTag7MenuItem = new JMenuItem("Add Tag",'a');
newTag7MenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_makeNewTag7();
setCursor(current_cursor);
}
});
tag7Menu.add(newTag7MenuItem);
if (!tableSettings.hideTag7) {
menuButtons.add(tag7Menu);
}
/////////////////#################
tag8Menu = new JMenu("Tag level 8");
tag8Menu.setMnemonic('8');
tag8TokenMenu = new JMenu("Tag tokens");
tag8Menu.add(tag8TokenMenu);
tag8LemmaMenu = new JMenu("Tag types");
tag8LemmaMenu.setMnemonic('y');
tag8Menu.add(tag8LemmaMenu);
tag8ConstituentMenu = new JMenu("Tag constituent");
tag8ConstituentMenu.setMnemonic('c');
tag8Menu.add(tag8ConstituentMenu);
tag8SentenceMenu = new JMenu("Tag sentence");
tag8SentenceMenu.setMnemonic('s');
tag8Menu.add(tag8SentenceMenu);
JMenuItem untagItem8 = new JMenuItem ("UNTAG", 'u');
untagItem8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_unTagTokens(8);
setCursor(current_cursor);
}
});
tag8Menu.add(untagItem8);
JMenuItem mergeTagIdsItem8 = new JMenuItem ("Merge Tag Ids", 'm');
mergeTagIdsItem8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_mergeTagIds(8);
setCursor(current_cursor);
}
});
tag8Menu.add(mergeTagIdsItem8);
JMenuItem separateTagIdsItem8 = new JMenuItem ("Separate Tag Ids", 's');
separateTagIdsItem8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_separateTagIds(8);
setCursor(current_cursor);
}
});
tag8Menu.add(separateTagIdsItem8);
JMenuItem editTagIdsItem8 = new JMenuItem ("Edit Tag Id", 'e');
editTagIdsItem8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_editTagIds(8);
setCursor(current_cursor);
}
});
tag8Menu.add(editTagIdsItem8);
JMenuItem copyTagItem8 = new JMenuItem ("Copy Tag & Id", 'c');
copyTagItem8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_copyTag(8);
setCursor(current_cursor);
}
});
tag8Menu.add(copyTagItem8);
JMenuItem pastTagItem8 = new JMenuItem ("Past Tag & Id", 'p');
pastTagItem8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_pastTag(8);
setCursor(current_cursor);
}
});
tag8Menu.add(pastTagItem8);
newTag8MenuItem = new JMenuItem("Add Tag",'a');
newTag8MenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Cursor current_cursor = getCursor();
setCursor(new Cursor ( Cursor.WAIT_CURSOR ));
DO_makeNewTag8();
setCursor(current_cursor);
}
});
tag8Menu.add(newTag8MenuItem);
if (!tableSettings.hideTag8) {
menuButtons.add(tag8Menu);
}
/// Text Area
table = new AnnotationTable(tableSettings);
///////////////////////
contentPanel = new JPanel();
setContentPane(contentPanel);
contentPanel.setLayout(new GridBagLayout());
contentPanel.add(menuButtons, new GridBagConstraints(0, 0, 1, 1, 0, 0
,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(10, 10, 10, 10), 15, 15));
contentPanel.add(table, new GridBagConstraints(0, 1, 1, 1, 0.3, 0.3
,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(10, 10, 10, 10), 0, 0));
contentPanel.add(messagePanel, new GridBagConstraints(0, 3, 1, 1, 0.3, 0.3
,GridBagConstraints.SOUTH, GridBagConstraints.HORIZONTAL, new Insets(10, 10, 10, 10), 0, 0));
}
|
diff --git a/src/test/java/pl/booone/iplay/utilities/hibernate/processors/TestGameProcessor.java b/src/test/java/pl/booone/iplay/utilities/hibernate/processors/TestGameProcessor.java
index 7692865..4585345 100644
--- a/src/test/java/pl/booone/iplay/utilities/hibernate/processors/TestGameProcessor.java
+++ b/src/test/java/pl/booone/iplay/utilities/hibernate/processors/TestGameProcessor.java
@@ -1,366 +1,366 @@
package pl.booone.iplay.utilities.hibernate.processors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import pl.booone.iplay.models.ageratings.pegi.PegiEnum;
import pl.booone.iplay.models.companies.CompanyDAO;
import pl.booone.iplay.models.companies.CompanyDTO;
import pl.booone.iplay.models.games.GameDTO;
import pl.booone.iplay.models.games.GameStatusEnum;
import pl.booone.iplay.models.gametypes.GameTypeDAO;
import pl.booone.iplay.models.gametypes.GameTypeDTO;
import pl.booone.iplay.models.gametypes.GameTypeEnum;
import pl.booone.iplay.models.platforms.PlatformDAO;
import pl.booone.iplay.models.platforms.PlatformDTO;
import pl.booone.iplay.models.platforms.PlatformEnum;
import pl.booone.iplay.utilities.hibernate.processors.exceptions.TestGameProcessorException;
import pl.booone.iplay.utilities.loggers.GeneralLogger;
import pl.booone.iplay.utilities.string.DateConverter;
import java.text.ParseException;
import java.util.*;
import static pl.booone.iplay.utilities.hibernate.processors.TestGameProcessor.FieldType.*;
/**
* Creates a GameDTO from format:
* |Title|dd.MM.yyyy premiereDate|PEGI18|FPP,SHOOTER
* |PlatformDTO,PlatformDTO|CompanyDTO,CompanyDTO|CompanyDTO,CompanyDTO|points|Status|dd.MM.yyy HH:mm:ss addedDate
*/
@Component
public class TestGameProcessor
{
private static final String FIXED_GAME_FIELD_SEPARATOR = "|";
private static final String FIXED_GAME_ARRAY_SEPARATOR = ",";
@Autowired
private CompanyDAO companyDAO;
@Autowired
private GameTypeDAO gameTypeDAO;
@Autowired
private PlatformDAO platformDAO;
public GameDTO getGameDTOFromFixedString(String fixedGame) throws TestGameProcessorException
{
if (fixedGame == null)
{
throw new TestGameProcessorException("Trying to create UserDTO from null String");
}
String[] userProperties = fixedGame.split(FIXED_GAME_FIELD_SEPARATOR);
userProperties = checkAndRepairFields(userProperties);
return generateGameFromProperties(userProperties);
}
private GameDTO generateGameFromProperties(String[] userProperties) throws TestGameProcessorException
{
GameDTO gameDTO = new GameDTO();
gameDTO.setTitle(getString(userProperties, Field.GAME_TITLE));
gameDTO.setPremiereDate(getDate(userProperties, Field.GAME_PREMIERE_DATE));
gameDTO.setPegiRating(getPegiEnum(getString(userProperties, Field.GAME_PEGI_ENUM)));
gameDTO.setGameTypes(getOrGenerateGameTypesList(getStringList(userProperties, Field.GAME_TYPES)));
gameDTO.setPlatforms(getOrGeneratePlatformsList(getStringList(userProperties, Field.GAME_PLATFORMS)));
gameDTO.setProducers(getOrGenerateCompaniesList(getStringList(userProperties, Field.GAME_PRODUCERS)));
gameDTO.setPublishers(getOrGenerateCompaniesList(getStringList(userProperties, Field.GAME_PUBLISHERS)));
try
{
gameDTO.setPoints(Integer.valueOf(getString(userProperties, Field.GAME_POINTS)));
}
catch (NumberFormatException ex)
{
- GeneralLogger.warn(this, "Number format exception while parsing points field: " + Arrays.toString(userProperties) + ", defaulting point to 0");
+ GeneralLogger.warn(this, "Number format exception while parsing points field: " + Arrays.toString(userProperties) + ", defaulting points to 0");
gameDTO.setPoints(0);
}
gameDTO.setGameStatus(getGameStatusEnum(getString(userProperties, Field.GAME_STATUS)));
gameDTO.setAddedDate(getDate(userProperties, Field.GAME_ADDED_DATE_TIME));
GeneralLogger.info(this, "Generated game: " + gameDTO.toString());
return gameDTO;
}
private String[] checkAndRepairFields(String[] userProperties) throws TestGameProcessorException
{
if (userProperties == null || userProperties.length == 0
|| userProperties.length != Field.values().length)
{
throw new TestGameProcessorException("fixed.user.property: " + Arrays.toString(userProperties) + " has wrong format, omitting.");
}
for (Field field : Field.values())
{
userProperties = checkAndRepair(userProperties, field);
}
return userProperties;
}
private String[] checkAndRepair(String[] userProperties, Field field) throws TestGameProcessorException
{
String property = getString(userProperties, field);
FieldType fieldType1 = field.getFieldType();
switch (fieldType1)
{
case STRING_ARRAY:
userProperties[field.getIndexPosition()] = fixStringArray(property);
break;
case DATE:
userProperties[field.getIndexPosition()] = fixDate(property);
break;
case DATETIME:
userProperties[field.getIndexPosition()] = fixDateTime(property);
break;
default:
userProperties[field.getIndexPosition()] = fixString(property);
break;
}
return userProperties;
}
private Set<CompanyDTO> getOrGenerateCompaniesList(List<String> companiesNames) throws TestGameProcessorException
{
Set<CompanyDTO> companiesList = new HashSet<CompanyDTO>();
for (String companyName : companiesNames)
{
companiesList.add(getOrGenerateCompany(companyName));
}
return companiesList;
}
private CompanyDTO getOrGenerateCompany(String companyName) throws TestGameProcessorException
{
CompanyDTO companyByName =
companyDAO.getCompanyByName(companyName);
if (companyByName == null)
{
GeneralLogger.warn(this, "Company not found, generating new from name [" + companyName + "]");
CompanyDTO companyDTO = new CompanyDTO(companyName);
companyDAO.saveOrUpdateCompany(companyDTO);
companyByName = companyDAO.getCompanyByName(companyName);
}
return companyByName;
}
private Set<GameTypeDTO> getOrGenerateGameTypesList(List<String> gameTypesNames)
{
Set<GameTypeDTO> gameTypeDTOList = new HashSet<GameTypeDTO>();
for (String gameTypeName : gameTypesNames)
{
gameTypeDTOList.add(getOrGenerateGameType(gameTypeName));
}
return gameTypeDTOList;
}
private GameTypeDTO getOrGenerateGameType(String gameTypeName)
{
GameTypeEnum gameTypeEnum;
try
{
gameTypeEnum = GameTypeEnum.valueOf(gameTypeName);
}
catch (IllegalArgumentException ex)
{
gameTypeEnum = GameTypeEnum.UNKNOWN;
}
return gameTypeDAO.getGameType(gameTypeEnum.getId());
}
private Set<PlatformDTO> getOrGeneratePlatformsList(List<String> platformNames)
{
Set<PlatformDTO> platformDTOs = new HashSet<PlatformDTO>();
for (String platformName : platformNames)
{
platformDTOs.add(getOrGeneratePlatform(platformName));
}
return platformDTOs;
}
private PlatformDTO getOrGeneratePlatform(String platformName)
{
PlatformEnum platformEnum;
try
{
platformEnum = PlatformEnum.valueOf(platformName);
}
catch (IllegalArgumentException ex)
{
platformEnum = PlatformEnum.UNKNOWN;
}
return platformDAO.getPlatform(platformEnum.getId());
}
private PegiEnum getPegiEnum(String enumValue)
{
try
{
return PegiEnum.valueOf(enumValue);
}
catch (IllegalArgumentException ex)
{
return PegiEnum.UNKNOWN;
}
}
private GameStatusEnum getGameStatusEnum(String enumValue)
{
try
{
return GameStatusEnum.valueOf(enumValue);
}
catch (IllegalArgumentException ex)
{
return GameStatusEnum.UNKNOWN;
}
}
private String fixString(String string)
{
if (string == null)
{
return "";
}
return string.trim();
}
private String fixStringArray(String string)
{
if (string == null)
{
return fixString(string);
}
String[] splitted = string.split(FIXED_GAME_ARRAY_SEPARATOR);
if (splitted == null)
{
return fixString(string);
}
StringBuilder sb = new StringBuilder();
for (String split : splitted)
{
sb.append(split.trim()).append(FIXED_GAME_ARRAY_SEPARATOR);
}
for (int i = 0; i < FIXED_GAME_ARRAY_SEPARATOR.length(); i++)
{
sb.deleteCharAt(sb.length() - 1);
}
return sb.toString();
}
private String fixDate(String string)
{
try
{
return DateConverter.getDateString(DateConverter.getDate(string));
}
catch (ParseException e)
{
GeneralLogger.warn(this, "Parse exception when fixing date [" + string + "], defaulting it to current system time.");
}
return DateConverter.getDateString(new Date(System.currentTimeMillis()));
}
private String fixDateTime(String string)
{
try
{
return DateConverter.getDateTimeString(DateConverter.getDate(string));
}
catch (ParseException e)
{
GeneralLogger.warn(this, "Parse exception when fixing datetime [" + string + "], defaulting it to current system time.");
}
return DateConverter.getDateTimeString(new Date(System.currentTimeMillis()));
}
//PROPERTIES_FIELD_ENUM(arrayIndex,FieldType)
public enum Field
{
GAME_TITLE(0, STRING),
GAME_PREMIERE_DATE(1, DATE),
GAME_PEGI_ENUM(2, STRING),
GAME_TYPES(3, STRING_ARRAY),
GAME_PLATFORMS(4, STRING_ARRAY),
GAME_PRODUCERS(5, STRING_ARRAY),
GAME_PUBLISHERS(6, STRING_ARRAY),
GAME_POINTS(7, STRING),
GAME_STATUS(8, STRING),
GAME_ADDED_DATE_TIME(9, DATETIME);
private int indexPosition;
private FieldType fieldType;
Field(int newIndexPosition, FieldType fieldType)
{
this.indexPosition = newIndexPosition;
this.fieldType = fieldType;
}
public int getIndexPosition()
{
return this.indexPosition;
}
public FieldType getFieldType()
{
return fieldType;
}
}
public enum FieldType
{
STRING,
STRING_ARRAY,
DATE,
DATETIME
}
private Date getDate(String[] userProperties, Field fieldType) throws TestGameProcessorException
{
if (fieldType.getFieldType() != DATE)
{
throw new TestGameProcessorException("GetDate - wrong function used to get field of type " + fieldType.name());
}
String dateInString = getString(userProperties, fieldType);
try
{
return DateConverter.getDate(dateInString);
}
catch (ParseException e)
{
throw new TestGameProcessorException("Date parse exception for property: " + dateInString);
}
}
private String getString(String[] userProperties, Field fieldType) throws TestGameProcessorException
{
return getStringList(userProperties, fieldType).get(0);
}
private List<String> getStringList(String[] userProperties, Field fieldType) throws TestGameProcessorException
{
if (userProperties.length < fieldType.getIndexPosition())
{
throw new TestGameProcessorException("Wrong property index - ArrayOutOfBounds exception for " + Arrays.toString(userProperties) + " for fieldType " + fieldType.name());
}
return getSplittedList(userProperties[fieldType.getIndexPosition()]);
}
private List<String> getSplittedList(String property) throws TestGameProcessorException
{
String[] propertiesArray = property.split(",");
List<String> resultProperties = new LinkedList<String>();
if (propertiesArray == null)
{
throw new TestGameProcessorException("Property is null after array split: " + property);
}
else
{
for (String resultProperty : propertiesArray)
{
String trimmedProperty = resultProperty.trim();
if (!resultProperties.contains(trimmedProperty)
&& !trimmedProperty.isEmpty())
{
resultProperties.add(trimmedProperty);
}
}
}
return resultProperties;
}
}
| true | true | private GameDTO generateGameFromProperties(String[] userProperties) throws TestGameProcessorException
{
GameDTO gameDTO = new GameDTO();
gameDTO.setTitle(getString(userProperties, Field.GAME_TITLE));
gameDTO.setPremiereDate(getDate(userProperties, Field.GAME_PREMIERE_DATE));
gameDTO.setPegiRating(getPegiEnum(getString(userProperties, Field.GAME_PEGI_ENUM)));
gameDTO.setGameTypes(getOrGenerateGameTypesList(getStringList(userProperties, Field.GAME_TYPES)));
gameDTO.setPlatforms(getOrGeneratePlatformsList(getStringList(userProperties, Field.GAME_PLATFORMS)));
gameDTO.setProducers(getOrGenerateCompaniesList(getStringList(userProperties, Field.GAME_PRODUCERS)));
gameDTO.setPublishers(getOrGenerateCompaniesList(getStringList(userProperties, Field.GAME_PUBLISHERS)));
try
{
gameDTO.setPoints(Integer.valueOf(getString(userProperties, Field.GAME_POINTS)));
}
catch (NumberFormatException ex)
{
GeneralLogger.warn(this, "Number format exception while parsing points field: " + Arrays.toString(userProperties) + ", defaulting point to 0");
gameDTO.setPoints(0);
}
gameDTO.setGameStatus(getGameStatusEnum(getString(userProperties, Field.GAME_STATUS)));
gameDTO.setAddedDate(getDate(userProperties, Field.GAME_ADDED_DATE_TIME));
GeneralLogger.info(this, "Generated game: " + gameDTO.toString());
return gameDTO;
}
| private GameDTO generateGameFromProperties(String[] userProperties) throws TestGameProcessorException
{
GameDTO gameDTO = new GameDTO();
gameDTO.setTitle(getString(userProperties, Field.GAME_TITLE));
gameDTO.setPremiereDate(getDate(userProperties, Field.GAME_PREMIERE_DATE));
gameDTO.setPegiRating(getPegiEnum(getString(userProperties, Field.GAME_PEGI_ENUM)));
gameDTO.setGameTypes(getOrGenerateGameTypesList(getStringList(userProperties, Field.GAME_TYPES)));
gameDTO.setPlatforms(getOrGeneratePlatformsList(getStringList(userProperties, Field.GAME_PLATFORMS)));
gameDTO.setProducers(getOrGenerateCompaniesList(getStringList(userProperties, Field.GAME_PRODUCERS)));
gameDTO.setPublishers(getOrGenerateCompaniesList(getStringList(userProperties, Field.GAME_PUBLISHERS)));
try
{
gameDTO.setPoints(Integer.valueOf(getString(userProperties, Field.GAME_POINTS)));
}
catch (NumberFormatException ex)
{
GeneralLogger.warn(this, "Number format exception while parsing points field: " + Arrays.toString(userProperties) + ", defaulting points to 0");
gameDTO.setPoints(0);
}
gameDTO.setGameStatus(getGameStatusEnum(getString(userProperties, Field.GAME_STATUS)));
gameDTO.setAddedDate(getDate(userProperties, Field.GAME_ADDED_DATE_TIME));
GeneralLogger.info(this, "Generated game: " + gameDTO.toString());
return gameDTO;
}
|
diff --git a/web/src/org/openmrs/web/controller/nealreports/NealReportController.java b/web/src/org/openmrs/web/controller/nealreports/NealReportController.java
index e885828..c4de8c7 100644
--- a/web/src/org/openmrs/web/controller/nealreports/NealReportController.java
+++ b/web/src/org/openmrs/web/controller/nealreports/NealReportController.java
@@ -1,814 +1,814 @@
/**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.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://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.web.controller.nealreports;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.Cohort;
import org.openmrs.Concept;
import org.openmrs.DrugOrder;
import org.openmrs.Encounter;
import org.openmrs.Obs;
import org.openmrs.Patient;
import org.openmrs.PatientIdentifier;
import org.openmrs.PatientIdentifierType;
import org.openmrs.PatientProgram;
import org.openmrs.PatientState;
import org.openmrs.Person;
import org.openmrs.Program;
import org.openmrs.ProgramWorkflow;
import org.openmrs.RelationshipType;
import org.openmrs.api.ConceptService;
import org.openmrs.api.PatientSetService;
import org.openmrs.api.PersonService;
import org.openmrs.api.context.Context;
import org.openmrs.util.OpenmrsUtil;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import org.springframework.web.servlet.view.AbstractView;
import reports.ReportMaker;
import reports.RwandaReportMaker;
import reports.keys.General;
import reports.keys.Hiv;
import reports.keys.Report;
import reports.keys.TB;
public class NealReportController implements Controller {
protected final Log log = LogFactory.getLog(getClass());
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
String reportType = request.getParameter("reportType");
String fDate = ServletRequestUtils.getStringParameter(request, "fDate", "");
String tDate = ServletRequestUtils.getStringParameter(request, "tDate", "");
SimpleDateFormat sdfEntered = OpenmrsUtil.getDateFormat();
SimpleDateFormat sdfExpected = new SimpleDateFormat("yyyy-MM-dd");
Date fromDate = null;
Date toDate = null;
if (fDate.length() > 0) {
try {
fromDate = sdfEntered.parse(fDate);
}
catch (ParseException e) {
fromDate = null;
}
}
if (tDate.length() > 0) {
try {
toDate = sdfEntered.parse(tDate);
}
catch (ParseException e) {
toDate = null;
}
}
String programName = Context.getAdministrationService().getGlobalProperty("reporting.programName");
if (programName == null)
programName = "rwanda";
if (programName.length() == 0)
programName = "rwanda";
Map reportConfig = new HashMap();
reportConfig.put("program", programName);
if (fromDate != null) {
String from = sdfExpected.format(fromDate);
log.debug("Adding fromDate of " + from + " to NEALREPORT");
reportConfig.put(Report.START_REPORT_PERIOD, from);
} else {
log.debug("NO FROMDATE TO ADD");
}
if (toDate != null) {
String to = sdfExpected.format(toDate);
log.debug("Adding toDate of " + to + " to NEALREPORT");
reportConfig.put(Report.END_REPORT_PERIOD, to);
} else {
log.debug("NO TO TO ADD");
}
RwandaReportMaker maker = (RwandaReportMaker) ReportMaker.configureReport(reportConfig);
maker.setParameter("report_type", reportType);
Locale locale = Context.getLocale();
ConceptService cs = Context.getConceptService();
PatientSetService pss = Context.getPatientSetService();
String patientSetParameter = request.getParameter("patientIds");
Cohort ps;
if (patientSetParameter != null && patientSetParameter.length() > 0) {
ps = new Cohort(patientSetParameter.trim());
} else {
ps = pss.getAllPatients();
}
Map<Integer, Map<String, String>> patientDataHolder = new HashMap<Integer, Map<String, String>>();
List<String> attributesToGet = new ArrayList<String>();
Map<String, String> attributeNamesForReportMaker = new HashMap<String, String>();
attributeHelper(attributesToGet, attributeNamesForReportMaker, "Patient.patientId", General.ID);
attributeHelper(attributesToGet, attributeNamesForReportMaker, "PersonName.givenName", General.FIRST_NAME);
attributeHelper(attributesToGet, attributeNamesForReportMaker, "PersonName.familyName", General.LAST_NAME);
attributeHelper(attributesToGet, attributeNamesForReportMaker, "Patient.birthdate", General.BIRTHDAY);
attributeHelper(attributesToGet, attributeNamesForReportMaker, "Patient.gender", General.SEX);
attributeHelper(attributesToGet, attributeNamesForReportMaker, "Patient.dead", General.HAS_DIED);
attributeHelper(attributesToGet, attributeNamesForReportMaker, "Patient.deathDate", General.DEATH_DATE);
attributeHelper(attributesToGet, attributeNamesForReportMaker, "PersonAddress.stateProvince", General.PROVINCE);
attributeHelper(attributesToGet, attributeNamesForReportMaker, "PersonAddress.countyDistrict", General.DISTRICT);
attributeHelper(attributesToGet, attributeNamesForReportMaker, "PersonAddress.cityVillage", General.SECTOR);
attributeHelper(attributesToGet, attributeNamesForReportMaker, "PersonAddress.neighborhoodCell", General.CELL);
attributeHelper(attributesToGet, attributeNamesForReportMaker, "PersonAddress.address1", General.UMUDUGUDU);
// General.ADDRESS
// General.USER_ID (this is actually patient identifier)
// General.DUE_DATE if pregnant
// Hiv.ACCOMP_FIRST_NAME
// Hiv.ACCOMP_LAST_NAME
// General.PREGNANT_P
// General.PMTCT (get meds for ptme? ask CA)
// General.FORMER_GROUP (previous ARV group)
List<Concept> conceptsToGet = new ArrayList<Concept>();
Map<Concept, String> namesForReportMaker = new HashMap<Concept, String>();
//conceptHelper(cs, conceptsToGet, namesForReportMaker, "TREATMENT GROUP", Hiv.TREATMENT_GROUP);
//conceptHelper(cs, conceptsToGet, namesForReportMaker, "TUBERCULOSIS TREATMENT GROUP", TB.TB_GROUP);
//conceptHelper(cs, conceptsToGet, namesForReportMaker, "CURRENT WHO HIV STAGE", Hiv.WHO_STAGE);
// TODO: replace static concepts for current groups
List<Concept> dynamicConceptsToGet = new ArrayList<Concept>();
Map<Concept, String> obsTypesForDynamicConcepts = new HashMap<Concept, String>();
dynamicConceptHelper(cs, dynamicConceptsToGet, obsTypesForDynamicConcepts, "WEIGHT (KG)", "weight");
dynamicConceptHelper(cs, dynamicConceptsToGet, obsTypesForDynamicConcepts, "HEIGHT (CM)", "height");
dynamicConceptHelper(cs, dynamicConceptsToGet, obsTypesForDynamicConcepts, "CD4 COUNT", Hiv.CD4COUNT);
dynamicConceptHelper(cs, dynamicConceptsToGet, obsTypesForDynamicConcepts, "CD4%", Hiv.CD4PERCENT);
//dynamicConceptHelper(cs, dynamicConceptsToGet, obsTypesForDynamicConcepts, "TREATMENT GROUP", Hiv.TREATMENT_GROUP);
//dynamicConceptHelper(cs, dynamicConceptsToGet, obsTypesForDynamicConcepts, "TUBERCULOSIS TREATMENT GROUP", TB.TB_GROUP);
dynamicConceptHelper(cs, dynamicConceptsToGet, obsTypesForDynamicConcepts, "CURRENT WHO HIV STAGE", Hiv.WHO_STAGE);
dynamicConceptHelper(cs, dynamicConceptsToGet, obsTypesForDynamicConcepts, "REASON FOR EXITING CARE",
General.OUTCOME);
dynamicConceptHelper(cs, dynamicConceptsToGet, obsTypesForDynamicConcepts, "PATIENT RECEIVED FOOD PACKAGE",
General.RECEIVE_FOOD);
dynamicConceptHelper(cs, dynamicConceptsToGet, obsTypesForDynamicConcepts, "TIME OF DAILY ACCOMPAGNATEUR VISIT",
Hiv.TIME_OF_ACCOMP_VISIT);
dynamicConceptHelper(cs, dynamicConceptsToGet, obsTypesForDynamicConcepts, "TRANSFER IN FROM",
General.TRANSFERRED_IN_FROM);
dynamicConceptHelper(cs, dynamicConceptsToGet, obsTypesForDynamicConcepts, "TRANSFER IN DATE",
General.TRANSFERRED_IN_DATE);
// TODO: replace dynamic concepts for current groups
long l = System.currentTimeMillis();
for (String attr : attributesToGet) {
String nameToUse = attributeNamesForReportMaker.get(attr);
Map<Integer, Object> temp = pss.getPatientAttributes(ps, attr, false);
for (Map.Entry<Integer, Object> e : temp.entrySet()) {
Integer ptId = e.getKey();
Map<String, String> holder = (Map<String, String>) patientDataHolder.get(ptId);
if (holder == null) {
holder = new HashMap<String, String>();
patientDataHolder.put(ptId, holder);
}
if (e.getValue() != null) {
Object obj = e.getValue();
String valToUse = null;
if (obj instanceof Date) {
valToUse = formatDate((Date) obj);
} else {
valToUse = obj.toString();
}
log.debug("Putting [" + nameToUse + "][" + valToUse + "] in report");
holder.put(nameToUse, valToUse);
} else {
log.debug("No value for " + nameToUse);
}
}
}
// quick hack: switch from Patient.healthCenter to PersonAttribute('Health Center')
// old version: attributeHelper(attributesToGet, attributeNamesForReportMaker, "Patient.healthCenter", General.SITE);
{
Map<Integer, Object> temp = pss
.getPersonAttributes(ps, "Health Center", "Location", "locationId", "name", false);
for (Map.Entry<Integer, Object> e : temp.entrySet()) {
if (e.getValue() == null)
continue;
Integer ptId = e.getKey();
Map<String, String> holder = (Map<String, String>) patientDataHolder.get(ptId);
if (holder == null) {
holder = new HashMap<String, String>();
patientDataHolder.put(ptId, holder);
}
String nameToUse = General.SITE;
String valToUse = e.getValue().toString();
holder.put(nameToUse, valToUse);
}
}
// modified by CA on 5 Dec 2006
// to do a data dump so that we can fill in missing IMB IDs
List<Patient> patients = Context.getPatientSetService().getPatients(ps.getMemberIds());
for (Patient p : patients) {
if (p.getActiveIdentifiers() != null) {
for (PatientIdentifier pId : p.getActiveIdentifiers()) {
PatientIdentifierType idType = pId.getIdentifierType();
if (idType.getName().equalsIgnoreCase("imb id")) {
String identifier = pId.getIdentifier();
Map<String, String> holder = (Map<String, String>) patientDataHolder.get(p.getPatientId());
if (holder == null)
holder = new HashMap<String, String>();
holder.put(General.USER_ID, identifier);
}
}
}
}
log.debug("Pulled attributesToGet in " + (System.currentTimeMillis() - l) + " ms");
l = System.currentTimeMillis();
for (Concept c : conceptsToGet) {
long l1 = System.currentTimeMillis();
String nameToUse = namesForReportMaker.get(c);
Map<Integer, List<Obs>> temp = pss.getObservations(ps, c);
long l2 = System.currentTimeMillis();
for (Map.Entry<Integer, List<Obs>> e : temp.entrySet()) {
Integer ptId = e.getKey();
Map<String, String> holder = (Map<String, String>) patientDataHolder.get(ptId);
if (holder == null) {
holder = new HashMap<String, String>();
patientDataHolder.put(ptId, holder);
}
holder.put(nameToUse, e.getValue().get(0).getValueAsString(locale));
}
long l3 = System.currentTimeMillis();
log.debug("\t" + nameToUse + " " + c + " step 1: " + (l2 - l1) + " ms. step 2: " + (l3 - l2) + " ms.");
}
log.debug("Pulled conceptsToGet in " + (System.currentTimeMillis() - l) + " ms");
l = System.currentTimeMillis();
// General.ENROLL_DATE
// Hiv.TREATMENT_STATUS
// General.HIV_POSITIVE_P
// General.TB_ACTIVE_P
- Program hivProgram = Context.getProgramWorkflowService().getProgram("HIV PROGRAM");
+ Program hivProgram = Context.getProgramWorkflowService().getProgramByName("HIV PROGRAM");
if (hivProgram != null) {
Map<Integer, PatientProgram> progs = pss.getCurrentPatientPrograms(ps, hivProgram);
for (Map.Entry<Integer, PatientProgram> e : progs.entrySet()) {
patientDataHolder.get(e.getKey()).put(General.HIV_POSITIVE_P, "t");
patientDataHolder.get(e.getKey()).put(General.ENROLL_DATE, formatDate(e.getValue().getDateEnrolled()));
//log.debug(e.getValue().getDateEnrolled());
}
- ProgramWorkflow wf = Context.getProgramWorkflowService().getWorkflow(hivProgram, "TREATMENT STATUS");
+ ProgramWorkflow wf = hivProgram.getWorkflowByName("TREATMENT STATUS");
log.debug("worlflow is " + wf + " and patientSet is " + ps);
Map<Integer, PatientState> states = pss.getCurrentStates(ps, wf);
if (states != null) {
log.debug("about to loop through [" + states.size() + "] statuses");
for (Map.Entry<Integer, PatientState> e : states.entrySet()) {
patientDataHolder.get(e.getKey()).put(Hiv.TREATMENT_STATUS,
e.getValue().getState().getConcept().getName(locale, false).getName());
log.debug("Just put state [" + e.getValue().getState().getConcept().getName(locale).getName()
+ "] in for patient [" + e.getKey() + "]");
// also want to add dynamically
PatientState state = e.getValue();
Map<String, String> holder = new HashMap<String, String>();
holder.put(General.ID, e.getKey().toString());
holder.put(Hiv.OBS_TYPE, Hiv.TREATMENT_STATUS);
holder.put(Hiv.OBS_DATE, formatDate(state.getStartDate()));
holder.put("stop_date", formatDate(state.getEndDate()));
holder.put(Hiv.RESULT, state.getState().getConcept().getName(locale).getName());
maker.addDynamic(holder);
}
} else {
log.debug("states is null, can't proceed");
}
- wf = Context.getProgramWorkflowService().getWorkflow(hivProgram, "TREATMENT GROUP");
+ wf = hivProgram.getWorkflowByName("TREATMENT GROUP");
log.debug("worlflow is " + wf + " and patientSet is " + ps);
states = pss.getCurrentStates(ps, wf);
if (states != null) {
log.debug("about to loop through [" + states.size() + "] statuses");
for (Map.Entry<Integer, PatientState> e : states.entrySet()) {
patientDataHolder.get(e.getKey()).put(Hiv.TREATMENT_GROUP,
e.getValue().getState().getConcept().getName(locale, false).getName());
log.debug("Just put state [" + e.getValue().getState().getConcept().getName(locale).getName()
+ "] in for patient [" + e.getKey() + "]");
// also want to add dynamically
PatientState state = e.getValue();
Map<String, String> holder = new HashMap<String, String>();
holder.put(General.ID, e.getKey().toString());
holder.put(Hiv.OBS_TYPE, Hiv.TREATMENT_GROUP);
holder.put(Hiv.OBS_DATE, formatDate(state.getStartDate()));
holder.put("stop_date", formatDate(state.getEndDate()));
holder.put(Hiv.RESULT, state.getState().getConcept().getName(locale).getName());
maker.addDynamic(holder);
}
} else {
log.debug("states is null, can't proceed");
}
} else {
log.debug("Couldn't find HIV PROGRAM");
}
- Program tbProgram = Context.getProgramWorkflowService().getProgram("TUBERCULOSIS PROGRAM");
+ Program tbProgram = Context.getProgramWorkflowService().getProgramByName("TUBERCULOSIS PROGRAM");
if (tbProgram != null) {
Map<Integer, PatientProgram> progs = pss.getCurrentPatientPrograms(ps, tbProgram);
for (Map.Entry<Integer, PatientProgram> e : progs.entrySet()) {
patientDataHolder.get(e.getKey()).put(General.TB_ACTIVE_P, "t");
patientDataHolder.get(e.getKey()).put(TB.TB_ENROLL_DATE, formatDate(e.getValue().getDateEnrolled()));
}
- ProgramWorkflow wf = Context.getProgramWorkflowService().getWorkflow(tbProgram, "TREATMENT STATUS");
+ ProgramWorkflow wf = tbProgram.getWorkflowByName("TREATMENT STATUS");
log.debug("worlflow is " + wf + " and patientSet is " + ps);
Map<Integer, PatientState> states = pss.getCurrentStates(ps, wf);
if (states != null) {
log.debug("about to loop through [" + states.size() + "] statuses");
for (Map.Entry<Integer, PatientState> e : states.entrySet()) {
patientDataHolder.get(e.getKey()).put(TB.TB_TREATMENT_STATUS,
e.getValue().getState().getConcept().getName(locale, false).getName());
log.debug("Just put state [" + e.getValue().getState().getConcept().getName(locale).getName()
+ "] in for patient [" + e.getKey() + "]");
// also want to add dynamically
PatientState state = e.getValue();
Map<String, String> holder = new HashMap<String, String>();
holder.put(General.ID, e.getKey().toString());
holder.put(Hiv.OBS_TYPE, TB.TB_TREATMENT_STATUS);
holder.put(Hiv.OBS_DATE, formatDate(state.getStartDate()));
holder.put("stop_date", formatDate(state.getEndDate()));
holder.put(Hiv.RESULT, state.getState().getConcept().getName(locale).getName());
maker.addDynamic(holder);
}
} else {
log.debug("states is null, can't proceed");
}
- wf = Context.getProgramWorkflowService().getWorkflow(tbProgram, "TUBERCULOSIS TREATMENT GROUP");
+ wf = tbProgram.getWorkflowByName("TUBERCULOSIS TREATMENT GROUP");
log.debug("worlflow is " + wf + " and patientSet is " + ps);
states = pss.getCurrentStates(ps, wf);
if (states != null) {
log.debug("about to loop through [" + states.size() + "] statuses");
for (Map.Entry<Integer, PatientState> e : states.entrySet()) {
patientDataHolder.get(e.getKey()).put(TB.TB_GROUP,
e.getValue().getState().getConcept().getName(locale, false).getName());
log.debug("Just put state [" + e.getValue().getState().getConcept().getName(locale).getName()
+ "] in for patient [" + e.getKey() + "]");
// also want to add dynamically
PatientState state = e.getValue();
Map<String, String> holder = new HashMap<String, String>();
holder.put(General.ID, e.getKey().toString());
holder.put(Hiv.OBS_TYPE, TB.TB_GROUP);
holder.put(Hiv.OBS_DATE, formatDate(state.getStartDate()));
holder.put("stop_date", formatDate(state.getEndDate()));
holder.put(Hiv.RESULT, state.getState().getConcept().getName(locale).getName());
maker.addDynamic(holder);
}
} else {
log.debug("states is null, can't proceed");
}
}
log.debug("Pulled enrollments and hiv treatment status in " + (System.currentTimeMillis() - l) + " ms");
l = System.currentTimeMillis();
{
PersonService personService = Context.getPersonService();
- RelationshipType relType = personService.findRelationshipType("Accompagnateur/Patient");
+ RelationshipType relType = personService.getRelationshipTypeByName("Accompagnateur/Patient");
if (relType != null) {
// get the accomp leader as well
RelationshipType accompLeaderType = personService
- .findRelationshipType("Accompagnateur Leader/Opposite of Accompagnateur Leader");
+ .getRelationshipTypeByName("Accompagnateur Leader/Opposite of Accompagnateur Leader");
Map<Integer, List<Person>> accompRelations = null;
if (accompLeaderType != null)
accompRelations = pss.getRelatives(null, accompLeaderType, false);
else
accompRelations = new HashMap<Integer, List<Person>>();
Map<Integer, List<Person>> chws = pss.getRelatives(ps, relType, false);
for (Map.Entry<Integer, List<Person>> e : chws.entrySet()) {
Person chw = e.getValue().get(0);
if (chw != null) {
patientDataHolder.get(e.getKey()).put(Hiv.ACCOMP_FIRST_NAME, chw.getGivenName());
patientDataHolder.get(e.getKey()).put(Hiv.ACCOMP_LAST_NAME, chw.getFamilyName());
}
// try to get accomp leader too
List<Person> accompLeaderRels = accompRelations.get(chw.getPersonId());
if (accompLeaderRels != null && accompLeaderRels.size() > 0) {
Person leader = accompLeaderRels.get(0);
patientDataHolder.get(e.getKey()).put(Hiv.ACCOMP_LEADER_FIRST_NAME, leader.getGivenName());
patientDataHolder.get(e.getKey()).put(Hiv.ACCOMP_LEADER_LAST_NAME, leader.getFamilyName());
} else {
log.debug("No accomp leader relationships at all to this accompagnateur, so can't find leader");
}
}
}
}
log.debug("Pulled accompagnateurs in " + (System.currentTimeMillis() - l) + " ms");
l = System.currentTimeMillis();
// --- for every arv drug, addDynamic() a holder with
// Hiv.OBS_TYPE == Hiv.ARV or "arv"
// General.DOSE_PER_DAY == total dose per day == ddd
// Hiv.OBS_DATE == start date of arvs
// Hiv.ARV == the name of the drug as 3-letter abbreviation, or whatever
// "stop_date" == stop date for ARVS
// "ddd_quotient" == number of times taken per day (i think)
// "strength_unit" == unit for strength, e.g, "tab"
// "strength_dose" == amount given per time
/*
{
// ARV REGIMENS
Map<Integer, List<DrugOrder>> regimens = pss.getDrugOrders(ps, Context.getConceptService().getConceptByName("ANTIRETROVIRAL DRUGS"));
for (Map.Entry<Integer, List<DrugOrder>> e : regimens.entrySet()) {
Date earliestStart = null;
for (DrugOrder reg : e.getValue()) {
try {
if (earliestStart == null || (reg.getStartDate() != null && earliestStart.compareTo(reg.getStartDate()) > 0))
earliestStart = reg.getStartDate();
Double ddd = reg.getDose() * Integer.parseInt(reg.getFrequency().substring(0, 1));
if (!reg.getUnits().equals(reg.getDrug().getUnits()))
throw new RuntimeException("Units mismatch: " + reg.getUnits() + " vs " + reg.getDrug().getUnits());
ddd /= reg.getDrug().getDoseStrength();
Map<String, String> holder = new HashMap<String, String>();
holder.put(General.ID, e.getKey().toString());
holder.put(Hiv.OBS_TYPE, Hiv.ARV);
holder.put(General.DOSE_PER_DAY, ddd.toString());
holder.put(Hiv.OBS_DATE, formatDate(reg.getStartDate()));
holder.put(Hiv.ARV, reg.getDrug().getName());
holder.put("stop_date", formatDate(reg.getDiscontinued() ? reg.getDiscontinuedDate() : reg.getAutoExpireDate()));
holder.put("ddd_quotient", reg.getFrequency().substring(0, 1));
//holder.put("strength_unit", reg.getUnits());
//holder.put("strength_dose", reg.getDose().toString());
holder.put("strength_unit", "");
holder.put("strength_dose", "");
maker.addDynamic(holder);
log.debug("HIV added " + holder);
} catch (Exception ex) {
log.warn("Exception with a drug order: " + reg, ex);
}
}
if (earliestStart != null)
patientDataHolder.get(e.getKey()).put(Hiv.FIRST_ARV_DATE, formatDate(earliestStart));
}
}
*/
// --- for every tb drug, addDynamic() a holder with
// Hiv.OBS_TYPE == TB.TB_REGIMEN or "atb"
// TB.TB_REGIMEN == the name of the drug
// General.DOSE_PER_DAY == total dose per day == ddd
// Hiv.OBS_DATE == start date of arvs
// "stop_date" == stop date for ARVS
// "ddd_quotient" == number of times taken per day (i think)
// "strength_unit" == unit for strength, e.g, "tab"
// "strength_dose" == amount given per time
/*
{
// TB REGIMENS
Map<Integer, List<DrugOrder>> regimens = pss.getDrugOrders(ps, Context.getConceptService().getConceptByName("TUBERCULOSIS TREATMENT DRUGS"));
for (Map.Entry<Integer, List<DrugOrder>> e : regimens.entrySet()) {
Date earliestStart = null;
for (DrugOrder reg : e.getValue()) {
if (earliestStart == null || (reg.getStartDate() != null && earliestStart.compareTo(reg.getStartDate()) > 0))
earliestStart = reg.getStartDate();
Double ddd = reg.getDose() * Integer.parseInt(reg.getFrequency().substring(0, 1));
Map<String, String> holder = new HashMap<String, String>();
holder.put(General.ID, e.getKey().toString());
holder.put(Hiv.OBS_TYPE, TB.TB_REGIMEN);
holder.put(General.DOSE_PER_DAY, ddd.toString());
holder.put(Hiv.OBS_DATE, formatDate(reg.getStartDate()));
holder.put(TB.TB_REGIMEN, reg.getDrug().getName());
holder.put("stop_date", formatDate(reg.getDiscontinued() ? reg.getDiscontinuedDate() : reg.getAutoExpireDate()));
holder.put("ddd_quotient", reg.getFrequency().substring(0, 1));
//holder.put("strength_unit", reg.getUnits());
//holder.put("strength_dose", reg.getDose().toString());
holder.put("strength_unit", "");
holder.put("strength_dose", "");
maker.addDynamic(holder);
log.debug("TB added " + holder);
}
if (earliestStart != null)
patientDataHolder.get(e.getKey()).put(TB.FIRST_TB_REGIMEN_DATE, formatDate(earliestStart));
}
}
*/
{
// ALL REGIMENS
Map<Integer, List<DrugOrder>> regimens = pss.getDrugOrders(ps, null);
- List<Concept> unwantedHiv = Context.getConceptService().getConceptsInSet(
- Context.getConceptService().getConceptByIdOrName("ANTIRETROVIRAL DRUGS"));
- List<Concept> unwantedTb = Context.getConceptService().getConceptsInSet(
- Context.getConceptService().getConceptByIdOrName("TUBERCULOSIS TREATMENT DRUGS"));
+ List<Concept> unwantedHiv = Context.getConceptService().getConceptsByConceptSet(
+ Context.getConceptService().getConcept("ANTIRETROVIRAL DRUGS"));
+ List<Concept> unwantedTb = Context.getConceptService().getConceptsByConceptSet(
+ Context.getConceptService().getConcept("TUBERCULOSIS TREATMENT DRUGS"));
for (Map.Entry<Integer, List<DrugOrder>> e : regimens.entrySet()) {
Date earliestStart = null;
for (DrugOrder reg : e.getValue()) {
try {
if (earliestStart == null
|| (reg.getStartDate() != null && earliestStart.compareTo(reg.getStartDate()) > 0))
earliestStart = reg.getStartDate();
Double ddd = reg.getDose() * Integer.parseInt(reg.getFrequency().substring(0, 1));
if (!reg.getUnits().equals(reg.getDrug().getUnits()))
throw new RuntimeException("Units mismatch: " + reg.getUnits() + " vs "
+ reg.getDrug().getUnits());
ddd /= reg.getDrug().getDoseStrength();
Map<String, String> holder = new HashMap<String, String>();
holder.put(General.ID, e.getKey().toString());
if (OpenmrsUtil.isConceptInList(reg.getDrug().getConcept(), unwantedHiv)) {
holder.put(Hiv.OBS_TYPE, Hiv.ARV);
} else if (OpenmrsUtil.isConceptInList(reg.getDrug().getConcept(), unwantedTb)) {
holder.put(Hiv.OBS_TYPE, TB.TB_REGIMEN);
} else {
holder.put(Hiv.OBS_TYPE, General.OTHER_REGIMEN);
}
holder.put(General.DOSE_PER_DAY, ddd.toString());
holder.put(Hiv.OBS_DATE, formatDate(reg.getStartDate()));
holder.put(Hiv.ARV, reg.getDrug().getName());
holder.put("stop_date", formatDate(reg.getDiscontinued() ? reg.getDiscontinuedDate() : reg
.getAutoExpireDate()));
holder.put("ddd_quotient", reg.getFrequency().substring(0, 1));
//holder.put("strength_unit", reg.getUnits());
//holder.put("strength_dose", reg.getDose().toString());
holder.put("strength_unit", "");
holder.put("strength_dose", "");
if (reg.getCreator() != null) {
if (reg.getCreator().getUsername() != null) {
holder.put(General.CREATOR, reg.getCreator().getUsername());
} else {
holder.put(General.CREATOR, "Unknown");
}
} else {
holder.put(General.CREATOR, "Unknown");
}
maker.addDynamic(holder);
log.debug("HIV added " + holder);
}
catch (Exception ex) {
log.warn("Exception with a drug order: " + reg, ex);
}
}
}
}
log.debug("Pulled regimens in " + (System.currentTimeMillis() - l) + " ms");
l = System.currentTimeMillis();
for (Concept c : dynamicConceptsToGet) {
long l1 = System.currentTimeMillis();
String typeToUse = obsTypesForDynamicConcepts.get(c);
Map<Integer, List<Obs>> temp = pss.getObservations(ps, c);
long l2 = System.currentTimeMillis();
for (Map.Entry<Integer, List<Obs>> e : temp.entrySet()) {
Integer ptId = e.getKey();
List<Obs> obs = e.getValue();
for (Obs o : obs) {
Map<String, String> holder = new HashMap<String, String>();
holder.put(General.ID, ptId.toString());
holder.put(Hiv.OBS_DATE, formatDate(o.getObsDatetime()));
holder.put(Hiv.RESULT, o.getValueAsString(locale));
holder.put(Hiv.OBS_TYPE, typeToUse);
holder.put("cdt", formatDate(o.getDateCreated()));
if (o.getCreator() != null) {
if (o.getCreator().getUsername() != null) {
holder.put(General.CREATOR, o.getCreator().getUsername());
} else {
holder.put(General.CREATOR, "Unknown");
}
} else {
holder.put(General.CREATOR, "Unknown");
}
maker.addDynamic(holder);
}
}
long l3 = System.currentTimeMillis();
log.debug("\t" + typeToUse + " " + c + " step 1: " + (l2 - l1) + " ms. step 2: " + (l3 - l2) + " ms.");
}
log.debug("Pulled dynamicConceptsToGet in " + (System.currentTimeMillis() - l) + " ms");
l = System.currentTimeMillis();
Map<Integer, Encounter> encounterList = Context.getPatientSetService().getEncounters(ps);
for (Map.Entry<Integer, Encounter> e : encounterList.entrySet()) {
Map<String, String> holder = new HashMap<String, String>();
holder.put(General.ID, e.getKey().toString());
holder.put(Hiv.OBS_TYPE, "encounter");
if (e.getValue().getEncounterDatetime() != null) {
holder.put(Hiv.OBS_DATE, formatDate(e.getValue().getEncounterDatetime()));
} else {
holder.put(Hiv.OBS_DATE, "");
}
if (e.getValue().getEncounterType() != null) {
holder.put(Hiv.RESULT, e.getValue().getEncounterType().getName());
} else {
holder.put(Hiv.RESULT, "");
}
if (e.getValue().getCreator() != null) {
if (e.getValue().getCreator().getUsername() != null) {
holder.put(General.CREATOR, e.getValue().getCreator().getUsername());
} else {
holder.put(General.CREATOR, "Unknown");
}
} else {
holder.put(General.CREATOR, "Unknown");
}
if (e.getValue().getObs() != null) {
holder.put(General.SIZE, "" + e.getValue().getObs().size());
} else {
holder.put(General.SIZE, "0");
}
maker.addDynamic(holder);
log.debug("Encounters added " + holder);
}
/*
// hack for demo in capetown using Kenya data
{
// arv start date
Map<Integer, List<Obs>> observs = pss.getObservations(ps, Context.getConceptService().getConcept(1255));
for (Map.Entry<Integer, List<Obs>> e : observs.entrySet()) {
Date date = null;
for (Obs observ : e.getValue()) {
if (observ.getValueCoded().getConceptId() == 1256) {
date = observ.getObsDatetime();
if (date == null) {
date = observ.getEncounter().getEncounterDatetime();
}
break;
}
}
if (date != null) {
patientDataHolder.get(e.getKey()).put(Hiv.FIRST_ARV_DATE, formatDate(date));
}
}
// tb tx start date
observs = pss.getObservations(ps, Context.getConceptService().getConcept(1268));
for (Map.Entry<Integer, List<Obs>> e : observs.entrySet()) {
Date date = null;
for (Obs observ : e.getValue()) {
if (observ.getValueCoded().getConceptId() == 1256) {
date = observ.getObsDatetime();
if (date == null) {
date = observ.getEncounter().getEncounterDatetime();
}
break;
}
}
if (date != null) {
patientDataHolder.get(e.getKey()).put(TB.FIRST_TB_REGIMEN_DATE, formatDate(date));
}
}
}
*/
/*
// location of most recent encounter
Map<Integer, Encounter> encs = pss.getEncountersByType(ps, null);
for (Map.Entry<Integer, Encounter> e : encs.entrySet()) {
String locName = null;
Location encLocation = e.getValue().getLocation();
if (encLocation != null) {
locName = encLocation.getName();
}
if (locName != null && locName.length() > 0) {
patientDataHolder.get(e.getKey()).put(General.SITE, locName);
}
}
*/
for (Map<String, String> patient : patientDataHolder.values()) {
// patient.put("BIRTH_YEAR", "1978");
//patient.put(General.HIV_POSITIVE_P, "t");
maker.addStatic(patient);
}
log.debug("Loaded data into report-maker in " + (System.currentTimeMillis() - l) + " ms");
l = System.currentTimeMillis();
File dir = new File("NEAL_REPORT_DIR");
dir.mkdir();
String filename = maker.generateReport(dir.getAbsolutePath() + "/");
log.debug("ran maker.generateReport() in " + (System.currentTimeMillis() - l) + " ms");
l = System.currentTimeMillis();
Map<String, Object> model = new HashMap<String, Object>();
model.put("dir", dir);
model.put("filename", filename);
AbstractView view = new AbstractView() {
protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response)
throws Exception {
File f = new File((File) model.get("dir"), (String) model.get("filename"));
response.setHeader("Content-Disposition", "attachment; filename=" + f.getName());
response.setHeader("Pragma", "no-cache");
response.setContentType("application/pdf");
response.setContentLength((int) f.length());
BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
BufferedInputStream in = new BufferedInputStream(new FileInputStream(f));
for (int i = in.read(); i >= 0; i = in.read()) {
out.write(i);
}
in.close();
out.flush();
System.gc();
f.delete();
}
};
return new ModelAndView(view, model);
}
private DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
private String formatDate(Date d) {
return d == null ? null : df.format(d);
}
private void dynamicConceptHelper(ConceptService cs, List<Concept> dynamicConceptsToGet,
Map<Concept, String> obsTypesForDynamicConcepts, String conceptName, String typeToUse) {
Concept c = cs.getConceptByName(conceptName);
if (c == null) {
throw new IllegalArgumentException("Cannot find concept named " + conceptName);
}
dynamicConceptsToGet.add(c);
obsTypesForDynamicConcepts.put(c, typeToUse);
}
private void attributeHelper(List<String> attributesToGet, Map<String, String> attributeNamesForReportMaker,
String attrName, String nameForReportMaker) {
attributesToGet.add(attrName);
attributeNamesForReportMaker.put(attrName, nameForReportMaker);
}
private void conceptHelper(ConceptService cs, List<Concept> conceptsToGet, Map<Concept, String> namesForReportMaker,
String conceptName, String nameForReportMaker) {
Concept c = cs.getConceptByName(conceptName);
if (c == null) {
throw new IllegalArgumentException("Cannot find concept named " + conceptName);
}
conceptsToGet.add(c);
namesForReportMaker.put(c, nameForReportMaker);
}
}
| false | true | public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
String reportType = request.getParameter("reportType");
String fDate = ServletRequestUtils.getStringParameter(request, "fDate", "");
String tDate = ServletRequestUtils.getStringParameter(request, "tDate", "");
SimpleDateFormat sdfEntered = OpenmrsUtil.getDateFormat();
SimpleDateFormat sdfExpected = new SimpleDateFormat("yyyy-MM-dd");
Date fromDate = null;
Date toDate = null;
if (fDate.length() > 0) {
try {
fromDate = sdfEntered.parse(fDate);
}
catch (ParseException e) {
fromDate = null;
}
}
if (tDate.length() > 0) {
try {
toDate = sdfEntered.parse(tDate);
}
catch (ParseException e) {
toDate = null;
}
}
String programName = Context.getAdministrationService().getGlobalProperty("reporting.programName");
if (programName == null)
programName = "rwanda";
if (programName.length() == 0)
programName = "rwanda";
Map reportConfig = new HashMap();
reportConfig.put("program", programName);
if (fromDate != null) {
String from = sdfExpected.format(fromDate);
log.debug("Adding fromDate of " + from + " to NEALREPORT");
reportConfig.put(Report.START_REPORT_PERIOD, from);
} else {
log.debug("NO FROMDATE TO ADD");
}
if (toDate != null) {
String to = sdfExpected.format(toDate);
log.debug("Adding toDate of " + to + " to NEALREPORT");
reportConfig.put(Report.END_REPORT_PERIOD, to);
} else {
log.debug("NO TO TO ADD");
}
RwandaReportMaker maker = (RwandaReportMaker) ReportMaker.configureReport(reportConfig);
maker.setParameter("report_type", reportType);
Locale locale = Context.getLocale();
ConceptService cs = Context.getConceptService();
PatientSetService pss = Context.getPatientSetService();
String patientSetParameter = request.getParameter("patientIds");
Cohort ps;
if (patientSetParameter != null && patientSetParameter.length() > 0) {
ps = new Cohort(patientSetParameter.trim());
} else {
ps = pss.getAllPatients();
}
Map<Integer, Map<String, String>> patientDataHolder = new HashMap<Integer, Map<String, String>>();
List<String> attributesToGet = new ArrayList<String>();
Map<String, String> attributeNamesForReportMaker = new HashMap<String, String>();
attributeHelper(attributesToGet, attributeNamesForReportMaker, "Patient.patientId", General.ID);
attributeHelper(attributesToGet, attributeNamesForReportMaker, "PersonName.givenName", General.FIRST_NAME);
attributeHelper(attributesToGet, attributeNamesForReportMaker, "PersonName.familyName", General.LAST_NAME);
attributeHelper(attributesToGet, attributeNamesForReportMaker, "Patient.birthdate", General.BIRTHDAY);
attributeHelper(attributesToGet, attributeNamesForReportMaker, "Patient.gender", General.SEX);
attributeHelper(attributesToGet, attributeNamesForReportMaker, "Patient.dead", General.HAS_DIED);
attributeHelper(attributesToGet, attributeNamesForReportMaker, "Patient.deathDate", General.DEATH_DATE);
attributeHelper(attributesToGet, attributeNamesForReportMaker, "PersonAddress.stateProvince", General.PROVINCE);
attributeHelper(attributesToGet, attributeNamesForReportMaker, "PersonAddress.countyDistrict", General.DISTRICT);
attributeHelper(attributesToGet, attributeNamesForReportMaker, "PersonAddress.cityVillage", General.SECTOR);
attributeHelper(attributesToGet, attributeNamesForReportMaker, "PersonAddress.neighborhoodCell", General.CELL);
attributeHelper(attributesToGet, attributeNamesForReportMaker, "PersonAddress.address1", General.UMUDUGUDU);
// General.ADDRESS
// General.USER_ID (this is actually patient identifier)
// General.DUE_DATE if pregnant
// Hiv.ACCOMP_FIRST_NAME
// Hiv.ACCOMP_LAST_NAME
// General.PREGNANT_P
// General.PMTCT (get meds for ptme? ask CA)
// General.FORMER_GROUP (previous ARV group)
List<Concept> conceptsToGet = new ArrayList<Concept>();
Map<Concept, String> namesForReportMaker = new HashMap<Concept, String>();
//conceptHelper(cs, conceptsToGet, namesForReportMaker, "TREATMENT GROUP", Hiv.TREATMENT_GROUP);
//conceptHelper(cs, conceptsToGet, namesForReportMaker, "TUBERCULOSIS TREATMENT GROUP", TB.TB_GROUP);
//conceptHelper(cs, conceptsToGet, namesForReportMaker, "CURRENT WHO HIV STAGE", Hiv.WHO_STAGE);
// TODO: replace static concepts for current groups
List<Concept> dynamicConceptsToGet = new ArrayList<Concept>();
Map<Concept, String> obsTypesForDynamicConcepts = new HashMap<Concept, String>();
dynamicConceptHelper(cs, dynamicConceptsToGet, obsTypesForDynamicConcepts, "WEIGHT (KG)", "weight");
dynamicConceptHelper(cs, dynamicConceptsToGet, obsTypesForDynamicConcepts, "HEIGHT (CM)", "height");
dynamicConceptHelper(cs, dynamicConceptsToGet, obsTypesForDynamicConcepts, "CD4 COUNT", Hiv.CD4COUNT);
dynamicConceptHelper(cs, dynamicConceptsToGet, obsTypesForDynamicConcepts, "CD4%", Hiv.CD4PERCENT);
//dynamicConceptHelper(cs, dynamicConceptsToGet, obsTypesForDynamicConcepts, "TREATMENT GROUP", Hiv.TREATMENT_GROUP);
//dynamicConceptHelper(cs, dynamicConceptsToGet, obsTypesForDynamicConcepts, "TUBERCULOSIS TREATMENT GROUP", TB.TB_GROUP);
dynamicConceptHelper(cs, dynamicConceptsToGet, obsTypesForDynamicConcepts, "CURRENT WHO HIV STAGE", Hiv.WHO_STAGE);
dynamicConceptHelper(cs, dynamicConceptsToGet, obsTypesForDynamicConcepts, "REASON FOR EXITING CARE",
General.OUTCOME);
dynamicConceptHelper(cs, dynamicConceptsToGet, obsTypesForDynamicConcepts, "PATIENT RECEIVED FOOD PACKAGE",
General.RECEIVE_FOOD);
dynamicConceptHelper(cs, dynamicConceptsToGet, obsTypesForDynamicConcepts, "TIME OF DAILY ACCOMPAGNATEUR VISIT",
Hiv.TIME_OF_ACCOMP_VISIT);
dynamicConceptHelper(cs, dynamicConceptsToGet, obsTypesForDynamicConcepts, "TRANSFER IN FROM",
General.TRANSFERRED_IN_FROM);
dynamicConceptHelper(cs, dynamicConceptsToGet, obsTypesForDynamicConcepts, "TRANSFER IN DATE",
General.TRANSFERRED_IN_DATE);
// TODO: replace dynamic concepts for current groups
long l = System.currentTimeMillis();
for (String attr : attributesToGet) {
String nameToUse = attributeNamesForReportMaker.get(attr);
Map<Integer, Object> temp = pss.getPatientAttributes(ps, attr, false);
for (Map.Entry<Integer, Object> e : temp.entrySet()) {
Integer ptId = e.getKey();
Map<String, String> holder = (Map<String, String>) patientDataHolder.get(ptId);
if (holder == null) {
holder = new HashMap<String, String>();
patientDataHolder.put(ptId, holder);
}
if (e.getValue() != null) {
Object obj = e.getValue();
String valToUse = null;
if (obj instanceof Date) {
valToUse = formatDate((Date) obj);
} else {
valToUse = obj.toString();
}
log.debug("Putting [" + nameToUse + "][" + valToUse + "] in report");
holder.put(nameToUse, valToUse);
} else {
log.debug("No value for " + nameToUse);
}
}
}
// quick hack: switch from Patient.healthCenter to PersonAttribute('Health Center')
// old version: attributeHelper(attributesToGet, attributeNamesForReportMaker, "Patient.healthCenter", General.SITE);
{
Map<Integer, Object> temp = pss
.getPersonAttributes(ps, "Health Center", "Location", "locationId", "name", false);
for (Map.Entry<Integer, Object> e : temp.entrySet()) {
if (e.getValue() == null)
continue;
Integer ptId = e.getKey();
Map<String, String> holder = (Map<String, String>) patientDataHolder.get(ptId);
if (holder == null) {
holder = new HashMap<String, String>();
patientDataHolder.put(ptId, holder);
}
String nameToUse = General.SITE;
String valToUse = e.getValue().toString();
holder.put(nameToUse, valToUse);
}
}
// modified by CA on 5 Dec 2006
// to do a data dump so that we can fill in missing IMB IDs
List<Patient> patients = Context.getPatientSetService().getPatients(ps.getMemberIds());
for (Patient p : patients) {
if (p.getActiveIdentifiers() != null) {
for (PatientIdentifier pId : p.getActiveIdentifiers()) {
PatientIdentifierType idType = pId.getIdentifierType();
if (idType.getName().equalsIgnoreCase("imb id")) {
String identifier = pId.getIdentifier();
Map<String, String> holder = (Map<String, String>) patientDataHolder.get(p.getPatientId());
if (holder == null)
holder = new HashMap<String, String>();
holder.put(General.USER_ID, identifier);
}
}
}
}
log.debug("Pulled attributesToGet in " + (System.currentTimeMillis() - l) + " ms");
l = System.currentTimeMillis();
for (Concept c : conceptsToGet) {
long l1 = System.currentTimeMillis();
String nameToUse = namesForReportMaker.get(c);
Map<Integer, List<Obs>> temp = pss.getObservations(ps, c);
long l2 = System.currentTimeMillis();
for (Map.Entry<Integer, List<Obs>> e : temp.entrySet()) {
Integer ptId = e.getKey();
Map<String, String> holder = (Map<String, String>) patientDataHolder.get(ptId);
if (holder == null) {
holder = new HashMap<String, String>();
patientDataHolder.put(ptId, holder);
}
holder.put(nameToUse, e.getValue().get(0).getValueAsString(locale));
}
long l3 = System.currentTimeMillis();
log.debug("\t" + nameToUse + " " + c + " step 1: " + (l2 - l1) + " ms. step 2: " + (l3 - l2) + " ms.");
}
log.debug("Pulled conceptsToGet in " + (System.currentTimeMillis() - l) + " ms");
l = System.currentTimeMillis();
// General.ENROLL_DATE
// Hiv.TREATMENT_STATUS
// General.HIV_POSITIVE_P
// General.TB_ACTIVE_P
Program hivProgram = Context.getProgramWorkflowService().getProgram("HIV PROGRAM");
if (hivProgram != null) {
Map<Integer, PatientProgram> progs = pss.getCurrentPatientPrograms(ps, hivProgram);
for (Map.Entry<Integer, PatientProgram> e : progs.entrySet()) {
patientDataHolder.get(e.getKey()).put(General.HIV_POSITIVE_P, "t");
patientDataHolder.get(e.getKey()).put(General.ENROLL_DATE, formatDate(e.getValue().getDateEnrolled()));
//log.debug(e.getValue().getDateEnrolled());
}
ProgramWorkflow wf = Context.getProgramWorkflowService().getWorkflow(hivProgram, "TREATMENT STATUS");
log.debug("worlflow is " + wf + " and patientSet is " + ps);
Map<Integer, PatientState> states = pss.getCurrentStates(ps, wf);
if (states != null) {
log.debug("about to loop through [" + states.size() + "] statuses");
for (Map.Entry<Integer, PatientState> e : states.entrySet()) {
patientDataHolder.get(e.getKey()).put(Hiv.TREATMENT_STATUS,
e.getValue().getState().getConcept().getName(locale, false).getName());
log.debug("Just put state [" + e.getValue().getState().getConcept().getName(locale).getName()
+ "] in for patient [" + e.getKey() + "]");
// also want to add dynamically
PatientState state = e.getValue();
Map<String, String> holder = new HashMap<String, String>();
holder.put(General.ID, e.getKey().toString());
holder.put(Hiv.OBS_TYPE, Hiv.TREATMENT_STATUS);
holder.put(Hiv.OBS_DATE, formatDate(state.getStartDate()));
holder.put("stop_date", formatDate(state.getEndDate()));
holder.put(Hiv.RESULT, state.getState().getConcept().getName(locale).getName());
maker.addDynamic(holder);
}
} else {
log.debug("states is null, can't proceed");
}
wf = Context.getProgramWorkflowService().getWorkflow(hivProgram, "TREATMENT GROUP");
log.debug("worlflow is " + wf + " and patientSet is " + ps);
states = pss.getCurrentStates(ps, wf);
if (states != null) {
log.debug("about to loop through [" + states.size() + "] statuses");
for (Map.Entry<Integer, PatientState> e : states.entrySet()) {
patientDataHolder.get(e.getKey()).put(Hiv.TREATMENT_GROUP,
e.getValue().getState().getConcept().getName(locale, false).getName());
log.debug("Just put state [" + e.getValue().getState().getConcept().getName(locale).getName()
+ "] in for patient [" + e.getKey() + "]");
// also want to add dynamically
PatientState state = e.getValue();
Map<String, String> holder = new HashMap<String, String>();
holder.put(General.ID, e.getKey().toString());
holder.put(Hiv.OBS_TYPE, Hiv.TREATMENT_GROUP);
holder.put(Hiv.OBS_DATE, formatDate(state.getStartDate()));
holder.put("stop_date", formatDate(state.getEndDate()));
holder.put(Hiv.RESULT, state.getState().getConcept().getName(locale).getName());
maker.addDynamic(holder);
}
} else {
log.debug("states is null, can't proceed");
}
} else {
log.debug("Couldn't find HIV PROGRAM");
}
Program tbProgram = Context.getProgramWorkflowService().getProgram("TUBERCULOSIS PROGRAM");
if (tbProgram != null) {
Map<Integer, PatientProgram> progs = pss.getCurrentPatientPrograms(ps, tbProgram);
for (Map.Entry<Integer, PatientProgram> e : progs.entrySet()) {
patientDataHolder.get(e.getKey()).put(General.TB_ACTIVE_P, "t");
patientDataHolder.get(e.getKey()).put(TB.TB_ENROLL_DATE, formatDate(e.getValue().getDateEnrolled()));
}
ProgramWorkflow wf = Context.getProgramWorkflowService().getWorkflow(tbProgram, "TREATMENT STATUS");
log.debug("worlflow is " + wf + " and patientSet is " + ps);
Map<Integer, PatientState> states = pss.getCurrentStates(ps, wf);
if (states != null) {
log.debug("about to loop through [" + states.size() + "] statuses");
for (Map.Entry<Integer, PatientState> e : states.entrySet()) {
patientDataHolder.get(e.getKey()).put(TB.TB_TREATMENT_STATUS,
e.getValue().getState().getConcept().getName(locale, false).getName());
log.debug("Just put state [" + e.getValue().getState().getConcept().getName(locale).getName()
+ "] in for patient [" + e.getKey() + "]");
// also want to add dynamically
PatientState state = e.getValue();
Map<String, String> holder = new HashMap<String, String>();
holder.put(General.ID, e.getKey().toString());
holder.put(Hiv.OBS_TYPE, TB.TB_TREATMENT_STATUS);
holder.put(Hiv.OBS_DATE, formatDate(state.getStartDate()));
holder.put("stop_date", formatDate(state.getEndDate()));
holder.put(Hiv.RESULT, state.getState().getConcept().getName(locale).getName());
maker.addDynamic(holder);
}
} else {
log.debug("states is null, can't proceed");
}
wf = Context.getProgramWorkflowService().getWorkflow(tbProgram, "TUBERCULOSIS TREATMENT GROUP");
log.debug("worlflow is " + wf + " and patientSet is " + ps);
states = pss.getCurrentStates(ps, wf);
if (states != null) {
log.debug("about to loop through [" + states.size() + "] statuses");
for (Map.Entry<Integer, PatientState> e : states.entrySet()) {
patientDataHolder.get(e.getKey()).put(TB.TB_GROUP,
e.getValue().getState().getConcept().getName(locale, false).getName());
log.debug("Just put state [" + e.getValue().getState().getConcept().getName(locale).getName()
+ "] in for patient [" + e.getKey() + "]");
// also want to add dynamically
PatientState state = e.getValue();
Map<String, String> holder = new HashMap<String, String>();
holder.put(General.ID, e.getKey().toString());
holder.put(Hiv.OBS_TYPE, TB.TB_GROUP);
holder.put(Hiv.OBS_DATE, formatDate(state.getStartDate()));
holder.put("stop_date", formatDate(state.getEndDate()));
holder.put(Hiv.RESULT, state.getState().getConcept().getName(locale).getName());
maker.addDynamic(holder);
}
} else {
log.debug("states is null, can't proceed");
}
}
log.debug("Pulled enrollments and hiv treatment status in " + (System.currentTimeMillis() - l) + " ms");
l = System.currentTimeMillis();
{
PersonService personService = Context.getPersonService();
RelationshipType relType = personService.findRelationshipType("Accompagnateur/Patient");
if (relType != null) {
// get the accomp leader as well
RelationshipType accompLeaderType = personService
.findRelationshipType("Accompagnateur Leader/Opposite of Accompagnateur Leader");
Map<Integer, List<Person>> accompRelations = null;
if (accompLeaderType != null)
accompRelations = pss.getRelatives(null, accompLeaderType, false);
else
accompRelations = new HashMap<Integer, List<Person>>();
Map<Integer, List<Person>> chws = pss.getRelatives(ps, relType, false);
for (Map.Entry<Integer, List<Person>> e : chws.entrySet()) {
Person chw = e.getValue().get(0);
if (chw != null) {
patientDataHolder.get(e.getKey()).put(Hiv.ACCOMP_FIRST_NAME, chw.getGivenName());
patientDataHolder.get(e.getKey()).put(Hiv.ACCOMP_LAST_NAME, chw.getFamilyName());
}
// try to get accomp leader too
List<Person> accompLeaderRels = accompRelations.get(chw.getPersonId());
if (accompLeaderRels != null && accompLeaderRels.size() > 0) {
Person leader = accompLeaderRels.get(0);
patientDataHolder.get(e.getKey()).put(Hiv.ACCOMP_LEADER_FIRST_NAME, leader.getGivenName());
patientDataHolder.get(e.getKey()).put(Hiv.ACCOMP_LEADER_LAST_NAME, leader.getFamilyName());
} else {
log.debug("No accomp leader relationships at all to this accompagnateur, so can't find leader");
}
}
}
}
log.debug("Pulled accompagnateurs in " + (System.currentTimeMillis() - l) + " ms");
l = System.currentTimeMillis();
// --- for every arv drug, addDynamic() a holder with
// Hiv.OBS_TYPE == Hiv.ARV or "arv"
// General.DOSE_PER_DAY == total dose per day == ddd
// Hiv.OBS_DATE == start date of arvs
// Hiv.ARV == the name of the drug as 3-letter abbreviation, or whatever
// "stop_date" == stop date for ARVS
// "ddd_quotient" == number of times taken per day (i think)
// "strength_unit" == unit for strength, e.g, "tab"
// "strength_dose" == amount given per time
/*
{
// ARV REGIMENS
Map<Integer, List<DrugOrder>> regimens = pss.getDrugOrders(ps, Context.getConceptService().getConceptByName("ANTIRETROVIRAL DRUGS"));
for (Map.Entry<Integer, List<DrugOrder>> e : regimens.entrySet()) {
Date earliestStart = null;
for (DrugOrder reg : e.getValue()) {
try {
if (earliestStart == null || (reg.getStartDate() != null && earliestStart.compareTo(reg.getStartDate()) > 0))
earliestStart = reg.getStartDate();
Double ddd = reg.getDose() * Integer.parseInt(reg.getFrequency().substring(0, 1));
if (!reg.getUnits().equals(reg.getDrug().getUnits()))
throw new RuntimeException("Units mismatch: " + reg.getUnits() + " vs " + reg.getDrug().getUnits());
ddd /= reg.getDrug().getDoseStrength();
Map<String, String> holder = new HashMap<String, String>();
holder.put(General.ID, e.getKey().toString());
holder.put(Hiv.OBS_TYPE, Hiv.ARV);
holder.put(General.DOSE_PER_DAY, ddd.toString());
holder.put(Hiv.OBS_DATE, formatDate(reg.getStartDate()));
holder.put(Hiv.ARV, reg.getDrug().getName());
holder.put("stop_date", formatDate(reg.getDiscontinued() ? reg.getDiscontinuedDate() : reg.getAutoExpireDate()));
holder.put("ddd_quotient", reg.getFrequency().substring(0, 1));
//holder.put("strength_unit", reg.getUnits());
//holder.put("strength_dose", reg.getDose().toString());
holder.put("strength_unit", "");
holder.put("strength_dose", "");
maker.addDynamic(holder);
log.debug("HIV added " + holder);
} catch (Exception ex) {
log.warn("Exception with a drug order: " + reg, ex);
}
}
if (earliestStart != null)
patientDataHolder.get(e.getKey()).put(Hiv.FIRST_ARV_DATE, formatDate(earliestStart));
}
}
*/
// --- for every tb drug, addDynamic() a holder with
// Hiv.OBS_TYPE == TB.TB_REGIMEN or "atb"
// TB.TB_REGIMEN == the name of the drug
// General.DOSE_PER_DAY == total dose per day == ddd
// Hiv.OBS_DATE == start date of arvs
// "stop_date" == stop date for ARVS
// "ddd_quotient" == number of times taken per day (i think)
// "strength_unit" == unit for strength, e.g, "tab"
// "strength_dose" == amount given per time
/*
{
// TB REGIMENS
Map<Integer, List<DrugOrder>> regimens = pss.getDrugOrders(ps, Context.getConceptService().getConceptByName("TUBERCULOSIS TREATMENT DRUGS"));
for (Map.Entry<Integer, List<DrugOrder>> e : regimens.entrySet()) {
Date earliestStart = null;
for (DrugOrder reg : e.getValue()) {
if (earliestStart == null || (reg.getStartDate() != null && earliestStart.compareTo(reg.getStartDate()) > 0))
earliestStart = reg.getStartDate();
Double ddd = reg.getDose() * Integer.parseInt(reg.getFrequency().substring(0, 1));
Map<String, String> holder = new HashMap<String, String>();
holder.put(General.ID, e.getKey().toString());
holder.put(Hiv.OBS_TYPE, TB.TB_REGIMEN);
holder.put(General.DOSE_PER_DAY, ddd.toString());
holder.put(Hiv.OBS_DATE, formatDate(reg.getStartDate()));
holder.put(TB.TB_REGIMEN, reg.getDrug().getName());
holder.put("stop_date", formatDate(reg.getDiscontinued() ? reg.getDiscontinuedDate() : reg.getAutoExpireDate()));
holder.put("ddd_quotient", reg.getFrequency().substring(0, 1));
//holder.put("strength_unit", reg.getUnits());
//holder.put("strength_dose", reg.getDose().toString());
holder.put("strength_unit", "");
holder.put("strength_dose", "");
maker.addDynamic(holder);
log.debug("TB added " + holder);
}
if (earliestStart != null)
patientDataHolder.get(e.getKey()).put(TB.FIRST_TB_REGIMEN_DATE, formatDate(earliestStart));
}
}
*/
{
// ALL REGIMENS
Map<Integer, List<DrugOrder>> regimens = pss.getDrugOrders(ps, null);
List<Concept> unwantedHiv = Context.getConceptService().getConceptsInSet(
Context.getConceptService().getConceptByIdOrName("ANTIRETROVIRAL DRUGS"));
List<Concept> unwantedTb = Context.getConceptService().getConceptsInSet(
Context.getConceptService().getConceptByIdOrName("TUBERCULOSIS TREATMENT DRUGS"));
for (Map.Entry<Integer, List<DrugOrder>> e : regimens.entrySet()) {
Date earliestStart = null;
for (DrugOrder reg : e.getValue()) {
try {
if (earliestStart == null
|| (reg.getStartDate() != null && earliestStart.compareTo(reg.getStartDate()) > 0))
earliestStart = reg.getStartDate();
Double ddd = reg.getDose() * Integer.parseInt(reg.getFrequency().substring(0, 1));
if (!reg.getUnits().equals(reg.getDrug().getUnits()))
throw new RuntimeException("Units mismatch: " + reg.getUnits() + " vs "
+ reg.getDrug().getUnits());
ddd /= reg.getDrug().getDoseStrength();
Map<String, String> holder = new HashMap<String, String>();
holder.put(General.ID, e.getKey().toString());
if (OpenmrsUtil.isConceptInList(reg.getDrug().getConcept(), unwantedHiv)) {
holder.put(Hiv.OBS_TYPE, Hiv.ARV);
} else if (OpenmrsUtil.isConceptInList(reg.getDrug().getConcept(), unwantedTb)) {
holder.put(Hiv.OBS_TYPE, TB.TB_REGIMEN);
} else {
holder.put(Hiv.OBS_TYPE, General.OTHER_REGIMEN);
}
holder.put(General.DOSE_PER_DAY, ddd.toString());
holder.put(Hiv.OBS_DATE, formatDate(reg.getStartDate()));
holder.put(Hiv.ARV, reg.getDrug().getName());
holder.put("stop_date", formatDate(reg.getDiscontinued() ? reg.getDiscontinuedDate() : reg
.getAutoExpireDate()));
holder.put("ddd_quotient", reg.getFrequency().substring(0, 1));
//holder.put("strength_unit", reg.getUnits());
//holder.put("strength_dose", reg.getDose().toString());
holder.put("strength_unit", "");
holder.put("strength_dose", "");
if (reg.getCreator() != null) {
if (reg.getCreator().getUsername() != null) {
holder.put(General.CREATOR, reg.getCreator().getUsername());
} else {
holder.put(General.CREATOR, "Unknown");
}
} else {
holder.put(General.CREATOR, "Unknown");
}
maker.addDynamic(holder);
log.debug("HIV added " + holder);
}
catch (Exception ex) {
log.warn("Exception with a drug order: " + reg, ex);
}
}
}
}
log.debug("Pulled regimens in " + (System.currentTimeMillis() - l) + " ms");
l = System.currentTimeMillis();
for (Concept c : dynamicConceptsToGet) {
long l1 = System.currentTimeMillis();
String typeToUse = obsTypesForDynamicConcepts.get(c);
Map<Integer, List<Obs>> temp = pss.getObservations(ps, c);
long l2 = System.currentTimeMillis();
for (Map.Entry<Integer, List<Obs>> e : temp.entrySet()) {
Integer ptId = e.getKey();
List<Obs> obs = e.getValue();
for (Obs o : obs) {
Map<String, String> holder = new HashMap<String, String>();
holder.put(General.ID, ptId.toString());
holder.put(Hiv.OBS_DATE, formatDate(o.getObsDatetime()));
holder.put(Hiv.RESULT, o.getValueAsString(locale));
holder.put(Hiv.OBS_TYPE, typeToUse);
holder.put("cdt", formatDate(o.getDateCreated()));
if (o.getCreator() != null) {
if (o.getCreator().getUsername() != null) {
holder.put(General.CREATOR, o.getCreator().getUsername());
} else {
holder.put(General.CREATOR, "Unknown");
}
} else {
holder.put(General.CREATOR, "Unknown");
}
maker.addDynamic(holder);
}
}
long l3 = System.currentTimeMillis();
log.debug("\t" + typeToUse + " " + c + " step 1: " + (l2 - l1) + " ms. step 2: " + (l3 - l2) + " ms.");
}
log.debug("Pulled dynamicConceptsToGet in " + (System.currentTimeMillis() - l) + " ms");
l = System.currentTimeMillis();
Map<Integer, Encounter> encounterList = Context.getPatientSetService().getEncounters(ps);
for (Map.Entry<Integer, Encounter> e : encounterList.entrySet()) {
Map<String, String> holder = new HashMap<String, String>();
holder.put(General.ID, e.getKey().toString());
holder.put(Hiv.OBS_TYPE, "encounter");
if (e.getValue().getEncounterDatetime() != null) {
holder.put(Hiv.OBS_DATE, formatDate(e.getValue().getEncounterDatetime()));
} else {
holder.put(Hiv.OBS_DATE, "");
}
if (e.getValue().getEncounterType() != null) {
holder.put(Hiv.RESULT, e.getValue().getEncounterType().getName());
} else {
holder.put(Hiv.RESULT, "");
}
if (e.getValue().getCreator() != null) {
if (e.getValue().getCreator().getUsername() != null) {
holder.put(General.CREATOR, e.getValue().getCreator().getUsername());
} else {
holder.put(General.CREATOR, "Unknown");
}
} else {
holder.put(General.CREATOR, "Unknown");
}
if (e.getValue().getObs() != null) {
holder.put(General.SIZE, "" + e.getValue().getObs().size());
} else {
holder.put(General.SIZE, "0");
}
maker.addDynamic(holder);
log.debug("Encounters added " + holder);
}
/*
// hack for demo in capetown using Kenya data
{
// arv start date
Map<Integer, List<Obs>> observs = pss.getObservations(ps, Context.getConceptService().getConcept(1255));
for (Map.Entry<Integer, List<Obs>> e : observs.entrySet()) {
Date date = null;
for (Obs observ : e.getValue()) {
if (observ.getValueCoded().getConceptId() == 1256) {
date = observ.getObsDatetime();
if (date == null) {
date = observ.getEncounter().getEncounterDatetime();
}
break;
}
}
if (date != null) {
patientDataHolder.get(e.getKey()).put(Hiv.FIRST_ARV_DATE, formatDate(date));
}
}
// tb tx start date
observs = pss.getObservations(ps, Context.getConceptService().getConcept(1268));
for (Map.Entry<Integer, List<Obs>> e : observs.entrySet()) {
Date date = null;
for (Obs observ : e.getValue()) {
if (observ.getValueCoded().getConceptId() == 1256) {
date = observ.getObsDatetime();
if (date == null) {
date = observ.getEncounter().getEncounterDatetime();
}
break;
}
}
if (date != null) {
patientDataHolder.get(e.getKey()).put(TB.FIRST_TB_REGIMEN_DATE, formatDate(date));
}
}
}
*/
/*
// location of most recent encounter
Map<Integer, Encounter> encs = pss.getEncountersByType(ps, null);
for (Map.Entry<Integer, Encounter> e : encs.entrySet()) {
String locName = null;
Location encLocation = e.getValue().getLocation();
if (encLocation != null) {
locName = encLocation.getName();
}
if (locName != null && locName.length() > 0) {
patientDataHolder.get(e.getKey()).put(General.SITE, locName);
}
}
*/
for (Map<String, String> patient : patientDataHolder.values()) {
// patient.put("BIRTH_YEAR", "1978");
//patient.put(General.HIV_POSITIVE_P, "t");
maker.addStatic(patient);
}
log.debug("Loaded data into report-maker in " + (System.currentTimeMillis() - l) + " ms");
l = System.currentTimeMillis();
File dir = new File("NEAL_REPORT_DIR");
dir.mkdir();
String filename = maker.generateReport(dir.getAbsolutePath() + "/");
log.debug("ran maker.generateReport() in " + (System.currentTimeMillis() - l) + " ms");
l = System.currentTimeMillis();
Map<String, Object> model = new HashMap<String, Object>();
model.put("dir", dir);
model.put("filename", filename);
AbstractView view = new AbstractView() {
protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response)
throws Exception {
File f = new File((File) model.get("dir"), (String) model.get("filename"));
response.setHeader("Content-Disposition", "attachment; filename=" + f.getName());
response.setHeader("Pragma", "no-cache");
response.setContentType("application/pdf");
response.setContentLength((int) f.length());
BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
BufferedInputStream in = new BufferedInputStream(new FileInputStream(f));
for (int i = in.read(); i >= 0; i = in.read()) {
out.write(i);
}
in.close();
out.flush();
System.gc();
f.delete();
}
};
return new ModelAndView(view, model);
}
| public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
String reportType = request.getParameter("reportType");
String fDate = ServletRequestUtils.getStringParameter(request, "fDate", "");
String tDate = ServletRequestUtils.getStringParameter(request, "tDate", "");
SimpleDateFormat sdfEntered = OpenmrsUtil.getDateFormat();
SimpleDateFormat sdfExpected = new SimpleDateFormat("yyyy-MM-dd");
Date fromDate = null;
Date toDate = null;
if (fDate.length() > 0) {
try {
fromDate = sdfEntered.parse(fDate);
}
catch (ParseException e) {
fromDate = null;
}
}
if (tDate.length() > 0) {
try {
toDate = sdfEntered.parse(tDate);
}
catch (ParseException e) {
toDate = null;
}
}
String programName = Context.getAdministrationService().getGlobalProperty("reporting.programName");
if (programName == null)
programName = "rwanda";
if (programName.length() == 0)
programName = "rwanda";
Map reportConfig = new HashMap();
reportConfig.put("program", programName);
if (fromDate != null) {
String from = sdfExpected.format(fromDate);
log.debug("Adding fromDate of " + from + " to NEALREPORT");
reportConfig.put(Report.START_REPORT_PERIOD, from);
} else {
log.debug("NO FROMDATE TO ADD");
}
if (toDate != null) {
String to = sdfExpected.format(toDate);
log.debug("Adding toDate of " + to + " to NEALREPORT");
reportConfig.put(Report.END_REPORT_PERIOD, to);
} else {
log.debug("NO TO TO ADD");
}
RwandaReportMaker maker = (RwandaReportMaker) ReportMaker.configureReport(reportConfig);
maker.setParameter("report_type", reportType);
Locale locale = Context.getLocale();
ConceptService cs = Context.getConceptService();
PatientSetService pss = Context.getPatientSetService();
String patientSetParameter = request.getParameter("patientIds");
Cohort ps;
if (patientSetParameter != null && patientSetParameter.length() > 0) {
ps = new Cohort(patientSetParameter.trim());
} else {
ps = pss.getAllPatients();
}
Map<Integer, Map<String, String>> patientDataHolder = new HashMap<Integer, Map<String, String>>();
List<String> attributesToGet = new ArrayList<String>();
Map<String, String> attributeNamesForReportMaker = new HashMap<String, String>();
attributeHelper(attributesToGet, attributeNamesForReportMaker, "Patient.patientId", General.ID);
attributeHelper(attributesToGet, attributeNamesForReportMaker, "PersonName.givenName", General.FIRST_NAME);
attributeHelper(attributesToGet, attributeNamesForReportMaker, "PersonName.familyName", General.LAST_NAME);
attributeHelper(attributesToGet, attributeNamesForReportMaker, "Patient.birthdate", General.BIRTHDAY);
attributeHelper(attributesToGet, attributeNamesForReportMaker, "Patient.gender", General.SEX);
attributeHelper(attributesToGet, attributeNamesForReportMaker, "Patient.dead", General.HAS_DIED);
attributeHelper(attributesToGet, attributeNamesForReportMaker, "Patient.deathDate", General.DEATH_DATE);
attributeHelper(attributesToGet, attributeNamesForReportMaker, "PersonAddress.stateProvince", General.PROVINCE);
attributeHelper(attributesToGet, attributeNamesForReportMaker, "PersonAddress.countyDistrict", General.DISTRICT);
attributeHelper(attributesToGet, attributeNamesForReportMaker, "PersonAddress.cityVillage", General.SECTOR);
attributeHelper(attributesToGet, attributeNamesForReportMaker, "PersonAddress.neighborhoodCell", General.CELL);
attributeHelper(attributesToGet, attributeNamesForReportMaker, "PersonAddress.address1", General.UMUDUGUDU);
// General.ADDRESS
// General.USER_ID (this is actually patient identifier)
// General.DUE_DATE if pregnant
// Hiv.ACCOMP_FIRST_NAME
// Hiv.ACCOMP_LAST_NAME
// General.PREGNANT_P
// General.PMTCT (get meds for ptme? ask CA)
// General.FORMER_GROUP (previous ARV group)
List<Concept> conceptsToGet = new ArrayList<Concept>();
Map<Concept, String> namesForReportMaker = new HashMap<Concept, String>();
//conceptHelper(cs, conceptsToGet, namesForReportMaker, "TREATMENT GROUP", Hiv.TREATMENT_GROUP);
//conceptHelper(cs, conceptsToGet, namesForReportMaker, "TUBERCULOSIS TREATMENT GROUP", TB.TB_GROUP);
//conceptHelper(cs, conceptsToGet, namesForReportMaker, "CURRENT WHO HIV STAGE", Hiv.WHO_STAGE);
// TODO: replace static concepts for current groups
List<Concept> dynamicConceptsToGet = new ArrayList<Concept>();
Map<Concept, String> obsTypesForDynamicConcepts = new HashMap<Concept, String>();
dynamicConceptHelper(cs, dynamicConceptsToGet, obsTypesForDynamicConcepts, "WEIGHT (KG)", "weight");
dynamicConceptHelper(cs, dynamicConceptsToGet, obsTypesForDynamicConcepts, "HEIGHT (CM)", "height");
dynamicConceptHelper(cs, dynamicConceptsToGet, obsTypesForDynamicConcepts, "CD4 COUNT", Hiv.CD4COUNT);
dynamicConceptHelper(cs, dynamicConceptsToGet, obsTypesForDynamicConcepts, "CD4%", Hiv.CD4PERCENT);
//dynamicConceptHelper(cs, dynamicConceptsToGet, obsTypesForDynamicConcepts, "TREATMENT GROUP", Hiv.TREATMENT_GROUP);
//dynamicConceptHelper(cs, dynamicConceptsToGet, obsTypesForDynamicConcepts, "TUBERCULOSIS TREATMENT GROUP", TB.TB_GROUP);
dynamicConceptHelper(cs, dynamicConceptsToGet, obsTypesForDynamicConcepts, "CURRENT WHO HIV STAGE", Hiv.WHO_STAGE);
dynamicConceptHelper(cs, dynamicConceptsToGet, obsTypesForDynamicConcepts, "REASON FOR EXITING CARE",
General.OUTCOME);
dynamicConceptHelper(cs, dynamicConceptsToGet, obsTypesForDynamicConcepts, "PATIENT RECEIVED FOOD PACKAGE",
General.RECEIVE_FOOD);
dynamicConceptHelper(cs, dynamicConceptsToGet, obsTypesForDynamicConcepts, "TIME OF DAILY ACCOMPAGNATEUR VISIT",
Hiv.TIME_OF_ACCOMP_VISIT);
dynamicConceptHelper(cs, dynamicConceptsToGet, obsTypesForDynamicConcepts, "TRANSFER IN FROM",
General.TRANSFERRED_IN_FROM);
dynamicConceptHelper(cs, dynamicConceptsToGet, obsTypesForDynamicConcepts, "TRANSFER IN DATE",
General.TRANSFERRED_IN_DATE);
// TODO: replace dynamic concepts for current groups
long l = System.currentTimeMillis();
for (String attr : attributesToGet) {
String nameToUse = attributeNamesForReportMaker.get(attr);
Map<Integer, Object> temp = pss.getPatientAttributes(ps, attr, false);
for (Map.Entry<Integer, Object> e : temp.entrySet()) {
Integer ptId = e.getKey();
Map<String, String> holder = (Map<String, String>) patientDataHolder.get(ptId);
if (holder == null) {
holder = new HashMap<String, String>();
patientDataHolder.put(ptId, holder);
}
if (e.getValue() != null) {
Object obj = e.getValue();
String valToUse = null;
if (obj instanceof Date) {
valToUse = formatDate((Date) obj);
} else {
valToUse = obj.toString();
}
log.debug("Putting [" + nameToUse + "][" + valToUse + "] in report");
holder.put(nameToUse, valToUse);
} else {
log.debug("No value for " + nameToUse);
}
}
}
// quick hack: switch from Patient.healthCenter to PersonAttribute('Health Center')
// old version: attributeHelper(attributesToGet, attributeNamesForReportMaker, "Patient.healthCenter", General.SITE);
{
Map<Integer, Object> temp = pss
.getPersonAttributes(ps, "Health Center", "Location", "locationId", "name", false);
for (Map.Entry<Integer, Object> e : temp.entrySet()) {
if (e.getValue() == null)
continue;
Integer ptId = e.getKey();
Map<String, String> holder = (Map<String, String>) patientDataHolder.get(ptId);
if (holder == null) {
holder = new HashMap<String, String>();
patientDataHolder.put(ptId, holder);
}
String nameToUse = General.SITE;
String valToUse = e.getValue().toString();
holder.put(nameToUse, valToUse);
}
}
// modified by CA on 5 Dec 2006
// to do a data dump so that we can fill in missing IMB IDs
List<Patient> patients = Context.getPatientSetService().getPatients(ps.getMemberIds());
for (Patient p : patients) {
if (p.getActiveIdentifiers() != null) {
for (PatientIdentifier pId : p.getActiveIdentifiers()) {
PatientIdentifierType idType = pId.getIdentifierType();
if (idType.getName().equalsIgnoreCase("imb id")) {
String identifier = pId.getIdentifier();
Map<String, String> holder = (Map<String, String>) patientDataHolder.get(p.getPatientId());
if (holder == null)
holder = new HashMap<String, String>();
holder.put(General.USER_ID, identifier);
}
}
}
}
log.debug("Pulled attributesToGet in " + (System.currentTimeMillis() - l) + " ms");
l = System.currentTimeMillis();
for (Concept c : conceptsToGet) {
long l1 = System.currentTimeMillis();
String nameToUse = namesForReportMaker.get(c);
Map<Integer, List<Obs>> temp = pss.getObservations(ps, c);
long l2 = System.currentTimeMillis();
for (Map.Entry<Integer, List<Obs>> e : temp.entrySet()) {
Integer ptId = e.getKey();
Map<String, String> holder = (Map<String, String>) patientDataHolder.get(ptId);
if (holder == null) {
holder = new HashMap<String, String>();
patientDataHolder.put(ptId, holder);
}
holder.put(nameToUse, e.getValue().get(0).getValueAsString(locale));
}
long l3 = System.currentTimeMillis();
log.debug("\t" + nameToUse + " " + c + " step 1: " + (l2 - l1) + " ms. step 2: " + (l3 - l2) + " ms.");
}
log.debug("Pulled conceptsToGet in " + (System.currentTimeMillis() - l) + " ms");
l = System.currentTimeMillis();
// General.ENROLL_DATE
// Hiv.TREATMENT_STATUS
// General.HIV_POSITIVE_P
// General.TB_ACTIVE_P
Program hivProgram = Context.getProgramWorkflowService().getProgramByName("HIV PROGRAM");
if (hivProgram != null) {
Map<Integer, PatientProgram> progs = pss.getCurrentPatientPrograms(ps, hivProgram);
for (Map.Entry<Integer, PatientProgram> e : progs.entrySet()) {
patientDataHolder.get(e.getKey()).put(General.HIV_POSITIVE_P, "t");
patientDataHolder.get(e.getKey()).put(General.ENROLL_DATE, formatDate(e.getValue().getDateEnrolled()));
//log.debug(e.getValue().getDateEnrolled());
}
ProgramWorkflow wf = hivProgram.getWorkflowByName("TREATMENT STATUS");
log.debug("worlflow is " + wf + " and patientSet is " + ps);
Map<Integer, PatientState> states = pss.getCurrentStates(ps, wf);
if (states != null) {
log.debug("about to loop through [" + states.size() + "] statuses");
for (Map.Entry<Integer, PatientState> e : states.entrySet()) {
patientDataHolder.get(e.getKey()).put(Hiv.TREATMENT_STATUS,
e.getValue().getState().getConcept().getName(locale, false).getName());
log.debug("Just put state [" + e.getValue().getState().getConcept().getName(locale).getName()
+ "] in for patient [" + e.getKey() + "]");
// also want to add dynamically
PatientState state = e.getValue();
Map<String, String> holder = new HashMap<String, String>();
holder.put(General.ID, e.getKey().toString());
holder.put(Hiv.OBS_TYPE, Hiv.TREATMENT_STATUS);
holder.put(Hiv.OBS_DATE, formatDate(state.getStartDate()));
holder.put("stop_date", formatDate(state.getEndDate()));
holder.put(Hiv.RESULT, state.getState().getConcept().getName(locale).getName());
maker.addDynamic(holder);
}
} else {
log.debug("states is null, can't proceed");
}
wf = hivProgram.getWorkflowByName("TREATMENT GROUP");
log.debug("worlflow is " + wf + " and patientSet is " + ps);
states = pss.getCurrentStates(ps, wf);
if (states != null) {
log.debug("about to loop through [" + states.size() + "] statuses");
for (Map.Entry<Integer, PatientState> e : states.entrySet()) {
patientDataHolder.get(e.getKey()).put(Hiv.TREATMENT_GROUP,
e.getValue().getState().getConcept().getName(locale, false).getName());
log.debug("Just put state [" + e.getValue().getState().getConcept().getName(locale).getName()
+ "] in for patient [" + e.getKey() + "]");
// also want to add dynamically
PatientState state = e.getValue();
Map<String, String> holder = new HashMap<String, String>();
holder.put(General.ID, e.getKey().toString());
holder.put(Hiv.OBS_TYPE, Hiv.TREATMENT_GROUP);
holder.put(Hiv.OBS_DATE, formatDate(state.getStartDate()));
holder.put("stop_date", formatDate(state.getEndDate()));
holder.put(Hiv.RESULT, state.getState().getConcept().getName(locale).getName());
maker.addDynamic(holder);
}
} else {
log.debug("states is null, can't proceed");
}
} else {
log.debug("Couldn't find HIV PROGRAM");
}
Program tbProgram = Context.getProgramWorkflowService().getProgramByName("TUBERCULOSIS PROGRAM");
if (tbProgram != null) {
Map<Integer, PatientProgram> progs = pss.getCurrentPatientPrograms(ps, tbProgram);
for (Map.Entry<Integer, PatientProgram> e : progs.entrySet()) {
patientDataHolder.get(e.getKey()).put(General.TB_ACTIVE_P, "t");
patientDataHolder.get(e.getKey()).put(TB.TB_ENROLL_DATE, formatDate(e.getValue().getDateEnrolled()));
}
ProgramWorkflow wf = tbProgram.getWorkflowByName("TREATMENT STATUS");
log.debug("worlflow is " + wf + " and patientSet is " + ps);
Map<Integer, PatientState> states = pss.getCurrentStates(ps, wf);
if (states != null) {
log.debug("about to loop through [" + states.size() + "] statuses");
for (Map.Entry<Integer, PatientState> e : states.entrySet()) {
patientDataHolder.get(e.getKey()).put(TB.TB_TREATMENT_STATUS,
e.getValue().getState().getConcept().getName(locale, false).getName());
log.debug("Just put state [" + e.getValue().getState().getConcept().getName(locale).getName()
+ "] in for patient [" + e.getKey() + "]");
// also want to add dynamically
PatientState state = e.getValue();
Map<String, String> holder = new HashMap<String, String>();
holder.put(General.ID, e.getKey().toString());
holder.put(Hiv.OBS_TYPE, TB.TB_TREATMENT_STATUS);
holder.put(Hiv.OBS_DATE, formatDate(state.getStartDate()));
holder.put("stop_date", formatDate(state.getEndDate()));
holder.put(Hiv.RESULT, state.getState().getConcept().getName(locale).getName());
maker.addDynamic(holder);
}
} else {
log.debug("states is null, can't proceed");
}
wf = tbProgram.getWorkflowByName("TUBERCULOSIS TREATMENT GROUP");
log.debug("worlflow is " + wf + " and patientSet is " + ps);
states = pss.getCurrentStates(ps, wf);
if (states != null) {
log.debug("about to loop through [" + states.size() + "] statuses");
for (Map.Entry<Integer, PatientState> e : states.entrySet()) {
patientDataHolder.get(e.getKey()).put(TB.TB_GROUP,
e.getValue().getState().getConcept().getName(locale, false).getName());
log.debug("Just put state [" + e.getValue().getState().getConcept().getName(locale).getName()
+ "] in for patient [" + e.getKey() + "]");
// also want to add dynamically
PatientState state = e.getValue();
Map<String, String> holder = new HashMap<String, String>();
holder.put(General.ID, e.getKey().toString());
holder.put(Hiv.OBS_TYPE, TB.TB_GROUP);
holder.put(Hiv.OBS_DATE, formatDate(state.getStartDate()));
holder.put("stop_date", formatDate(state.getEndDate()));
holder.put(Hiv.RESULT, state.getState().getConcept().getName(locale).getName());
maker.addDynamic(holder);
}
} else {
log.debug("states is null, can't proceed");
}
}
log.debug("Pulled enrollments and hiv treatment status in " + (System.currentTimeMillis() - l) + " ms");
l = System.currentTimeMillis();
{
PersonService personService = Context.getPersonService();
RelationshipType relType = personService.getRelationshipTypeByName("Accompagnateur/Patient");
if (relType != null) {
// get the accomp leader as well
RelationshipType accompLeaderType = personService
.getRelationshipTypeByName("Accompagnateur Leader/Opposite of Accompagnateur Leader");
Map<Integer, List<Person>> accompRelations = null;
if (accompLeaderType != null)
accompRelations = pss.getRelatives(null, accompLeaderType, false);
else
accompRelations = new HashMap<Integer, List<Person>>();
Map<Integer, List<Person>> chws = pss.getRelatives(ps, relType, false);
for (Map.Entry<Integer, List<Person>> e : chws.entrySet()) {
Person chw = e.getValue().get(0);
if (chw != null) {
patientDataHolder.get(e.getKey()).put(Hiv.ACCOMP_FIRST_NAME, chw.getGivenName());
patientDataHolder.get(e.getKey()).put(Hiv.ACCOMP_LAST_NAME, chw.getFamilyName());
}
// try to get accomp leader too
List<Person> accompLeaderRels = accompRelations.get(chw.getPersonId());
if (accompLeaderRels != null && accompLeaderRels.size() > 0) {
Person leader = accompLeaderRels.get(0);
patientDataHolder.get(e.getKey()).put(Hiv.ACCOMP_LEADER_FIRST_NAME, leader.getGivenName());
patientDataHolder.get(e.getKey()).put(Hiv.ACCOMP_LEADER_LAST_NAME, leader.getFamilyName());
} else {
log.debug("No accomp leader relationships at all to this accompagnateur, so can't find leader");
}
}
}
}
log.debug("Pulled accompagnateurs in " + (System.currentTimeMillis() - l) + " ms");
l = System.currentTimeMillis();
// --- for every arv drug, addDynamic() a holder with
// Hiv.OBS_TYPE == Hiv.ARV or "arv"
// General.DOSE_PER_DAY == total dose per day == ddd
// Hiv.OBS_DATE == start date of arvs
// Hiv.ARV == the name of the drug as 3-letter abbreviation, or whatever
// "stop_date" == stop date for ARVS
// "ddd_quotient" == number of times taken per day (i think)
// "strength_unit" == unit for strength, e.g, "tab"
// "strength_dose" == amount given per time
/*
{
// ARV REGIMENS
Map<Integer, List<DrugOrder>> regimens = pss.getDrugOrders(ps, Context.getConceptService().getConceptByName("ANTIRETROVIRAL DRUGS"));
for (Map.Entry<Integer, List<DrugOrder>> e : regimens.entrySet()) {
Date earliestStart = null;
for (DrugOrder reg : e.getValue()) {
try {
if (earliestStart == null || (reg.getStartDate() != null && earliestStart.compareTo(reg.getStartDate()) > 0))
earliestStart = reg.getStartDate();
Double ddd = reg.getDose() * Integer.parseInt(reg.getFrequency().substring(0, 1));
if (!reg.getUnits().equals(reg.getDrug().getUnits()))
throw new RuntimeException("Units mismatch: " + reg.getUnits() + " vs " + reg.getDrug().getUnits());
ddd /= reg.getDrug().getDoseStrength();
Map<String, String> holder = new HashMap<String, String>();
holder.put(General.ID, e.getKey().toString());
holder.put(Hiv.OBS_TYPE, Hiv.ARV);
holder.put(General.DOSE_PER_DAY, ddd.toString());
holder.put(Hiv.OBS_DATE, formatDate(reg.getStartDate()));
holder.put(Hiv.ARV, reg.getDrug().getName());
holder.put("stop_date", formatDate(reg.getDiscontinued() ? reg.getDiscontinuedDate() : reg.getAutoExpireDate()));
holder.put("ddd_quotient", reg.getFrequency().substring(0, 1));
//holder.put("strength_unit", reg.getUnits());
//holder.put("strength_dose", reg.getDose().toString());
holder.put("strength_unit", "");
holder.put("strength_dose", "");
maker.addDynamic(holder);
log.debug("HIV added " + holder);
} catch (Exception ex) {
log.warn("Exception with a drug order: " + reg, ex);
}
}
if (earliestStart != null)
patientDataHolder.get(e.getKey()).put(Hiv.FIRST_ARV_DATE, formatDate(earliestStart));
}
}
*/
// --- for every tb drug, addDynamic() a holder with
// Hiv.OBS_TYPE == TB.TB_REGIMEN or "atb"
// TB.TB_REGIMEN == the name of the drug
// General.DOSE_PER_DAY == total dose per day == ddd
// Hiv.OBS_DATE == start date of arvs
// "stop_date" == stop date for ARVS
// "ddd_quotient" == number of times taken per day (i think)
// "strength_unit" == unit for strength, e.g, "tab"
// "strength_dose" == amount given per time
/*
{
// TB REGIMENS
Map<Integer, List<DrugOrder>> regimens = pss.getDrugOrders(ps, Context.getConceptService().getConceptByName("TUBERCULOSIS TREATMENT DRUGS"));
for (Map.Entry<Integer, List<DrugOrder>> e : regimens.entrySet()) {
Date earliestStart = null;
for (DrugOrder reg : e.getValue()) {
if (earliestStart == null || (reg.getStartDate() != null && earliestStart.compareTo(reg.getStartDate()) > 0))
earliestStart = reg.getStartDate();
Double ddd = reg.getDose() * Integer.parseInt(reg.getFrequency().substring(0, 1));
Map<String, String> holder = new HashMap<String, String>();
holder.put(General.ID, e.getKey().toString());
holder.put(Hiv.OBS_TYPE, TB.TB_REGIMEN);
holder.put(General.DOSE_PER_DAY, ddd.toString());
holder.put(Hiv.OBS_DATE, formatDate(reg.getStartDate()));
holder.put(TB.TB_REGIMEN, reg.getDrug().getName());
holder.put("stop_date", formatDate(reg.getDiscontinued() ? reg.getDiscontinuedDate() : reg.getAutoExpireDate()));
holder.put("ddd_quotient", reg.getFrequency().substring(0, 1));
//holder.put("strength_unit", reg.getUnits());
//holder.put("strength_dose", reg.getDose().toString());
holder.put("strength_unit", "");
holder.put("strength_dose", "");
maker.addDynamic(holder);
log.debug("TB added " + holder);
}
if (earliestStart != null)
patientDataHolder.get(e.getKey()).put(TB.FIRST_TB_REGIMEN_DATE, formatDate(earliestStart));
}
}
*/
{
// ALL REGIMENS
Map<Integer, List<DrugOrder>> regimens = pss.getDrugOrders(ps, null);
List<Concept> unwantedHiv = Context.getConceptService().getConceptsByConceptSet(
Context.getConceptService().getConcept("ANTIRETROVIRAL DRUGS"));
List<Concept> unwantedTb = Context.getConceptService().getConceptsByConceptSet(
Context.getConceptService().getConcept("TUBERCULOSIS TREATMENT DRUGS"));
for (Map.Entry<Integer, List<DrugOrder>> e : regimens.entrySet()) {
Date earliestStart = null;
for (DrugOrder reg : e.getValue()) {
try {
if (earliestStart == null
|| (reg.getStartDate() != null && earliestStart.compareTo(reg.getStartDate()) > 0))
earliestStart = reg.getStartDate();
Double ddd = reg.getDose() * Integer.parseInt(reg.getFrequency().substring(0, 1));
if (!reg.getUnits().equals(reg.getDrug().getUnits()))
throw new RuntimeException("Units mismatch: " + reg.getUnits() + " vs "
+ reg.getDrug().getUnits());
ddd /= reg.getDrug().getDoseStrength();
Map<String, String> holder = new HashMap<String, String>();
holder.put(General.ID, e.getKey().toString());
if (OpenmrsUtil.isConceptInList(reg.getDrug().getConcept(), unwantedHiv)) {
holder.put(Hiv.OBS_TYPE, Hiv.ARV);
} else if (OpenmrsUtil.isConceptInList(reg.getDrug().getConcept(), unwantedTb)) {
holder.put(Hiv.OBS_TYPE, TB.TB_REGIMEN);
} else {
holder.put(Hiv.OBS_TYPE, General.OTHER_REGIMEN);
}
holder.put(General.DOSE_PER_DAY, ddd.toString());
holder.put(Hiv.OBS_DATE, formatDate(reg.getStartDate()));
holder.put(Hiv.ARV, reg.getDrug().getName());
holder.put("stop_date", formatDate(reg.getDiscontinued() ? reg.getDiscontinuedDate() : reg
.getAutoExpireDate()));
holder.put("ddd_quotient", reg.getFrequency().substring(0, 1));
//holder.put("strength_unit", reg.getUnits());
//holder.put("strength_dose", reg.getDose().toString());
holder.put("strength_unit", "");
holder.put("strength_dose", "");
if (reg.getCreator() != null) {
if (reg.getCreator().getUsername() != null) {
holder.put(General.CREATOR, reg.getCreator().getUsername());
} else {
holder.put(General.CREATOR, "Unknown");
}
} else {
holder.put(General.CREATOR, "Unknown");
}
maker.addDynamic(holder);
log.debug("HIV added " + holder);
}
catch (Exception ex) {
log.warn("Exception with a drug order: " + reg, ex);
}
}
}
}
log.debug("Pulled regimens in " + (System.currentTimeMillis() - l) + " ms");
l = System.currentTimeMillis();
for (Concept c : dynamicConceptsToGet) {
long l1 = System.currentTimeMillis();
String typeToUse = obsTypesForDynamicConcepts.get(c);
Map<Integer, List<Obs>> temp = pss.getObservations(ps, c);
long l2 = System.currentTimeMillis();
for (Map.Entry<Integer, List<Obs>> e : temp.entrySet()) {
Integer ptId = e.getKey();
List<Obs> obs = e.getValue();
for (Obs o : obs) {
Map<String, String> holder = new HashMap<String, String>();
holder.put(General.ID, ptId.toString());
holder.put(Hiv.OBS_DATE, formatDate(o.getObsDatetime()));
holder.put(Hiv.RESULT, o.getValueAsString(locale));
holder.put(Hiv.OBS_TYPE, typeToUse);
holder.put("cdt", formatDate(o.getDateCreated()));
if (o.getCreator() != null) {
if (o.getCreator().getUsername() != null) {
holder.put(General.CREATOR, o.getCreator().getUsername());
} else {
holder.put(General.CREATOR, "Unknown");
}
} else {
holder.put(General.CREATOR, "Unknown");
}
maker.addDynamic(holder);
}
}
long l3 = System.currentTimeMillis();
log.debug("\t" + typeToUse + " " + c + " step 1: " + (l2 - l1) + " ms. step 2: " + (l3 - l2) + " ms.");
}
log.debug("Pulled dynamicConceptsToGet in " + (System.currentTimeMillis() - l) + " ms");
l = System.currentTimeMillis();
Map<Integer, Encounter> encounterList = Context.getPatientSetService().getEncounters(ps);
for (Map.Entry<Integer, Encounter> e : encounterList.entrySet()) {
Map<String, String> holder = new HashMap<String, String>();
holder.put(General.ID, e.getKey().toString());
holder.put(Hiv.OBS_TYPE, "encounter");
if (e.getValue().getEncounterDatetime() != null) {
holder.put(Hiv.OBS_DATE, formatDate(e.getValue().getEncounterDatetime()));
} else {
holder.put(Hiv.OBS_DATE, "");
}
if (e.getValue().getEncounterType() != null) {
holder.put(Hiv.RESULT, e.getValue().getEncounterType().getName());
} else {
holder.put(Hiv.RESULT, "");
}
if (e.getValue().getCreator() != null) {
if (e.getValue().getCreator().getUsername() != null) {
holder.put(General.CREATOR, e.getValue().getCreator().getUsername());
} else {
holder.put(General.CREATOR, "Unknown");
}
} else {
holder.put(General.CREATOR, "Unknown");
}
if (e.getValue().getObs() != null) {
holder.put(General.SIZE, "" + e.getValue().getObs().size());
} else {
holder.put(General.SIZE, "0");
}
maker.addDynamic(holder);
log.debug("Encounters added " + holder);
}
/*
// hack for demo in capetown using Kenya data
{
// arv start date
Map<Integer, List<Obs>> observs = pss.getObservations(ps, Context.getConceptService().getConcept(1255));
for (Map.Entry<Integer, List<Obs>> e : observs.entrySet()) {
Date date = null;
for (Obs observ : e.getValue()) {
if (observ.getValueCoded().getConceptId() == 1256) {
date = observ.getObsDatetime();
if (date == null) {
date = observ.getEncounter().getEncounterDatetime();
}
break;
}
}
if (date != null) {
patientDataHolder.get(e.getKey()).put(Hiv.FIRST_ARV_DATE, formatDate(date));
}
}
// tb tx start date
observs = pss.getObservations(ps, Context.getConceptService().getConcept(1268));
for (Map.Entry<Integer, List<Obs>> e : observs.entrySet()) {
Date date = null;
for (Obs observ : e.getValue()) {
if (observ.getValueCoded().getConceptId() == 1256) {
date = observ.getObsDatetime();
if (date == null) {
date = observ.getEncounter().getEncounterDatetime();
}
break;
}
}
if (date != null) {
patientDataHolder.get(e.getKey()).put(TB.FIRST_TB_REGIMEN_DATE, formatDate(date));
}
}
}
*/
/*
// location of most recent encounter
Map<Integer, Encounter> encs = pss.getEncountersByType(ps, null);
for (Map.Entry<Integer, Encounter> e : encs.entrySet()) {
String locName = null;
Location encLocation = e.getValue().getLocation();
if (encLocation != null) {
locName = encLocation.getName();
}
if (locName != null && locName.length() > 0) {
patientDataHolder.get(e.getKey()).put(General.SITE, locName);
}
}
*/
for (Map<String, String> patient : patientDataHolder.values()) {
// patient.put("BIRTH_YEAR", "1978");
//patient.put(General.HIV_POSITIVE_P, "t");
maker.addStatic(patient);
}
log.debug("Loaded data into report-maker in " + (System.currentTimeMillis() - l) + " ms");
l = System.currentTimeMillis();
File dir = new File("NEAL_REPORT_DIR");
dir.mkdir();
String filename = maker.generateReport(dir.getAbsolutePath() + "/");
log.debug("ran maker.generateReport() in " + (System.currentTimeMillis() - l) + " ms");
l = System.currentTimeMillis();
Map<String, Object> model = new HashMap<String, Object>();
model.put("dir", dir);
model.put("filename", filename);
AbstractView view = new AbstractView() {
protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response)
throws Exception {
File f = new File((File) model.get("dir"), (String) model.get("filename"));
response.setHeader("Content-Disposition", "attachment; filename=" + f.getName());
response.setHeader("Pragma", "no-cache");
response.setContentType("application/pdf");
response.setContentLength((int) f.length());
BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
BufferedInputStream in = new BufferedInputStream(new FileInputStream(f));
for (int i = in.read(); i >= 0; i = in.read()) {
out.write(i);
}
in.close();
out.flush();
System.gc();
f.delete();
}
};
return new ModelAndView(view, model);
}
|
diff --git a/vhdllab-client/src/main/java/hr/fer/zemris/vhdllab/platform/ui/command/WelcomeCommand.java b/vhdllab-client/src/main/java/hr/fer/zemris/vhdllab/platform/ui/command/WelcomeCommand.java
index 802ca632..4ed75820 100644
--- a/vhdllab-client/src/main/java/hr/fer/zemris/vhdllab/platform/ui/command/WelcomeCommand.java
+++ b/vhdllab-client/src/main/java/hr/fer/zemris/vhdllab/platform/ui/command/WelcomeCommand.java
@@ -1,101 +1,101 @@
/*******************************************************************************
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership.
*
* 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 hr.fer.zemris.vhdllab.platform.ui.command;
import java.util.prefs.Preferences;
import javax.swing.JComponent;
import org.apache.commons.lang.SystemUtils;
import org.springframework.richclient.command.ActionCommand;
import org.springframework.richclient.command.CommandManager;
import org.springframework.richclient.command.support.ApplicationWindowAwareCommand;
import org.springframework.richclient.dialog.ApplicationDialog;
import org.springframework.richclient.dialog.CloseAction;
import org.springframework.richclient.text.HtmlPane;
public class WelcomeCommand extends ApplicationWindowAwareCommand {
public static final String ID = "welcomeCommand";
protected static final String PREF_WELCOME_DIALOG_SHOW_COUNT = "welcome.dialog.show.count";
public WelcomeCommand() {
super(ID);
}
@Override
protected void doExecuteCommand() {
Preferences pref = Preferences.userNodeForPackage(WelcomeCommand.class);
int count = pref.getInt(PREF_WELCOME_DIALOG_SHOW_COUNT, 0);
if (count < 10) {
- // showWelcomeDialog();
+ showWelcomeDialog();
showUpdateJavaDialog();
pref.putInt(PREF_WELCOME_DIALOG_SHOW_COUNT, count + 1);
}
}
protected void showWelcomeDialog() {
CommandManager cm = getApplicationWindow().getCommandManager();
ActionCommand command = (ActionCommand) cm.getCommand("bugsCommand");
command.execute();
}
protected void showUpdateJavaDialog() {
if (!SystemUtils.JAVA_RUNTIME_VERSION.startsWith("1.7")) {
UpdateJavaDialog dialog = new UpdateJavaDialog();
dialog.setParentComponent(getApplicationWindow().getControl());
dialog.showDialog();
}
}
private static class UpdateJavaDialog extends ApplicationDialog {
public UpdateJavaDialog() {
super();
setTitle("Update Java");
setModal(false);
setCloseAction(CloseAction.DISPOSE);
}
@Override
protected JComponent createDialogContentPane() {
HtmlPane pane = new HtmlPane();
pane.setText("<html>A number of VHDLLab bugs are actually bugs in Java itself.<br />"
+ "Please update Java for added stability.<br />"
+ "<a href='http://www.java.com/en/download/index.jsp'>http://www.java.com/en/download/index.jsp</a>");
return pane;
}
@Override
protected boolean onFinish() {
return true;
}
@Override
protected Object[] getCommandGroupMembers() {
return new Object[] { getFinishCommand() };
}
}
}
| true | true | protected void doExecuteCommand() {
Preferences pref = Preferences.userNodeForPackage(WelcomeCommand.class);
int count = pref.getInt(PREF_WELCOME_DIALOG_SHOW_COUNT, 0);
if (count < 10) {
// showWelcomeDialog();
showUpdateJavaDialog();
pref.putInt(PREF_WELCOME_DIALOG_SHOW_COUNT, count + 1);
}
}
| protected void doExecuteCommand() {
Preferences pref = Preferences.userNodeForPackage(WelcomeCommand.class);
int count = pref.getInt(PREF_WELCOME_DIALOG_SHOW_COUNT, 0);
if (count < 10) {
showWelcomeDialog();
showUpdateJavaDialog();
pref.putInt(PREF_WELCOME_DIALOG_SHOW_COUNT, count + 1);
}
}
|
diff --git a/src/Main.java b/src/Main.java
index 0b3811f..0bae125 100644
--- a/src/Main.java
+++ b/src/Main.java
@@ -1,189 +1,189 @@
import uk.ac.shef.wit.simmetrics.similaritymetrics.*;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.converters.ArffLoader;
import java.io.*;
import java.util.*;
public class Main {
private static final int ID_ATTRIBUTE_NUM = 2;
private static final int ATTR_0_NUM = 0;
private static List<List<Integer>> process(List<String> attrs, InterfaceStringMetric metric, float metricThreshold) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
for (String value : attrs) {
result.add(process(value, attrs, metric, metricThreshold));
}
return result;
}
private static List<Integer> process(String attr, List<String> attrs, InterfaceStringMetric metric, float metricThreshold) {
List<Integer> indices = new ArrayList<Integer>();
for (int i = 0; i < attrs.size(); ++i) {
String currentAttr = attrs.get(i);
float similarity = metric.getSimilarity(attr, currentAttr);
if (similarity >= metricThreshold) {
indices.add(i);
}
}
return indices;
}
public static void main(String[] args) throws IOException {
final File root = new File(args[0]);
- final float thresholdStep = args.length >= 1 ? Float.parseFloat(args[3]) : 0.1f;
- final float thresholdStart = args.length >= 2 ? Float.parseFloat(args[1]) : 0;
- final float thresholdEnd = args.length >= 3 ? Float.parseFloat(args[2]) : 1;
+ final float thresholdStep = args.length > 1 ? Float.parseFloat(args[1]) : 0.1f;
+ final float thresholdStart = args.length > 2 ? Float.parseFloat(args[2]) : 0;
+ final float thresholdEnd = args.length > 3 ? Float.parseFloat(args[3]) : 1;
File[] files = root.listFiles();
for (File file : files) {
final String filepath = file.getCanonicalPath();
final String keyMetricName = file.getName().contains("animal") ? "substring" : "strict";
InterfaceStringMetric keyMetric = keyMetricMap.get(keyMetricName);
Instances data = loadData(filepath);
List<String> refinedValues = getValues(data);
List<String> refinedIds = getIds(data);
List<List<Integer>> processedIds = process(refinedIds, keyMetric, 1.0f);
for (final InterfaceStringMetric entityMetric : entityMetricMap.values()) {
for (float threshold = thresholdStart; threshold <= thresholdEnd; threshold += thresholdStep) {
List<List<Integer>> processedValues = process(refinedValues, entityMetric, threshold);
Result result = calc(data, processedValues, processedIds);
float precision = result.getPrecision();
float recall = result.getRecall();
System.out.println(file.getName() + " '" + entityMetric.getShortDescriptionString()+ "' " + keyMetricName
+ " " + threshold + " " + precision + " " + recall);
}
}
}
}
public static void main_0(String[] args) throws IOException {
String filename = args[0];
String entityMetricName = args[1];
String keyMetricName = args[2];
float threshold = Float.parseFloat(args[3]);
boolean outputData = args.length > 4;
System.out.println(entityMetricName);
InterfaceStringMetric entityMetric = entityMetricMap.get(entityMetricName);
InterfaceStringMetric keyMetric = keyMetricMap.get(keyMetricName);
Instances data = loadData(filename);
List<String> refinedValues = getValues(data);
List<String> refinedIds = getIds(data);
List<List<Integer>> processedIds = process(refinedIds, keyMetric, 1.0f);
List<List<Integer>> processedValues = process(refinedValues, entityMetric, threshold);
if (outputData) {
printMatching(data, ATTR_0_NUM, processedValues);
}
Result result = calc(data, processedValues, processedIds);
float precision = result.getPrecision();
float recall = result.getRecall();
System.out.println(filename + " " + entityMetricName+ " " + keyMetricName
+ " " + threshold + " " + precision + " " + recall);
}
private static Instances loadData(String filename) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(filename));
ArffLoader.ArffReader arff = new ArffLoader.ArffReader(reader);
Instances data = arff.getData();
data.setClassIndex(data.numAttributes() - 1);
return data;
}
private static List<String> getValues(Instances data) throws IOException {
Enumeration values = data.enumerateInstances();
List<String> refinedValues = new ArrayList<String>(data.numInstances());
while (values.hasMoreElements()) {
String value = ((Instance) values.nextElement()).stringValue(ATTR_0_NUM);
refinedValues.add(value.replaceAll("[-,.]", "").replaceAll("\\s+", " ").toLowerCase());
}
return refinedValues;
}
private static List<String> getIds(Instances data) {
Enumeration ids = data.enumerateInstances();
List<String> refinedIds = new ArrayList<String>(data.numInstances());
while (ids.hasMoreElements()) {
String value = ((Instance) ids.nextElement()).stringValue(ID_ATTRIBUTE_NUM);
refinedIds.add(value);
}
return refinedIds;
}
private static Result calc(Instances data, List<List<Integer>> processedValues, List<List<Integer>> processedIds) {
int truePositive = 0;
int falseNegative = 0;
int falsePositive = 0;
int trueNegative = 0;
for (int i = 0; i < processedValues.size(); ++i) {
List<Integer> indices = processedValues.get(i);
List<Integer> bar = processedIds.get(i);
String id = data.instance(i).stringValue(ID_ATTRIBUTE_NUM);
int intersec = 0;
for (Integer index : indices) {
String id2 = data.instance(index).stringValue(ID_ATTRIBUTE_NUM);
if (id.equals(id2)) {
++truePositive;
} else {
++falseNegative;
}
if (bar.contains(index))
intersec++;
}
falsePositive += bar.size() - intersec;
}
float precision = (float) truePositive / (truePositive + falsePositive);
float recall = (float) truePositive / (truePositive + falseNegative);
return new Result(precision, recall);
}
private static void printMatching(Instances data, int attribute, List<List<Integer>> processedValues) {
for (int i = 0; i < processedValues.size(); ++i) {
List<Integer> indices = processedValues.get(i);
System.out.print(data.instance(i).stringValue(attribute) + " -> ");
for (Integer index : indices) {
System.out.print(data.instance(index).stringValue(attribute) + " | ");
}
System.out.println();
}
}
static Map<String, InterfaceStringMetric> entityMetricMap = new HashMap<String, InterfaceStringMetric>() {{
put("levenshtein", new Levenshtein());
put("jaro-winkler", new JaroWinkler());
put("monge-elkan", new MongeElkan());
put("soundex", new Soundex());
put("cosine", new CosineSimilarity());
put("jaccard", new JaccardSimilarity());
}};
static Map<String, InterfaceStringMetric> keyMetricMap = new HashMap<String, InterfaceStringMetric>() {{
put("strict", new StrictEqualityMetric());
put("substring", new SubstringEqualityMetric());
}};
}
| true | true | public static void main(String[] args) throws IOException {
final File root = new File(args[0]);
final float thresholdStep = args.length >= 1 ? Float.parseFloat(args[3]) : 0.1f;
final float thresholdStart = args.length >= 2 ? Float.parseFloat(args[1]) : 0;
final float thresholdEnd = args.length >= 3 ? Float.parseFloat(args[2]) : 1;
File[] files = root.listFiles();
for (File file : files) {
final String filepath = file.getCanonicalPath();
final String keyMetricName = file.getName().contains("animal") ? "substring" : "strict";
InterfaceStringMetric keyMetric = keyMetricMap.get(keyMetricName);
Instances data = loadData(filepath);
List<String> refinedValues = getValues(data);
List<String> refinedIds = getIds(data);
List<List<Integer>> processedIds = process(refinedIds, keyMetric, 1.0f);
for (final InterfaceStringMetric entityMetric : entityMetricMap.values()) {
for (float threshold = thresholdStart; threshold <= thresholdEnd; threshold += thresholdStep) {
List<List<Integer>> processedValues = process(refinedValues, entityMetric, threshold);
Result result = calc(data, processedValues, processedIds);
float precision = result.getPrecision();
float recall = result.getRecall();
System.out.println(file.getName() + " '" + entityMetric.getShortDescriptionString()+ "' " + keyMetricName
+ " " + threshold + " " + precision + " " + recall);
}
}
}
}
| public static void main(String[] args) throws IOException {
final File root = new File(args[0]);
final float thresholdStep = args.length > 1 ? Float.parseFloat(args[1]) : 0.1f;
final float thresholdStart = args.length > 2 ? Float.parseFloat(args[2]) : 0;
final float thresholdEnd = args.length > 3 ? Float.parseFloat(args[3]) : 1;
File[] files = root.listFiles();
for (File file : files) {
final String filepath = file.getCanonicalPath();
final String keyMetricName = file.getName().contains("animal") ? "substring" : "strict";
InterfaceStringMetric keyMetric = keyMetricMap.get(keyMetricName);
Instances data = loadData(filepath);
List<String> refinedValues = getValues(data);
List<String> refinedIds = getIds(data);
List<List<Integer>> processedIds = process(refinedIds, keyMetric, 1.0f);
for (final InterfaceStringMetric entityMetric : entityMetricMap.values()) {
for (float threshold = thresholdStart; threshold <= thresholdEnd; threshold += thresholdStep) {
List<List<Integer>> processedValues = process(refinedValues, entityMetric, threshold);
Result result = calc(data, processedValues, processedIds);
float precision = result.getPrecision();
float recall = result.getRecall();
System.out.println(file.getName() + " '" + entityMetric.getShortDescriptionString()+ "' " + keyMetricName
+ " " + threshold + " " + precision + " " + recall);
}
}
}
}
|
diff --git a/src/distributed/systems/das/BattleField.java b/src/distributed/systems/das/BattleField.java
index 0789bb2..8c4ad55 100644
--- a/src/distributed/systems/das/BattleField.java
+++ b/src/distributed/systems/das/BattleField.java
@@ -1,775 +1,775 @@
package distributed.systems.das;
import java.net.InetSocketAddress;
import java.util.HashSet;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import distributed.systems.core.IMessageReceivedHandler;
import distributed.systems.core.Message;
import distributed.systems.core.SynchronizedClientSocket;
import distributed.systems.core.SynchronizedSocket;
import distributed.systems.das.units.Player;
import distributed.systems.das.units.Unit;
/**
* The actual battlefield where the fighting takes place.
* It consists of an array of a certain width and height.
*
* It is a singleton, which can be requested by the
* getBattleField() method. A unit can be put onto the
* battlefield by using the putUnit() method.
*
* @author Pieter Anemaet, Boaz Pat-El
*/
public class BattleField implements IMessageReceivedHandler {
/* The array of units */
private Unit[][] map;
private ConcurrentHashMap<InetSocketAddress, Unit> units;
/* The static singleton */
//private static BattleField battlefield;
/* Primary socket of the battlefield */
//private Socket serverSocket;
private SynchronizedSocket serverSocket;
private String url;
private int port;
private final int timeout = 3000;
private Map<ActionID, ActionInfo> pendingOutsideActions;
private Map<Integer, ActionInfo> pendingOwnActions;
private int localMessageCounter = 0;
/* The last id that was assigned to an unit. This variable is used to
* enforce that each unit has its own unique id.
*/
private int lastUnitID = 0;
public final static String serverID = "server";
public final static int MAP_WIDTH = 25;
public final static int MAP_HEIGHT = 25;
//private ArrayList <Unit> units;
//private Map<InetSocketAddress, Integer> units;
private HashSet<InetSocketAddress> battlefields;
/**
* Initialize the battlefield to the specified size
* @param width of the battlefield
* @param height of the battlefield
*/
BattleField(String url, int port) {
battlefields = new HashSet<InetSocketAddress>();
this.url = url;
this.port = port;
battlefields.add(new InetSocketAddress(url, port));
initBattleField();
}
BattleField(String url, int port, String otherUrl, int otherPort) {
battlefields = new HashSet<InetSocketAddress>();
this.url = url;
this.port = port;
battlefields.add(new InetSocketAddress(url, port));
initBattleField();
Message message = new Message();
message.put("request", MessageRequest.requestBFList);
message.put("bfAddress", new InetSocketAddress(url, port));
SynchronizedClientSocket clientSocket;
clientSocket = new SynchronizedClientSocket(message, new InetSocketAddress(otherUrl, otherPort), this);
clientSocket.sendMessageWithResponse();
}
private synchronized void initBattleField(){
map = new Unit[MAP_WIDTH][MAP_WIDTH];
units = new ConcurrentHashMap<InetSocketAddress, Unit>();
serverSocket = new SynchronizedSocket(url, port);
serverSocket.addMessageReceivedHandler(this);
//units = new ArrayList<Unit>();
pendingOwnActions = new ConcurrentHashMap<Integer, ActionInfo>();
pendingOutsideActions = new ConcurrentHashMap<ActionID, ActionInfo>();
//Updates to game state
new Thread(new Runnable() {
public void run() {
SynchronizedClientSocket clientSocket;
while(true) {
for( Map.Entry<InetSocketAddress, Unit> entry : units.entrySet()) {
if(!entry.getValue().getBattlefieldAddress().equals(new InetSocketAddress(url, port))) continue;
Message message = new Message();
message.put("request", MessageRequest.gameState);
message.put("gamestate", map);
//Puts position of the unit we are sending to in the map we are sending
Unit u = entry.getValue();
message.put("unit", u);
clientSocket = new SynchronizedClientSocket(message, entry.getKey(), null);
clientSocket.sendMessage();
}
try {
Thread.sleep(100L);//Time between gameState update is sent to units
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
/**
* Singleton method which returns the sole
* instance of the battlefield.
*
* @return the battlefield.
*/
/*
public static BattleField getBattleField() {
if (battlefield == null)
battlefield = new BattleField(MAP_WIDTH, MAP_HEIGHT);
return battlefield;
}*/
/**
* Puts a new unit at the specified position. First, it
* checks whether the position is empty, if not, it
* does nothing.
* In addition, the unit is also put in the list of known units.
*
* @param unit is the actual unit being spawned
* on the specified position.
* @param x is the x position.
* @param y is the y position.
* @return true when the unit has been put on the
* specified position.
*/
private boolean spawnUnit(Unit unit, InetSocketAddress address, int x, int y)
{
synchronized (this) {
if (map[x][y] != null)
return false;
map[x][y] = unit;
//unit.setRunning(false);
unit.setPosition(x, y);
units.put(address, unit);
}
return true;
}
/**
* Put a unit at the specified position. First, it
* checks whether the position is empty, if not, it
* does nothing.
*
* @param unit is the actual unit being put
* on the specified position.
* @param x is the x position.
* @param y is the y position.
* @return true when the unit has been put on the
* specified position.
*/
private synchronized boolean putUnit(Unit unit, int x, int y)
{
if (map[x][y] != null)
return false;
map[x][y] = unit;
unit.setPosition(x, y);
return true;
}
/**
* Get a unit from a position.
*
* @param x position.
* @param y position.
* @return the unit at the specified position, or return
* null if there is no unit at that specific position.
*/
public Unit getUnit(int x, int y)
{
assert x >= 0 && x < map.length;
assert y >= 0 && x < map[0].length;
return map[x][y];
}
/**
* Move the specified unit a certain number of steps.
*
* @param unit is the unit being moved.
* @param deltax is the delta in the x position.
* @param deltay is the delta in the y position.
*
* @return true on success.
*/
private synchronized boolean moveUnit(Unit tUnit, int newX, int newY)
{
int originalX = tUnit.getX();
int originalY = tUnit.getY();
Unit unit = map[originalX][originalY];
if(unit == null || !unit.equals(tUnit)) return false;
// TODO Limitar movimentos diagonais
//if(!((Math.abs(unit.getX() - x) <= 1 && Math.abs(unit.getY() - y) == 0)|| (Math.abs(unit.getY() - y) <= 1 && Math.abs(unit.getX() - x) == 0))) return false;
//System.out.println(originalX + " " + originalY + ":");
if (unit.getHitPoints() <= 0)
return false;
if (newX >= 0 && newX < BattleField.MAP_WIDTH)
if (newY >= 0 && newY < BattleField.MAP_HEIGHT)
if (map[newX][newY] == null) {
if (putUnit(unit, newX, newY)) {
map[originalX][originalY] = null;
return true;
}
}
return false;
}
/**
* Remove a unit from a specific position and makes the unit disconnect from the server.
*
* @param x position.
* @param y position.
*/
private synchronized void removeUnit(int x, int y)
{
Unit unitToRemove = this.getUnit(x, y);
if (unitToRemove == null)
return; // There was no unit here to remove
map[x][y] = null;
unitToRemove.disconnect();
units.remove(unitToRemove);
}
/**
* Returns a new unique unit ID.
* @return int: a new unique unit ID.
*/
public synchronized int getNewUnitID() {
return ++lastUnitID;
}
public Message onMessageReceived(Message msg) {
//System.out.println("MESSAGE RECEIVED:" + msg.get("request"));
//System.out.println("MESSAGE RECEIVED " + (MessageRequest)msg.get("request"));
if((Boolean)msg.get("sync") != null && (Boolean)msg.get("sync") == true) {
//System.out.println("SYNC MESSAGE RECEIVED " + (MessageRequest)msg.get("request"));
processSyncMessage(msg);
} else {
MessageRequest request = (MessageRequest)msg.get("request");
Message reply = null;
String origin = (String)msg.get("origin");
Unit unit;
switch(request)
{
case spawnUnit:
case moveUnit:
case dealDamage:
case healDamage:
syncActionWithBattlefields(msg);
break;
case requestBFList: {
reply = new Message();
reply.put("request", MessageRequest.replyBFList);
battlefields.add((InetSocketAddress)msg.get("bfAddress"));
reply.put("bfList", battlefields);
return reply;
}
case replyBFList: {
HashSet<InetSocketAddress> bfList = (HashSet<InetSocketAddress>)msg.get("bfList");
for(InetSocketAddress address: bfList) {
battlefields.add(address);
}
for(InetSocketAddress address: battlefields) {
SynchronizedClientSocket clientSocket;
Message message = new Message();
message.put("request", MessageRequest.addBF);
message.put("bfAddress", new InetSocketAddress(url, port));
clientSocket = new SynchronizedClientSocket(message,address, this);
clientSocket.sendMessage();
}
//System.out.println("BATTLEFIELDS:"+ bfList.toString());
//reply = new Message();
//HashSet bfList = (HashSet<InetSocketAddress>)msg.get("bfList");
//int y = (Integer)msg.get("y");
//reply.put("id", msg.get("id"));
return null;
}
case addBF: {
battlefields.add((InetSocketAddress)msg.get("bfAddress"));
//System.out.println("ADD BF:"+ battlefields.toString());
return null;
}
//break;
//case removeUnit:
//this.removeUnit((Integer)msg.get("x"), (Integer)msg.get("y"));
//if(syncBF(msg)) return null;
case SyncActionResponse:
processResponseMessage(msg);
break;
case SyncActionConfirm:
return processConfirmMessage(msg);
}
}
return null;
//serverSocket.sendMessage(reply, origin);
/*
try {
if (reply != null)
serverSocket.sendMessage(reply, origin);
}
/*catch(IDNotAssignedException idnae) {
// Could happen if the target already logged out
}*/
}
private Message processEvent(Message msg, ActionInfo removeAction) {
Unit unit = null;
switch ((MessageRequest)removeAction.message.get("request")) {
case spawnUnit: {
//System.out.println("BATTLE FIELD:Spawn" + port);
System.out.println(battlefields.toString());
Boolean succeded = this.spawnUnit((Unit)msg.get("unit"), (InetSocketAddress)msg.get("address"), (Integer)msg.get("x"), (Integer)msg.get("y"));
if(succeded) {
units.put((InetSocketAddress)msg.get("address"), (Unit)msg.get("unit"));
}
Message reply = new Message();
reply.put("request", MessageRequest.spawnAck);
reply.put("succeded", succeded);
reply.put("gamestate", map);
//Puts position of the unit we are sending to in the map we are sending
Unit u = units.get((InetSocketAddress)msg.get("address"));
reply.put("unit", u);
return reply;
}
case dealDamage: {
int x = (Integer)msg.get("x");
int y = (Integer)msg.get("y");
unit = this.getUnit(x, y);
if (unit != null) {
unit.adjustHitPoints( -(Integer)msg.get("damage") );
if(unit.getHitPoints() <= 0) {
map[x][y] = null;
}
}
break;
}
case healDamage:
{
int x = (Integer)msg.get("x");
int y = (Integer)msg.get("y");
unit = this.getUnit(x, y);
if (unit != null)
unit.adjustHitPoints( (Integer)msg.get("healed") );
/* Copy the id of the message so that the unit knows
* what message the battlefield responded to.
*/
break;
}
case moveUnit:
{
//System.out.println("BATTLEFIELD: MOVEUNIT");
Unit tempUnit = (Unit)msg.get("unit");
/*
if(temptUnit == null) {
System.out.println("NULL");
}*/
boolean move = this.moveUnit(units.get((InetSocketAddress)msg.get("address")), (Integer)msg.get("x"), (Integer)msg.get("y"));
if(!move) System.out.println("MOVE CANCELED");
/* Copy the id of the message so that the unit knows
* what message the battlefield responded to.
*/
break;
}
default:
break;
}
return null;
}
private synchronized Message processConfirmMessage(Message msg) {
Integer messageID = (Integer)msg.get("serverMessageID");
//System.out.println("[S"+port+"] MessageID "+messageID+" Address "+(InetSocketAddress)msg.get("serverAddress")+"\nOutsideSize "+pendingOutsideActions.size()+"\n[S"+port+"]"+pendingOutsideActions);
ActionInfo removeAction = pendingOutsideActions.remove(new ActionID(messageID, (InetSocketAddress)msg.get("serverAddress")));
if(removeAction != null) {
removeAction.timer.cancel();
//System.out.println("[S"+port+"] OutsideSize "+pendingOutsideActions.size()+" Confirm = "+(Boolean)msg.get("confirm")+" RemoveAction Request: "+removeAction.message.get("request"));
if((Boolean)msg.get("confirm")) processEvent(msg,removeAction);
}
return null;
}
private synchronized Message processResponseMessage(Message msg) {
Integer messageID = (Integer)msg.get("serverMessageID");
ActionInfo actionInfo = pendingOwnActions.get(messageID);
InetSocketAddress serverAddress = (InetSocketAddress)msg.get("serverAddress");
Message message = msg.clone();
message.put("request", MessageRequest.SyncActionConfirm);
message.put("serverAddress", new InetSocketAddress(url, port));
message.put("serverMessageID", messageID);
if(actionInfo != null) {
if((Boolean)msg.get("ack")) {
//System.out.println("[S"+port+"] "+actionInfo.message.get("address")+" ACK TRUE from "+serverAddress.getHostName()+":"+serverAddress.getPort()+" Adding info to queue.");
actionInfo.ackReceived.add((InetSocketAddress)msg.get("serverAddress"));
if(actionInfo.ackReceived.size() == battlefields.size()-1) {
message.put("confirm", true);
for(InetSocketAddress address : actionInfo.ackReceived) {
SynchronizedClientSocket clientSocket = new SynchronizedClientSocket(message, address, this);
clientSocket.sendMessage();
}
ActionInfo removeAction = pendingOwnActions.remove(messageID);
removeAction.timer.cancel();
Message toPlayer = processEvent(msg, removeAction);
if(toPlayer!=null) {
SynchronizedClientSocket clientSocket = new SynchronizedClientSocket(toPlayer, (InetSocketAddress)msg.get("address"), this);
clientSocket.sendMessage();
}
}
} else {
pendingOwnActions.remove(messageID).timer.cancel();
message.put("confirm", false);
SynchronizedClientSocket clientSocket = new SynchronizedClientSocket(message, serverAddress, this);
clientSocket.sendMessage();
}
} else {
message.put("confirm", false);
SynchronizedClientSocket clientSocket = new SynchronizedClientSocket(message, serverAddress, this);
clientSocket.sendMessage();
}
return null;
}
private synchronized void processSyncMessage(Message msg) {
MessageRequest request = (MessageRequest)msg.get("request");
Integer messageID = (Integer)msg.get("serverMessageID");
//InetSocketAddress originAddress = (InetSocketAddress)msg.get("address");
InetSocketAddress serverAddress = (InetSocketAddress)msg.get("serverAddress");
Integer x = (Integer)msg.get("x");
Integer y = (Integer)msg.get("y");
msg.put("sync", (Boolean)false);
//System.out.println("[S"+port+"] Process Sync Message from "+serverAddress.getPort()+"\n Message "+request.name()+" with X="+x+"|Y="+y);
boolean conflictFound = false;
Set<InetSocketAddress> toRemoveTemp = new HashSet<InetSocketAddress>();
switch(request) {
case spawnUnit:
if (getUnit(x, y) == null){
for(ActionInfo info : pendingOwnActions.values()){
MessageRequest actionType = (MessageRequest)info.message.get("request");
if(actionType == MessageRequest.moveUnit || actionType == MessageRequest.spawnUnit){
if(x.equals((Integer)info.message.get("x")) && y.equals((Integer)info.message.get("y"))) {
//sendActionAck(msg, false, messageID, originAddress);
conflictFound = true;
break;
}
}
}
for(ActionInfo info : pendingOutsideActions.values()){
MessageRequest actionType = (MessageRequest)info.message.get("request");
if(actionType == MessageRequest.moveUnit || actionType == MessageRequest.spawnUnit){
if(x.equals((Integer)info.message.get("x")) && y.equals((Integer)info.message.get("y"))) {
//sendActionAck(msg, false, messageID, originAddress);
conflictFound = true;
break;
}
}
}
}
else {
conflictFound = true;
}
if(conflictFound) {
sendActionAck(msg, false, messageID, serverAddress);
} else {
addPendingOutsideAction(msg, messageID, serverAddress);
sendActionAck(msg, true, messageID, serverAddress);
}
break;
case moveUnit:
if (getUnit(x, y) == null){
Unit unit = units.get((InetSocketAddress)msg.get("address"));
if(!((Math.abs(unit.getX() - x) <= 1 && Math.abs(unit.getY() - y) == 0)|| (Math.abs(unit.getY() - y) <= 1 && Math.abs(unit.getX() - x) == 0))) {
conflictFound = true;
}
for(ActionInfo info : pendingOwnActions.values()){
MessageRequest actionType = (MessageRequest)info.message.get("request");
if(actionType == MessageRequest.moveUnit || actionType == MessageRequest.spawnUnit){
if(x.equals((Integer)info.message.get("x")) && y.equals((Integer)info.message.get("y"))) {
conflictFound = true;
break;
}
} else if(actionType == MessageRequest.healDamage || actionType == MessageRequest.dealDamage) {
if(unit.getX().equals((Integer)info.message.get("x")) && unit.getY().equals((Integer)info.message.get("y"))) {
toRemoveTemp.add((InetSocketAddress)info.message.get("serverAddress"));
}
}
}
for(ActionInfo info : pendingOutsideActions.values()){
MessageRequest actionType = (MessageRequest)info.message.get("request");
if(actionType == MessageRequest.moveUnit || actionType == MessageRequest.spawnUnit){
if(x.equals((Integer)info.message.get("x")) && y.equals((Integer)info.message.get("y"))) {
conflictFound = true;
break;
}
}
}
}
else {
conflictFound = true;
}
if(conflictFound) {
sendActionAck(msg, false, messageID, serverAddress);
} else {
for(InetSocketAddress addressToRemove : toRemoveTemp) {
ActionInfo info = pendingOwnActions.remove(addressToRemove);
if(info!=null)info.timer.cancel();
}
addPendingOutsideAction(msg, messageID, serverAddress);
sendActionAck(msg, true, messageID, serverAddress);
}
break;
case dealDamage:
case healDamage:
- if (getUnit(x, y) != null && getUnit(x, y) instanceof Player) {
+ if (getUnit(x, y) != null) {
for(ActionInfo info : pendingOwnActions.values()){
MessageRequest actionType = (MessageRequest)info.message.get("request");
if(actionType == MessageRequest.moveUnit){
Unit infoUnit = units.get((InetSocketAddress)info.message.get("address"));
if(x.equals(infoUnit.getX()) && y.equals(infoUnit.getY())) {
conflictFound = true;
break;
}
}
} for(ActionInfo info : pendingOutsideActions.values()){
MessageRequest actionType = (MessageRequest)info.message.get("request");
if(actionType == MessageRequest.moveUnit){
Unit infoUnit = units.get((InetSocketAddress)info.message.get("address"));
if(x.equals(infoUnit.getX()) && y.equals(infoUnit.getY())) {
conflictFound = true;
break;
}
}
}
}
else {
conflictFound = true;
}
if(conflictFound) {
sendActionAck(msg, false, messageID, serverAddress);
} else {
for(InetSocketAddress addressToRemove : toRemoveTemp) {
pendingOwnActions.remove(addressToRemove).timer.cancel();
}
addPendingOutsideAction(msg, messageID, serverAddress);
sendActionAck(msg, true, messageID, serverAddress);
}
break;
}
}
private void sendActionAck(Message message ,boolean valid, Integer messageID, InetSocketAddress address) {
Message toSend = new Message();
toSend = message.clone();
toSend.put("request", MessageRequest.SyncActionResponse);
toSend.put("serverAddress", (InetSocketAddress)new InetSocketAddress(url,port));
toSend.put("ack", (Boolean)valid);
SynchronizedClientSocket socket = new SynchronizedClientSocket(toSend, address, this);
socket.sendMessage();
}
/**
*
* @param message
* @return true if message is already a sync message, or false if the if it was not a sync message and it was propagated.
*/
private boolean syncBF(Message message){
for (InetSocketAddress address : battlefields) {
if(address.equals(new InetSocketAddress(url, port))) continue;
message.put("sync", (Boolean)true);
String s = "[S"+port+"] SENDING SYNC MESSAGE\nBefore change: "+message.get("address")+"\nAfter Change: ";
message.put("address", new InetSocketAddress(url,port));
s+= message.get("address");
//System.out.println(s);
//System.out.println("####################");
SynchronizedClientSocket clientSocket;
clientSocket = new SynchronizedClientSocket(message, address, this);
clientSocket.sendMessage();
//messageList.put(message, 0);
}
return false;
}
private void addPendingOutsideAction(Message message, Integer messageID, InetSocketAddress originAddress) {
Timer timer = new Timer();
//System.out.println("Adding to OUTSIDE ACTION | Message type: "+message.get("request"));
pendingOutsideActions.put(new ActionID(messageID, originAddress), new ActionInfo(message, timer, false));
timer.schedule(new ScheduledTask(), timeout);
}
public synchronized void syncActionWithBattlefields(Message message) {
Timer timer = new Timer();
pendingOwnActions.put(++localMessageCounter, new ActionInfo(message, timer, true));
sendSyncMessage(message);
timer.schedule(new ScheduledTask(), timeout);
}
private void sendSyncMessage(Message message){
SynchronizedClientSocket clientSocket;
message.put("sync", (Boolean)true);
message.put("serverAddress", new InetSocketAddress(url, port));
message.put("serverMessageID", localMessageCounter);
for (InetSocketAddress address : battlefields) {
if(address.equals(new InetSocketAddress(url, port))) continue;
clientSocket = new SynchronizedClientSocket(message, address, this);
clientSocket.sendMessage();
}
}
public InetSocketAddress getAddress() {
return new InetSocketAddress(url, port);
}
/**
* Close down the battlefield. Unregisters
* the serverSocket so the program can
* actually end.
*/
public synchronized void shutdown() {
// Remove all units from the battlefield and make them disconnect from the server
/*for (Unit unit : units) {
unit.disconnect();
unit.stopRunnerThread();
}*/
//serverSocket.unRegister();
}
private class ScheduledTask extends TimerTask implements Runnable {
//private IMessageReceivedHandler handler;
//private Message message;
//private InetSocketAddress destinationAddress;
/*
ScheduledTask(){
}*/
@Override
public void run() {
System.out.println("TIME OUT");
//TODO
//handler.onReadExceptionThrown(message, destinationAddress);
}
}
private class ActionID {
public Integer messageId; //Action Message ID
public InetSocketAddress address; //Server responsible for action
public ActionID(Integer messageId, InetSocketAddress address) {
this.messageId = messageId;
this.address = address;
}
public String toString() {
return "["+messageId+" "+address+"]";
}
@Override
public boolean equals(Object o) {
return address.equals(((ActionID)o).address) && messageId.equals(((ActionID)o).messageId) ;
}
@Override
public int hashCode() {
return address.hashCode() + messageId.hashCode() ;
}
}
private class ActionInfo {
public Message message;
public Timer timer;
public Queue<InetSocketAddress> ackReceived;
public ActionInfo(Message message, Timer timer, boolean activateQueue) {
this.message = message;
this.timer = timer;
if(activateQueue)
this.ackReceived = new ConcurrentLinkedQueue<InetSocketAddress>();
else
this.ackReceived = null;
}
}
}
| true | true | private synchronized void processSyncMessage(Message msg) {
MessageRequest request = (MessageRequest)msg.get("request");
Integer messageID = (Integer)msg.get("serverMessageID");
//InetSocketAddress originAddress = (InetSocketAddress)msg.get("address");
InetSocketAddress serverAddress = (InetSocketAddress)msg.get("serverAddress");
Integer x = (Integer)msg.get("x");
Integer y = (Integer)msg.get("y");
msg.put("sync", (Boolean)false);
//System.out.println("[S"+port+"] Process Sync Message from "+serverAddress.getPort()+"\n Message "+request.name()+" with X="+x+"|Y="+y);
boolean conflictFound = false;
Set<InetSocketAddress> toRemoveTemp = new HashSet<InetSocketAddress>();
switch(request) {
case spawnUnit:
if (getUnit(x, y) == null){
for(ActionInfo info : pendingOwnActions.values()){
MessageRequest actionType = (MessageRequest)info.message.get("request");
if(actionType == MessageRequest.moveUnit || actionType == MessageRequest.spawnUnit){
if(x.equals((Integer)info.message.get("x")) && y.equals((Integer)info.message.get("y"))) {
//sendActionAck(msg, false, messageID, originAddress);
conflictFound = true;
break;
}
}
}
for(ActionInfo info : pendingOutsideActions.values()){
MessageRequest actionType = (MessageRequest)info.message.get("request");
if(actionType == MessageRequest.moveUnit || actionType == MessageRequest.spawnUnit){
if(x.equals((Integer)info.message.get("x")) && y.equals((Integer)info.message.get("y"))) {
//sendActionAck(msg, false, messageID, originAddress);
conflictFound = true;
break;
}
}
}
}
else {
conflictFound = true;
}
if(conflictFound) {
sendActionAck(msg, false, messageID, serverAddress);
} else {
addPendingOutsideAction(msg, messageID, serverAddress);
sendActionAck(msg, true, messageID, serverAddress);
}
break;
case moveUnit:
if (getUnit(x, y) == null){
Unit unit = units.get((InetSocketAddress)msg.get("address"));
if(!((Math.abs(unit.getX() - x) <= 1 && Math.abs(unit.getY() - y) == 0)|| (Math.abs(unit.getY() - y) <= 1 && Math.abs(unit.getX() - x) == 0))) {
conflictFound = true;
}
for(ActionInfo info : pendingOwnActions.values()){
MessageRequest actionType = (MessageRequest)info.message.get("request");
if(actionType == MessageRequest.moveUnit || actionType == MessageRequest.spawnUnit){
if(x.equals((Integer)info.message.get("x")) && y.equals((Integer)info.message.get("y"))) {
conflictFound = true;
break;
}
} else if(actionType == MessageRequest.healDamage || actionType == MessageRequest.dealDamage) {
if(unit.getX().equals((Integer)info.message.get("x")) && unit.getY().equals((Integer)info.message.get("y"))) {
toRemoveTemp.add((InetSocketAddress)info.message.get("serverAddress"));
}
}
}
for(ActionInfo info : pendingOutsideActions.values()){
MessageRequest actionType = (MessageRequest)info.message.get("request");
if(actionType == MessageRequest.moveUnit || actionType == MessageRequest.spawnUnit){
if(x.equals((Integer)info.message.get("x")) && y.equals((Integer)info.message.get("y"))) {
conflictFound = true;
break;
}
}
}
}
else {
conflictFound = true;
}
if(conflictFound) {
sendActionAck(msg, false, messageID, serverAddress);
} else {
for(InetSocketAddress addressToRemove : toRemoveTemp) {
ActionInfo info = pendingOwnActions.remove(addressToRemove);
if(info!=null)info.timer.cancel();
}
addPendingOutsideAction(msg, messageID, serverAddress);
sendActionAck(msg, true, messageID, serverAddress);
}
break;
case dealDamage:
case healDamage:
if (getUnit(x, y) != null && getUnit(x, y) instanceof Player) {
for(ActionInfo info : pendingOwnActions.values()){
MessageRequest actionType = (MessageRequest)info.message.get("request");
if(actionType == MessageRequest.moveUnit){
Unit infoUnit = units.get((InetSocketAddress)info.message.get("address"));
if(x.equals(infoUnit.getX()) && y.equals(infoUnit.getY())) {
conflictFound = true;
break;
}
}
} for(ActionInfo info : pendingOutsideActions.values()){
MessageRequest actionType = (MessageRequest)info.message.get("request");
if(actionType == MessageRequest.moveUnit){
Unit infoUnit = units.get((InetSocketAddress)info.message.get("address"));
if(x.equals(infoUnit.getX()) && y.equals(infoUnit.getY())) {
conflictFound = true;
break;
}
}
}
}
else {
conflictFound = true;
}
if(conflictFound) {
sendActionAck(msg, false, messageID, serverAddress);
} else {
for(InetSocketAddress addressToRemove : toRemoveTemp) {
pendingOwnActions.remove(addressToRemove).timer.cancel();
}
addPendingOutsideAction(msg, messageID, serverAddress);
sendActionAck(msg, true, messageID, serverAddress);
}
break;
}
}
| private synchronized void processSyncMessage(Message msg) {
MessageRequest request = (MessageRequest)msg.get("request");
Integer messageID = (Integer)msg.get("serverMessageID");
//InetSocketAddress originAddress = (InetSocketAddress)msg.get("address");
InetSocketAddress serverAddress = (InetSocketAddress)msg.get("serverAddress");
Integer x = (Integer)msg.get("x");
Integer y = (Integer)msg.get("y");
msg.put("sync", (Boolean)false);
//System.out.println("[S"+port+"] Process Sync Message from "+serverAddress.getPort()+"\n Message "+request.name()+" with X="+x+"|Y="+y);
boolean conflictFound = false;
Set<InetSocketAddress> toRemoveTemp = new HashSet<InetSocketAddress>();
switch(request) {
case spawnUnit:
if (getUnit(x, y) == null){
for(ActionInfo info : pendingOwnActions.values()){
MessageRequest actionType = (MessageRequest)info.message.get("request");
if(actionType == MessageRequest.moveUnit || actionType == MessageRequest.spawnUnit){
if(x.equals((Integer)info.message.get("x")) && y.equals((Integer)info.message.get("y"))) {
//sendActionAck(msg, false, messageID, originAddress);
conflictFound = true;
break;
}
}
}
for(ActionInfo info : pendingOutsideActions.values()){
MessageRequest actionType = (MessageRequest)info.message.get("request");
if(actionType == MessageRequest.moveUnit || actionType == MessageRequest.spawnUnit){
if(x.equals((Integer)info.message.get("x")) && y.equals((Integer)info.message.get("y"))) {
//sendActionAck(msg, false, messageID, originAddress);
conflictFound = true;
break;
}
}
}
}
else {
conflictFound = true;
}
if(conflictFound) {
sendActionAck(msg, false, messageID, serverAddress);
} else {
addPendingOutsideAction(msg, messageID, serverAddress);
sendActionAck(msg, true, messageID, serverAddress);
}
break;
case moveUnit:
if (getUnit(x, y) == null){
Unit unit = units.get((InetSocketAddress)msg.get("address"));
if(!((Math.abs(unit.getX() - x) <= 1 && Math.abs(unit.getY() - y) == 0)|| (Math.abs(unit.getY() - y) <= 1 && Math.abs(unit.getX() - x) == 0))) {
conflictFound = true;
}
for(ActionInfo info : pendingOwnActions.values()){
MessageRequest actionType = (MessageRequest)info.message.get("request");
if(actionType == MessageRequest.moveUnit || actionType == MessageRequest.spawnUnit){
if(x.equals((Integer)info.message.get("x")) && y.equals((Integer)info.message.get("y"))) {
conflictFound = true;
break;
}
} else if(actionType == MessageRequest.healDamage || actionType == MessageRequest.dealDamage) {
if(unit.getX().equals((Integer)info.message.get("x")) && unit.getY().equals((Integer)info.message.get("y"))) {
toRemoveTemp.add((InetSocketAddress)info.message.get("serverAddress"));
}
}
}
for(ActionInfo info : pendingOutsideActions.values()){
MessageRequest actionType = (MessageRequest)info.message.get("request");
if(actionType == MessageRequest.moveUnit || actionType == MessageRequest.spawnUnit){
if(x.equals((Integer)info.message.get("x")) && y.equals((Integer)info.message.get("y"))) {
conflictFound = true;
break;
}
}
}
}
else {
conflictFound = true;
}
if(conflictFound) {
sendActionAck(msg, false, messageID, serverAddress);
} else {
for(InetSocketAddress addressToRemove : toRemoveTemp) {
ActionInfo info = pendingOwnActions.remove(addressToRemove);
if(info!=null)info.timer.cancel();
}
addPendingOutsideAction(msg, messageID, serverAddress);
sendActionAck(msg, true, messageID, serverAddress);
}
break;
case dealDamage:
case healDamage:
if (getUnit(x, y) != null) {
for(ActionInfo info : pendingOwnActions.values()){
MessageRequest actionType = (MessageRequest)info.message.get("request");
if(actionType == MessageRequest.moveUnit){
Unit infoUnit = units.get((InetSocketAddress)info.message.get("address"));
if(x.equals(infoUnit.getX()) && y.equals(infoUnit.getY())) {
conflictFound = true;
break;
}
}
} for(ActionInfo info : pendingOutsideActions.values()){
MessageRequest actionType = (MessageRequest)info.message.get("request");
if(actionType == MessageRequest.moveUnit){
Unit infoUnit = units.get((InetSocketAddress)info.message.get("address"));
if(x.equals(infoUnit.getX()) && y.equals(infoUnit.getY())) {
conflictFound = true;
break;
}
}
}
}
else {
conflictFound = true;
}
if(conflictFound) {
sendActionAck(msg, false, messageID, serverAddress);
} else {
for(InetSocketAddress addressToRemove : toRemoveTemp) {
pendingOwnActions.remove(addressToRemove).timer.cancel();
}
addPendingOutsideAction(msg, messageID, serverAddress);
sendActionAck(msg, true, messageID, serverAddress);
}
break;
}
}
|
diff --git a/src/main/java/test/cli/cloudify/cloud/services/rackspace/RackspaceCloudService.java b/src/main/java/test/cli/cloudify/cloud/services/rackspace/RackspaceCloudService.java
index 27ec867f..328add76 100644
--- a/src/main/java/test/cli/cloudify/cloud/services/rackspace/RackspaceCloudService.java
+++ b/src/main/java/test/cli/cloudify/cloud/services/rackspace/RackspaceCloudService.java
@@ -1,146 +1,146 @@
package test.cli.cloudify.cloud.services.rackspace;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.cloudifysource.esc.driver.provisioning.openstack.Node;
import org.cloudifysource.esc.driver.provisioning.openstack.OpenstackException;
import test.cli.cloudify.cloud.services.AbstractCloudService;
import test.cli.cloudify.cloud.services.tools.openstack.OpenstackClient;
import test.cli.cloudify.cloud.services.tools.openstack.RackspaceClient;
import framework.utils.IOUtils;
import framework.utils.LogUtils;
public class RackspaceCloudService extends AbstractCloudService {
private String user = "gsrackspace";
private String apiKey = "1ee2495897b53409f4643926f1968c0c";
private String tenant = "658142";
private RackspaceClient rackspaceClient;
public RackspaceCloudService() {
super("rsopenstack");
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getApiKey() {
return apiKey;
}
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
public String getTenant() {
return tenant;
}
public void setTenant(String tenant) {
this.tenant = tenant;
}
@Override
public void injectCloudAuthenticationDetails()
throws IOException {
getProperties().put("user", this.user);
getProperties().put("apiKey", this.apiKey);
getProperties().put("tenant", this.tenant);
Map<String, String> propsToReplace = new HashMap<String, String>();
propsToReplace.put("machineNamePrefix " + "\"agent\"", "machineNamePrefix " + '"' + getMachinePrefix()
+ "cloudify-agent" + '"');
propsToReplace.put("managementGroup " + "\"management\"", "managementGroup " + '"' + getMachinePrefix()
+ "cloudify-manager" + '"');
propsToReplace.put("numberOfManagementMachines 1", "numberOfManagementMachines " + getNumberOfManagementMachines());
propsToReplace.put("\"openstack.wireLog\": \"false\"", "\"openstack.wireLog\": \"true\"");
IOUtils.replaceTextInFile(getPathToCloudGroovy(), propsToReplace);
}
private RackspaceClient createClient() {
RackspaceClient client = new RackspaceClient();
client.setConfig(getCloud());
return client;
}
@Override
public boolean scanLeakedAgentNodes() {
if (rackspaceClient == null) {
this.rackspaceClient = createClient();
}
String token = rackspaceClient.createAuthenticationToken();
final String agentPrefix = getCloud().getProvider().getMachineNamePrefix();
return checkForLeakedNode(token, agentPrefix);
}
@Override
public boolean scanLeakedAgentAndManagementNodes() {
if(rackspaceClient == null) {
rackspaceClient = createClient();
}
String token = rackspaceClient.createAuthenticationToken();
final String agentPrefix = getCloud().getProvider().getMachineNamePrefix();
final String mgmtPrefix = getCloud().getProvider().getManagementGroup();
final boolean result = checkForLeakedNode(token, agentPrefix, mgmtPrefix);
this.rackspaceClient.close();
return result;
}
private boolean checkForLeakedNode(String token, final String... prefixes) {
List<Node> nodes;
try {
nodes = rackspaceClient.listServers(token);
} catch (OpenstackException e) {
throw new IllegalStateException("Failed to query openstack cloud for current servers", e);
}
List<Node> leakedNodes = new LinkedList<Node>();
for (Node node : nodes) {
if (node.getStatus().equals(OpenstackClient.MACHINE_STATUS_ACTIVE)) {
for (String prefix : prefixes) {
if (node.getName().startsWith(prefix)) {
leakedNodes.add(node);
}
}
}
}
if (leakedNodes.size() > 0) {
LogUtils.log("Found leaking nodes in Rackspace cloud after teardown");
for (Node node : leakedNodes) {
LogUtils.log("Shutting down: " + node);
try {
rackspaceClient.terminateServer(node.getId(), token, System.currentTimeMillis() + 60000);
} catch (Exception e) {
- LogUtils.log("Failed to terminate HP openstack node: " + node.getId()
+ LogUtils.log("Failed to terminate Rackspace openstack node: " + node.getId()
+ ". This node may be leaking. Node details: " + node + ", Error was: " + e.getMessage(), e);
}
}
return false;
}
return true;
}
}
| true | true | private boolean checkForLeakedNode(String token, final String... prefixes) {
List<Node> nodes;
try {
nodes = rackspaceClient.listServers(token);
} catch (OpenstackException e) {
throw new IllegalStateException("Failed to query openstack cloud for current servers", e);
}
List<Node> leakedNodes = new LinkedList<Node>();
for (Node node : nodes) {
if (node.getStatus().equals(OpenstackClient.MACHINE_STATUS_ACTIVE)) {
for (String prefix : prefixes) {
if (node.getName().startsWith(prefix)) {
leakedNodes.add(node);
}
}
}
}
if (leakedNodes.size() > 0) {
LogUtils.log("Found leaking nodes in Rackspace cloud after teardown");
for (Node node : leakedNodes) {
LogUtils.log("Shutting down: " + node);
try {
rackspaceClient.terminateServer(node.getId(), token, System.currentTimeMillis() + 60000);
} catch (Exception e) {
LogUtils.log("Failed to terminate HP openstack node: " + node.getId()
+ ". This node may be leaking. Node details: " + node + ", Error was: " + e.getMessage(), e);
}
}
return false;
}
return true;
}
| private boolean checkForLeakedNode(String token, final String... prefixes) {
List<Node> nodes;
try {
nodes = rackspaceClient.listServers(token);
} catch (OpenstackException e) {
throw new IllegalStateException("Failed to query openstack cloud for current servers", e);
}
List<Node> leakedNodes = new LinkedList<Node>();
for (Node node : nodes) {
if (node.getStatus().equals(OpenstackClient.MACHINE_STATUS_ACTIVE)) {
for (String prefix : prefixes) {
if (node.getName().startsWith(prefix)) {
leakedNodes.add(node);
}
}
}
}
if (leakedNodes.size() > 0) {
LogUtils.log("Found leaking nodes in Rackspace cloud after teardown");
for (Node node : leakedNodes) {
LogUtils.log("Shutting down: " + node);
try {
rackspaceClient.terminateServer(node.getId(), token, System.currentTimeMillis() + 60000);
} catch (Exception e) {
LogUtils.log("Failed to terminate Rackspace openstack node: " + node.getId()
+ ". This node may be leaking. Node details: " + node + ", Error was: " + e.getMessage(), e);
}
}
return false;
}
return true;
}
|
diff --git a/plugins/org.eclipse.xtext.ui.core/src/org/eclipse/xtext/ui/core/editor/XtextDamagerRepairer.java b/plugins/org.eclipse.xtext.ui.core/src/org/eclipse/xtext/ui/core/editor/XtextDamagerRepairer.java
index e4acfc7ac..64c856b58 100644
--- a/plugins/org.eclipse.xtext.ui.core/src/org/eclipse/xtext/ui/core/editor/XtextDamagerRepairer.java
+++ b/plugins/org.eclipse.xtext.ui.core/src/org/eclipse/xtext/ui/core/editor/XtextDamagerRepairer.java
@@ -1,112 +1,112 @@
/*******************************************************************************
* Copyright (c) 2009 itemis AG (http://www.itemis.eu) 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.xtext.ui.core.editor;
import org.eclipse.jface.text.DocumentEvent;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITypedRegion;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.rules.DefaultDamagerRepairer;
import org.eclipse.jface.text.rules.ITokenScanner;
import org.eclipse.xtext.parsetree.AbstractNode;
import org.eclipse.xtext.parsetree.CompositeNode;
import org.eclipse.xtext.parsetree.LeafNode;
import org.eclipse.xtext.parsetree.Range;
import org.eclipse.xtext.resource.XtextResource;
import org.eclipse.xtext.ui.core.editor.model.UnitOfWork;
import org.eclipse.xtext.ui.core.editor.model.XtextDocument;
/**
* @author Sebastian Zarnekow - Initial contribution and API
*/
public class XtextDamagerRepairer extends DefaultDamagerRepairer {
public XtextDamagerRepairer(ITokenScanner scanner) {
super(scanner);
}
protected XtextDocument getDocument() {
return (XtextDocument) fDocument;
}
@Override
public void setDocument(IDocument document) {
if (document != null && !(document instanceof XtextDocument))
throw new IllegalArgumentException("document is invalid: " + document);
super.setDocument(document);
}
@Override
public IRegion getDamageRegion(ITypedRegion partition, final DocumentEvent e, boolean documentPartitioningChanged) {
if (documentPartitioningChanged)
return partition;
IRegion result = getDocument().readOnly(new UnitOfWork<IRegion>(){
private final int offset = e.getOffset();
private final int endOffset = offset + e.getLength();
public IRegion exec(XtextResource resource) throws Exception {
AbstractNode node = resource.getParseResult().getRootNode();
AbstractNode start = null;
AbstractNode end = null;
// find latest node that covers the start of the change
while(node != null && start == null) {
if (node instanceof CompositeNode) {
if (((CompositeNode) node).getChildren().isEmpty())
break;
for(AbstractNode child: ((CompositeNode) node).getChildren()) {
if (child.getTotalOffset() <= offset && child.getTotalOffset() + child.getTotalLength() >= offset) {
node = child;
if (node instanceof LeafNode || node.getTotalOffset() == offset)
start = node;
break;
}
}
} else {
throw new IllegalStateException("node is not in expected range but is not a composite.");
}
}
// search up to the first, deepest node, that covers the end
node = start;
while(node != null && end == null) {
if (node.getTotalLength() + node.getTotalOffset() >= endOffset) {
+ if ((node instanceof CompositeNode) && ((CompositeNode) node).getChildren().isEmpty())
+ break;
while(end == null) {
if (node instanceof CompositeNode) {
- if (((CompositeNode) node).getChildren().isEmpty())
- break;
for(int i = ((CompositeNode) node).getChildren().size() - 1; i >= 0; i--) {
AbstractNode child = ((CompositeNode) node).getChildren().get(i);
if (child.getTotalOffset() + child.getTotalLength() >= endOffset && child.getTotalOffset() <= endOffset) {
node = child;
if (node instanceof LeafNode || node.getTotalOffset() + node.getTotalLength() == endOffset)
end = node;
break;
}
}
} else {
end = node;
}
}
} else {
node = node.getParent();
}
}
// include region with syntax errors
int startOffset = start != null ? start.getTotalOffset() : offset;
int endOffset = end != null ? end.getTotalOffset() + end.getTotalLength() : this.endOffset;
Range range = new Range(startOffset, endOffset);
range.mergeAllErrors(resource.getParseResult().getRootNode());
// cover the difference between inserted text and removed text
return new Region(range.getFromOffset(), range.getToOffset() - range.getFromOffset() + e.getText().length() - e.getLength());
}
});
return result;
}
}
| false | true | public IRegion getDamageRegion(ITypedRegion partition, final DocumentEvent e, boolean documentPartitioningChanged) {
if (documentPartitioningChanged)
return partition;
IRegion result = getDocument().readOnly(new UnitOfWork<IRegion>(){
private final int offset = e.getOffset();
private final int endOffset = offset + e.getLength();
public IRegion exec(XtextResource resource) throws Exception {
AbstractNode node = resource.getParseResult().getRootNode();
AbstractNode start = null;
AbstractNode end = null;
// find latest node that covers the start of the change
while(node != null && start == null) {
if (node instanceof CompositeNode) {
if (((CompositeNode) node).getChildren().isEmpty())
break;
for(AbstractNode child: ((CompositeNode) node).getChildren()) {
if (child.getTotalOffset() <= offset && child.getTotalOffset() + child.getTotalLength() >= offset) {
node = child;
if (node instanceof LeafNode || node.getTotalOffset() == offset)
start = node;
break;
}
}
} else {
throw new IllegalStateException("node is not in expected range but is not a composite.");
}
}
// search up to the first, deepest node, that covers the end
node = start;
while(node != null && end == null) {
if (node.getTotalLength() + node.getTotalOffset() >= endOffset) {
while(end == null) {
if (node instanceof CompositeNode) {
if (((CompositeNode) node).getChildren().isEmpty())
break;
for(int i = ((CompositeNode) node).getChildren().size() - 1; i >= 0; i--) {
AbstractNode child = ((CompositeNode) node).getChildren().get(i);
if (child.getTotalOffset() + child.getTotalLength() >= endOffset && child.getTotalOffset() <= endOffset) {
node = child;
if (node instanceof LeafNode || node.getTotalOffset() + node.getTotalLength() == endOffset)
end = node;
break;
}
}
} else {
end = node;
}
}
} else {
node = node.getParent();
}
}
// include region with syntax errors
int startOffset = start != null ? start.getTotalOffset() : offset;
int endOffset = end != null ? end.getTotalOffset() + end.getTotalLength() : this.endOffset;
Range range = new Range(startOffset, endOffset);
range.mergeAllErrors(resource.getParseResult().getRootNode());
// cover the difference between inserted text and removed text
return new Region(range.getFromOffset(), range.getToOffset() - range.getFromOffset() + e.getText().length() - e.getLength());
}
});
return result;
}
| public IRegion getDamageRegion(ITypedRegion partition, final DocumentEvent e, boolean documentPartitioningChanged) {
if (documentPartitioningChanged)
return partition;
IRegion result = getDocument().readOnly(new UnitOfWork<IRegion>(){
private final int offset = e.getOffset();
private final int endOffset = offset + e.getLength();
public IRegion exec(XtextResource resource) throws Exception {
AbstractNode node = resource.getParseResult().getRootNode();
AbstractNode start = null;
AbstractNode end = null;
// find latest node that covers the start of the change
while(node != null && start == null) {
if (node instanceof CompositeNode) {
if (((CompositeNode) node).getChildren().isEmpty())
break;
for(AbstractNode child: ((CompositeNode) node).getChildren()) {
if (child.getTotalOffset() <= offset && child.getTotalOffset() + child.getTotalLength() >= offset) {
node = child;
if (node instanceof LeafNode || node.getTotalOffset() == offset)
start = node;
break;
}
}
} else {
throw new IllegalStateException("node is not in expected range but is not a composite.");
}
}
// search up to the first, deepest node, that covers the end
node = start;
while(node != null && end == null) {
if (node.getTotalLength() + node.getTotalOffset() >= endOffset) {
if ((node instanceof CompositeNode) && ((CompositeNode) node).getChildren().isEmpty())
break;
while(end == null) {
if (node instanceof CompositeNode) {
for(int i = ((CompositeNode) node).getChildren().size() - 1; i >= 0; i--) {
AbstractNode child = ((CompositeNode) node).getChildren().get(i);
if (child.getTotalOffset() + child.getTotalLength() >= endOffset && child.getTotalOffset() <= endOffset) {
node = child;
if (node instanceof LeafNode || node.getTotalOffset() + node.getTotalLength() == endOffset)
end = node;
break;
}
}
} else {
end = node;
}
}
} else {
node = node.getParent();
}
}
// include region with syntax errors
int startOffset = start != null ? start.getTotalOffset() : offset;
int endOffset = end != null ? end.getTotalOffset() + end.getTotalLength() : this.endOffset;
Range range = new Range(startOffset, endOffset);
range.mergeAllErrors(resource.getParseResult().getRootNode());
// cover the difference between inserted text and removed text
return new Region(range.getFromOffset(), range.getToOffset() - range.getFromOffset() + e.getText().length() - e.getLength());
}
});
return result;
}
|
diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/StructuredTextViewer.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/StructuredTextViewer.java
index d9ba00685..1976f6d7a 100644
--- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/StructuredTextViewer.java
+++ b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/StructuredTextViewer.java
@@ -1,951 +1,953 @@
/*******************************************************************************
* Copyright (c) 2001, 2010 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Jens Lukowski/Innoopract - initial renaming/restructuring
*
*******************************************************************************/
package org.eclipse.wst.sse.ui.internal;
import java.util.ArrayList;
import org.eclipse.core.runtime.Assert;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DocumentRewriteSession;
import org.eclipse.jface.text.DocumentRewriteSessionType;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentAdapter;
import org.eclipse.jface.text.IDocumentExtension4;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextPresentationListener;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.ITextViewerExtension2;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.text.contentassist.IContentAssistant;
import org.eclipse.jface.text.formatter.FormattingContext;
import org.eclipse.jface.text.formatter.FormattingContextProperties;
import org.eclipse.jface.text.formatter.IContentFormatterExtension;
import org.eclipse.jface.text.formatter.IFormattingContext;
import org.eclipse.jface.text.hyperlink.IHyperlinkDetector;
import org.eclipse.jface.text.information.IInformationPresenter;
import org.eclipse.jface.text.projection.ProjectionDocument;
import org.eclipse.jface.text.quickassist.IQuickAssistAssistant;
import org.eclipse.jface.text.reconciler.IReconciler;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.jface.text.source.IOverviewRuler;
import org.eclipse.jface.text.source.IVerticalRuler;
import org.eclipse.jface.text.source.SourceViewerConfiguration;
import org.eclipse.jface.text.source.projection.ProjectionViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.wst.sse.core.internal.cleanup.StructuredContentCleanupHandler;
import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument;
import org.eclipse.wst.sse.core.internal.undo.IDocumentSelectionMediator;
import org.eclipse.wst.sse.core.internal.undo.IStructuredTextUndoManager;
import org.eclipse.wst.sse.core.internal.undo.UndoDocumentEvent;
import org.eclipse.wst.sse.ui.StructuredTextViewerConfiguration;
import org.eclipse.wst.sse.ui.internal.provisional.style.AbstractLineStyleProvider;
import org.eclipse.wst.sse.ui.internal.provisional.style.CompatibleHighlighter;
import org.eclipse.wst.sse.ui.internal.provisional.style.Highlighter;
import org.eclipse.wst.sse.ui.internal.provisional.style.LineStyleProvider;
import org.eclipse.wst.sse.ui.internal.provisional.style.ReconcilerHighlighter;
import org.eclipse.wst.sse.ui.internal.reconcile.StructuredRegionProcessor;
import org.eclipse.wst.sse.ui.internal.util.PlatformStatusLineUtil;
/**
* <p>
* Like {@link org.eclipse.wst.sse.ui.StructuredTextEditor}, this class is not
* meant to be subclassed.<br />
*/
public class StructuredTextViewer extends ProjectionViewer implements IDocumentSelectionMediator {
/** Text operation codes */
private static final int BASE = ProjectionViewer.COLLAPSE_ALL; // see
// ProjectionViewer.COLLAPSE_ALL
private static final int CLEANUP_DOCUMENT = BASE + 4;
public static final int FORMAT_ACTIVE_ELEMENTS = BASE + 3;
private static final String FORMAT_ACTIVE_ELEMENTS_TEXT = SSEUIMessages.Format_Active_Elements_UI_; //$NON-NLS-1$
public static final int FORMAT_DOCUMENT = BASE + 2;
private static final String FORMAT_DOCUMENT_TEXT = SSEUIMessages.Format_Document_UI_; //$NON-NLS-1$
private static final String TEXT_CUT = SSEUIMessages.Text_Cut_UI_; //$NON-NLS-1$
private static final String TEXT_PASTE = SSEUIMessages.Text_Paste_UI_; //$NON-NLS-1$
private static final String TEXT_SHIFT_LEFT = SSEUIMessages.Text_Shift_Left_UI_; //$NON-NLS-1$ = "Text Shift Left"
private static final String TEXT_SHIFT_RIGHT = SSEUIMessages.Text_Shift_Right_UI_; //$NON-NLS-1$ = "Text Shift Right"
private static final boolean TRACE_EXCEPTIONS = true;
/*
* Max length of chars to format before it is considered a "big format"
* This is used to indication a small unrestricted rewrite session.
*/
private final int MAX_SMALL_FORMAT_LENGTH = 1000;
private boolean fBackgroundupdateInProgress;
private StructuredContentCleanupHandler fContentCleanupHandler = null;
//private IDocumentAdapter fDocAdapter;
private Highlighter fHighlighter;
private ReconcilerHighlighter fRecHighlighter = null;
// private ViewerSelectionManager fViewerSelectionManager;
private SourceViewerConfiguration fConfiguration;
/*
* True if formatter has been set
*/
private boolean fFormatterSet = false;
/**
* @see org.eclipse.jface.text.source.SourceViewer#SourceViewer(Composite,
* IVerticalRuler, IOverviewRuler, boolean, int)
*/
public StructuredTextViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, boolean showAnnotationsOverview, int styles) {
super(parent, verticalRuler, overviewRuler, showAnnotationsOverview, styles);
}
/**
*
*/
private void beep() {
getTextWidget().getDisplay().beep();
}
public void beginBackgroundUpdate() {
fBackgroundupdateInProgress = true;
setRedraw(false);
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.text.ITextOperationTarget#canDoOperation(int)
*/
public boolean canDoOperation(int operation) {
if (fBackgroundupdateInProgress) {
return false;
}
switch (operation) {
case CONTENTASSIST_PROPOSALS : {
// (pa) if position isn't READ_ONLY (containsReadOnly()
// returns false),
// Otherwise, you DO want content assist (return true)
IDocument doc = getDocument();
if (doc != null && doc instanceof IStructuredDocument) {
return isEditable() && (!((IStructuredDocument) doc).containsReadOnly(getSelectedRange().x, 0));
}
break;
}
case CLEANUP_DOCUMENT : {
return (fContentCleanupHandler != null && isEditable());
}
case FORMAT_DOCUMENT :
case FORMAT_ACTIVE_ELEMENTS : {
// if formatter not set yet, contentformatter can be null
return ((fContentFormatter != null || !fFormatterSet) && isEditable());
}
}
return super.canDoOperation(operation);
}
/**
* Should be identical to superclass version. Plus, we get our own special
* Highlighter. Plus we uninstall before installing.
*/
public void configure(SourceViewerConfiguration configuration) {
if (getTextWidget() == null)
return;
setDocumentPartitioning(configuration.getConfiguredDocumentPartitioning(this));
// always uninstall highlighter and null it out on new configuration
if (fHighlighter != null) {
fHighlighter.uninstall();
fHighlighter = null;
}
if(fRecHighlighter != null) {
fRecHighlighter.uninstall();
fRecHighlighter = null;
}
// Bug 230297 - Uninstall presentation reconciler in preparation of a new one
if(fPresentationReconciler != null) {
fPresentationReconciler.uninstall();
fPresentationReconciler = null;
}
IReconciler newReconciler = configuration.getReconciler(this);
if (newReconciler != fReconciler || newReconciler == null || fReconciler == null) {
if (fReconciler != null) {
fReconciler.uninstall();
}
fReconciler = newReconciler;
if (fReconciler != null) {
fReconciler.install(this);
// https://w3.opensource.ibm.com/bugzilla/show_bug.cgi?id=3858
// still need set document on the reconciler (strategies)
if (fReconciler instanceof StructuredRegionProcessor)
((StructuredRegionProcessor) fReconciler).setDocument(getDocument());
}
}
IContentAssistant newAssistant = configuration.getContentAssistant(this);
if (newAssistant != fContentAssistant || newAssistant == null || fContentAssistant == null) {
if (fContentAssistant != null)
fContentAssistant.uninstall();
fContentAssistant = newAssistant;
if (fContentAssistant != null) {
fContentAssistant.install(this);
fContentAssistantInstalled = true;
}
else {
// 248036
// disable the content assist operation if no content
// assistant
enableOperation(CONTENTASSIST_PROPOSALS, false);
+ fContentAssistantInstalled = false;
}
}
IQuickAssistAssistant quickAssistant = configuration.getQuickAssistAssistant(this);
if (quickAssistant != fQuickAssistAssistant || quickAssistant == null || fQuickAssistAssistant == null) {
if (fQuickAssistAssistant != null)
fQuickAssistAssistant.uninstall();
fQuickAssistAssistant = quickAssistant;
if (fQuickAssistAssistant != null) {
fQuickAssistAssistant.install(this);
fQuickAssistAssistantInstalled = true;
}
else {
// 248036
// disable the content assist operation if no content
// assistant
enableOperation(QUICK_ASSIST, false);
+ fQuickAssistAssistantInstalled = false;
}
}
fContentFormatter = configuration.getContentFormatter(this);
// do not uninstall old information presenter if it's the same
IInformationPresenter newInformationPresenter = configuration.getInformationPresenter(this);
if (newInformationPresenter == null || fInformationPresenter == null || !(newInformationPresenter.equals(fInformationPresenter))) {
if (fInformationPresenter != null)
fInformationPresenter.uninstall();
fInformationPresenter = newInformationPresenter;
if (fInformationPresenter != null)
fInformationPresenter.install(this);
}
// disconnect from the old undo manager before setting the new one
if (fUndoManager != null) {
fUndoManager.disconnect();
}
setUndoManager(configuration.getUndoManager(this));
// release old annotation hover before setting new one
if (fAnnotationHover instanceof StructuredTextAnnotationHover) {
((StructuredTextAnnotationHover) fAnnotationHover).release();
}
setAnnotationHover(configuration.getAnnotationHover(this));
// release old annotation hover before setting new one
if (fOverviewRulerAnnotationHover instanceof StructuredTextAnnotationHover) {
((StructuredTextAnnotationHover) fOverviewRulerAnnotationHover).release();
}
setOverviewRulerAnnotationHover(configuration.getOverviewRulerAnnotationHover(this));
getTextWidget().setTabs(configuration.getTabWidth(this));
setHoverControlCreator(configuration.getInformationControlCreator(this));
// if hyperlink manager has already been created, uninstall it
if (fHyperlinkManager != null) {
setHyperlinkDetectors(null, SWT.NONE);
}
setHyperlinkPresenter(configuration.getHyperlinkPresenter(this));
IHyperlinkDetector[] hyperlinkDetectors = configuration.getHyperlinkDetectors(this);
int eventStateMask = configuration.getHyperlinkStateMask(this);
setHyperlinkDetectors(hyperlinkDetectors, eventStateMask);
String[] types = configuration.getConfiguredContentTypes(this);
// clear autoindent/autoedit strategies
fAutoIndentStrategies = null;
for (int i = 0; i < types.length; i++) {
String t = types[i];
setAutoEditStrategies(configuration.getAutoEditStrategies(this, t), t);
setTextDoubleClickStrategy(configuration.getDoubleClickStrategy(this, t), t);
int[] stateMasks = configuration.getConfiguredTextHoverStateMasks(this, t);
if (stateMasks != null) {
for (int j = 0; j < stateMasks.length; j++) {
int stateMask = stateMasks[j];
setTextHover(configuration.getTextHover(this, t, stateMask), t, stateMask);
}
}
else {
setTextHover(configuration.getTextHover(this, t), t, ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK);
}
String[] prefixes = configuration.getIndentPrefixes(this, t);
if (prefixes != null && prefixes.length > 0)
setIndentPrefixes(prefixes, t);
prefixes = configuration.getDefaultPrefixes(this, t);
if (prefixes != null && prefixes.length > 0)
setDefaultPrefixes(prefixes, t);
// Bug 230297 - Add LineStyleProviders from the new configuration if
// the document is set
if(getDocument() != null) {
// add highlighter/linestyleprovider
LineStyleProvider[] providers = ((StructuredTextViewerConfiguration) configuration).getLineStyleProviders(this, t);
if (providers != null) {
for (int j = 0; j < providers.length; ++j) {
if(fRecHighlighter == null) {
fRecHighlighter = new ReconcilerHighlighter();
((StructuredTextViewerConfiguration) configuration).setHighlighter(fRecHighlighter);
}
if (providers[j] instanceof AbstractLineStyleProvider) {
((AbstractLineStyleProvider) providers[j]).init((IStructuredDocument) getDocument(), fRecHighlighter);
fRecHighlighter.addProvider(t, providers[j]);
}
else {
// init with compatibility instance
if (fHighlighter == null) {
fHighlighter = new CompatibleHighlighter();
}
Logger.log(Logger.INFO_DEBUG, "CompatibleHighlighter installing compatibility for " + providers[j].getClass()); //$NON-NLS-1$
providers[j].init((IStructuredDocument) getDocument(), fHighlighter);
fHighlighter.addProvider(t, providers[j]);
}
}
}
}
}
// initialize highlighter after linestyleproviders were added
if (fHighlighter != null) {
fHighlighter.setDocumentPartitioning(configuration.getConfiguredDocumentPartitioning(this));
fHighlighter.setDocument((IStructuredDocument) getDocument());
fHighlighter.install(this);
}
if (fRecHighlighter != null)
fRecHighlighter.install(this);
activatePlugins();
fConfiguration = configuration;
// Update the viewer's presentation reconciler
fPresentationReconciler = configuration.getPresentationReconciler(this);
if(fPresentationReconciler != null)
fPresentationReconciler.install(this);
}
/**
* @param document
* @param startOffset
* @param endOffset
* @return
*/
private boolean containsReadOnly(IDocument document, int startOffset, int endOffset) {
int start = startOffset;
int end = endOffset;
IStructuredDocument structuredDocument = null;
if (document instanceof IStructuredDocument) {
structuredDocument = (IStructuredDocument) document;
}
else {
if (document instanceof ProjectionDocument) {
IDocument doc = ((ProjectionDocument) document).getMasterDocument();
if (doc instanceof IStructuredDocument) {
structuredDocument = (IStructuredDocument) doc;
int adjust = ((ProjectionDocument) document).getProjectionMapping().getCoverage().getOffset();
start = adjust + start;
end = adjust + end;
}
}
}
if (structuredDocument == null) {
return false;
}
else {
int length = end - start;
return structuredDocument.containsReadOnly(start, length);
}
}
/**
* @deprecated - present for compatibility only
*/
protected IDocumentAdapter createDocumentAdapter() {
return super.createDocumentAdapter();
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.text.ITextOperationTarget#doOperation(int)
*/
public void doOperation(int operation) {
Point selection = getTextWidget().getSelection();
int cursorPosition = selection.x;
int selectionLength = selection.y - selection.x;
switch (operation) {
case CUT :
beginRecording(TEXT_CUT, TEXT_CUT, cursorPosition, selectionLength);
super.doOperation(operation);
selection = getTextWidget().getSelection();
cursorPosition = selection.x;
selectionLength = selection.y - selection.x;
endRecording(cursorPosition, selectionLength);
break;
case PASTE :
beginRecording(TEXT_PASTE, TEXT_PASTE, cursorPosition, selectionLength);
super.doOperation(operation);
selection = getTextWidget().getSelection();
cursorPosition = selection.x;
selectionLength = selection.y - selection.x;
endRecording(cursorPosition, selectionLength);
break;
case CONTENTASSIST_PROPOSALS :
// maybe not configured?
if (fContentAssistant != null && isEditable()) {
// CMVC 263269
// need an explicit check here because the
// contentAssistAction is no longer being updated on
// cursor
// position
if (canDoOperation(CONTENTASSIST_PROPOSALS)) {
String err = fContentAssistant.showPossibleCompletions();
if (err != null) {
// don't wanna beep if there is no error
PlatformStatusLineUtil.displayTemporaryErrorMessage(this, err);
}
}
else
beep();
}
break;
case CONTENTASSIST_CONTEXT_INFORMATION :
if (fContentAssistant != null) {
String err = fContentAssistant.showContextInformation();
if (err != null) {
// don't wanna beep if there is no error
PlatformStatusLineUtil.displayTemporaryErrorMessage(this, err);
}
}
break;
case SHIFT_RIGHT :
beginRecording(TEXT_SHIFT_RIGHT, TEXT_SHIFT_RIGHT, cursorPosition, selectionLength);
updateIndentationPrefixes();
super.doOperation(SHIFT_RIGHT);
selection = getTextWidget().getSelection();
cursorPosition = selection.x;
selectionLength = selection.y - selection.x;
endRecording(cursorPosition, selectionLength);
break;
case SHIFT_LEFT :
beginRecording(TEXT_SHIFT_LEFT, TEXT_SHIFT_LEFT, cursorPosition, selectionLength);
updateIndentationPrefixes();
super.doOperation(SHIFT_LEFT);
selection = getTextWidget().getSelection();
cursorPosition = selection.x;
selectionLength = selection.y - selection.x;
endRecording(cursorPosition, selectionLength);
break;
case FORMAT_DOCUMENT :
DocumentRewriteSession rewriteSession = null;
IDocument document = getDocument();
try {
/*
* This command will actually format selection if text is
* selected, otherwise format entire document
*/
// begin recording
beginRecording(FORMAT_DOCUMENT_TEXT, FORMAT_DOCUMENT_TEXT, cursorPosition, selectionLength);
boolean formatDocument = false;
IRegion region = null;
Point s = getSelectedRange();
if (s.y > 0) {
// only format currently selected text
region = new Region(s.x, s.y);
}
else {
// no selection, so format entire document
region = getModelCoverage();
formatDocument = true;
}
if (document instanceof IDocumentExtension4) {
IDocumentExtension4 extension = (IDocumentExtension4) document;
DocumentRewriteSessionType type = (selection.y == 0 || selection.y > MAX_SMALL_FORMAT_LENGTH) ? DocumentRewriteSessionType.UNRESTRICTED : DocumentRewriteSessionType.UNRESTRICTED_SMALL;
rewriteSession = (extension.getActiveRewriteSession() != null) ? null : extension.startRewriteSession(type);
}
else {
setRedraw(false);
}
if (fContentFormatter instanceof IContentFormatterExtension) {
IContentFormatterExtension extension = (IContentFormatterExtension) fContentFormatter;
IFormattingContext context = new FormattingContext();
context.setProperty(FormattingContextProperties.CONTEXT_DOCUMENT, Boolean.valueOf(formatDocument));
context.setProperty(FormattingContextProperties.CONTEXT_REGION, region);
extension.format(document, context);
}
else {
fContentFormatter.format(document, region);
}
}
finally {
try {
if (rewriteSession != null) {
IDocumentExtension4 extension = (IDocumentExtension4) document;
extension.stopRewriteSession(rewriteSession);
}
else {
setRedraw(true);
}
}
finally {
// end recording
selection = getTextWidget().getSelection();
cursorPosition = selection.x;
selectionLength = selection.y - selection.x;
endRecording(cursorPosition, selectionLength);
}
}
break;
case FORMAT_ACTIVE_ELEMENTS :
rewriteSession = null;
document = getDocument();
try {
/*
* This command will format the node at cursor position
* (and all its children)
*/
// begin recording
beginRecording(FORMAT_ACTIVE_ELEMENTS_TEXT, FORMAT_ACTIVE_ELEMENTS_TEXT, cursorPosition, selectionLength);
IRegion region = null;
Point s = getSelectedRange();
if (s.y > -1) {
// only format node at cursor position
region = new Region(s.x, s.y);
}
if (document instanceof IDocumentExtension4) {
IDocumentExtension4 extension = (IDocumentExtension4) document;
DocumentRewriteSessionType type = (selection.y == 0 || selection.y > MAX_SMALL_FORMAT_LENGTH) ? DocumentRewriteSessionType.UNRESTRICTED : DocumentRewriteSessionType.UNRESTRICTED_SMALL;
rewriteSession = (extension.getActiveRewriteSession() != null) ? null : extension.startRewriteSession(type);
}
else {
setRedraw(false);
}
if (fContentFormatter instanceof IContentFormatterExtension) {
IContentFormatterExtension extension = (IContentFormatterExtension) fContentFormatter;
IFormattingContext context = new FormattingContext();
context.setProperty(FormattingContextProperties.CONTEXT_DOCUMENT, Boolean.FALSE);
context.setProperty(FormattingContextProperties.CONTEXT_REGION, region);
extension.format(getDocument(), context);
}
else {
fContentFormatter.format(getDocument(), region);
}
}
finally {
try {
if (rewriteSession != null) {
IDocumentExtension4 extension = (IDocumentExtension4) document;
extension.stopRewriteSession(rewriteSession);
}
else {
setRedraw(true);
}
}
finally {
// end recording
selection = getTextWidget().getSelection();
cursorPosition = selection.x;
selectionLength = selection.y - selection.x;
endRecording(cursorPosition, selectionLength);
}
}
break;
default :
super.doOperation(operation);
}
}
private void endRecording(int cursorPosition, int selectionLength) {
IDocument doc = getDocument();
if (doc instanceof IStructuredDocument) {
IStructuredDocument structuredDocument = (IStructuredDocument) doc;
IStructuredTextUndoManager undoManager = structuredDocument.getUndoManager();
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=198617
// undo after paste in document with folds - wrong behavior
IRegion widgetSelection = new Region(cursorPosition, selectionLength);
IRegion documentSelection = widgetRange2ModelRange(widgetSelection);
if (documentSelection == null)
documentSelection = widgetSelection;
undoManager.endRecording(this, documentSelection.getOffset(), documentSelection.getLength());
}
else {
// TODO: how to handle other document types?
}
}
private void beginRecording(String label, String description, int cursorPosition, int selectionLength) {
IDocument doc = getDocument();
if (doc instanceof IStructuredDocument) {
IStructuredDocument structuredDocument = (IStructuredDocument) doc;
IStructuredTextUndoManager undoManager = structuredDocument.getUndoManager();
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=198617
// undo after paste in document with folds - wrong behavior
IRegion widgetSelection = new Region(cursorPosition, selectionLength);
IRegion documentSelection = widgetRange2ModelRange(widgetSelection);
if (documentSelection == null)
documentSelection = widgetSelection;
undoManager.beginRecording(this, label, description, documentSelection.getOffset(), documentSelection.getLength());
}
else {
// TODO: how to handle other document types?
}
}
public void endBackgroundUpdate() {
fBackgroundupdateInProgress = false;
setRedraw(true);
}
protected void handleDispose() {
Logger.trace("Source Editor", "StructuredTextViewer::handleDispose entry"); //$NON-NLS-1$ //$NON-NLS-2$
// before we dispose, we set a special "empty" selection, to prevent
// the "leak one document" that
// otherwise occurs when editor closed (since last selection stays in
// SelectedResourceManager.
// the occurance of the "leak" isn't so bad, but makes debugging other
// leaks very hard.
setSelection(TextSelection.emptySelection());
if (fHighlighter != null) {
fHighlighter.uninstall();
fHighlighter = null;
}
if (fRecHighlighter != null) {
fRecHighlighter.uninstall();
fRecHighlighter = null;
}
super.handleDispose();
Logger.trace("Source Editor", "StructuredTextViewer::handleDispose exit"); //$NON-NLS-1$ //$NON-NLS-2$
}
/*
* Overridden for special support of background update and read-only
* regions
*/
protected void handleVerifyEvent(VerifyEvent e) {
IRegion modelRange = event2ModelRange(e);
if (exposeModelRange(modelRange)) {
e.doit = false;
return;
}
if (fEventConsumer != null) {
fEventConsumer.processEvent(e);
if (!e.doit)
return;
}
if (fBackgroundupdateInProgress) {
e.doit = false;
beep();
return;
}
// for read-only support
if (containsReadOnly(getVisibleDocument(), e.start, e.end)) {
e.doit = false;
beep();
return;
}
try {
super.handleVerifyEvent(e);
}
catch (Exception x) {
/*
* Note, we catch and log any exception, since an otherwise can
* actually prevent typing! see
* https://bugs.eclipse.org/bugs/show_bug.cgi?id=111318
*/
if (TRACE_EXCEPTIONS)
Logger.logException("StructuredTextViewer.exception.verifyText", x); //$NON-NLS-1$
}
}
public int modelLine2WidgetLine(int modelLine) {
/**
* need to override this method as a workaround for Bug 85709
*/
if (fInformationMapping == null) {
IDocument document = getDocument();
if (document != null) {
try {
IRegion modelLineRegion = getDocument().getLineInformation(modelLine);
IRegion region = getModelCoverage();
if (modelLineRegion != null && region != null) {
int modelEnd = modelLineRegion.getOffset() + modelLineRegion.getLength();
int regionEnd = region.getOffset() + region.getLength();
// returns -1 if modelLine is invalid
if ((modelLineRegion.getOffset() < region.getOffset()) || (modelEnd > regionEnd))
return -1;
}
}
catch (BadLocationException e) {
// returns -1 if modelLine is invalid
return -1;
}
}
}
return super.modelLine2WidgetLine(modelLine);
}
public int modelOffset2WidgetOffset(int modelOffset) {
/**
* need to override this method as a workaround for Bug 85709
*/
if (fInformationMapping == null) {
IRegion region = getModelCoverage();
if (region != null) {
// returns -1 if modelOffset is invalid
if (modelOffset < region.getOffset() || modelOffset > (region.getOffset() + region.getLength()))
return -1;
}
}
return super.modelOffset2WidgetOffset(modelOffset);
}
public IRegion modelRange2WidgetRange(IRegion modelRange) {
// need to override this method as workaround for Bug85709
if (fInformationMapping == null) {
IRegion region = getModelCoverage();
if (region != null && modelRange != null) {
int modelEnd = modelRange.getOffset() + modelRange.getLength();
int regionEnd = region.getOffset() + region.getLength();
// returns null if modelRange is invalid
if ((modelRange.getOffset() < region.getOffset()) || (modelEnd > regionEnd))
return null;
}
}
return super.modelRange2WidgetRange(modelRange);
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.text.source.ISourceViewer#setDocument(org.eclipse.jface.text.IDocument,
* org.eclipse.jface.text.source.IAnnotationModel, int, int)
*/
public void setDocument(IDocument document, IAnnotationModel annotationModel, int modelRangeOffset, int modelRangeLength) {
// partial fix for:
// https://w3.opensource.ibm.com/bugzilla/show_bug.cgi?id=1970
// when our document is set, especially to null during close,
// immediately uninstall the reconciler.
// this is to avoid an unnecessary final "reconcile"
// that blocks display thread
if (document == null) {
if (fReconciler != null) {
fReconciler.uninstall();
}
}
super.setDocument(document, annotationModel, modelRangeOffset, modelRangeLength);
if (document instanceof IStructuredDocument) {
IStructuredDocument structuredDocument = (IStructuredDocument) document;
// notify highlighter
updateHighlighter(structuredDocument);
// set the formatter again now that document has been set
if (!fFormatterSet && fConfiguration != null) {
fContentFormatter = fConfiguration.getContentFormatter(this);
fFormatterSet = true;
}
// set document in the viewer-based undo manager
if (fUndoManager != null) {
fUndoManager.disconnect();
fUndoManager.connect(this);
}
// CaretEvent is not sent to ViewerSelectionManager after Save As.
// Need to notify ViewerSelectionManager here.
// notifyViewerSelectionManager(getSelectedRange().x,
// getSelectedRange().y);
}
}
/**
* Uninstalls anything that was installed by configure
*/
public void unconfigure() {
Logger.trace("Source Editor", "StructuredTextViewer::unconfigure entry"); //$NON-NLS-1$ //$NON-NLS-2$
if (fHighlighter != null) {
fHighlighter.uninstall();
fHighlighter = null;
}
if (fRecHighlighter != null) {
fRecHighlighter.uninstall();
fRecHighlighter = null;
}
if (fAnnotationHover instanceof StructuredTextAnnotationHover) {
((StructuredTextAnnotationHover) fAnnotationHover).release();
}
if (fOverviewRulerAnnotationHover instanceof StructuredTextAnnotationHover) {
((StructuredTextAnnotationHover) fOverviewRulerAnnotationHover).release();
}
super.unconfigure();
fConfiguration = null;
Logger.trace("Source Editor", "StructuredTextViewer::unconfigure exit"); //$NON-NLS-1$ //$NON-NLS-2$
}
/*
* (non-Javadoc)
*
* @see org.eclipse.wst.sse.core.undo.IDocumentSelectionMediator#undoOperationSelectionChanged(org.eclipse.wst.sse.core.undo.UndoDocumentEvent)
*/
public void undoOperationSelectionChanged(UndoDocumentEvent event) {
if (event.getRequester() != null && event.getRequester().equals(this) && event.getDocument().equals(getDocument())) {
// BUG107687: Undo/redo do not scroll editor
ITextSelection selection = new TextSelection(event.getOffset(), event.getLength());
setSelection(selection, true);
}
}
private void updateHighlighter(IStructuredDocument document) {
boolean documentSet = false;
// if highlighter has not been created yet, initialize and install it
if (fRecHighlighter == null && fConfiguration instanceof StructuredTextViewerConfiguration) {
String[] types = fConfiguration.getConfiguredContentTypes(this);
for (int i = 0; i < types.length; i++) {
String t = types[i];
// add highlighter/linestyleprovider
LineStyleProvider[] providers = ((StructuredTextViewerConfiguration) fConfiguration).getLineStyleProviders(this, t);
if (providers != null) {
for (int j = 0; j < providers.length; ++j) {
if(fRecHighlighter == null) {
fRecHighlighter = new ReconcilerHighlighter();
((StructuredTextViewerConfiguration) fConfiguration).setHighlighter(fRecHighlighter);
}
if (providers[j] instanceof AbstractLineStyleProvider) {
((AbstractLineStyleProvider) providers[j]).init(document, fRecHighlighter);
fRecHighlighter.addProvider(t, providers[j]);
}
else {
// init with compatibility instance
if (fHighlighter == null) {
fHighlighter = new CompatibleHighlighter();
}
Logger.log(Logger.INFO_DEBUG, "CompatibleHighlighter installing compatibility for " + providers[j].getClass()); //$NON-NLS-1$
providers[j].init(document, fHighlighter);
fHighlighter.addProvider(t, providers[j]);
}
}
}
}
if(fRecHighlighter != null)
fRecHighlighter.install(this);
if(fHighlighter != null) {
fHighlighter.setDocumentPartitioning(fConfiguration.getConfiguredDocumentPartitioning(this));
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=203347
// make sure to set document before install
fHighlighter.setDocument(document);
fHighlighter.install(this);
documentSet = true;
}
}
if (fHighlighter != null && !documentSet)
fHighlighter.setDocument(document);
// install content type independent plugins
if (fPresentationReconciler != null)
fPresentationReconciler.uninstall();
// 228847 - XSL Content Assist tests fail with Null Pointer on Highlighter
if(fConfiguration != null)
fPresentationReconciler = fConfiguration.getPresentationReconciler(this);
if (fPresentationReconciler != null)
fPresentationReconciler.install(this);
}
/**
* Make sure indentation is correct before using.
*/
private void updateIndentationPrefixes() {
SourceViewerConfiguration configuration = fConfiguration;
if (fConfiguration != null) {
String[] types = configuration.getConfiguredContentTypes(this);
for (int i = 0; i < types.length; i++) {
String[] prefixes = configuration.getIndentPrefixes(this, types[i]);
if (prefixes != null && prefixes.length > 0)
setIndentPrefixes(prefixes, types[i]);
}
}
}
/**
* Prepends the text presentation listener at the beginning of the viewer's
* list of text presentation listeners. If the listener is already registered
* with the viewer this call moves the listener to the beginning of
* the list.
*
* @param listener the text presentation listener
* @since 3.1
*/
public void prependTextPresentationListener(ITextPresentationListener listener) {
Assert.isNotNull(listener);
if (fTextPresentationListeners == null)
fTextPresentationListeners= new ArrayList();
fTextPresentationListeners.remove(listener);
fTextPresentationListeners.add(0, listener);
}
}
| false | true | public void configure(SourceViewerConfiguration configuration) {
if (getTextWidget() == null)
return;
setDocumentPartitioning(configuration.getConfiguredDocumentPartitioning(this));
// always uninstall highlighter and null it out on new configuration
if (fHighlighter != null) {
fHighlighter.uninstall();
fHighlighter = null;
}
if(fRecHighlighter != null) {
fRecHighlighter.uninstall();
fRecHighlighter = null;
}
// Bug 230297 - Uninstall presentation reconciler in preparation of a new one
if(fPresentationReconciler != null) {
fPresentationReconciler.uninstall();
fPresentationReconciler = null;
}
IReconciler newReconciler = configuration.getReconciler(this);
if (newReconciler != fReconciler || newReconciler == null || fReconciler == null) {
if (fReconciler != null) {
fReconciler.uninstall();
}
fReconciler = newReconciler;
if (fReconciler != null) {
fReconciler.install(this);
// https://w3.opensource.ibm.com/bugzilla/show_bug.cgi?id=3858
// still need set document on the reconciler (strategies)
if (fReconciler instanceof StructuredRegionProcessor)
((StructuredRegionProcessor) fReconciler).setDocument(getDocument());
}
}
IContentAssistant newAssistant = configuration.getContentAssistant(this);
if (newAssistant != fContentAssistant || newAssistant == null || fContentAssistant == null) {
if (fContentAssistant != null)
fContentAssistant.uninstall();
fContentAssistant = newAssistant;
if (fContentAssistant != null) {
fContentAssistant.install(this);
fContentAssistantInstalled = true;
}
else {
// 248036
// disable the content assist operation if no content
// assistant
enableOperation(CONTENTASSIST_PROPOSALS, false);
}
}
IQuickAssistAssistant quickAssistant = configuration.getQuickAssistAssistant(this);
if (quickAssistant != fQuickAssistAssistant || quickAssistant == null || fQuickAssistAssistant == null) {
if (fQuickAssistAssistant != null)
fQuickAssistAssistant.uninstall();
fQuickAssistAssistant = quickAssistant;
if (fQuickAssistAssistant != null) {
fQuickAssistAssistant.install(this);
fQuickAssistAssistantInstalled = true;
}
else {
// 248036
// disable the content assist operation if no content
// assistant
enableOperation(QUICK_ASSIST, false);
}
}
fContentFormatter = configuration.getContentFormatter(this);
// do not uninstall old information presenter if it's the same
IInformationPresenter newInformationPresenter = configuration.getInformationPresenter(this);
if (newInformationPresenter == null || fInformationPresenter == null || !(newInformationPresenter.equals(fInformationPresenter))) {
if (fInformationPresenter != null)
fInformationPresenter.uninstall();
fInformationPresenter = newInformationPresenter;
if (fInformationPresenter != null)
fInformationPresenter.install(this);
}
// disconnect from the old undo manager before setting the new one
if (fUndoManager != null) {
fUndoManager.disconnect();
}
setUndoManager(configuration.getUndoManager(this));
// release old annotation hover before setting new one
if (fAnnotationHover instanceof StructuredTextAnnotationHover) {
((StructuredTextAnnotationHover) fAnnotationHover).release();
}
setAnnotationHover(configuration.getAnnotationHover(this));
// release old annotation hover before setting new one
if (fOverviewRulerAnnotationHover instanceof StructuredTextAnnotationHover) {
((StructuredTextAnnotationHover) fOverviewRulerAnnotationHover).release();
}
setOverviewRulerAnnotationHover(configuration.getOverviewRulerAnnotationHover(this));
getTextWidget().setTabs(configuration.getTabWidth(this));
setHoverControlCreator(configuration.getInformationControlCreator(this));
// if hyperlink manager has already been created, uninstall it
if (fHyperlinkManager != null) {
setHyperlinkDetectors(null, SWT.NONE);
}
setHyperlinkPresenter(configuration.getHyperlinkPresenter(this));
IHyperlinkDetector[] hyperlinkDetectors = configuration.getHyperlinkDetectors(this);
int eventStateMask = configuration.getHyperlinkStateMask(this);
setHyperlinkDetectors(hyperlinkDetectors, eventStateMask);
String[] types = configuration.getConfiguredContentTypes(this);
// clear autoindent/autoedit strategies
fAutoIndentStrategies = null;
for (int i = 0; i < types.length; i++) {
String t = types[i];
setAutoEditStrategies(configuration.getAutoEditStrategies(this, t), t);
setTextDoubleClickStrategy(configuration.getDoubleClickStrategy(this, t), t);
int[] stateMasks = configuration.getConfiguredTextHoverStateMasks(this, t);
if (stateMasks != null) {
for (int j = 0; j < stateMasks.length; j++) {
int stateMask = stateMasks[j];
setTextHover(configuration.getTextHover(this, t, stateMask), t, stateMask);
}
}
else {
setTextHover(configuration.getTextHover(this, t), t, ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK);
}
String[] prefixes = configuration.getIndentPrefixes(this, t);
if (prefixes != null && prefixes.length > 0)
setIndentPrefixes(prefixes, t);
prefixes = configuration.getDefaultPrefixes(this, t);
if (prefixes != null && prefixes.length > 0)
setDefaultPrefixes(prefixes, t);
// Bug 230297 - Add LineStyleProviders from the new configuration if
// the document is set
if(getDocument() != null) {
// add highlighter/linestyleprovider
LineStyleProvider[] providers = ((StructuredTextViewerConfiguration) configuration).getLineStyleProviders(this, t);
if (providers != null) {
for (int j = 0; j < providers.length; ++j) {
if(fRecHighlighter == null) {
fRecHighlighter = new ReconcilerHighlighter();
((StructuredTextViewerConfiguration) configuration).setHighlighter(fRecHighlighter);
}
if (providers[j] instanceof AbstractLineStyleProvider) {
((AbstractLineStyleProvider) providers[j]).init((IStructuredDocument) getDocument(), fRecHighlighter);
fRecHighlighter.addProvider(t, providers[j]);
}
else {
// init with compatibility instance
if (fHighlighter == null) {
fHighlighter = new CompatibleHighlighter();
}
Logger.log(Logger.INFO_DEBUG, "CompatibleHighlighter installing compatibility for " + providers[j].getClass()); //$NON-NLS-1$
providers[j].init((IStructuredDocument) getDocument(), fHighlighter);
fHighlighter.addProvider(t, providers[j]);
}
}
}
}
}
// initialize highlighter after linestyleproviders were added
if (fHighlighter != null) {
fHighlighter.setDocumentPartitioning(configuration.getConfiguredDocumentPartitioning(this));
fHighlighter.setDocument((IStructuredDocument) getDocument());
fHighlighter.install(this);
}
if (fRecHighlighter != null)
fRecHighlighter.install(this);
activatePlugins();
fConfiguration = configuration;
// Update the viewer's presentation reconciler
fPresentationReconciler = configuration.getPresentationReconciler(this);
if(fPresentationReconciler != null)
fPresentationReconciler.install(this);
}
| public void configure(SourceViewerConfiguration configuration) {
if (getTextWidget() == null)
return;
setDocumentPartitioning(configuration.getConfiguredDocumentPartitioning(this));
// always uninstall highlighter and null it out on new configuration
if (fHighlighter != null) {
fHighlighter.uninstall();
fHighlighter = null;
}
if(fRecHighlighter != null) {
fRecHighlighter.uninstall();
fRecHighlighter = null;
}
// Bug 230297 - Uninstall presentation reconciler in preparation of a new one
if(fPresentationReconciler != null) {
fPresentationReconciler.uninstall();
fPresentationReconciler = null;
}
IReconciler newReconciler = configuration.getReconciler(this);
if (newReconciler != fReconciler || newReconciler == null || fReconciler == null) {
if (fReconciler != null) {
fReconciler.uninstall();
}
fReconciler = newReconciler;
if (fReconciler != null) {
fReconciler.install(this);
// https://w3.opensource.ibm.com/bugzilla/show_bug.cgi?id=3858
// still need set document on the reconciler (strategies)
if (fReconciler instanceof StructuredRegionProcessor)
((StructuredRegionProcessor) fReconciler).setDocument(getDocument());
}
}
IContentAssistant newAssistant = configuration.getContentAssistant(this);
if (newAssistant != fContentAssistant || newAssistant == null || fContentAssistant == null) {
if (fContentAssistant != null)
fContentAssistant.uninstall();
fContentAssistant = newAssistant;
if (fContentAssistant != null) {
fContentAssistant.install(this);
fContentAssistantInstalled = true;
}
else {
// 248036
// disable the content assist operation if no content
// assistant
enableOperation(CONTENTASSIST_PROPOSALS, false);
fContentAssistantInstalled = false;
}
}
IQuickAssistAssistant quickAssistant = configuration.getQuickAssistAssistant(this);
if (quickAssistant != fQuickAssistAssistant || quickAssistant == null || fQuickAssistAssistant == null) {
if (fQuickAssistAssistant != null)
fQuickAssistAssistant.uninstall();
fQuickAssistAssistant = quickAssistant;
if (fQuickAssistAssistant != null) {
fQuickAssistAssistant.install(this);
fQuickAssistAssistantInstalled = true;
}
else {
// 248036
// disable the content assist operation if no content
// assistant
enableOperation(QUICK_ASSIST, false);
fQuickAssistAssistantInstalled = false;
}
}
fContentFormatter = configuration.getContentFormatter(this);
// do not uninstall old information presenter if it's the same
IInformationPresenter newInformationPresenter = configuration.getInformationPresenter(this);
if (newInformationPresenter == null || fInformationPresenter == null || !(newInformationPresenter.equals(fInformationPresenter))) {
if (fInformationPresenter != null)
fInformationPresenter.uninstall();
fInformationPresenter = newInformationPresenter;
if (fInformationPresenter != null)
fInformationPresenter.install(this);
}
// disconnect from the old undo manager before setting the new one
if (fUndoManager != null) {
fUndoManager.disconnect();
}
setUndoManager(configuration.getUndoManager(this));
// release old annotation hover before setting new one
if (fAnnotationHover instanceof StructuredTextAnnotationHover) {
((StructuredTextAnnotationHover) fAnnotationHover).release();
}
setAnnotationHover(configuration.getAnnotationHover(this));
// release old annotation hover before setting new one
if (fOverviewRulerAnnotationHover instanceof StructuredTextAnnotationHover) {
((StructuredTextAnnotationHover) fOverviewRulerAnnotationHover).release();
}
setOverviewRulerAnnotationHover(configuration.getOverviewRulerAnnotationHover(this));
getTextWidget().setTabs(configuration.getTabWidth(this));
setHoverControlCreator(configuration.getInformationControlCreator(this));
// if hyperlink manager has already been created, uninstall it
if (fHyperlinkManager != null) {
setHyperlinkDetectors(null, SWT.NONE);
}
setHyperlinkPresenter(configuration.getHyperlinkPresenter(this));
IHyperlinkDetector[] hyperlinkDetectors = configuration.getHyperlinkDetectors(this);
int eventStateMask = configuration.getHyperlinkStateMask(this);
setHyperlinkDetectors(hyperlinkDetectors, eventStateMask);
String[] types = configuration.getConfiguredContentTypes(this);
// clear autoindent/autoedit strategies
fAutoIndentStrategies = null;
for (int i = 0; i < types.length; i++) {
String t = types[i];
setAutoEditStrategies(configuration.getAutoEditStrategies(this, t), t);
setTextDoubleClickStrategy(configuration.getDoubleClickStrategy(this, t), t);
int[] stateMasks = configuration.getConfiguredTextHoverStateMasks(this, t);
if (stateMasks != null) {
for (int j = 0; j < stateMasks.length; j++) {
int stateMask = stateMasks[j];
setTextHover(configuration.getTextHover(this, t, stateMask), t, stateMask);
}
}
else {
setTextHover(configuration.getTextHover(this, t), t, ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK);
}
String[] prefixes = configuration.getIndentPrefixes(this, t);
if (prefixes != null && prefixes.length > 0)
setIndentPrefixes(prefixes, t);
prefixes = configuration.getDefaultPrefixes(this, t);
if (prefixes != null && prefixes.length > 0)
setDefaultPrefixes(prefixes, t);
// Bug 230297 - Add LineStyleProviders from the new configuration if
// the document is set
if(getDocument() != null) {
// add highlighter/linestyleprovider
LineStyleProvider[] providers = ((StructuredTextViewerConfiguration) configuration).getLineStyleProviders(this, t);
if (providers != null) {
for (int j = 0; j < providers.length; ++j) {
if(fRecHighlighter == null) {
fRecHighlighter = new ReconcilerHighlighter();
((StructuredTextViewerConfiguration) configuration).setHighlighter(fRecHighlighter);
}
if (providers[j] instanceof AbstractLineStyleProvider) {
((AbstractLineStyleProvider) providers[j]).init((IStructuredDocument) getDocument(), fRecHighlighter);
fRecHighlighter.addProvider(t, providers[j]);
}
else {
// init with compatibility instance
if (fHighlighter == null) {
fHighlighter = new CompatibleHighlighter();
}
Logger.log(Logger.INFO_DEBUG, "CompatibleHighlighter installing compatibility for " + providers[j].getClass()); //$NON-NLS-1$
providers[j].init((IStructuredDocument) getDocument(), fHighlighter);
fHighlighter.addProvider(t, providers[j]);
}
}
}
}
}
// initialize highlighter after linestyleproviders were added
if (fHighlighter != null) {
fHighlighter.setDocumentPartitioning(configuration.getConfiguredDocumentPartitioning(this));
fHighlighter.setDocument((IStructuredDocument) getDocument());
fHighlighter.install(this);
}
if (fRecHighlighter != null)
fRecHighlighter.install(this);
activatePlugins();
fConfiguration = configuration;
// Update the viewer's presentation reconciler
fPresentationReconciler = configuration.getPresentationReconciler(this);
if(fPresentationReconciler != null)
fPresentationReconciler.install(this);
}
|
diff --git a/src/simpleserver/minecraft/MessageHandler.java b/src/simpleserver/minecraft/MessageHandler.java
index 63f88ce..22bcf4c 100644
--- a/src/simpleserver/minecraft/MessageHandler.java
+++ b/src/simpleserver/minecraft/MessageHandler.java
@@ -1,156 +1,156 @@
/*
* Copyright (c) 2010 SimpleServer authors (see CONTRIBUTORS)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package simpleserver.minecraft;
import static simpleserver.lang.Translations.t;
import static simpleserver.util.Util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import simpleserver.Server;
import simpleserver.command.CommandFeedback;
import simpleserver.command.InvalidCommand;
import simpleserver.command.ServerCommand;
public class MessageHandler {
private final Server server;
private final static Pattern DISCONNECT = Pattern.compile(".*\\[INFO\\] (.*) lost connection:.*");
private final static Pattern CONNECT = Pattern.compile(".*\\[INFO\\] (.*) \\[.*\\] logged in with entity id \\d+ at .*");
private boolean loaded = false;
private int ignoreLines = 0;
private CommandFeedback feedback = new CommandFeedback() {
public void send(String message, Object... args) {
println(String.format(message, args));
}
};
public MessageHandler(Server server) {
this.server = server;
}
public synchronized void waitUntilLoaded() throws InterruptedException {
if (!loaded) {
wait();
}
}
public void handleError(Exception exception) {
if (!server.isRestarting() && !server.isStopping()) {
if (exception != null) {
println(exception);
}
String baseError = "[SimpleServer] Minecraft process stopped unexpectedly!";
if (server.config.properties.getBoolean("exitOnFailure")) {
System.out.println(baseError);
server.stop();
} else {
System.out.println(baseError + " Automatically restarting...");
server.restart();
}
}
}
public void handleQuit() {
handleError(null);
}
public void handleOutput(String line) {
if (!server.config.properties.getBoolean("debug") && line.contains("\tat")) {
return;
}
Integer[] ports = server.getRobotPorts();
if (ports != null) {
for (Integer port : ports) {
if (port != null) {
if (line.contains(port.toString())) {
server.removeRobotPort(port);
return;
}
}
}
}
if (ignoreLine()) {
return;
}
if (line.contains("[INFO] Done (")) {
synchronized (this) {
loaded = true;
notifyAll();
}
- } else if (line.contains("[INFO] CONSOLE: Save complete.") || line.contains("[INFO] Save complete.")) {
+ } else if (line.contains("[INFO] Saved the world")) {
server.setSaving(false);
if (server.options.getBoolean("announceBackup")) {
server.runCommand("say", t("Save Complete!"));
}
} else if (line.contains("[SEVERE] Unexpected exception")) {
handleError(new Exception(line));
} else if (line.matches("^>+$")) {
return;
} else if (line.contains("SERVER IS RUNNING IN OFFLINE/INSECURE MODE") && server.config.properties.getBoolean("onlineMode")) {
ignoreNextLines(3);
return;
} else {
Matcher connect = CONNECT.matcher(line);
if (connect.find()) {
if (server.bots.ninja(connect.group(1))) {
return;
}
} else {
Matcher disconnect = DISCONNECT.matcher(line);
if (disconnect.find()) {
if (server.bots.ninja(disconnect.group(1))) {
return;
}
}
}
}
server.addOutputLine(line);
System.out.println(line);
}
public boolean parseCommand(String line) {
ServerCommand command = server.getCommandParser().getServerCommand(line.split(" ")[0]);
if ((command != null) && !(command instanceof InvalidCommand)) {
command.execute(server, line, feedback);
return !command.shouldPassThroughToConsole(server);
}
return false;
}
private void ignoreNextLines(int count) {
ignoreLines = count;
}
private boolean ignoreLine() {
if (ignoreLines > 0) {
ignoreLines--;
return true;
}
return false;
}
}
| true | true | public void handleOutput(String line) {
if (!server.config.properties.getBoolean("debug") && line.contains("\tat")) {
return;
}
Integer[] ports = server.getRobotPorts();
if (ports != null) {
for (Integer port : ports) {
if (port != null) {
if (line.contains(port.toString())) {
server.removeRobotPort(port);
return;
}
}
}
}
if (ignoreLine()) {
return;
}
if (line.contains("[INFO] Done (")) {
synchronized (this) {
loaded = true;
notifyAll();
}
} else if (line.contains("[INFO] CONSOLE: Save complete.") || line.contains("[INFO] Save complete.")) {
server.setSaving(false);
if (server.options.getBoolean("announceBackup")) {
server.runCommand("say", t("Save Complete!"));
}
} else if (line.contains("[SEVERE] Unexpected exception")) {
handleError(new Exception(line));
} else if (line.matches("^>+$")) {
return;
} else if (line.contains("SERVER IS RUNNING IN OFFLINE/INSECURE MODE") && server.config.properties.getBoolean("onlineMode")) {
ignoreNextLines(3);
return;
} else {
Matcher connect = CONNECT.matcher(line);
if (connect.find()) {
if (server.bots.ninja(connect.group(1))) {
return;
}
} else {
Matcher disconnect = DISCONNECT.matcher(line);
if (disconnect.find()) {
if (server.bots.ninja(disconnect.group(1))) {
return;
}
}
}
}
server.addOutputLine(line);
System.out.println(line);
}
| public void handleOutput(String line) {
if (!server.config.properties.getBoolean("debug") && line.contains("\tat")) {
return;
}
Integer[] ports = server.getRobotPorts();
if (ports != null) {
for (Integer port : ports) {
if (port != null) {
if (line.contains(port.toString())) {
server.removeRobotPort(port);
return;
}
}
}
}
if (ignoreLine()) {
return;
}
if (line.contains("[INFO] Done (")) {
synchronized (this) {
loaded = true;
notifyAll();
}
} else if (line.contains("[INFO] Saved the world")) {
server.setSaving(false);
if (server.options.getBoolean("announceBackup")) {
server.runCommand("say", t("Save Complete!"));
}
} else if (line.contains("[SEVERE] Unexpected exception")) {
handleError(new Exception(line));
} else if (line.matches("^>+$")) {
return;
} else if (line.contains("SERVER IS RUNNING IN OFFLINE/INSECURE MODE") && server.config.properties.getBoolean("onlineMode")) {
ignoreNextLines(3);
return;
} else {
Matcher connect = CONNECT.matcher(line);
if (connect.find()) {
if (server.bots.ninja(connect.group(1))) {
return;
}
} else {
Matcher disconnect = DISCONNECT.matcher(line);
if (disconnect.find()) {
if (server.bots.ninja(disconnect.group(1))) {
return;
}
}
}
}
server.addOutputLine(line);
System.out.println(line);
}
|
diff --git a/src/com/mistphizzle/donationpoints/plugin/SignListener.java b/src/com/mistphizzle/donationpoints/plugin/SignListener.java
index 60c712f..731f946 100644
--- a/src/com/mistphizzle/donationpoints/plugin/SignListener.java
+++ b/src/com/mistphizzle/donationpoints/plugin/SignListener.java
@@ -1,68 +1,68 @@
package com.mistphizzle.donationpoints.plugin;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.block.Sign;
public class SignListener implements Listener {
public static String SignMessage;
public static DonationPoints plugin;
public SignListener(DonationPoints instance) {
plugin = instance;
}
@EventHandler
public void onBlockBreak(BlockBreakEvent e) {
Player player = e.getPlayer();
Block block = e.getBlock();
if (block.getState() instanceof Sign) {
Sign s = (Sign) block.getState();
String signline1 = s.getLine(0);
if (signline1.equalsIgnoreCase("[" + SignMessage + "]") && !player.hasPermission("donationpoints.sign.break")) {
player.sendMessage("�cYou don't have permission to break a DonationPoints sign.");
e.setCancelled(true);
}
}
}
@EventHandler
public void onSignChance(SignChangeEvent e) {
if (e.isCancelled()) return;
if (e.getPlayer() == null) return;
Player p = e.getPlayer();
String line1 = e.getLine(0);
Block block = e.getBlock();
Sign s = (Sign) block.getState();
String pack = e.getLine(1);
// Permissions
if (line1.equalsIgnoreCase("[" + SignMessage + "]") && !p.hasPermission("donationpoints.sign.create")) {
e.setCancelled(true);
block.breakNaturally();
p.sendMessage("�cYou don't have permission to create DonationPoints signs.");
} else if (p.hasPermission("donationpoints.sign.create") && line1.equalsIgnoreCase("[" + SignMessage + "]")) {
if (block.getType() == Material.SIGN_POST) {
p.sendMessage("�cDonationPoints signs must be placed on a wall.");
block.breakNaturally();
e.setCancelled(true);
} if (plugin.getConfig().getString("packages." + pack) == null) {
p.sendMessage("�cThat package does not exist.");
e.setCancelled(true);
block.breakNaturally();
} if (e.getLine(1).isEmpty()) {
- p.sendMessage("�cYou didn't enter a packag eon the second line!");
+ p.sendMessage("�cYou didn't enter a package on the second line!");
e.setCancelled(true);
block.breakNaturally();
} else {
p.sendMessage("�aYou have created a DonationPoints sign.");
}
}
}
}
| true | true | public void onSignChance(SignChangeEvent e) {
if (e.isCancelled()) return;
if (e.getPlayer() == null) return;
Player p = e.getPlayer();
String line1 = e.getLine(0);
Block block = e.getBlock();
Sign s = (Sign) block.getState();
String pack = e.getLine(1);
// Permissions
if (line1.equalsIgnoreCase("[" + SignMessage + "]") && !p.hasPermission("donationpoints.sign.create")) {
e.setCancelled(true);
block.breakNaturally();
p.sendMessage("�cYou don't have permission to create DonationPoints signs.");
} else if (p.hasPermission("donationpoints.sign.create") && line1.equalsIgnoreCase("[" + SignMessage + "]")) {
if (block.getType() == Material.SIGN_POST) {
p.sendMessage("�cDonationPoints signs must be placed on a wall.");
block.breakNaturally();
e.setCancelled(true);
} if (plugin.getConfig().getString("packages." + pack) == null) {
p.sendMessage("�cThat package does not exist.");
e.setCancelled(true);
block.breakNaturally();
} if (e.getLine(1).isEmpty()) {
p.sendMessage("�cYou didn't enter a packag eon the second line!");
e.setCancelled(true);
block.breakNaturally();
} else {
p.sendMessage("�aYou have created a DonationPoints sign.");
}
}
}
| public void onSignChance(SignChangeEvent e) {
if (e.isCancelled()) return;
if (e.getPlayer() == null) return;
Player p = e.getPlayer();
String line1 = e.getLine(0);
Block block = e.getBlock();
Sign s = (Sign) block.getState();
String pack = e.getLine(1);
// Permissions
if (line1.equalsIgnoreCase("[" + SignMessage + "]") && !p.hasPermission("donationpoints.sign.create")) {
e.setCancelled(true);
block.breakNaturally();
p.sendMessage("�cYou don't have permission to create DonationPoints signs.");
} else if (p.hasPermission("donationpoints.sign.create") && line1.equalsIgnoreCase("[" + SignMessage + "]")) {
if (block.getType() == Material.SIGN_POST) {
p.sendMessage("�cDonationPoints signs must be placed on a wall.");
block.breakNaturally();
e.setCancelled(true);
} if (plugin.getConfig().getString("packages." + pack) == null) {
p.sendMessage("�cThat package does not exist.");
e.setCancelled(true);
block.breakNaturally();
} if (e.getLine(1).isEmpty()) {
p.sendMessage("�cYou didn't enter a package on the second line!");
e.setCancelled(true);
block.breakNaturally();
} else {
p.sendMessage("�aYou have created a DonationPoints sign.");
}
}
}
|
diff --git a/table-browser-impl/src/main/java/org/cytoscape/browser/internal/AttributeBrowserToolBar.java b/table-browser-impl/src/main/java/org/cytoscape/browser/internal/AttributeBrowserToolBar.java
index 930a17bb0..edd85fa4c 100644
--- a/table-browser-impl/src/main/java/org/cytoscape/browser/internal/AttributeBrowserToolBar.java
+++ b/table-browser-impl/src/main/java/org/cytoscape/browser/internal/AttributeBrowserToolBar.java
@@ -1,921 +1,921 @@
/*
Copyright (c) 2006, 2007, 2010, The Cytoscape Consortium (www.cytoscape.org)
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation; either version 2.1 of the License, or
any later version.
This library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. The software and
documentation provided hereunder is on an "as is" basis, and the
Institute for Systems Biology and the Whitehead Institute
have no obligations to provide maintenance, support,
updates, enhancements or modifications. In no event shall the
Institute for Systems Biology and the Whitehead Institute
be liable to any party for direct, indirect, special,
incidental or consequential damages, including lost profits, arising
out of the use of this software and its documentation, even if the
Institute for Systems Biology and the Whitehead Institute
have been advised of the possibility of such damage. See
the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
*/
package org.cytoscape.browser.internal;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.GroupLayout.ParallelGroup;
import javax.swing.GroupLayout.SequentialGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JToggleButton;
import javax.swing.JToolBar;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import org.cytoscape.application.CyApplicationManager;
import org.cytoscape.browser.internal.util.ColumnResizer;
import org.cytoscape.equations.EquationCompiler;
import org.cytoscape.model.CyColumn;
import org.cytoscape.model.CyEdge;
import org.cytoscape.model.CyIdentifiable;
import org.cytoscape.model.CyNetwork;
import org.cytoscape.model.CyNode;
import org.cytoscape.model.CyTable;
import org.cytoscape.model.subnetwork.CyRootNetwork;
import org.cytoscape.model.subnetwork.CySubNetwork;
import org.cytoscape.service.util.CyServiceRegistrar;
import org.cytoscape.task.destroy.DeleteTableTaskFactory;
import org.cytoscape.util.swing.CheckBoxJList;
import org.cytoscape.work.swing.DialogTaskManager;
/**
* Toolbar for the Browser. All buttons related to this should be placed here.
*
*/
public class AttributeBrowserToolBar extends JPanel implements PopupMenuListener {
private static final long serialVersionUID = -508393701912596399L;
private BrowserTableModel browserTableModel;
private static final Dimension TOOLBAR_SIZE = new Dimension(500, 38);
/* GUI components */
private JPopupMenu attributeSelectionPopupMenu;
private JScrollPane jScrollPane;
private JPopupMenu createColumnMenu;
private JToolBar toolBar;
private SequentialGroup hToolBarGroup;
private ParallelGroup vToolBarGroup;
private JButton selectButton;
private CheckBoxJList attributeList;
private JList attrDeletionList;
private JButton createNewAttributeButton;
private JButton deleteAttributeButton;
private JButton deleteTableButton;
private JButton selectAllAttributesButton;
private JButton unselectAllAttributesButton;
private JButton formulaBuilderButton;
// private JButton mapGlobalTableButton;
// private final MapGlobalToLocalTableTaskFactory mapGlobalTableTaskFactoryService;
private final JComboBox tableChooser;
private AttributeListModel attrListModel;
private final EquationCompiler compiler;
private final DeleteTableTaskFactory deleteTableTaskFactory;
private final DialogTaskManager guiTaskMgr;
private final JButton selectionModeButton;
private final List<JComponent> components;
private final Class<? extends CyIdentifiable> objType;
private final CyApplicationManager appMgr;
public AttributeBrowserToolBar(final CyServiceRegistrar serviceRegistrar,
final EquationCompiler compiler,
final DeleteTableTaskFactory deleteTableTaskFactory,
final DialogTaskManager guiTaskMgr,
final JComboBox tableChooser,
final Class<? extends CyIdentifiable> objType,
final CyApplicationManager appMgr) {//, final MapGlobalToLocalTableTaskFactory mapGlobalTableTaskFactoryService) {
this(serviceRegistrar, compiler, deleteTableTaskFactory, guiTaskMgr, tableChooser,
new JButton(), objType, appMgr);//, mapGlobalTableTaskFactoryService);
}
public AttributeBrowserToolBar(final CyServiceRegistrar serviceRegistrar,
final EquationCompiler compiler,
final DeleteTableTaskFactory deleteTableTaskFactory,
final DialogTaskManager guiTaskMgr,
final JComboBox tableChooser,
final JButton selectionModeButton,
final Class<? extends CyIdentifiable> objType,
final CyApplicationManager appMgr) {// , final MapGlobalToLocalTableTaskFactory mapGlobalTableTaskFactoryService) {
this.compiler = compiler;
this.selectionModeButton = selectionModeButton;
this.appMgr = appMgr;
// this.mapGlobalTableTaskFactoryService = mapGlobalTableTaskFactoryService;
this.components = new ArrayList<JComponent>();
this.tableChooser = tableChooser;
this.deleteTableTaskFactory = deleteTableTaskFactory;
this.guiTaskMgr = guiTaskMgr;
this.attrListModel = new AttributeListModel(null);
this.objType = objType;
serviceRegistrar.registerAllServices(attrListModel, new Properties());
selectionModeButton.setEnabled(false);
initializeGUI();
}
public void setBrowserTableModel(final BrowserTableModel browserTableModel) {
this.browserTableModel = browserTableModel;
attrListModel.setBrowserTableModel(browserTableModel);
updateEnableState();
}
@Override
public void popupMenuCanceled(PopupMenuEvent e) {
// TODO Auto-generated method stub
}
@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
// Update actual table
try {
if (attributeList != null) {
final Object[] selectedValues = attributeList.getSelectedValues();
final Set<String> visibleAttributes = new HashSet<String>();
for (final Object selectedValue : selectedValues)
visibleAttributes.add((String)selectedValue);
browserTableModel.setVisibleAttributeNames(visibleAttributes);
}
} catch (Exception ex) {
attributeList.clearSelection();
}
}
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
// Do nothing
}
public void updateEnableState() {
for (final JComponent comp : components) {
boolean enabled = browserTableModel != null;
if (comp == deleteTableButton /*|| comp == mapGlobalTableButton*/)
enabled &= objType == null;
comp.setEnabled(enabled);
}
}
protected void addComponent(final JComponent component, final ComponentPlacement placement) {
hToolBarGroup.addPreferredGap(placement).addComponent(component);
vToolBarGroup.addComponent(component, Alignment.CENTER, GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE);
components.add(component);
}
private void initializeGUI() {
setLayout(new BorderLayout());
add(getToolBar(), BorderLayout.CENTER);
getAttributeSelectionPopupMenu();
getJPopupMenu();
// Add buttons
if (selectionModeButton != null)
addComponent(selectionModeButton, ComponentPlacement.RELATED);
addComponent(getSelectButton(), ComponentPlacement.UNRELATED);
addComponent(getSelectAllButton(), ComponentPlacement.RELATED);
addComponent(getUnselectAllButton(), ComponentPlacement.RELATED);
addComponent(getNewButton(), ComponentPlacement.UNRELATED);
addComponent(getDeleteButton(), ComponentPlacement.RELATED);
addComponent(getDeleteTableButton(), ComponentPlacement.RELATED);
addComponent(getFunctionBuilderButton(), ComponentPlacement.UNRELATED);
// addComponent(getMapGlobalTableButton(). ComponentPlacement.UNRELATED);
if (tableChooser != null)
addComponent(tableChooser, ComponentPlacement.UNRELATED);
}
public String getToBeDeletedAttribute() {
return attrDeletionList.getSelectedValue().toString();
}
/**
* This method initializes jPopupMenu
*
* @return javax.swing.JPopupMenu
*/
private JPopupMenu getAttributeSelectionPopupMenu() {
if (attributeSelectionPopupMenu == null) {
attributeSelectionPopupMenu = new JPopupMenu();
attributeSelectionPopupMenu.add(getJScrollPane());
attributeSelectionPopupMenu.addPopupMenuListener(this);
}
return attributeSelectionPopupMenu;
}
/**
* This method initializes jScrollPane
*
* @return javax.swing.JScrollPane
*/
private JScrollPane getJScrollPane() {
if (jScrollPane == null) {
jScrollPane = new JScrollPane();
- jScrollPane.setPreferredSize(new Dimension(600, 300));
+ jScrollPane.setPreferredSize(new Dimension(250, 200));
jScrollPane.setViewportView(getSelectedAttributeList());
}
return jScrollPane;
}
/**
* This method initializes jPopupMenu
*
* @return javax.swing.JPopupMenu
*/
private JPopupMenu getJPopupMenu() {
if (createColumnMenu == null) {
createColumnMenu = new JPopupMenu();
//final JMenu column = new JMenu("New Column");
final JMenu columnRegular = new JMenu("New Single Column");
final JMenu columnList = new JMenu("New List Column");
columnRegular.add(getJMenuItemIntegerAttribute(false));
columnRegular.add(getJMenuItemLongIntegerAttribute(false));
columnRegular.add(getJMenuItemStringAttribute(false));
columnRegular.add(getJMenuItemFloatingPointAttribute(false));
columnRegular.add(getJMenuItemBooleanAttribute(false));
columnList.add(getJMenuItemIntegerListAttribute(false));
columnList.add(getJMenuItemLongIntegerListAttribute(false));
columnList.add(getJMenuItemStringListAttribute(false));
columnList.add(getJMenuItemFloatingPointListAttribute(false));
columnList.add(getJMenuItemBooleanListAttribute(false));
//column.add(columnRegular);
//column.add(columnList);
createColumnMenu.add(columnRegular);
createColumnMenu.add(columnList);
/*
// This is not valid for Global Table.
if (objType != null) {
final JMenu shared = new JMenu("New Shared Column");
final JMenu sharedRegular = new JMenu("Single");
final JMenu sharedList = new JMenu("List");
sharedRegular.add(getJMenuItemIntegerAttribute(true));
sharedRegular.add(getJMenuItemLongIntegerAttribute(true));
sharedRegular.add(getJMenuItemStringAttribute(true));
sharedRegular.add(getJMenuItemFloatingPointAttribute(true));
sharedRegular.add(getJMenuItemBooleanAttribute(true));
sharedList.add(getJMenuItemIntegerListAttribute(true));
sharedList.add(getJMenuItemLongIntegerListAttribute(true));
sharedList.add(getJMenuItemStringListAttribute(true));
sharedList.add(getJMenuItemFloatingPointListAttribute(true));
sharedList.add(getJMenuItemBooleanListAttribute(true));
shared.add(sharedRegular);
shared.add(sharedList);
createColumnMenu.add(shared);
}
*/
}
return createColumnMenu;
}
/**
* This method initializes jMenuItemStringAttribute
*
* @return javax.swing.JMenuItem
*/
private JMenuItem getJMenuItemStringAttribute(final boolean isShared) {
final JMenuItem jMenuItemStringAttribute = new JMenuItem();
jMenuItemStringAttribute.setText("String");
jMenuItemStringAttribute.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
createNewAttribute("String", isShared);
}
});
return jMenuItemStringAttribute;
}
/**
* This method initializes jMenuItemIntegerAttribute
*
* @return javax.swing.JMenuItem
*/
private JMenuItem getJMenuItemIntegerAttribute(final boolean isShared) {
final JMenuItem jMenuItemIntegerAttribute = new JMenuItem();
jMenuItemIntegerAttribute.setText("Integer");
jMenuItemIntegerAttribute.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
createNewAttribute("Integer", isShared);
}
});
return jMenuItemIntegerAttribute;
}
/**
* This method initializes jMenuItemLongIntegerAttribute
*
* @return javax.swing.JMenuItem
*/
private JMenuItem getJMenuItemLongIntegerAttribute(final boolean isShared) {
final JMenuItem jMenuItemLongIntegerAttribute = new JMenuItem();
jMenuItemLongIntegerAttribute.setText("Long Integer");
jMenuItemLongIntegerAttribute.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
createNewAttribute("Long Integer", isShared);
}
});
return jMenuItemLongIntegerAttribute;
}
/**
* This method initializes jMenuItemFloatingPointAttribute
*
* @return javax.swing.JMenuItem
*/
private JMenuItem getJMenuItemFloatingPointAttribute(final boolean isShared) {
final JMenuItem jMenuItemFloatingPointAttribute = new JMenuItem();
jMenuItemFloatingPointAttribute.setText("Floating Point");
jMenuItemFloatingPointAttribute.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
createNewAttribute("Floating Point", isShared);
}
});
return jMenuItemFloatingPointAttribute;
}
/**
* This method initializes jMenuItemBooleanAttribute
*
* @return javax.swing.JMenuItem
*/
private JMenuItem getJMenuItemBooleanAttribute(final boolean isShared) {
final JMenuItem jMenuItemBooleanAttribute = new JMenuItem();
jMenuItemBooleanAttribute.setText("Boolean");
jMenuItemBooleanAttribute.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
createNewAttribute("Boolean", isShared);
}
});
return jMenuItemBooleanAttribute;
}
/**
* This method initializes jMenuItemStringListAttribute
*
* @return javax.swing.JMenuItem
*/
private JMenuItem getJMenuItemStringListAttribute(final boolean isShared) {
final JMenuItem jMenuItemStringListAttribute = new JMenuItem();
jMenuItemStringListAttribute.setText("String");
jMenuItemStringListAttribute.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
createNewAttribute("String List", isShared);
}
});
return jMenuItemStringListAttribute;
}
/**
* This method initializes jMenuItemIntegerListAttribute
*
* @return javax.swing.JMenuItem
*/
private JMenuItem getJMenuItemIntegerListAttribute(final boolean isShared) {
final JMenuItem jMenuItemIntegerListAttribute = new JMenuItem();
jMenuItemIntegerListAttribute.setText("Integer");
jMenuItemIntegerListAttribute.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
createNewAttribute("Integer List", isShared);
}
});
return jMenuItemIntegerListAttribute;
}
/**
* This method initializes jMenuItemLongIntegerListAttribute
*
* @return javax.swing.JMenuItem
*/
private JMenuItem getJMenuItemLongIntegerListAttribute(final boolean isShared) {
final JMenuItem jMenuItemLongIntegerListAttribute = new JMenuItem();
jMenuItemLongIntegerListAttribute.setText("Long Integer");
jMenuItemLongIntegerListAttribute.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
createNewAttribute("Integer List", isShared);
}
});
return jMenuItemLongIntegerListAttribute;
}
/**
* This method initializes jMenuItemFloatingPointListAttribute
*
* @return javax.swing.JMenuItem
*/
private JMenuItem getJMenuItemFloatingPointListAttribute(final boolean isShared) {
final JMenuItem jMenuItemFloatingPointListAttribute = new JMenuItem();
jMenuItemFloatingPointListAttribute.setText("Floating Point");
jMenuItemFloatingPointListAttribute.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
createNewAttribute("Floating Point List", isShared);
}
});
return jMenuItemFloatingPointListAttribute;
}
/**
* This method initializes jMenuItemBooleanListAttribute
*
* @return javax.swing.JMenuItem
*/
private JMenuItem getJMenuItemBooleanListAttribute(final boolean isShared) {
final JMenuItem jMenuItemBooleanListAttribute = new JMenuItem();
jMenuItemBooleanListAttribute.setText("Boolean");
jMenuItemBooleanListAttribute.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
createNewAttribute("Boolean List", isShared);
}
});
return jMenuItemBooleanListAttribute;
}
/**
* This method initializes the toolBar
*
* @return javax.swing.JToolBar
*/
private JToolBar getToolBar() {
if (toolBar == null) {
toolBar = new JToolBar();
toolBar.setMargin(new Insets(0, 0, 3, 0));
toolBar.setPreferredSize(TOOLBAR_SIZE);
toolBar.setSize(TOOLBAR_SIZE);
toolBar.setFloatable(false);
toolBar.setOrientation(JToolBar.HORIZONTAL);
final GroupLayout buttonBarLayout = new GroupLayout(toolBar);
toolBar.setLayout(buttonBarLayout);
hToolBarGroup = buttonBarLayout.createSequentialGroup();
vToolBarGroup = buttonBarLayout.createParallelGroup(GroupLayout.Alignment.LEADING);
// Layout information.
buttonBarLayout.setHorizontalGroup(buttonBarLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(hToolBarGroup));
buttonBarLayout.setVerticalGroup(vToolBarGroup);
}
return toolBar;
}
/**
* This method initializes jButton
*
* @return javax.swing.JButton
*/
private JButton getSelectButton() {
if (selectButton == null) {
selectButton = new JButton();
selectButton.setBorder(null);
selectButton.setMargin(new Insets(0, 0, 0, 0));
selectButton.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/table-select-column-icon.png")));
selectButton.setToolTipText("Select Column");
selectButton.setBorder(null);
selectButton.setEnabled(false);
selectButton.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (browserTableModel == null)
return;
attributeList.setSelectedItems(browserTableModel.getVisibleAttributeNames());
attributeSelectionPopupMenu.show(e.getComponent(), e.getX(), e.getY());
}
});
}
return selectButton;
}
private JButton getFunctionBuilderButton() {
if (formulaBuilderButton == null) {
formulaBuilderButton = new JButton();
formulaBuilderButton.setBorder(null);
formulaBuilderButton.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/fx.png")));
formulaBuilderButton.setToolTipText("Function Builder");
formulaBuilderButton.setMargin(new Insets(1, 1, 1, 1));
formulaBuilderButton.setBorder(null);
formulaBuilderButton.setEnabled(false);
final JFrame rootFrame = (JFrame) SwingUtilities.getRoot(this);
formulaBuilderButton.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (browserTableModel == null)
return;
final JTable table = browserTableModel.getTable();
// Do not allow opening of the formula builder dialog
// while a cell is being edited!
if (table.getCellEditor() != null)
return;
final int cellRow = table.getSelectedRow();
final int cellColumn = table.getSelectedColumn();
if (cellRow == -1 || cellColumn == -1 || !browserTableModel.isCellEditable(cellRow, cellColumn)) {
JOptionPane.showMessageDialog(rootFrame, "Can't enter a formula w/o a selected cell.",
"Information", JOptionPane.INFORMATION_MESSAGE);
} else {
final String attrName = getAttribName(cellRow, cellColumn);
final Map<String, Class<?>> attribNameToTypeMap = new HashMap<String, Class<?>>();
final CyTable attrs = browserTableModel.getAttributes();
initAttribNameToTypeMap(attrs, attrName, attribNameToTypeMap);
final FormulaBuilderDialog formulaBuilderDialog = new FormulaBuilderDialog(compiler,
browserTableModel, rootFrame, attrName);
formulaBuilderDialog.setLocationRelativeTo(rootFrame);
formulaBuilderDialog.setVisible(true);
}
}
private void initAttribNameToTypeMap(final CyTable attrs, final String attrName,
final Map<String, Class<?>> attribNameToTypeMap) {
for (final CyColumn column : attrs.getColumns())
attribNameToTypeMap.put(column.getName(), column.getType());
attribNameToTypeMap.remove(attrName);
}
});
}
return formulaBuilderButton;
}
private String getAttribName(final int cellRow, final int cellColumn) {
return browserTableModel.getColumnName(cellColumn);
}
private JButton getDeleteButton() {
if (deleteAttributeButton == null) {
deleteAttributeButton = new JButton();
deleteAttributeButton.setBorder(null);
deleteAttributeButton.setMargin(new Insets(0, 0, 0, 0));
deleteAttributeButton.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/stock_delete.png")));
deleteAttributeButton.setToolTipText("Delete Column...");
deleteAttributeButton.setBorder(null);
// Create pop-up window for deletion
deleteAttributeButton.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (deleteAttributeButton.isEnabled())
removeAttribute(e);
}
});
deleteAttributeButton.setEnabled(false);
}
return deleteAttributeButton;
}
private JButton getDeleteTableButton() {
if (deleteTableButton == null) {
deleteTableButton = new JButton();
deleteTableButton.setBorder(null);
deleteTableButton.setMargin(new Insets(0, 0, 0, 0));
deleteTableButton.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/table_delete.png")));
deleteTableButton.setToolTipText("Delete Table...");
deleteTableButton.setBorder(null);
// Create pop-up window for deletion
deleteTableButton.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (deleteTableButton.isEnabled())
removeTable(e);
}
});
deleteTableButton.setEnabled(false);
}
return deleteTableButton;
}
private JButton getSelectAllButton() {
if (selectAllAttributesButton == null) {
selectAllAttributesButton = new JButton();
selectAllAttributesButton.setBorder(null);
selectAllAttributesButton.setMargin(new Insets(0, 0, 0, 0));
selectAllAttributesButton.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/select_all.png")));
selectAllAttributesButton.setToolTipText("Select All Columns");
selectAllAttributesButton.setBorder(null);
selectAllAttributesButton.setEnabled(false);
selectAllAttributesButton.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
try {
final CyTable table = browserTableModel.getAttributes();
final Set<String> allAttrNames = new HashSet<String>();
for (final CyColumn column : table.getColumns())
allAttrNames.add(column.getName());
browserTableModel.setVisibleAttributeNames(allAttrNames);
// Resize column
ColumnResizer.adjustColumnPreferredWidths(browserTableModel.getTable());
} catch (Exception ex) {
attributeList.clearSelection();
}
}
});
}
return selectAllAttributesButton;
}
private JButton getUnselectAllButton() {
if (unselectAllAttributesButton == null) {
unselectAllAttributesButton = new JButton();
unselectAllAttributesButton.setBorder(null);
unselectAllAttributesButton.setMargin(new Insets(0, 0, 0, 0));
unselectAllAttributesButton.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/unselect_all.png")));
unselectAllAttributesButton.setToolTipText("Unselect All Columns");
unselectAllAttributesButton.setBorder(null);
unselectAllAttributesButton.setEnabled(false);
unselectAllAttributesButton.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
try {
browserTableModel.setVisibleAttributeNames(new HashSet<String>());
} catch (Exception ex) {
attributeList.clearSelection();
}
}
});
}
return unselectAllAttributesButton;
}
private void removeAttribute(final MouseEvent e) {
final String[] attrArray = getAttributeArray();
final JFrame frame = (JFrame)SwingUtilities.getRoot(this);
final DeletionDialog dDialog = new DeletionDialog(frame, browserTableModel.getAttributes());
dDialog.pack();
dDialog.setLocationRelativeTo(toolBar);
dDialog.setVisible(true);
}
private void removeTable(final MouseEvent e) {
final CyTable table = browserTableModel.getAttributes();
if (table.getMutability() == CyTable.Mutability.MUTABLE) {
String title = "Please confirm this action";
String msg = "Are you sure you want to delete this table?";
int _confirmValue = JOptionPane.showConfirmDialog(this, msg, title, JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE);
// if user selects yes delete the table
if (_confirmValue == JOptionPane.OK_OPTION)
guiTaskMgr.execute(deleteTableTaskFactory.createTaskIterator(table));
} else if (table.getMutability() == CyTable.Mutability.PERMANENTLY_IMMUTABLE) {
String title = "Error";
String msg = "Can not delete this table, it is PERMANENTLY_IMMUTABLE";
JOptionPane.showMessageDialog(this, msg, title, JOptionPane.ERROR_MESSAGE);
} else if (table.getMutability() == CyTable.Mutability.IMMUTABLE_DUE_TO_VIRT_COLUMN_REFERENCES) {
String title = "Error";
String msg = "Can not delete this table, it is IMMUTABLE_DUE_TO_VIRT_COLUMN_REFERENCES";
JOptionPane.showMessageDialog(this, msg, title, JOptionPane.ERROR_MESSAGE);
}
}
private JList getSelectedAttributeList() {
if (attributeList == null) {
attributeList = new CheckBoxJList();
attributeList.setModel(attrListModel);
attributeList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
attributeList.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
attributeSelectionPopupMenu.setVisible(false);
}
}
});
}
return attributeList;
}
private String[] getAttributeArray() {
final CyTable attrs = browserTableModel.getAttributes();
final Collection<CyColumn> columns = attrs.getColumns();
final String[] attributeArray = new String[columns.size() - 1];
int index = 0;
for (final CyColumn column : columns) {
if (!column.isPrimaryKey())
attributeArray[index++] = column.getName();
}
Arrays.sort(attributeArray);
return attributeArray;
}
/**
* This method initializes createNewAttributeButton
*
* @return javax.swing.JButton
*/
private JButton getNewButton() {
if (createNewAttributeButton == null) {
createNewAttributeButton = new JButton();
createNewAttributeButton.setBorder(null);
createNewAttributeButton.setFont(new java.awt.Font("Dialog", java.awt.Font.PLAIN, 12));
createNewAttributeButton.setHorizontalTextPosition(SwingConstants.CENTER);
createNewAttributeButton.setMargin(new Insets(0, 0, 0, 0));
createNewAttributeButton.setToolTipText("Create New Column");
createNewAttributeButton.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/stock_new.png")));
createNewAttributeButton.setBorder(null);
createNewAttributeButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (browserTableModel != null)
createColumnMenu.show(e.getComponent(), e.getX(), e.getY());
}
});
createNewAttributeButton.setEnabled(false);
}
return createNewAttributeButton;
}
/*
private JButton getMapGlobalTableButton() {
if (mapGlobalTableButton == null) {
mapGlobalTableButton = new JButton();
mapGlobalTableButton.setBorder(null);
mapGlobalTableButton.setMargin(new Insets(0, 0, 0, 0));
mapGlobalTableButton.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/table_map.png")));
mapGlobalTableButton.setToolTipText("Link Table to Attributes");
mapGlobalTableButton.setBorder(null);
mapGlobalTableButton.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (mapGlobalTableButton.isEnabled())
guiTaskManagerServiceRef.execute(mapGlobalTableTaskFactoryService.createTaskIterator( browserTableModel.getAttributes() ));
}
});
}
mapGlobalTableButton.setEnabled(false);
return mapGlobalTableButton;
}
*/
private void createNewAttribute(final String type, boolean isShared) {
final String[] existingAttrs = getAttributeArray();
String newAttribName = null;
do {
newAttribName = JOptionPane.showInputDialog(this, "Please enter new column name: ",
"Create New " + type + " Column",
JOptionPane.QUESTION_MESSAGE);
if (newAttribName == null)
return;
if (Arrays.binarySearch(existingAttrs, newAttribName) >= 0) {
newAttribName = null;
JOptionPane.showMessageDialog(null,
"Column " + newAttribName + " already exists.",
"Error.", JOptionPane.ERROR_MESSAGE);
}
} while (newAttribName == null);
final CyTable attrs;
if(isShared) {
final CyNetwork network = appMgr.getCurrentNetwork();
if(network instanceof CySubNetwork) {
final CyRootNetwork rootNetwork = ((CySubNetwork) network).getRootNetwork();
CyTable sharedTable = null;
if(this.objType == CyNode.class)
sharedTable = rootNetwork.getSharedNodeTable();
else if(this.objType == CyEdge.class)
sharedTable = rootNetwork.getSharedEdgeTable();
else if(this.objType == CyNetwork.class)
sharedTable = rootNetwork.getSharedNetworkTable();
else {
throw new IllegalStateException("Object type is not valid. This should not happen.");
}
attrs = sharedTable;
} else {
throw new IllegalArgumentException("This is not a CySubNetwork and there is no shared table.");
}
} else {
attrs = browserTableModel.getAttributes();
}
if (type.equals("String"))
attrs.createColumn(newAttribName, String.class, false);
else if (type.equals("Floating Point"))
attrs.createColumn(newAttribName, Double.class, false);
else if (type.equals("Integer"))
attrs.createColumn(newAttribName, Integer.class, false);
else if (type.equals("Long Integer"))
attrs.createColumn(newAttribName, Long.class, false);
else if (type.equals("Boolean"))
attrs.createColumn(newAttribName, Boolean.class, false);
else if (type.equals("String List"))
attrs.createListColumn(newAttribName, String.class, false);
else if (type.equals("Floating Point List"))
attrs.createListColumn(newAttribName, Double.class, false);
else if (type.equals("Integer List"))
attrs.createListColumn(newAttribName, Integer.class, false);
else if (type.equals("Long Integer List"))
attrs.createListColumn(newAttribName, Long.class, false);
else if (type.equals("Boolean List"))
attrs.createListColumn(newAttribName, Boolean.class, false);
else
throw new IllegalArgumentException("unknown column type \"" + type + "\".");
}
}
| true | true | public AttributeBrowserToolBar(final CyServiceRegistrar serviceRegistrar,
final EquationCompiler compiler,
final DeleteTableTaskFactory deleteTableTaskFactory,
final DialogTaskManager guiTaskMgr,
final JComboBox tableChooser,
final Class<? extends CyIdentifiable> objType,
final CyApplicationManager appMgr) {//, final MapGlobalToLocalTableTaskFactory mapGlobalTableTaskFactoryService) {
this(serviceRegistrar, compiler, deleteTableTaskFactory, guiTaskMgr, tableChooser,
new JButton(), objType, appMgr);//, mapGlobalTableTaskFactoryService);
}
public AttributeBrowserToolBar(final CyServiceRegistrar serviceRegistrar,
final EquationCompiler compiler,
final DeleteTableTaskFactory deleteTableTaskFactory,
final DialogTaskManager guiTaskMgr,
final JComboBox tableChooser,
final JButton selectionModeButton,
final Class<? extends CyIdentifiable> objType,
final CyApplicationManager appMgr) {// , final MapGlobalToLocalTableTaskFactory mapGlobalTableTaskFactoryService) {
this.compiler = compiler;
this.selectionModeButton = selectionModeButton;
this.appMgr = appMgr;
// this.mapGlobalTableTaskFactoryService = mapGlobalTableTaskFactoryService;
this.components = new ArrayList<JComponent>();
this.tableChooser = tableChooser;
this.deleteTableTaskFactory = deleteTableTaskFactory;
this.guiTaskMgr = guiTaskMgr;
this.attrListModel = new AttributeListModel(null);
this.objType = objType;
serviceRegistrar.registerAllServices(attrListModel, new Properties());
selectionModeButton.setEnabled(false);
initializeGUI();
}
public void setBrowserTableModel(final BrowserTableModel browserTableModel) {
this.browserTableModel = browserTableModel;
attrListModel.setBrowserTableModel(browserTableModel);
updateEnableState();
}
@Override
public void popupMenuCanceled(PopupMenuEvent e) {
// TODO Auto-generated method stub
}
@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
// Update actual table
try {
if (attributeList != null) {
final Object[] selectedValues = attributeList.getSelectedValues();
final Set<String> visibleAttributes = new HashSet<String>();
for (final Object selectedValue : selectedValues)
visibleAttributes.add((String)selectedValue);
browserTableModel.setVisibleAttributeNames(visibleAttributes);
}
} catch (Exception ex) {
attributeList.clearSelection();
}
}
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
// Do nothing
}
public void updateEnableState() {
for (final JComponent comp : components) {
boolean enabled = browserTableModel != null;
if (comp == deleteTableButton /*|| comp == mapGlobalTableButton*/)
enabled &= objType == null;
comp.setEnabled(enabled);
}
}
protected void addComponent(final JComponent component, final ComponentPlacement placement) {
hToolBarGroup.addPreferredGap(placement).addComponent(component);
vToolBarGroup.addComponent(component, Alignment.CENTER, GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE);
components.add(component);
}
private void initializeGUI() {
setLayout(new BorderLayout());
add(getToolBar(), BorderLayout.CENTER);
getAttributeSelectionPopupMenu();
getJPopupMenu();
// Add buttons
if (selectionModeButton != null)
addComponent(selectionModeButton, ComponentPlacement.RELATED);
addComponent(getSelectButton(), ComponentPlacement.UNRELATED);
addComponent(getSelectAllButton(), ComponentPlacement.RELATED);
addComponent(getUnselectAllButton(), ComponentPlacement.RELATED);
addComponent(getNewButton(), ComponentPlacement.UNRELATED);
addComponent(getDeleteButton(), ComponentPlacement.RELATED);
addComponent(getDeleteTableButton(), ComponentPlacement.RELATED);
addComponent(getFunctionBuilderButton(), ComponentPlacement.UNRELATED);
// addComponent(getMapGlobalTableButton(). ComponentPlacement.UNRELATED);
if (tableChooser != null)
addComponent(tableChooser, ComponentPlacement.UNRELATED);
}
public String getToBeDeletedAttribute() {
return attrDeletionList.getSelectedValue().toString();
}
/**
* This method initializes jPopupMenu
*
* @return javax.swing.JPopupMenu
*/
private JPopupMenu getAttributeSelectionPopupMenu() {
if (attributeSelectionPopupMenu == null) {
attributeSelectionPopupMenu = new JPopupMenu();
attributeSelectionPopupMenu.add(getJScrollPane());
attributeSelectionPopupMenu.addPopupMenuListener(this);
}
return attributeSelectionPopupMenu;
}
/**
* This method initializes jScrollPane
*
* @return javax.swing.JScrollPane
*/
private JScrollPane getJScrollPane() {
if (jScrollPane == null) {
jScrollPane = new JScrollPane();
jScrollPane.setPreferredSize(new Dimension(600, 300));
jScrollPane.setViewportView(getSelectedAttributeList());
}
return jScrollPane;
}
/**
* This method initializes jPopupMenu
*
* @return javax.swing.JPopupMenu
*/
private JPopupMenu getJPopupMenu() {
if (createColumnMenu == null) {
createColumnMenu = new JPopupMenu();
//final JMenu column = new JMenu("New Column");
final JMenu columnRegular = new JMenu("New Single Column");
final JMenu columnList = new JMenu("New List Column");
columnRegular.add(getJMenuItemIntegerAttribute(false));
columnRegular.add(getJMenuItemLongIntegerAttribute(false));
columnRegular.add(getJMenuItemStringAttribute(false));
columnRegular.add(getJMenuItemFloatingPointAttribute(false));
columnRegular.add(getJMenuItemBooleanAttribute(false));
columnList.add(getJMenuItemIntegerListAttribute(false));
columnList.add(getJMenuItemLongIntegerListAttribute(false));
columnList.add(getJMenuItemStringListAttribute(false));
columnList.add(getJMenuItemFloatingPointListAttribute(false));
columnList.add(getJMenuItemBooleanListAttribute(false));
//column.add(columnRegular);
//column.add(columnList);
createColumnMenu.add(columnRegular);
createColumnMenu.add(columnList);
/*
// This is not valid for Global Table.
if (objType != null) {
final JMenu shared = new JMenu("New Shared Column");
final JMenu sharedRegular = new JMenu("Single");
final JMenu sharedList = new JMenu("List");
sharedRegular.add(getJMenuItemIntegerAttribute(true));
sharedRegular.add(getJMenuItemLongIntegerAttribute(true));
sharedRegular.add(getJMenuItemStringAttribute(true));
sharedRegular.add(getJMenuItemFloatingPointAttribute(true));
sharedRegular.add(getJMenuItemBooleanAttribute(true));
sharedList.add(getJMenuItemIntegerListAttribute(true));
sharedList.add(getJMenuItemLongIntegerListAttribute(true));
sharedList.add(getJMenuItemStringListAttribute(true));
sharedList.add(getJMenuItemFloatingPointListAttribute(true));
sharedList.add(getJMenuItemBooleanListAttribute(true));
shared.add(sharedRegular);
shared.add(sharedList);
createColumnMenu.add(shared);
}
*/
}
return createColumnMenu;
}
/**
* This method initializes jMenuItemStringAttribute
*
* @return javax.swing.JMenuItem
*/
private JMenuItem getJMenuItemStringAttribute(final boolean isShared) {
final JMenuItem jMenuItemStringAttribute = new JMenuItem();
jMenuItemStringAttribute.setText("String");
jMenuItemStringAttribute.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
createNewAttribute("String", isShared);
}
});
return jMenuItemStringAttribute;
}
/**
* This method initializes jMenuItemIntegerAttribute
*
* @return javax.swing.JMenuItem
*/
private JMenuItem getJMenuItemIntegerAttribute(final boolean isShared) {
final JMenuItem jMenuItemIntegerAttribute = new JMenuItem();
jMenuItemIntegerAttribute.setText("Integer");
jMenuItemIntegerAttribute.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
createNewAttribute("Integer", isShared);
}
});
return jMenuItemIntegerAttribute;
}
/**
* This method initializes jMenuItemLongIntegerAttribute
*
* @return javax.swing.JMenuItem
*/
private JMenuItem getJMenuItemLongIntegerAttribute(final boolean isShared) {
final JMenuItem jMenuItemLongIntegerAttribute = new JMenuItem();
jMenuItemLongIntegerAttribute.setText("Long Integer");
jMenuItemLongIntegerAttribute.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
createNewAttribute("Long Integer", isShared);
}
});
return jMenuItemLongIntegerAttribute;
}
/**
* This method initializes jMenuItemFloatingPointAttribute
*
* @return javax.swing.JMenuItem
*/
private JMenuItem getJMenuItemFloatingPointAttribute(final boolean isShared) {
final JMenuItem jMenuItemFloatingPointAttribute = new JMenuItem();
jMenuItemFloatingPointAttribute.setText("Floating Point");
jMenuItemFloatingPointAttribute.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
createNewAttribute("Floating Point", isShared);
}
});
return jMenuItemFloatingPointAttribute;
}
/**
* This method initializes jMenuItemBooleanAttribute
*
* @return javax.swing.JMenuItem
*/
private JMenuItem getJMenuItemBooleanAttribute(final boolean isShared) {
final JMenuItem jMenuItemBooleanAttribute = new JMenuItem();
jMenuItemBooleanAttribute.setText("Boolean");
jMenuItemBooleanAttribute.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
createNewAttribute("Boolean", isShared);
}
});
return jMenuItemBooleanAttribute;
}
/**
* This method initializes jMenuItemStringListAttribute
*
* @return javax.swing.JMenuItem
*/
private JMenuItem getJMenuItemStringListAttribute(final boolean isShared) {
final JMenuItem jMenuItemStringListAttribute = new JMenuItem();
jMenuItemStringListAttribute.setText("String");
jMenuItemStringListAttribute.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
createNewAttribute("String List", isShared);
}
});
return jMenuItemStringListAttribute;
}
/**
* This method initializes jMenuItemIntegerListAttribute
*
* @return javax.swing.JMenuItem
*/
private JMenuItem getJMenuItemIntegerListAttribute(final boolean isShared) {
final JMenuItem jMenuItemIntegerListAttribute = new JMenuItem();
jMenuItemIntegerListAttribute.setText("Integer");
jMenuItemIntegerListAttribute.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
createNewAttribute("Integer List", isShared);
}
});
return jMenuItemIntegerListAttribute;
}
/**
* This method initializes jMenuItemLongIntegerListAttribute
*
* @return javax.swing.JMenuItem
*/
private JMenuItem getJMenuItemLongIntegerListAttribute(final boolean isShared) {
final JMenuItem jMenuItemLongIntegerListAttribute = new JMenuItem();
jMenuItemLongIntegerListAttribute.setText("Long Integer");
jMenuItemLongIntegerListAttribute.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
createNewAttribute("Integer List", isShared);
}
});
return jMenuItemLongIntegerListAttribute;
}
/**
* This method initializes jMenuItemFloatingPointListAttribute
*
* @return javax.swing.JMenuItem
*/
private JMenuItem getJMenuItemFloatingPointListAttribute(final boolean isShared) {
final JMenuItem jMenuItemFloatingPointListAttribute = new JMenuItem();
jMenuItemFloatingPointListAttribute.setText("Floating Point");
jMenuItemFloatingPointListAttribute.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
createNewAttribute("Floating Point List", isShared);
}
});
return jMenuItemFloatingPointListAttribute;
}
/**
* This method initializes jMenuItemBooleanListAttribute
*
* @return javax.swing.JMenuItem
*/
private JMenuItem getJMenuItemBooleanListAttribute(final boolean isShared) {
final JMenuItem jMenuItemBooleanListAttribute = new JMenuItem();
jMenuItemBooleanListAttribute.setText("Boolean");
jMenuItemBooleanListAttribute.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
createNewAttribute("Boolean List", isShared);
}
});
return jMenuItemBooleanListAttribute;
}
/**
* This method initializes the toolBar
*
* @return javax.swing.JToolBar
*/
private JToolBar getToolBar() {
if (toolBar == null) {
toolBar = new JToolBar();
toolBar.setMargin(new Insets(0, 0, 3, 0));
toolBar.setPreferredSize(TOOLBAR_SIZE);
toolBar.setSize(TOOLBAR_SIZE);
toolBar.setFloatable(false);
toolBar.setOrientation(JToolBar.HORIZONTAL);
final GroupLayout buttonBarLayout = new GroupLayout(toolBar);
toolBar.setLayout(buttonBarLayout);
hToolBarGroup = buttonBarLayout.createSequentialGroup();
vToolBarGroup = buttonBarLayout.createParallelGroup(GroupLayout.Alignment.LEADING);
// Layout information.
buttonBarLayout.setHorizontalGroup(buttonBarLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(hToolBarGroup));
buttonBarLayout.setVerticalGroup(vToolBarGroup);
}
return toolBar;
}
/**
* This method initializes jButton
*
* @return javax.swing.JButton
*/
private JButton getSelectButton() {
if (selectButton == null) {
selectButton = new JButton();
selectButton.setBorder(null);
selectButton.setMargin(new Insets(0, 0, 0, 0));
selectButton.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/table-select-column-icon.png")));
selectButton.setToolTipText("Select Column");
selectButton.setBorder(null);
selectButton.setEnabled(false);
selectButton.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (browserTableModel == null)
return;
attributeList.setSelectedItems(browserTableModel.getVisibleAttributeNames());
attributeSelectionPopupMenu.show(e.getComponent(), e.getX(), e.getY());
}
});
}
return selectButton;
}
private JButton getFunctionBuilderButton() {
if (formulaBuilderButton == null) {
formulaBuilderButton = new JButton();
formulaBuilderButton.setBorder(null);
formulaBuilderButton.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/fx.png")));
formulaBuilderButton.setToolTipText("Function Builder");
formulaBuilderButton.setMargin(new Insets(1, 1, 1, 1));
formulaBuilderButton.setBorder(null);
formulaBuilderButton.setEnabled(false);
final JFrame rootFrame = (JFrame) SwingUtilities.getRoot(this);
formulaBuilderButton.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (browserTableModel == null)
return;
final JTable table = browserTableModel.getTable();
// Do not allow opening of the formula builder dialog
// while a cell is being edited!
if (table.getCellEditor() != null)
return;
final int cellRow = table.getSelectedRow();
final int cellColumn = table.getSelectedColumn();
if (cellRow == -1 || cellColumn == -1 || !browserTableModel.isCellEditable(cellRow, cellColumn)) {
JOptionPane.showMessageDialog(rootFrame, "Can't enter a formula w/o a selected cell.",
"Information", JOptionPane.INFORMATION_MESSAGE);
} else {
final String attrName = getAttribName(cellRow, cellColumn);
final Map<String, Class<?>> attribNameToTypeMap = new HashMap<String, Class<?>>();
final CyTable attrs = browserTableModel.getAttributes();
initAttribNameToTypeMap(attrs, attrName, attribNameToTypeMap);
final FormulaBuilderDialog formulaBuilderDialog = new FormulaBuilderDialog(compiler,
browserTableModel, rootFrame, attrName);
formulaBuilderDialog.setLocationRelativeTo(rootFrame);
formulaBuilderDialog.setVisible(true);
}
}
private void initAttribNameToTypeMap(final CyTable attrs, final String attrName,
final Map<String, Class<?>> attribNameToTypeMap) {
for (final CyColumn column : attrs.getColumns())
attribNameToTypeMap.put(column.getName(), column.getType());
attribNameToTypeMap.remove(attrName);
}
});
}
return formulaBuilderButton;
}
private String getAttribName(final int cellRow, final int cellColumn) {
return browserTableModel.getColumnName(cellColumn);
}
private JButton getDeleteButton() {
if (deleteAttributeButton == null) {
deleteAttributeButton = new JButton();
deleteAttributeButton.setBorder(null);
deleteAttributeButton.setMargin(new Insets(0, 0, 0, 0));
deleteAttributeButton.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/stock_delete.png")));
deleteAttributeButton.setToolTipText("Delete Column...");
deleteAttributeButton.setBorder(null);
// Create pop-up window for deletion
deleteAttributeButton.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (deleteAttributeButton.isEnabled())
removeAttribute(e);
}
});
deleteAttributeButton.setEnabled(false);
}
return deleteAttributeButton;
}
private JButton getDeleteTableButton() {
if (deleteTableButton == null) {
deleteTableButton = new JButton();
deleteTableButton.setBorder(null);
deleteTableButton.setMargin(new Insets(0, 0, 0, 0));
deleteTableButton.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/table_delete.png")));
deleteTableButton.setToolTipText("Delete Table...");
deleteTableButton.setBorder(null);
// Create pop-up window for deletion
deleteTableButton.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (deleteTableButton.isEnabled())
removeTable(e);
}
});
deleteTableButton.setEnabled(false);
}
return deleteTableButton;
}
private JButton getSelectAllButton() {
if (selectAllAttributesButton == null) {
selectAllAttributesButton = new JButton();
selectAllAttributesButton.setBorder(null);
selectAllAttributesButton.setMargin(new Insets(0, 0, 0, 0));
selectAllAttributesButton.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/select_all.png")));
selectAllAttributesButton.setToolTipText("Select All Columns");
selectAllAttributesButton.setBorder(null);
selectAllAttributesButton.setEnabled(false);
selectAllAttributesButton.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
try {
final CyTable table = browserTableModel.getAttributes();
final Set<String> allAttrNames = new HashSet<String>();
for (final CyColumn column : table.getColumns())
allAttrNames.add(column.getName());
browserTableModel.setVisibleAttributeNames(allAttrNames);
// Resize column
ColumnResizer.adjustColumnPreferredWidths(browserTableModel.getTable());
} catch (Exception ex) {
attributeList.clearSelection();
}
}
});
}
return selectAllAttributesButton;
}
private JButton getUnselectAllButton() {
if (unselectAllAttributesButton == null) {
unselectAllAttributesButton = new JButton();
unselectAllAttributesButton.setBorder(null);
unselectAllAttributesButton.setMargin(new Insets(0, 0, 0, 0));
unselectAllAttributesButton.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/unselect_all.png")));
unselectAllAttributesButton.setToolTipText("Unselect All Columns");
unselectAllAttributesButton.setBorder(null);
unselectAllAttributesButton.setEnabled(false);
unselectAllAttributesButton.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
try {
browserTableModel.setVisibleAttributeNames(new HashSet<String>());
} catch (Exception ex) {
attributeList.clearSelection();
}
}
});
}
return unselectAllAttributesButton;
}
private void removeAttribute(final MouseEvent e) {
final String[] attrArray = getAttributeArray();
final JFrame frame = (JFrame)SwingUtilities.getRoot(this);
final DeletionDialog dDialog = new DeletionDialog(frame, browserTableModel.getAttributes());
dDialog.pack();
dDialog.setLocationRelativeTo(toolBar);
dDialog.setVisible(true);
}
private void removeTable(final MouseEvent e) {
final CyTable table = browserTableModel.getAttributes();
if (table.getMutability() == CyTable.Mutability.MUTABLE) {
String title = "Please confirm this action";
String msg = "Are you sure you want to delete this table?";
int _confirmValue = JOptionPane.showConfirmDialog(this, msg, title, JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE);
// if user selects yes delete the table
if (_confirmValue == JOptionPane.OK_OPTION)
guiTaskMgr.execute(deleteTableTaskFactory.createTaskIterator(table));
} else if (table.getMutability() == CyTable.Mutability.PERMANENTLY_IMMUTABLE) {
String title = "Error";
String msg = "Can not delete this table, it is PERMANENTLY_IMMUTABLE";
JOptionPane.showMessageDialog(this, msg, title, JOptionPane.ERROR_MESSAGE);
} else if (table.getMutability() == CyTable.Mutability.IMMUTABLE_DUE_TO_VIRT_COLUMN_REFERENCES) {
String title = "Error";
String msg = "Can not delete this table, it is IMMUTABLE_DUE_TO_VIRT_COLUMN_REFERENCES";
JOptionPane.showMessageDialog(this, msg, title, JOptionPane.ERROR_MESSAGE);
}
}
private JList getSelectedAttributeList() {
if (attributeList == null) {
attributeList = new CheckBoxJList();
attributeList.setModel(attrListModel);
attributeList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
attributeList.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
attributeSelectionPopupMenu.setVisible(false);
}
}
});
}
return attributeList;
}
private String[] getAttributeArray() {
final CyTable attrs = browserTableModel.getAttributes();
final Collection<CyColumn> columns = attrs.getColumns();
final String[] attributeArray = new String[columns.size() - 1];
int index = 0;
for (final CyColumn column : columns) {
if (!column.isPrimaryKey())
attributeArray[index++] = column.getName();
}
Arrays.sort(attributeArray);
return attributeArray;
}
/**
* This method initializes createNewAttributeButton
*
* @return javax.swing.JButton
*/
private JButton getNewButton() {
if (createNewAttributeButton == null) {
createNewAttributeButton = new JButton();
createNewAttributeButton.setBorder(null);
createNewAttributeButton.setFont(new java.awt.Font("Dialog", java.awt.Font.PLAIN, 12));
createNewAttributeButton.setHorizontalTextPosition(SwingConstants.CENTER);
createNewAttributeButton.setMargin(new Insets(0, 0, 0, 0));
createNewAttributeButton.setToolTipText("Create New Column");
createNewAttributeButton.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/stock_new.png")));
createNewAttributeButton.setBorder(null);
createNewAttributeButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (browserTableModel != null)
createColumnMenu.show(e.getComponent(), e.getX(), e.getY());
}
});
createNewAttributeButton.setEnabled(false);
}
return createNewAttributeButton;
}
/*
private JButton getMapGlobalTableButton() {
if (mapGlobalTableButton == null) {
mapGlobalTableButton = new JButton();
mapGlobalTableButton.setBorder(null);
mapGlobalTableButton.setMargin(new Insets(0, 0, 0, 0));
mapGlobalTableButton.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/table_map.png")));
mapGlobalTableButton.setToolTipText("Link Table to Attributes");
mapGlobalTableButton.setBorder(null);
mapGlobalTableButton.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (mapGlobalTableButton.isEnabled())
guiTaskManagerServiceRef.execute(mapGlobalTableTaskFactoryService.createTaskIterator( browserTableModel.getAttributes() ));
}
});
}
mapGlobalTableButton.setEnabled(false);
return mapGlobalTableButton;
}
*/
private void createNewAttribute(final String type, boolean isShared) {
final String[] existingAttrs = getAttributeArray();
String newAttribName = null;
do {
newAttribName = JOptionPane.showInputDialog(this, "Please enter new column name: ",
"Create New " + type + " Column",
JOptionPane.QUESTION_MESSAGE);
if (newAttribName == null)
return;
if (Arrays.binarySearch(existingAttrs, newAttribName) >= 0) {
newAttribName = null;
JOptionPane.showMessageDialog(null,
"Column " + newAttribName + " already exists.",
"Error.", JOptionPane.ERROR_MESSAGE);
}
} while (newAttribName == null);
final CyTable attrs;
if(isShared) {
final CyNetwork network = appMgr.getCurrentNetwork();
if(network instanceof CySubNetwork) {
final CyRootNetwork rootNetwork = ((CySubNetwork) network).getRootNetwork();
CyTable sharedTable = null;
if(this.objType == CyNode.class)
sharedTable = rootNetwork.getSharedNodeTable();
else if(this.objType == CyEdge.class)
sharedTable = rootNetwork.getSharedEdgeTable();
else if(this.objType == CyNetwork.class)
sharedTable = rootNetwork.getSharedNetworkTable();
else {
throw new IllegalStateException("Object type is not valid. This should not happen.");
}
attrs = sharedTable;
} else {
throw new IllegalArgumentException("This is not a CySubNetwork and there is no shared table.");
}
} else {
attrs = browserTableModel.getAttributes();
}
if (type.equals("String"))
attrs.createColumn(newAttribName, String.class, false);
else if (type.equals("Floating Point"))
attrs.createColumn(newAttribName, Double.class, false);
else if (type.equals("Integer"))
attrs.createColumn(newAttribName, Integer.class, false);
else if (type.equals("Long Integer"))
attrs.createColumn(newAttribName, Long.class, false);
else if (type.equals("Boolean"))
attrs.createColumn(newAttribName, Boolean.class, false);
else if (type.equals("String List"))
attrs.createListColumn(newAttribName, String.class, false);
else if (type.equals("Floating Point List"))
attrs.createListColumn(newAttribName, Double.class, false);
else if (type.equals("Integer List"))
attrs.createListColumn(newAttribName, Integer.class, false);
else if (type.equals("Long Integer List"))
attrs.createListColumn(newAttribName, Long.class, false);
else if (type.equals("Boolean List"))
attrs.createListColumn(newAttribName, Boolean.class, false);
else
throw new IllegalArgumentException("unknown column type \"" + type + "\".");
}
}
| public AttributeBrowserToolBar(final CyServiceRegistrar serviceRegistrar,
final EquationCompiler compiler,
final DeleteTableTaskFactory deleteTableTaskFactory,
final DialogTaskManager guiTaskMgr,
final JComboBox tableChooser,
final Class<? extends CyIdentifiable> objType,
final CyApplicationManager appMgr) {//, final MapGlobalToLocalTableTaskFactory mapGlobalTableTaskFactoryService) {
this(serviceRegistrar, compiler, deleteTableTaskFactory, guiTaskMgr, tableChooser,
new JButton(), objType, appMgr);//, mapGlobalTableTaskFactoryService);
}
public AttributeBrowserToolBar(final CyServiceRegistrar serviceRegistrar,
final EquationCompiler compiler,
final DeleteTableTaskFactory deleteTableTaskFactory,
final DialogTaskManager guiTaskMgr,
final JComboBox tableChooser,
final JButton selectionModeButton,
final Class<? extends CyIdentifiable> objType,
final CyApplicationManager appMgr) {// , final MapGlobalToLocalTableTaskFactory mapGlobalTableTaskFactoryService) {
this.compiler = compiler;
this.selectionModeButton = selectionModeButton;
this.appMgr = appMgr;
// this.mapGlobalTableTaskFactoryService = mapGlobalTableTaskFactoryService;
this.components = new ArrayList<JComponent>();
this.tableChooser = tableChooser;
this.deleteTableTaskFactory = deleteTableTaskFactory;
this.guiTaskMgr = guiTaskMgr;
this.attrListModel = new AttributeListModel(null);
this.objType = objType;
serviceRegistrar.registerAllServices(attrListModel, new Properties());
selectionModeButton.setEnabled(false);
initializeGUI();
}
public void setBrowserTableModel(final BrowserTableModel browserTableModel) {
this.browserTableModel = browserTableModel;
attrListModel.setBrowserTableModel(browserTableModel);
updateEnableState();
}
@Override
public void popupMenuCanceled(PopupMenuEvent e) {
// TODO Auto-generated method stub
}
@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
// Update actual table
try {
if (attributeList != null) {
final Object[] selectedValues = attributeList.getSelectedValues();
final Set<String> visibleAttributes = new HashSet<String>();
for (final Object selectedValue : selectedValues)
visibleAttributes.add((String)selectedValue);
browserTableModel.setVisibleAttributeNames(visibleAttributes);
}
} catch (Exception ex) {
attributeList.clearSelection();
}
}
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
// Do nothing
}
public void updateEnableState() {
for (final JComponent comp : components) {
boolean enabled = browserTableModel != null;
if (comp == deleteTableButton /*|| comp == mapGlobalTableButton*/)
enabled &= objType == null;
comp.setEnabled(enabled);
}
}
protected void addComponent(final JComponent component, final ComponentPlacement placement) {
hToolBarGroup.addPreferredGap(placement).addComponent(component);
vToolBarGroup.addComponent(component, Alignment.CENTER, GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE);
components.add(component);
}
private void initializeGUI() {
setLayout(new BorderLayout());
add(getToolBar(), BorderLayout.CENTER);
getAttributeSelectionPopupMenu();
getJPopupMenu();
// Add buttons
if (selectionModeButton != null)
addComponent(selectionModeButton, ComponentPlacement.RELATED);
addComponent(getSelectButton(), ComponentPlacement.UNRELATED);
addComponent(getSelectAllButton(), ComponentPlacement.RELATED);
addComponent(getUnselectAllButton(), ComponentPlacement.RELATED);
addComponent(getNewButton(), ComponentPlacement.UNRELATED);
addComponent(getDeleteButton(), ComponentPlacement.RELATED);
addComponent(getDeleteTableButton(), ComponentPlacement.RELATED);
addComponent(getFunctionBuilderButton(), ComponentPlacement.UNRELATED);
// addComponent(getMapGlobalTableButton(). ComponentPlacement.UNRELATED);
if (tableChooser != null)
addComponent(tableChooser, ComponentPlacement.UNRELATED);
}
public String getToBeDeletedAttribute() {
return attrDeletionList.getSelectedValue().toString();
}
/**
* This method initializes jPopupMenu
*
* @return javax.swing.JPopupMenu
*/
private JPopupMenu getAttributeSelectionPopupMenu() {
if (attributeSelectionPopupMenu == null) {
attributeSelectionPopupMenu = new JPopupMenu();
attributeSelectionPopupMenu.add(getJScrollPane());
attributeSelectionPopupMenu.addPopupMenuListener(this);
}
return attributeSelectionPopupMenu;
}
/**
* This method initializes jScrollPane
*
* @return javax.swing.JScrollPane
*/
private JScrollPane getJScrollPane() {
if (jScrollPane == null) {
jScrollPane = new JScrollPane();
jScrollPane.setPreferredSize(new Dimension(250, 200));
jScrollPane.setViewportView(getSelectedAttributeList());
}
return jScrollPane;
}
/**
* This method initializes jPopupMenu
*
* @return javax.swing.JPopupMenu
*/
private JPopupMenu getJPopupMenu() {
if (createColumnMenu == null) {
createColumnMenu = new JPopupMenu();
//final JMenu column = new JMenu("New Column");
final JMenu columnRegular = new JMenu("New Single Column");
final JMenu columnList = new JMenu("New List Column");
columnRegular.add(getJMenuItemIntegerAttribute(false));
columnRegular.add(getJMenuItemLongIntegerAttribute(false));
columnRegular.add(getJMenuItemStringAttribute(false));
columnRegular.add(getJMenuItemFloatingPointAttribute(false));
columnRegular.add(getJMenuItemBooleanAttribute(false));
columnList.add(getJMenuItemIntegerListAttribute(false));
columnList.add(getJMenuItemLongIntegerListAttribute(false));
columnList.add(getJMenuItemStringListAttribute(false));
columnList.add(getJMenuItemFloatingPointListAttribute(false));
columnList.add(getJMenuItemBooleanListAttribute(false));
//column.add(columnRegular);
//column.add(columnList);
createColumnMenu.add(columnRegular);
createColumnMenu.add(columnList);
/*
// This is not valid for Global Table.
if (objType != null) {
final JMenu shared = new JMenu("New Shared Column");
final JMenu sharedRegular = new JMenu("Single");
final JMenu sharedList = new JMenu("List");
sharedRegular.add(getJMenuItemIntegerAttribute(true));
sharedRegular.add(getJMenuItemLongIntegerAttribute(true));
sharedRegular.add(getJMenuItemStringAttribute(true));
sharedRegular.add(getJMenuItemFloatingPointAttribute(true));
sharedRegular.add(getJMenuItemBooleanAttribute(true));
sharedList.add(getJMenuItemIntegerListAttribute(true));
sharedList.add(getJMenuItemLongIntegerListAttribute(true));
sharedList.add(getJMenuItemStringListAttribute(true));
sharedList.add(getJMenuItemFloatingPointListAttribute(true));
sharedList.add(getJMenuItemBooleanListAttribute(true));
shared.add(sharedRegular);
shared.add(sharedList);
createColumnMenu.add(shared);
}
*/
}
return createColumnMenu;
}
/**
* This method initializes jMenuItemStringAttribute
*
* @return javax.swing.JMenuItem
*/
private JMenuItem getJMenuItemStringAttribute(final boolean isShared) {
final JMenuItem jMenuItemStringAttribute = new JMenuItem();
jMenuItemStringAttribute.setText("String");
jMenuItemStringAttribute.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
createNewAttribute("String", isShared);
}
});
return jMenuItemStringAttribute;
}
/**
* This method initializes jMenuItemIntegerAttribute
*
* @return javax.swing.JMenuItem
*/
private JMenuItem getJMenuItemIntegerAttribute(final boolean isShared) {
final JMenuItem jMenuItemIntegerAttribute = new JMenuItem();
jMenuItemIntegerAttribute.setText("Integer");
jMenuItemIntegerAttribute.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
createNewAttribute("Integer", isShared);
}
});
return jMenuItemIntegerAttribute;
}
/**
* This method initializes jMenuItemLongIntegerAttribute
*
* @return javax.swing.JMenuItem
*/
private JMenuItem getJMenuItemLongIntegerAttribute(final boolean isShared) {
final JMenuItem jMenuItemLongIntegerAttribute = new JMenuItem();
jMenuItemLongIntegerAttribute.setText("Long Integer");
jMenuItemLongIntegerAttribute.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
createNewAttribute("Long Integer", isShared);
}
});
return jMenuItemLongIntegerAttribute;
}
/**
* This method initializes jMenuItemFloatingPointAttribute
*
* @return javax.swing.JMenuItem
*/
private JMenuItem getJMenuItemFloatingPointAttribute(final boolean isShared) {
final JMenuItem jMenuItemFloatingPointAttribute = new JMenuItem();
jMenuItemFloatingPointAttribute.setText("Floating Point");
jMenuItemFloatingPointAttribute.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
createNewAttribute("Floating Point", isShared);
}
});
return jMenuItemFloatingPointAttribute;
}
/**
* This method initializes jMenuItemBooleanAttribute
*
* @return javax.swing.JMenuItem
*/
private JMenuItem getJMenuItemBooleanAttribute(final boolean isShared) {
final JMenuItem jMenuItemBooleanAttribute = new JMenuItem();
jMenuItemBooleanAttribute.setText("Boolean");
jMenuItemBooleanAttribute.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
createNewAttribute("Boolean", isShared);
}
});
return jMenuItemBooleanAttribute;
}
/**
* This method initializes jMenuItemStringListAttribute
*
* @return javax.swing.JMenuItem
*/
private JMenuItem getJMenuItemStringListAttribute(final boolean isShared) {
final JMenuItem jMenuItemStringListAttribute = new JMenuItem();
jMenuItemStringListAttribute.setText("String");
jMenuItemStringListAttribute.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
createNewAttribute("String List", isShared);
}
});
return jMenuItemStringListAttribute;
}
/**
* This method initializes jMenuItemIntegerListAttribute
*
* @return javax.swing.JMenuItem
*/
private JMenuItem getJMenuItemIntegerListAttribute(final boolean isShared) {
final JMenuItem jMenuItemIntegerListAttribute = new JMenuItem();
jMenuItemIntegerListAttribute.setText("Integer");
jMenuItemIntegerListAttribute.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
createNewAttribute("Integer List", isShared);
}
});
return jMenuItemIntegerListAttribute;
}
/**
* This method initializes jMenuItemLongIntegerListAttribute
*
* @return javax.swing.JMenuItem
*/
private JMenuItem getJMenuItemLongIntegerListAttribute(final boolean isShared) {
final JMenuItem jMenuItemLongIntegerListAttribute = new JMenuItem();
jMenuItemLongIntegerListAttribute.setText("Long Integer");
jMenuItemLongIntegerListAttribute.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
createNewAttribute("Integer List", isShared);
}
});
return jMenuItemLongIntegerListAttribute;
}
/**
* This method initializes jMenuItemFloatingPointListAttribute
*
* @return javax.swing.JMenuItem
*/
private JMenuItem getJMenuItemFloatingPointListAttribute(final boolean isShared) {
final JMenuItem jMenuItemFloatingPointListAttribute = new JMenuItem();
jMenuItemFloatingPointListAttribute.setText("Floating Point");
jMenuItemFloatingPointListAttribute.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
createNewAttribute("Floating Point List", isShared);
}
});
return jMenuItemFloatingPointListAttribute;
}
/**
* This method initializes jMenuItemBooleanListAttribute
*
* @return javax.swing.JMenuItem
*/
private JMenuItem getJMenuItemBooleanListAttribute(final boolean isShared) {
final JMenuItem jMenuItemBooleanListAttribute = new JMenuItem();
jMenuItemBooleanListAttribute.setText("Boolean");
jMenuItemBooleanListAttribute.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
createNewAttribute("Boolean List", isShared);
}
});
return jMenuItemBooleanListAttribute;
}
/**
* This method initializes the toolBar
*
* @return javax.swing.JToolBar
*/
private JToolBar getToolBar() {
if (toolBar == null) {
toolBar = new JToolBar();
toolBar.setMargin(new Insets(0, 0, 3, 0));
toolBar.setPreferredSize(TOOLBAR_SIZE);
toolBar.setSize(TOOLBAR_SIZE);
toolBar.setFloatable(false);
toolBar.setOrientation(JToolBar.HORIZONTAL);
final GroupLayout buttonBarLayout = new GroupLayout(toolBar);
toolBar.setLayout(buttonBarLayout);
hToolBarGroup = buttonBarLayout.createSequentialGroup();
vToolBarGroup = buttonBarLayout.createParallelGroup(GroupLayout.Alignment.LEADING);
// Layout information.
buttonBarLayout.setHorizontalGroup(buttonBarLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(hToolBarGroup));
buttonBarLayout.setVerticalGroup(vToolBarGroup);
}
return toolBar;
}
/**
* This method initializes jButton
*
* @return javax.swing.JButton
*/
private JButton getSelectButton() {
if (selectButton == null) {
selectButton = new JButton();
selectButton.setBorder(null);
selectButton.setMargin(new Insets(0, 0, 0, 0));
selectButton.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/table-select-column-icon.png")));
selectButton.setToolTipText("Select Column");
selectButton.setBorder(null);
selectButton.setEnabled(false);
selectButton.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (browserTableModel == null)
return;
attributeList.setSelectedItems(browserTableModel.getVisibleAttributeNames());
attributeSelectionPopupMenu.show(e.getComponent(), e.getX(), e.getY());
}
});
}
return selectButton;
}
private JButton getFunctionBuilderButton() {
if (formulaBuilderButton == null) {
formulaBuilderButton = new JButton();
formulaBuilderButton.setBorder(null);
formulaBuilderButton.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/fx.png")));
formulaBuilderButton.setToolTipText("Function Builder");
formulaBuilderButton.setMargin(new Insets(1, 1, 1, 1));
formulaBuilderButton.setBorder(null);
formulaBuilderButton.setEnabled(false);
final JFrame rootFrame = (JFrame) SwingUtilities.getRoot(this);
formulaBuilderButton.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (browserTableModel == null)
return;
final JTable table = browserTableModel.getTable();
// Do not allow opening of the formula builder dialog
// while a cell is being edited!
if (table.getCellEditor() != null)
return;
final int cellRow = table.getSelectedRow();
final int cellColumn = table.getSelectedColumn();
if (cellRow == -1 || cellColumn == -1 || !browserTableModel.isCellEditable(cellRow, cellColumn)) {
JOptionPane.showMessageDialog(rootFrame, "Can't enter a formula w/o a selected cell.",
"Information", JOptionPane.INFORMATION_MESSAGE);
} else {
final String attrName = getAttribName(cellRow, cellColumn);
final Map<String, Class<?>> attribNameToTypeMap = new HashMap<String, Class<?>>();
final CyTable attrs = browserTableModel.getAttributes();
initAttribNameToTypeMap(attrs, attrName, attribNameToTypeMap);
final FormulaBuilderDialog formulaBuilderDialog = new FormulaBuilderDialog(compiler,
browserTableModel, rootFrame, attrName);
formulaBuilderDialog.setLocationRelativeTo(rootFrame);
formulaBuilderDialog.setVisible(true);
}
}
private void initAttribNameToTypeMap(final CyTable attrs, final String attrName,
final Map<String, Class<?>> attribNameToTypeMap) {
for (final CyColumn column : attrs.getColumns())
attribNameToTypeMap.put(column.getName(), column.getType());
attribNameToTypeMap.remove(attrName);
}
});
}
return formulaBuilderButton;
}
private String getAttribName(final int cellRow, final int cellColumn) {
return browserTableModel.getColumnName(cellColumn);
}
private JButton getDeleteButton() {
if (deleteAttributeButton == null) {
deleteAttributeButton = new JButton();
deleteAttributeButton.setBorder(null);
deleteAttributeButton.setMargin(new Insets(0, 0, 0, 0));
deleteAttributeButton.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/stock_delete.png")));
deleteAttributeButton.setToolTipText("Delete Column...");
deleteAttributeButton.setBorder(null);
// Create pop-up window for deletion
deleteAttributeButton.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (deleteAttributeButton.isEnabled())
removeAttribute(e);
}
});
deleteAttributeButton.setEnabled(false);
}
return deleteAttributeButton;
}
private JButton getDeleteTableButton() {
if (deleteTableButton == null) {
deleteTableButton = new JButton();
deleteTableButton.setBorder(null);
deleteTableButton.setMargin(new Insets(0, 0, 0, 0));
deleteTableButton.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/table_delete.png")));
deleteTableButton.setToolTipText("Delete Table...");
deleteTableButton.setBorder(null);
// Create pop-up window for deletion
deleteTableButton.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (deleteTableButton.isEnabled())
removeTable(e);
}
});
deleteTableButton.setEnabled(false);
}
return deleteTableButton;
}
private JButton getSelectAllButton() {
if (selectAllAttributesButton == null) {
selectAllAttributesButton = new JButton();
selectAllAttributesButton.setBorder(null);
selectAllAttributesButton.setMargin(new Insets(0, 0, 0, 0));
selectAllAttributesButton.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/select_all.png")));
selectAllAttributesButton.setToolTipText("Select All Columns");
selectAllAttributesButton.setBorder(null);
selectAllAttributesButton.setEnabled(false);
selectAllAttributesButton.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
try {
final CyTable table = browserTableModel.getAttributes();
final Set<String> allAttrNames = new HashSet<String>();
for (final CyColumn column : table.getColumns())
allAttrNames.add(column.getName());
browserTableModel.setVisibleAttributeNames(allAttrNames);
// Resize column
ColumnResizer.adjustColumnPreferredWidths(browserTableModel.getTable());
} catch (Exception ex) {
attributeList.clearSelection();
}
}
});
}
return selectAllAttributesButton;
}
private JButton getUnselectAllButton() {
if (unselectAllAttributesButton == null) {
unselectAllAttributesButton = new JButton();
unselectAllAttributesButton.setBorder(null);
unselectAllAttributesButton.setMargin(new Insets(0, 0, 0, 0));
unselectAllAttributesButton.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/unselect_all.png")));
unselectAllAttributesButton.setToolTipText("Unselect All Columns");
unselectAllAttributesButton.setBorder(null);
unselectAllAttributesButton.setEnabled(false);
unselectAllAttributesButton.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
try {
browserTableModel.setVisibleAttributeNames(new HashSet<String>());
} catch (Exception ex) {
attributeList.clearSelection();
}
}
});
}
return unselectAllAttributesButton;
}
private void removeAttribute(final MouseEvent e) {
final String[] attrArray = getAttributeArray();
final JFrame frame = (JFrame)SwingUtilities.getRoot(this);
final DeletionDialog dDialog = new DeletionDialog(frame, browserTableModel.getAttributes());
dDialog.pack();
dDialog.setLocationRelativeTo(toolBar);
dDialog.setVisible(true);
}
private void removeTable(final MouseEvent e) {
final CyTable table = browserTableModel.getAttributes();
if (table.getMutability() == CyTable.Mutability.MUTABLE) {
String title = "Please confirm this action";
String msg = "Are you sure you want to delete this table?";
int _confirmValue = JOptionPane.showConfirmDialog(this, msg, title, JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE);
// if user selects yes delete the table
if (_confirmValue == JOptionPane.OK_OPTION)
guiTaskMgr.execute(deleteTableTaskFactory.createTaskIterator(table));
} else if (table.getMutability() == CyTable.Mutability.PERMANENTLY_IMMUTABLE) {
String title = "Error";
String msg = "Can not delete this table, it is PERMANENTLY_IMMUTABLE";
JOptionPane.showMessageDialog(this, msg, title, JOptionPane.ERROR_MESSAGE);
} else if (table.getMutability() == CyTable.Mutability.IMMUTABLE_DUE_TO_VIRT_COLUMN_REFERENCES) {
String title = "Error";
String msg = "Can not delete this table, it is IMMUTABLE_DUE_TO_VIRT_COLUMN_REFERENCES";
JOptionPane.showMessageDialog(this, msg, title, JOptionPane.ERROR_MESSAGE);
}
}
private JList getSelectedAttributeList() {
if (attributeList == null) {
attributeList = new CheckBoxJList();
attributeList.setModel(attrListModel);
attributeList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
attributeList.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
attributeSelectionPopupMenu.setVisible(false);
}
}
});
}
return attributeList;
}
private String[] getAttributeArray() {
final CyTable attrs = browserTableModel.getAttributes();
final Collection<CyColumn> columns = attrs.getColumns();
final String[] attributeArray = new String[columns.size() - 1];
int index = 0;
for (final CyColumn column : columns) {
if (!column.isPrimaryKey())
attributeArray[index++] = column.getName();
}
Arrays.sort(attributeArray);
return attributeArray;
}
/**
* This method initializes createNewAttributeButton
*
* @return javax.swing.JButton
*/
private JButton getNewButton() {
if (createNewAttributeButton == null) {
createNewAttributeButton = new JButton();
createNewAttributeButton.setBorder(null);
createNewAttributeButton.setFont(new java.awt.Font("Dialog", java.awt.Font.PLAIN, 12));
createNewAttributeButton.setHorizontalTextPosition(SwingConstants.CENTER);
createNewAttributeButton.setMargin(new Insets(0, 0, 0, 0));
createNewAttributeButton.setToolTipText("Create New Column");
createNewAttributeButton.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/stock_new.png")));
createNewAttributeButton.setBorder(null);
createNewAttributeButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (browserTableModel != null)
createColumnMenu.show(e.getComponent(), e.getX(), e.getY());
}
});
createNewAttributeButton.setEnabled(false);
}
return createNewAttributeButton;
}
/*
private JButton getMapGlobalTableButton() {
if (mapGlobalTableButton == null) {
mapGlobalTableButton = new JButton();
mapGlobalTableButton.setBorder(null);
mapGlobalTableButton.setMargin(new Insets(0, 0, 0, 0));
mapGlobalTableButton.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/table_map.png")));
mapGlobalTableButton.setToolTipText("Link Table to Attributes");
mapGlobalTableButton.setBorder(null);
mapGlobalTableButton.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (mapGlobalTableButton.isEnabled())
guiTaskManagerServiceRef.execute(mapGlobalTableTaskFactoryService.createTaskIterator( browserTableModel.getAttributes() ));
}
});
}
mapGlobalTableButton.setEnabled(false);
return mapGlobalTableButton;
}
*/
private void createNewAttribute(final String type, boolean isShared) {
final String[] existingAttrs = getAttributeArray();
String newAttribName = null;
do {
newAttribName = JOptionPane.showInputDialog(this, "Please enter new column name: ",
"Create New " + type + " Column",
JOptionPane.QUESTION_MESSAGE);
if (newAttribName == null)
return;
if (Arrays.binarySearch(existingAttrs, newAttribName) >= 0) {
newAttribName = null;
JOptionPane.showMessageDialog(null,
"Column " + newAttribName + " already exists.",
"Error.", JOptionPane.ERROR_MESSAGE);
}
} while (newAttribName == null);
final CyTable attrs;
if(isShared) {
final CyNetwork network = appMgr.getCurrentNetwork();
if(network instanceof CySubNetwork) {
final CyRootNetwork rootNetwork = ((CySubNetwork) network).getRootNetwork();
CyTable sharedTable = null;
if(this.objType == CyNode.class)
sharedTable = rootNetwork.getSharedNodeTable();
else if(this.objType == CyEdge.class)
sharedTable = rootNetwork.getSharedEdgeTable();
else if(this.objType == CyNetwork.class)
sharedTable = rootNetwork.getSharedNetworkTable();
else {
throw new IllegalStateException("Object type is not valid. This should not happen.");
}
attrs = sharedTable;
} else {
throw new IllegalArgumentException("This is not a CySubNetwork and there is no shared table.");
}
} else {
attrs = browserTableModel.getAttributes();
}
if (type.equals("String"))
attrs.createColumn(newAttribName, String.class, false);
else if (type.equals("Floating Point"))
attrs.createColumn(newAttribName, Double.class, false);
else if (type.equals("Integer"))
attrs.createColumn(newAttribName, Integer.class, false);
else if (type.equals("Long Integer"))
attrs.createColumn(newAttribName, Long.class, false);
else if (type.equals("Boolean"))
attrs.createColumn(newAttribName, Boolean.class, false);
else if (type.equals("String List"))
attrs.createListColumn(newAttribName, String.class, false);
else if (type.equals("Floating Point List"))
attrs.createListColumn(newAttribName, Double.class, false);
else if (type.equals("Integer List"))
attrs.createListColumn(newAttribName, Integer.class, false);
else if (type.equals("Long Integer List"))
attrs.createListColumn(newAttribName, Long.class, false);
else if (type.equals("Boolean List"))
attrs.createListColumn(newAttribName, Boolean.class, false);
else
throw new IllegalArgumentException("unknown column type \"" + type + "\".");
}
}
|
diff --git a/src/javachallenge/graphics/GraphicTest.java b/src/javachallenge/graphics/GraphicTest.java
index d366b95..2368446 100644
--- a/src/javachallenge/graphics/GraphicTest.java
+++ b/src/javachallenge/graphics/GraphicTest.java
@@ -1,74 +1,74 @@
package javachallenge.graphics;
import java.awt.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.util.Scanner;
import javachallenge.common.Direction;
import javachallenge.graphics.GraphicClient;
import javachallenge.graphics.components.ProgressBar;
import javachallenge.graphics.components.ScoreBar;
import javachallenge.graphics.util.Position;
import javachallenge.server.Map;
import javachallenge.server.Game;
import javax.swing.*;
public class GraphicTest {
public static void main(String[] args) throws Exception{
Map map=Map.load("map/m1.txt");
- GraphicClient client=new GraphicClient(map,4);
+ GraphicClient client=new GraphicClient(map);
//GraphicClient client = new GraphicClient(30, 14, new Position[] {});
/*JFrame frame=new JFrame();
frame.setLayout(null);
frame.getContentPane().setPreferredSize(new Dimension(400, 400));
//final ProgressBar bar=new ProgressBar(10,10,100,20, Color.green,Color.red,0);
ScoreBar bar=new ScoreBar(10,10,100,50,Color.green,Color.red,"kire khar") ;
frame.pack();
frame.setVisible(true);
frame.add(bar);*/
Scanner scanner=new Scanner(System.in);
while (true)
{
String com=scanner.next();
if (com.startsWith("s")) // spawn
{
int id=scanner.nextInt(),x=scanner.nextInt(),y=scanner.nextInt();
client.spawn(id,new Position(x,y));
}
else if (com.startsWith("k")) // kill
{
int id=scanner.nextInt();
client.die(id);
}
else if (com.startsWith("m")) // move
{
int id=scanner.nextInt(),pos=scanner.nextInt();
client.move(id,Direction.values()[pos]);
}
else if (com.startsWith("f")) { // obtain flag
int id = scanner.nextInt();
client.obtainFlag (id);
}
else if (com.startsWith("h")) { // help
System.out.println("h[elp]");
System.out.println("e[xit]");
System.out.println("s[pawn] id x y");
System.out.println("k[ill] id");
System.out.println("m[ove] id dir");
System.out.println("f[lag] id");
System.out.println(client.units);
System.out.println(client.flags);
}
else if (com.startsWith("l")) {
String s = scanner.next();
client.log(s);
}
else if (com.startsWith("e")) // exit
break;
}
scanner.close();
}
}
| true | true | public static void main(String[] args) throws Exception{
Map map=Map.load("map/m1.txt");
GraphicClient client=new GraphicClient(map,4);
//GraphicClient client = new GraphicClient(30, 14, new Position[] {});
/*JFrame frame=new JFrame();
frame.setLayout(null);
frame.getContentPane().setPreferredSize(new Dimension(400, 400));
//final ProgressBar bar=new ProgressBar(10,10,100,20, Color.green,Color.red,0);
ScoreBar bar=new ScoreBar(10,10,100,50,Color.green,Color.red,"kire khar") ;
frame.pack();
frame.setVisible(true);
frame.add(bar);*/
Scanner scanner=new Scanner(System.in);
while (true)
{
String com=scanner.next();
if (com.startsWith("s")) // spawn
{
int id=scanner.nextInt(),x=scanner.nextInt(),y=scanner.nextInt();
client.spawn(id,new Position(x,y));
}
else if (com.startsWith("k")) // kill
{
int id=scanner.nextInt();
client.die(id);
}
else if (com.startsWith("m")) // move
{
int id=scanner.nextInt(),pos=scanner.nextInt();
client.move(id,Direction.values()[pos]);
}
else if (com.startsWith("f")) { // obtain flag
int id = scanner.nextInt();
client.obtainFlag (id);
}
else if (com.startsWith("h")) { // help
System.out.println("h[elp]");
System.out.println("e[xit]");
System.out.println("s[pawn] id x y");
System.out.println("k[ill] id");
System.out.println("m[ove] id dir");
System.out.println("f[lag] id");
System.out.println(client.units);
System.out.println(client.flags);
}
else if (com.startsWith("l")) {
String s = scanner.next();
client.log(s);
}
else if (com.startsWith("e")) // exit
break;
}
scanner.close();
}
| public static void main(String[] args) throws Exception{
Map map=Map.load("map/m1.txt");
GraphicClient client=new GraphicClient(map);
//GraphicClient client = new GraphicClient(30, 14, new Position[] {});
/*JFrame frame=new JFrame();
frame.setLayout(null);
frame.getContentPane().setPreferredSize(new Dimension(400, 400));
//final ProgressBar bar=new ProgressBar(10,10,100,20, Color.green,Color.red,0);
ScoreBar bar=new ScoreBar(10,10,100,50,Color.green,Color.red,"kire khar") ;
frame.pack();
frame.setVisible(true);
frame.add(bar);*/
Scanner scanner=new Scanner(System.in);
while (true)
{
String com=scanner.next();
if (com.startsWith("s")) // spawn
{
int id=scanner.nextInt(),x=scanner.nextInt(),y=scanner.nextInt();
client.spawn(id,new Position(x,y));
}
else if (com.startsWith("k")) // kill
{
int id=scanner.nextInt();
client.die(id);
}
else if (com.startsWith("m")) // move
{
int id=scanner.nextInt(),pos=scanner.nextInt();
client.move(id,Direction.values()[pos]);
}
else if (com.startsWith("f")) { // obtain flag
int id = scanner.nextInt();
client.obtainFlag (id);
}
else if (com.startsWith("h")) { // help
System.out.println("h[elp]");
System.out.println("e[xit]");
System.out.println("s[pawn] id x y");
System.out.println("k[ill] id");
System.out.println("m[ove] id dir");
System.out.println("f[lag] id");
System.out.println(client.units);
System.out.println(client.flags);
}
else if (com.startsWith("l")) {
String s = scanner.next();
client.log(s);
}
else if (com.startsWith("e")) // exit
break;
}
scanner.close();
}
|
diff --git a/src/main/java/com/eyeq/pivot4j/transform/impl/ChangeSlicerImpl.java b/src/main/java/com/eyeq/pivot4j/transform/impl/ChangeSlicerImpl.java
index 49e80dbc..7a4c6336 100644
--- a/src/main/java/com/eyeq/pivot4j/transform/impl/ChangeSlicerImpl.java
+++ b/src/main/java/com/eyeq/pivot4j/transform/impl/ChangeSlicerImpl.java
@@ -1,252 +1,253 @@
/*
* ====================================================================
* This software is subject to the terms of the Common Public License
* Agreement, available at the following URL:
* http://www.opensource.org/licenses/cpl.html .
* You must accept the terms of that agreement to use this software.
* ====================================================================
*/
package com.eyeq.pivot4j.transform.impl;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.olap4j.CellSet;
import org.olap4j.CellSetAxis;
import org.olap4j.Position;
import org.olap4j.metadata.Hierarchy;
import org.olap4j.metadata.Member;
import com.eyeq.pivot4j.mdx.Exp;
import com.eyeq.pivot4j.mdx.FunCall;
import com.eyeq.pivot4j.mdx.MemberExp;
import com.eyeq.pivot4j.mdx.Syntax;
import com.eyeq.pivot4j.query.QueryAdapter;
import com.eyeq.pivot4j.transform.AbstractTransform;
import com.eyeq.pivot4j.transform.ChangeSlicer;
public class ChangeSlicerImpl extends AbstractTransform implements ChangeSlicer {
/**
* @param queryAdapter
*/
public ChangeSlicerImpl(QueryAdapter queryAdapter) {
super(queryAdapter);
}
/**
* @see com.eyeq.pivot4j.transform.ChangeSlicer#getHierarchies()
*/
@Override
public List<Hierarchy> getHierarchies() {
if (!getModel().isInitialized()) {
return Collections.emptyList();
}
CellSet cellSet = getModel().getCellSet();
CellSetAxis slicer = cellSet.getFilterAxis();
return slicer.getAxisMetaData().getHierarchies();
}
/**
* @see com.eyeq.pivot4j.transform.ChangeSlicer#getSlicer()
*/
public List<Member> getSlicer() {
if (!getModel().isInitialized()) {
return Collections.emptyList();
}
// Use result rather than query
CellSet cellSet = getModel().getCellSet();
CellSetAxis slicer = cellSet.getFilterAxis();
List<Position> positions = slicer.getPositions();
List<Member> members = new ArrayList<Member>();
for (Position position : positions) {
List<Member> posMembers = position.getMembers();
for (Member posMember : posMembers) {
if (!members.contains(posMember)) {
members.add(posMember);
}
}
}
return members;
}
/**
* @see com.eyeq.pivot4j.transform.ChangeSlicer#getSlicer(org.olap4j.metadata
* .Hierarchy)
*/
@Override
public List<Member> getSlicer(Hierarchy hierarchy) {
if (hierarchy == null) {
return getSlicer();
}
CellSet cellSet = getModel().getCellSet();
CellSetAxis slicer = cellSet.getFilterAxis();
List<Position> positions = slicer.getPositions();
List<Member> members = new ArrayList<Member>();
for (Position position : positions) {
List<Member> posMembers = position.getMembers();
for (Member posMember : posMembers) {
if (posMember.getHierarchy().equals(hierarchy)
&& !members.contains(posMember)) {
members.add(posMember);
}
}
}
return members;
}
/**
* @see com.eyeq.pivot4j.transform.ChangeSlicer#setSlicer(java.util.List)
*/
public void setSlicer(List<Member> members) {
Exp exp = null;
if (members != null && !members.isEmpty()) {
List<Hierarchy> hierarchies = new ArrayList<Hierarchy>(
members.size());
Map<Hierarchy, List<Member>> memberMap = new HashMap<Hierarchy, List<Member>>();
for (Member member : members) {
Hierarchy hierarchy = member.getHierarchy();
if (!hierarchies.contains(hierarchy)) {
hierarchies.add(hierarchy);
}
List<Member> hierarchyMembers = memberMap.get(hierarchy);
if (hierarchyMembers == null) {
hierarchyMembers = new ArrayList<Member>(members.size());
memberMap.put(hierarchy, hierarchyMembers);
}
hierarchyMembers.add(member);
}
if (hierarchies.size() == 1) {
Hierarchy hierarchy = hierarchies.get(0);
exp = createMemberSetExpression(hierarchy,
memberMap.get(hierarchy));
} else {
Exp[] sets = new Exp[hierarchies.size()];
int index = 0;
for (Hierarchy hierarchy : hierarchies) {
Exp set = createMemberSetExpression(hierarchy,
memberMap.get(hierarchy));
if (set != null) {
sets[index++] = set;
}
}
exp = new FunCall("CrossJoin", sets, Syntax.Function);
}
}
getQueryAdapter().changeSlicer(exp);
}
/**
* @see com.eyeq.pivot4j.transform.ChangeSlicer#setSlicer(org.olap4j.metadata
* .Hierarchy, java.util.List)
*/
@Override
public void setSlicer(Hierarchy hierarchy, List<Member> members) {
if (hierarchy == null) {
setSlicer(members);
return;
}
Exp exp = null;
List<Hierarchy> hierarchies = new ArrayList<Hierarchy>();
Map<Hierarchy, List<Member>> memberMap = new HashMap<Hierarchy, List<Member>>();
List<Member> membersOnSlicer = getSlicer();
if (membersOnSlicer != null && !membersOnSlicer.isEmpty()) {
for (Member member : membersOnSlicer) {
Hierarchy memberHierarchy = member.getHierarchy();
if (!hierarchies.contains(memberHierarchy)) {
hierarchies.add(memberHierarchy);
}
if (!memberHierarchy.equals(hierarchy)) {
List<Member> hierarchyMembers = memberMap
.get(memberHierarchy);
if (hierarchyMembers == null) {
hierarchyMembers = new ArrayList<Member>();
memberMap.put(memberHierarchy, hierarchyMembers);
}
hierarchyMembers.add(member);
}
}
}
if (members == null || members.isEmpty()) {
hierarchies.remove(hierarchy);
} else {
if (!hierarchies.contains(hierarchy)) {
hierarchies.add(hierarchy);
}
memberMap.put(hierarchy, members);
}
- if (hierarchies.size() == 1) {
+ int size = hierarchies.size();
+ if (size == 1) {
Hierarchy hier = hierarchies.get(0);
exp = createMemberSetExpression(hier, memberMap.get(hier));
- } else {
+ } else if (size > 1) {
Exp[] sets = new Exp[hierarchies.size()];
int index = 0;
for (Hierarchy hier : hierarchies) {
Exp set = createMemberSetExpression(hier, memberMap.get(hier));
if (set != null) {
sets[index++] = set;
}
}
exp = new FunCall("CrossJoin", sets, Syntax.Function);
}
getQueryAdapter().changeSlicer(exp);
}
/**
* @param hierachy
* @param members
* @return
*/
protected Exp createMemberSetExpression(Hierarchy hierachy,
List<Member> members) {
if (members == null || members.isEmpty()) {
return null;
} else if (members.size() == 1) {
return new MemberExp(members.get(0));
}
List<Exp> expressions = new ArrayList<Exp>(members.size());
for (Member member : members) {
expressions.add(new MemberExp(member));
}
return new FunCall("{}",
expressions.toArray(new Exp[expressions.size()]), Syntax.Braces);
}
}
| false | true | public void setSlicer(Hierarchy hierarchy, List<Member> members) {
if (hierarchy == null) {
setSlicer(members);
return;
}
Exp exp = null;
List<Hierarchy> hierarchies = new ArrayList<Hierarchy>();
Map<Hierarchy, List<Member>> memberMap = new HashMap<Hierarchy, List<Member>>();
List<Member> membersOnSlicer = getSlicer();
if (membersOnSlicer != null && !membersOnSlicer.isEmpty()) {
for (Member member : membersOnSlicer) {
Hierarchy memberHierarchy = member.getHierarchy();
if (!hierarchies.contains(memberHierarchy)) {
hierarchies.add(memberHierarchy);
}
if (!memberHierarchy.equals(hierarchy)) {
List<Member> hierarchyMembers = memberMap
.get(memberHierarchy);
if (hierarchyMembers == null) {
hierarchyMembers = new ArrayList<Member>();
memberMap.put(memberHierarchy, hierarchyMembers);
}
hierarchyMembers.add(member);
}
}
}
if (members == null || members.isEmpty()) {
hierarchies.remove(hierarchy);
} else {
if (!hierarchies.contains(hierarchy)) {
hierarchies.add(hierarchy);
}
memberMap.put(hierarchy, members);
}
if (hierarchies.size() == 1) {
Hierarchy hier = hierarchies.get(0);
exp = createMemberSetExpression(hier, memberMap.get(hier));
} else {
Exp[] sets = new Exp[hierarchies.size()];
int index = 0;
for (Hierarchy hier : hierarchies) {
Exp set = createMemberSetExpression(hier, memberMap.get(hier));
if (set != null) {
sets[index++] = set;
}
}
exp = new FunCall("CrossJoin", sets, Syntax.Function);
}
getQueryAdapter().changeSlicer(exp);
}
| public void setSlicer(Hierarchy hierarchy, List<Member> members) {
if (hierarchy == null) {
setSlicer(members);
return;
}
Exp exp = null;
List<Hierarchy> hierarchies = new ArrayList<Hierarchy>();
Map<Hierarchy, List<Member>> memberMap = new HashMap<Hierarchy, List<Member>>();
List<Member> membersOnSlicer = getSlicer();
if (membersOnSlicer != null && !membersOnSlicer.isEmpty()) {
for (Member member : membersOnSlicer) {
Hierarchy memberHierarchy = member.getHierarchy();
if (!hierarchies.contains(memberHierarchy)) {
hierarchies.add(memberHierarchy);
}
if (!memberHierarchy.equals(hierarchy)) {
List<Member> hierarchyMembers = memberMap
.get(memberHierarchy);
if (hierarchyMembers == null) {
hierarchyMembers = new ArrayList<Member>();
memberMap.put(memberHierarchy, hierarchyMembers);
}
hierarchyMembers.add(member);
}
}
}
if (members == null || members.isEmpty()) {
hierarchies.remove(hierarchy);
} else {
if (!hierarchies.contains(hierarchy)) {
hierarchies.add(hierarchy);
}
memberMap.put(hierarchy, members);
}
int size = hierarchies.size();
if (size == 1) {
Hierarchy hier = hierarchies.get(0);
exp = createMemberSetExpression(hier, memberMap.get(hier));
} else if (size > 1) {
Exp[] sets = new Exp[hierarchies.size()];
int index = 0;
for (Hierarchy hier : hierarchies) {
Exp set = createMemberSetExpression(hier, memberMap.get(hier));
if (set != null) {
sets[index++] = set;
}
}
exp = new FunCall("CrossJoin", sets, Syntax.Function);
}
getQueryAdapter().changeSlicer(exp);
}
|
diff --git a/src/haven/MCache.java b/src/haven/MCache.java
index 94b667e0..f890345b 100644
--- a/src/haven/MCache.java
+++ b/src/haven/MCache.java
@@ -1,403 +1,403 @@
/*
* This file is part of the Haven & Hearth game client.
* Copyright (C) 2009 Fredrik Tolf <[email protected]>, and
* Björn Johannessen <[email protected]>
*
* Redistribution and/or modification of this file is subject to the
* terms of the GNU Lesser 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.
*
* Other parts of this source tree adhere to other copying
* rights. Please see the file `COPYING' in the root directory of the
* source tree for details.
*
* A copy the GNU Lesser General Public License is distributed along
* with the source tree of which this file is a part in the file
* `doc/LPGL-3'. If it is missing for any reason, please see the Free
* Software Foundation's website at <http://www.fsf.org/>, or write
* to the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307 USA
*/
package haven;
import java.util.*;
import haven.Resource.Tileset;
import haven.Resource.Tile;
import java.util.zip.Inflater;
public class MCache {
public static final Coord tilesz = new Coord(11, 11);
public static final Coord cmaps = new Coord(100, 100);
private final Resource[] sets = new Resource[256];
private final Tileset[] csets = new Tileset[256];
Map<Coord, Request> req = new HashMap<Coord, Request>();
Map<Coord, Grid> grids = new HashMap<Coord, Grid>();
Session sess;
Set<Overlay> ols = new HashSet<Overlay>();
Random gen = new Random();
Map<Integer, Defrag> fragbufs = new TreeMap<Integer, Defrag>();
public static class LoadingMap extends RuntimeException {
private LoadingMap() {}
}
private static class Request {
private long lastreq = 0;
private int reqs = 0;
}
public class Overlay {
Coord c1, c2;
int mask;
public Overlay(Coord c1, Coord c2, int mask) {
this.c1 = c1;
this.c2 = c2;
this.mask = mask;
ols.add(this);
}
public void destroy() {
ols.remove(this);
}
public void update(Coord c1, Coord c2) {
this.c1 = c1;
this.c2 = c2;
}
}
public class Grid {
public final int tiles[] = new int[cmaps.x * cmaps.y];
public final int z[] = new int[cmaps.x * cmaps.y];
public final int ol[] = new int[cmaps.x * cmaps.y];
private Collection<Gob> fo;
public final Coord gc, ul;
public final long id;
String mnm;
private class Flavobj extends Gob {
private Flavobj(Coord c) {
super(sess.glob, c);
}
public Random mkrandoom() {
Random r = new Random(Grid.this.id);
r.setSeed(r.nextInt() ^ rc.x);
r.setSeed(r.nextInt() ^ rc.y);
return(r);
}
}
public Grid(Coord gc) {
this.gc = gc;
this.ul = gc.mul(cmaps);
id = (((long)gc.x) << 32l) ^ ((long)gc.y);
}
public int gettile(Coord tc) {
return(tiles[tc.x + (tc.y * cmaps.x)]);
}
public int getz(Coord tc) {
return(z[tc.x + (tc.y * cmaps.x)]);
}
public int getol(Coord tc) {
return(ol[tc.x + (tc.y * cmaps.x)]);
}
private void makeflavor() {
Collection<Gob> fo = new LinkedList<Gob>();
fo.clear();
Coord c = new Coord(0, 0);
Coord tc = gc.mul(cmaps);
int i = 0;
Random rnd = new Random(id);
for(c.y = 0; c.y < cmaps.x; c.y++) {
for(c.x = 0; c.x < cmaps.y; c.x++, i++) {
Tileset set = tileset(tiles[i]);
if(set.flavobjs.size() > 0) {
if(rnd.nextInt(set.flavprob) == 0) {
Resource r = set.flavobjs.pick(rnd);
Gob g = new Flavobj(c.add(tc).mul(tilesz));
g.setattr(new ResDrawable(g, r));
fo.add(g);
}
}
}
}
this.fo = fo;
}
public Collection<Gob> getfo() {
if(fo == null)
makeflavor();
return(fo);
}
}
public MCache(Session sess) {
this.sess = sess;
}
public void invalidate(Coord cc) {
synchronized(req) {
if(req.get(cc) == null)
req.put(cc, new Request());
}
}
public void invalblob(Message msg) {
int type = msg.uint8();
if(type == 0) {
invalidate(msg.coord());
} else if(type == 1) {
Coord ul = msg.coord();
Coord lr = msg.coord();
trim(ul, lr);
} else if(type == 2) {
trimall();
}
}
private Grid cached = null;
public Grid getgrid(Coord gc) {
synchronized(grids) {
if((cached == null) || !cached.gc.equals(cached)) {
cached = grids.get(gc);
if(cached == null) {
request(gc);
throw(new LoadingMap());
}
}
return(cached);
}
}
public Grid getgridt(Coord tc) {
return(getgrid(tc.div(cmaps)));
}
public int gettile(Coord tc) {
Grid g = getgridt(tc);
return(g.gettile(tc.sub(g.ul)));
}
public int getz(Coord tc) {
Grid g = getgridt(tc);
return(g.getz(tc.sub(g.ul)));
}
public float getcz(float px, float py) {
float tw = tilesz.x, th = tilesz.y;
Coord ul = new Coord((int)(px / tw), (int)(py / th));
float sx = (px % tw) / tw;
float sy = (py % th) / th;
return(((1.0f - sy) * (((1.0f - sx) * getz(ul)) + (sx * getz(ul.add(1, 0))))) +
(sy * (((1.0f - sx) * getz(ul.add(0, 1))) + (sx * getz(ul.add(1, 1))))));
}
public float getcz(Coord pc) {
return(getcz(pc.x, pc.y));
}
public int getol(Coord tc) {
Grid g = getgridt(tc);
int ol = g.getol(tc.sub(g.ul));
for(Overlay lol : ols) {
if(tc.isect(lol.c1, lol.c2.add(lol.c1.inv()).add(new Coord(1, 1))))
ol |= lol.mask;
}
return(ol);
}
public void mapdata2(Message msg) {
Coord c = msg.coord();
String mmname = msg.string().intern();
if(mmname.equals(""))
mmname = null;
int[] pfl = new int[256];
while(true) {
int pidx = msg.uint8();
if(pidx == 255)
break;
pfl[pidx] = msg.uint8();
}
Message blob = new Message(0);
{
Inflater z = new Inflater();
z.setInput(msg.blob, msg.off, msg.blob.length - msg.off);
byte[] buf = new byte[10000];
while(true) {
try {
int len;
if((len = z.inflate(buf)) == 0) {
if(!z.finished())
throw(new RuntimeException("Got unterminated map blob"));
break;
}
blob.addbytes(buf, 0, len);
} catch(java.util.zip.DataFormatException e) {
throw(new RuntimeException("Got malformed map blob", e));
}
}
}
synchronized(grids) {
synchronized(req) {
if(req.containsKey(c)) {
Grid g = new Grid(c);
g.mnm = mmname;
for(int i = 0; i < g.tiles.length; i++)
g.tiles[i] = blob.uint8();
- for(int i = 0, y = 0; y < cmaps.y; y++, i++) {
- for(int x = 0; x < cmaps.x; x++)
- g.z[i] = (int)(Math.sin((g.ul.x + x) / 2.0) + Math.sin((g.ul.y + y) / 2.0));
+ for(int i = 0, y = 0; y < cmaps.y; y++) {
+ for(int x = 0; x < cmaps.x; x++, i++)
+ g.z[i] = (int)((Math.sin((g.ul.x + x) / 2.0) + Math.sin((g.ul.y + y) / 2.0)) * 16);
}
for(int i = 0; i < g.ol.length; i++)
g.ol[i] = 0;
while(true) {
int pidx = blob.uint8();
if(pidx == 255)
break;
int fl = pfl[pidx];
int type = blob.uint8();
Coord c1 = new Coord(blob.uint8(), blob.uint8());
Coord c2 = new Coord(blob.uint8(), blob.uint8());
int ol;
if(type == 0) {
if((fl & 1) == 1)
ol = 2;
else
ol = 1;
} else if(type == 1) {
if((fl & 1) == 1)
ol = 8;
else
ol = 4;
} else {
throw(new RuntimeException("Unknown plot type " + type));
}
for(int y = c1.y; y <= c2.y; y++) {
for(int x = c1.x; x <= c2.x; x++) {
g.ol[x + (y * cmaps.x)] |= ol;
}
}
}
req.remove(c);
if(grids.remove(c) == cached)
cached = null;
grids.put(c, g);
}
}
}
}
public void mapdata(Message msg) {
long now = System.currentTimeMillis();
int pktid = msg.int32();
int off = msg.uint16();
int len = msg.uint16();
Defrag fragbuf;
synchronized(fragbufs) {
if((fragbuf = fragbufs.get(pktid)) == null) {
fragbuf = new Defrag(len);
fragbufs.put(pktid, fragbuf);
}
fragbuf.add(msg.blob, 8, msg.blob.length - 8, off);
fragbuf.last = now;
if(fragbuf.done()) {
mapdata2(fragbuf.msg());
fragbufs.remove(pktid);
}
/* Clean up old buffers */
for(Iterator<Map.Entry<Integer, Defrag>> i = fragbufs.entrySet().iterator(); i.hasNext();) {
Map.Entry<Integer, Defrag> e = i.next();
Defrag old = e.getValue();
if(now - old.last > 10000)
i.remove();
}
}
}
public Tileset tileset(int i) {
if(csets[i] == null) {
if(sets[i].loading)
throw(new LoadingMap());
csets[i] = sets[i].layer(Resource.tileset);
}
return(csets[i]);
}
public void tilemap(Message msg) {
while(!msg.eom()) {
int id = msg.uint8();
String resnm = msg.string();
int resver = msg.uint16();
sets[id] = Resource.load(resnm, resver);
}
}
public void trimall() {
synchronized(grids) {
synchronized(req) {
grids.clear();
req.clear();
}
}
}
public void trim(Coord ul, Coord lr) {
synchronized(grids) {
synchronized(req) {
for(Iterator<Map.Entry<Coord, Grid>> i = grids.entrySet().iterator(); i.hasNext();) {
Map.Entry<Coord, Grid> e = i.next();
Coord gc = e.getKey();
Grid g = e.getValue();
if((gc.x < ul.x) || (gc.y < ul.y) || (gc.x > lr.x) || (gc.y > lr.y))
i.remove();
}
for(Iterator<Coord> i = req.keySet().iterator(); i.hasNext();) {
Coord gc = i.next();
if((gc.x < ul.x) || (gc.y < ul.y) || (gc.x > lr.x) || (gc.y > lr.y))
i.remove();
}
}
}
}
public void request(Coord gc) {
synchronized(req) {
if(!req.containsKey(gc))
req.put(gc, new Request());
}
}
public void sendreqs() {
long now = System.currentTimeMillis();
synchronized(req) {
for(Iterator<Map.Entry<Coord, Request>> i = req.entrySet().iterator(); i.hasNext();) {
Map.Entry<Coord, Request> e = i.next();
Coord c = e.getKey();
Request r = e.getValue();
if(now - r.lastreq > 1000) {
r.lastreq = now;
if(++r.reqs >= 5) {
i.remove();
} else {
Message msg = new Message(Session.MSG_MAPREQ);
msg.addcoord(c);
sess.sendmsg(msg);
}
}
}
}
}
}
| true | true | public void mapdata2(Message msg) {
Coord c = msg.coord();
String mmname = msg.string().intern();
if(mmname.equals(""))
mmname = null;
int[] pfl = new int[256];
while(true) {
int pidx = msg.uint8();
if(pidx == 255)
break;
pfl[pidx] = msg.uint8();
}
Message blob = new Message(0);
{
Inflater z = new Inflater();
z.setInput(msg.blob, msg.off, msg.blob.length - msg.off);
byte[] buf = new byte[10000];
while(true) {
try {
int len;
if((len = z.inflate(buf)) == 0) {
if(!z.finished())
throw(new RuntimeException("Got unterminated map blob"));
break;
}
blob.addbytes(buf, 0, len);
} catch(java.util.zip.DataFormatException e) {
throw(new RuntimeException("Got malformed map blob", e));
}
}
}
synchronized(grids) {
synchronized(req) {
if(req.containsKey(c)) {
Grid g = new Grid(c);
g.mnm = mmname;
for(int i = 0; i < g.tiles.length; i++)
g.tiles[i] = blob.uint8();
for(int i = 0, y = 0; y < cmaps.y; y++, i++) {
for(int x = 0; x < cmaps.x; x++)
g.z[i] = (int)(Math.sin((g.ul.x + x) / 2.0) + Math.sin((g.ul.y + y) / 2.0));
}
for(int i = 0; i < g.ol.length; i++)
g.ol[i] = 0;
while(true) {
int pidx = blob.uint8();
if(pidx == 255)
break;
int fl = pfl[pidx];
int type = blob.uint8();
Coord c1 = new Coord(blob.uint8(), blob.uint8());
Coord c2 = new Coord(blob.uint8(), blob.uint8());
int ol;
if(type == 0) {
if((fl & 1) == 1)
ol = 2;
else
ol = 1;
} else if(type == 1) {
if((fl & 1) == 1)
ol = 8;
else
ol = 4;
} else {
throw(new RuntimeException("Unknown plot type " + type));
}
for(int y = c1.y; y <= c2.y; y++) {
for(int x = c1.x; x <= c2.x; x++) {
g.ol[x + (y * cmaps.x)] |= ol;
}
}
}
req.remove(c);
if(grids.remove(c) == cached)
cached = null;
grids.put(c, g);
}
}
}
}
| public void mapdata2(Message msg) {
Coord c = msg.coord();
String mmname = msg.string().intern();
if(mmname.equals(""))
mmname = null;
int[] pfl = new int[256];
while(true) {
int pidx = msg.uint8();
if(pidx == 255)
break;
pfl[pidx] = msg.uint8();
}
Message blob = new Message(0);
{
Inflater z = new Inflater();
z.setInput(msg.blob, msg.off, msg.blob.length - msg.off);
byte[] buf = new byte[10000];
while(true) {
try {
int len;
if((len = z.inflate(buf)) == 0) {
if(!z.finished())
throw(new RuntimeException("Got unterminated map blob"));
break;
}
blob.addbytes(buf, 0, len);
} catch(java.util.zip.DataFormatException e) {
throw(new RuntimeException("Got malformed map blob", e));
}
}
}
synchronized(grids) {
synchronized(req) {
if(req.containsKey(c)) {
Grid g = new Grid(c);
g.mnm = mmname;
for(int i = 0; i < g.tiles.length; i++)
g.tiles[i] = blob.uint8();
for(int i = 0, y = 0; y < cmaps.y; y++) {
for(int x = 0; x < cmaps.x; x++, i++)
g.z[i] = (int)((Math.sin((g.ul.x + x) / 2.0) + Math.sin((g.ul.y + y) / 2.0)) * 16);
}
for(int i = 0; i < g.ol.length; i++)
g.ol[i] = 0;
while(true) {
int pidx = blob.uint8();
if(pidx == 255)
break;
int fl = pfl[pidx];
int type = blob.uint8();
Coord c1 = new Coord(blob.uint8(), blob.uint8());
Coord c2 = new Coord(blob.uint8(), blob.uint8());
int ol;
if(type == 0) {
if((fl & 1) == 1)
ol = 2;
else
ol = 1;
} else if(type == 1) {
if((fl & 1) == 1)
ol = 8;
else
ol = 4;
} else {
throw(new RuntimeException("Unknown plot type " + type));
}
for(int y = c1.y; y <= c2.y; y++) {
for(int x = c1.x; x <= c2.x; x++) {
g.ol[x + (y * cmaps.x)] |= ol;
}
}
}
req.remove(c);
if(grids.remove(c) == cached)
cached = null;
grids.put(c, g);
}
}
}
}
|
diff --git a/java/src/edu/umich/insoar/LanguageConnector.java b/java/src/edu/umich/insoar/LanguageConnector.java
index cebe45cb..649dfda5 100644
--- a/java/src/edu/umich/insoar/LanguageConnector.java
+++ b/java/src/edu/umich/insoar/LanguageConnector.java
@@ -1,251 +1,252 @@
package edu.umich.insoar;
import sml.Agent;
import sml.Agent.OutputEventInterface;
import sml.Agent.RunEventInterface;
import sml.Identifier;
import sml.WMElement;
import sml.smlRunEventId;
import com.soartech.bolt.BOLTLGSupport;
import com.soartech.bolt.testing.ActionType;
import edu.umich.insoar.language.AgentMessageParser;
import edu.umich.insoar.language.Patterns.LingObject;
import edu.umich.insoar.world.Messages;
import edu.umich.insoar.world.WMUtil;
public class LanguageConnector implements OutputEventInterface, RunEventInterface {
private SoarAgent soarAgent;
private BOLTLGSupport lgsupport;
private Messages messages;
public LanguageConnector(SoarAgent soarAgent, BOLTLGSupport lgsupport)
{
this.soarAgent = soarAgent;
this.lgsupport = lgsupport;
messages = new Messages();
String[] outputHandlerStrings = { "send-message", "remove-message", "push-segment",
"pop-segment", "report-interaction" };
for (String outputHandlerString : outputHandlerStrings)
{
soarAgent.getAgent().AddOutputHandler(outputHandlerString, this, null);
}
soarAgent.getAgent().RegisterForRunEvent(
smlRunEventId.smlEVENT_AFTER_OUTPUT_PHASE, this, null);
}
public void clear(){
messages.destroy();
clearLGMessages();
}
public void clearLGMessages(){
lgsupport.clear();
soarAgent.commitChanges();
}
public void destroyMessage(int id){
if(messages.getIdNumber() == id){
messages.destroy();
}
}
public void newMessage(String message){
if (lgsupport == null) {
messages.addMessage(message);
} else if(message.length() > 0){
if(message.charAt(0) == ':'){
messages.addMessage(message.substring(1));
} else {
// LGSupport has access to the agent object and handles all WM interaction from here
lgsupport.handleInput(message);
}
}
}
public void runEventHandler(int eventID, Object data, Agent agent, int phase)
{
Identifier outputLink = agent.GetOutputLink();
if(outputLink != null){
WMElement waitingWME = outputLink.FindByAttribute("waiting", 0);
ChatFrame.Singleton().setReady(waitingWME != null);
}
Identifier inputLink = agent.GetInputLink();
if(inputLink != null){
messages.updateInputLink(inputLink);
}
}
@Override
public void outputEventHandler(Object data, String agentName,
String attributeName, WMElement wme)
{
synchronized(this){
if (!(wme.IsJustAdded() && wme.IsIdentifier()))
{
return;
}
Identifier id = wme.ConvertToIdentifier();
System.out.println(wme.GetAttribute());
try{
if (wme.GetAttribute().equals("send-message"))
{
processOutputLinkMessage(id);
}
else if (wme.GetAttribute().equals("remove-message"))
{
processRemoveMesageCommand(id);
}
else if(wme.GetAttribute().equals("push-segment"))
{
processPushSegmentCommand(id);
}
else if(wme.GetAttribute().equals("pop-segment"))
{
processPopSegmentCommand(id);
}
else if(wme.GetAttribute().equals("report-interaction")){
processReportInteraction(id);
}
soarAgent.commitChanges();
} catch (IllegalStateException e){
System.out.println(e.getMessage());
}
}
}
private void processOutputLinkMessage(Identifier messageId)
{
if (messageId == null)
{
return;
}
if (messageId.GetNumberChildren() == 0)
{
messageId.CreateStringWME("status", "error");
throw new IllegalStateException("Message has no children");
}
if(WMUtil.getIdentifierOfAttribute(messageId, "first") == null){
processAgentMessageStructureCommand(messageId);
} else {
processAgentMessageStringCommand(messageId);
}
}
private void processRemoveMesageCommand(Identifier messageId) {
int id = Integer.parseInt(WMUtil.getValueOfAttribute(messageId, "id", "Error (remove-message): No id"));
destroyMessage(id);
messageId.CreateStringWME("status", "complete");
}
private void processAgentMessageStructureCommand(Identifier messageId)
{
String type = WMUtil.getValueOfAttribute(messageId, "type",
"Message does not have ^type");
String message = "";
message = AgentMessageParser.translateAgentMessage(messageId);
if(!message.equals("")){
ChatFrame.Singleton().addMessage(message, ActionType.Agent);
}
messageId.CreateStringWME("status", "complete");
}
private void processAgentMessageStringCommand(Identifier messageId){
String message = "";
WMElement wordsWME = messageId.FindByAttribute("first", 0);
if (wordsWME == null || !wordsWME.IsIdentifier())
{
messageId.CreateStringWME("status", "error");
throw new IllegalStateException("Message has no first attribute");
}
Identifier currentWordId = wordsWME.ConvertToIdentifier();
// Follows the linked list down until it can't find the 'rest' attribute
// of a WME
while (currentWordId != null)
{
Identifier nextWordId = null;
for (int i = 0; i < currentWordId.GetNumberChildren(); i++)
{
WMElement child = currentWordId.GetChild(i);
- if (child.GetAttribute().equals("word"))
+ if (child.GetAttribute().equals("value"))
{
- message += child.GetValueAsString() + " ";
+ // message += child.GetIdentifierName()+ " ";
+ message += child.GetValueAsString()+ " ";
}
else if (child.GetAttribute().equals("next")
&& child.IsIdentifier())
{
nextWordId = child.ConvertToIdentifier();
}
}
currentWordId = nextWordId;
}
if (message == "")
{
messageId.CreateStringWME("status", "error");
throw new IllegalStateException("Message was empty");
}
message += ".";
ChatFrame.Singleton().addMessage(message.substring(0, message.length() - 1), ActionType.Agent);
messageId.CreateStringWME("status", "complete");
}
private void processPushSegmentCommand(Identifier id){
//String type = WMUtil.getValueOfAttribute(id, "type", "Error (push-segment): No ^type attribute");
//String originator = WMUtil.getValueOfAttribute(id, "originator", "Error (push-segment): No ^originator attribute");
//InSoar.Singleton().getSoarAgent().getStack().pushSegment(type, originator);
id.CreateStringWME("status", "complete");
}
private void processPopSegmentCommand(Identifier id){
//InSoar.Singleton().getSoarAgent().getStack().popSegment();
id.CreateStringWME("status", "complete");
}
private void processReportInteraction(Identifier id){
String type = WMUtil.getValueOfAttribute(id, "type");
String originator = WMUtil.getValueOfAttribute(id, "originator");
Identifier sat = WMUtil.getIdentifierOfAttribute(id, "satisfaction");
String eventName = sat.GetChild(0).GetAttribute();
WMElement eventTypeWME = sat.GetChild(0).ConvertToIdentifier().FindByAttribute("type", 0);
Identifier context = WMUtil.getIdentifierOfAttribute(id, "context");
String message = "";
if(type.equals("get-next-task")){
message = "I am idle and waiting for you to initiate a new interaction";
} else if(type.equals("get-next-subaction")){
String verb = WMUtil.getValueOfAttribute(context, "verb");
message = "What is the next step in performing '" + verb + "'?";
} else if(type.equals("category-of-word")){
String word = WMUtil.getValueOfAttribute(context, "word");
message = "I do not know the category of " + word + ". " +
"You can say something like 'a shape' or 'blue is a color'";
} else if(type.equals("which-question")){
String objStr = LingObject.createFromSoarSpeak(context, "description").toString();
message = "I see multiple examples of '" + objStr + "' and I need clarification";
} else if(type.equals("teaching-request")){
String objStr = LingObject.createFromSoarSpeak(context, "description").toString();
message = "Please give me teaching examples of '" + objStr + "' and tell me 'finished' when you are done.";
} else if(type.equals("get-goal")){
String verb = WMUtil.getValueOfAttribute(context, "verb");
message = "Please tell me what the goal of '" + verb + "'is.";
}
ChatFrame.Singleton().addMessage(message, ActionType.Agent);
id.CreateStringWME("status", "complete");
}
}
| false | true | private void processAgentMessageStringCommand(Identifier messageId){
String message = "";
WMElement wordsWME = messageId.FindByAttribute("first", 0);
if (wordsWME == null || !wordsWME.IsIdentifier())
{
messageId.CreateStringWME("status", "error");
throw new IllegalStateException("Message has no first attribute");
}
Identifier currentWordId = wordsWME.ConvertToIdentifier();
// Follows the linked list down until it can't find the 'rest' attribute
// of a WME
while (currentWordId != null)
{
Identifier nextWordId = null;
for (int i = 0; i < currentWordId.GetNumberChildren(); i++)
{
WMElement child = currentWordId.GetChild(i);
if (child.GetAttribute().equals("word"))
{
message += child.GetValueAsString() + " ";
}
else if (child.GetAttribute().equals("next")
&& child.IsIdentifier())
{
nextWordId = child.ConvertToIdentifier();
}
}
currentWordId = nextWordId;
}
if (message == "")
{
messageId.CreateStringWME("status", "error");
throw new IllegalStateException("Message was empty");
}
message += ".";
ChatFrame.Singleton().addMessage(message.substring(0, message.length() - 1), ActionType.Agent);
messageId.CreateStringWME("status", "complete");
}
| private void processAgentMessageStringCommand(Identifier messageId){
String message = "";
WMElement wordsWME = messageId.FindByAttribute("first", 0);
if (wordsWME == null || !wordsWME.IsIdentifier())
{
messageId.CreateStringWME("status", "error");
throw new IllegalStateException("Message has no first attribute");
}
Identifier currentWordId = wordsWME.ConvertToIdentifier();
// Follows the linked list down until it can't find the 'rest' attribute
// of a WME
while (currentWordId != null)
{
Identifier nextWordId = null;
for (int i = 0; i < currentWordId.GetNumberChildren(); i++)
{
WMElement child = currentWordId.GetChild(i);
if (child.GetAttribute().equals("value"))
{
// message += child.GetIdentifierName()+ " ";
message += child.GetValueAsString()+ " ";
}
else if (child.GetAttribute().equals("next")
&& child.IsIdentifier())
{
nextWordId = child.ConvertToIdentifier();
}
}
currentWordId = nextWordId;
}
if (message == "")
{
messageId.CreateStringWME("status", "error");
throw new IllegalStateException("Message was empty");
}
message += ".";
ChatFrame.Singleton().addMessage(message.substring(0, message.length() - 1), ActionType.Agent);
messageId.CreateStringWME("status", "complete");
}
|
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/search/RepositorySearchResultView.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/search/RepositorySearchResultView.java
index 946db8c24..57b6901ee 100644
--- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/search/RepositorySearchResultView.java
+++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/search/RepositorySearchResultView.java
@@ -1,347 +1,347 @@
/*******************************************************************************
* Copyright (c) 2003 - 2006 University Of British Columbia 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:
* University Of British Columbia - initial API and implementation
*******************************************************************************/
package org.eclipse.mylar.internal.tasks.ui.search;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.ILabelDecorator;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.mylar.internal.tasks.ui.TaskListColorsAndFonts;
import org.eclipse.mylar.internal.tasks.ui.TaskUiUtil;
import org.eclipse.mylar.internal.tasks.ui.views.TaskElementLabelProvider;
import org.eclipse.mylar.internal.tasks.ui.views.TaskListTableLabelProvider;
import org.eclipse.mylar.tasks.core.AbstractQueryHit;
import org.eclipse.mylar.tasks.ui.TasksUiPlugin;
import org.eclipse.search.internal.ui.SearchMessages;
import org.eclipse.search.internal.ui.SearchPlugin;
import org.eclipse.search.internal.ui.SearchPreferencePage;
import org.eclipse.search.ui.IContextMenuConstants;
import org.eclipse.search.ui.text.AbstractTextSearchViewPage;
import org.eclipse.search.ui.text.Match;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.IShowInTargetList;
import org.eclipse.ui.themes.IThemeManager;
/**
* Displays the results of a Repository search.
*
* @see org.eclipse.search.ui.text.AbstractTextSearchViewPage
*/
public class RepositorySearchResultView extends AbstractTextSearchViewPage implements IAdaptable {
// The categories to sort bug results by
public static final int ORDER_PRIORITY = 1;
public static final int ORDER_DESCRIPTION = 2;
public static final int ORDER_SEVERITY = 3;
public static final int ORDER_STATUS = 4;
public static final int ORDER_ID = 5;
public static final int ORDER_DEFAULT = ORDER_PRIORITY;
private static final String KEY_SORTING = TasksUiPlugin.PLUGIN_ID + ".search.resultpage.sorting"; //$NON-NLS-1$
private SearchResultContentProvider bugContentProvider;
private int bugCurrentSortOrder;
// private SearchResultSortAction bugSortByIDAction;
// private SearchResultSortAction bugSortBySeverityAction;
private SearchResultSortAction bugSortByPriorityAction;
private SearchResultSortAction bugSortByDescriptionAction;
// private SearchResultSortAction bugSortByStatusAction;
// private AddFavoriteAction addToFavoritesAction;
private OpenSearchResultAction openInEditorAction;
private static final String[] SHOW_IN_TARGETS = new String[] { IPageLayout.ID_RES_NAV };
private static final IShowInTargetList SHOW_IN_TARGET_LIST = new IShowInTargetList() {
public String[] getShowInTargetIds() {
return SHOW_IN_TARGETS;
}
};
private IPropertyChangeListener bugPropertyChangeListener;
/**
* Constructor
*/
public RepositorySearchResultView() {
// Only use the table layout.
super(FLAG_LAYOUT_FLAT);
bugSortByPriorityAction = new SearchResultSortAction("Bug priority", this, ORDER_PRIORITY);
bugSortByDescriptionAction = new SearchResultSortAction("Bug Description", this, ORDER_DESCRIPTION);
// bugSortByIDAction = new SearchResultSortAction("Bug ID", this,
// ORDER_ID);
// bugSortBySeverityAction = new SearchResultSortAction("Bug severity",
// this, ORDER_SEVERITY);
// bugSortByStatusAction = new SearchResultSortAction("Bug status",
// this,
// ORDER_STATUS);
bugCurrentSortOrder = ORDER_DEFAULT;
// addToFavoritesAction = new AddFavoriteAction("Mark Result as
// Favorite", this);
openInEditorAction = new OpenSearchResultAction("Open in Editor", this);
bugPropertyChangeListener = new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
if (SearchPreferencePage.LIMIT_TABLE.equals(event.getProperty())
|| SearchPreferencePage.LIMIT_TABLE_TO.equals(event.getProperty()))
if (getViewer() instanceof TableViewer) {
getViewPart().updateLabel();
getViewer().refresh();
}
}
};
SearchPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(bugPropertyChangeListener);
}
@Override
protected void elementsChanged(Object[] objects) {
if (bugContentProvider != null) {
bugContentProvider.elementsChanged(objects);
}
}
@Override
protected void clear() {
if (bugContentProvider != null) {
bugContentProvider.clear();
}
}
// Allows the inherited method "getViewer" to be accessed publicly.
@Override
public StructuredViewer getViewer() {
return super.getViewer();
}
@Override
protected void configureTreeViewer(TreeViewer viewer) {
// The tree layout is not used, so this function does not need to do
// anything.
}
@Override
protected void configureTableViewer(TableViewer viewer) {
viewer.setUseHashlookup(true);
String[] columnNames = new String[] { "", "!", "Description" };
TableColumn[] columns = new TableColumn[columnNames.length];
int[] columnWidths = new int[] { 20, 20, 500 };
viewer.setColumnProperties(columnNames);
- viewer.getTable().setHeaderVisible(true);
+ viewer.getTable().setHeaderVisible(false);
for (int i = 0; i < columnNames.length; i++) {
columns[i] = new TableColumn(viewer.getTable(), 0, i); // SWT.LEFT
columns[i].setText(columnNames[i]);
columns[i].setWidth(columnWidths[i]);
columns[i].setData(new Integer(i));
columns[i].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
TableColumn col = (TableColumn) e.getSource();
Integer integer = (Integer) col.getData();
setSortOrder(integer.intValue());
}
});
}
// TaskElementLabelProvider BugzillaLabelProvider
IThemeManager themeManager = getSite().getWorkbenchWindow().getWorkbench().getThemeManager();
Color categoryBackground = themeManager.getCurrentTheme().getColorRegistry().get(
TaskListColorsAndFonts.THEME_COLOR_TASKLIST_CATEGORY);
SearchViewTableLabelProvider taskListTableLabelProvider = new SearchViewTableLabelProvider(
new TaskElementLabelProvider(), PlatformUI.getWorkbench().getDecoratorManager().getLabelDecorator(),
categoryBackground);
viewer.setLabelProvider(taskListTableLabelProvider);
viewer.setContentProvider(new SearchResultTableContentProvider(this));
// Set the order when the search view is loading so that the items are
// sorted right away
setSortOrder(bugCurrentSortOrder);
bugContentProvider = (SearchResultContentProvider) viewer.getContentProvider();
}
/**
* Sets the new sorting category, and reorders all of the bug reports.
*
* @param sortOrder
* The new category to sort bug reports by
*/
public void setSortOrder(int sortOrder) {
StructuredViewer viewer = getViewer();
switch (sortOrder) {
case ORDER_ID:
viewer.setSorter(new SearchResultSorterId());
break;
case ORDER_DESCRIPTION:
viewer.setSorter(new SearchResultSorterDescription());
break;
case ORDER_PRIORITY:
viewer.setSorter(new SearchResultSorterPriority());
break;
// case ORDER_SEVERITY:
// viewer.setSorter(new BugzillaSeveritySearchSorter());
// break;
// case ORDER_STATUS:
// viewer.setSorter(new BugzillaStateSearchSorter());
// break;
default:
// If the setting is not one of the four valid ones,
// use the default order setting.
sortOrder = ORDER_DEFAULT;
viewer.setSorter(new SearchResultSorterPriority());
break;
}
bugCurrentSortOrder = sortOrder;
getSettings().put(KEY_SORTING, bugCurrentSortOrder);
}
/*
* (non-Javadoc)
*
* @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class)
*/
public Object getAdapter(Class adapter) {
if (IShowInTargetList.class.equals(adapter)) {
return SHOW_IN_TARGET_LIST;
}
return null;
}
@Override
protected void showMatch(Match match, int currentOffset, int currentLength, boolean activate)
throws PartInitException {
AbstractQueryHit repositoryHit = (AbstractQueryHit) match.getElement();
TaskUiUtil.openRepositoryTask(repositoryHit.getRepositoryUrl(), repositoryHit.getId(), repositoryHit.getUrl());
// try {
// int id = Integer.parseInt(repositoryHit.getId());
// String bugUrl =
// BugzillaServerFacade.getBugUrlWithoutLogin(repositoryHit.getRepositoryUrl(),
// id);
// TaskUiUtil.openRepositoryTask(repositoryHit.getRepositoryUrl(),
// repositoryHit.getId(), bugUrl);
// } catch (NumberFormatException e) {
// MylarStatusHandler.fail(e, "Could not open, malformed id: " +
// repositoryHit.getId(), true);
// }
}
@Override
protected void fillContextMenu(IMenuManager mgr) {
super.fillContextMenu(mgr);
// Create the submenu for sorting
MenuManager sortMenu = new MenuManager(SearchMessages.SortDropDownAction_label); //$NON-NLS-1$
sortMenu.add(bugSortByPriorityAction);
sortMenu.add(bugSortByDescriptionAction);
// sortMenu.add(bugSortByIDAction);
// sortMenu.add(bugSortBySeverityAction);
// sortMenu.add(bugSortByStatusAction);
// Check the right sort option
bugSortByPriorityAction.setChecked(bugCurrentSortOrder == bugSortByPriorityAction.getSortOrder());
bugSortByDescriptionAction.setChecked(bugCurrentSortOrder == bugSortByDescriptionAction.getSortOrder());
// bugSortByIDAction.setChecked(bugCurrentSortOrder ==
// bugSortByIDAction.getSortOrder());
// bugSortBySeverityAction.setChecked(bugCurrentSortOrder ==
// bugSortBySeverityAction.getSortOrder());
// bugSortByStatusAction.setChecked(bugCurrentSortOrder ==
// bugSortByStatusAction.getSortOrder());
// Add the new context menu items
mgr.appendToGroup(IContextMenuConstants.GROUP_VIEWER_SETUP, sortMenu);
// mgr.appendToGroup(IContextMenuConstants.GROUP_ADDITIONS,
// addToFavoritesAction);
mgr.appendToGroup(IContextMenuConstants.GROUP_OPEN, openInEditorAction);
}
class SearchViewTableLabelProvider extends TaskListTableLabelProvider {
public SearchViewTableLabelProvider(ILabelProvider provider, ILabelDecorator decorator, Color parentBackground) {
super(provider, decorator, parentBackground, null);
}
@Override
public Image getColumnImage(Object element, int columnIndex) {
switch (columnIndex) {
case 0:
++columnIndex;
break;
case 1:
++columnIndex;
break;
case 2:
columnIndex = 2 + columnIndex;
break;
}
return super.getColumnImage(element, columnIndex);
}
@Override
public String getColumnText(Object obj, int columnIndex) {
switch (columnIndex) {
case 0:
++columnIndex;
break;
case 1:
++columnIndex;
break;
case 2:
columnIndex = 2 + columnIndex;
break;
}
return super.getColumnText(obj, columnIndex);
}
@Override
public Color getBackground(Object element, int columnIndex) {
// Note: see bug 142889
return null;
}
}
}
| true | true | protected void configureTableViewer(TableViewer viewer) {
viewer.setUseHashlookup(true);
String[] columnNames = new String[] { "", "!", "Description" };
TableColumn[] columns = new TableColumn[columnNames.length];
int[] columnWidths = new int[] { 20, 20, 500 };
viewer.setColumnProperties(columnNames);
viewer.getTable().setHeaderVisible(true);
for (int i = 0; i < columnNames.length; i++) {
columns[i] = new TableColumn(viewer.getTable(), 0, i); // SWT.LEFT
columns[i].setText(columnNames[i]);
columns[i].setWidth(columnWidths[i]);
columns[i].setData(new Integer(i));
columns[i].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
TableColumn col = (TableColumn) e.getSource();
Integer integer = (Integer) col.getData();
setSortOrder(integer.intValue());
}
});
}
// TaskElementLabelProvider BugzillaLabelProvider
IThemeManager themeManager = getSite().getWorkbenchWindow().getWorkbench().getThemeManager();
Color categoryBackground = themeManager.getCurrentTheme().getColorRegistry().get(
TaskListColorsAndFonts.THEME_COLOR_TASKLIST_CATEGORY);
SearchViewTableLabelProvider taskListTableLabelProvider = new SearchViewTableLabelProvider(
new TaskElementLabelProvider(), PlatformUI.getWorkbench().getDecoratorManager().getLabelDecorator(),
categoryBackground);
viewer.setLabelProvider(taskListTableLabelProvider);
viewer.setContentProvider(new SearchResultTableContentProvider(this));
// Set the order when the search view is loading so that the items are
// sorted right away
setSortOrder(bugCurrentSortOrder);
bugContentProvider = (SearchResultContentProvider) viewer.getContentProvider();
}
| protected void configureTableViewer(TableViewer viewer) {
viewer.setUseHashlookup(true);
String[] columnNames = new String[] { "", "!", "Description" };
TableColumn[] columns = new TableColumn[columnNames.length];
int[] columnWidths = new int[] { 20, 20, 500 };
viewer.setColumnProperties(columnNames);
viewer.getTable().setHeaderVisible(false);
for (int i = 0; i < columnNames.length; i++) {
columns[i] = new TableColumn(viewer.getTable(), 0, i); // SWT.LEFT
columns[i].setText(columnNames[i]);
columns[i].setWidth(columnWidths[i]);
columns[i].setData(new Integer(i));
columns[i].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
TableColumn col = (TableColumn) e.getSource();
Integer integer = (Integer) col.getData();
setSortOrder(integer.intValue());
}
});
}
// TaskElementLabelProvider BugzillaLabelProvider
IThemeManager themeManager = getSite().getWorkbenchWindow().getWorkbench().getThemeManager();
Color categoryBackground = themeManager.getCurrentTheme().getColorRegistry().get(
TaskListColorsAndFonts.THEME_COLOR_TASKLIST_CATEGORY);
SearchViewTableLabelProvider taskListTableLabelProvider = new SearchViewTableLabelProvider(
new TaskElementLabelProvider(), PlatformUI.getWorkbench().getDecoratorManager().getLabelDecorator(),
categoryBackground);
viewer.setLabelProvider(taskListTableLabelProvider);
viewer.setContentProvider(new SearchResultTableContentProvider(this));
// Set the order when the search view is loading so that the items are
// sorted right away
setSortOrder(bugCurrentSortOrder);
bugContentProvider = (SearchResultContentProvider) viewer.getContentProvider();
}
|
diff --git a/src/net/sf/freecol/client/gui/panel/ColonyPanel.java b/src/net/sf/freecol/client/gui/panel/ColonyPanel.java
index fee3d6a72..4b37d15a6 100644
--- a/src/net/sf/freecol/client/gui/panel/ColonyPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/ColonyPanel.java
@@ -1,1699 +1,1699 @@
/**
* Copyright (C) 2002-2007 The FreeCol Team
*
* This file is part of FreeCol.
*
* FreeCol 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.
*
* FreeCol 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 FreeCol. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.freecol.client.gui.panel;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.dnd.Autoscroll;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.ComponentInputMap;
import javax.swing.ImageIcon;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JToolTip;
import javax.swing.JViewport;
import javax.swing.KeyStroke;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingUtilities;
import javax.swing.border.BevelBorder;
import net.miginfocom.swing.MigLayout;
import net.sf.freecol.client.ClientOptions;
import net.sf.freecol.client.gui.Canvas;
import net.sf.freecol.client.gui.GUI;
import net.sf.freecol.client.gui.i18n.Messages;
import net.sf.freecol.common.model.AbstractGoods;
import net.sf.freecol.common.model.BuildableType;
import net.sf.freecol.common.model.Building;
import net.sf.freecol.common.model.Colony;
import net.sf.freecol.common.model.ColonyTile;
import net.sf.freecol.common.model.FreeColGameObject;
import net.sf.freecol.common.model.FreeColObject;
import net.sf.freecol.common.model.Game;
import net.sf.freecol.common.model.Goods;
import net.sf.freecol.common.model.GoodsType;
import net.sf.freecol.common.model.IndianSettlement;
import net.sf.freecol.common.model.Map.Direction;
import net.sf.freecol.common.model.ModelMessage;
import net.sf.freecol.common.model.Player;
import net.sf.freecol.common.model.Settlement;
import net.sf.freecol.common.model.Specification;
import net.sf.freecol.common.model.StringTemplate;
import net.sf.freecol.common.model.Tile;
import net.sf.freecol.common.model.TileType;
import net.sf.freecol.common.model.TradeRoute;
import net.sf.freecol.common.model.Unit;
import net.sf.freecol.common.model.Colony.ColonyChangeEvent;
import net.sf.freecol.common.resources.ResourceManager;
/**
* This is a panel for the Colony display. It shows the units that are working
* in the colony, the buildings and much more.
*/
public final class ColonyPanel extends FreeColPanel implements ActionListener,PropertyChangeListener {
private static Logger logger = Logger.getLogger(ColonyPanel.class.getName());
/**
* The height of the area in which autoscrolling should happen.
*/
public static final int SCROLL_AREA_HEIGHT = 40;
/**
* The speed of the scrolling.
*/
public static final int SCROLL_SPEED = 40;
private static final int EXIT = 0, BUILDQUEUE = 1, UNLOAD = 2, WAREHOUSE = 4, FILL = 5;
private final JLabel rebelShield = new JLabel();
private final JLabel rebelLabel = new JLabel();
private final JLabel bonusLabel = new JLabel();
private final JLabel royalistLabel = new JLabel();
private final JLabel royalistShield = new JLabel();
private final JLabel rebelMemberLabel = new JLabel();
private final JLabel popLabel = new JLabel();
private final JLabel royalistMemberLabel = new JLabel();
private final JPanel netProductionPanel = new JPanel();
private final JPanel populationPanel = new JPanel() {
public JToolTip createToolTip() {
return new RebelToolTip(colony, getCanvas());
}
@Override
public String getUIClassID() {
return "PopulationPanelUI";
}
};
private final JComboBox nameBox;
private final OutsideColonyPanel outsideColonyPanel;
private final InPortPanel inPortPanel;
private final ColonyCargoPanel cargoPanel;
private final WarehousePanel warehousePanel;
private final TilePanel tilePanel;
private final BuildingsPanel buildingsPanel;
private final ConstructionPanel constructionPanel;
private final DefaultTransferHandler defaultTransferHandler;
private final MouseListener pressListener;
private final MouseListener releaseListener;
private Colony colony;
private UnitLabel selectedUnit;
private JButton exitButton = new JButton(Messages.message("close"));
private JButton unloadButton = new JButton(Messages.message("unload"));
private JButton fillButton = new JButton(Messages.message("fill"));
private JButton warehouseButton = new JButton(Messages.message("warehouseDialog.name"));
private JButton buildQueueButton = new JButton(Messages.message("colonyPanel.buildQueue"));
/**
* The saved size of this panel.
*/
private static Dimension savedSize = null;
/**
* The constructor for the panel.
*
* @param parent The parent of this panel
*/
public ColonyPanel(final Canvas parent, Colony colony) {
super(parent);
setFocusCycleRoot(true);
// Use ESCAPE for closing the ColonyPanel:
InputMap closeInputMap = new ComponentInputMap(exitButton);
closeInputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false), "pressed");
closeInputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, true), "released");
SwingUtilities.replaceUIInputMap(exitButton, JComponent.WHEN_IN_FOCUSED_WINDOW, closeInputMap);
InputMap unloadInputMap = new ComponentInputMap(unloadButton);
unloadInputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_U, 0, false), "pressed");
unloadInputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_U, 0, true), "released");
SwingUtilities.replaceUIInputMap(unloadButton, JComponent.WHEN_IN_FOCUSED_WINDOW, unloadInputMap);
InputMap fillInputMap = new ComponentInputMap(fillButton);
fillInputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_L, 0, false), "pressed");
fillInputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_L, 0, true), "released");
SwingUtilities.replaceUIInputMap(fillButton, JComponent.WHEN_IN_FOCUSED_WINDOW, fillInputMap);
netProductionPanel.setOpaque(false);
populationPanel.setOpaque(true);
populationPanel.setToolTipText(" ");
populationPanel.setLayout(new MigLayout("wrap 5, fill, insets 0",
"[][]:push[center]:push[right][]", ""));
populationPanel.add(rebelShield, "bottom");
populationPanel.add(rebelLabel, "split 2, flowy");
populationPanel.add(rebelMemberLabel);
populationPanel.add(popLabel, "split 2, flowy");
populationPanel.add(bonusLabel);
populationPanel.add(royalistLabel, "split 2, flowy");
populationPanel.add(royalistMemberLabel);
populationPanel.add(royalistShield, "bottom");
constructionPanel = new ConstructionPanel(parent, colony);
constructionPanel.setOpaque(true);
outsideColonyPanel = new OutsideColonyPanel();
outsideColonyPanel.setLayout(new GridLayout(0, 8));
inPortPanel = new InPortPanel();
inPortPanel.setLayout(new GridLayout(0, 2));
warehousePanel = new WarehousePanel(this);
warehousePanel.setLayout(new GridLayout(1, 0));
tilePanel = new TilePanel(this);
buildingsPanel = new BuildingsPanel(this);
cargoPanel = new ColonyCargoPanel(parent);
cargoPanel.setParentPanel(this);
cargoPanel.setLayout(new GridLayout(1, 0));
defaultTransferHandler = new DefaultTransferHandler(parent, this);
pressListener = new DragListener(this);
releaseListener = new DropListener();
JScrollPane outsideColonyScroll = new JScrollPane(outsideColonyPanel,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
outsideColonyScroll.getVerticalScrollBar().setUnitIncrement( 16 );
JScrollPane inPortScroll = new JScrollPane(inPortPanel,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
inPortScroll.getVerticalScrollBar().setUnitIncrement( 16 );
JScrollPane cargoScroll = new JScrollPane(cargoPanel,
ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
JScrollPane warehouseScroll = new JScrollPane(warehousePanel,
ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
JScrollPane tilesScroll = new JScrollPane(tilePanel,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
JScrollPane buildingsScroll = new JScrollPane(buildingsPanel,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
buildingsScroll.getVerticalScrollBar().setUnitIncrement( 16 );
// Make the colony label
nameBox = new JComboBox();
nameBox.setFont(smallHeaderFont);
List<Colony> settlements = colony.getOwner().getColonies();
sortColonies(settlements);
for (Colony aColony : settlements) {
nameBox.addItem(aColony);
}
nameBox.setSelectedItem(colony);
nameBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
initialize((Colony) nameBox.getSelectedItem());
}
});
buildingsScroll.setAutoscrolls(true);
buildingsScroll.getViewport().setOpaque(false);
buildingsPanel.setOpaque(false);
/** Borders */
tilesScroll.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
buildingsScroll.setBorder(BorderFactory.createEtchedBorder());
warehouseScroll.setBorder(BorderFactory.createEtchedBorder());
cargoScroll.setBorder(BorderFactory.createEtchedBorder());
inPortScroll.setBorder(BorderFactory.createEtchedBorder());
outsideColonyScroll.setBorder(BorderFactory.createEtchedBorder());
exitButton.setActionCommand(String.valueOf(EXIT));
enterPressesWhenFocused(exitButton);
exitButton.addActionListener(this);
unloadButton.setActionCommand(String.valueOf(UNLOAD));
enterPressesWhenFocused(unloadButton);
unloadButton.addActionListener(this);
fillButton.setActionCommand(String.valueOf(FILL));
enterPressesWhenFocused(fillButton);
fillButton.addActionListener(this);
warehouseButton.setActionCommand(String.valueOf(WAREHOUSE));
enterPressesWhenFocused(warehouseButton);
warehouseButton.addActionListener(this);
buildQueueButton.setActionCommand(String.valueOf(BUILDQUEUE));
enterPressesWhenFocused(buildQueueButton);
buildQueueButton.addActionListener(this);
selectedUnit = null;
// See the message of Ulf Onnen for more information about the presence
// of this fake mouse listener.
addMouseListener(new MouseAdapter() {
});
setLayout(new MigLayout("fill, wrap 2, insets 2", "[390!][fill]", "[][][][][growprio 200,shrinkprio 10][growprio 150,shrinkprio 50]"));
add(nameBox, "height 48:, grow");
add(netProductionPanel, "growx");
add(tilesScroll, "width 390!, height 200!, top");
add(buildingsScroll, "span 1 3, grow");
add(populationPanel, "grow");
add(constructionPanel, "growx, top");
add(inPortScroll, "split 2, grow, height 60:121:");
add(cargoScroll, "grow, height 60:121:");
add(outsideColonyScroll, "grow, height 60:121:");
add(warehouseScroll, "span, height 40:60:80, growx");
add(unloadButton, "span, split 5, align center");
add(fillButton);
add(warehouseButton);
add(buildQueueButton);
add(exitButton);
initialize(colony);
if (savedSize != null) {
setPreferredSize(savedSize);
}
}
@Override
public void requestFocus() {
exitButton.requestFocus();
}
/**
* Get the <code>SavedSize</code> value.
*
* @return a <code>Dimension</code> value
*/
public final Dimension getSavedSize() {
return savedSize;
}
/**
* Set the <code>SavedSize</code> value.
*
* @param newSavedSize The new SavedSize value.
*/
public final void setSavedSize(final Dimension newSavedSize) {
ColonyPanel.savedSize = newSavedSize;
}
/**
* Initialize the data on the window. This is the same as calling:
* <code>initialize(colony, game, null)</code>.
*
* @param colony The <code>Colony</code> to be displayed.
*/
public void initialize(Colony colony) {
initialize(colony, null);
}
/**
* Initialize the data on the window.
*
* @param colony The <code>Colony</code> to be displayed.
* @param preSelectedUnit This <code>Unit</code> will be selected if it is
* not <code>null</code> and it is a carrier located in the
* given <code>Colony</code>.
*/
public void initialize(final Colony colony, Unit preSelectedUnit) {
setColony(colony);
rebelShield.setIcon(new ImageIcon(ResourceManager.getImage(colony.getOwner().getNation().getId()
+ ".coat-of-arms.image", 0.5)));
royalistShield.setIcon(new ImageIcon(ResourceManager.getImage(colony.getOwner().getNation().getRefNation().getId()
+ ".coat-of-arms.image", 0.5)));
// Set listeners and transfer handlers
outsideColonyPanel.removeMouseListener(releaseListener);
inPortPanel.removeMouseListener(releaseListener);
cargoPanel.removeMouseListener(releaseListener);
warehousePanel.removeMouseListener(releaseListener);
if (isEditable()) {
outsideColonyPanel.setTransferHandler(defaultTransferHandler);
inPortPanel.setTransferHandler(defaultTransferHandler);
cargoPanel.setTransferHandler(defaultTransferHandler);
warehousePanel.setTransferHandler(defaultTransferHandler);
outsideColonyPanel.addMouseListener(releaseListener);
inPortPanel.addMouseListener(releaseListener);
cargoPanel.addMouseListener(releaseListener);
warehousePanel.addMouseListener(releaseListener);
} else {
outsideColonyPanel.setTransferHandler(null);
inPortPanel.setTransferHandler(null);
cargoPanel.setTransferHandler(null);
warehousePanel.setTransferHandler(null);
}
// Enable/disable widgets
unloadButton.setEnabled(isEditable());
fillButton.setEnabled(isEditable());
warehouseButton.setEnabled(isEditable());
nameBox.setEnabled(isEditable());
// update all the subpanels
cargoPanel.removeAll();
warehousePanel.removeAll();
tilePanel.removeAll();
inPortPanel.initialize(preSelectedUnit);
warehousePanel.initialize();
buildingsPanel.initialize();
tilePanel.initialize();
updateProductionPanel();
updateSoLLabel();
constructionPanel.setColony(colony);
outsideColonyPanel.setColony(colony);
}
/**
* Enables the unload and fill buttons if the currently selected unit is a
* carrier with some cargo.
*/
private void updateCarrierButtons() {
unloadButton.setEnabled(false);
fillButton.setEnabled(false);
if (isEditable() && selectedUnit != null) {
Unit unit = selectedUnit.getUnit();
if (unit != null && unit.isCarrier() && unit.getSpaceLeft() < unit.getType().getSpace()) {
unloadButton.setEnabled(true);
for (Goods goods : unit.getGoodsList()) {
if (getColony().getGoodsCount(goods.getType()) > 0) {
fillButton.setEnabled(true);
return;
}
}
}
}
}
/**
* Updates the SoL membership label.
*/
private void updateSoLLabel() {
int population = colony.getUnitCount();
int members = getColony().getMembers();
int rebels = getColony().getSoL();
String rebelNumber = Messages.message("colonyPanel.rebelLabel", "%number%",
Integer.toString(members));
String royalistNumber = Messages.message("colonyPanel.royalistLabel", "%number%",
Integer.toString(population - members));
/*
* TODO : remove compatibility code sometime after 0.9.1
*
* The string templates were changed from percentages to
* absolute numbers shortly before 0.9.0, so that translators
* had no chance to catch up.
*/
if (rebelNumber.endsWith("%")) {
rebelNumber = rebelNumber.substring(0, rebelNumber.length() - 1);
}
if (royalistNumber.endsWith("%")) {
royalistNumber = royalistNumber.substring(0, royalistNumber.length() - 1);
}
// end TODO
popLabel.setText(Messages.message("colonyPanel.populationLabel", "%number%",
Integer.toString(population)));
rebelLabel.setText(rebelNumber);
rebelMemberLabel.setText(Integer.toString(rebels) + "%");
bonusLabel.setText(Messages.message("colonyPanel.bonusLabel", "%number%",
Integer.toString(getColony().getProductionBonus())));
royalistLabel.setText(royalistNumber);
royalistMemberLabel.setText(Integer.toString(getColony().getTory()) + "%");
}
public void updateInPortPanel() {
inPortPanel.initialize(null);
}
public void updateWarehousePanel() {
warehousePanel.update();
}
public void updateTilePanel() {
tilePanel.initialize();
}
private void sortBuildings(List<Building> buildings) {
Collections.sort(buildings);
}
private void sortColonies(List<Colony> colonies) {
Collections.sort(colonies, getClient().getClientOptions().getColonyComparator());
}
public void updateProductionPanel() {
netProductionPanel.removeAll();
int gross = 0, net = 0;
Specification spec = getSpecification();
// food
List<AbstractGoods> ratios;
List<GoodsType> goodsTypes = spec.getFoodGoodsTypeList();
for (GoodsType goodsType : goodsTypes) {
gross += colony.getProductionOf(goodsType);
net += colony.getProductionNetOf(goodsType);
}
if (net != 0) {
GoodsType goodsType = spec.getGoodsType("model.goods.food");
netProductionPanel.add(new ProductionLabel(goodsType, net, getCanvas()));
// ratios = new ArrayList<AbstractGoods>();
// for (GoodsType goodsType : goodsTypes) {
// // get food production proportions so we can represent surplus in the same ratios
// ratios.add(new AbstractGoods(goodsType, colony.getProductionOf(goodsType) * net / gross));
// }
// netProductionPanel.add(new ProductionMultiplesLabel(ratios, getCanvas()));
}
// liberty
gross = net = 0;
goodsTypes = spec.getLibertyGoodsTypeList();
for (GoodsType goodsType : goodsTypes) {
gross += colony.getProductionOf(goodsType);
net += colony.getProductionNetOf(goodsType);
}
if (net != 0) {
GoodsType goodsType = spec.getGoodsType("model.goods.bells");
netProductionPanel.add(new ProductionLabel(goodsType, net, getCanvas()));
// ratios = new ArrayList<AbstractGoods>();
// for (GoodsType goodsType : goodsTypes) {
// ratios.add(new AbstractGoods(goodsType, colony.getProductionOf(goodsType) * net / gross));
// }
// netProductionPanel.add(new ProductionMultiplesLabel(ratios, getCanvas()));
}
// immigration
gross = net = 0;
goodsTypes = spec.getImmigrationGoodsTypeList();
for (GoodsType goodsType : goodsTypes) {
gross += colony.getProductionOf(goodsType);
net += colony.getProductionNetOf(goodsType);
}
if (net != 0) {
GoodsType goodsType = spec.getGoodsType("model.goods.crosses");
netProductionPanel.add(new ProductionLabel(goodsType, net, getCanvas()));
// ratios = new ArrayList<AbstractGoods>();
// for (GoodsType goodsType : goodsTypes) {
// ratios.add(new AbstractGoods(goodsType, colony.getProductionOf(goodsType) * net / gross));
// }
// netProductionPanel.add(new ProductionMultiplesLabel(ratios, getCanvas()));
}
List<GoodsType> generalGoods = new ArrayList<GoodsType>(spec.getGoodsTypeList());
generalGoods.removeAll(spec.getFoodGoodsTypeList());
generalGoods.removeAll(spec.getLibertyGoodsTypeList());
generalGoods.removeAll(spec.getImmigrationGoodsTypeList());
generalGoods.removeAll(spec.getFarmedGoodsTypeList());
// non-storable goods
goodsTypes = new ArrayList<GoodsType>(generalGoods);
for (GoodsType goodsType : goodsTypes) {
if (!goodsType.isStorable()) {
generalGoods.remove(goodsType);
net = colony.getProductionNetOf(goodsType);
if (net != 0) {
netProductionPanel.add(new ProductionLabel(goodsType, net, getCanvas()));
}
}
}
// farmed goods
- goodsTypes = spec.getFarmedGoodsTypeList();
+ goodsTypes = new ArrayList<GoodsType>(spec.getFarmedGoodsTypeList());
goodsTypes.removeAll(spec.getFoodGoodsTypeList());
goodsTypes.removeAll(spec.getLibertyGoodsTypeList());
goodsTypes.removeAll(spec.getImmigrationGoodsTypeList());
for (GoodsType goodsType : goodsTypes) {
net = colony.getProductionNetOf(goodsType);
if (net != 0) {
netProductionPanel.add(new ProductionLabel(goodsType, net, getCanvas()));
}
}
// everything left except military & breedables
goodsTypes = new ArrayList<GoodsType>(generalGoods);
for (GoodsType goodsType : goodsTypes) {
if (!goodsType.isMilitaryGoods() && !goodsType.isBreedable()) {
generalGoods.remove(goodsType);
net = colony.getProductionNetOf(goodsType);
if (net != 0) {
netProductionPanel.add(new ProductionLabel(goodsType, net, getCanvas()));
}
}
}
// military goods
goodsTypes = new ArrayList<GoodsType>(generalGoods);
for (GoodsType goodsType : goodsTypes) {
if (!goodsType.isBreedable()) {
generalGoods.remove(goodsType);
net = colony.getProductionNetOf(goodsType);
if (net != 0) {
netProductionPanel.add(new ProductionLabel(goodsType, net, getCanvas()));
}
}
}
// breedable things go last
goodsTypes = new ArrayList<GoodsType>(generalGoods);
for (GoodsType goodsType : goodsTypes) {
generalGoods.remove(goodsType);
net = colony.getProductionNetOf(goodsType);
if (net != 0) {
netProductionPanel.add(new ProductionLabel(goodsType, net, getCanvas()));
}
}
/*
GoodsType grain = getSpecification().getGoodsType("model.goods.food");
int food = 0;
List<AbstractGoods> foodProduction = new ArrayList<AbstractGoods>();
for (GoodsType goodsType : getSpecification().getGoodsTypeList()) {
int production = colony.getProductionOf(goodsType);
if (production != 0) {
if (goodsType.isFoodType()) {
foodProduction.add(new AbstractGoods(goodsType, production));
food += production;
} else if (goodsType.isBreedable()) {
ProductionLabel horseLabel = new ProductionLabel(goodsType, production, getCanvas());
horseLabel.setMaxGoodsIcons(1);
netProductionPanel.add(horseLabel);
} else if (goodsType.isImmigrationType() || goodsType.isLibertyType()) {
int consumption = colony.getConsumption(goodsType);
ProductionLabel bellsLabel = new ProductionLabel(goodsType, production, getCanvas());
bellsLabel.setToolTipPrefix(Messages.message("totalProduction"));
if (consumption != 0) {
int surplus = production - consumption;
ProductionLabel surplusLabel = new ProductionLabel(goodsType, surplus, getCanvas());
surplusLabel.setToolTipPrefix(Messages.message("surplusProduction"));
netProductionPanel.add(surplusLabel, 0);
}
netProductionPanel.add(bellsLabel, 0);
} else {
production = colony.getProductionNetOf(goodsType);
netProductionPanel.add(new ProductionLabel(goodsType, production, getCanvas()));
}
}
}
netProductionPanel.add(new ProductionLabel(grain, food - colony.getFoodConsumption(), getCanvas()), 0);
ProductionMultiplesLabel label = new ProductionMultiplesLabel(foodProduction, getCanvas());
label.setToolTipPrefix(Messages.message("totalProduction"));
netProductionPanel.add(label, 0);
*/
netProductionPanel.revalidate();
}
/**
* Returns the currently select unit.
*
* @return The currently select unit.
*/
public Unit getSelectedUnit() {
if (selectedUnit == null)
return null;
else
return selectedUnit.getUnit();
}
/**
* Returns the currently select unit.
*
* @return The currently select unit.
*/
public UnitLabel getSelectedUnitLabel() {
return selectedUnit;
}
/**
* Analyzes an event and calls the right external methods to take care of
* the user's request.
*
* @param event The incoming action event
*/
public void actionPerformed(ActionEvent event) {
String command = event.getActionCommand();
try {
switch (Integer.valueOf(command).intValue()) {
case EXIT:
closeColonyPanel();
break;
case UNLOAD:
unload();
break;
case WAREHOUSE:
if (getCanvas().showFreeColDialog(new WarehouseDialog(getCanvas(), colony))) {
warehousePanel.update();
}
break;
case BUILDQUEUE:
getCanvas().showSubPanel(new BuildQueuePanel(colony, getCanvas()));
break;
case FILL:
fill();
break;
default:
logger.warning("Invalid action");
}
} catch (NumberFormatException e) {
logger.warning("Invalid action number: " + command);
}
}
/**
* Unloads all goods and units from the carrier currently selected.
*/
private void unload() {
Unit unit = getSelectedUnit();
if (unit != null && unit.isCarrier()) {
Iterator<Goods> goodsIterator = unit.getGoodsIterator();
while (goodsIterator.hasNext()) {
Goods goods = goodsIterator.next();
getController().unloadCargo(goods, false);
}
Iterator<Unit> unitIterator = unit.getUnitIterator();
while (unitIterator.hasNext()) {
Unit newUnit = unitIterator.next();
getController().leaveShip(newUnit);
}
cargoPanel.initialize();
outsideColonyPanel.initialize();
}
unloadButton.setEnabled(false);
fillButton.setEnabled(false);
}
/**
* Fill goods from the carrier currently selected until 100 units.
*/
private void fill() {
Unit unit = getSelectedUnit();
if (unit != null && unit.isCarrier()) {
Iterator<Goods> goodsIterator = unit.getGoodsIterator();
while (goodsIterator.hasNext()) {
Goods goods = goodsIterator.next();
if (goods.getAmount() < 100 && colony.getGoodsCount(goods.getType()) > 0) {
int amount = Math.min(100 - goods.getAmount(), colony.getGoodsCount(goods.getType()));
getController().loadCargo(new Goods(goods.getGame(), colony, goods.getType(), amount), unit);
}
}
}
}
/**
* Closes the <code>ColonyPanel</code>.
*/
public void closeColonyPanel() {
Canvas canvas = getCanvas();
if (getColony().getUnitCount() == 0) {
if (canvas.showConfirmDialog("abandonColony.text",
"abandonColony.yes",
"abandonColony.no")) {
canvas.remove(this);
getController().abandonColony(getColony());
}
} else {
BuildableType buildable = colony.getCurrentlyBuilding();
if (buildable != null
&& buildable.getPopulationRequired() > colony.getUnitCount()
&& !canvas.showConfirmDialog(null, StringTemplate.template("colonyPanel.reducePopulation")
.addName("%colony%", colony.getName())
.addAmount("%number%", buildable.getPopulationRequired())
.add("%buildable%", buildable.getNameKey()),
"ok", "cancel")) {
return;
}
canvas.remove(this);
// remove property listeners
if (colony != null) {
colony.removePropertyChangeListener(this);
colony.getTile().removePropertyChangeListener(Tile.UNIT_CHANGE, outsideColonyPanel);
colony.getGoodsContainer().removePropertyChangeListener(warehousePanel);
}
if (getSelectedUnit() != null) {
getSelectedUnit().removePropertyChangeListener(this);
}
buildingsPanel.removePropertyChangeListeners();
tilePanel.removePropertyChangeListeners();
if (getGame().getCurrentPlayer() == getMyPlayer()) {
getController().nextModelMessage();
Unit activeUnit = canvas.getGUI().getActiveUnit();
if (activeUnit == null || activeUnit.getTile() == null || activeUnit.getMovesLeft() <= 0
|| (!(activeUnit.getLocation() instanceof Tile) && !(activeUnit.isOnCarrier()))) {
canvas.getGUI().setActiveUnit(null);
getController().nextActiveUnit();
}
}
getClient().getGUI().restartBlinking();
}
}
/**
* Selects a unit that is located somewhere on this panel.
*
* @param unit The unit that is being selected.
*/
public void setSelectedUnit(Unit unit) {
Component[] components = inPortPanel.getComponents();
for (int i = 0; i < components.length; i++) {
if (components[i] instanceof UnitLabel && ((UnitLabel) components[i]).getUnit() == unit) {
setSelectedUnitLabel((UnitLabel) components[i]);
break;
}
}
updateCarrierButtons();
}
/**
* Selects a unit that is located somewhere on this panel.
*
* @param unitLabel The unit that is being selected.
*/
public void setSelectedUnitLabel(UnitLabel unitLabel) {
if (selectedUnit != unitLabel) {
if (selectedUnit != null) {
selectedUnit.setSelected(false);
selectedUnit.getUnit().removePropertyChangeListener(this);
}
selectedUnit = unitLabel;
if (unitLabel == null) {
cargoPanel.setCarrier(null);
} else {
cargoPanel.setCarrier(unitLabel.getUnit());
unitLabel.setSelected(true);
unitLabel.getUnit().addPropertyChangeListener(this);
}
}
}
/**
* Returns a pointer to the <code>CargoPanel</code>-object in use.
*
* @return The <code>CargoPanel</code>.
*/
public final CargoPanel getCargoPanel() {
return cargoPanel;
}
/**
* Returns a pointer to the <code>WarehousePanel</code>-object in use.
*
* @return The <code>WarehousePanel</code>.
*/
public final WarehousePanel getWarehousePanel() {
return warehousePanel;
}
/**
* Returns a pointer to the <code>TilePanel</code>-object in use.
*
* @return The <code>TilePanel</code>.
*/
public final TilePanel getTilePanel() {
return tilePanel;
}
/**
* Returns a pointer to the <code>Colony</code>-pointer in use.
*
* @return The <code>Colony</code>.
*/
public synchronized final Colony getColony() {
return colony;
}
/**
* Set the current colony.
*
* @param colony The new colony value.
*/
private synchronized void setColony(Colony colony) {
if (this.colony != null){
this.colony.removePropertyChangeListener(this);
}
this.colony = colony;
if (this.colony != null){
this.colony.addPropertyChangeListener(this);
}
editable = (colony.getOwner() == getMyPlayer());
}
/**
* This panel shows the content of a carrier in the colony
*/
public final class ColonyCargoPanel extends CargoPanel {
public ColonyCargoPanel(Canvas canvas) {
super(canvas, true);
}
@Override
public String getUIClassID() {
return "CargoPanelUI";
}
}
/**
* This panel is a list of the colony's buildings.
*/
public final class BuildingsPanel extends JPanel {
private final ColonyPanel colonyPanel;
/**
* Creates this BuildingsPanel.
*
* @param colonyPanel The panel that holds this BuildingsPanel.
*/
public BuildingsPanel(ColonyPanel colonyPanel) {
setLayout(new MigLayout("wrap 4, gap 0"));
this.colonyPanel = colonyPanel;
}
@Override
public String getUIClassID() {
return "BuildingsPanelUI";
}
/**
* Initializes the <code>BuildingsPanel</code> by loading/displaying
* the buildings of the colony.
*/
public void initialize() {
removeAll();
MouseAdapter mouseAdapter = new MouseAdapter() {
public void mousePressed(MouseEvent e) {
getCanvas().showSubPanel(new BuildQueuePanel(colony, getCanvas()));
}
};
ASingleBuildingPanel aSingleBuildingPanel;
List<Building> buildings = getColony().getBuildings();
sortBuildings(buildings);
for (Building building : buildings) {
aSingleBuildingPanel = new ASingleBuildingPanel(building);
if (colonyPanel.isEditable()) {
aSingleBuildingPanel.addMouseListener(releaseListener);
aSingleBuildingPanel.setTransferHandler(defaultTransferHandler);
}
aSingleBuildingPanel.setOpaque(false);
aSingleBuildingPanel.addMouseListener(mouseAdapter);
add(aSingleBuildingPanel);
}
}
public void update(){
initialize();
}
public void removePropertyChangeListeners() {
for (Component component : getComponents()) {
if (component instanceof ASingleBuildingPanel) {
((ASingleBuildingPanel) component).removePropertyChangeListeners();
} else if (component instanceof BuildingSitePanel) {
((BuildingSitePanel) component).removePropertyChangeListeners();
}
}
}
/**
* This panel is a single line (one building) in the
* <code>BuildingsPanel</code>.
*/
public final class ASingleBuildingPanel extends BuildingPanel implements Autoscroll {
/**
* Creates this ASingleBuildingPanel.
*
* @param building The building to display information from.
*/
public ASingleBuildingPanel(Building building) {
super(building, getCanvas());
}
public void initialize() {
super.initialize();
if (colonyPanel.isEditable()) {
for (UnitLabel unitLabel : getUnitLabels()) {
unitLabel.setTransferHandler(defaultTransferHandler);
unitLabel.addMouseListener(pressListener);
}
}
}
public void autoscroll(Point p) {
JViewport vp = (JViewport) colonyPanel.buildingsPanel.getParent();
if (getLocation().y + p.y - vp.getViewPosition().y < SCROLL_AREA_HEIGHT) {
vp.setViewPosition(new Point(vp.getViewPosition().x,
Math.max(vp.getViewPosition().y - SCROLL_SPEED, 0)));
} else if (getLocation().y + p.y - vp.getViewPosition().y >= vp.getHeight() - SCROLL_AREA_HEIGHT) {
vp.setViewPosition(new Point(vp.getViewPosition().x,
Math.min(vp.getViewPosition().y + SCROLL_SPEED,
colonyPanel.buildingsPanel.getHeight()
- vp.getHeight())));
}
}
public Insets getAutoscrollInsets() {
Rectangle r = getBounds();
return new Insets(r.x, r.y, r.width, r.height);
}
/**
* Adds a component to this ASingleBuildingPanel and makes sure that
* the unit that the component represents gets modified so that it
* will be located in the colony.
*
* @param comp The component to add to this ColonistsPanel.
* @param editState Must be set to 'true' if the state of the
* component that is added (which should be a dropped
* component representing a Unit) should be changed so
* that the underlying unit will be located in the
* colony.
* @return The component argument.
*/
public Component add(Component comp, boolean editState) {
Container oldParent = comp.getParent();
if (editState) {
if (comp instanceof UnitLabel) {
Unit unit = ((UnitLabel) comp).getUnit();
if (getBuilding().canAdd(unit)) {
oldParent.remove(comp);
getController().work(unit, getBuilding());
} else {
return null;
}
} else {
logger.warning("An invalid component got dropped on this BuildingsPanel.");
return null;
}
}
initialize();
return null;
}
}
}
/**
* A panel that holds UnitLabels that represent Units that are standing in
* front of a colony.
*/
public final class OutsideColonyPanel extends JPanel implements PropertyChangeListener {
private Colony colony;
public OutsideColonyPanel() {
super();
setBorder(BorderFactory.createTitledBorder(BorderFactory.createEmptyBorder(),
Messages.message("outsideColony")));
}
public void setColony(Colony newColony) {
if (colony != null) {
colony.getTile().removePropertyChangeListener(Tile.UNIT_CHANGE, this);
}
this.colony = newColony;
if (colony != null) {
colony.getTile().addPropertyChangeListener(Tile.UNIT_CHANGE, this);
}
initialize();
}
public void initialize() {
removeAll();
if (colony == null) {
return;
}
Tile colonyTile = colony.getTile();
for (Unit unit : colonyTile.getUnitList()) {
// we only deal with land, non-carrier units here
if(unit.isNaval() || unit.isCarrier()){
continue;
}
UnitLabel unitLabel = new UnitLabel(unit, getCanvas());
if (isEditable()) {
unitLabel.setTransferHandler(defaultTransferHandler);
unitLabel.addMouseListener(pressListener);
}
add(unitLabel, false);
}
revalidate();
repaint();
}
public Colony getColony() {
return colony;
}
@Override
public String getUIClassID() {
return "OutsideColonyPanelUI";
}
/**
* Adds a component to this OutsideColonyPanel and makes sure that the
* unit that the component represents gets modified so that it will be
* located in the colony.
*
* @param comp The component to add to this ColonistsPanel.
* @param editState Must be set to 'true' if the state of the component
* that is added (which should be a dropped component
* representing a Unit) should be changed so that the
* underlying unit will be located in the colony.
* @return The component argument.
*/
public Component add(Component comp, boolean editState) {
Container oldParent = comp.getParent();
if (editState) {
if (comp instanceof UnitLabel) {
UnitLabel unitLabel = ((UnitLabel) comp);
Unit unit = unitLabel.getUnit();
if (!unit.isOnCarrier()) {
getController().putOutsideColony(unit);
}
if (unit.getColony() == null) {
closeColonyPanel();
return null;
} else if (!(unit.getLocation() instanceof Tile) && !unit.isOnCarrier()) {
return null;
}
oldParent.remove(comp);
initialize();
return comp;
} else {
logger.warning("An invalid component got dropped on this ColonistsPanel.");
return null;
}
} else {
((UnitLabel) comp).setSmall(false);
Component c = add(comp);
return c;
}
}
public void propertyChange(PropertyChangeEvent event) {
initialize();
}
}
/**
* A panel that holds UnitsLabels that represent naval Units that are
* waiting in the port of the colony.
*/
public final class InPortPanel extends JPanel {
public InPortPanel() {
super();
setBorder(BorderFactory.createTitledBorder(BorderFactory.createEmptyBorder(),
Messages.message("inPort")));
}
@Override
public String getUIClassID() {
return "InPortPanelUI";
}
public void initialize(Unit selectedUnit) {
// This is required
UnitLabel oldSelectedUnitLabel = ColonyPanel.this.getSelectedUnitLabel();
if(oldSelectedUnitLabel != null){
if(selectedUnit == null){
selectedUnit = oldSelectedUnitLabel.getUnit();
}
ColonyPanel.this.setSelectedUnit(null);
}
removeAll();
if (colony == null) {
return;
}
Tile colonyTile = colony.getTile();
Unit lastCarrier = null;
for (Unit unit : colonyTile.getUnitList()) {
if(!unit.isCarrier()){
continue;
}
lastCarrier = unit;
UnitLabel unitLabel = new UnitLabel(unit, getCanvas());
TradeRoute tradeRoute = unit.getTradeRoute();
if (tradeRoute != null) {
unitLabel.setDescriptionLabel(Messages.message(Messages.getLabel(unit))
+ " (" + tradeRoute.getName() + ")");
}
if (isEditable()) {
unitLabel.setTransferHandler(defaultTransferHandler);
unitLabel.addMouseListener(pressListener);
}
add(unitLabel, false);
}
revalidate();
repaint();
// last carrier is selected by default, if no other should be
if(selectedUnit == null && lastCarrier != null){
selectedUnit = lastCarrier;
}
// select the unit
if(selectedUnit != null){
ColonyPanel.this.setSelectedUnit(selectedUnit);
}
}
}
/**
* A panel that holds goods that represent cargo that is inside the Colony.
*/
public final class WarehousePanel extends JPanel implements PropertyChangeListener {
private final ColonyPanel colonyPanel;
/**
* Creates this WarehousePanel.
*
* @param colonyPanel The panel that holds this WarehousePanel.
*/
public WarehousePanel(ColonyPanel colonyPanel) {
this.colonyPanel = colonyPanel;
}
public void initialize() {
// get notified of warehouse changes
colony.getGoodsContainer().addPropertyChangeListener(this);
update();
revalidate();
repaint();
}
private void update() {
removeAll();
for (GoodsType goodsType : getSpecification().getGoodsTypeList()) {
if (goodsType.isStorable()) {
Goods goods = colony.getGoodsContainer().getGoods(goodsType);
if (goods.getAmount() >= getClient().getClientOptions()
.getInteger(ClientOptions.MIN_NUMBER_FOR_DISPLAYING_GOODS)) {
GoodsLabel goodsLabel = new GoodsLabel(goods, getCanvas());
if (colonyPanel.isEditable()) {
goodsLabel.setTransferHandler(defaultTransferHandler);
goodsLabel.addMouseListener(pressListener);
}
add(goodsLabel, false);
}
}
}
}
@Override
public String getUIClassID() {
return "WarehousePanelUI";
}
/**
* Adds a component to this WarehousePanel and makes sure that the unit or
* good that the component represents gets modified so that it is on
* board the currently selected ship.
*
* @param comp The component to add to this WarehousePanel.
* @param editState Must be set to 'true' if the state of the component
* that is added (which should be a dropped component
* representing a Unit or good) should be changed so that the
* underlying unit or goods are on board the currently
* selected ship.
* @return The component argument.
*/
public Component add(Component comp, boolean editState) {
if (editState) {
if (comp instanceof GoodsLabel) {
comp.getParent().remove(comp);
((GoodsLabel) comp).setSmall(false);
return comp;
}
logger.warning("An invalid component got dropped on this WarehousePanel.");
return null;
}
Component c = add(comp);
return c;
}
public void propertyChange(PropertyChangeEvent event) {
update();
}
}
/**
* A panel that displays the tiles in the immediate area around the colony.
*/
public final class TilePanel extends FreeColPanel {
private final ColonyPanel colonyPanel;
private Tile[][] tiles = new Tile[3][3];
/**
* Creates this TilePanel.
*
* @param colonyPanel The panel that holds this TilePanel.
*/
public TilePanel(ColonyPanel colonyPanel) {
super(colonyPanel.getCanvas());
this.colonyPanel = colonyPanel;
setBackground(Color.BLACK);
setBorder(null);
setLayout(null);
}
public void initialize() {
Tile tile = colony.getTile();
tiles[0][0] = tile.getNeighbourOrNull(Direction.N);
tiles[0][1] = tile.getNeighbourOrNull(Direction.NE);
tiles[0][2] = tile.getNeighbourOrNull(Direction.E);
tiles[1][0] = tile.getNeighbourOrNull(Direction.NW);
tiles[1][1] = tile;
tiles[1][2] = tile.getNeighbourOrNull(Direction.SE);
tiles[2][0] = tile.getNeighbourOrNull(Direction.W);
tiles[2][1] = tile.getNeighbourOrNull(Direction.SW);
tiles[2][2] = tile.getNeighbourOrNull(Direction.S);
int layer = 2;
for (int x = 0; x < 3; x++) {
for (int y = 0; y < 3; y++) {
if (tiles[x][y] != null) {
ColonyTile colonyTile = colony.getColonyTile(tiles[x][y]);
ASingleTilePanel p = new ASingleTilePanel(colonyTile, x, y);
add(p, new Integer(layer));
layer++;
}
}
}
}
public void removePropertyChangeListeners() {
for (Component component : getComponents()) {
if (component instanceof ASingleTilePanel) {
((ASingleTilePanel) component).removePropertyChangeListeners();
}
}
}
@Override
public void paintComponent(Graphics g) {
GUI colonyTileGUI = getCanvas().getColonyTileGUI();
Game game = colony.getGame();
g.setColor(Color.black);
g.fillRect(0, 0, getWidth(), getHeight());
TileType tileType = getColony().getTile().getType();
int tileWidth = getLibrary().getTerrainImageWidth(tileType) / 2;
int tileHeight = getLibrary().getTerrainImageHeight(tileType) / 2;
if (getColony() != null) {
for (int x = 0; x < 3; x++) {
for (int y = 0; y < 3; y++) {
if (tiles[x][y] != null) {
int xx = ((2 - x) + y) * tileWidth;
int yy = (x + y) * tileHeight;
g.translate(xx, yy);
colonyTileGUI.displayColonyTile((Graphics2D) g, game.getMap(), tiles[x][y], getColony());
g.translate(-xx, -yy);
}
}
}
}
}
/**
* Panel for visualizing a <code>ColonyTile</code>. The component
* itself is not visible, however the content of the component is (i.e.
* the people working and the production)
*/
public final class ASingleTilePanel extends JPanel implements PropertyChangeListener {
private ColonyTile colonyTile;
public ASingleTilePanel(ColonyTile colonyTile, int x, int y) {
setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0));
this.colonyTile = colonyTile;
colonyTile.addPropertyChangeListener(this);
setOpaque(false);
TileType tileType = colonyTile.getTile().getType();
// Size and position:
setSize(getLibrary().getTerrainImageWidth(tileType), getLibrary().getTerrainImageHeight(tileType));
setLocation(((2 - x) + y) * getLibrary().getTerrainImageWidth(tileType) / 2,
(x + y) * getLibrary().getTerrainImage(tileType, 0, 0).getHeight(null) / 2);
initialize();
}
private void initialize() {
removeAll();
UnitLabel unitLabel = null;
if (colonyTile.getUnit() != null) {
Unit unit = colonyTile.getUnit();
unitLabel = new UnitLabel(unit, getCanvas());
if (colonyPanel.isEditable()) {
unitLabel.setTransferHandler(defaultTransferHandler);
unitLabel.addMouseListener(pressListener);
}
super.add(unitLabel);
}
updateDescriptionLabel(unitLabel, true);
if (colonyTile.isColonyCenterTile()) {
initializeAsCenterTile();
}
if (colonyPanel.isEditable()) {
setTransferHandler(defaultTransferHandler);
addMouseListener(releaseListener);
}
revalidate();
repaint();
}
/**
* Initialized the center of the colony panel tile. The one
* containing the city.
*
*/
private void initializeAsCenterTile() {
setLayout(new GridLayout(2, 1));
TileType tileType = colonyTile.getTile().getType();
AbstractGoods primaryGoods = tileType.getPrimaryGoods();
if (primaryGoods != null) {
GoodsType goodsType = primaryGoods.getType();
ImageIcon goodsIcon = getLibrary().getGoodsImageIcon(goodsType);
ProductionLabel pl =
new ProductionLabel(goodsType, colonyTile.getProductionOf(goodsType),
getCanvas());
pl.setSize(getLibrary().getTerrainImageWidth(tileType), goodsIcon.getIconHeight());
add(pl);
}
AbstractGoods secondaryGoods = tileType.getSecondaryGoods();
if (secondaryGoods != null) {
GoodsType goodsType = secondaryGoods.getType();
ImageIcon goodsIcon = getLibrary().getGoodsImageIcon(goodsType);
ProductionLabel pl =
new ProductionLabel(goodsType, colonyTile.getProductionOf(goodsType),
getCanvas());
pl.setSize(getLibrary().getTerrainImageWidth(tileType), goodsIcon.getIconHeight());
add(pl);
}
}
public void removePropertyChangeListeners() {
colonyTile.removePropertyChangeListener(this);
}
/**
* Updates the description label The description label is a tooltip
* with the terrain type, road and plow indicator if any
*
* If a unit is on it update the tooltip of it instead
*/
private void updateDescriptionLabel(UnitLabel unit, boolean toAdd) {
String tileDescription = Messages.message(this.colonyTile.getLabel());
if (unit == null) {
setToolTipText(tileDescription);
} else {
String unitDescription = Messages.message(Messages.getLabel(unit.getUnit()));
if (toAdd) {
unitDescription = tileDescription + " [" + unitDescription + "]";
}
unit.setDescriptionLabel(unitDescription);
}
}
/**
* Adds a component to this CargoPanel and makes sure that the unit
* or good that the component represents gets modified so that it is
* on board the currently selected ship.
*
* @param comp The component to add to this CargoPanel.
* @param editState Must be set to 'true' if the state of the
* component that is added (which should be a dropped
* component representing a Unit or good) should be
* changed so that the underlying unit or goods are on
* board the currently selected ship.
* @return The component argument.
*/
public Component add(Component comp, boolean editState) {
Container oldParent = comp.getParent();
if (editState) {
if (comp instanceof UnitLabel) {
Unit unit = ((UnitLabel) comp).getUnit();
Tile tile = colonyTile.getWorkTile();
Player player = unit.getOwner();
logger.info("Colony " + colony.getName()
+ " claims tile " + tile.toString()
+ " with unit " + unit.getId());
if ((tile.getOwner() != player
|| tile.getOwningSettlement() != colony)
&& !getController().claimLand(tile, colony, 0)) {
logger.warning("Colony " + colony.getName()
+ " could not claim tile " + tile.toString()
+ " with unit " + unit.getId());
return null;
}
if (colonyTile.canAdd(unit)) {
oldParent.remove(comp);
GoodsType workType = colonyTile.getWorkType(unit);
getController().work(unit, colonyTile);
// check whether worktype is suitable
if (workType != unit.getWorkType()) {
getController().changeWorkType(unit, workType);
}
((UnitLabel) comp).setSmall(false);
if (getClient().getClientOptions().getBoolean(ClientOptions.SHOW_NOT_BEST_TILE)) {
ColonyTile bestTile = colony.getVacantColonyTileFor(unit, false, workType);
if (colonyTile != bestTile
&& (colonyTile.getProductionOf(unit, workType)
< bestTile.getProductionOf(unit, workType))) {
StringTemplate template = StringTemplate.template("colonyPanel.notBestTile")
.addStringTemplate("%unit%", Messages.getLabel(unit))
.add("%goods%", workType.getNameKey())
.addStringTemplate("%tile%", bestTile.getLabel());
getCanvas().showInformationMessage(template);
}
}
} else {
// could not add the unit on the tile
Canvas canvas = getCanvas();
Tile workTile = colonyTile.getWorkTile();
Settlement s = workTile.getOwningSettlement();
if (s != null && s != getColony()) {
if (s.getOwner() == player) {
// Its one of ours
canvas.errorMessage("tileTakenSelf");
} else if (s.getOwner().isEuropean()) {
// occupied by a foreign european colony
canvas.errorMessage("tileTakenEuro");
} else if (s instanceof IndianSettlement) {
// occupied by an indian settlement
canvas.errorMessage("tileTakenInd");
}
} else {
if(colonyTile.getUnitCount() > 0) { // Tile is already occupied
;
} else if (!workTile.isLand()) { // no docks
canvas.errorMessage("tileNeedsDocks");
} else if (workTile.hasLostCityRumour()) {
canvas.errorMessage("tileHasRumour");
}
}
return null;
}
} else {
logger.warning("An invalid component got dropped on this CargoPanel.");
return null;
}
}
/*
* At this point, the panel has already been updated
* via the property change listener.
*
removeAll();
Component c = super.add(comp);
refresh();
*/
return comp;
}
public void propertyChange(PropertyChangeEvent event) {
initialize();
}
/**
* Checks if this <code>JComponent</code> contains the given
* coordinate.
*/
@Override
public boolean contains(int px, int py) {
int w = getWidth();
int h = getHeight();
int dx = Math.abs(w/2 - px);
int dy = Math.abs(h/2 - py);
return (dx + w * dy / h) <= w/2;
}
}
}
public void propertyChange(PropertyChangeEvent e) {
if (!isShowing() || getColony() == null) {
return;
}
String property = e.getPropertyName();
if (Unit.CARGO_CHANGE.equals(property)) {
updateInPortPanel();
} else if (ColonyChangeEvent.POPULATION_CHANGE.toString().equals(property)) {
updateSoLLabel();
} else if (ColonyChangeEvent.BONUS_CHANGE.toString().equals(property)) {
ModelMessage msg = getColony().checkForGovMgtChangeMessage();
if (msg != null) {
getCanvas().showInformationMessage(msg);
}
updateSoLLabel();
} else if (ColonyChangeEvent.UNIT_TYPE_CHANGE.toString().equals(property)) {
FreeColGameObject object = (FreeColGameObject) e.getSource();
String oldType = (String) e.getOldValue();
String newType = (String) e.getNewValue();
getCanvas().showInformationMessage(object,
"model.colony.unitChange",
"%oldType%", oldType,
"%newType%", newType);
updateTilePanel();
} else if (ColonyTile.UNIT_CHANGE.toString().equals(property)) {
updateTilePanel();
updateProductionPanel();
} else if (property.startsWith("model.goods.")) {
// changes to warehouse goods count may affect building production
//which requires a view update
updateProductionPanel();
updateWarehousePanel();
buildingsPanel.update();
} else if (Building.UNIT_CHANGE.equals(property)) {
// already processed by BuildingPanel
} else {
logger.warning("Unknown property change event: " + e.getPropertyName());
}
}
}
| true | true | public void updateProductionPanel() {
netProductionPanel.removeAll();
int gross = 0, net = 0;
Specification spec = getSpecification();
// food
List<AbstractGoods> ratios;
List<GoodsType> goodsTypes = spec.getFoodGoodsTypeList();
for (GoodsType goodsType : goodsTypes) {
gross += colony.getProductionOf(goodsType);
net += colony.getProductionNetOf(goodsType);
}
if (net != 0) {
GoodsType goodsType = spec.getGoodsType("model.goods.food");
netProductionPanel.add(new ProductionLabel(goodsType, net, getCanvas()));
// ratios = new ArrayList<AbstractGoods>();
// for (GoodsType goodsType : goodsTypes) {
// // get food production proportions so we can represent surplus in the same ratios
// ratios.add(new AbstractGoods(goodsType, colony.getProductionOf(goodsType) * net / gross));
// }
// netProductionPanel.add(new ProductionMultiplesLabel(ratios, getCanvas()));
}
// liberty
gross = net = 0;
goodsTypes = spec.getLibertyGoodsTypeList();
for (GoodsType goodsType : goodsTypes) {
gross += colony.getProductionOf(goodsType);
net += colony.getProductionNetOf(goodsType);
}
if (net != 0) {
GoodsType goodsType = spec.getGoodsType("model.goods.bells");
netProductionPanel.add(new ProductionLabel(goodsType, net, getCanvas()));
// ratios = new ArrayList<AbstractGoods>();
// for (GoodsType goodsType : goodsTypes) {
// ratios.add(new AbstractGoods(goodsType, colony.getProductionOf(goodsType) * net / gross));
// }
// netProductionPanel.add(new ProductionMultiplesLabel(ratios, getCanvas()));
}
// immigration
gross = net = 0;
goodsTypes = spec.getImmigrationGoodsTypeList();
for (GoodsType goodsType : goodsTypes) {
gross += colony.getProductionOf(goodsType);
net += colony.getProductionNetOf(goodsType);
}
if (net != 0) {
GoodsType goodsType = spec.getGoodsType("model.goods.crosses");
netProductionPanel.add(new ProductionLabel(goodsType, net, getCanvas()));
// ratios = new ArrayList<AbstractGoods>();
// for (GoodsType goodsType : goodsTypes) {
// ratios.add(new AbstractGoods(goodsType, colony.getProductionOf(goodsType) * net / gross));
// }
// netProductionPanel.add(new ProductionMultiplesLabel(ratios, getCanvas()));
}
List<GoodsType> generalGoods = new ArrayList<GoodsType>(spec.getGoodsTypeList());
generalGoods.removeAll(spec.getFoodGoodsTypeList());
generalGoods.removeAll(spec.getLibertyGoodsTypeList());
generalGoods.removeAll(spec.getImmigrationGoodsTypeList());
generalGoods.removeAll(spec.getFarmedGoodsTypeList());
// non-storable goods
goodsTypes = new ArrayList<GoodsType>(generalGoods);
for (GoodsType goodsType : goodsTypes) {
if (!goodsType.isStorable()) {
generalGoods.remove(goodsType);
net = colony.getProductionNetOf(goodsType);
if (net != 0) {
netProductionPanel.add(new ProductionLabel(goodsType, net, getCanvas()));
}
}
}
// farmed goods
goodsTypes = spec.getFarmedGoodsTypeList();
goodsTypes.removeAll(spec.getFoodGoodsTypeList());
goodsTypes.removeAll(spec.getLibertyGoodsTypeList());
goodsTypes.removeAll(spec.getImmigrationGoodsTypeList());
for (GoodsType goodsType : goodsTypes) {
net = colony.getProductionNetOf(goodsType);
if (net != 0) {
netProductionPanel.add(new ProductionLabel(goodsType, net, getCanvas()));
}
}
// everything left except military & breedables
goodsTypes = new ArrayList<GoodsType>(generalGoods);
for (GoodsType goodsType : goodsTypes) {
if (!goodsType.isMilitaryGoods() && !goodsType.isBreedable()) {
generalGoods.remove(goodsType);
net = colony.getProductionNetOf(goodsType);
if (net != 0) {
netProductionPanel.add(new ProductionLabel(goodsType, net, getCanvas()));
}
}
}
// military goods
goodsTypes = new ArrayList<GoodsType>(generalGoods);
for (GoodsType goodsType : goodsTypes) {
if (!goodsType.isBreedable()) {
generalGoods.remove(goodsType);
net = colony.getProductionNetOf(goodsType);
if (net != 0) {
netProductionPanel.add(new ProductionLabel(goodsType, net, getCanvas()));
}
}
}
// breedable things go last
goodsTypes = new ArrayList<GoodsType>(generalGoods);
for (GoodsType goodsType : goodsTypes) {
generalGoods.remove(goodsType);
net = colony.getProductionNetOf(goodsType);
if (net != 0) {
netProductionPanel.add(new ProductionLabel(goodsType, net, getCanvas()));
}
}
/*
GoodsType grain = getSpecification().getGoodsType("model.goods.food");
int food = 0;
List<AbstractGoods> foodProduction = new ArrayList<AbstractGoods>();
for (GoodsType goodsType : getSpecification().getGoodsTypeList()) {
int production = colony.getProductionOf(goodsType);
if (production != 0) {
if (goodsType.isFoodType()) {
foodProduction.add(new AbstractGoods(goodsType, production));
food += production;
} else if (goodsType.isBreedable()) {
ProductionLabel horseLabel = new ProductionLabel(goodsType, production, getCanvas());
horseLabel.setMaxGoodsIcons(1);
netProductionPanel.add(horseLabel);
} else if (goodsType.isImmigrationType() || goodsType.isLibertyType()) {
int consumption = colony.getConsumption(goodsType);
ProductionLabel bellsLabel = new ProductionLabel(goodsType, production, getCanvas());
bellsLabel.setToolTipPrefix(Messages.message("totalProduction"));
if (consumption != 0) {
int surplus = production - consumption;
ProductionLabel surplusLabel = new ProductionLabel(goodsType, surplus, getCanvas());
surplusLabel.setToolTipPrefix(Messages.message("surplusProduction"));
netProductionPanel.add(surplusLabel, 0);
}
netProductionPanel.add(bellsLabel, 0);
} else {
production = colony.getProductionNetOf(goodsType);
netProductionPanel.add(new ProductionLabel(goodsType, production, getCanvas()));
}
}
}
netProductionPanel.add(new ProductionLabel(grain, food - colony.getFoodConsumption(), getCanvas()), 0);
ProductionMultiplesLabel label = new ProductionMultiplesLabel(foodProduction, getCanvas());
label.setToolTipPrefix(Messages.message("totalProduction"));
netProductionPanel.add(label, 0);
*/
netProductionPanel.revalidate();
}
| public void updateProductionPanel() {
netProductionPanel.removeAll();
int gross = 0, net = 0;
Specification spec = getSpecification();
// food
List<AbstractGoods> ratios;
List<GoodsType> goodsTypes = spec.getFoodGoodsTypeList();
for (GoodsType goodsType : goodsTypes) {
gross += colony.getProductionOf(goodsType);
net += colony.getProductionNetOf(goodsType);
}
if (net != 0) {
GoodsType goodsType = spec.getGoodsType("model.goods.food");
netProductionPanel.add(new ProductionLabel(goodsType, net, getCanvas()));
// ratios = new ArrayList<AbstractGoods>();
// for (GoodsType goodsType : goodsTypes) {
// // get food production proportions so we can represent surplus in the same ratios
// ratios.add(new AbstractGoods(goodsType, colony.getProductionOf(goodsType) * net / gross));
// }
// netProductionPanel.add(new ProductionMultiplesLabel(ratios, getCanvas()));
}
// liberty
gross = net = 0;
goodsTypes = spec.getLibertyGoodsTypeList();
for (GoodsType goodsType : goodsTypes) {
gross += colony.getProductionOf(goodsType);
net += colony.getProductionNetOf(goodsType);
}
if (net != 0) {
GoodsType goodsType = spec.getGoodsType("model.goods.bells");
netProductionPanel.add(new ProductionLabel(goodsType, net, getCanvas()));
// ratios = new ArrayList<AbstractGoods>();
// for (GoodsType goodsType : goodsTypes) {
// ratios.add(new AbstractGoods(goodsType, colony.getProductionOf(goodsType) * net / gross));
// }
// netProductionPanel.add(new ProductionMultiplesLabel(ratios, getCanvas()));
}
// immigration
gross = net = 0;
goodsTypes = spec.getImmigrationGoodsTypeList();
for (GoodsType goodsType : goodsTypes) {
gross += colony.getProductionOf(goodsType);
net += colony.getProductionNetOf(goodsType);
}
if (net != 0) {
GoodsType goodsType = spec.getGoodsType("model.goods.crosses");
netProductionPanel.add(new ProductionLabel(goodsType, net, getCanvas()));
// ratios = new ArrayList<AbstractGoods>();
// for (GoodsType goodsType : goodsTypes) {
// ratios.add(new AbstractGoods(goodsType, colony.getProductionOf(goodsType) * net / gross));
// }
// netProductionPanel.add(new ProductionMultiplesLabel(ratios, getCanvas()));
}
List<GoodsType> generalGoods = new ArrayList<GoodsType>(spec.getGoodsTypeList());
generalGoods.removeAll(spec.getFoodGoodsTypeList());
generalGoods.removeAll(spec.getLibertyGoodsTypeList());
generalGoods.removeAll(spec.getImmigrationGoodsTypeList());
generalGoods.removeAll(spec.getFarmedGoodsTypeList());
// non-storable goods
goodsTypes = new ArrayList<GoodsType>(generalGoods);
for (GoodsType goodsType : goodsTypes) {
if (!goodsType.isStorable()) {
generalGoods.remove(goodsType);
net = colony.getProductionNetOf(goodsType);
if (net != 0) {
netProductionPanel.add(new ProductionLabel(goodsType, net, getCanvas()));
}
}
}
// farmed goods
goodsTypes = new ArrayList<GoodsType>(spec.getFarmedGoodsTypeList());
goodsTypes.removeAll(spec.getFoodGoodsTypeList());
goodsTypes.removeAll(spec.getLibertyGoodsTypeList());
goodsTypes.removeAll(spec.getImmigrationGoodsTypeList());
for (GoodsType goodsType : goodsTypes) {
net = colony.getProductionNetOf(goodsType);
if (net != 0) {
netProductionPanel.add(new ProductionLabel(goodsType, net, getCanvas()));
}
}
// everything left except military & breedables
goodsTypes = new ArrayList<GoodsType>(generalGoods);
for (GoodsType goodsType : goodsTypes) {
if (!goodsType.isMilitaryGoods() && !goodsType.isBreedable()) {
generalGoods.remove(goodsType);
net = colony.getProductionNetOf(goodsType);
if (net != 0) {
netProductionPanel.add(new ProductionLabel(goodsType, net, getCanvas()));
}
}
}
// military goods
goodsTypes = new ArrayList<GoodsType>(generalGoods);
for (GoodsType goodsType : goodsTypes) {
if (!goodsType.isBreedable()) {
generalGoods.remove(goodsType);
net = colony.getProductionNetOf(goodsType);
if (net != 0) {
netProductionPanel.add(new ProductionLabel(goodsType, net, getCanvas()));
}
}
}
// breedable things go last
goodsTypes = new ArrayList<GoodsType>(generalGoods);
for (GoodsType goodsType : goodsTypes) {
generalGoods.remove(goodsType);
net = colony.getProductionNetOf(goodsType);
if (net != 0) {
netProductionPanel.add(new ProductionLabel(goodsType, net, getCanvas()));
}
}
/*
GoodsType grain = getSpecification().getGoodsType("model.goods.food");
int food = 0;
List<AbstractGoods> foodProduction = new ArrayList<AbstractGoods>();
for (GoodsType goodsType : getSpecification().getGoodsTypeList()) {
int production = colony.getProductionOf(goodsType);
if (production != 0) {
if (goodsType.isFoodType()) {
foodProduction.add(new AbstractGoods(goodsType, production));
food += production;
} else if (goodsType.isBreedable()) {
ProductionLabel horseLabel = new ProductionLabel(goodsType, production, getCanvas());
horseLabel.setMaxGoodsIcons(1);
netProductionPanel.add(horseLabel);
} else if (goodsType.isImmigrationType() || goodsType.isLibertyType()) {
int consumption = colony.getConsumption(goodsType);
ProductionLabel bellsLabel = new ProductionLabel(goodsType, production, getCanvas());
bellsLabel.setToolTipPrefix(Messages.message("totalProduction"));
if (consumption != 0) {
int surplus = production - consumption;
ProductionLabel surplusLabel = new ProductionLabel(goodsType, surplus, getCanvas());
surplusLabel.setToolTipPrefix(Messages.message("surplusProduction"));
netProductionPanel.add(surplusLabel, 0);
}
netProductionPanel.add(bellsLabel, 0);
} else {
production = colony.getProductionNetOf(goodsType);
netProductionPanel.add(new ProductionLabel(goodsType, production, getCanvas()));
}
}
}
netProductionPanel.add(new ProductionLabel(grain, food - colony.getFoodConsumption(), getCanvas()), 0);
ProductionMultiplesLabel label = new ProductionMultiplesLabel(foodProduction, getCanvas());
label.setToolTipPrefix(Messages.message("totalProduction"));
netProductionPanel.add(label, 0);
*/
netProductionPanel.revalidate();
}
|
diff --git a/src/halo/query/model/ModelMethod.java b/src/halo/query/model/ModelMethod.java
index 16743ab..61017e1 100644
--- a/src/halo/query/model/ModelMethod.java
+++ b/src/halo/query/model/ModelMethod.java
@@ -1,123 +1,123 @@
package halo.query.model;
import java.util.ArrayList;
import java.util.List;
import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.CtNewMethod;
import javassist.NotFoundException;
/**
* 使用javassit自动生成方法代码
*
* @author akwei
*/
public class ModelMethod {
private static CtMethod createMethod(String methodFunc,
CtClass ctClass) throws CannotCompileException {
return CtNewMethod.make(methodFunc, ctClass);
}
public static List<CtMethod> addNewMethod(ClassPool pool, String className,
CtClass ctClass)
throws CannotCompileException, NotFoundException {
List<CtMethod> list = new ArrayList<CtMethod>();
CtClass stringCls = pool.get("java.lang.String");
CtClass objectsCls = pool.get("java.lang.Object[]");
CtClass objectCls = pool.get("java.lang.Object");
CtClass intCls = pool.get("int");
String classInMethod = className + ".class";
// count
try {
ctClass.getDeclaredMethod("count", new CtClass[] { stringCls,
objectsCls });
}
catch (NotFoundException e) {
list.add(createMethod(
"public static int count(String sqlAfterTable, Object[] values){"
+ "return query.count("
+ classInMethod
+ ", sqlAfterTable, values);"
+ "}", ctClass));
}
// objById
try {
ctClass.getDeclaredMethod("objById", new CtClass[] {
objectCls });
}
catch (NotFoundException e) {
list.add(createMethod(
"public static Object objById(Object idValue) {"
+ "return query.objById(" + classInMethod
+ ", idValue);" + "}",
ctClass));
}
// obj
try {
ctClass.getDeclaredMethod("obj", new CtClass[] {
stringCls, objectsCls });
}
catch (NotFoundException e) {
list.add(createMethod(
"public static Object obj(String sqlAfterTable, Object[] values) {"
+ "return query.obj(" + classInMethod
+ ", sqlAfterTable, values);"
+ "}", ctClass));
}
// mysqlList
try {
ctClass.getDeclaredMethod("mysqlList", new CtClass[] {
stringCls, intCls, intCls, objectsCls });
}
catch (NotFoundException e) {
list.add(createMethod(
"public static java.util.List mysqlList(String sqlAfterTable, int begin, int size, Object[] values) {"
+ "return query.mysqlList("
+ classInMethod
+ ", sqlAfterTable, begin, size, values);"
+ "}", ctClass));
}
// db2List
try {
ctClass.getDeclaredMethod("db2List", new CtClass[] {
stringCls, intCls, intCls, objectsCls });
}
catch (NotFoundException e) {
list.add(createMethod(
"public static java.util.List db2List(String where, String orderBy, int begin, int size, Object[] values) {"
+ "return query.db2List("
+ classInMethod
+ ", where, orderBy, begin, size, values);"
+ "}", ctClass));
}
// update
try {
ctClass.getDeclaredMethod("update", new CtClass[] {
stringCls, objectsCls });
}
catch (NotFoundException e) {
list.add(createMethod(
- "public int update(String updateSqlSeg, Object[] values) {"
+ "public static int update(String updateSqlSeg, Object[] values) {"
+ "return query.update(" + classInMethod
+ ", updateSqlSeg, values);"
+ "}", ctClass));
}
try {
ctClass.getDeclaredMethod("list", new CtClass[] { stringCls,
objectsCls });
}
catch (NotFoundException e) {
list.add(createMethod(
"public static java.util.List list(String afterFrom, Object[] values) {"
+ "return query.list("
+ classInMethod
+ ", afterFrom, values);"
+ "}", ctClass));
}
return list;
}
}
| true | true | public static List<CtMethod> addNewMethod(ClassPool pool, String className,
CtClass ctClass)
throws CannotCompileException, NotFoundException {
List<CtMethod> list = new ArrayList<CtMethod>();
CtClass stringCls = pool.get("java.lang.String");
CtClass objectsCls = pool.get("java.lang.Object[]");
CtClass objectCls = pool.get("java.lang.Object");
CtClass intCls = pool.get("int");
String classInMethod = className + ".class";
// count
try {
ctClass.getDeclaredMethod("count", new CtClass[] { stringCls,
objectsCls });
}
catch (NotFoundException e) {
list.add(createMethod(
"public static int count(String sqlAfterTable, Object[] values){"
+ "return query.count("
+ classInMethod
+ ", sqlAfterTable, values);"
+ "}", ctClass));
}
// objById
try {
ctClass.getDeclaredMethod("objById", new CtClass[] {
objectCls });
}
catch (NotFoundException e) {
list.add(createMethod(
"public static Object objById(Object idValue) {"
+ "return query.objById(" + classInMethod
+ ", idValue);" + "}",
ctClass));
}
// obj
try {
ctClass.getDeclaredMethod("obj", new CtClass[] {
stringCls, objectsCls });
}
catch (NotFoundException e) {
list.add(createMethod(
"public static Object obj(String sqlAfterTable, Object[] values) {"
+ "return query.obj(" + classInMethod
+ ", sqlAfterTable, values);"
+ "}", ctClass));
}
// mysqlList
try {
ctClass.getDeclaredMethod("mysqlList", new CtClass[] {
stringCls, intCls, intCls, objectsCls });
}
catch (NotFoundException e) {
list.add(createMethod(
"public static java.util.List mysqlList(String sqlAfterTable, int begin, int size, Object[] values) {"
+ "return query.mysqlList("
+ classInMethod
+ ", sqlAfterTable, begin, size, values);"
+ "}", ctClass));
}
// db2List
try {
ctClass.getDeclaredMethod("db2List", new CtClass[] {
stringCls, intCls, intCls, objectsCls });
}
catch (NotFoundException e) {
list.add(createMethod(
"public static java.util.List db2List(String where, String orderBy, int begin, int size, Object[] values) {"
+ "return query.db2List("
+ classInMethod
+ ", where, orderBy, begin, size, values);"
+ "}", ctClass));
}
// update
try {
ctClass.getDeclaredMethod("update", new CtClass[] {
stringCls, objectsCls });
}
catch (NotFoundException e) {
list.add(createMethod(
"public int update(String updateSqlSeg, Object[] values) {"
+ "return query.update(" + classInMethod
+ ", updateSqlSeg, values);"
+ "}", ctClass));
}
try {
ctClass.getDeclaredMethod("list", new CtClass[] { stringCls,
objectsCls });
}
catch (NotFoundException e) {
list.add(createMethod(
"public static java.util.List list(String afterFrom, Object[] values) {"
+ "return query.list("
+ classInMethod
+ ", afterFrom, values);"
+ "}", ctClass));
}
return list;
}
| public static List<CtMethod> addNewMethod(ClassPool pool, String className,
CtClass ctClass)
throws CannotCompileException, NotFoundException {
List<CtMethod> list = new ArrayList<CtMethod>();
CtClass stringCls = pool.get("java.lang.String");
CtClass objectsCls = pool.get("java.lang.Object[]");
CtClass objectCls = pool.get("java.lang.Object");
CtClass intCls = pool.get("int");
String classInMethod = className + ".class";
// count
try {
ctClass.getDeclaredMethod("count", new CtClass[] { stringCls,
objectsCls });
}
catch (NotFoundException e) {
list.add(createMethod(
"public static int count(String sqlAfterTable, Object[] values){"
+ "return query.count("
+ classInMethod
+ ", sqlAfterTable, values);"
+ "}", ctClass));
}
// objById
try {
ctClass.getDeclaredMethod("objById", new CtClass[] {
objectCls });
}
catch (NotFoundException e) {
list.add(createMethod(
"public static Object objById(Object idValue) {"
+ "return query.objById(" + classInMethod
+ ", idValue);" + "}",
ctClass));
}
// obj
try {
ctClass.getDeclaredMethod("obj", new CtClass[] {
stringCls, objectsCls });
}
catch (NotFoundException e) {
list.add(createMethod(
"public static Object obj(String sqlAfterTable, Object[] values) {"
+ "return query.obj(" + classInMethod
+ ", sqlAfterTable, values);"
+ "}", ctClass));
}
// mysqlList
try {
ctClass.getDeclaredMethod("mysqlList", new CtClass[] {
stringCls, intCls, intCls, objectsCls });
}
catch (NotFoundException e) {
list.add(createMethod(
"public static java.util.List mysqlList(String sqlAfterTable, int begin, int size, Object[] values) {"
+ "return query.mysqlList("
+ classInMethod
+ ", sqlAfterTable, begin, size, values);"
+ "}", ctClass));
}
// db2List
try {
ctClass.getDeclaredMethod("db2List", new CtClass[] {
stringCls, intCls, intCls, objectsCls });
}
catch (NotFoundException e) {
list.add(createMethod(
"public static java.util.List db2List(String where, String orderBy, int begin, int size, Object[] values) {"
+ "return query.db2List("
+ classInMethod
+ ", where, orderBy, begin, size, values);"
+ "}", ctClass));
}
// update
try {
ctClass.getDeclaredMethod("update", new CtClass[] {
stringCls, objectsCls });
}
catch (NotFoundException e) {
list.add(createMethod(
"public static int update(String updateSqlSeg, Object[] values) {"
+ "return query.update(" + classInMethod
+ ", updateSqlSeg, values);"
+ "}", ctClass));
}
try {
ctClass.getDeclaredMethod("list", new CtClass[] { stringCls,
objectsCls });
}
catch (NotFoundException e) {
list.add(createMethod(
"public static java.util.List list(String afterFrom, Object[] values) {"
+ "return query.list("
+ classInMethod
+ ", afterFrom, values);"
+ "}", ctClass));
}
return list;
}
|
diff --git a/java/src/general/SearchBitonicArray.java b/java/src/general/SearchBitonicArray.java
index c03fa34..79b5e9c 100644
--- a/java/src/general/SearchBitonicArray.java
+++ b/java/src/general/SearchBitonicArray.java
@@ -1,129 +1,126 @@
package general;
/**
* Search in a bitonic array. An array is bitonic if it is comprised of an
* increasing sequence of integers followed immediately by a decreasing sequence
* of integers. Write a program that, given a bitonic array of N distinct
* integer values, determines whether a given integer is in the array.
*
* Standard version: Use ~3lgN compares in the worst case.
* Optimal version: Use ~2lgN compares in the worst case (and prove that
* no algorithm can guarantee to perform fewer than ~2lgN compares in the worst case).
*/
public class SearchBitonicArray {
public static int searchBitonicArray(int[] array, int value) {
if (array == null) {
return -1;
}
return searchBitonicArray(array, value, 0, array.length - 1);
}
private static int searchBitonicArray(int[] array, int value,
int startIndex, int endIndex) {
if (startIndex > endIndex) {
return -1;
}
int middleIndex = (startIndex + endIndex) / 2;
if (value == array[middleIndex]) {
return middleIndex;
}
if (array[middleIndex] < array[startIndex]) {
//
// V /\ V
// V / \ V
// S \ V
// \ V
// \ M
// \
// \
// \
// E
//
// Here,
// S => startIndex
// M => middleIndex
// E => endIndex
// V => possible indices of searched value.
//
// In the diagram above, by definition of bitonic
// array, when array[middleIndex] < array[startIndex],
// then array[middleIndex] is always greater than array[endIndex].
if (value > array[middleIndex]) {
return searchBitonicArray(array, value, startIndex,
middleIndex - 1);
}
//
// /\
// / \
// S \
// \ M
// \ V
// \ V
// \ V
// \ V
// E
return searchBitonicArray(array, value, middleIndex + 1, endIndex);
}
// If value > array[middleIndex], then the value could exist
// to the right or the left of middleIndex, so we have to
// search on both sides of middleIndex.
//
- // First case:
- //
- //
// V /\ V
// / \ M
// / \
// / \
// S \
// \
// \
// \
// E
// V /\ V
// M / \
// / \
// / \
// / \
// / E
// /
// S
//
// Similarly, if value < array[middleIndex], then the value could exist
// to the right or the left of middleIndex, so we have to
// search on both sides of middleIndex.
//
// First case:
//
// /\
// / \ M
// / \ V
// / \ V
// S \ V
// \ V
// \ V
// \ V
// E
// /\
// M / \
// V / \
// V / \
// V / \
// V / E
// V /
// S
//
int found = searchBitonicArray(array, value, startIndex,
middleIndex - 1);
if (found == -1) {
found = searchBitonicArray(array, value, middleIndex + 1, endIndex);
}
return found;
}
}
| true | true | private static int searchBitonicArray(int[] array, int value,
int startIndex, int endIndex) {
if (startIndex > endIndex) {
return -1;
}
int middleIndex = (startIndex + endIndex) / 2;
if (value == array[middleIndex]) {
return middleIndex;
}
if (array[middleIndex] < array[startIndex]) {
//
// V /\ V
// V / \ V
// S \ V
// \ V
// \ M
// \
// \
// \
// E
//
// Here,
// S => startIndex
// M => middleIndex
// E => endIndex
// V => possible indices of searched value.
//
// In the diagram above, by definition of bitonic
// array, when array[middleIndex] < array[startIndex],
// then array[middleIndex] is always greater than array[endIndex].
if (value > array[middleIndex]) {
return searchBitonicArray(array, value, startIndex,
middleIndex - 1);
}
//
// /\
// / \
// S \
// \ M
// \ V
// \ V
// \ V
// \ V
// E
return searchBitonicArray(array, value, middleIndex + 1, endIndex);
}
// If value > array[middleIndex], then the value could exist
// to the right or the left of middleIndex, so we have to
// search on both sides of middleIndex.
//
// First case:
//
//
// V /\ V
// / \ M
// / \
// / \
// S \
// \
// \
// \
// E
// V /\ V
// M / \
// / \
// / \
// / \
// / E
// /
// S
//
// Similarly, if value < array[middleIndex], then the value could exist
// to the right or the left of middleIndex, so we have to
// search on both sides of middleIndex.
//
// First case:
//
// /\
// / \ M
// / \ V
// / \ V
// S \ V
// \ V
// \ V
// \ V
// E
// /\
// M / \
// V / \
// V / \
// V / \
// V / E
// V /
// S
//
int found = searchBitonicArray(array, value, startIndex,
middleIndex - 1);
if (found == -1) {
found = searchBitonicArray(array, value, middleIndex + 1, endIndex);
}
return found;
}
| private static int searchBitonicArray(int[] array, int value,
int startIndex, int endIndex) {
if (startIndex > endIndex) {
return -1;
}
int middleIndex = (startIndex + endIndex) / 2;
if (value == array[middleIndex]) {
return middleIndex;
}
if (array[middleIndex] < array[startIndex]) {
//
// V /\ V
// V / \ V
// S \ V
// \ V
// \ M
// \
// \
// \
// E
//
// Here,
// S => startIndex
// M => middleIndex
// E => endIndex
// V => possible indices of searched value.
//
// In the diagram above, by definition of bitonic
// array, when array[middleIndex] < array[startIndex],
// then array[middleIndex] is always greater than array[endIndex].
if (value > array[middleIndex]) {
return searchBitonicArray(array, value, startIndex,
middleIndex - 1);
}
//
// /\
// / \
// S \
// \ M
// \ V
// \ V
// \ V
// \ V
// E
return searchBitonicArray(array, value, middleIndex + 1, endIndex);
}
// If value > array[middleIndex], then the value could exist
// to the right or the left of middleIndex, so we have to
// search on both sides of middleIndex.
//
// V /\ V
// / \ M
// / \
// / \
// S \
// \
// \
// \
// E
// V /\ V
// M / \
// / \
// / \
// / \
// / E
// /
// S
//
// Similarly, if value < array[middleIndex], then the value could exist
// to the right or the left of middleIndex, so we have to
// search on both sides of middleIndex.
//
// First case:
//
// /\
// / \ M
// / \ V
// / \ V
// S \ V
// \ V
// \ V
// \ V
// E
// /\
// M / \
// V / \
// V / \
// V / \
// V / E
// V /
// S
//
int found = searchBitonicArray(array, value, startIndex,
middleIndex - 1);
if (found == -1) {
found = searchBitonicArray(array, value, middleIndex + 1, endIndex);
}
return found;
}
|
diff --git a/bikeshed/src/com/google/gwt/sample/expenses/gwt/client/ExpensesMobile.java b/bikeshed/src/com/google/gwt/sample/expenses/gwt/client/ExpensesMobile.java
index 14fed5747..6b3bc7349 100644
--- a/bikeshed/src/com/google/gwt/sample/expenses/gwt/client/ExpensesMobile.java
+++ b/bikeshed/src/com/google/gwt/sample/expenses/gwt/client/ExpensesMobile.java
@@ -1,126 +1,125 @@
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.gwt.sample.expenses.gwt.client;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.requestfactory.client.AuthenticationFailureHandler;
import com.google.gwt.requestfactory.client.LoginWidget;
import com.google.gwt.requestfactory.shared.Receiver;
import com.google.gwt.requestfactory.shared.RequestEvent;
import com.google.gwt.requestfactory.shared.UserInformationRecord;
import com.google.gwt.sample.expenses.gwt.request.EmployeeRecord;
import com.google.gwt.sample.expenses.gwt.request.ExpensesRequestFactory;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.Window.Location;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.valuestore.shared.SyncResult;
import com.google.gwt.valuestore.shared.Value;
import java.util.Set;
/**
* Entry point for the mobile version of the Expenses app.
*/
public class ExpensesMobile implements EntryPoint {
/**
* The url parameter that specifies the employee id.
*/
private static final String EMPLOYEE_ID_PARAM = "employeeId";
/**
* TODO(jgw): Put this some place more sensible.
*
* @param amount the amount in dollars
*/
public static String formatCurrency(double amount) {
StringBuilder sb = new StringBuilder();
int price = (int) (amount * 100);
boolean negative = price < 0;
if (negative) {
price = -price;
}
int dollars = price / 100;
int cents = price % 100;
if (negative) {
sb.append("-");
}
sb.append(dollars);
sb.append('.');
if (cents < 10) {
sb.append('0');
}
sb.append(cents);
return sb.toString();
}
/**
* This is the entry point method.
*/
public void onModuleLoad() {
// Get the employee ID from the URL.
long employeeId = 1;
try {
String value = Window.Location.getParameter(EMPLOYEE_ID_PARAM);
if (value != null && value.length() > 0) {
employeeId = Long.parseLong(value);
}
} catch (NumberFormatException e) {
RootPanel.get().add(new Label("employeeId is invalid"));
return;
}
final HandlerManager eventBus = new HandlerManager(null);
final ExpensesRequestFactory requestFactory = GWT.create(
ExpensesRequestFactory.class);
requestFactory.init(eventBus);
final long finalEmployeeId = employeeId;
requestFactory.employeeRequest().findEmployee(Value.of(employeeId)).fire(
new Receiver<EmployeeRecord>() {
- @Override
public void onSuccess(EmployeeRecord employee,
Set<SyncResult> syncResults) {
final ExpensesMobileShell shell = new ExpensesMobileShell(eventBus,
requestFactory, employee);
RootPanel.get().add(shell);
// Check for Authentication failures or mismatches
eventBus.addHandler(RequestEvent.TYPE,
new AuthenticationFailureHandler());
// Add a login widget to the page
final LoginWidget login = shell.getLoginWidget();
Receiver<UserInformationRecord> receiver
= new Receiver<UserInformationRecord>() {
public void onSuccess(UserInformationRecord userInformationRecord,
Set<SyncResult> syncResults) {
login.setUserInformation(userInformationRecord);
}
};
requestFactory.userInformationRequest().getCurrentUserInformation(
Location.getHref()).fire(receiver);
}
- } );
+ });
}
}
| false | true | public void onModuleLoad() {
// Get the employee ID from the URL.
long employeeId = 1;
try {
String value = Window.Location.getParameter(EMPLOYEE_ID_PARAM);
if (value != null && value.length() > 0) {
employeeId = Long.parseLong(value);
}
} catch (NumberFormatException e) {
RootPanel.get().add(new Label("employeeId is invalid"));
return;
}
final HandlerManager eventBus = new HandlerManager(null);
final ExpensesRequestFactory requestFactory = GWT.create(
ExpensesRequestFactory.class);
requestFactory.init(eventBus);
final long finalEmployeeId = employeeId;
requestFactory.employeeRequest().findEmployee(Value.of(employeeId)).fire(
new Receiver<EmployeeRecord>() {
@Override
public void onSuccess(EmployeeRecord employee,
Set<SyncResult> syncResults) {
final ExpensesMobileShell shell = new ExpensesMobileShell(eventBus,
requestFactory, employee);
RootPanel.get().add(shell);
// Check for Authentication failures or mismatches
eventBus.addHandler(RequestEvent.TYPE,
new AuthenticationFailureHandler());
// Add a login widget to the page
final LoginWidget login = shell.getLoginWidget();
Receiver<UserInformationRecord> receiver
= new Receiver<UserInformationRecord>() {
public void onSuccess(UserInformationRecord userInformationRecord,
Set<SyncResult> syncResults) {
login.setUserInformation(userInformationRecord);
}
};
requestFactory.userInformationRequest().getCurrentUserInformation(
Location.getHref()).fire(receiver);
}
} );
}
| public void onModuleLoad() {
// Get the employee ID from the URL.
long employeeId = 1;
try {
String value = Window.Location.getParameter(EMPLOYEE_ID_PARAM);
if (value != null && value.length() > 0) {
employeeId = Long.parseLong(value);
}
} catch (NumberFormatException e) {
RootPanel.get().add(new Label("employeeId is invalid"));
return;
}
final HandlerManager eventBus = new HandlerManager(null);
final ExpensesRequestFactory requestFactory = GWT.create(
ExpensesRequestFactory.class);
requestFactory.init(eventBus);
final long finalEmployeeId = employeeId;
requestFactory.employeeRequest().findEmployee(Value.of(employeeId)).fire(
new Receiver<EmployeeRecord>() {
public void onSuccess(EmployeeRecord employee,
Set<SyncResult> syncResults) {
final ExpensesMobileShell shell = new ExpensesMobileShell(eventBus,
requestFactory, employee);
RootPanel.get().add(shell);
// Check for Authentication failures or mismatches
eventBus.addHandler(RequestEvent.TYPE,
new AuthenticationFailureHandler());
// Add a login widget to the page
final LoginWidget login = shell.getLoginWidget();
Receiver<UserInformationRecord> receiver
= new Receiver<UserInformationRecord>() {
public void onSuccess(UserInformationRecord userInformationRecord,
Set<SyncResult> syncResults) {
login.setUserInformation(userInformationRecord);
}
};
requestFactory.userInformationRequest().getCurrentUserInformation(
Location.getHref()).fire(receiver);
}
});
}
|
diff --git a/cmds/monkey/src/com/android/commands/monkey/MonkeyActivityEvent.java b/cmds/monkey/src/com/android/commands/monkey/MonkeyActivityEvent.java
index 262377a..6d91ab9 100644
--- a/cmds/monkey/src/com/android/commands/monkey/MonkeyActivityEvent.java
+++ b/cmds/monkey/src/com/android/commands/monkey/MonkeyActivityEvent.java
@@ -1,84 +1,84 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.commands.monkey;
import android.app.IActivityManager;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.os.RemoteException;
import android.view.IWindowManager;
import android.util.Log;
/**
* monkey activity event
*/
public class MonkeyActivityEvent extends MonkeyEvent {
private ComponentName mApp;
long mAlarmTime = 0;
public MonkeyActivityEvent(ComponentName app) {
super(EVENT_TYPE_ACTIVITY);
mApp = app;
}
public MonkeyActivityEvent(ComponentName app, long arg) {
super(EVENT_TYPE_ACTIVITY);
mApp = app;
mAlarmTime = arg;
}
/**
* @return Intent for the new activity
*/
private Intent getEvent() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setComponent(mApp);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
return intent;
}
@Override
public int injectEvent(IWindowManager iwm, IActivityManager iam, int verbose) {
Intent intent = getEvent();
if (verbose > 0) {
System.out.println(":Switch: " + intent.toURI());
}
if (mAlarmTime != 0){
Bundle args = new Bundle();
args.putLong("alarmTime", mAlarmTime);
intent.putExtras(args);
}
try {
iam.startActivity(null, intent, null, null, 0, null, null, 0,
- false, false);
+ false, false, null, null, false);
} catch (RemoteException e) {
System.err.println("** Failed talking with activity manager!");
return MonkeyEvent.INJECT_ERROR_REMOTE_EXCEPTION;
} catch (SecurityException e) {
if (verbose > 0) {
System.out.println("** Permissions error starting activity "
+ intent.toURI());
}
return MonkeyEvent.INJECT_ERROR_SECURITY_EXCEPTION;
}
return MonkeyEvent.INJECT_SUCCESS;
}
}
| true | true | public int injectEvent(IWindowManager iwm, IActivityManager iam, int verbose) {
Intent intent = getEvent();
if (verbose > 0) {
System.out.println(":Switch: " + intent.toURI());
}
if (mAlarmTime != 0){
Bundle args = new Bundle();
args.putLong("alarmTime", mAlarmTime);
intent.putExtras(args);
}
try {
iam.startActivity(null, intent, null, null, 0, null, null, 0,
false, false);
} catch (RemoteException e) {
System.err.println("** Failed talking with activity manager!");
return MonkeyEvent.INJECT_ERROR_REMOTE_EXCEPTION;
} catch (SecurityException e) {
if (verbose > 0) {
System.out.println("** Permissions error starting activity "
+ intent.toURI());
}
return MonkeyEvent.INJECT_ERROR_SECURITY_EXCEPTION;
}
return MonkeyEvent.INJECT_SUCCESS;
}
| public int injectEvent(IWindowManager iwm, IActivityManager iam, int verbose) {
Intent intent = getEvent();
if (verbose > 0) {
System.out.println(":Switch: " + intent.toURI());
}
if (mAlarmTime != 0){
Bundle args = new Bundle();
args.putLong("alarmTime", mAlarmTime);
intent.putExtras(args);
}
try {
iam.startActivity(null, intent, null, null, 0, null, null, 0,
false, false, null, null, false);
} catch (RemoteException e) {
System.err.println("** Failed talking with activity manager!");
return MonkeyEvent.INJECT_ERROR_REMOTE_EXCEPTION;
} catch (SecurityException e) {
if (verbose > 0) {
System.out.println("** Permissions error starting activity "
+ intent.toURI());
}
return MonkeyEvent.INJECT_ERROR_SECURITY_EXCEPTION;
}
return MonkeyEvent.INJECT_SUCCESS;
}
|
diff --git a/src/core/java/org/wyona/yanel/servlet/CreateUsecaseHelper.java b/src/core/java/org/wyona/yanel/servlet/CreateUsecaseHelper.java
index 6df0a2efb..16d8c3d91 100644
--- a/src/core/java/org/wyona/yanel/servlet/CreateUsecaseHelper.java
+++ b/src/core/java/org/wyona/yanel/servlet/CreateUsecaseHelper.java
@@ -1,251 +1,251 @@
/*
* Copyright 2006 Wyona
*
* 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.wyona.org/licenses/APACHE-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.wyona.yanel.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.net.URL;
import org.apache.log4j.Logger;
import org.w3c.dom.Element;
import org.wyona.yanel.core.ResourceTypeDefinition;
import org.wyona.yanel.core.Resource;
import org.wyona.yanel.core.ResourceTypeRegistry;
import org.wyona.yanel.core.Yanel;
import org.wyona.yanel.core.map.Map;
//import org.wyona.yanel.core.map.MapFactory;
import org.wyona.yanel.core.api.attributes.ViewableV1;
import org.wyona.yanel.core.api.attributes.ViewableV2;
import org.wyona.yanel.core.api.attributes.CreatableV2;
import org.wyona.yanel.core.util.ResourceAttributeHelper;
import org.wyona.yanel.core.Path;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
*/
public class CreateUsecaseHelper {
private static Logger log = Logger.getLogger(CreateUsecaseHelper.class);
/**
*
*/
public HttpServletResponse create(HttpServletRequest request, HttpServletResponse response, org.wyona.yanel.core.Yanel yanel) throws IOException {
String createName = request.getParameter("create.name");
String resourceType = request.getParameter("resource.type");
String create = request.getParameter("create");
PrintWriter w = response.getWriter();
if (resourceType == null || createName == null) {
w.print(resourcesTypeSelectScreen(createName));
} else {
if(create == null){
if (resourceType.equals("") || createName.equals("")) {
w.print(resourcesTypeSelectScreen(createName));
} else {
w.print(createResourceScreen(createName, resourceType));
}
} else{
w.print(doCreate(resourceType, request, response, createName, yanel));
}
}
// TODO: Should this really be set here ...
response.setContentType("text/html");
response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK);
return response;
}
/**
* @return A XHTML page with the resource selection screen
*/
public String resourcesTypeSelectScreen(String createName) {
StringBuffer form = new StringBuffer();
form.append("<?xml version=\"1.0\"?>");
form.append("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
form.append("<body>");
form.append("<form>");
form.append("<input type=\"hidden\" name=\"yanel.usecase\" value=\"create\"/>");
if (createName != null) {
form.append("Name: <input type=\"text\" name=\"create.name\" value=\"" + createName + "\"/>");
} else {
form.append("Name: <input type=\"text\" name=\"create.name\"/>");
}
form.append("<br/>Resource Type: <select name=\"resource.type\">");
ResourceTypeRegistry rtr = new ResourceTypeRegistry();
ResourceTypeDefinition[] rtds = rtr.getResourceTypeDefinitions();
for (int i = 0; i < rtds.length; i++) {
try {
Resource resource = rtr.newResource(rtds[i].getResourceTypeUniversalName());
if (resource != null && ResourceAttributeHelper.hasAttributeImplemented(resource, "Creatable", "2")) {
form.append("<option value=\"" + rtds[i].getResourceTypeUniversalName() + "\">" + rtds[i].getResourceTypeLocalName() + "</option>");
}
} catch(Exception e) {
log.error(e);
}
}
form.append("</select>");
form.append("<br/><input type=\"submit\" value=\"Next\"/>");
form.append("</form>");
form.append("</body>");
form.append("</html>");
return form.toString();
}
/**
* @return a html page with the resource selction screen as a string
*/
public String createResourceScreen(String createName, String rti) {
String resourcesCreateScreen = null;
String[] PropertyNames = null;
ResourceTypeRegistry rtr = new ResourceTypeRegistry();
try {
Resource resource = rtr.newResource(rti);
if (resource != null) {
if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Creatable", "2")) {
PropertyNames = ((CreatableV2) resource).getPropertyNames();
((CreatableV2) resource).setProperty("Name", createName);
StringBuffer form = new StringBuffer();
form.append("<?xml version=\"1.0\"?>");
form.append("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
form.append("<body>");
form.append("<h1>Create new resource</h1>");
if (createName == null) {
form.append("Name: <input type=\"text\"/><br/>");
} else {
form.append("Name: " + createName + "<br/>");
}
form.append("Resource Type: " + rti + "<br/><br/>");
form.append("<form>");
form.append("<input type=\"hidden\" name=\"yanel.usecase\" value=\"create\"/>");
form.append("<input type=\"hidden\" name=\"resource.type\" value=\""+rti+"\"/>");
form.append("<input type=\"hidden\" name=\"create.name\" value=\""+createName+"\"/>");
form.append("<input type=\"hidden\" name=\"create\" value=\"create.resource\"/>");
if (PropertyNames != null && PropertyNames.length > 0) {
form.append("<p>Resource specific properties:</p>");
for (int i = 0; i < PropertyNames.length; i++) {
form.append(PropertyNames[i] + ": <input name=\"" + PropertyNames[i]
+ "\" value=\""
+ ((CreatableV2) resource).getProperty(PropertyNames[i])
- + "\" size=\"60\">");
+ + "\" size=\"60\"><br/>");
}
} else {
form.append("<p>No resource specific properties!</p>");
}
form.append("<br/><br/><input type=\"submit\" value=\"Create Resource\"/>");
form.append("</form>");
form.append("</body>");
form.append("</html>");
resourcesCreateScreen = form.toString();
return resourcesCreateScreen;
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
String message = e.toString();
log.error(e.getMessage(), e);
// Element exceptionElement = (Element)
// rootElement.appendChild(doc.createElement("exception"));
// exceptionElement.appendChild(doc.createTextNode(message));
// setYanelOutput(response, doc);
// response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return message;
}
return resourcesCreateScreen;
}
/**
*
*/
public String doCreate(String newResourceType, HttpServletRequest request, HttpServletResponse response, String createName, org.wyona.yanel.core.Yanel yanel) {
String responseAfterCreationScreen = null;
String[] PropertyNames = null;
try {
org.wyona.yanel.core.map.Realm realm = yanel.getMap().getRealm(request.getServletPath());
Path pathFromWhereCreateUsecaseHasBeenIssued = yanel.getMap().getPath(realm, request.getServletPath());
org.wyona.commons.io.Path parent = pathFromWhereCreateUsecaseHasBeenIssued.getParent();
Path newPath = null;
if(parent.equals("null")) {
// if pathFromWhereCreateUsecaseHasBeenIssued is ROOT
newPath = new Path("/" + createName);
} else {
newPath = new Path(parent + "/" + createName);
}
Resource newResource = yanel.getResourceManager().getResource(request, response, realm, newPath, new ResourceTypeRegistry().getResourceTypeDefinition(newResourceType), new org.wyona.yanel.core.ResourceTypeIdentifier(newResourceType, null));
if (newResource != null) {
if (ResourceAttributeHelper.hasAttributeImplemented(newResource, "Creatable", "2")) {
PropertyNames = ((CreatableV2) newResource).getPropertyNames();
((CreatableV2) newResource).create(request);
//response after creation, better would be a redirect to the fresh created resource
StringBuffer form = new StringBuffer();
form.append("<?xml version=\"1.0\"?>");
form.append("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
form.append("<body>");
form.append("New resource has been created successfully: <a href=\"" + createName + "\">" + createName + "</a>");
form.append("</body>");
responseAfterCreationScreen = form.toString();
}else{
//response after creation failed
StringBuffer form = new StringBuffer();
form.append("<?xml version=\"1.0\"?>");
form.append("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
form.append("<body>");
form.append("creation NOT successfull!");
form.append("</body>");
responseAfterCreationScreen = form.toString();
}
return responseAfterCreationScreen;
}
}
catch (Exception e) {
log.error(e.getMessage(), e);
String message = e.toString();
log.error(e.getMessage(), e);
// Element exceptionElement = (Element)
// rootElement.appendChild(doc.createElement("exception"));
// exceptionElement.appendChild(doc.createTextNode(message));
// setYanelOutput(response, doc);
// response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return message;
}
return responseAfterCreationScreen;
}
}
| true | true | public String createResourceScreen(String createName, String rti) {
String resourcesCreateScreen = null;
String[] PropertyNames = null;
ResourceTypeRegistry rtr = new ResourceTypeRegistry();
try {
Resource resource = rtr.newResource(rti);
if (resource != null) {
if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Creatable", "2")) {
PropertyNames = ((CreatableV2) resource).getPropertyNames();
((CreatableV2) resource).setProperty("Name", createName);
StringBuffer form = new StringBuffer();
form.append("<?xml version=\"1.0\"?>");
form.append("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
form.append("<body>");
form.append("<h1>Create new resource</h1>");
if (createName == null) {
form.append("Name: <input type=\"text\"/><br/>");
} else {
form.append("Name: " + createName + "<br/>");
}
form.append("Resource Type: " + rti + "<br/><br/>");
form.append("<form>");
form.append("<input type=\"hidden\" name=\"yanel.usecase\" value=\"create\"/>");
form.append("<input type=\"hidden\" name=\"resource.type\" value=\""+rti+"\"/>");
form.append("<input type=\"hidden\" name=\"create.name\" value=\""+createName+"\"/>");
form.append("<input type=\"hidden\" name=\"create\" value=\"create.resource\"/>");
if (PropertyNames != null && PropertyNames.length > 0) {
form.append("<p>Resource specific properties:</p>");
for (int i = 0; i < PropertyNames.length; i++) {
form.append(PropertyNames[i] + ": <input name=\"" + PropertyNames[i]
+ "\" value=\""
+ ((CreatableV2) resource).getProperty(PropertyNames[i])
+ "\" size=\"60\">");
}
} else {
form.append("<p>No resource specific properties!</p>");
}
form.append("<br/><br/><input type=\"submit\" value=\"Create Resource\"/>");
form.append("</form>");
form.append("</body>");
form.append("</html>");
resourcesCreateScreen = form.toString();
return resourcesCreateScreen;
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
String message = e.toString();
log.error(e.getMessage(), e);
// Element exceptionElement = (Element)
// rootElement.appendChild(doc.createElement("exception"));
// exceptionElement.appendChild(doc.createTextNode(message));
// setYanelOutput(response, doc);
// response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return message;
}
return resourcesCreateScreen;
}
| public String createResourceScreen(String createName, String rti) {
String resourcesCreateScreen = null;
String[] PropertyNames = null;
ResourceTypeRegistry rtr = new ResourceTypeRegistry();
try {
Resource resource = rtr.newResource(rti);
if (resource != null) {
if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Creatable", "2")) {
PropertyNames = ((CreatableV2) resource).getPropertyNames();
((CreatableV2) resource).setProperty("Name", createName);
StringBuffer form = new StringBuffer();
form.append("<?xml version=\"1.0\"?>");
form.append("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
form.append("<body>");
form.append("<h1>Create new resource</h1>");
if (createName == null) {
form.append("Name: <input type=\"text\"/><br/>");
} else {
form.append("Name: " + createName + "<br/>");
}
form.append("Resource Type: " + rti + "<br/><br/>");
form.append("<form>");
form.append("<input type=\"hidden\" name=\"yanel.usecase\" value=\"create\"/>");
form.append("<input type=\"hidden\" name=\"resource.type\" value=\""+rti+"\"/>");
form.append("<input type=\"hidden\" name=\"create.name\" value=\""+createName+"\"/>");
form.append("<input type=\"hidden\" name=\"create\" value=\"create.resource\"/>");
if (PropertyNames != null && PropertyNames.length > 0) {
form.append("<p>Resource specific properties:</p>");
for (int i = 0; i < PropertyNames.length; i++) {
form.append(PropertyNames[i] + ": <input name=\"" + PropertyNames[i]
+ "\" value=\""
+ ((CreatableV2) resource).getProperty(PropertyNames[i])
+ "\" size=\"60\"><br/>");
}
} else {
form.append("<p>No resource specific properties!</p>");
}
form.append("<br/><br/><input type=\"submit\" value=\"Create Resource\"/>");
form.append("</form>");
form.append("</body>");
form.append("</html>");
resourcesCreateScreen = form.toString();
return resourcesCreateScreen;
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
String message = e.toString();
log.error(e.getMessage(), e);
// Element exceptionElement = (Element)
// rootElement.appendChild(doc.createElement("exception"));
// exceptionElement.appendChild(doc.createTextNode(message));
// setYanelOutput(response, doc);
// response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return message;
}
return resourcesCreateScreen;
}
|
diff --git a/src/joshua/decoder/ff/lm/LanguageModelFF.java b/src/joshua/decoder/ff/lm/LanguageModelFF.java
index c51f74f2..2957bfc5 100644
--- a/src/joshua/decoder/ff/lm/LanguageModelFF.java
+++ b/src/joshua/decoder/ff/lm/LanguageModelFF.java
@@ -1,357 +1,357 @@
/* This file is part of the Joshua Machine Translation System.
*
* Joshua 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 joshua.decoder.ff.lm;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import joshua.corpus.Vocabulary;
import joshua.decoder.chart_parser.SourcePath;
import joshua.decoder.ff.DefaultStatefulFF;
import joshua.decoder.ff.state_maintenance.DPState;
import joshua.decoder.ff.state_maintenance.NgramDPState;
import joshua.decoder.ff.tm.Rule;
import joshua.decoder.hypergraph.HGNode;
/**
* This class performs the following:
* <ol>
* <li> Gets the additional LM score due to combinations of small
* items into larger ones by using rules
* <li> Gets the LM state
* <li> Gets the left-side LM state estimation score
* </ol>
*
*
* @author Zhifei Li, <[email protected]>
* @version $LastChangedDate$
*/
public class LanguageModelFF extends DefaultStatefulFF {
/** Logger for this class. */
private static final Logger logger = Logger.getLogger(LanguageModelFF.class.getName());
private final String START_SYM="<s>";
private final int START_SYM_ID;
private final String STOP_SYM="</s>";
private final int STOP_SYM_ID;
/* These must be static (for now) for LMGrammar, but they shouldn't be! in case of multiple LM features */
static String BACKOFF_LEFT_LM_STATE_SYM="<lzfbo>";
static public int BACKOFF_LEFT_LM_STATE_SYM_ID;//used for equivelant state
static String NULL_RIGHT_LM_STATE_SYM="<lzfrnull>";
static public int NULL_RIGHT_LM_STATE_SYM_ID;//used for equivelant state
private final boolean addStartAndEndSymbol = true;
/**
* N-gram language model. We assume the language model is
* in ARPA format for equivalent state:
*
* <ol>
* <li>We assume it is a backoff lm, and high-order ngram
* implies low-order ngram; absense of low-order ngram
* implies high-order ngram</li>
* <li>For a ngram, existence of backoffweight => existence
* a probability Two ways of dealing with low counts:
* <ul>
* <li>SRILM: don't multiply zeros in for unknown
* words</li>
* <li>Pharaoh: cap at a minimum score exp(-10),
* including unknown words</li>
* </ul>
* </li>
*/
private final NGramLanguageModel lmGrammar;
/**
* We always use this order of ngram, though the LMGrammar
* may provide higher order probability.
*/
private final int ngramOrder;// = 3;
//boolean add_boundary=false; //this is needed unless the text already has <s> and </s>
/** stateID is any integer exept -1
**/
public LanguageModelFF(int stateID, int featID, int ngramOrder, NGramLanguageModel lmGrammar, double weight) {
super(stateID, weight, featID);
this.ngramOrder = ngramOrder;
this.lmGrammar = lmGrammar;
this.START_SYM_ID = Vocabulary.id(START_SYM);
this.STOP_SYM_ID = Vocabulary.id(STOP_SYM);
LanguageModelFF.BACKOFF_LEFT_LM_STATE_SYM_ID = Vocabulary.id(BACKOFF_LEFT_LM_STATE_SYM);
LanguageModelFF.NULL_RIGHT_LM_STATE_SYM_ID = Vocabulary.id(NULL_RIGHT_LM_STATE_SYM);
}
public double transitionLogP(Rule rule, List<HGNode> antNodes, int spanStart, int spanEnd, SourcePath srcPath, int sentID) {
return computeTransition(rule.getEnglish(), antNodes);
}
public double finalTransitionLogP(HGNode antNode, int spanStart, int spanEnd, SourcePath srcPath, int sentID) {
return computeFinalTransitionLogP((NgramDPState)antNode.getDPState(this.getStateID()));
}
/**will consider all the complete ngrams,
* and all the incomplete-ngrams that will have sth fit into its left side*/
public double estimateLogP(Rule rule, int sentID) {
return estimateRuleLogProb(rule.getEnglish());
}
public double estimateFutureLogP(Rule rule, DPState curDPState, int sentID) {
//TODO: do not consider <s> and </s>
boolean addStart = false;
boolean addEnd = false;
return estimateStateLogProb((NgramDPState)curDPState, addStart, addEnd);
}
/**
* Compute the cost of a rule application. The cost of applying a
* rule is computed by determining the n-gram costs for all
* n-grams created by this rule application, and summing them.
* N-grams are created when (a) terminal words in the rule string
* are followed by a nonterminal (b) terminal words in the rule
* string are preceded by a nonterminal (c) we encounter adjacent
* nonterminals. In all of these situations, the corresponding
* boundary words of the node in the hypergraph represented by the
* nonterminal must be retrieved.
*/
private double computeTransition(int[] enWords, List<HGNode> antNodes) {
List<Integer> currentNgram = new ArrayList<Integer>();
double transitionLogP = 0.0;
for (int c = 0; c < enWords.length; c++) {
int curID = enWords[c];
- if (Vocabulary.isNonterminal(curID)) {
+ if (Vocabulary.nt(curID)) {
int index = -(curID + 1);
NgramDPState state = (NgramDPState) antNodes.get(index).getDPState(this.getStateID());
List<Integer> leftContext = state.getLeftLMStateWords();
List<Integer> rightContext = state.getRightLMStateWords();
if (leftContext.size() != rightContext.size() ) {
throw new RuntimeException("computeTransition: left and right contexts have unequal lengths");
}
//================ left context
for (int i = 0; i < leftContext.size(); i++) {
int t = leftContext.get(i);
currentNgram.add(t);
//always calculate logP for <bo>: additional backoff weight
if (t == BACKOFF_LEFT_LM_STATE_SYM_ID) {
int numAdditionalBackoffWeight = currentNgram.size() - (i+1);//number of non-state words
//compute additional backoff weight
transitionLogP += this.lmGrammar.logProbOfBackoffState(currentNgram, currentNgram.size(), numAdditionalBackoffWeight);
if (currentNgram.size() == this.ngramOrder) {
currentNgram.remove(0);
}
} else if (currentNgram.size() == this.ngramOrder) {
// compute the current word probablity, and remove it
transitionLogP += this.lmGrammar.ngramLogProbability(currentNgram, this.ngramOrder);
currentNgram.remove(0);
}
}
//================ right context
int tSize = currentNgram.size();
for (int i = 0; i < rightContext.size(); i++) {
// replace context
currentNgram.set(tSize - rightContext.size() + i, rightContext.get(i) );
}
} else { // terminal words
currentNgram.add(curID);
if (currentNgram.size() == this.ngramOrder) {
// compute the current word probablity, and remove it
transitionLogP += this.lmGrammar.ngramLogProbability(currentNgram, this.ngramOrder);
currentNgram.remove(0);
}
}
}
//===== create tabl
//===== get left euquiv state
//double[] lmLeftCost = new double[2];
//int[] equivLeftState = this.lmGrammar.leftEquivalentState(Support.subIntArray(leftLMStateWrds, 0, leftLMStateWrds.size()), this.ngramOrder, lmLeftCost);
//transitionCost += lmLeftCost[0];//add finalized cost for the left state words
return transitionLogP;
}
private double computeFinalTransitionLogP(NgramDPState state) {
double res = 0.0;
List<Integer> currentNgram = new ArrayList<Integer>();
List<Integer> leftContext = state.getLeftLMStateWords();
List<Integer> rightContext = state.getRightLMStateWords();
if (leftContext.size() != rightContext.size()) {
throw new RuntimeException(
"LMModel.compute_equiv_state_final_transition: left and right contexts have unequal lengths");
}
//================ left context
if (addStartAndEndSymbol)
currentNgram.add(START_SYM_ID);
for (int i = 0; i < leftContext.size(); i++) {
int t = leftContext.get(i);
currentNgram.add(t);
if (t == BACKOFF_LEFT_LM_STATE_SYM_ID) {//calculate logP for <bo>: additional backoff weight
int additionalBackoffWeight = currentNgram.size() - (i+1);
//compute additional backoff weight
//TOTO: may not work with the case that add_start_and_end_symbol=false
res += this.lmGrammar.logProbOfBackoffState(
currentNgram, currentNgram.size(), additionalBackoffWeight);
} else { // partial ngram
//compute the current word probablity
if (currentNgram.size() >= 2) { // start from bigram
res += this.lmGrammar.ngramLogProbability(
currentNgram, currentNgram.size());
}
}
if (currentNgram.size() == this.ngramOrder) {
currentNgram.remove(0);
}
}
//================ right context
//switch context, we will never score the right context probablity because they are either duplicate or partional ngram
if(addStartAndEndSymbol){
int tSize = currentNgram.size();
for (int i = 0; i < rightContext.size(); i++) {//replace context
currentNgram.set(tSize - rightContext.size() + i, rightContext.get(i));
}
currentNgram.add(STOP_SYM_ID);
res += this.lmGrammar.ngramLogProbability(currentNgram, currentNgram.size());
}
return res;
}
/*in general: consider all the complete ngrams, and all the incomplete-ngrams that WILL have sth fit into its left side, so
*if the left side of incomplete-ngrams is a ECLIPS, then ignore the incomplete-ngrams
*if the left side of incomplete-ngrams is a Non-Terminal, then consider the incomplete-ngrams
*if the left side of incomplete-ngrams is boundary of a rule, then consider the incomplete-ngrams*/
private double estimateRuleLogProb(int[] enWords) {
double estimate = 0.0;
boolean considerIncompleteNgrams = true;
List<Integer> words = new ArrayList<Integer>();
boolean skipStart = (enWords[0] == START_SYM_ID);
for (int c = 0; c < enWords.length; c++) {
int curWrd = enWords[c];
/*if (c_wrd == Symbol.ECLIPS_SYM_ID) {
estimate += score_chunk(
words, consider_incomplete_ngrams, skip_start);
consider_incomplete_ngrams = false;
//for the LM bonus function: this simply means the right state will not be considered at all because all the ngrams in right-context will be incomplete
words.clear();
skip_start = false;
} else*/ if( Vocabulary.nt(curWrd) ) {
estimate += scoreChunkLogP( words, considerIncompleteNgrams, skipStart);
considerIncompleteNgrams = true;
words.clear();
skipStart = false;
} else {
words.add(curWrd);
}
}
estimate += scoreChunkLogP( words, considerIncompleteNgrams, skipStart );
return estimate;
}
/**TODO:
* This does not work when addStart == true or addEnd == true
**/
private double estimateStateLogProb(NgramDPState state, boolean addStart, boolean addEnd) {
double res = 0.0;
List<Integer> leftContext = state.getLeftLMStateWords();
if (null != leftContext) {
List<Integer> words = new ArrayList<Integer>();;
if (addStart == true)
words.add(START_SYM_ID);
words.addAll(leftContext);
boolean considerIncompleteNgrams = true;
boolean skipStart = true;
if (words.get(0) != START_SYM_ID) {
skipStart = false;
}
res += scoreChunkLogP(words, considerIncompleteNgrams, skipStart);
}
/*if (add_start == true) {
System.out.println("left context: " +Symbol.get_string(l_context) + ";prob "+res);
}*/
if (addEnd == true) {//only when add_end is true, we get a complete ngram, otherwise, all ngrams in r_state are incomplete and we should do nothing
List<Integer> rightContext = state.getRightLMStateWords();
List<Integer> list = new ArrayList<Integer>(rightContext);
list.add(STOP_SYM_ID);
double tem = scoreChunkLogP(list, false, false);
res += tem;
//System.out.println("right context:"+ Symbol.get_string(r_context) + "; score: " + tem);
}
return res;
}
private double scoreChunkLogP(List<Integer> words, boolean considerIncompleteNgrams, boolean skipStart) {
if (words.size() <= 0) {
return 0.0;
} else {
int startIndex;
if (! considerIncompleteNgrams) {
startIndex = this.ngramOrder;
} else if (skipStart) {
startIndex = 2;
} else {
startIndex = 1;
}
return this.lmGrammar.sentenceLogProbability(
words, this.ngramOrder, startIndex);
}
}
}
| true | true | private double computeTransition(int[] enWords, List<HGNode> antNodes) {
List<Integer> currentNgram = new ArrayList<Integer>();
double transitionLogP = 0.0;
for (int c = 0; c < enWords.length; c++) {
int curID = enWords[c];
if (Vocabulary.isNonterminal(curID)) {
int index = -(curID + 1);
NgramDPState state = (NgramDPState) antNodes.get(index).getDPState(this.getStateID());
List<Integer> leftContext = state.getLeftLMStateWords();
List<Integer> rightContext = state.getRightLMStateWords();
if (leftContext.size() != rightContext.size() ) {
throw new RuntimeException("computeTransition: left and right contexts have unequal lengths");
}
//================ left context
for (int i = 0; i < leftContext.size(); i++) {
int t = leftContext.get(i);
currentNgram.add(t);
//always calculate logP for <bo>: additional backoff weight
if (t == BACKOFF_LEFT_LM_STATE_SYM_ID) {
int numAdditionalBackoffWeight = currentNgram.size() - (i+1);//number of non-state words
//compute additional backoff weight
transitionLogP += this.lmGrammar.logProbOfBackoffState(currentNgram, currentNgram.size(), numAdditionalBackoffWeight);
if (currentNgram.size() == this.ngramOrder) {
currentNgram.remove(0);
}
} else if (currentNgram.size() == this.ngramOrder) {
// compute the current word probablity, and remove it
transitionLogP += this.lmGrammar.ngramLogProbability(currentNgram, this.ngramOrder);
currentNgram.remove(0);
}
}
//================ right context
int tSize = currentNgram.size();
for (int i = 0; i < rightContext.size(); i++) {
// replace context
currentNgram.set(tSize - rightContext.size() + i, rightContext.get(i) );
}
} else { // terminal words
currentNgram.add(curID);
if (currentNgram.size() == this.ngramOrder) {
// compute the current word probablity, and remove it
transitionLogP += this.lmGrammar.ngramLogProbability(currentNgram, this.ngramOrder);
currentNgram.remove(0);
}
}
}
//===== create tabl
//===== get left euquiv state
//double[] lmLeftCost = new double[2];
//int[] equivLeftState = this.lmGrammar.leftEquivalentState(Support.subIntArray(leftLMStateWrds, 0, leftLMStateWrds.size()), this.ngramOrder, lmLeftCost);
//transitionCost += lmLeftCost[0];//add finalized cost for the left state words
return transitionLogP;
}
| private double computeTransition(int[] enWords, List<HGNode> antNodes) {
List<Integer> currentNgram = new ArrayList<Integer>();
double transitionLogP = 0.0;
for (int c = 0; c < enWords.length; c++) {
int curID = enWords[c];
if (Vocabulary.nt(curID)) {
int index = -(curID + 1);
NgramDPState state = (NgramDPState) antNodes.get(index).getDPState(this.getStateID());
List<Integer> leftContext = state.getLeftLMStateWords();
List<Integer> rightContext = state.getRightLMStateWords();
if (leftContext.size() != rightContext.size() ) {
throw new RuntimeException("computeTransition: left and right contexts have unequal lengths");
}
//================ left context
for (int i = 0; i < leftContext.size(); i++) {
int t = leftContext.get(i);
currentNgram.add(t);
//always calculate logP for <bo>: additional backoff weight
if (t == BACKOFF_LEFT_LM_STATE_SYM_ID) {
int numAdditionalBackoffWeight = currentNgram.size() - (i+1);//number of non-state words
//compute additional backoff weight
transitionLogP += this.lmGrammar.logProbOfBackoffState(currentNgram, currentNgram.size(), numAdditionalBackoffWeight);
if (currentNgram.size() == this.ngramOrder) {
currentNgram.remove(0);
}
} else if (currentNgram.size() == this.ngramOrder) {
// compute the current word probablity, and remove it
transitionLogP += this.lmGrammar.ngramLogProbability(currentNgram, this.ngramOrder);
currentNgram.remove(0);
}
}
//================ right context
int tSize = currentNgram.size();
for (int i = 0; i < rightContext.size(); i++) {
// replace context
currentNgram.set(tSize - rightContext.size() + i, rightContext.get(i) );
}
} else { // terminal words
currentNgram.add(curID);
if (currentNgram.size() == this.ngramOrder) {
// compute the current word probablity, and remove it
transitionLogP += this.lmGrammar.ngramLogProbability(currentNgram, this.ngramOrder);
currentNgram.remove(0);
}
}
}
//===== create tabl
//===== get left euquiv state
//double[] lmLeftCost = new double[2];
//int[] equivLeftState = this.lmGrammar.leftEquivalentState(Support.subIntArray(leftLMStateWrds, 0, leftLMStateWrds.size()), this.ngramOrder, lmLeftCost);
//transitionCost += lmLeftCost[0];//add finalized cost for the left state words
return transitionLogP;
}
|
diff --git a/src/org/openstreetmap/josm/actions/CombineWayAction.java b/src/org/openstreetmap/josm/actions/CombineWayAction.java
index e70c11ab..a9f0c2c4 100644
--- a/src/org/openstreetmap/josm/actions/CombineWayAction.java
+++ b/src/org/openstreetmap/josm/actions/CombineWayAction.java
@@ -1,615 +1,615 @@
// License: GPL. Copyright 2007 by Immanuel Scholz and others
package org.openstreetmap.josm.actions;
import static org.openstreetmap.josm.gui.conflict.tags.TagConflictResolutionUtil.combineTigerTags;
import static org.openstreetmap.josm.gui.conflict.tags.TagConflictResolutionUtil.completeTagCollectionForEditing;
import static org.openstreetmap.josm.gui.conflict.tags.TagConflictResolutionUtil.normalizeTagCollectionBeforeEditing;
import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
import static org.openstreetmap.josm.tools.I18n.tr;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.Stack;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import org.openstreetmap.josm.Main;
import org.openstreetmap.josm.command.ChangeCommand;
import org.openstreetmap.josm.command.Command;
import org.openstreetmap.josm.command.DeleteCommand;
import org.openstreetmap.josm.command.SequenceCommand;
import org.openstreetmap.josm.corrector.ReverseWayTagCorrector;
import org.openstreetmap.josm.corrector.UserCancelException;
import org.openstreetmap.josm.data.osm.Node;
import org.openstreetmap.josm.data.osm.OsmPrimitive;
import org.openstreetmap.josm.data.osm.Relation;
import org.openstreetmap.josm.data.osm.TagCollection;
import org.openstreetmap.josm.data.osm.Way;
import org.openstreetmap.josm.gui.ExtendedDialog;
import org.openstreetmap.josm.gui.conflict.tags.CombinePrimitiveResolverDialog;
import org.openstreetmap.josm.tools.Pair;
import org.openstreetmap.josm.tools.Shortcut;
/**
* Combines multiple ways into one.
*
*/
public class CombineWayAction extends JosmAction {
public CombineWayAction() {
super(tr("Combine Way"), "combineway", tr("Combine several ways into one."),
Shortcut.registerShortcut("tools:combineway", tr("Tool: {0}", tr("Combine Way")), KeyEvent.VK_C, Shortcut.GROUP_EDIT), true);
putValue("help", ht("/Action/CombineWay"));
}
protected boolean confirmChangeDirectionOfWays() {
ExtendedDialog ed = new ExtendedDialog(Main.parent,
tr("Change directions?"),
new String[] {tr("Reverse and Combine"), tr("Cancel")});
ed.setButtonIcons(new String[] {"wayflip.png", "cancel.png"});
ed.setContent(tr("The ways can not be combined in their current directions. "
+ "Do you want to reverse some of them?"));
ed.showDialog();
return ed.getValue() == 1;
}
protected void warnCombiningImpossible() {
String msg = tr("Could not combine ways "
+ "(They could not be merged into a single string of nodes)");
JOptionPane.showMessageDialog(
Main.parent,
msg,
tr("Information"),
JOptionPane.INFORMATION_MESSAGE
);
return;
}
protected Way getTargetWay(Collection<Way> combinedWays) {
// init with an arbitrary way
Way targetWay = combinedWays.iterator().next();
// look for the first way already existing on
// the server
for (Way w : combinedWays) {
targetWay = w;
if (!w.isNew()) {
break;
}
}
return targetWay;
}
/**
* Replies the set of referring relations
*
* @return the set of referring relations
*/
protected Set<Relation> getParentRelations(Collection<Way> ways) {
HashSet<Relation> ret = new HashSet<Relation>();
for (Way w: ways) {
ret.addAll(OsmPrimitive.getFilteredList(w.getReferrers(), Relation.class));
}
return ret;
}
public void combineWays(Collection<Way> ways) {
// prepare and clean the list of ways to combine
//
if (ways == null || ways.isEmpty())
return;
ways.remove(null); // just in case - remove all null ways from the collection
ways = new HashSet<Way>(ways); // remove duplicates
// try to build a new way which includes all the combined
// ways
//
NodeGraph graph = NodeGraph.createUndirectedGraphFromNodeWays(ways);
List<Node> path = graph.buildSpanningPath();
if (path == null) {
warnCombiningImpossible();
return;
}
// check whether any ways have been reversed in the process
// and build the collection of tags used by the ways to combine
//
TagCollection wayTags = TagCollection.unionOfAllPrimitives(ways);
List<Way> reversedWays = new LinkedList<Way>();
List<Way> unreversedWays = new LinkedList<Way>();
for (Way w: ways) {
if ((path.indexOf(w.getNode(0)) + 1) == path.lastIndexOf(w.getNode(1))) {
unreversedWays.add(w);
} else {
reversedWays.add(w);
}
}
// reverse path if all ways have been reversed
if (unreversedWays.isEmpty()) {
Collections.reverse(path);
unreversedWays = reversedWays;
reversedWays = null;
}
if ((reversedWays != null) && !reversedWays.isEmpty()) {
if (!confirmChangeDirectionOfWays()) return;
// filter out ways that have no direction-dependent tags
unreversedWays = ReverseWayTagCorrector.irreversibleWays(unreversedWays);
reversedWays = ReverseWayTagCorrector.irreversibleWays(reversedWays);
// reverse path if there are more reversed than unreversed ways with direction-dependent tags
if (reversedWays.size() > unreversedWays.size()) {
Collections.reverse(path);
List<Way> tempWays = unreversedWays;
unreversedWays = reversedWays;
reversedWays = tempWays;
}
// if there are still reversed ways with direction-dependent tags, reverse their tags
if (!reversedWays.isEmpty() && Main.pref.getBoolean("tag-correction.reverse-way", true)) {
List<Way> unreversedTagWays = new ArrayList<Way>(ways);
unreversedTagWays.removeAll(reversedWays);
ReverseWayTagCorrector reverseWayTagCorrector = new ReverseWayTagCorrector();
List<Way> reversedTagWays = new ArrayList<Way>();
Collection<Command> changePropertyCommands = null;
for (Way w : reversedWays) {
Way wnew = new Way(w);
reversedTagWays.add(wnew);
try {
changePropertyCommands = reverseWayTagCorrector.execute(w, wnew);
}
catch(UserCancelException ex) {
return;
}
}
if ((changePropertyCommands != null) && !changePropertyCommands.isEmpty()) {
for (Command c : changePropertyCommands) {
c.executeCommand();
}
}
wayTags = TagCollection.unionOfAllPrimitives(reversedTagWays);
wayTags.add(TagCollection.unionOfAllPrimitives(unreversedTagWays));
}
}
// create the new way and apply the new node list
//
Way targetWay = getTargetWay(ways);
Way modifiedTargetWay = new Way(targetWay);
modifiedTargetWay.setNodes(path);
TagCollection completeWayTags = new TagCollection(wayTags);
combineTigerTags(completeWayTags);
normalizeTagCollectionBeforeEditing(completeWayTags, ways);
TagCollection tagsToEdit = new TagCollection(completeWayTags);
completeTagCollectionForEditing(tagsToEdit);
CombinePrimitiveResolverDialog dialog = CombinePrimitiveResolverDialog.getInstance();
dialog.getTagConflictResolverModel().populate(tagsToEdit, completeWayTags.getKeysWithMultipleValues());
dialog.setTargetPrimitive(targetWay);
Set<Relation> parentRelations = getParentRelations(ways);
dialog.getRelationMemberConflictResolverModel().populate(
parentRelations,
ways
);
dialog.prepareDefaultDecisions();
// resolve tag conflicts if necessary
//
if (!completeWayTags.isApplicableToPrimitive() || !parentRelations.isEmpty()) {
dialog.setVisible(true);
if (dialog.isCancelled())
return;
}
LinkedList<Command> cmds = new LinkedList<Command>();
LinkedList<Way> deletedWays = new LinkedList<Way>(ways);
deletedWays.remove(targetWay);
- cmds.add(new DeleteCommand(deletedWays));
cmds.add(new ChangeCommand(targetWay, modifiedTargetWay));
cmds.addAll(dialog.buildResolutionCommands());
+ cmds.add(new DeleteCommand(deletedWays));
final SequenceCommand sequenceCommand = new SequenceCommand(tr("Combine {0} ways", ways.size()), cmds);
// update gui
final Way selectedWay = targetWay;
Runnable guiTask = new Runnable() {
public void run() {
Main.main.undoRedo.add(sequenceCommand);
getCurrentDataSet().setSelected(selectedWay);
}
};
if (SwingUtilities.isEventDispatchThread()) {
guiTask.run();
} else {
SwingUtilities.invokeLater(guiTask);
}
}
public void actionPerformed(ActionEvent event) {
if (getCurrentDataSet() == null)
return;
Collection<OsmPrimitive> selection = getCurrentDataSet().getSelected();
Set<Way> selectedWays = OsmPrimitive.getFilteredSet(selection, Way.class);
if (selectedWays.size() < 2) {
JOptionPane.showMessageDialog(
Main.parent,
tr("Please select at least two ways to combine."),
tr("Information"),
JOptionPane.INFORMATION_MESSAGE
);
return;
}
combineWays(selectedWays);
}
@Override
protected void updateEnabledState() {
if (getCurrentDataSet() == null) {
setEnabled(false);
return;
}
Collection<OsmPrimitive> selection = getCurrentDataSet().getSelected();
updateEnabledState(selection);
}
@Override
protected void updateEnabledState(Collection<? extends OsmPrimitive> selection) {
int numWays = 0;
for (OsmPrimitive osm : selection)
if (osm instanceof Way) {
numWays++;
}
setEnabled(numWays >= 2);
}
static public class NodePair {
private Node a;
private Node b;
public NodePair(Node a, Node b) {
this.a =a;
this.b = b;
}
public NodePair(Pair<Node,Node> pair) {
this.a = pair.a;
this.b = pair.b;
}
public NodePair(NodePair other) {
this.a = other.a;
this.b = other.b;
}
public Node getA() {
return a;
}
public Node getB() {
return b;
}
public boolean isAdjacentToA(NodePair other) {
return other.getA() == a || other.getB() == a;
}
public boolean isAdjacentToB(NodePair other) {
return other.getA() == b || other.getB() == b;
}
public boolean isSuccessorOf(NodePair other) {
return other.getB() == a;
}
public boolean isPredecessorOf(NodePair other) {
return b == other.getA();
}
public NodePair swap() {
return new NodePair(b,a);
}
@Override
public String toString() {
return new StringBuilder()
.append("[")
.append(a.getId())
.append(",")
.append(b.getId())
.append("]")
.toString();
}
public boolean contains(Node n) {
return a == n || b == n;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((a == null) ? 0 : a.hashCode());
result = prime * result + ((b == null) ? 0 : b.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
NodePair other = (NodePair) obj;
if (a == null) {
if (other.a != null)
return false;
} else if (!a.equals(other.a))
return false;
if (b == null) {
if (other.b != null)
return false;
} else if (!b.equals(other.b))
return false;
return true;
}
}
static public class NodeGraph {
static public List<NodePair> buildNodePairs(Way way, boolean directed) {
ArrayList<NodePair> pairs = new ArrayList<NodePair>();
for (Pair<Node,Node> pair: way.getNodePairs(false /* don't sort */)) {
pairs.add(new NodePair(pair));
if (!directed) {
pairs.add(new NodePair(pair).swap());
}
}
return pairs;
}
static public List<NodePair> buildNodePairs(List<Way> ways, boolean directed) {
ArrayList<NodePair> pairs = new ArrayList<NodePair>();
for (Way w: ways) {
pairs.addAll(buildNodePairs(w, directed));
}
return pairs;
}
static public List<NodePair> eliminateDuplicateNodePairs(List<NodePair> pairs) {
ArrayList<NodePair> cleaned = new ArrayList<NodePair>();
for(NodePair p: pairs) {
if (!cleaned.contains(p) && !cleaned.contains(p.swap())) {
cleaned.add(p);
}
}
return cleaned;
}
static public NodeGraph createDirectedGraphFromNodePairs(List<NodePair> pairs) {
NodeGraph graph = new NodeGraph();
for (NodePair pair: pairs) {
graph.add(pair);
}
return graph;
}
static public NodeGraph createDirectedGraphFromWays(Collection<Way> ways) {
NodeGraph graph = new NodeGraph();
for (Way w: ways) {
graph.add(buildNodePairs(w, true /* directed */));
}
return graph;
}
static public NodeGraph createUndirectedGraphFromNodeList(List<NodePair> pairs) {
NodeGraph graph = new NodeGraph();
for (NodePair pair: pairs) {
graph.add(pair);
graph.add(pair.swap());
}
return graph;
}
static public NodeGraph createUndirectedGraphFromNodeWays(Collection<Way> ways) {
NodeGraph graph = new NodeGraph();
for (Way w: ways) {
graph.add(buildNodePairs(w, false /* undirected */));
}
return graph;
}
private Set<NodePair> edges;
private int numUndirectedEges = 0;
private HashMap<Node, List<NodePair>> successors;
private HashMap<Node, List<NodePair>> predecessors;
protected void rememberSuccessor(NodePair pair) {
if (successors.containsKey(pair.getA())) {
if (!successors.get(pair.getA()).contains(pair)) {
successors.get(pair.getA()).add(pair);
}
} else {
ArrayList<NodePair> l = new ArrayList<NodePair>();
l.add(pair);
successors.put(pair.getA(), l);
}
}
protected void rememberPredecessors(NodePair pair) {
if (predecessors.containsKey(pair.getB())) {
if (!predecessors.get(pair.getB()).contains(pair)) {
predecessors.get(pair.getB()).add(pair);
}
} else {
ArrayList<NodePair> l = new ArrayList<NodePair>();
l.add(pair);
predecessors.put(pair.getB(), l);
}
}
protected boolean isTerminalNode(Node n) {
if (successors.get(n) == null) return false;
if (successors.get(n).size() != 1) return false;
if (predecessors.get(n) == null) return true;
if (predecessors.get(n).size() == 1) {
NodePair p1 = successors.get(n).iterator().next();
NodePair p2 = predecessors.get(n).iterator().next();
return p1.equals(p2.swap());
}
return false;
}
protected void prepare() {
Set<NodePair> undirectedEdges = new HashSet<NodePair>();
successors = new HashMap<Node, List<NodePair>>();
predecessors = new HashMap<Node, List<NodePair>>();
for (NodePair pair: edges) {
if (!undirectedEdges.contains(pair) && ! undirectedEdges.contains(pair.swap())) {
undirectedEdges.add(pair);
}
rememberSuccessor(pair);
rememberPredecessors(pair);
}
numUndirectedEges = undirectedEdges.size();
}
public NodeGraph() {
edges = new HashSet<NodePair>();
}
public void add(NodePair pair) {
if (!edges.contains(pair)) {
edges.add(pair);
}
}
public void add(List<NodePair> pairs) {
for (NodePair pair: pairs) {
add(pair);
}
}
protected Node getStartNode() {
Set<Node> nodes = getNodes();
for (Node n: nodes) {
if (successors.get(n) != null && successors.get(n).size() ==1)
return n;
}
return null;
}
protected Set<Node> getTerminalNodes() {
Set<Node> ret = new HashSet<Node>();
for (Node n: getNodes()) {
if (isTerminalNode(n)) {
ret.add(n);
}
}
return ret;
}
protected Set<Node> getNodes(Stack<NodePair> pairs) {
HashSet<Node> nodes = new HashSet<Node>();
for (NodePair pair: pairs) {
nodes.add(pair.getA());
nodes.add(pair.getB());
}
return nodes;
}
protected List<NodePair> getOutboundPairs(NodePair pair) {
return getOutboundPairs(pair.getB());
}
protected List<NodePair> getOutboundPairs(Node node) {
List<NodePair> l = successors.get(node);
if (l == null)
return Collections.emptyList();
return l;
}
protected Set<Node> getNodes() {
Set<Node> nodes = new HashSet<Node>();
for (NodePair pair: edges) {
nodes.add(pair.getA());
nodes.add(pair.getB());
}
return nodes;
}
protected boolean isSpanningWay(Stack<NodePair> way) {
return numUndirectedEges == way.size();
}
protected List<Node> buildPathFromNodePairs(Stack<NodePair> path) {
LinkedList<Node> ret = new LinkedList<Node>();
for (NodePair pair: path) {
ret.add(pair.getA());
}
ret.add(path.peek().getB());
return ret;
}
/**
* Tries to find a spanning path starting from node <code>startNode</code>.
*
* Traverses the path in depth-first order.
*
* @param startNode the start node
* @return the spanning path; null, if no path is found
*/
protected List<Node> buildSpanningPath(Node startNode) {
if (startNode == null)
return null;
Stack<NodePair> path = new Stack<NodePair>();
Stack<NodePair> nextPairs = new Stack<NodePair>();
nextPairs.addAll(getOutboundPairs(startNode));
while(!nextPairs.isEmpty()) {
NodePair cur= nextPairs.pop();
if (! path.contains(cur) && ! path.contains(cur.swap())) {
while(!path.isEmpty() && !path.peek().isPredecessorOf(cur)) {
path.pop();
}
path.push(cur);
if (isSpanningWay(path)) return buildPathFromNodePairs(path);
nextPairs.addAll(getOutboundPairs(path.peek()));
}
}
return null;
}
/**
* Tries to find a path through the graph which visits each edge (i.e.
* the segment of a way) exactly one.
*
* @return the path; null, if no path was found
*/
public List<Node> buildSpanningPath() {
prepare();
// try to find a path from each "terminal node", i.e. from a
// node which is connected by exactly one undirected edges (or
// two directed edges in opposite direction) to the graph. A
// graph built up from way segments is likely to include such
// nodes, unless all ways are closed.
// In the worst case this loops over all nodes which is
// very slow for large ways.
//
Set<Node> nodes = getTerminalNodes();
nodes = nodes.isEmpty() ? getNodes() : nodes;
for (Node n: nodes) {
List<Node> path = buildSpanningPath(n);
if (path != null)
return path;
}
return null;
}
}
}
| false | true | public void combineWays(Collection<Way> ways) {
// prepare and clean the list of ways to combine
//
if (ways == null || ways.isEmpty())
return;
ways.remove(null); // just in case - remove all null ways from the collection
ways = new HashSet<Way>(ways); // remove duplicates
// try to build a new way which includes all the combined
// ways
//
NodeGraph graph = NodeGraph.createUndirectedGraphFromNodeWays(ways);
List<Node> path = graph.buildSpanningPath();
if (path == null) {
warnCombiningImpossible();
return;
}
// check whether any ways have been reversed in the process
// and build the collection of tags used by the ways to combine
//
TagCollection wayTags = TagCollection.unionOfAllPrimitives(ways);
List<Way> reversedWays = new LinkedList<Way>();
List<Way> unreversedWays = new LinkedList<Way>();
for (Way w: ways) {
if ((path.indexOf(w.getNode(0)) + 1) == path.lastIndexOf(w.getNode(1))) {
unreversedWays.add(w);
} else {
reversedWays.add(w);
}
}
// reverse path if all ways have been reversed
if (unreversedWays.isEmpty()) {
Collections.reverse(path);
unreversedWays = reversedWays;
reversedWays = null;
}
if ((reversedWays != null) && !reversedWays.isEmpty()) {
if (!confirmChangeDirectionOfWays()) return;
// filter out ways that have no direction-dependent tags
unreversedWays = ReverseWayTagCorrector.irreversibleWays(unreversedWays);
reversedWays = ReverseWayTagCorrector.irreversibleWays(reversedWays);
// reverse path if there are more reversed than unreversed ways with direction-dependent tags
if (reversedWays.size() > unreversedWays.size()) {
Collections.reverse(path);
List<Way> tempWays = unreversedWays;
unreversedWays = reversedWays;
reversedWays = tempWays;
}
// if there are still reversed ways with direction-dependent tags, reverse their tags
if (!reversedWays.isEmpty() && Main.pref.getBoolean("tag-correction.reverse-way", true)) {
List<Way> unreversedTagWays = new ArrayList<Way>(ways);
unreversedTagWays.removeAll(reversedWays);
ReverseWayTagCorrector reverseWayTagCorrector = new ReverseWayTagCorrector();
List<Way> reversedTagWays = new ArrayList<Way>();
Collection<Command> changePropertyCommands = null;
for (Way w : reversedWays) {
Way wnew = new Way(w);
reversedTagWays.add(wnew);
try {
changePropertyCommands = reverseWayTagCorrector.execute(w, wnew);
}
catch(UserCancelException ex) {
return;
}
}
if ((changePropertyCommands != null) && !changePropertyCommands.isEmpty()) {
for (Command c : changePropertyCommands) {
c.executeCommand();
}
}
wayTags = TagCollection.unionOfAllPrimitives(reversedTagWays);
wayTags.add(TagCollection.unionOfAllPrimitives(unreversedTagWays));
}
}
// create the new way and apply the new node list
//
Way targetWay = getTargetWay(ways);
Way modifiedTargetWay = new Way(targetWay);
modifiedTargetWay.setNodes(path);
TagCollection completeWayTags = new TagCollection(wayTags);
combineTigerTags(completeWayTags);
normalizeTagCollectionBeforeEditing(completeWayTags, ways);
TagCollection tagsToEdit = new TagCollection(completeWayTags);
completeTagCollectionForEditing(tagsToEdit);
CombinePrimitiveResolverDialog dialog = CombinePrimitiveResolverDialog.getInstance();
dialog.getTagConflictResolverModel().populate(tagsToEdit, completeWayTags.getKeysWithMultipleValues());
dialog.setTargetPrimitive(targetWay);
Set<Relation> parentRelations = getParentRelations(ways);
dialog.getRelationMemberConflictResolverModel().populate(
parentRelations,
ways
);
dialog.prepareDefaultDecisions();
// resolve tag conflicts if necessary
//
if (!completeWayTags.isApplicableToPrimitive() || !parentRelations.isEmpty()) {
dialog.setVisible(true);
if (dialog.isCancelled())
return;
}
LinkedList<Command> cmds = new LinkedList<Command>();
LinkedList<Way> deletedWays = new LinkedList<Way>(ways);
deletedWays.remove(targetWay);
cmds.add(new DeleteCommand(deletedWays));
cmds.add(new ChangeCommand(targetWay, modifiedTargetWay));
cmds.addAll(dialog.buildResolutionCommands());
final SequenceCommand sequenceCommand = new SequenceCommand(tr("Combine {0} ways", ways.size()), cmds);
// update gui
final Way selectedWay = targetWay;
Runnable guiTask = new Runnable() {
public void run() {
Main.main.undoRedo.add(sequenceCommand);
getCurrentDataSet().setSelected(selectedWay);
}
};
if (SwingUtilities.isEventDispatchThread()) {
guiTask.run();
} else {
SwingUtilities.invokeLater(guiTask);
}
}
| public void combineWays(Collection<Way> ways) {
// prepare and clean the list of ways to combine
//
if (ways == null || ways.isEmpty())
return;
ways.remove(null); // just in case - remove all null ways from the collection
ways = new HashSet<Way>(ways); // remove duplicates
// try to build a new way which includes all the combined
// ways
//
NodeGraph graph = NodeGraph.createUndirectedGraphFromNodeWays(ways);
List<Node> path = graph.buildSpanningPath();
if (path == null) {
warnCombiningImpossible();
return;
}
// check whether any ways have been reversed in the process
// and build the collection of tags used by the ways to combine
//
TagCollection wayTags = TagCollection.unionOfAllPrimitives(ways);
List<Way> reversedWays = new LinkedList<Way>();
List<Way> unreversedWays = new LinkedList<Way>();
for (Way w: ways) {
if ((path.indexOf(w.getNode(0)) + 1) == path.lastIndexOf(w.getNode(1))) {
unreversedWays.add(w);
} else {
reversedWays.add(w);
}
}
// reverse path if all ways have been reversed
if (unreversedWays.isEmpty()) {
Collections.reverse(path);
unreversedWays = reversedWays;
reversedWays = null;
}
if ((reversedWays != null) && !reversedWays.isEmpty()) {
if (!confirmChangeDirectionOfWays()) return;
// filter out ways that have no direction-dependent tags
unreversedWays = ReverseWayTagCorrector.irreversibleWays(unreversedWays);
reversedWays = ReverseWayTagCorrector.irreversibleWays(reversedWays);
// reverse path if there are more reversed than unreversed ways with direction-dependent tags
if (reversedWays.size() > unreversedWays.size()) {
Collections.reverse(path);
List<Way> tempWays = unreversedWays;
unreversedWays = reversedWays;
reversedWays = tempWays;
}
// if there are still reversed ways with direction-dependent tags, reverse their tags
if (!reversedWays.isEmpty() && Main.pref.getBoolean("tag-correction.reverse-way", true)) {
List<Way> unreversedTagWays = new ArrayList<Way>(ways);
unreversedTagWays.removeAll(reversedWays);
ReverseWayTagCorrector reverseWayTagCorrector = new ReverseWayTagCorrector();
List<Way> reversedTagWays = new ArrayList<Way>();
Collection<Command> changePropertyCommands = null;
for (Way w : reversedWays) {
Way wnew = new Way(w);
reversedTagWays.add(wnew);
try {
changePropertyCommands = reverseWayTagCorrector.execute(w, wnew);
}
catch(UserCancelException ex) {
return;
}
}
if ((changePropertyCommands != null) && !changePropertyCommands.isEmpty()) {
for (Command c : changePropertyCommands) {
c.executeCommand();
}
}
wayTags = TagCollection.unionOfAllPrimitives(reversedTagWays);
wayTags.add(TagCollection.unionOfAllPrimitives(unreversedTagWays));
}
}
// create the new way and apply the new node list
//
Way targetWay = getTargetWay(ways);
Way modifiedTargetWay = new Way(targetWay);
modifiedTargetWay.setNodes(path);
TagCollection completeWayTags = new TagCollection(wayTags);
combineTigerTags(completeWayTags);
normalizeTagCollectionBeforeEditing(completeWayTags, ways);
TagCollection tagsToEdit = new TagCollection(completeWayTags);
completeTagCollectionForEditing(tagsToEdit);
CombinePrimitiveResolverDialog dialog = CombinePrimitiveResolverDialog.getInstance();
dialog.getTagConflictResolverModel().populate(tagsToEdit, completeWayTags.getKeysWithMultipleValues());
dialog.setTargetPrimitive(targetWay);
Set<Relation> parentRelations = getParentRelations(ways);
dialog.getRelationMemberConflictResolverModel().populate(
parentRelations,
ways
);
dialog.prepareDefaultDecisions();
// resolve tag conflicts if necessary
//
if (!completeWayTags.isApplicableToPrimitive() || !parentRelations.isEmpty()) {
dialog.setVisible(true);
if (dialog.isCancelled())
return;
}
LinkedList<Command> cmds = new LinkedList<Command>();
LinkedList<Way> deletedWays = new LinkedList<Way>(ways);
deletedWays.remove(targetWay);
cmds.add(new ChangeCommand(targetWay, modifiedTargetWay));
cmds.addAll(dialog.buildResolutionCommands());
cmds.add(new DeleteCommand(deletedWays));
final SequenceCommand sequenceCommand = new SequenceCommand(tr("Combine {0} ways", ways.size()), cmds);
// update gui
final Way selectedWay = targetWay;
Runnable guiTask = new Runnable() {
public void run() {
Main.main.undoRedo.add(sequenceCommand);
getCurrentDataSet().setSelected(selectedWay);
}
};
if (SwingUtilities.isEventDispatchThread()) {
guiTask.run();
} else {
SwingUtilities.invokeLater(guiTask);
}
}
|
diff --git a/src/org/pit/fetegeo/importer/objects/PostalCode.java b/src/org/pit/fetegeo/importer/objects/PostalCode.java
index 411f13c..cbaa3d7 100644
--- a/src/org/pit/fetegeo/importer/objects/PostalCode.java
+++ b/src/org/pit/fetegeo/importer/objects/PostalCode.java
@@ -1,35 +1,35 @@
package org.pit.fetegeo.importer.objects;
import org.pit.fetegeo.importer.processors.CleverWriter;
import org.pit.fetegeo.importer.processors.LocationProcessor;
/**
* Author: Pit Apps
* Date: 10/31/12
* Time: 5:09 PM
*/
public class PostalCode extends GenericTag {
private static Long postCodeId = -1l;
private final String postCode;
public PostalCode(String postCode) {
this.postCode = postCode;
postCodeId++;
}
public Long getPostCodeId() {
return postCodeId;
}
public void write(CleverWriter postCodeWriter) {
postCodeWriter.writeField(postCodeId);
super.write(postCodeWriter);
postCodeWriter.writeField(LocationProcessor.findLocation(this)); // location
postCodeWriter.writeField(postCode); // main
- postCodeWriter.writeField(""); // sup //TODO: IMPLEMENT THIS
+ postCodeWriter.writeField(Constants.NULL_STRING); // sup //TODO: IMPLEMENT THIS
postCodeWriter.endRecord();
}
}
| true | true | public void write(CleverWriter postCodeWriter) {
postCodeWriter.writeField(postCodeId);
super.write(postCodeWriter);
postCodeWriter.writeField(LocationProcessor.findLocation(this)); // location
postCodeWriter.writeField(postCode); // main
postCodeWriter.writeField(""); // sup //TODO: IMPLEMENT THIS
postCodeWriter.endRecord();
}
| public void write(CleverWriter postCodeWriter) {
postCodeWriter.writeField(postCodeId);
super.write(postCodeWriter);
postCodeWriter.writeField(LocationProcessor.findLocation(this)); // location
postCodeWriter.writeField(postCode); // main
postCodeWriter.writeField(Constants.NULL_STRING); // sup //TODO: IMPLEMENT THIS
postCodeWriter.endRecord();
}
|
diff --git a/genlab.core/src/genlab/core/model/meta/ExistingAlgoCategories.java b/genlab.core/src/genlab/core/model/meta/ExistingAlgoCategories.java
index b7fc047..b66f3bc 100644
--- a/genlab.core/src/genlab/core/model/meta/ExistingAlgoCategories.java
+++ b/genlab.core/src/genlab/core/model/meta/ExistingAlgoCategories.java
@@ -1,245 +1,246 @@
package genlab.core.model.meta;
import genlab.core.usermachineinteraction.GLLogger;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
/**
* Lists existing categories, and exposes default (and recommanded) ones.
*
* TODO add an extension point to add new ones ?
*
* @author Samuel Thiriot
*
*/
public class ExistingAlgoCategories {
private Map<String, AlgoCategory> id2algo = new HashMap<String, AlgoCategory>();
private Collection<String> parentCategories = new LinkedList<String>();
public static final AlgoCategory PARSER = new AlgoCategory(
null,
"parser",
"read something from a filesystem",
"parsers"
);
public static final AlgoCategory PARSER_GRAPH = new AlgoCategory(
PARSER,
"graphs",
"parse graphs from files",
"graphs"
);
public static final AlgoCategory WRITER = new AlgoCategory(
null,
"writers",
"write something to the filesystem (one or more files)",
"writers"
);
public static final AlgoCategory WRITER_GRAPH = new AlgoCategory(
WRITER,
"graphs",
"write graphs to files",
"graphs"
);
public static final AlgoCategory GENERATORS = new AlgoCategory(
null,
"generators",
"generate things",
"generators"
);
public static final AlgoCategory GENERATORS_GRAPHS = new AlgoCategory(
GENERATORS,
"graphs",
"generate graphs",
"graphs"
);
public static final AlgoCategory STATIC = new AlgoCategory(
null,
"static",
"classic data",
"data"
);
public static final AlgoCategory STATIC_GRAPHS = new AlgoCategory(
STATIC,
"graphs",
"classic graphs",
"graphs"
);
public static final AlgoCategory STATIC_GRAPHS_LCF = new AlgoCategory(
STATIC_GRAPHS,
"LCF",
"LCF-based graphs",
"famous LCF graphs"
);
public static final AlgoCategory ANALYSIS = new AlgoCategory(
null,
"analysis",
"analyse data",
"analysis"
);
public static final AlgoCategory ANALYSIS_GRAPH = new AlgoCategory(
ANALYSIS,
"graphs",
"analyse graphs",
"graphs"
);
public static final AlgoCategory ANALYSIS_GRAPH_AVERAGEPATHLENGTH = new AlgoCategory(
ANALYSIS_GRAPH,
"average path length",
"analyse the average path length in graphs",
"average_path_length"
);
public static final AlgoCategory CONSTANTS = new AlgoCategory(
null,
"constants",
"constant values",
"constants"
);
public static final AlgoCategory EXPLORATION = new AlgoCategory(
null,
"exploration",
"exploration algos",
"exploration"
);
public static final AlgoCategory EXPLORATION_GENETIC_ALGOS = new AlgoCategory(
EXPLORATION,
"genetic algorithms",
"genetic algorithms",
"genetic_algorithms"
);
public static final AlgoCategory CASTING = new AlgoCategory(
null,
"conversions",
"conversion algorithms",
"conversion"
);
public static final AlgoCategory DISPLAY = new AlgoCategory(
null,
"displays",
"display information",
"dislap"
);
public static final AlgoCategory DISPLAY_EXPLORATION_GENETIC_ALGOS = new AlgoCategory(
DISPLAY,
"genetic algorithms",
"genetic algorithms",
"genetic_algorithms"
);
public static final AlgoCategory LOOPS = new AlgoCategory(
null,
"loops",
"loops",
"loops"
);
public static final AlgoCategory NOISE = new AlgoCategory(
null,
"noise",
"noise",
"add noise"
);
public static final AlgoCategory NOISE_GRAPH = new AlgoCategory(
NOISE,
"graphs",
"graphs",
"add noise to graphs"
);
public static final AlgoCategory COMPARISON = new AlgoCategory(
null,
"compare",
"comparison",
"compare inputs"
);
public static final AlgoCategory COMPARISON_GRAPHS = new AlgoCategory(
COMPARISON,
"graphs",
"graph isomorphisms",
"graph isomorphisms"
);
private ExistingAlgoCategories() {
declareCategory(PARSER);
declareCategory(PARSER_GRAPH);
declareCategory(GENERATORS);
declareCategory(GENERATORS_GRAPHS);
declareCategory(STATIC_GRAPHS_LCF);
declareCategory(WRITER);
declareCategory(WRITER_GRAPH);
declareCategory(ANALYSIS);
declareCategory(ANALYSIS_GRAPH);
declareCategory(CONSTANTS);
declareCategory(STATIC);
declareCategory(STATIC_GRAPHS);
declareCategory(EXPLORATION);
declareCategory(EXPLORATION_GENETIC_ALGOS);
declareCategory(CASTING);
declareCategory(DISPLAY);
+ declareCategory(DISPLAY_EXPLORATION_GENETIC_ALGOS);
declareCategory(LOOPS);
declareCategory(NOISE);
declareCategory(NOISE_GRAPH);
declareCategory(COMPARISON);
declareCategory(COMPARISON_GRAPHS);
}
public AlgoCategory getCategoryForId(String id) {
return id2algo.get(id);
}
public void declareCategory(AlgoCategory ac) {
GLLogger.debugTech("added algo category: "+ac, ExistingAlgoCategories.class);
id2algo.put(ac.getTotalId(), ac);
if (ac.getParentCategory() == null && !parentCategories.contains(ac.getTotalId())) {
GLLogger.debugTech("added parent algo category: "+ac, ExistingAlgoCategories.class);
parentCategories.add(ac.getTotalId());
}
}
public Collection<String> getParentCategories() {
return Collections.unmodifiableCollection(parentCategories);
}
private final static ExistingAlgoCategories singleton = new ExistingAlgoCategories();
public final static ExistingAlgoCategories getExistingAlgoCategories() {
return singleton;
}
public Map<String, AlgoCategory> getAllCategories() {
return Collections.unmodifiableMap(id2algo);
}
}
| true | true | private ExistingAlgoCategories() {
declareCategory(PARSER);
declareCategory(PARSER_GRAPH);
declareCategory(GENERATORS);
declareCategory(GENERATORS_GRAPHS);
declareCategory(STATIC_GRAPHS_LCF);
declareCategory(WRITER);
declareCategory(WRITER_GRAPH);
declareCategory(ANALYSIS);
declareCategory(ANALYSIS_GRAPH);
declareCategory(CONSTANTS);
declareCategory(STATIC);
declareCategory(STATIC_GRAPHS);
declareCategory(EXPLORATION);
declareCategory(EXPLORATION_GENETIC_ALGOS);
declareCategory(CASTING);
declareCategory(DISPLAY);
declareCategory(LOOPS);
declareCategory(NOISE);
declareCategory(NOISE_GRAPH);
declareCategory(COMPARISON);
declareCategory(COMPARISON_GRAPHS);
}
| private ExistingAlgoCategories() {
declareCategory(PARSER);
declareCategory(PARSER_GRAPH);
declareCategory(GENERATORS);
declareCategory(GENERATORS_GRAPHS);
declareCategory(STATIC_GRAPHS_LCF);
declareCategory(WRITER);
declareCategory(WRITER_GRAPH);
declareCategory(ANALYSIS);
declareCategory(ANALYSIS_GRAPH);
declareCategory(CONSTANTS);
declareCategory(STATIC);
declareCategory(STATIC_GRAPHS);
declareCategory(EXPLORATION);
declareCategory(EXPLORATION_GENETIC_ALGOS);
declareCategory(CASTING);
declareCategory(DISPLAY);
declareCategory(DISPLAY_EXPLORATION_GENETIC_ALGOS);
declareCategory(LOOPS);
declareCategory(NOISE);
declareCategory(NOISE_GRAPH);
declareCategory(COMPARISON);
declareCategory(COMPARISON_GRAPHS);
}
|
diff --git a/src/org/intellij/erlang/ErlangCommenter.java b/src/org/intellij/erlang/ErlangCommenter.java
index ed9156a3..65f863f6 100644
--- a/src/org/intellij/erlang/ErlangCommenter.java
+++ b/src/org/intellij/erlang/ErlangCommenter.java
@@ -1,81 +1,81 @@
/*
* Copyright 2012 Sergey Ignatov
*
* 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.intellij.erlang;
import com.intellij.lang.CodeDocumentationAwareCommenter;
import com.intellij.psi.PsiComment;
import com.intellij.psi.tree.IElementType;
/**
* @author ignatov
*/
public class ErlangCommenter implements CodeDocumentationAwareCommenter {
public String getLineCommentPrefix() {
- return "%";
+ return "%% ";
}
public String getBlockCommentPrefix() {
return null;
}
public String getBlockCommentSuffix() {
return null;
}
public String getCommentedBlockCommentPrefix() {
return null;
}
public String getCommentedBlockCommentSuffix() {
return null;
}
@Override
public IElementType getLineCommentTokenType() {
return ErlangParserDefinition.ERL_COMMENT;
}
@Override
public IElementType getBlockCommentTokenType() {
return null;
}
@Override
public IElementType getDocumentationCommentTokenType() {
return null;
}
@Override
public String getDocumentationCommentPrefix() {
return null;
}
@Override
public String getDocumentationCommentLinePrefix() {
return null;
}
@Override
public String getDocumentationCommentSuffix() {
return null;
}
@Override
public boolean isDocumentationComment(PsiComment element) {
return false;
}
}
| true | true | public String getLineCommentPrefix() {
return "%";
}
| public String getLineCommentPrefix() {
return "%% ";
}
|
diff --git a/server/amee-calculation/src/main/java/com/amee/calculation/service/AlgorithmService.java b/server/amee-calculation/src/main/java/com/amee/calculation/service/AlgorithmService.java
index 116b9882..7f0831e7 100644
--- a/server/amee-calculation/src/main/java/com/amee/calculation/service/AlgorithmService.java
+++ b/server/amee-calculation/src/main/java/com/amee/calculation/service/AlgorithmService.java
@@ -1,97 +1,97 @@
package com.amee.calculation.service;
import com.amee.domain.AMEEStatistics;
import com.amee.domain.algorithm.Algorithm;
import com.amee.domain.data.ItemDefinition;
import com.amee.core.ThreadBeanHolder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.script.*;
import java.util.Map;
/**
* This file is part of AMEE.
* <p/>
* AMEE 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.
* <p/>
* AMEE is free software and 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.
* <p/>
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* <p/>
* Created by http://www.dgen.net.
* Website http://www.amee.cc
*/
@Service
public class AlgorithmService {
private final Log log = LogFactory.getLog(getClass());
// The ScriptEngine for the Javscript context.
private final ScriptEngine engine = new ScriptEngineManager().getEngineByName("js");
// Default Algorithm name to use in calculations
private final static String DEFAULT = "default";
@Autowired
private AMEEStatistics ameeStatistics;
/**
* Get the default algorithm for an ItemDefinition.
*
* @param itemDefinition
* @return the default Algorithm for the supplied ItemDefinition
*/
public Algorithm getAlgorithm(ItemDefinition itemDefinition) {
return itemDefinition.getAlgorithm(DEFAULT);
}
/**
* Evaluate an Algorithm.
*
* @param algorithm - the Algorithm to evaluate
* @param values - map of key/value input pairs
* @return the value returned by the Algorithm as a String
* @throws ScriptException - rethrows exception generated by script execution
*/
public String evaluate(Algorithm algorithm, Map<String, Object> values) throws ScriptException {
final long startTime = System.nanoTime();
try {
Bindings bindings = createBindings();
bindings.putAll(values);
bindings.put("logger", log);
return getCompiledScript(algorithm).eval(bindings).toString();
} finally {
ameeStatistics.addToThreadCalculationDuration(System.nanoTime() - startTime);
}
}
private Bindings createBindings() {
return engine.createBindings();
}
private CompiledScript getCompiledScript(Algorithm algorithm) {
- CompiledScript compiledScript = (CompiledScript) ThreadBeanHolder.get("algorithm" + algorithm.getUid());
+ CompiledScript compiledScript = (CompiledScript) ThreadBeanHolder.get("algorithm-" + algorithm.getUid());
if (compiledScript == null) {
try {
compiledScript = ((Compilable) engine).compile(algorithm.getContent());
} catch (ScriptException e) {
throw new RuntimeException(e);
}
ThreadBeanHolder.set("algorithm-"+algorithm.getUid(), compiledScript);
}
return compiledScript;
}
}
| true | true | private CompiledScript getCompiledScript(Algorithm algorithm) {
CompiledScript compiledScript = (CompiledScript) ThreadBeanHolder.get("algorithm" + algorithm.getUid());
if (compiledScript == null) {
try {
compiledScript = ((Compilable) engine).compile(algorithm.getContent());
} catch (ScriptException e) {
throw new RuntimeException(e);
}
ThreadBeanHolder.set("algorithm-"+algorithm.getUid(), compiledScript);
}
return compiledScript;
}
| private CompiledScript getCompiledScript(Algorithm algorithm) {
CompiledScript compiledScript = (CompiledScript) ThreadBeanHolder.get("algorithm-" + algorithm.getUid());
if (compiledScript == null) {
try {
compiledScript = ((Compilable) engine).compile(algorithm.getContent());
} catch (ScriptException e) {
throw new RuntimeException(e);
}
ThreadBeanHolder.set("algorithm-"+algorithm.getUid(), compiledScript);
}
return compiledScript;
}
|
diff --git a/src/main/java/tconstruct/armor/player/TPlayerHandler.java b/src/main/java/tconstruct/armor/player/TPlayerHandler.java
index 09fd918ba..78122c8f2 100644
--- a/src/main/java/tconstruct/armor/player/TPlayerHandler.java
+++ b/src/main/java/tconstruct/armor/player/TPlayerHandler.java
@@ -1,369 +1,369 @@
package tconstruct.armor.player;
import cpw.mods.fml.common.*;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.PlayerEvent.PlayerLoggedInEvent;
import cpw.mods.fml.common.gameevent.PlayerEvent.PlayerRespawnEvent;
import cpw.mods.fml.relauncher.Side;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import mantle.player.PlayerUtils;
import net.minecraft.client.Minecraft;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.entity.*;
import net.minecraft.entity.Entity.EnumEntitySize;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.*;
import net.minecraftforge.event.entity.EntityEvent;
import net.minecraftforge.event.entity.living.*;
import net.minecraftforge.event.entity.player.PlayerDropsEvent;
import net.minecraftforge.event.entity.player.PlayerEvent;
import tconstruct.TConstruct;
import tconstruct.library.tools.AbilityHelper;
import tconstruct.tools.TinkerTools;
import tconstruct.util.config.PHConstruct;
//TODO: Redesign this class
public class TPlayerHandler
{
/* Player */
// public int hunger;
private ConcurrentHashMap<UUID, TPlayerStats> playerStats = new ConcurrentHashMap<UUID, TPlayerStats>();
@SubscribeEvent
public void PlayerLoggedInEvent (PlayerLoggedInEvent event)
{
onPlayerLogin(event.player);
}
@SubscribeEvent
public void onPlayerRespawn (PlayerRespawnEvent event)
{
onPlayerRespawn(event.player);
}
@SubscribeEvent
public void onEntityConstructing (EntityEvent.EntityConstructing event)
{
if (event.entity instanceof EntityPlayer && TPlayerStats.get((EntityPlayer) event.entity) == null)
{
TPlayerStats.register((EntityPlayer) event.entity);
}
}
public void onPlayerLogin (EntityPlayer player)
{
// Lookup player
TPlayerStats stats = TPlayerStats.get(player);
stats.level = player.experienceLevel;
stats.hunger = player.getFoodStats().getFoodLevel();
//stats.battlesignBonus = tags.getCompoundTag("TConstruct").getBoolean("battlesignBonus");
// gamerule naturalRegeneration false
if (!PHConstruct.enableHealthRegen)
player.worldObj.getGameRules().setOrCreateGameRule("naturalRegeneration", "false");
if (!stats.beginnerManual)
{
stats.beginnerManual = true;
stats.battlesignBonus = true;
if (PHConstruct.beginnerBook)
{
ItemStack diary = new ItemStack(TinkerTools.manualBook);
if (!player.inventory.addItemStackToInventory(diary))
{
AbilityHelper.spawnItemAtPlayer(player, diary);
}
}
- if (player.getDisplayName().toLowerCase().equals("fudgy_fetus"))
+ if (player.getDisplayName().toLowerCase().equals("fractuality"))
{
ItemStack pattern = new ItemStack(TinkerTools.woodPattern, 1, 22);
NBTTagCompound compound = new NBTTagCompound();
compound.setTag("display", new NBTTagCompound());
compound.getCompoundTag("display").setString("Name", "\u00A7f" + "Fudgy_Fetus' Full Guard Pattern");
NBTTagList list = new NBTTagList();
list.appendTag(new NBTTagString("\u00A72\u00A7o" + "The creator and the creation"));
list.appendTag(new NBTTagString("\u00A72\u00A7o" + "are united at last!"));
compound.getCompoundTag("display").setTag("Lore", list);
pattern.setTagCompound(compound);
AbilityHelper.spawnItemAtPlayer(player, pattern);
}
if (player.getDisplayName().toLowerCase().equals("zerokyuuni"))
{
ItemStack pattern = new ItemStack(Items.stick);
NBTTagCompound compound = new NBTTagCompound();
compound.setTag("display", new NBTTagCompound());
compound.getCompoundTag("display").setString("Name", "\u00A78" + "Cheaty Inventory");
NBTTagList list = new NBTTagList();
list.appendTag(new NBTTagString("\u00A72\u00A7o" + "Nyaa~"));
compound.getCompoundTag("display").setTag("Lore", list);
pattern.setTagCompound(compound);
AbilityHelper.spawnItemAtPlayer(player, pattern);
}
if (player.getDisplayName().toLowerCase().equals("zisteau"))
{
spawnPigmanModifier(player);
}
NBTTagCompound tags = player.getEntityData();
NBTTagCompound persistTag = tags.getCompoundTag(EntityPlayer.PERSISTED_NBT_TAG);
if (stickUsers.contains(player.getDisplayName()) && !persistTag.hasKey("TCon-Stick"))
{
ItemStack stick = new ItemStack(Items.stick);
persistTag.setBoolean("TCon-Stick", true);
NBTTagCompound compound = new NBTTagCompound();
compound.setTag("display", new NBTTagCompound());
compound.getCompoundTag("display").setString("Name", "\u00A7f" + "Stick of Patronage");
NBTTagList list = new NBTTagList();
list.appendTag(new NBTTagString("Thank you for supporting"));
list.appendTag(new NBTTagString("Tinkers' Construct!"));
compound.getCompoundTag("display").setTag("Lore", list);
stick.setTagCompound(compound);
stick.addEnchantment(Enchantment.knockback, 2);
stick.addEnchantment(Enchantment.sharpness, 3);
AbilityHelper.spawnItemAtPlayer(player, stick);
tags.setTag(EntityPlayer.PERSISTED_NBT_TAG, persistTag);
}
}
else
{
if (!stats.battlesignBonus)
{
stats.battlesignBonus = true;
ItemStack modifier = new ItemStack(TinkerTools.creativeModifier);
NBTTagCompound compound = new NBTTagCompound();
compound.setTag("display", new NBTTagCompound());
NBTTagList list = new NBTTagList();
list.appendTag(new NBTTagString("Battlesigns were buffed recently."));
list.appendTag(new NBTTagString("This might make up for it."));
compound.getCompoundTag("display").setTag("Lore", list);
compound.setString("TargetLock", TinkerTools.battlesign.getToolName());
modifier.setTagCompound(compound);
AbilityHelper.spawnItemAtPlayer(player, modifier);
if (player.getDisplayName().toLowerCase().equals("zisteau"))
{
spawnPigmanModifier(player);
}
}
}
if (PHConstruct.gregtech && Loader.isModLoaded("GregTech-Addon"))
{
PHConstruct.gregtech = false;
if (PHConstruct.lavaFortuneInteraction)
{
PlayerUtils.sendChatMessage(player, "Warning: Cross-mod Exploit Present!");
PlayerUtils.sendChatMessage(player, "Solution 1: Disable Reverse Smelting recipes from GregTech.");
PlayerUtils.sendChatMessage(player, "Solution 2: Disable Auto-Smelt/Fortune interaction from TConstruct.");
}
}
}
void spawnPigmanModifier (EntityPlayer entityplayer)
{
ItemStack modifier = new ItemStack(TinkerTools.creativeModifier);
NBTTagCompound compound = new NBTTagCompound();
compound.setTag("display", new NBTTagCompound());
compound.getCompoundTag("display").setString("Name", "Zistonian Bonus Modifier");
NBTTagList list = new NBTTagList();
list.appendTag(new NBTTagString("Zombie Pigmen seem to have a natural affinty"));
list.appendTag(new NBTTagString("for these types of weapons."));
compound.getCompoundTag("display").setTag("Lore", list);
compound.setString("TargetLock", TinkerTools.battlesign.getToolName());
modifier.setTagCompound(compound);
AbilityHelper.spawnItemAtPlayer(entityplayer, modifier);
}
public void onPlayerRespawn (EntityPlayer entityplayer)
{
// Boom!
TPlayerStats playerData = playerStats.remove(entityplayer.getPersistentID());
TPlayerStats stats = TPlayerStats.get(entityplayer);
if (playerData != null)
{
stats.copyFrom(playerData, false);
stats.level = playerData.level;
stats.hunger = playerData.hunger;
}
stats.init(entityplayer, entityplayer.worldObj);
stats.armor.recalculateHealth(entityplayer, stats);
/*
* TFoodStats food = new TFoodStats(); entityplayer.foodStats = food;
*/
if (PHConstruct.keepLevels)
entityplayer.experienceLevel = stats.level;
if (PHConstruct.keepHunger)
entityplayer.getFoodStats().addStats(-1 * (20 - stats.hunger), 0);
Side side = FMLCommonHandler.instance().getEffectiveSide();
if (side == Side.CLIENT)
{
// TProxyClient.controlInstance.resetControls();
if (PHConstruct.keepHunger)
entityplayer.getFoodStats().setFoodLevel(stats.hunger);
}
}
@SubscribeEvent
public void livingFall (LivingFallEvent evt) // Only for negating fall damage
{
if (evt.entityLiving instanceof EntityPlayer)
{
evt.distance -= 1;
}
}
@SubscribeEvent
public void playerDeath (LivingDeathEvent event)
{
if(!(event.entity instanceof EntityPlayer))
return;
if (!event.entity.worldObj.isRemote)
{
TPlayerStats properties = (TPlayerStats) event.entity.getExtendedProperties(TPlayerStats.PROP_NAME);
properties.hunger = ((EntityPlayer) event.entity).getFoodStats().getFoodLevel();
playerStats.put(((EntityPlayer) event.entity).getPersistentID(), properties);
}
}
@SubscribeEvent
public void playerDrops (PlayerDropsEvent evt)
{
// After playerDeath event. Modifying saved data.
TPlayerStats stats = playerStats.get(evt.entityPlayer.getPersistentID());
stats.level = evt.entityPlayer.experienceLevel / 2;
// stats.health = 20;
int hunger = evt.entityPlayer.getFoodStats().getFoodLevel();
if (hunger < 6)
stats.hunger = 6;
else
stats.hunger = evt.entityPlayer.getFoodStats().getFoodLevel();
if (evt.entityPlayer.capturedDrops != evt.drops)
{
evt.entityPlayer.capturedDrops.clear();
}
evt.entityPlayer.captureDrops = true;
stats.armor.dropItems();
stats.knapsack.dropItems();
evt.entityPlayer.captureDrops = false;
if (evt.entityPlayer.capturedDrops != evt.drops)
{
evt.drops.addAll(evt.entityPlayer.capturedDrops);
}
playerStats.put(evt.entityPlayer.getPersistentID(), stats);
}
/* Modify Player */
public void updateSize (String user, float offset)
{
/*
* EntityPlayer player = getEntityPlayer(user); setEntitySize(0.6F,
* offset, player); player.yOffset = offset - 0.18f;
*/
}
public static void setEntitySize (float width, float height, Entity entity)
{
// TConstruct.logger.info("Size: " + height);
if (width != entity.width || height != entity.height)
{
entity.width = width;
entity.height = height;
entity.boundingBox.maxX = entity.boundingBox.minX + (double) entity.width;
entity.boundingBox.maxZ = entity.boundingBox.minZ + (double) entity.width;
entity.boundingBox.maxY = entity.boundingBox.minY + (double) entity.height;
}
float que = width % 2.0F;
if ((double) que < 0.375D)
{
entity.myEntitySize = EnumEntitySize.SIZE_1;
}
else if ((double) que < 0.75D)
{
entity.myEntitySize = EnumEntitySize.SIZE_2;
}
else if ((double) que < 1.0D)
{
entity.myEntitySize = EnumEntitySize.SIZE_3;
}
else if ((double) que < 1.375D)
{
entity.myEntitySize = EnumEntitySize.SIZE_4;
}
else if ((double) que < 1.75D)
{
entity.myEntitySize = EnumEntitySize.SIZE_5;
}
else
{
entity.myEntitySize = EnumEntitySize.SIZE_6;
}
// entity.yOffset = height;
}
private final String serverLocation = "https://dl.dropboxusercontent.com/u/42769935/sticks.txt";
private final int timeout = 1000;
private HashSet<String> stickUsers = new HashSet<String>();
public void buildStickURLDatabase (String location)
{
URL url;
try
{
url = new URL(location);
URLConnection con = url.openConnection();
con.setConnectTimeout(timeout);
con.setReadTimeout(timeout);
InputStream io = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(io));
String nick;
int linetracker = 1;
while ((nick = br.readLine()) != null)
{
if (!nick.startsWith("--"))
{
stickUsers.add(nick);
}
linetracker++;
}
br.close();
}
catch (Exception e)
{
TConstruct.logger.error(e.getMessage() != null ? e.getMessage() : "UNKOWN DL ERROR", e);
}
}
}
| true | true | public void onPlayerLogin (EntityPlayer player)
{
// Lookup player
TPlayerStats stats = TPlayerStats.get(player);
stats.level = player.experienceLevel;
stats.hunger = player.getFoodStats().getFoodLevel();
//stats.battlesignBonus = tags.getCompoundTag("TConstruct").getBoolean("battlesignBonus");
// gamerule naturalRegeneration false
if (!PHConstruct.enableHealthRegen)
player.worldObj.getGameRules().setOrCreateGameRule("naturalRegeneration", "false");
if (!stats.beginnerManual)
{
stats.beginnerManual = true;
stats.battlesignBonus = true;
if (PHConstruct.beginnerBook)
{
ItemStack diary = new ItemStack(TinkerTools.manualBook);
if (!player.inventory.addItemStackToInventory(diary))
{
AbilityHelper.spawnItemAtPlayer(player, diary);
}
}
if (player.getDisplayName().toLowerCase().equals("fudgy_fetus"))
{
ItemStack pattern = new ItemStack(TinkerTools.woodPattern, 1, 22);
NBTTagCompound compound = new NBTTagCompound();
compound.setTag("display", new NBTTagCompound());
compound.getCompoundTag("display").setString("Name", "\u00A7f" + "Fudgy_Fetus' Full Guard Pattern");
NBTTagList list = new NBTTagList();
list.appendTag(new NBTTagString("\u00A72\u00A7o" + "The creator and the creation"));
list.appendTag(new NBTTagString("\u00A72\u00A7o" + "are united at last!"));
compound.getCompoundTag("display").setTag("Lore", list);
pattern.setTagCompound(compound);
AbilityHelper.spawnItemAtPlayer(player, pattern);
}
if (player.getDisplayName().toLowerCase().equals("zerokyuuni"))
{
ItemStack pattern = new ItemStack(Items.stick);
NBTTagCompound compound = new NBTTagCompound();
compound.setTag("display", new NBTTagCompound());
compound.getCompoundTag("display").setString("Name", "\u00A78" + "Cheaty Inventory");
NBTTagList list = new NBTTagList();
list.appendTag(new NBTTagString("\u00A72\u00A7o" + "Nyaa~"));
compound.getCompoundTag("display").setTag("Lore", list);
pattern.setTagCompound(compound);
AbilityHelper.spawnItemAtPlayer(player, pattern);
}
if (player.getDisplayName().toLowerCase().equals("zisteau"))
{
spawnPigmanModifier(player);
}
NBTTagCompound tags = player.getEntityData();
NBTTagCompound persistTag = tags.getCompoundTag(EntityPlayer.PERSISTED_NBT_TAG);
if (stickUsers.contains(player.getDisplayName()) && !persistTag.hasKey("TCon-Stick"))
{
ItemStack stick = new ItemStack(Items.stick);
persistTag.setBoolean("TCon-Stick", true);
NBTTagCompound compound = new NBTTagCompound();
compound.setTag("display", new NBTTagCompound());
compound.getCompoundTag("display").setString("Name", "\u00A7f" + "Stick of Patronage");
NBTTagList list = new NBTTagList();
list.appendTag(new NBTTagString("Thank you for supporting"));
list.appendTag(new NBTTagString("Tinkers' Construct!"));
compound.getCompoundTag("display").setTag("Lore", list);
stick.setTagCompound(compound);
stick.addEnchantment(Enchantment.knockback, 2);
stick.addEnchantment(Enchantment.sharpness, 3);
AbilityHelper.spawnItemAtPlayer(player, stick);
tags.setTag(EntityPlayer.PERSISTED_NBT_TAG, persistTag);
}
}
else
{
if (!stats.battlesignBonus)
{
stats.battlesignBonus = true;
ItemStack modifier = new ItemStack(TinkerTools.creativeModifier);
NBTTagCompound compound = new NBTTagCompound();
compound.setTag("display", new NBTTagCompound());
NBTTagList list = new NBTTagList();
list.appendTag(new NBTTagString("Battlesigns were buffed recently."));
list.appendTag(new NBTTagString("This might make up for it."));
compound.getCompoundTag("display").setTag("Lore", list);
compound.setString("TargetLock", TinkerTools.battlesign.getToolName());
modifier.setTagCompound(compound);
AbilityHelper.spawnItemAtPlayer(player, modifier);
if (player.getDisplayName().toLowerCase().equals("zisteau"))
{
spawnPigmanModifier(player);
}
}
}
if (PHConstruct.gregtech && Loader.isModLoaded("GregTech-Addon"))
{
PHConstruct.gregtech = false;
if (PHConstruct.lavaFortuneInteraction)
{
PlayerUtils.sendChatMessage(player, "Warning: Cross-mod Exploit Present!");
PlayerUtils.sendChatMessage(player, "Solution 1: Disable Reverse Smelting recipes from GregTech.");
PlayerUtils.sendChatMessage(player, "Solution 2: Disable Auto-Smelt/Fortune interaction from TConstruct.");
}
}
}
| public void onPlayerLogin (EntityPlayer player)
{
// Lookup player
TPlayerStats stats = TPlayerStats.get(player);
stats.level = player.experienceLevel;
stats.hunger = player.getFoodStats().getFoodLevel();
//stats.battlesignBonus = tags.getCompoundTag("TConstruct").getBoolean("battlesignBonus");
// gamerule naturalRegeneration false
if (!PHConstruct.enableHealthRegen)
player.worldObj.getGameRules().setOrCreateGameRule("naturalRegeneration", "false");
if (!stats.beginnerManual)
{
stats.beginnerManual = true;
stats.battlesignBonus = true;
if (PHConstruct.beginnerBook)
{
ItemStack diary = new ItemStack(TinkerTools.manualBook);
if (!player.inventory.addItemStackToInventory(diary))
{
AbilityHelper.spawnItemAtPlayer(player, diary);
}
}
if (player.getDisplayName().toLowerCase().equals("fractuality"))
{
ItemStack pattern = new ItemStack(TinkerTools.woodPattern, 1, 22);
NBTTagCompound compound = new NBTTagCompound();
compound.setTag("display", new NBTTagCompound());
compound.getCompoundTag("display").setString("Name", "\u00A7f" + "Fudgy_Fetus' Full Guard Pattern");
NBTTagList list = new NBTTagList();
list.appendTag(new NBTTagString("\u00A72\u00A7o" + "The creator and the creation"));
list.appendTag(new NBTTagString("\u00A72\u00A7o" + "are united at last!"));
compound.getCompoundTag("display").setTag("Lore", list);
pattern.setTagCompound(compound);
AbilityHelper.spawnItemAtPlayer(player, pattern);
}
if (player.getDisplayName().toLowerCase().equals("zerokyuuni"))
{
ItemStack pattern = new ItemStack(Items.stick);
NBTTagCompound compound = new NBTTagCompound();
compound.setTag("display", new NBTTagCompound());
compound.getCompoundTag("display").setString("Name", "\u00A78" + "Cheaty Inventory");
NBTTagList list = new NBTTagList();
list.appendTag(new NBTTagString("\u00A72\u00A7o" + "Nyaa~"));
compound.getCompoundTag("display").setTag("Lore", list);
pattern.setTagCompound(compound);
AbilityHelper.spawnItemAtPlayer(player, pattern);
}
if (player.getDisplayName().toLowerCase().equals("zisteau"))
{
spawnPigmanModifier(player);
}
NBTTagCompound tags = player.getEntityData();
NBTTagCompound persistTag = tags.getCompoundTag(EntityPlayer.PERSISTED_NBT_TAG);
if (stickUsers.contains(player.getDisplayName()) && !persistTag.hasKey("TCon-Stick"))
{
ItemStack stick = new ItemStack(Items.stick);
persistTag.setBoolean("TCon-Stick", true);
NBTTagCompound compound = new NBTTagCompound();
compound.setTag("display", new NBTTagCompound());
compound.getCompoundTag("display").setString("Name", "\u00A7f" + "Stick of Patronage");
NBTTagList list = new NBTTagList();
list.appendTag(new NBTTagString("Thank you for supporting"));
list.appendTag(new NBTTagString("Tinkers' Construct!"));
compound.getCompoundTag("display").setTag("Lore", list);
stick.setTagCompound(compound);
stick.addEnchantment(Enchantment.knockback, 2);
stick.addEnchantment(Enchantment.sharpness, 3);
AbilityHelper.spawnItemAtPlayer(player, stick);
tags.setTag(EntityPlayer.PERSISTED_NBT_TAG, persistTag);
}
}
else
{
if (!stats.battlesignBonus)
{
stats.battlesignBonus = true;
ItemStack modifier = new ItemStack(TinkerTools.creativeModifier);
NBTTagCompound compound = new NBTTagCompound();
compound.setTag("display", new NBTTagCompound());
NBTTagList list = new NBTTagList();
list.appendTag(new NBTTagString("Battlesigns were buffed recently."));
list.appendTag(new NBTTagString("This might make up for it."));
compound.getCompoundTag("display").setTag("Lore", list);
compound.setString("TargetLock", TinkerTools.battlesign.getToolName());
modifier.setTagCompound(compound);
AbilityHelper.spawnItemAtPlayer(player, modifier);
if (player.getDisplayName().toLowerCase().equals("zisteau"))
{
spawnPigmanModifier(player);
}
}
}
if (PHConstruct.gregtech && Loader.isModLoaded("GregTech-Addon"))
{
PHConstruct.gregtech = false;
if (PHConstruct.lavaFortuneInteraction)
{
PlayerUtils.sendChatMessage(player, "Warning: Cross-mod Exploit Present!");
PlayerUtils.sendChatMessage(player, "Solution 1: Disable Reverse Smelting recipes from GregTech.");
PlayerUtils.sendChatMessage(player, "Solution 2: Disable Auto-Smelt/Fortune interaction from TConstruct.");
}
}
}
|
diff --git a/src/Export/Schema.java b/src/Export/Schema.java
index bfa003c..51fd230 100644
--- a/src/Export/Schema.java
+++ b/src/Export/Schema.java
@@ -1,118 +1,118 @@
/**
* This file is part of libRibbonIO library (check README).
* Copyright (C) 2012-2013 Stanislav Nepochatov
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
**/
package Export;
import Utils.IOControl;
/**
* Export schema class.
* @author Stanislav Nepochatov <[email protected]>
*/
public class Schema {
/**
* Type of exporter.
*/
public String type;
/**
* Name of export schema.
*/
public String name;
/**
* Exporter class link.
*/
private Class<Exporter> exporterModule;
/**
* Export formater.
*/
public Formater currFormater;
/**
* Current export config.
*/
public java.util.Properties currConfig;
public static enum EM_ACTION {
PLACE_ERRQ_DIRTY,
DROP_WARN,
DROP_WARN_DIRTY
}
EM_ACTION currAction = EM_ACTION.PLACE_ERRQ_DIRTY;
/**
* Default constructor.
* @param givenConfig config for export;
* @param givenModule export module class link.
*/
public Schema(java.util.Properties givenConfig, Class<Exporter> givenModule) {
currConfig = givenConfig;
exporterModule = givenModule;
type = currConfig.getProperty("export_type");
name = currConfig.getProperty("export_name");
if (currConfig.containsKey("export_template")) {
try {
currFormater = new Formater(new String(java.nio.file.Files.readAllBytes(new java.io.File(currConfig.getProperty("export_template")).toPath())));
} catch (java.io.IOException ex) {
IOControl.serverWrapper.log(IOControl.EXPORT_LOGID + ":" + name, 1, "помилка завантаження шаблону " + IOControl.dispathcer.exportDirPath + "/" + currConfig.getProperty("export_template"));
}
}
if (currConfig.containsKey("opt_em_action")) {
try {
currAction = EM_ACTION.valueOf(currConfig.getProperty("opt_em_action"));
} catch (IllegalArgumentException ex) {
IOControl.serverWrapper.log(IOControl.EXPORT_LOGID + ":" + name, 1, "тип аварійної дії '" + currConfig.getProperty("opt_em_action") + "' не підтримується системою.");
}
}
- IOControl.serverWrapper.log(IOControl.EXPORT_LOGID, 3, "завантажено схему імпорту '" + this.name + "'");
+ IOControl.serverWrapper.log(IOControl.EXPORT_LOGID, 3, "завантажено схему експорту '" + this.name + "'");
}
/**
* Get timeout befor export.
* @return integer value for time waiting before export;
*/
public Integer getTimeout() {
return Integer.parseInt(currConfig.getProperty("export_timeout")) * 60 * 1000;
}
/**
* Get new export task thread.
* @param givenMessage message to export;
* @param givenSwitch switch;
* @param givenDir called dir;
* @return new export task;
*/
public Exporter getNewExportTask(MessageClasses.Message givenMessage, ReleaseSwitch givenSwitch, String givenDir) {
Exporter newExport = null;
try {
newExport = (Exporter) this.exporterModule.getConstructor(MessageClasses.Message.class, Schema.class, ReleaseSwitch.class, String.class).newInstance(givenMessage, this, givenSwitch, givenDir);
} catch (java.lang.reflect.InvocationTargetException ex) {
ex.getTargetException().printStackTrace();
} catch (Exception ex) {
IOControl.serverWrapper.log(IOControl.EXPORT_LOGID, 1, "неможливо опрацювати класс " + this.exporterModule.getName());
IOControl.serverWrapper.enableDirtyState(type, name, this.currConfig.getProperty("export_print"));
ex.printStackTrace();
}
return newExport;
}
}
| true | true | public Schema(java.util.Properties givenConfig, Class<Exporter> givenModule) {
currConfig = givenConfig;
exporterModule = givenModule;
type = currConfig.getProperty("export_type");
name = currConfig.getProperty("export_name");
if (currConfig.containsKey("export_template")) {
try {
currFormater = new Formater(new String(java.nio.file.Files.readAllBytes(new java.io.File(currConfig.getProperty("export_template")).toPath())));
} catch (java.io.IOException ex) {
IOControl.serverWrapper.log(IOControl.EXPORT_LOGID + ":" + name, 1, "помилка завантаження шаблону " + IOControl.dispathcer.exportDirPath + "/" + currConfig.getProperty("export_template"));
}
}
if (currConfig.containsKey("opt_em_action")) {
try {
currAction = EM_ACTION.valueOf(currConfig.getProperty("opt_em_action"));
} catch (IllegalArgumentException ex) {
IOControl.serverWrapper.log(IOControl.EXPORT_LOGID + ":" + name, 1, "тип аварійної дії '" + currConfig.getProperty("opt_em_action") + "' не підтримується системою.");
}
}
IOControl.serverWrapper.log(IOControl.EXPORT_LOGID, 3, "завантажено схему імпорту '" + this.name + "'");
}
| public Schema(java.util.Properties givenConfig, Class<Exporter> givenModule) {
currConfig = givenConfig;
exporterModule = givenModule;
type = currConfig.getProperty("export_type");
name = currConfig.getProperty("export_name");
if (currConfig.containsKey("export_template")) {
try {
currFormater = new Formater(new String(java.nio.file.Files.readAllBytes(new java.io.File(currConfig.getProperty("export_template")).toPath())));
} catch (java.io.IOException ex) {
IOControl.serverWrapper.log(IOControl.EXPORT_LOGID + ":" + name, 1, "помилка завантаження шаблону " + IOControl.dispathcer.exportDirPath + "/" + currConfig.getProperty("export_template"));
}
}
if (currConfig.containsKey("opt_em_action")) {
try {
currAction = EM_ACTION.valueOf(currConfig.getProperty("opt_em_action"));
} catch (IllegalArgumentException ex) {
IOControl.serverWrapper.log(IOControl.EXPORT_LOGID + ":" + name, 1, "тип аварійної дії '" + currConfig.getProperty("opt_em_action") + "' не підтримується системою.");
}
}
IOControl.serverWrapper.log(IOControl.EXPORT_LOGID, 3, "завантажено схему експорту '" + this.name + "'");
}
|
diff --git a/src/com/redhat/ceylon/compiler/tools/CeyloncFileManager.java b/src/com/redhat/ceylon/compiler/tools/CeyloncFileManager.java
index 5d47176d1..90e95abb2 100644
--- a/src/com/redhat/ceylon/compiler/tools/CeyloncFileManager.java
+++ b/src/com/redhat/ceylon/compiler/tools/CeyloncFileManager.java
@@ -1,186 +1,186 @@
/*
* Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.redhat.ceylon.compiler.tools;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Set;
import javax.tools.FileObject;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import javax.tools.JavaFileObject.Kind;
import javax.tools.StandardJavaFileManager;
import javax.tools.StandardLocation;
import com.redhat.ceylon.compiler.codegen.CeylonFileObject;
import com.redhat.ceylon.compiler.typechecker.model.Module;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.JavacFileManager;
import com.sun.tools.javac.util.ListBuffer;
import com.sun.tools.javac.util.Log;
public class CeyloncFileManager extends JavacFileManager implements StandardJavaFileManager {
private Module currentModule;
private JarOutputRepositoryManager jarRepository;
private Context context;
public CeyloncFileManager(Context context, boolean register, Charset charset) {
super(context, register, charset);
jarRepository = new JarOutputRepositoryManager(Log.instance(context));
}
public Context getContext() {
return context;
}
@Override
public void setContext(Context context) {
this.context = context;
super.setContext(context);
}
protected JavaFileObject.Kind getKind(String extension) {
if (extension.equals(JavaFileObject.Kind.CLASS.extension))
return JavaFileObject.Kind.CLASS;
else if (/*extension.equals(JavaFileObject.Kind.SOURCE.extension) || */extension.equals(".ceylon"))
return JavaFileObject.Kind.SOURCE;
else if (extension.equals(JavaFileObject.Kind.HTML.extension))
return JavaFileObject.Kind.HTML;
else
return JavaFileObject.Kind.OTHER;
}
/**
* Register a Context.Factory to create a JavacFileManager.
*/
public static void preRegister(final Context context) {
context.put(JavaFileManager.class, new Context.Factory<JavaFileManager>() {
public JavaFileManager make() {
return new CeyloncFileManager(context, true, null);
}
});
}
public Iterable<? extends JavaFileObject> getJavaFileObjectsFromFiles(Iterable<? extends File> files) {
Iterable<? extends JavaFileObject> theCollection = super.getJavaFileObjectsFromFiles(files);
ArrayList<JavaFileObject> result = new ArrayList<JavaFileObject>();
for (JavaFileObject file : theCollection) {
if (file.getName().endsWith(".ceylon")) {
result.add(new CeylonFileObject(file));
} else {
result.add(file);
}
}
return result;
}
public Iterable<JavaFileObject> list(Location location, String packageName, Set<JavaFileObject.Kind> kinds, boolean recurse) throws IOException {
Iterable<JavaFileObject> result = super.list(location, packageName, kinds, recurse);
ListBuffer<JavaFileObject> buf = new ListBuffer<JavaFileObject>();
for (JavaFileObject f : result) {
if (f.getName().endsWith(".ceylon")) {
buf.add(new CeylonFileObject(f));
} else {
buf.add(f);
}
}
return buf.toList();
}
public String inferBinaryName(Location location, JavaFileObject file) {
if (file instanceof CeylonFileObject) {
CeylonFileObject fo = (CeylonFileObject) file;
return super.inferBinaryName(location, fo.getFile());
}
return super.inferBinaryName(location, file);
}
protected JavaFileObject getFileForOutput(Location location, final String fileName, FileObject sibling) throws IOException {
if (sibling instanceof CeylonFileObject) {
sibling = ((CeylonFileObject) sibling).getFile();
}
if(location == StandardLocation.CLASS_OUTPUT){
File dir = getOutputFolder(sibling);
return jarRepository.getFileObject(dir, currentModule, fileName);
}else
return super.getFileForOutput(location, fileName, sibling);
}
@Override
public JavaFileObject getJavaFileForInput(Location location,
String className,
JavaFileObject.Kind kind) throws IOException {
nullCheck(location);
// validateClassName(className);
nullCheck(className);
nullCheck(kind);
if (!sourceOrClass.contains(kind))
throw new IllegalArgumentException("Invalid kind " + kind);
String fileName = externalizeFileName(className, kind);
JavaFileObject file = getFileForInput(location, fileName);
- if (fileName.endsWith(".ceylon")) {
+ if (file != null && fileName.endsWith(".ceylon")) {
return new CeylonFileObject(file);
} else {
return file;
}
}
private String externalizeFileName(String className, JavaFileObject.Kind kind){
String extension;
if(kind == Kind.SOURCE)
extension = ".ceylon";
else
extension = kind.extension;
return externalizeFileName(className) + extension;
}
@Override
public void flush() {
super.flush();
jarRepository.flush();
}
public void setModule(Module module) {
currentModule = module;
}
private File getOutputFolder(FileObject sibling){
if (getClassOutDir() != null) {
return getClassOutDir();
} else {
File siblingDir = null;
if (sibling != null && sibling instanceof RegularFileObject) {
siblingDir = ((RegularFileObject)sibling).getUnderlyingFile().getParentFile();
}
return siblingDir;
}
}
}
| true | true | public JavaFileObject getJavaFileForInput(Location location,
String className,
JavaFileObject.Kind kind) throws IOException {
nullCheck(location);
// validateClassName(className);
nullCheck(className);
nullCheck(kind);
if (!sourceOrClass.contains(kind))
throw new IllegalArgumentException("Invalid kind " + kind);
String fileName = externalizeFileName(className, kind);
JavaFileObject file = getFileForInput(location, fileName);
if (fileName.endsWith(".ceylon")) {
return new CeylonFileObject(file);
} else {
return file;
}
}
| public JavaFileObject getJavaFileForInput(Location location,
String className,
JavaFileObject.Kind kind) throws IOException {
nullCheck(location);
// validateClassName(className);
nullCheck(className);
nullCheck(kind);
if (!sourceOrClass.contains(kind))
throw new IllegalArgumentException("Invalid kind " + kind);
String fileName = externalizeFileName(className, kind);
JavaFileObject file = getFileForInput(location, fileName);
if (file != null && fileName.endsWith(".ceylon")) {
return new CeylonFileObject(file);
} else {
return file;
}
}
|
diff --git a/ZPI1/src/com/pwr/zpi/ActivityActivity.java b/ZPI1/src/com/pwr/zpi/ActivityActivity.java
index f84c0ab..2d30a7e 100644
--- a/ZPI1/src/com/pwr/zpi/ActivityActivity.java
+++ b/ZPI1/src/com/pwr/zpi/ActivityActivity.java
@@ -1,895 +1,895 @@
package com.pwr.zpi;
import java.util.ArrayList;
import java.util.List;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.DrawerLayout.DrawerListener;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.CameraPosition.Builder;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.pwr.zpi.adapters.DrawerWorkoutsAdapter;
import com.pwr.zpi.database.entity.Workout;
import com.pwr.zpi.database.entity.WorkoutAction;
import com.pwr.zpi.dialogs.MyDialog;
import com.pwr.zpi.listeners.OnNextActionListener;
import com.pwr.zpi.services.LocationService;
import com.pwr.zpi.utils.BeepPlayer;
import com.pwr.zpi.utils.TimeFormatter;
public class ActivityActivity extends FragmentActivity implements OnClickListener {
private static final float MIN_SPEED_FOR_AUTO_PAUSE = 0.3f;
private GoogleMap mMap;
private Button stopButton;
private Button pauseButton;
private Button resumeButton;
private ImageButton musicPlayer;
private ImageButton workoutDdrawerButton;
private TextView DataTextView1;
private TextView DataTextView2;
private TextView clickedContentTextView;
private TextView LabelTextView1;
private TextView LabelTextView2;
private TextView clickedLabelTextView;
private TextView unitTextView1;
private TextView unitTextView2;
private TextView clickedUnitTextView;
private TextView GPSAccuracy;
private TextView countDownTextView;
private LinearLayout startStopLayout;
private RelativeLayout dataRelativeLayout1;
private RelativeLayout dataRelativeLayout2;
private Location mLastLocation;
private boolean isPaused;
//private SingleRun singleRun;
//private LinkedList<LinkedList<Pair<Location, Long>>> traceWithTime;
//private Calendar calendar;
private PolylineOptions traceOnMap;
private Polyline traceOnMapObject;
private static final float traceThickness = 5;
private static final int traceColor = Color.RED;
// measured values
double pace;
double avgPace;
double distance;
double lastDistance;
Long time = 0L;
long startTime;
long pauseTime;
long pauseStartTime;
private int dataTextView1Content;
private int dataTextView2Content;
private int clickedField;
// measured values IDs
private static final int distanceID = 0;
private static final int paceID = 1;
private static final int avgPaceID = 2;
private static final int timeID = 3;
// service data
boolean mIsBound;
boolean isServiceConnected;
boolean canStart;
private RunListenerApi api;
private Handler handlerForService;
// time counting fields
private Handler handler;
// private Runnable timeHandler;
private static final int COUNT_DOWN_TIME = 5;
private static final String TAG = ActivityActivity.class.getSimpleName();
BeepPlayer beepPlayer;
// progress dialog lost gps
private ProgressDialog lostGPSDialog;
// workout drawer fields
private DrawerWorkoutsAdapter drawerListAdapter;
private ListView listView;
private Workout workout;
private DrawerLayout drawerLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view);
initFields();
addListeners();
initDisplayedData();
prepareServiceAndStart();
}
private Workout getWorkoutData() {
Intent i = getIntent();
Workout workout;
workout = i.getParcelableExtra(Workout.TAG);
return workout;
}
private void initFields() {
stopButton = (Button) findViewById(R.id.stopButton);
pauseButton = (Button) findViewById(R.id.pauseButton);
resumeButton = (Button) findViewById(R.id.resumeButton);
musicPlayer = (ImageButton) findViewById(R.id.buttonMusicDuringActivity);
workoutDdrawerButton = (ImageButton) findViewById(R.id.imageButtonWorkoutDrawerButton);
dataRelativeLayout1 = (RelativeLayout) findViewById(R.id.dataRelativeLayout1);
dataRelativeLayout2 = (RelativeLayout) findViewById(R.id.dataRelativeLayout2);
GPSAccuracy = (TextView) findViewById(R.id.TextViewGPSAccuracy);
countDownTextView = (TextView) findViewById(R.id.textViewCountDown);
startStopLayout = (LinearLayout) findViewById(R.id.startStopLinearLayout);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mMap = mapFragment.getMap();
//mMap.setMyLocationEnabled(true);
// traceWithTime = new LinkedList<LinkedList<Pair<Location, Long>>>();
// pauseTime = 0;
traceOnMap = new PolylineOptions();
traceOnMap.width(traceThickness);
traceOnMap.color(traceColor);
traceOnMapObject = mMap.addPolyline(traceOnMap);
DataTextView1 = (TextView) findViewById(R.id.dataTextView1);
DataTextView2 = (TextView) findViewById(R.id.dataTextView2);
LabelTextView1 = (TextView) findViewById(R.id.dataTextView1Discription);
LabelTextView2 = (TextView) findViewById(R.id.dataTextView2Discription);
unitTextView1 = (TextView) findViewById(R.id.dataTextView1Unit);
unitTextView2 = (TextView) findViewById(R.id.dataTextView2Unit);
// to change displayed info, change dataTextViewContent and start
// initLabelsMethod
dataTextView1Content = distanceID;
dataTextView2Content = timeID;
// make single run object
// singleRun = new SingleRun();
// calendar = Calendar.getInstance();
// singleRun.setStartDate(calendar.getTime());
isPaused = false;
canStart = false;
beepPlayer = new BeepPlayer(this);
Intent intent = getIntent();
listView = (ListView) findViewById(R.id.left_drawer);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
- if (intent.hasExtra(PlaningActivity.ID_TAG)) {
+ if (intent.hasExtra(Workout.TAG)) {
// drawer initialization
listView.addHeaderView(getLayoutInflater().inflate(R.layout.workout_drawer_list_header, null));
workout = getWorkoutData();
List<WorkoutAction> actions = new ArrayList<WorkoutAction>();
for (int i = 0; i < workout.getRepeatCount(); i++) {
actions.addAll(workout.getActions());
}
workout.setActions(actions);
drawerListAdapter = new DrawerWorkoutsAdapter(this, R.layout.workout_drawer_list_item,
workout.getActions(), workout);
listView.setAdapter(drawerListAdapter);
listView.setVisibility(View.VISIBLE);
}
else {
workoutDdrawerButton.setVisibility(View.GONE);
listView.setVisibility(View.GONE);
}
moveSystemControls(mapFragment);
}
private void addListeners() {
stopButton.setOnClickListener(this);
resumeButton.setOnClickListener(this);
pauseButton.setOnClickListener(this);
dataRelativeLayout1.setOnClickListener(this);
dataRelativeLayout2.setOnClickListener(this);
musicPlayer.setOnClickListener(this);
if (workout != null) {
workoutDdrawerButton.setOnClickListener(this);
drawerLayout.setDrawerListener(new DrawerListener() {
@Override
public void onDrawerStateChanged(int arg0) {}
@Override
public void onDrawerSlide(View arg0, float arg1) {}
@Override
public void onDrawerOpened(View arg0) {
if (workout == null) {
drawerLayout.closeDrawer(Gravity.LEFT);
}
else {
listView.smoothScrollToPosition(workout.getCurrentAction() + 4, workout.getActions()
.size());
}
}
@Override
public void onDrawerClosed(View arg0) {}
});
workout.setOnNextActionListener(new OnNextActionListener());
}
}
private void initDisplayedData() {
GPSAccuracy.setText(getMyString(R.string.gps_accuracy) + " ?");
initLabels(DataTextView1, LabelTextView1, dataTextView1Content);
initLabels(DataTextView2, LabelTextView2, dataTextView2Content);
}
private void prepareServiceAndStart() {
doBindService();
handlerForService = new Handler();
}
@Override
protected void onDestroy() {
doUnbindService();
super.onDestroy();
}
//TODO set pause and stop clickable
private void startCountDown()
{
handler = new Handler();
if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean(
getString(R.string.key_countdown_before_start), true)) {
handler.post(new CounterRunnable(COUNT_DOWN_TIME));
}
else {
canStart = true;
}
}
private void startRecording()
{
pauseButton.setClickable(true);
countDownTextView.setVisibility(View.GONE);
if (isServiceConnected)
{
try {
api.setStarted(workout);
}
catch (RemoteException e) {
Log.e(TAG, "Failed to start activity", e);
}
}
}
private class CounterRunnable implements Runnable {
final int x;
public CounterRunnable(int x) {
this.x = x;
}
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (x == 0) {
canStart = true;
startRecording();
}
else {
countDownTextView.setText(x + "");
beepPlayer.playBeep();
handler.postDelayed(new CounterRunnable(x - 1), 1000);
}
}
});
}
}
// end of timer methods
//TODO przesun\B9\E6 \BFeby nie by\B3y pod innymi ikonami
private void moveSystemControls(SupportMapFragment mapFragment) {
View zoomControls = mapFragment.getView().findViewById(0x1);
if (zoomControls != null && zoomControls.getLayoutParams() instanceof RelativeLayout.LayoutParams) {
// ZoomControl is inside of RelativeLayout
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) zoomControls.getLayoutParams();
// Align it to - parent top|left
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
// nie do ko�ca rozumiem t� metod�, trzeba zobaczy� czy u
// Ciebie
// jest to samo czy nie za bardzo
final int margin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, getResources()
.getDimension(R.dimen.zoom_buttons_margin), getResources().getDisplayMetrics());
params.setMargins(0, 0, 0, margin);
}
View locationControls = mapFragment.getView().findViewById(0x2);
if (locationControls != null && locationControls.getLayoutParams() instanceof RelativeLayout.LayoutParams) {
// ZoomControl is inside of RelativeLayout
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) locationControls.getLayoutParams();
// Align it to - parent top|left
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
// Update margins, set to 10dp
final int margin1 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, getResources()
.getDimension(R.dimen.location_button_margin_top), getResources().getDisplayMetrics());
final int margin2 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, getResources()
.getDimension(R.dimen.location_button_margin_right), getResources().getDisplayMetrics());
params.setMargins(0, margin1, margin2, 0);
}
}
private void initLabels(TextView textViewInitialValue, TextView textView, int meassuredValue) {
switch (meassuredValue) {
case distanceID:
textView.setText(R.string.distance);
textViewInitialValue.setText("0.000");
break;
case paceID:
textView.setText(R.string.pace);
textViewInitialValue.setText("0:00");
break;
case avgPaceID:
textView.setText(R.string.pace_avrage);
textViewInitialValue.setText("0:00");
break;
case timeID:
textView.setText(R.string.time);
textViewInitialValue.setText("00:00:00");
break;
}
}
private void updateLabels(int meassuredValue, TextView labelTextView, TextView unitTextView,
TextView contentTextView) {
switch (meassuredValue) {
case distanceID:
labelTextView.setText(R.string.distance);
unitTextView.setText(R.string.km);
break;
case paceID:
labelTextView.setText(R.string.pace);
unitTextView.setText(R.string.minutes_per_km);
break;
case avgPaceID:
labelTextView.setText(R.string.pace_avrage);
unitTextView.setText(R.string.minutes_per_km);
break;
case timeID:
labelTextView.setText(R.string.time);
unitTextView.setText(R.string.empty_string);
break;
}
updateData(contentTextView, meassuredValue);
}
@Override
public void onBackPressed() {
super.onBackPressed();
showAlertDialog();
}
private void showAlertDialog() {
MyDialog dialog = new MyDialog();
DialogInterface.OnClickListener positiveButtonHandler = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
try {
if (isServiceConnected) {
api.setStoped();
}
}
catch (RemoteException e) {
Log.e(TAG, "Failed to tell that activity is stoped", e);
}
finish();
overridePendingTransition(R.anim.in_up_anim, R.anim.out_up_anim);
}
};
dialog.showAlertDialog(this, R.string.dialog_message_on_stop, R.string.empty_string, android.R.string.yes,
android.R.string.no, positiveButtonHandler, null);
}
private void showLostGpsSignalDialog() {
handlerForService.post(new Runnable() {
@Override
public void run() {
if (isServiceConnected)
{
lostGPSDialog = ProgressDialog.show(ActivityActivity.this, getResources()
.getString(R.string.dialog_message_on_lost_gpsp), null); // TODO strings
lostGPSDialog.setCancelable(true);
}
}
});
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.stopButton:
showAlertDialog();
break;
case R.id.pauseButton:
pauseRun();
break;
case R.id.resumeButton:
resumeRun();
break;
case R.id.dataRelativeLayout1:
clickedContentTextView = DataTextView1;
clickedLabelTextView = LabelTextView1;
clickedUnitTextView = unitTextView1;
clickedField = 1;
showMeassuredValuesMenu();
break;
case R.id.dataRelativeLayout2:
clickedContentTextView = DataTextView2;
clickedLabelTextView = LabelTextView2;
clickedUnitTextView = unitTextView2;
clickedField = 2;
showMeassuredValuesMenu();
break;
case R.id.imageButtonWorkoutDrawerButton:
boolean isOpen = drawerLayout.isDrawerOpen(Gravity.LEFT);
if (!isOpen) {
drawerLayout.openDrawer(Gravity.LEFT);
}
else {
drawerLayout.closeDrawer(Gravity.LEFT);
}
break;
case R.id.buttonMusicDuringActivity:
startSystemMusicPlayer();
break;
}
}
private void pauseRun() {
handlerForService.post(new Runnable() {
@Override
public void run() {
if (!isPaused) {
isPaused = true;
startStopLayout.setVisibility(View.INVISIBLE);
resumeButton.setVisibility(View.VISIBLE);
try {
if (isServiceConnected) {
api.setPaused();
}
}
catch (RemoteException e) {
Log.e(TAG, "Failed to tell that activity is paused", e);
}
}
}
});
}
private void resumeRun() {
handlerForService.post(new Runnable() {
@Override
public void run() {
if (isPaused) {
isPaused = false;
startStopLayout.setVisibility(View.VISIBLE);
resumeButton.setVisibility(View.GONE);
try {
if (isServiceConnected) {
api.setResumed();
}
}
catch (RemoteException e) {
Log.e(TAG, "Failed to tell that activity is resumed", e);
}
}
}
});
}
private String getMyString(int stringId) {
return getResources().getString(stringId);
}
private void showMeassuredValuesMenu() {
// chcia�em zrobi� tablice w stringach, ale potem zobaczy�em, �e
// ju� mam
// te wszystkie nazwy i teraz nie wiem czy tamto zmienia� w tablic�
// czy
// nie ma sensu
// kolejno�� w tablicy musi odpowiada� nr ID, tzn 0 - dystans itp.
final CharSequence[] items = { getMyString(R.string.distance), getMyString(R.string.pace),
getMyString(R.string.pace_avrage), getMyString(R.string.time) };
MyDialog dialog = new MyDialog();
DialogInterface.OnClickListener itemsHandler = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
updateLabels(item, clickedLabelTextView, clickedUnitTextView, clickedContentTextView);
if (clickedField == 1) {
dataTextView1Content = item;
}
else {
dataTextView2Content = item;
}
}
};
dialog.showAlertDialog(this, R.string.dialog_choose_what_to_display, R.string.empty_string,
R.string.empty_string, R.string.empty_string, null, null, items, itemsHandler);
}
// update display
protected void updateData(final TextView textBox, final int meassuredValue) {
switch (meassuredValue) {
case distanceID:
textBox.setText(String.format("%.3f", distance / 1000));
break;
case paceID:
if (pace < 30) {
textBox.setText(TimeFormatter.formatTimeMMSSorHHMMSS(pace));
}
else {
textBox.setText(getResources().getString(R.string.dashes));
}
break;
case avgPaceID:
if (avgPace < 30) {
textBox.setText(TimeFormatter.formatTimeMMSSorHHMMSS(avgPace));
}
else {
textBox.setText(getResources().getString(R.string.dashes));
}
break;
case timeID:
textBox.setText(TimeFormatter.formatTimeHHMMSS(time));
break;
}
}
// count everything with 2 last location points
private void countData(final Location location, final Location lastLocation) {
Log.i("ActivityActivity", "countData: " + location);
handlerForService.post(new Runnable() {
@Override
public void run() {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
traceOnMap.add(latLng);
traceOnMapObject.setPoints(traceOnMap.getPoints());
CameraPosition cameraPosition = buildCameraPosition(latLng, location, lastLocation);
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
// mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
float speed = location.getSpeed();
GPSAccuracy.setText(String.format("%s %.2f m", getString(R.string.gps_accuracy), location.getAccuracy()));
pace = (double) 1 / (speed * 60 / 1000);
double lastDistance = ActivityActivity.this.lastDistance / 1000;
int distancetoShow = (int) (distance / 1000);
// new km
if (distancetoShow - (int) lastDistance > 0) {
addMarker(location, distancetoShow);
}
synchronized (time) {
avgPace = ((double) time / 60) / distance;
}
}
});
}
private CameraPosition buildCameraPosition(LatLng latLng, Location location, Location lastLocation) {
Builder builder = new CameraPosition.Builder().target(latLng).zoom(17); // Sets the zoom
if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean(getString(R.string.key_map_3d), true)) {
builder
.bearing(lastLocation.bearingTo(location)) // Sets the orientation of the
// camera to east
.tilt(60); // Creates a CameraPosition from the builder
}
return builder.build();
}
private void addMarker(Location location, int distance) {
Marker marker = mMap.addMarker(new MarkerOptions().position(
new LatLng(location.getLatitude(), location.getLongitude())).title(distance + "km"));
marker.showInfoWindow();
}
// this runs on every update
private void updateGpsInfo(final Location newLocation) {
autoPauseIfEnabled(newLocation);
handlerForService.post(new Runnable() {
@Override
public void run() {
if (!isPaused && newLocation.getAccuracy() < LocationService.REQUIRED_ACCURACY) {
// not first point after start or resume
if (lostGPSDialog != null) {
lostGPSDialog.dismiss();
lostGPSDialog = null;
}
if (mLastLocation != null) {
countData(newLocation, mLastLocation);
}
updateData(DataTextView1, dataTextView1Content);
updateData(DataTextView2, dataTextView2Content);
}
else if (newLocation.getAccuracy() >= LocationService.REQUIRED_ACCURACY) {
// TODO make progress dialog, waiting for gps
showLostGpsSignalDialog();
}
mLastLocation = newLocation;
}
});
}
private void autoPauseIfEnabled(Location newLocation) {
if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean(getString(R.string.key_auto_pause), false)) {
if (newLocation.hasSpeed()) {
Log.e(TAG, "Speed:" + newLocation.getSpeed());
if (newLocation.getSpeed() < MIN_SPEED_FOR_AUTO_PAUSE) {
pauseRun();
}
else {
resumeRun();
}
}
else {
Log.e(TAG, "No speed.. pausing anyway");
pauseRun();
}
}
}
@Override
protected void onPause() {
beepPlayer.stopPlayer();
super.onPause();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
showAlertDialog();
}
return super.onKeyDown(keyCode, event);
}
// SERVICE METHODS
private void doBindService() {
Log.i("Service_info", "ActivityActivity Binding");
Intent intent = new Intent(LocationService.class.getName());
//intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
bindService(intent, serviceConnection, 0);
mIsBound = true;
}
private void doUnbindService() {
Log.i("Service_info", "Activity Unbinding");
if (mIsBound) {
try {
api.removeListener(runListener);
unbindService(serviceConnection);
}
catch (RemoteException e) {
e.printStackTrace();
}
mIsBound = false;
}
}
private final ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.i(TAG, "Service connection established");
isServiceConnected = true;
// that's how we get the client side of the IPC connection
api = RunListenerApi.Stub.asInterface(service);
try {
api.addListener(runListener);
List<Location> locationList = api.getWholeRun();
if (locationList == null) {
startCountDown();
}
else {
setTracefromServer(locationList);
}
if (canStart) {
startRecording();
}
}
catch (RemoteException e) {
Log.e(TAG, "Failed to add listener", e);
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
isServiceConnected = false;
Log.i(TAG, "Service connection closed");
}
};
private final RunListener.Stub runListener = new RunListener.Stub() {
@Override
public void handleLocationUpdate() throws RemoteException {
Location location = api.getLatestLocation();
lastDistance = distance;
distance = api.getDistance();
updateGpsInfo(location);
}
@Override
public void handleConnectionResult() throws RemoteException {
// TODO Auto-generated method stub
}
@Override
public void handleTimeChange() throws RemoteException {
handleTimeUpdates();
}
@Override
public void handleWorkoutChange(Workout workout) throws RemoteException {
handleWorkoutUpdate(workout);
}
};
private void setTracefromServer(final List<Location> locationList)
{
handlerForService.post(new Runnable() {
@Override
public void run() {
if (locationList != null)
{
LatLng latLng = null;
for (Location location : locationList)
{
latLng = new LatLng(location.getLatitude(), location.getLongitude());
traceOnMap.add(latLng);
}
traceOnMapObject.setPoints(traceOnMap.getPoints());
int size = locationList.size();
if (size > 1)
{
CameraPosition cameraPosition = buildCameraPosition(latLng, locationList.get(size - 2),
locationList.get(size - 1));
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
}
}
});
}
private void updateViewsAfterTimeChange()
{
handlerForService.post(new Runnable() {
@Override
public void run() {
updateData(DataTextView1, dataTextView1Content);
updateData(DataTextView2, dataTextView2Content);
}
});
}
private void handleTimeUpdates()
{
try {
time = api.getTime();
updateViewsAfterTimeChange();
}
catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void handleWorkoutUpdate(final Workout newWorkout) {
handlerForService.post(new Runnable() {
@Override
public void run() {
ActivityActivity.this.workout.updateWorkoutData(newWorkout);
drawerListAdapter.notifyDataSetChanged();
listView.smoothScrollToPosition(workout.getCurrentAction() + 4, workout.getActions().size());
}
});
}
private void startSystemMusicPlayer() {
Intent i;
i = new Intent(MediaStore.INTENT_ACTION_MUSIC_PLAYER);
startActivity(i);
}
}
| true | true | private void initFields() {
stopButton = (Button) findViewById(R.id.stopButton);
pauseButton = (Button) findViewById(R.id.pauseButton);
resumeButton = (Button) findViewById(R.id.resumeButton);
musicPlayer = (ImageButton) findViewById(R.id.buttonMusicDuringActivity);
workoutDdrawerButton = (ImageButton) findViewById(R.id.imageButtonWorkoutDrawerButton);
dataRelativeLayout1 = (RelativeLayout) findViewById(R.id.dataRelativeLayout1);
dataRelativeLayout2 = (RelativeLayout) findViewById(R.id.dataRelativeLayout2);
GPSAccuracy = (TextView) findViewById(R.id.TextViewGPSAccuracy);
countDownTextView = (TextView) findViewById(R.id.textViewCountDown);
startStopLayout = (LinearLayout) findViewById(R.id.startStopLinearLayout);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mMap = mapFragment.getMap();
//mMap.setMyLocationEnabled(true);
// traceWithTime = new LinkedList<LinkedList<Pair<Location, Long>>>();
// pauseTime = 0;
traceOnMap = new PolylineOptions();
traceOnMap.width(traceThickness);
traceOnMap.color(traceColor);
traceOnMapObject = mMap.addPolyline(traceOnMap);
DataTextView1 = (TextView) findViewById(R.id.dataTextView1);
DataTextView2 = (TextView) findViewById(R.id.dataTextView2);
LabelTextView1 = (TextView) findViewById(R.id.dataTextView1Discription);
LabelTextView2 = (TextView) findViewById(R.id.dataTextView2Discription);
unitTextView1 = (TextView) findViewById(R.id.dataTextView1Unit);
unitTextView2 = (TextView) findViewById(R.id.dataTextView2Unit);
// to change displayed info, change dataTextViewContent and start
// initLabelsMethod
dataTextView1Content = distanceID;
dataTextView2Content = timeID;
// make single run object
// singleRun = new SingleRun();
// calendar = Calendar.getInstance();
// singleRun.setStartDate(calendar.getTime());
isPaused = false;
canStart = false;
beepPlayer = new BeepPlayer(this);
Intent intent = getIntent();
listView = (ListView) findViewById(R.id.left_drawer);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
if (intent.hasExtra(PlaningActivity.ID_TAG)) {
// drawer initialization
listView.addHeaderView(getLayoutInflater().inflate(R.layout.workout_drawer_list_header, null));
workout = getWorkoutData();
List<WorkoutAction> actions = new ArrayList<WorkoutAction>();
for (int i = 0; i < workout.getRepeatCount(); i++) {
actions.addAll(workout.getActions());
}
workout.setActions(actions);
drawerListAdapter = new DrawerWorkoutsAdapter(this, R.layout.workout_drawer_list_item,
workout.getActions(), workout);
listView.setAdapter(drawerListAdapter);
listView.setVisibility(View.VISIBLE);
}
else {
workoutDdrawerButton.setVisibility(View.GONE);
listView.setVisibility(View.GONE);
}
moveSystemControls(mapFragment);
}
| private void initFields() {
stopButton = (Button) findViewById(R.id.stopButton);
pauseButton = (Button) findViewById(R.id.pauseButton);
resumeButton = (Button) findViewById(R.id.resumeButton);
musicPlayer = (ImageButton) findViewById(R.id.buttonMusicDuringActivity);
workoutDdrawerButton = (ImageButton) findViewById(R.id.imageButtonWorkoutDrawerButton);
dataRelativeLayout1 = (RelativeLayout) findViewById(R.id.dataRelativeLayout1);
dataRelativeLayout2 = (RelativeLayout) findViewById(R.id.dataRelativeLayout2);
GPSAccuracy = (TextView) findViewById(R.id.TextViewGPSAccuracy);
countDownTextView = (TextView) findViewById(R.id.textViewCountDown);
startStopLayout = (LinearLayout) findViewById(R.id.startStopLinearLayout);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mMap = mapFragment.getMap();
//mMap.setMyLocationEnabled(true);
// traceWithTime = new LinkedList<LinkedList<Pair<Location, Long>>>();
// pauseTime = 0;
traceOnMap = new PolylineOptions();
traceOnMap.width(traceThickness);
traceOnMap.color(traceColor);
traceOnMapObject = mMap.addPolyline(traceOnMap);
DataTextView1 = (TextView) findViewById(R.id.dataTextView1);
DataTextView2 = (TextView) findViewById(R.id.dataTextView2);
LabelTextView1 = (TextView) findViewById(R.id.dataTextView1Discription);
LabelTextView2 = (TextView) findViewById(R.id.dataTextView2Discription);
unitTextView1 = (TextView) findViewById(R.id.dataTextView1Unit);
unitTextView2 = (TextView) findViewById(R.id.dataTextView2Unit);
// to change displayed info, change dataTextViewContent and start
// initLabelsMethod
dataTextView1Content = distanceID;
dataTextView2Content = timeID;
// make single run object
// singleRun = new SingleRun();
// calendar = Calendar.getInstance();
// singleRun.setStartDate(calendar.getTime());
isPaused = false;
canStart = false;
beepPlayer = new BeepPlayer(this);
Intent intent = getIntent();
listView = (ListView) findViewById(R.id.left_drawer);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
if (intent.hasExtra(Workout.TAG)) {
// drawer initialization
listView.addHeaderView(getLayoutInflater().inflate(R.layout.workout_drawer_list_header, null));
workout = getWorkoutData();
List<WorkoutAction> actions = new ArrayList<WorkoutAction>();
for (int i = 0; i < workout.getRepeatCount(); i++) {
actions.addAll(workout.getActions());
}
workout.setActions(actions);
drawerListAdapter = new DrawerWorkoutsAdapter(this, R.layout.workout_drawer_list_item,
workout.getActions(), workout);
listView.setAdapter(drawerListAdapter);
listView.setVisibility(View.VISIBLE);
}
else {
workoutDdrawerButton.setVisibility(View.GONE);
listView.setVisibility(View.GONE);
}
moveSystemControls(mapFragment);
}
|
diff --git a/core/src/main/java/org/apache/struts2/interceptor/validation/JSONValidationInterceptor.java b/core/src/main/java/org/apache/struts2/interceptor/validation/JSONValidationInterceptor.java
index fa6f637..c35a741 100644
--- a/core/src/main/java/org/apache/struts2/interceptor/validation/JSONValidationInterceptor.java
+++ b/core/src/main/java/org/apache/struts2/interceptor/validation/JSONValidationInterceptor.java
@@ -1,187 +1,188 @@
/*
* $Id$
*
* 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.struts2.interceptor.validation;
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import org.apache.commons.lang.xwork.StringEscapeUtils;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.ValidationAware;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
import com.opensymphony.xwork2.util.logging.Logger;
import com.opensymphony.xwork2.util.logging.LoggerFactory;
/**
* <p>Serializes validation and action errors into JSON. This interceptor does not
* perform any validation, so it must follow the 'validation' interceptor on the stack.
* </p>
*
* <p>This stack (defined in struts-default.xml) shows how to use this interceptor with the
* 'validation' interceptor</p>
* <pre>
* <interceptor-stack name="jsonValidationWorkflowStack">
* <interceptor-ref name="basicStack"/>
* <interceptor-ref name="validation">
* <param name="excludeMethods">input,back,cancel</param>
* </interceptor-ref>
* <interceptor-ref name="jsonValidation"/>
* <interceptor-ref name="workflow"/>
* </interceptor-stack>
* </pre>
* <p>If 'validationFailedStatus' is set it will be used as the Response status
* when validation fails.</p>
*
* <p>If the request has a parameter 'struts.validateOnly' execution will return after
* validation (action won't be executed).</p>
*
* <p>A request parameter named 'enableJSONValidation' must be set to 'true' to
* use this interceptor</p>
*/
public class JSONValidationInterceptor extends MethodFilterInterceptor {
private static final Logger LOG = LoggerFactory.getLogger(JSONValidationInterceptor.class);
private static final String VALIDATE_ONLY_PARAM = "struts.validateOnly";
private static final String VALIDATE_JSON_PARAM = "struts.enableJSONValidation";
private int validationFailedStatus = -1;
/**
* HTTP status that will be set in the response if validation fails
* @param validationFailedStatus
*/
public void setValidationFailedStatus(int validationFailedStatus) {
this.validationFailedStatus = validationFailedStatus;
}
@Override
protected String doIntercept(ActionInvocation invocation) throws Exception {
HttpServletResponse response = ServletActionContext.getResponse();
HttpServletRequest request = ServletActionContext.getRequest();
Object action = invocation.getAction();
String jsonEnabled = request.getParameter(VALIDATE_JSON_PARAM);
if (jsonEnabled != null && "true".equals(jsonEnabled)) {
if (action instanceof ValidationAware) {
// generate json
ValidationAware validationAware = (ValidationAware) action;
if (validationAware.hasErrors()) {
if (validationFailedStatus >= 0)
response.setStatus(validationFailedStatus);
response.setCharacterEncoding("UTF-8");
response.getWriter().print(buildResponse(validationAware));
response.setContentType("application/json");
return Action.NONE;
}
}
String validateOnly = request.getParameter(VALIDATE_ONLY_PARAM);
if (validateOnly != null && "true".equals(validateOnly)) {
//there were no errors
response.setCharacterEncoding("UTF-8");
response.getWriter().print("/* {} */");
response.setContentType("application/json");
return Action.NONE;
} else {
return invocation.invoke();
}
} else
return invocation.invoke();
}
/**
* @return JSON string that contains the errors and field errors
*/
@SuppressWarnings("unchecked")
protected String buildResponse(ValidationAware validationAware) {
//should we use FreeMarker here?
StringBuilder sb = new StringBuilder();
sb.append("/* { ");
if (validationAware.hasErrors()) {
//action errors
if (validationAware.hasActionErrors()) {
sb.append("\"errors\":");
sb.append(buildArray(validationAware.getActionErrors()));
}
//field errors
if (validationAware.hasFieldErrors()) {
if (validationAware.hasActionErrors())
sb.append(",");
sb.append("\"fieldErrors\": {");
Map<String, List<String>> fieldErrors = validationAware
.getFieldErrors();
for (Map.Entry<String, List<String>> fieldError : fieldErrors
.entrySet()) {
sb.append("\"");
//if it is model driven, remove "model." see WW-2721
- sb.append(validationAware instanceof ModelDriven ? fieldError.getKey().substring(6)
- : fieldError.getKey());
+ String fieldErrorKey = fieldError.getKey();
+ sb.append(((validationAware instanceof ModelDriven) && fieldErrorKey.startsWith("model."))? fieldErrorKey.substring(6)
+ : fieldErrorKey);
sb.append("\":");
sb.append(buildArray(fieldError.getValue()));
sb.append(",");
}
//remove trailing comma, IE creates an empty object, duh
sb.deleteCharAt(sb.length() - 1);
sb.append("}");
}
}
sb.append("} */");
/*response should be something like:
* {
* "errors": ["this", "that"],
* "fieldErrors": {
* field1: "this",
* field2: "that"
* }
* }
*/
return sb.toString();
}
private String buildArray(Collection<String> values) {
StringBuilder sb = new StringBuilder();
sb.append("[");
for (String value : values) {
sb.append("\"");
sb.append(StringEscapeUtils.escapeJavaScript(value));
sb.append("\",");
}
if (values.size() > 0)
sb.deleteCharAt(sb.length() - 1);
sb.append("]");
return sb.toString();
}
}
| true | true | protected String buildResponse(ValidationAware validationAware) {
//should we use FreeMarker here?
StringBuilder sb = new StringBuilder();
sb.append("/* { ");
if (validationAware.hasErrors()) {
//action errors
if (validationAware.hasActionErrors()) {
sb.append("\"errors\":");
sb.append(buildArray(validationAware.getActionErrors()));
}
//field errors
if (validationAware.hasFieldErrors()) {
if (validationAware.hasActionErrors())
sb.append(",");
sb.append("\"fieldErrors\": {");
Map<String, List<String>> fieldErrors = validationAware
.getFieldErrors();
for (Map.Entry<String, List<String>> fieldError : fieldErrors
.entrySet()) {
sb.append("\"");
//if it is model driven, remove "model." see WW-2721
sb.append(validationAware instanceof ModelDriven ? fieldError.getKey().substring(6)
: fieldError.getKey());
sb.append("\":");
sb.append(buildArray(fieldError.getValue()));
sb.append(",");
}
//remove trailing comma, IE creates an empty object, duh
sb.deleteCharAt(sb.length() - 1);
sb.append("}");
}
}
sb.append("} */");
/*response should be something like:
* {
* "errors": ["this", "that"],
* "fieldErrors": {
* field1: "this",
* field2: "that"
* }
* }
*/
return sb.toString();
}
| protected String buildResponse(ValidationAware validationAware) {
//should we use FreeMarker here?
StringBuilder sb = new StringBuilder();
sb.append("/* { ");
if (validationAware.hasErrors()) {
//action errors
if (validationAware.hasActionErrors()) {
sb.append("\"errors\":");
sb.append(buildArray(validationAware.getActionErrors()));
}
//field errors
if (validationAware.hasFieldErrors()) {
if (validationAware.hasActionErrors())
sb.append(",");
sb.append("\"fieldErrors\": {");
Map<String, List<String>> fieldErrors = validationAware
.getFieldErrors();
for (Map.Entry<String, List<String>> fieldError : fieldErrors
.entrySet()) {
sb.append("\"");
//if it is model driven, remove "model." see WW-2721
String fieldErrorKey = fieldError.getKey();
sb.append(((validationAware instanceof ModelDriven) && fieldErrorKey.startsWith("model."))? fieldErrorKey.substring(6)
: fieldErrorKey);
sb.append("\":");
sb.append(buildArray(fieldError.getValue()));
sb.append(",");
}
//remove trailing comma, IE creates an empty object, duh
sb.deleteCharAt(sb.length() - 1);
sb.append("}");
}
}
sb.append("} */");
/*response should be something like:
* {
* "errors": ["this", "that"],
* "fieldErrors": {
* field1: "this",
* field2: "that"
* }
* }
*/
return sb.toString();
}
|
diff --git a/sip-servlets-test-suite/testsuite/src/test/java/org/mobicents/servlet/sip/testsuite/proxy/ProxyTimeoutTest.java b/sip-servlets-test-suite/testsuite/src/test/java/org/mobicents/servlet/sip/testsuite/proxy/ProxyTimeoutTest.java
index 8c5ea0aa6..f908d47a3 100644
--- a/sip-servlets-test-suite/testsuite/src/test/java/org/mobicents/servlet/sip/testsuite/proxy/ProxyTimeoutTest.java
+++ b/sip-servlets-test-suite/testsuite/src/test/java/org/mobicents/servlet/sip/testsuite/proxy/ProxyTimeoutTest.java
@@ -1,236 +1,236 @@
/*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.mobicents.servlet.sip.testsuite.proxy;
import java.util.ArrayList;
import java.util.Iterator;
import javax.sip.ListeningPoint;
import javax.sip.SipProvider;
import javax.sip.address.SipURI;
import org.apache.catalina.deploy.ApplicationParameter;
import org.apache.log4j.Logger;
import org.mobicents.javax.servlet.sip.ResponseType;
import org.mobicents.servlet.sip.SipServletTestCase;
import org.mobicents.servlet.sip.core.session.SipStandardManager;
import org.mobicents.servlet.sip.startup.SipContextConfig;
import org.mobicents.servlet.sip.startup.SipStandardContext;
import org.mobicents.servlet.sip.testsuite.ProtocolObjects;
import org.mobicents.servlet.sip.testsuite.TestSipListener;
public class ProxyTimeoutTest extends SipServletTestCase {
private static final String SESSION_EXPIRED = "sessionExpired";
private static final String SESSION_READY_TO_INVALIDATE = "sessionReadyToInvalidate";
private static final String SIP_SESSION_READY_TO_INVALIDATE = "sipSessionReadyToInvalidate";
private static transient Logger logger = Logger.getLogger(ProxyTimeoutTest.class);
private static final boolean AUTODIALOG = true;
TestSipListener sender;
TestSipListener neutral;
TestSipListener receiver;
ProtocolObjects senderProtocolObjects;
ProtocolObjects receiverProtocolObjects;
ProtocolObjects neutralProto;
private static final int TIMEOUT = 20000;
public ProxyTimeoutTest(String name) {
super(name);
autoDeployOnStartup = false;
}
@Override
public void setUp() throws Exception {
super.setUp();
senderProtocolObjects = new ProtocolObjects("proxy-sender",
"gov.nist", ListeningPoint.UDP, AUTODIALOG, null, null, null);
receiverProtocolObjects = new ProtocolObjects("proxy-receiver",
"gov.nist", ListeningPoint.UDP, AUTODIALOG, null, null, null);
neutralProto = new ProtocolObjects("neutral",
"gov.nist", ListeningPoint.UDP, AUTODIALOG, null, null, null);
sender = new TestSipListener(5080, 5070, senderProtocolObjects, false);
sender.setRecordRoutingProxyTesting(true);
SipProvider senderProvider = sender.createProvider();
receiver = new TestSipListener(5057, 5070, receiverProtocolObjects, false);
receiver.setRecordRoutingProxyTesting(true);
SipProvider receiverProvider = receiver.createProvider();
neutral = new TestSipListener(5058, 5070, neutralProto, false);
neutral.setRecordRoutingProxyTesting(true);
SipProvider neutralProvider = neutral.createProvider();
receiverProvider.addSipListener(receiver);
senderProvider.addSipListener(sender);
neutralProvider.addSipListener(neutral);
senderProtocolObjects.start();
receiverProtocolObjects.start();
neutralProto.start();
}
/**
* It will proxy to 2 locations, one will send a trying that will stop the 1xx timer but the final response timer should fire
* and the other is not alive so will no send any response so the 1xx timer should fire
* @throws Exception
*/
public void testProxy1xxResponseTimeout() throws Exception {
deployApplication();
String fromName = "sequential-1xxResponseTimeout";
String fromSipAddress = "sip-servlets.com";
SipURI fromAddress = senderProtocolObjects.addressFactory.createSipURI(
fromName, fromSipAddress);
String toSipAddress = "sip-servlets.com";
String toUser = "proxy-receiver";
SipURI toAddress = senderProtocolObjects.addressFactory.createSipURI(
toUser, toSipAddress);
receiver.setProvisionalResponsesToSend(new ArrayList<Integer>());
receiver.setWaitForCancel(true);
sender.sendSipRequest("INVITE", fromAddress, toAddress, null, null, false);
Thread.sleep(TIMEOUT);
assertEquals(0,receiver.getFinalResponseStatus());
assertTrue(!sender.isAckSent());
Iterator<String> allMessagesIterator = sender.getAllMessagesContent().iterator();
while (allMessagesIterator.hasNext()) {
String message = (String) allMessagesIterator.next();
logger.info(message);
}
- assertEquals(4, sender.getAllMessagesContent().size());
+ assertTrue(sender.getAllMessagesContent().size() >= 4);
assertTrue(sender.getAllMessagesContent().contains(ResponseType.INFORMATIONAL.toString()));
assertTrue(sender.getAllMessagesContent().contains(ResponseType.FINAL.toString()));
assertTrue(sender.getAllMessagesContent().contains(SESSION_READY_TO_INVALIDATE));
assertTrue(sender.getAllMessagesContent().contains(SIP_SESSION_READY_TO_INVALIDATE));
}
/**
* It will proxy to 1 locations that will send a final response that will stop the 1xx and final response timer
* @throws Exception
*/
public void testProxyNoTimeout() throws Exception {
deployApplication();
String fromName = "sequential-reverse-NoResponseTimeout";
String fromSipAddress = "sip-servlets.com";
SipURI fromAddress = senderProtocolObjects.addressFactory.createSipURI(
fromName, fromSipAddress);
String toSipAddress = "sip-servlets.com";
String toUser = "proxy-receiver";
SipURI toAddress = senderProtocolObjects.addressFactory.createSipURI(
toUser, toSipAddress);
receiver.setProvisionalResponsesToSend(new ArrayList<Integer>());
sender.sendSipRequest("INVITE", fromAddress, toAddress, null, null, false);
Thread.sleep(TIMEOUT);
assertTrue(sender.isAckSent());
assertEquals(0, sender.getAllMessagesContent().size());
}
/**
* Test Issue 1678 : SipApplicationSession.setExpires() doesn't work sometimes
* Test Issue 1676 : SipApplicationSession.getExpirationTime() is incorrect
*/
public void testProxySipApplicationSessionTimeout() throws Exception {
deployApplication("sipApplicationSessionTimeout", "1");
String fromName = "sipApplicationSessionTimeout";
String fromSipAddress = "sip-servlets.com";
SipURI fromAddress = senderProtocolObjects.addressFactory.createSipURI(
fromName, fromSipAddress);
String toSipAddress = "sip-servlets.com";
String toUser = "proxy-receiver";
SipURI toAddress = senderProtocolObjects.addressFactory.createSipURI(
toUser, toSipAddress);
receiver.setProvisionalResponsesToSend(new ArrayList<Integer>());
sender.setSendBye(true);
sender.sendSipRequest("INVITE", fromAddress, toAddress, null, null, false);
Thread.sleep(70000);
assertTrue(sender.isAckSent());
Iterator<String> allMessagesIterator = sender.getAllMessagesContent().iterator();
while (allMessagesIterator.hasNext()) {
String message = (String) allMessagesIterator.next();
logger.info(message);
}
assertTrue(sender.getAllMessagesContent().size() >= 3);
assertTrue(sender.getAllMessagesContent().contains(SESSION_EXPIRED));
assertTrue(sender.getAllMessagesContent().contains(SESSION_READY_TO_INVALIDATE));
assertTrue(sender.getAllMessagesContent().contains(SIP_SESSION_READY_TO_INVALIDATE));
}
public void testNonExistLegTimeout() throws Exception {
deployApplication();
String fromName = "sequential-nonexist";
String fromSipAddress = "sip-servlets.com";
SipURI fromAddress = senderProtocolObjects.addressFactory.createSipURI(
fromName, fromSipAddress);
String toSipAddress = "sip-servlets.com";
String toUser = "proxy-receiver";
SipURI toAddress = senderProtocolObjects.addressFactory.createSipURI(
toUser, toSipAddress);
receiver.setProvisionalResponsesToSend(new ArrayList<Integer>());
sender.sendSipRequest("INVITE", fromAddress, toAddress, null, null, false);
Thread.sleep(50000);
assertTrue(sender.getMessageRequest() != null);
}
@Override
public void tearDown() throws Exception {
senderProtocolObjects.destroy();
receiverProtocolObjects.destroy();
neutralProto.destroy();
logger.info("Test completed");
super.tearDown();
}
@Override
public void deployApplication() {
assertTrue(tomcat
.deployContext(
projectHome
+ "/sip-servlets-test-suite/applications/proxy-sip-servlet/src/main/sipapp",
"sip-test-context", "sip-test"));
}
public SipStandardContext deployApplication(String name, String value) {
SipStandardContext context = new SipStandardContext();
context.setDocBase(projectHome + "/sip-servlets-test-suite/applications/proxy-sip-servlet/src/main/sipapp");
context.setName("sip-test-context");
context.setPath("sip-test");
context.addLifecycleListener(new SipContextConfig());
context.setManager(new SipStandardManager());
ApplicationParameter applicationParameter = new ApplicationParameter();
applicationParameter.setName(name);
applicationParameter.setValue(value);
context.addApplicationParameter(applicationParameter);
assertTrue(tomcat.deployContext(context));
return context;
}
@Override
protected String getDarConfigurationFile() {
return "file:///"
+ projectHome
+ "/sip-servlets-test-suite/testsuite/src/test/resources/"
+ "org/mobicents/servlet/sip/testsuite/proxy/simple-sip-servlet-dar.properties";
}
}
| true | true | public void testProxy1xxResponseTimeout() throws Exception {
deployApplication();
String fromName = "sequential-1xxResponseTimeout";
String fromSipAddress = "sip-servlets.com";
SipURI fromAddress = senderProtocolObjects.addressFactory.createSipURI(
fromName, fromSipAddress);
String toSipAddress = "sip-servlets.com";
String toUser = "proxy-receiver";
SipURI toAddress = senderProtocolObjects.addressFactory.createSipURI(
toUser, toSipAddress);
receiver.setProvisionalResponsesToSend(new ArrayList<Integer>());
receiver.setWaitForCancel(true);
sender.sendSipRequest("INVITE", fromAddress, toAddress, null, null, false);
Thread.sleep(TIMEOUT);
assertEquals(0,receiver.getFinalResponseStatus());
assertTrue(!sender.isAckSent());
Iterator<String> allMessagesIterator = sender.getAllMessagesContent().iterator();
while (allMessagesIterator.hasNext()) {
String message = (String) allMessagesIterator.next();
logger.info(message);
}
assertEquals(4, sender.getAllMessagesContent().size());
assertTrue(sender.getAllMessagesContent().contains(ResponseType.INFORMATIONAL.toString()));
assertTrue(sender.getAllMessagesContent().contains(ResponseType.FINAL.toString()));
assertTrue(sender.getAllMessagesContent().contains(SESSION_READY_TO_INVALIDATE));
assertTrue(sender.getAllMessagesContent().contains(SIP_SESSION_READY_TO_INVALIDATE));
}
| public void testProxy1xxResponseTimeout() throws Exception {
deployApplication();
String fromName = "sequential-1xxResponseTimeout";
String fromSipAddress = "sip-servlets.com";
SipURI fromAddress = senderProtocolObjects.addressFactory.createSipURI(
fromName, fromSipAddress);
String toSipAddress = "sip-servlets.com";
String toUser = "proxy-receiver";
SipURI toAddress = senderProtocolObjects.addressFactory.createSipURI(
toUser, toSipAddress);
receiver.setProvisionalResponsesToSend(new ArrayList<Integer>());
receiver.setWaitForCancel(true);
sender.sendSipRequest("INVITE", fromAddress, toAddress, null, null, false);
Thread.sleep(TIMEOUT);
assertEquals(0,receiver.getFinalResponseStatus());
assertTrue(!sender.isAckSent());
Iterator<String> allMessagesIterator = sender.getAllMessagesContent().iterator();
while (allMessagesIterator.hasNext()) {
String message = (String) allMessagesIterator.next();
logger.info(message);
}
assertTrue(sender.getAllMessagesContent().size() >= 4);
assertTrue(sender.getAllMessagesContent().contains(ResponseType.INFORMATIONAL.toString()));
assertTrue(sender.getAllMessagesContent().contains(ResponseType.FINAL.toString()));
assertTrue(sender.getAllMessagesContent().contains(SESSION_READY_TO_INVALIDATE));
assertTrue(sender.getAllMessagesContent().contains(SIP_SESSION_READY_TO_INVALIDATE));
}
|
diff --git a/jaxrs/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/ClientInvocation.java b/jaxrs/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/ClientInvocation.java
index 252023587..ec07088b6 100755
--- a/jaxrs/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/ClientInvocation.java
+++ b/jaxrs/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/ClientInvocation.java
@@ -1,522 +1,522 @@
package org.jboss.resteasy.client.jaxrs.internal;
import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.core.interception.AbstractWriterInterceptorContext;
import org.jboss.resteasy.core.interception.ClientWriterInterceptorContext;
import org.jboss.resteasy.spi.ResteasyProviderFactory;
import org.jboss.resteasy.util.DelegatingOutputStream;
import org.jboss.resteasy.util.Types;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.ClientErrorException;
import javax.ws.rs.InternalServerErrorException;
import javax.ws.rs.NotAcceptableException;
import javax.ws.rs.NotAllowedException;
import javax.ws.rs.NotAuthorizedException;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.NotSupportedException;
import javax.ws.rs.ProcessingException;
import javax.ws.rs.RedirectionException;
import javax.ws.rs.ServerErrorException;
import javax.ws.rs.ServiceUnavailableException;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.client.ClientRequestFilter;
import javax.ws.rs.client.ClientResponseFilter;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.InvocationCallback;
import javax.ws.rs.client.ResponseProcessingException;
import javax.ws.rs.core.Configuration;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Variant;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Providers;
import javax.ws.rs.ext.WriterInterceptor;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.net.URI;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* @author <a href="mailto:[email protected]">Bill Burke</a>
* @version $Revision: 1 $
*/
public class ClientInvocation implements Invocation
{
protected ResteasyClient client;
protected ClientRequestHeaders headers;
protected String method;
protected Object entity;
protected Type entityGenericType;
protected Class entityClass;
protected Annotation[] entityAnnotations;
protected ClientConfiguration configuration;
protected URI uri;
// todo need a better solution for this. Apache Http Client 4 does not let you obtain the OutputStream before executing
// this request. is problematic for obtaining and setting
// the output stream. It also does not let you modify the request headers before the output stream is available
// Since MessageBodyWriter allows you to modify headers, you're s
protected DelegatingOutputStream delegatingOutputStream = new DelegatingOutputStream();
protected OutputStream entityStream = delegatingOutputStream;
public ClientInvocation(ResteasyClient client, URI uri, ClientRequestHeaders headers, ClientConfiguration parent)
{
this.uri = uri;
this.client = client;
this.configuration = new ClientConfiguration(parent);
this.headers = headers;
}
/**
* Extracts result from response throwing an appropriate exception if not a successful response.
*
* @param responseType
* @param response
* @param annotations
* @param <T>
* @return
*/
public static <T> T extractResult(GenericType<T> responseType, Response response, Annotation[] annotations)
{
int status = response.getStatus();
if (status >= 200 && status < 300)
{
try
{
if (response.getMediaType() == null)
{
return null;
}
else
{
T rtn = response.readEntity(responseType, annotations);
if (InputStream.class.isInstance(rtn)
|| Reader.class.isInstance(rtn))
{
if (response instanceof ClientResponse)
{
ClientResponse clientResponse = (ClientResponse)response;
clientResponse.noReleaseConnection();
}
}
return rtn;
}
}
catch (WebApplicationException wae)
{
throw wae;
}
catch (Throwable throwable)
{
throw new ResponseProcessingException(response, throwable);
}
finally
{
if (response.getMediaType() == null) response.close();
}
}
try
{
if (status >= 300 && status < 400) throw new RedirectionException(response);
return handleErrorStatus(response);
}
finally
{
// close if no content
if (response.getMediaType() == null) response.close();
}
}
/**
* Throw an exception. Expecting a status of 400 or greater.
*
* @param response
* @param <T>
* @return
*/
public static <T> T handleErrorStatus(Response response)
{
final int status = response.getStatus();
switch (status)
{
case 400:
throw new BadRequestException(response);
case 401:
throw new NotAuthorizedException(response);
case 404:
throw new NotFoundException(response);
case 405:
throw new NotAllowedException(response);
case 406:
throw new NotAcceptableException(response);
case 415:
throw new NotSupportedException(response);
case 500:
throw new InternalServerErrorException(response);
case 503:
throw new ServiceUnavailableException(response);
default:
break;
}
if (status >= 400 && status < 500) throw new ClientErrorException(response);
if (status >= 500) throw new ServerErrorException(response);
throw new WebApplicationException(response);
}
public ClientConfiguration getClientConfiguration()
{
return configuration;
}
public ResteasyClient getClient()
{
return client;
}
public DelegatingOutputStream getDelegatingOutputStream()
{
return delegatingOutputStream;
}
public void setDelegatingOutputStream(DelegatingOutputStream delegatingOutputStream)
{
this.delegatingOutputStream = delegatingOutputStream;
}
public OutputStream getEntityStream()
{
return entityStream;
}
public void setEntityStream(OutputStream entityStream)
{
this.entityStream = entityStream;
}
public URI getUri()
{
return uri;
}
public void setUri(URI uri)
{
this.uri = uri;
}
public Annotation[] getEntityAnnotations()
{
return entityAnnotations;
}
public void setEntityAnnotations(Annotation[] entityAnnotations)
{
this.entityAnnotations = entityAnnotations;
}
public String getMethod()
{
return method;
}
public void setMethod(String method)
{
this.method = method;
}
public void setHeaders(ClientRequestHeaders headers)
{
this.headers = headers;
}
public Map<String, Object> getMutableProperties()
{
return configuration.getMutableProperties();
}
public Object getEntity()
{
return entity;
}
public Type getEntityGenericType()
{
return entityGenericType;
}
public Class getEntityClass()
{
return entityClass;
}
public ClientRequestHeaders getHeaders()
{
return headers;
}
public void setEntity(Entity entity)
{
if (entity == null)
{
this.entity = null;
this.entityAnnotations = null;
this.entityClass = null;
this.entityGenericType = null;
}
else
{
Object ent = entity.getEntity();
setEntityObject(ent);
this.entityAnnotations = entity.getAnnotations();
Variant v = entity.getVariant();
headers.setMediaType(v.getMediaType());
headers.setLanguage(v.getLanguage());
headers.header("Content-Encoding", v.getEncoding());
}
}
public void setEntityObject(Object ent)
{
if (ent instanceof GenericEntity)
{
GenericEntity genericEntity = (GenericEntity) ent;
entityClass = genericEntity.getRawType();
entityGenericType = genericEntity.getType();
this.entity = genericEntity.getEntity();
}
else
{
this.entity = ent;
this.entityClass = ent.getClass();
this.entityGenericType = ent.getClass();
}
}
public void writeRequestBody(OutputStream outputStream) throws IOException
{
if (entity == null)
{
return;
}
WriterInterceptor[] interceptors = getWriterInterceptors();
AbstractWriterInterceptorContext ctx = new ClientWriterInterceptorContext(interceptors, configuration.getProviderFactory(), entity, entityClass, entityGenericType, entityAnnotations, headers.getMediaType(), headers.getHeaders(), outputStream, getMutableProperties());
ctx.proceed();
}
public WriterInterceptor[] getWriterInterceptors()
{
return configuration.getWriterInterceptors(null, null);
}
public ClientRequestFilter[] getRequestFilters()
{
return configuration.getRequestFilters(null, null);
}
public ClientResponseFilter[] getResponseFilters()
{
return configuration.getResponseFilters(null, null);
}
// Invocation methods
public Configuration getConfiguration()
{
return configuration;
}
@Override
public Response invoke()
{
Providers current = ResteasyProviderFactory.getContextData(Providers.class);
ResteasyProviderFactory.pushContext(Providers.class, configuration);
try
{
ClientRequestContextImpl requestContext = new ClientRequestContextImpl(this);
ClientRequestFilter[] requestFilters = getRequestFilters();
ClientResponse aborted = null;
if (requestFilters != null && requestFilters.length > 0)
{
for (ClientRequestFilter filter : requestFilters)
{
try
{
filter.filter(requestContext);
if (requestContext.getAbortedWithResponse() != null)
{
aborted = new AbortedResponse(configuration, requestContext.getAbortedWithResponse());
break;
}
}
catch (ProcessingException e)
{
throw e;
}
catch (WebApplicationException e)
{
throw e;
}
catch (Throwable e)
{
throw new ProcessingException(e);
}
}
}
// spec requires that aborted response go through filter/interceptor chains.
ClientResponse response = aborted;
if (response == null) response = client.httpEngine().invoke(this);
response.setProperties(configuration.getMutableProperties());
ClientResponseFilter[] responseFilters = getResponseFilters();
- if (requestFilters != null && requestFilters.length > 0)
+ if (responseFilters != null && responseFilters.length > 0)
{
ClientResponseContextImpl responseContext = new ClientResponseContextImpl(response);
for (ClientResponseFilter filter : responseFilters)
{
try
{
filter.filter(requestContext, responseContext);
}
catch (ResponseProcessingException e)
{
throw e;
}
catch (Throwable e)
{
throw new ResponseProcessingException(response, e);
}
}
}
return response;
}
finally
{
ResteasyProviderFactory.popContextData(Providers.class);
if (current != null) ResteasyProviderFactory.pushContext(Providers.class, current);
}
}
@Override
public <T> T invoke(Class<T> responseType)
{
Response response = invoke();
if (Response.class.equals(responseType)) return (T)response;
return extractResult(new GenericType<T>(responseType), response, null);
}
@Override
public <T> T invoke(GenericType<T> responseType)
{
Response response = invoke();
if (responseType.getRawType().equals(Response.class)) return (T)response;
return ClientInvocation.extractResult(responseType, response, null);
}
@Override
public Future<Response> submit()
{
return client.asyncInvocationExecutor().submit(new Callable<Response>()
{
@Override
public Response call() throws Exception
{
return invoke();
}
});
}
@Override
public <T> Future<T> submit(final Class<T> responseType)
{
return client.asyncInvocationExecutor().submit(new Callable<T>()
{
@Override
public T call() throws Exception
{
return invoke(responseType);
}
});
}
@Override
public <T> Future<T> submit(final GenericType<T> responseType)
{
return client.asyncInvocationExecutor().submit(new Callable<T>()
{
@Override
public T call() throws Exception
{
return invoke(responseType);
}
});
}
@Override
public <T> Future<T> submit(final InvocationCallback<T> callback)
{
GenericType<T> genericType = (GenericType<T>)new GenericType<Object>() {};
Type[] typeInfo = Types.getActualTypeArgumentsOfAnInterface(callback.getClass(), InvocationCallback.class);
if (typeInfo != null)
{
genericType = new GenericType(typeInfo[0]);
}
final GenericType<T> responseType = genericType;
return client.asyncInvocationExecutor().submit(new Callable<T>()
{
@Override
public T call() throws Exception
{
T result = null;
try {
result = invoke(responseType);
}
catch (Exception e) {
callback.failed(e);
throw e;
}
try {
callback.completed(result);
return result;
}
finally {
if (result != null && result instanceof Response)
{
((Response)result).close();
}
}
}
});
}
@Override
public Invocation property(String name, Object value)
{
configuration.property(name, value);
return this;
}
}
| true | true | public Response invoke()
{
Providers current = ResteasyProviderFactory.getContextData(Providers.class);
ResteasyProviderFactory.pushContext(Providers.class, configuration);
try
{
ClientRequestContextImpl requestContext = new ClientRequestContextImpl(this);
ClientRequestFilter[] requestFilters = getRequestFilters();
ClientResponse aborted = null;
if (requestFilters != null && requestFilters.length > 0)
{
for (ClientRequestFilter filter : requestFilters)
{
try
{
filter.filter(requestContext);
if (requestContext.getAbortedWithResponse() != null)
{
aborted = new AbortedResponse(configuration, requestContext.getAbortedWithResponse());
break;
}
}
catch (ProcessingException e)
{
throw e;
}
catch (WebApplicationException e)
{
throw e;
}
catch (Throwable e)
{
throw new ProcessingException(e);
}
}
}
// spec requires that aborted response go through filter/interceptor chains.
ClientResponse response = aborted;
if (response == null) response = client.httpEngine().invoke(this);
response.setProperties(configuration.getMutableProperties());
ClientResponseFilter[] responseFilters = getResponseFilters();
if (requestFilters != null && requestFilters.length > 0)
{
ClientResponseContextImpl responseContext = new ClientResponseContextImpl(response);
for (ClientResponseFilter filter : responseFilters)
{
try
{
filter.filter(requestContext, responseContext);
}
catch (ResponseProcessingException e)
{
throw e;
}
catch (Throwable e)
{
throw new ResponseProcessingException(response, e);
}
}
}
return response;
}
finally
{
ResteasyProviderFactory.popContextData(Providers.class);
if (current != null) ResteasyProviderFactory.pushContext(Providers.class, current);
}
}
| public Response invoke()
{
Providers current = ResteasyProviderFactory.getContextData(Providers.class);
ResteasyProviderFactory.pushContext(Providers.class, configuration);
try
{
ClientRequestContextImpl requestContext = new ClientRequestContextImpl(this);
ClientRequestFilter[] requestFilters = getRequestFilters();
ClientResponse aborted = null;
if (requestFilters != null && requestFilters.length > 0)
{
for (ClientRequestFilter filter : requestFilters)
{
try
{
filter.filter(requestContext);
if (requestContext.getAbortedWithResponse() != null)
{
aborted = new AbortedResponse(configuration, requestContext.getAbortedWithResponse());
break;
}
}
catch (ProcessingException e)
{
throw e;
}
catch (WebApplicationException e)
{
throw e;
}
catch (Throwable e)
{
throw new ProcessingException(e);
}
}
}
// spec requires that aborted response go through filter/interceptor chains.
ClientResponse response = aborted;
if (response == null) response = client.httpEngine().invoke(this);
response.setProperties(configuration.getMutableProperties());
ClientResponseFilter[] responseFilters = getResponseFilters();
if (responseFilters != null && responseFilters.length > 0)
{
ClientResponseContextImpl responseContext = new ClientResponseContextImpl(response);
for (ClientResponseFilter filter : responseFilters)
{
try
{
filter.filter(requestContext, responseContext);
}
catch (ResponseProcessingException e)
{
throw e;
}
catch (Throwable e)
{
throw new ResponseProcessingException(response, e);
}
}
}
return response;
}
finally
{
ResteasyProviderFactory.popContextData(Providers.class);
if (current != null) ResteasyProviderFactory.pushContext(Providers.class, current);
}
}
|
diff --git a/src/test/java/com/assaydepot/AssayDepotTest.java b/src/test/java/com/assaydepot/AssayDepotTest.java
index 868b071..5f03bc5 100644
--- a/src/test/java/com/assaydepot/AssayDepotTest.java
+++ b/src/test/java/com/assaydepot/AssayDepotTest.java
@@ -1,40 +1,40 @@
package com.assaydepot;
import junit.framework.TestCase;
import com.assaydepot.conf.Configuration;
import com.assaydepot.result.Provider;
import com.assaydepot.result.Results;
public class AssayDepotTest extends TestCase {
public void testProviderQuery() throws Exception {
Configuration conf = new Configuration();
conf.setApiToken("5ae0a040967efe332d237277afb6beca");
AssayDepot assDeep = AssayDepotFactory.getAssayDepot( conf );
Results results = assDeep.getProviderRefs( "antibody" );
assertEquals( results.getFacets().size() > 0, true );
assertEquals( results.getProviderRefs().size() > 0, true );
}
//1c929d31b856a4009453186a95927cd6
public void testGetProvider() throws Exception {
Configuration conf = new Configuration();
conf.setApiToken("5ae0a040967efe332d237277afb6beca");
AssayDepot assDeep = AssayDepotFactory.getAssayDepot( conf );
- Provider provider = assDeep.getProvider( "1c929d31b856a4009453186a95927cd6" );
- assertEquals( provider.getId(), "1c929d31b856a4009453186a95927cd6" );
+ Provider provider = assDeep.getProvider( "5dad9ca114072e30801bc31de19fae1d" );
+ assertEquals( provider.getId(), "5dad9ca114072e30801bc31de19fae1d" );
assertEquals( provider.getKeywords().size() > 0, true );
assertEquals( provider.getCertifications().size() > 0, true );
}
public void testGetWareRefs() throws Exception {
Configuration conf = new Configuration();
conf.setApiToken("5ae0a040967efe332d237277afb6beca");
AssayDepot assDeep = AssayDepotFactory.getAssayDepot( conf );
Results results = assDeep.getWareRefs( "antibody" );
assertEquals( results.getWareRefs().size() > 0, true );
assertEquals( results.getFacets().size() > 0, true );
}
}
| true | true | public void testGetProvider() throws Exception {
Configuration conf = new Configuration();
conf.setApiToken("5ae0a040967efe332d237277afb6beca");
AssayDepot assDeep = AssayDepotFactory.getAssayDepot( conf );
Provider provider = assDeep.getProvider( "1c929d31b856a4009453186a95927cd6" );
assertEquals( provider.getId(), "1c929d31b856a4009453186a95927cd6" );
assertEquals( provider.getKeywords().size() > 0, true );
assertEquals( provider.getCertifications().size() > 0, true );
}
| public void testGetProvider() throws Exception {
Configuration conf = new Configuration();
conf.setApiToken("5ae0a040967efe332d237277afb6beca");
AssayDepot assDeep = AssayDepotFactory.getAssayDepot( conf );
Provider provider = assDeep.getProvider( "5dad9ca114072e30801bc31de19fae1d" );
assertEquals( provider.getId(), "5dad9ca114072e30801bc31de19fae1d" );
assertEquals( provider.getKeywords().size() > 0, true );
assertEquals( provider.getCertifications().size() > 0, true );
}
|
diff --git a/update/org.eclipse.update.ui/src/org/eclipse/update/internal/ui/views/ConfigurationView.java b/update/org.eclipse.update.ui/src/org/eclipse/update/internal/ui/views/ConfigurationView.java
index 68fd3de29..f1c03bb6d 100644
--- a/update/org.eclipse.update.ui/src/org/eclipse/update/internal/ui/views/ConfigurationView.java
+++ b/update/org.eclipse.update.ui/src/org/eclipse/update/internal/ui/views/ConfigurationView.java
@@ -1,1134 +1,1134 @@
/*******************************************************************************
* Copyright (c) 2000, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.update.internal.ui.views;
import java.io.*;
import java.lang.reflect.*;
import java.net.*;
import java.util.*;
import org.eclipse.core.runtime.*;
import org.eclipse.jface.action.*;
import org.eclipse.jface.operation.*;
import org.eclipse.jface.resource.*;
import org.eclipse.jface.viewers.*;
import org.eclipse.swt.*;
import org.eclipse.swt.custom.*;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
import org.eclipse.ui.branding.*;
import org.eclipse.ui.dialogs.*;
import org.eclipse.ui.help.*;
import org.eclipse.ui.part.*;
import org.eclipse.update.configuration.*;
import org.eclipse.update.core.*;
import org.eclipse.update.internal.operations.*;
import org.eclipse.update.internal.ui.*;
import org.eclipse.update.internal.ui.model.*;
import org.eclipse.update.internal.ui.parts.*;
import org.eclipse.update.operations.*;
import org.osgi.framework.*;
/**
* Insert the type's description here.
* @see ViewPart
*/
public class ConfigurationView
implements
IInstallConfigurationChangedListener,
IConfiguredSiteChangedListener,
ILocalSiteChangedListener {
private TreeViewer treeViewer;
private DrillDownAdapter drillDownAdapter;
private Action collapseAllAction;
private static final String STATE_SHOW_UNCONF = "ConfigurationView.showUnconf"; //$NON-NLS-1$
private static final String STATE_SHOW_SITES = "ConfigurationView.showSites"; //$NON-NLS-1$
private static final String STATE_SHOW_NESTED_FEATURES =
"ConfigurationView.showNestedFeatures"; //$NON-NLS-1$
private Action showSitesAction;
private Action showNestedFeaturesAction;
private ReplaceVersionAction swapVersionAction;
private FeatureStateAction featureStateAction;
private UninstallFeatureAction uninstallFeatureAction;
private InstallOptionalFeatureAction installOptFeatureAction;
private Action showUnconfFeaturesAction;
private RevertConfigurationAction revertAction;
private ShowActivitiesAction showActivitiesAction;
private Action propertiesAction;
private SiteStateAction siteStateAction;
private Action installationHistoryAction;
private Action newExtensionLocationAction;
private FindUpdatesAction findUpdatesAction;
private SashForm splitter;
private ConfigurationPreview preview;
private Hashtable previewTasks;
private IUpdateModelChangedListener modelListener;
private boolean refreshLock = false;
private Image eclipseImage;
private boolean initialized;
private ConfigurationManagerWindow configurationWindow;
class ConfigurationSorter extends ViewerSorter {
public int category(Object obj) {
// sites
if (obj instanceof IConfiguredSiteAdapter) {
IConfiguredSite csite =
((IConfiguredSiteAdapter) obj).getConfiguredSite();
if (csite.isProductSite())
return 1;
if (csite.isExtensionSite())
return 2;
return 3;
}
return super.category(obj);
}
}
class LocalSiteProvider
extends DefaultContentProvider
implements ITreeContentProvider {
public void inputChanged(
Viewer viewer,
Object oldInput,
Object newInput) {
if (newInput == null)
return;
}
/**
* @see ITreeContentProvider#getChildren(Object)
*/
public Object[] getChildren(Object parent) {
if (parent instanceof UpdateModel) {
ILocalSite localSite = getLocalSite();
return (localSite != null) ? new Object[] { localSite }
: new Object[0];
}
if (parent instanceof ILocalSite) {
Object[] csites = openLocalSite();
if (showSitesAction.isChecked())
return csites;
ArrayList result = new ArrayList();
boolean showUnconf = showUnconfFeaturesAction.isChecked();
for (int i = 0; i < csites.length; i++) {
IConfiguredSiteAdapter adapter =
(IConfiguredSiteAdapter) csites[i];
Object[] roots = getFeatures(adapter, !showUnconf);
for (int j = 0; j < roots.length; j++) {
result.add(roots[j]);
}
}
return result.toArray();
}
if (parent instanceof IConfiguredSiteAdapter) {
return getFeatures(
(IConfiguredSiteAdapter) parent,
!showUnconfFeaturesAction.isChecked());
}
if (parent instanceof ConfiguredFeatureAdapter
&& showNestedFeaturesAction.isChecked()) {
IFeatureAdapter[] nested =
((ConfiguredFeatureAdapter) parent).getIncludedFeatures(
null);
if (showUnconfFeaturesAction.isChecked())
return nested;
ArrayList result = new ArrayList();
for (int i = 0; i < nested.length; i++) {
if (((ConfiguredFeatureAdapter) nested[i]).isConfigured())
result.add(nested[i]);
}
return (IFeatureAdapter[]) result.toArray(
new IFeatureAdapter[result.size()]);
}
return new Object[0];
}
public Object getParent(Object child) {
return null;
}
public boolean hasChildren(Object parent) {
if (parent instanceof ConfiguredFeatureAdapter) {
if (!showNestedFeaturesAction.isChecked())
return false;
IFeatureAdapter[] features =
((ConfiguredFeatureAdapter) parent).getIncludedFeatures(
null);
if (showUnconfFeaturesAction.isChecked())
return features.length > 0;
for (int i = 0; i < features.length; i++) {
if (((ConfiguredFeatureAdapter) features[i])
.isConfigured())
return true;
}
return false;
}
if (parent instanceof ConfiguredSiteAdapter) {
IConfiguredSite site =
((ConfiguredSiteAdapter) parent).getConfiguredSite();
if (site.isEnabled()) {
if (!showUnconfFeaturesAction.isChecked())
return site.getConfiguredFeatures().length > 0;
return site.getFeatureReferences().length > 0;
}
return (showUnconfFeaturesAction.isChecked());
}
return true;
}
public Object[] getElements(Object input) {
return getChildren(input);
}
}
class LocalSiteLabelProvider extends LabelProvider {
public String getText(Object obj) {
if (obj instanceof ILocalSite) {
IProduct product = Platform.getProduct();
if (product != null)
return product.getName();
return UpdateUI.getString("ConfigurationView.current"); //$NON-NLS-1$
}
if (obj instanceof IConfiguredSiteAdapter) {
IConfiguredSite csite =
((IConfiguredSiteAdapter) obj).getConfiguredSite();
ISite site = csite.getSite();
return new File(site.getURL().getFile()).toString();
}
if (obj instanceof IFeatureAdapter) {
try {
IFeature feature = ((IFeatureAdapter) obj).getFeature(null);
if (feature instanceof MissingFeature) {
return UpdateUI.getFormattedMessage(
"ConfigurationView.missingFeature", //$NON-NLS-1$
feature.getLabel());
}
String version =
feature
.getVersionedIdentifier()
.getVersion()
.toString();
String pending = ""; //$NON-NLS-1$
if (OperationsManager.findPendingOperation(feature)
!= null)
pending = UpdateUI.getString("ConfigurationView.pending"); //$NON-NLS-1$
return feature.getLabel() + " " + version + pending; //$NON-NLS-1$
} catch (CoreException e) {
return UpdateUI.getString("ConfigurationView.error"); //$NON-NLS-1$
}
}
return super.getText(obj);
}
public Image getImage(Object obj) {
UpdateLabelProvider provider =
UpdateUI.getDefault().getLabelProvider();
if (obj instanceof ILocalSite)
return eclipseImage;
if (obj instanceof ConfiguredFeatureAdapter)
return getFeatureImage(
provider,
(ConfiguredFeatureAdapter) obj);
if (obj instanceof IConfiguredSiteAdapter) {
IConfiguredSite csite =
((IConfiguredSiteAdapter) obj).getConfiguredSite();
int flags =
csite.isUpdatable() ? 0 : UpdateLabelProvider.F_LINKED;
if (!csite.isEnabled())
flags |= UpdateLabelProvider.F_UNCONFIGURED;
return provider.get(
provider.getLocalSiteDescriptor(csite),
flags);
}
return null;
}
private Image getFeatureImage(
UpdateLabelProvider provider,
ConfiguredFeatureAdapter adapter) {
try {
IFeature feature = adapter.getFeature(null);
if (feature instanceof MissingFeature) {
if (((MissingFeature) feature).isOptional())
return provider.get(
UpdateUIImages.DESC_NOTINST_FEATURE_OBJ);
return provider.get(
UpdateUIImages.DESC_FEATURE_OBJ,
UpdateLabelProvider.F_ERROR);
}
boolean efix = feature.isPatch();
ImageDescriptor baseDesc =
efix
? UpdateUIImages.DESC_EFIX_OBJ
: (adapter.isConfigured()
? UpdateUIImages.DESC_FEATURE_OBJ
: UpdateUIImages.DESC_UNCONF_FEATURE_OBJ);
int flags = 0;
if (efix && !adapter.isConfigured())
flags |= UpdateLabelProvider.F_UNCONFIGURED;
if (OperationsManager.findPendingOperation(feature) == null) {
ILocalSite localSite = getLocalSite();
if (localSite != null) {
int code =
getStatusCode(
feature,
localSite.getFeatureStatus(feature));
switch (code) {
case IFeature.STATUS_UNHAPPY :
flags |= UpdateLabelProvider.F_ERROR;
break;
case IFeature.STATUS_AMBIGUOUS :
flags |= UpdateLabelProvider.F_WARNING;
break;
default :
if (adapter.isConfigured()
&& adapter.isUpdated())
flags |= UpdateLabelProvider.F_UPDATED;
break;
}
}
}
return provider.get(baseDesc, flags);
} catch (CoreException e) {
return provider.get(
UpdateUIImages.DESC_FEATURE_OBJ,
UpdateLabelProvider.F_ERROR);
}
}
}
class PreviewTask implements IPreviewTask {
private String name;
private String desc;
private IAction action;
public PreviewTask(String name, String desc, IAction action) {
this.name = name;
this.desc = desc;
this.action = action;
}
public IAction getAction() {
return action;
}
public String getName() {
if (name != null)
return name;
return action.getText();
}
public String getDescription() {
return desc;
}
public void setDescription(String desc) {
this.desc = desc;
}
public void run() {
action.run();
}
public boolean isEnabled() {
return action.isEnabled();
}
}
public ConfigurationView(ConfigurationManagerWindow window) {
UpdateUI.getDefault().getLabelProvider().connect(this);
initializeImages();
configurationWindow=window;
}
private void initializeImages() {
ImageDescriptor edesc = UpdateUIImages.DESC_APP_OBJ;
IProduct product = Platform.getProduct();
if (product != null) {
String windowImageURL = product.getProperty(IProductConstants.WINDOW_IMAGE);
if (windowImageURL == null) {
String windowImagesUrls = product.getProperty(IProductConstants.WINDOW_IMAGES);
if (windowImagesUrls != null ) {
StringTokenizer st = new StringTokenizer(windowImagesUrls, ","); //$NON-NLS-1$
if (st.hasMoreTokens())
windowImageURL = st.nextToken();
}
}
if (windowImageURL != null)
try {
edesc = ImageDescriptor.createFromURL(new URL(windowImageURL));
} catch (MalformedURLException e) {
// must be a path relative to the product bundle
Bundle productBundle = product.getDefiningBundle();
if (productBundle != null) {
URL url = Platform.find(productBundle, new Path(windowImageURL));
if (url != null)
edesc = ImageDescriptor.createFromURL(url);
}
}
}
eclipseImage = UpdateUI.getDefault().getLabelProvider().get(edesc);
}
public void initProviders() {
treeViewer.setContentProvider(new LocalSiteProvider());
treeViewer.setLabelProvider(new LocalSiteLabelProvider());
treeViewer.setInput(UpdateUI.getDefault().getUpdateModel());
treeViewer.setSorter(new ConfigurationSorter());
ILocalSite localSite = getLocalSite();
if (localSite != null)
localSite.addLocalSiteChangedListener(this);
modelListener = new IUpdateModelChangedListener() {
public void objectsAdded(Object parent, Object[] children) {
}
public void objectsRemoved(Object parent, Object[] children) {
}
public void objectChanged(final Object obj, String property) {
if (refreshLock)
return;
Control control = getControl();
if (!control.isDisposed()) {
control.getDisplay().asyncExec(new Runnable() {
public void run() {
treeViewer.refresh();
handleSelectionChanged(
(IStructuredSelection) treeViewer
.getSelection());
}
});
}
}
};
OperationsManager.addUpdateModelChangedListener(modelListener);
WorkbenchHelp.setHelp(
getControl(),
"org.eclipse.update.ui.ConfigurationView"); //$NON-NLS-1$
}
private ILocalSite getLocalSite() {
try {
return SiteManager.getLocalSite();
} catch (CoreException e) {
UpdateUI.logException(e);
return null;
}
}
private Object[] openLocalSite() {
final Object[][] bag = new Object[1][];
BusyIndicator.showWhile(getControl().getDisplay(), new Runnable() {
public void run() {
ILocalSite localSite = getLocalSite();
if (localSite == null)
return;
IInstallConfiguration config =
getLocalSite().getCurrentConfiguration();
IConfiguredSite[] sites = config.getConfiguredSites();
Object[] result = new Object[sites.length];
for (int i = 0; i < sites.length; i++) {
result[i] = new ConfiguredSiteAdapter(config, sites[i]);
}
if (!initialized) {
config.addInstallConfigurationChangedListener(
ConfigurationView.this);
initialized = true;
}
bag[0] = result;
}
});
return bag[0];
}
public void dispose() {
UpdateUI.getDefault().getLabelProvider().disconnect(this);
if (initialized) {
ILocalSite localSite = getLocalSite();
if (localSite != null) {
localSite.removeLocalSiteChangedListener(this);
IInstallConfiguration config =
localSite.getCurrentConfiguration();
config.removeInstallConfigurationChangedListener(this);
}
initialized = false;
}
OperationsManager.removeUpdateModelChangedListener(modelListener);
if (preview != null)
preview.dispose();
//super.dispose();
}
protected void makeActions() {
collapseAllAction = new Action() {
public void run() {
treeViewer.getControl().setRedraw(false);
treeViewer.collapseToLevel(
treeViewer.getInput(),
TreeViewer.ALL_LEVELS);
treeViewer.getControl().setRedraw(true);
}
};
collapseAllAction.setText(UpdateUI.getString("ConfigurationView.collapseLabel")); //$NON-NLS-1$
collapseAllAction.setToolTipText(UpdateUI.getString("ConfigurationView.collapseTooltip")); //$NON-NLS-1$
collapseAllAction.setImageDescriptor(UpdateUIImages.DESC_COLLAPSE_ALL);
drillDownAdapter = new DrillDownAdapter(treeViewer);
featureStateAction = new FeatureStateAction();
siteStateAction = new SiteStateAction();
revertAction = new RevertConfigurationAction(UpdateUI.getString("ConfigurationView.revertLabel")); //$NON-NLS-1$
WorkbenchHelp.setHelp(
revertAction,
"org.eclipse.update.ui.CofigurationView_revertAction"); //$NON-NLS-1$
installationHistoryAction =
new InstallationHistoryAction(
UpdateUI.getString("ConfigurationView.installHistory"), //$NON-NLS-1$
UpdateUIImages.DESC_HISTORY_OBJ);
installationHistoryAction.setToolTipText(installationHistoryAction.getText());
newExtensionLocationAction =
new NewExtensionLocationAction(
UpdateUI.getString("ConfigurationView.extLocation"), //$NON-NLS-1$
UpdateUIImages.DESC_ESITE_OBJ);
propertiesAction =
new PropertyDialogAction(
UpdateUI.getActiveWorkbenchShell(),
treeViewer);
WorkbenchHelp.setHelp(
propertiesAction,
"org.eclipse.update.ui.CofigurationView_propertiesAction"); //$NON-NLS-1$
uninstallFeatureAction = new UninstallFeatureAction(UpdateUI.getString("ConfigurationView.uninstall")); //$NON-NLS-1$
installOptFeatureAction =
new InstallOptionalFeatureAction(
getControl().getShell(),
UpdateUI.getString("ConfigurationView.install")); //$NON-NLS-1$
swapVersionAction = new ReplaceVersionAction(UpdateUI.getString("ConfigurationView.anotherVersion")); //$NON-NLS-1$
findUpdatesAction =
new FindUpdatesAction(getControl().getShell(), UpdateUI.getString("ConfigurationView.findUpdates")); //$NON-NLS-1$
showActivitiesAction = new ShowActivitiesAction(getControl().getShell(), UpdateUI.getString("ConfigurationView.showActivitiesLabel")); //$NON-NLS-1$
WorkbenchHelp.setHelp(
showActivitiesAction,
"org.eclipse.update.ui.CofigurationView_showActivitiesAction"); //$NON-NLS-1$
makeShowUnconfiguredFeaturesAction();
makeShowSitesAction();
makeShowNestedFeaturesAction();
makePreviewTasks();
configurationWindow.setPropertiesActionHandler(propertiesAction);
}
private void makeShowNestedFeaturesAction() {
final Preferences pref = UpdateUI.getDefault().getPluginPreferences();
pref.setDefault(STATE_SHOW_NESTED_FEATURES, true);
showNestedFeaturesAction = new Action() {
public void run() {
treeViewer.refresh();
pref.setValue(
STATE_SHOW_NESTED_FEATURES,
showNestedFeaturesAction.isChecked());
}
};
showNestedFeaturesAction.setText(UpdateUI.getString("ConfigurationView.showNestedFeatures")); //$NON-NLS-1$
showNestedFeaturesAction.setImageDescriptor(
UpdateUIImages.DESC_SHOW_HIERARCHY);
showNestedFeaturesAction.setDisabledImageDescriptor(
UpdateUIImages.DESC_SHOW_HIERARCHY_D);
showNestedFeaturesAction.setChecked(
pref.getBoolean(STATE_SHOW_NESTED_FEATURES));
showNestedFeaturesAction.setToolTipText(UpdateUI.getString("ConfigurationView.showNestedTooltip")); //$NON-NLS-1$
}
private void makeShowSitesAction() {
final Preferences pref = UpdateUI.getDefault().getPluginPreferences();
pref.setDefault(STATE_SHOW_SITES, true);
showSitesAction = new Action() {
public void run() {
treeViewer.refresh();
pref.setValue(STATE_SHOW_SITES, showSitesAction.isChecked());
UpdateUI.getDefault().savePluginPreferences();
}
};
showSitesAction.setText(UpdateUI.getString("ConfigurationView.showInstall")); //$NON-NLS-1$
showSitesAction.setImageDescriptor(UpdateUIImages.DESC_LSITE_OBJ);
showSitesAction.setChecked(pref.getBoolean(STATE_SHOW_SITES));
showSitesAction.setToolTipText(UpdateUI.getString("ConfigurationView.showInstallTooltip")); //$NON-NLS-1$
}
private void makeShowUnconfiguredFeaturesAction() {
final Preferences pref = UpdateUI.getDefault().getPluginPreferences();
pref.setDefault(STATE_SHOW_UNCONF, false);
showUnconfFeaturesAction = new Action() {
public void run() {
pref.setValue(
STATE_SHOW_UNCONF,
showUnconfFeaturesAction.isChecked());
UpdateUI.getDefault().savePluginPreferences();
treeViewer.refresh();
}
};
WorkbenchHelp.setHelp(
showUnconfFeaturesAction,
"org.eclipse.update.ui.CofigurationView_showUnconfFeaturesAction"); //$NON-NLS-1$
showUnconfFeaturesAction.setText(UpdateUI.getString("ConfigurationView.showDisabled")); //$NON-NLS-1$
showUnconfFeaturesAction.setImageDescriptor(
UpdateUIImages.DESC_UNCONF_FEATURE_OBJ);
showUnconfFeaturesAction.setChecked(pref.getBoolean(STATE_SHOW_UNCONF));
showUnconfFeaturesAction.setToolTipText(UpdateUI.getString("ConfigurationView.showDisabledTooltip")); //$NON-NLS-1$
}
protected void fillActionBars(ToolBarManager tbm) {
tbm.add(showSitesAction);
tbm.add(showNestedFeaturesAction);
tbm.add(showUnconfFeaturesAction);
tbm.add(new Separator());
drillDownAdapter.addNavigationActions(tbm);
tbm.add(new Separator());
tbm.add(collapseAllAction);
tbm.add(new Separator());
tbm.add(installationHistoryAction);
}
protected Object getSelectedObject() {
ISelection selection = treeViewer.getSelection();
if (selection instanceof IStructuredSelection
&& !selection.isEmpty()) {
IStructuredSelection ssel = (IStructuredSelection) selection;
if (ssel.size() == 1)
return ssel.getFirstElement();
}
return null;
}
protected void fillContextMenu(IMenuManager manager) {
Object obj = getSelectedObject();
if (obj instanceof ILocalSite) {
manager.add(revertAction);
manager.add(findUpdatesAction);
} else if (obj instanceof IConfiguredSiteAdapter) {
manager.add(siteStateAction);
}
if (obj instanceof ILocalSite
|| obj instanceof IConfiguredSiteAdapter) {
manager.add(new Separator());
MenuManager mgr = new MenuManager(UpdateUI.getString("ConfigurationView.new")); //$NON-NLS-1$
mgr.add(newExtensionLocationAction);
manager.add(mgr);
manager.add(new Separator());
} else if (obj instanceof ConfiguredFeatureAdapter) {
try {
MenuManager mgr = new MenuManager(UpdateUI.getString("ConfigurationView.replaceWith")); //$NON-NLS-1$
mgr.add(swapVersionAction);
manager.add(mgr);
manager.add(featureStateAction);
IFeature feature =
((ConfiguredFeatureAdapter) obj).getFeature(null);
if (feature instanceof MissingFeature) {
manager.add(installOptFeatureAction);
} else {
manager.add(uninstallFeatureAction);
}
manager.add(new Separator());
manager.add(findUpdatesAction);
manager.add(new Separator());
} catch (CoreException e) {
}
}
drillDownAdapter.addNavigationActions(manager);
if (obj instanceof ILocalSite) {
manager.add(new Separator());
manager.add(installationHistoryAction);
}
if (obj instanceof IFeatureAdapter
|| obj instanceof ILocalSite
|| obj instanceof IConfiguredSiteAdapter) {
manager.add(new Separator());
manager.add(propertiesAction);
}
}
public void installSiteAdded(IConfiguredSite csite) {
asyncRefresh();
}
public void installSiteRemoved(IConfiguredSite site) {
asyncRefresh();
}
public void featureInstalled(IFeature feature) {
asyncRefresh();
}
public void featureRemoved(IFeature feature) {
asyncRefresh();
}
public void featureConfigured(IFeature feature) {
}
public void featureUnconfigured(IFeature feature) {
}
public void currentInstallConfigurationChanged(IInstallConfiguration configuration) {
asyncRefresh();
}
public void installConfigurationRemoved(IInstallConfiguration configuration) {
asyncRefresh();
}
private void asyncRefresh() {
Display display = SWTUtil.getStandardDisplay();
if (display == null)
return;
if (getControl().isDisposed())
return;
display.asyncExec(new Runnable() {
public void run() {
if (!getControl().isDisposed())
treeViewer.refresh();
}
});
}
private Object[] getFeatures(
final IConfiguredSiteAdapter siteAdapter,
final boolean configuredOnly) {
final IConfiguredSite csite = siteAdapter.getConfiguredSite();
final Object[][] bag = new Object[1][];
refreshLock = true;
IRunnableWithProgress op = new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) {
ArrayList result = new ArrayList();
IFeatureReference[] refs;
if (configuredOnly)
refs = csite.getConfiguredFeatures();
else {
ISite site = csite.getSite();
refs = site.getFeatureReferences();
}
monitor.beginTask(
UpdateUI.getString("ConfigurationView.loading"), //$NON-NLS-1$
refs.length);
for (int i = 0; i < refs.length; i++) {
IFeatureReference ref = refs[i];
IFeature feature;
try {
monitor.subTask(ref.getURL().toString());
feature = ref.getFeature(null);
} catch (CoreException e) {
feature =
new MissingFeature(ref.getSite(), ref.getURL());
}
monitor.worked(1);
result.add(
new ConfiguredFeatureAdapter(
siteAdapter,
feature,
csite.isConfigured(feature),
false,
false));
}
monitor.done();
bag[0] = getRootFeatures(result);
}
};
try {
if (configurationWindow.getShell().isVisible())
configurationWindow.run(true, false, op);
else
op.run(new NullProgressMonitor());
} catch (InterruptedException e) {
} catch (InvocationTargetException e) {
} finally {
refreshLock = false;
}
return bag[0];
}
private Object[] getRootFeatures(ArrayList list) {
ArrayList children = new ArrayList();
ArrayList result = new ArrayList();
try {
for (int i = 0; i < list.size(); i++) {
ConfiguredFeatureAdapter cf =
(ConfiguredFeatureAdapter) list.get(i);
IFeature feature = cf.getFeature(null);
if (feature != null)
addChildFeatures(
feature,
children,
cf.isConfigured());
}
for (int i = 0; i < list.size(); i++) {
ConfiguredFeatureAdapter cf =
(ConfiguredFeatureAdapter) list.get(i);
IFeature feature = cf.getFeature(null);
if (feature != null
&& isChildFeature(feature, children) == false)
result.add(cf);
}
} catch (CoreException e) {
return list.toArray();
}
return result.toArray();
}
private void addChildFeatures(
IFeature feature,
ArrayList children,
boolean configured) {
try {
IIncludedFeatureReference[] included =
feature.getIncludedFeatureReferences();
for (int i = 0; i < included.length; i++) {
IFeature childFeature;
try {
childFeature =
included[i].getFeature(null);
} catch (CoreException e) {
childFeature = new MissingFeature(included[i]);
}
children.add(childFeature);
}
} catch (CoreException e) {
UpdateUI.logException(e);
}
}
private boolean isChildFeature(IFeature feature, ArrayList children) {
for (int i = 0; i < children.size(); i++) {
IFeature child = (IFeature) children.get(i);
if (feature
.getVersionedIdentifier()
.equals(child.getVersionedIdentifier()))
return true;
}
return false;
}
protected void handleDoubleClick(DoubleClickEvent e) {
if (e.getSelection() instanceof IStructuredSelection) {
IStructuredSelection ssel = (IStructuredSelection) e.getSelection();
Object obj = ssel.getFirstElement();
if (obj!=null)
propertiesAction.run();
}
}
public void createPartControl(Composite parent) {
splitter = new SashForm(parent, SWT.HORIZONTAL);
splitter.setLayoutData(new GridData(GridData.FILL_BOTH));
Composite leftContainer = createLineContainer(splitter);
Composite rightContainer = createLineContainer(splitter);
createTreeViewer(leftContainer);
makeActions();
createVerticalLine(leftContainer);
createVerticalLine(rightContainer);
preview = new ConfigurationPreview(this);
preview.createControl(rightContainer);
preview.getControl().setLayoutData(
new GridData(GridData.FILL_BOTH));
splitter.setWeights(new int[] { 2, 3 });
fillActionBars(getConfigurationWindow().getToolBarManager());
treeViewer.expandToLevel(2);
}
private void createTreeViewer(Composite parent) {
treeViewer =
new TreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
treeViewer.getControl().setLayoutData(new GridData(GridData.FILL_BOTH));
treeViewer.setUseHashlookup(true);
initProviders();
MenuManager menuMgr = new MenuManager("#PopupMenu"); //$NON-NLS-1$
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(new IMenuListener() {
public void menuAboutToShow(IMenuManager manager) {
manager.add(new GroupMarker("additions")); //$NON-NLS-1$
fillContextMenu(manager);
}
});
treeViewer.getControl().setMenu(
menuMgr.createContextMenu(treeViewer.getControl()));
treeViewer
.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
handleSelectionChanged(event);
}
});
treeViewer.addDoubleClickListener(new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent event) {
handleDoubleClick(event);
}
});
}
public TreeViewer getTreeViewer() {
return treeViewer;
}
private Composite createLineContainer(Composite parent) {
Composite container = new Composite(parent, SWT.NULL);
GridLayout layout = new GridLayout();
layout.numColumns = 2;
layout.marginWidth = layout.marginHeight = 0;
layout.horizontalSpacing = 0;
container.setLayout(layout);
return container;
}
private void createVerticalLine(Composite parent) {
Label line = new Label(parent, SWT.SEPARATOR | SWT.VERTICAL);
GridData gd = new GridData(GridData.VERTICAL_ALIGN_FILL);
gd.widthHint = 1;
line.setLayoutData(gd);
}
public Control getControl() {
return splitter;
}
private int getStatusCode(IFeature feature, IStatus status) {
int code = status.getCode();
if (code == IFeature.STATUS_UNHAPPY) {
if (status.isMultiStatus()) {
IStatus[] children = status.getChildren();
for (int i = 0; i < children.length; i++) {
IStatus child = children[i];
if (child.isMultiStatus()
|| child.getCode() != IFeature.STATUS_DISABLED)
return code;
}
// If we are here, global status is unhappy
// because one or more included features
// is disabled.
if (UpdateUtils.hasObsoletePatches(feature)) {
// The disabled included features
// are old patches that are now
// subsumed by better versions of
// the features they were designed to
// patch.
return IFeature.STATUS_HAPPY;
}
}
}
return code;
}
protected void handleSelectionChanged(IStructuredSelection ssel) {
Object obj = ssel.getFirstElement();
if (obj instanceof IFeatureAdapter) {
try {
propertiesAction.setEnabled(true);
ConfiguredFeatureAdapter adapter = (ConfiguredFeatureAdapter) obj;
IFeature feature = adapter.getFeature(null);
boolean missing = feature instanceof MissingFeature;
boolean enable = !missing && ((adapter.isOptional() || !adapter.isIncluded()));
featureStateAction.setFeature(adapter);
featureStateAction.setEnabled(enable);
uninstallFeatureAction.setFeature(adapter);
uninstallFeatureAction.setEnabled(enable && uninstallFeatureAction.canUninstall());
if (adapter.isConfigured())
setDescriptionOnTask(uninstallFeatureAction, adapter,UpdateUI.getString("ConfigurationView.uninstallDesc2"));
else
setDescriptionOnTask(uninstallFeatureAction, adapter,UpdateUI.getString("ConfigurationView.uninstallDesc"));
if (enable && adapter.isConfigured()) {
IFeature[] features = UpdateUtils.getInstalledFeatures(feature, false);
swapVersionAction.setEnabled(features.length > 1);
if (features.length > 1) {
swapVersionAction.setCurrentFeature(feature);
swapVersionAction.setFeatures(features);
}
findUpdatesAction.setEnabled(true);
findUpdatesAction.setFeature(feature);
} else {
swapVersionAction.setEnabled(false);
findUpdatesAction.setEnabled(false);
}
if (missing) {
MissingFeature mf = (MissingFeature) feature;
installOptFeatureAction.setEnabled(
mf.isOptional() && mf.getOriginatingSiteURL() != null);
installOptFeatureAction.setFeature(mf);
} else {
installOptFeatureAction.setEnabled(false);
}
} catch (CoreException ex) {
UpdateUI.logException(ex);
}
}
if (obj instanceof ILocalSite) {
propertiesAction.setEnabled(true);
findUpdatesAction.setEnabled(true);
findUpdatesAction.setFeature(null);
ILocalSite site = getLocalSite();
revertAction.setEnabled(site != null && site.getConfigurationHistory().length > 1);
} else if (obj instanceof IConfiguredSiteAdapter) {
siteStateAction.setSite(
((IConfiguredSiteAdapter) obj).getConfiguredSite());
siteStateAction.setEnabled(true);
}
preview.setSelection(ssel);
}
protected void handleSelectionChanged(SelectionChangedEvent e) {
handleSelectionChanged(((IStructuredSelection) e.getSelection()));
}
private void setDescriptionOnTask(IAction action, ConfiguredFeatureAdapter adapter, String desc) {
IPreviewTask[] tasks = getPreviewTasks(adapter);
if (tasks == null)
return;
for (int i=0; i<tasks.length; i++)
if (tasks[i].getAction() == action)
tasks[i].setDescription(desc);
}
private void makePreviewTasks() {
previewTasks = new Hashtable();
Class key;
ArrayList array = new ArrayList();
// local site tasks
key = ILocalSite.class;
array.add(
new PreviewTask(
- UpdateUI.getString("ConfigurationView.revertPreviousLabel"), //$NON-NLS-1$
- UpdateUI.getString("ConfigurationView.revertPreviousDesc"), //$NON-NLS-1$
- revertAction));
- array.add(
- new PreviewTask(
UpdateUI.getString("ConfigurationView.updateLabel"), //$NON-NLS-1$
UpdateUI.getString("ConfigurationView.updateDesc"), //$NON-NLS-1$
findUpdatesAction));
array.add(
new PreviewTask(
- UpdateUI.getString("ConfigurationView.extLocLabel"), //$NON-NLS-1$
- UpdateUI.getString("ConfigurationView.extLocDesc"), //$NON-NLS-1$
- newExtensionLocationAction));
- array.add(
- new PreviewTask(
UpdateUI.getString("ConfigurationView.installHistLabel"), //$NON-NLS-1$
UpdateUI.getString("ConfigurationView.installHistDesc"), //$NON-NLS-1$
installationHistoryAction));
array.add(
new PreviewTask(
UpdateUI.getString("ConfigurationView.activitiesLabel"), //$NON-NLS-1$
UpdateUI.getString("ConfigurationView.activitiesDesc"), //$NON-NLS-1$
showActivitiesAction));
+ array.add(
+ new PreviewTask(
+ UpdateUI.getString("ConfigurationView.extLocLabel"), //$NON-NLS-1$
+ UpdateUI.getString("ConfigurationView.extLocDesc"), //$NON-NLS-1$
+ newExtensionLocationAction));
+ array.add(
+ new PreviewTask(
+ UpdateUI.getString("ConfigurationView.revertPreviousLabel"), //$NON-NLS-1$
+ UpdateUI.getString("ConfigurationView.revertPreviousDesc"), //$NON-NLS-1$
+ revertAction));
previewTasks.put(key, array.toArray(new IPreviewTask[array.size()]));
// configured site tasks
array.clear();
key = IConfiguredSiteAdapter.class;
array.add(
new PreviewTask(
null,
UpdateUI.getString("ConfigurationView.enableLocDesc"), //$NON-NLS-1$
siteStateAction));
array.add(
new PreviewTask(
UpdateUI.getString("ConfigurationView.extLocLabel"), //$NON-NLS-1$
UpdateUI.getString("ConfigurationView.extLocDesc"), //$NON-NLS-1$
newExtensionLocationAction));
array.add(
new PreviewTask(
UpdateUI.getString("ConfigurationView.propertiesLabel"), //$NON-NLS-1$
UpdateUI.getString("ConfigurationView.installPropDesc"), //$NON-NLS-1$
propertiesAction));
previewTasks.put(key, array.toArray(new IPreviewTask[array.size()]));
// feature adapter tasks
array.clear();
key = IFeatureAdapter.class;
array.add(
+ new PreviewTask(
+ UpdateUI.getString("ConfigurationView.scanLabel"), //$NON-NLS-1$
+ UpdateUI.getString("ConfigurationView.scanDesc"), //$NON-NLS-1$
+ findUpdatesAction));
+ array.add(
new PreviewTask(
UpdateUI.getString("ConfigurationView.replaceVersionLabel"), //$NON-NLS-1$
UpdateUI.getString("ConfigurationView.replaceVersionDesc"), //$NON-NLS-1$
swapVersionAction));
array.add(
new PreviewTask(
null,
UpdateUI.getString("ConfigurationView.enableFeatureDesc"), //$NON-NLS-1$
featureStateAction));
array.add(
new PreviewTask(
UpdateUI.getString("ConfigurationView.installOptionalLabel"), //$NON-NLS-1$
UpdateUI.getString("ConfigurationView.installOptionalDesc"), //$NON-NLS-1$
installOptFeatureAction));
array.add(
new PreviewTask(
UpdateUI.getString("ConfigurationView.uninstallLabel"), //$NON-NLS-1$
UpdateUI.getString("ConfigurationView.uninstallDesc"), //$NON-NLS-1$
uninstallFeatureAction));
array.add(
new PreviewTask(
- UpdateUI.getString("ConfigurationView.scanLabel"), //$NON-NLS-1$
- UpdateUI.getString("ConfigurationView.scanDesc"), //$NON-NLS-1$
- findUpdatesAction));
- array.add(
- new PreviewTask(
UpdateUI.getString("ConfigurationView.featurePropLabel"), //$NON-NLS-1$
UpdateUI.getString("ConfigurationView.featurePropDesc"), //$NON-NLS-1$
propertiesAction));
previewTasks.put(key, array.toArray(new IPreviewTask[array.size()]));
}
public IPreviewTask[] getPreviewTasks(Object object) {
IPreviewTask[] tasks = null;
if (object instanceof IFeatureAdapter)
tasks = (IPreviewTask[]) previewTasks.get(IFeatureAdapter.class);
if (object instanceof ILocalSite)
tasks = (IPreviewTask[]) previewTasks.get(ILocalSite.class);
if (object instanceof IConfiguredSiteAdapter)
tasks =
(IPreviewTask[]) previewTasks.get(IConfiguredSiteAdapter.class);
return (tasks != null) ? tasks : new IPreviewTask[0];
}
ConfigurationManagerWindow getConfigurationWindow(){
return configurationWindow;
}
}
| false | true | private void makePreviewTasks() {
previewTasks = new Hashtable();
Class key;
ArrayList array = new ArrayList();
// local site tasks
key = ILocalSite.class;
array.add(
new PreviewTask(
UpdateUI.getString("ConfigurationView.revertPreviousLabel"), //$NON-NLS-1$
UpdateUI.getString("ConfigurationView.revertPreviousDesc"), //$NON-NLS-1$
revertAction));
array.add(
new PreviewTask(
UpdateUI.getString("ConfigurationView.updateLabel"), //$NON-NLS-1$
UpdateUI.getString("ConfigurationView.updateDesc"), //$NON-NLS-1$
findUpdatesAction));
array.add(
new PreviewTask(
UpdateUI.getString("ConfigurationView.extLocLabel"), //$NON-NLS-1$
UpdateUI.getString("ConfigurationView.extLocDesc"), //$NON-NLS-1$
newExtensionLocationAction));
array.add(
new PreviewTask(
UpdateUI.getString("ConfigurationView.installHistLabel"), //$NON-NLS-1$
UpdateUI.getString("ConfigurationView.installHistDesc"), //$NON-NLS-1$
installationHistoryAction));
array.add(
new PreviewTask(
UpdateUI.getString("ConfigurationView.activitiesLabel"), //$NON-NLS-1$
UpdateUI.getString("ConfigurationView.activitiesDesc"), //$NON-NLS-1$
showActivitiesAction));
previewTasks.put(key, array.toArray(new IPreviewTask[array.size()]));
// configured site tasks
array.clear();
key = IConfiguredSiteAdapter.class;
array.add(
new PreviewTask(
null,
UpdateUI.getString("ConfigurationView.enableLocDesc"), //$NON-NLS-1$
siteStateAction));
array.add(
new PreviewTask(
UpdateUI.getString("ConfigurationView.extLocLabel"), //$NON-NLS-1$
UpdateUI.getString("ConfigurationView.extLocDesc"), //$NON-NLS-1$
newExtensionLocationAction));
array.add(
new PreviewTask(
UpdateUI.getString("ConfigurationView.propertiesLabel"), //$NON-NLS-1$
UpdateUI.getString("ConfigurationView.installPropDesc"), //$NON-NLS-1$
propertiesAction));
previewTasks.put(key, array.toArray(new IPreviewTask[array.size()]));
// feature adapter tasks
array.clear();
key = IFeatureAdapter.class;
array.add(
new PreviewTask(
UpdateUI.getString("ConfigurationView.replaceVersionLabel"), //$NON-NLS-1$
UpdateUI.getString("ConfigurationView.replaceVersionDesc"), //$NON-NLS-1$
swapVersionAction));
array.add(
new PreviewTask(
null,
UpdateUI.getString("ConfigurationView.enableFeatureDesc"), //$NON-NLS-1$
featureStateAction));
array.add(
new PreviewTask(
UpdateUI.getString("ConfigurationView.installOptionalLabel"), //$NON-NLS-1$
UpdateUI.getString("ConfigurationView.installOptionalDesc"), //$NON-NLS-1$
installOptFeatureAction));
array.add(
new PreviewTask(
UpdateUI.getString("ConfigurationView.uninstallLabel"), //$NON-NLS-1$
UpdateUI.getString("ConfigurationView.uninstallDesc"), //$NON-NLS-1$
uninstallFeatureAction));
array.add(
new PreviewTask(
UpdateUI.getString("ConfigurationView.scanLabel"), //$NON-NLS-1$
UpdateUI.getString("ConfigurationView.scanDesc"), //$NON-NLS-1$
findUpdatesAction));
array.add(
new PreviewTask(
UpdateUI.getString("ConfigurationView.featurePropLabel"), //$NON-NLS-1$
UpdateUI.getString("ConfigurationView.featurePropDesc"), //$NON-NLS-1$
propertiesAction));
previewTasks.put(key, array.toArray(new IPreviewTask[array.size()]));
}
| private void makePreviewTasks() {
previewTasks = new Hashtable();
Class key;
ArrayList array = new ArrayList();
// local site tasks
key = ILocalSite.class;
array.add(
new PreviewTask(
UpdateUI.getString("ConfigurationView.updateLabel"), //$NON-NLS-1$
UpdateUI.getString("ConfigurationView.updateDesc"), //$NON-NLS-1$
findUpdatesAction));
array.add(
new PreviewTask(
UpdateUI.getString("ConfigurationView.installHistLabel"), //$NON-NLS-1$
UpdateUI.getString("ConfigurationView.installHistDesc"), //$NON-NLS-1$
installationHistoryAction));
array.add(
new PreviewTask(
UpdateUI.getString("ConfigurationView.activitiesLabel"), //$NON-NLS-1$
UpdateUI.getString("ConfigurationView.activitiesDesc"), //$NON-NLS-1$
showActivitiesAction));
array.add(
new PreviewTask(
UpdateUI.getString("ConfigurationView.extLocLabel"), //$NON-NLS-1$
UpdateUI.getString("ConfigurationView.extLocDesc"), //$NON-NLS-1$
newExtensionLocationAction));
array.add(
new PreviewTask(
UpdateUI.getString("ConfigurationView.revertPreviousLabel"), //$NON-NLS-1$
UpdateUI.getString("ConfigurationView.revertPreviousDesc"), //$NON-NLS-1$
revertAction));
previewTasks.put(key, array.toArray(new IPreviewTask[array.size()]));
// configured site tasks
array.clear();
key = IConfiguredSiteAdapter.class;
array.add(
new PreviewTask(
null,
UpdateUI.getString("ConfigurationView.enableLocDesc"), //$NON-NLS-1$
siteStateAction));
array.add(
new PreviewTask(
UpdateUI.getString("ConfigurationView.extLocLabel"), //$NON-NLS-1$
UpdateUI.getString("ConfigurationView.extLocDesc"), //$NON-NLS-1$
newExtensionLocationAction));
array.add(
new PreviewTask(
UpdateUI.getString("ConfigurationView.propertiesLabel"), //$NON-NLS-1$
UpdateUI.getString("ConfigurationView.installPropDesc"), //$NON-NLS-1$
propertiesAction));
previewTasks.put(key, array.toArray(new IPreviewTask[array.size()]));
// feature adapter tasks
array.clear();
key = IFeatureAdapter.class;
array.add(
new PreviewTask(
UpdateUI.getString("ConfigurationView.scanLabel"), //$NON-NLS-1$
UpdateUI.getString("ConfigurationView.scanDesc"), //$NON-NLS-1$
findUpdatesAction));
array.add(
new PreviewTask(
UpdateUI.getString("ConfigurationView.replaceVersionLabel"), //$NON-NLS-1$
UpdateUI.getString("ConfigurationView.replaceVersionDesc"), //$NON-NLS-1$
swapVersionAction));
array.add(
new PreviewTask(
null,
UpdateUI.getString("ConfigurationView.enableFeatureDesc"), //$NON-NLS-1$
featureStateAction));
array.add(
new PreviewTask(
UpdateUI.getString("ConfigurationView.installOptionalLabel"), //$NON-NLS-1$
UpdateUI.getString("ConfigurationView.installOptionalDesc"), //$NON-NLS-1$
installOptFeatureAction));
array.add(
new PreviewTask(
UpdateUI.getString("ConfigurationView.uninstallLabel"), //$NON-NLS-1$
UpdateUI.getString("ConfigurationView.uninstallDesc"), //$NON-NLS-1$
uninstallFeatureAction));
array.add(
new PreviewTask(
UpdateUI.getString("ConfigurationView.featurePropLabel"), //$NON-NLS-1$
UpdateUI.getString("ConfigurationView.featurePropDesc"), //$NON-NLS-1$
propertiesAction));
previewTasks.put(key, array.toArray(new IPreviewTask[array.size()]));
}
|
diff --git a/src/main/java/uk/ac/prospects/w4/webapp/UrlBuilder.java b/src/main/java/uk/ac/prospects/w4/webapp/UrlBuilder.java
index 99192d5..d3d0f82 100644
--- a/src/main/java/uk/ac/prospects/w4/webapp/UrlBuilder.java
+++ b/src/main/java/uk/ac/prospects/w4/webapp/UrlBuilder.java
@@ -1,132 +1,134 @@
package uk.ac.prospects.w4.webapp;
import org.springframework.util.StringUtils;
/**
* Constructs the string containing the parameters that need to be preserved accross the widget
*/
public class UrlBuilder {
/**
* Builds the parameter string for the links to calendar page from other pages
*
* @param provId
* @param provTitle
* @param keyword
* @param fromStartDate
* @param toStartDate
* @param courseTitle
* @return The parameter string that needs to be preserved when going to the calendar page from any other page.
*/
public static String buildCalendarURL(String provId, String provTitle, String keyword, String fromStartDate, String toStartDate, String courseTitle){
StringBuilder sb = buildBasicURL(provId, provTitle, keyword, courseTitle);
StringBuilder calendarSb = new StringBuilder();
if (StringUtils.hasText(fromStartDate) || StringUtils.hasText(toStartDate) || StringUtils.hasText(courseTitle)) {
//calendarSb.append("preserve=");
if (StringUtils.hasText(fromStartDate)){
calendarSb.append("fromStartDate:" + fromStartDate);
}
if (StringUtils.hasText(toStartDate)){
if (calendarSb.length() > 0)
calendarSb.append(",");
calendarSb.append("toStartDate:" + toStartDate);
}
}
if ((sb.length() > 0) && (calendarSb.length() > 0)){
sb.append("&");
+ }
+ if (calendarSb.length() > 0) {
sb.append("preserve=");
sb.append(calendarSb);
}
return sb.toString();
}
/**
* Builds the parameter string to all pages apart from calendar
*
* @param provId
* @param provTitle
* @param keyword
* @param fromStartDate
* @param toStartDate
* @param courseTitle
* @return The parameter string that needs to be preserved when going to any page in the widget apart from calendar
*/
public static String buildGeneralURL(String provId, String provTitle, String keyword, String fromStartDate, String toStartDate, String courseTitle){
StringBuilder sb = buildBasicURL(provId, provTitle, keyword, courseTitle);
if (StringUtils.hasText(fromStartDate)){
if (sb.length() > 0)
sb.append("&");
sb.append("fromStartDate=" + fromStartDate);
}
if (StringUtils.hasText(toStartDate)){
if (sb.length() > 0)
sb.append("&");
sb.append("toStartDate=" + toStartDate);
}
return sb.toString();
}
public static String buildCalendarURLForCalendarPage(String provId, String provTitle, String keyword, String courseTitle, String preserve){
StringBuilder sb = new StringBuilder(buildBasicURL(provId, provTitle, keyword, courseTitle));
if (StringUtils.hasText(preserve)){
if (sb.length() > 0)
sb.append("&");
sb.append("preserve=" + preserve);
}
return sb.toString();
}
public static String buildGeneralURLForCalendarPage(String provId, String provTitle, String keyword, String courseTitle, String preserve){
StringBuilder sb = new StringBuilder(buildBasicURL(provId, provTitle, keyword, courseTitle));
if (StringUtils.hasText(preserve)){
StringBuilder calendarSb = new StringBuilder();
String[] parameterPairs = preserve.split(",");
for (String pair : parameterPairs){
if (calendarSb.length() > 0){
calendarSb.append("&");
}
calendarSb.append(pair.split(":")[0]);
calendarSb.append("=");
calendarSb.append(pair.split(":")[1]);
}
if (sb.length() > 0){
sb.append("&");
}
sb.append(calendarSb);
}
return sb.toString();
}
private static StringBuilder buildBasicURL(String provId, String provTitle, String keyword, String courseTitle) {
StringBuilder sb = new StringBuilder();
if (StringUtils.hasText(provId)){
sb.append("provid=" + provId);
}
if (StringUtils.hasText(provTitle)){
if (sb.length() > 0)
sb.append("&");
sb.append("provTitle=" + provTitle);
}
if (StringUtils.hasText(keyword)){
if (sb.length() > 0)
sb.append("&");
sb.append("keyword=" + keyword);
}
if (StringUtils.hasText(courseTitle)){
if (sb.length() > 0)
sb.append("&");
sb.append("courseTitle=" + courseTitle);
}
return sb;
}
}
| true | true | public static String buildCalendarURL(String provId, String provTitle, String keyword, String fromStartDate, String toStartDate, String courseTitle){
StringBuilder sb = buildBasicURL(provId, provTitle, keyword, courseTitle);
StringBuilder calendarSb = new StringBuilder();
if (StringUtils.hasText(fromStartDate) || StringUtils.hasText(toStartDate) || StringUtils.hasText(courseTitle)) {
//calendarSb.append("preserve=");
if (StringUtils.hasText(fromStartDate)){
calendarSb.append("fromStartDate:" + fromStartDate);
}
if (StringUtils.hasText(toStartDate)){
if (calendarSb.length() > 0)
calendarSb.append(",");
calendarSb.append("toStartDate:" + toStartDate);
}
}
if ((sb.length() > 0) && (calendarSb.length() > 0)){
sb.append("&");
sb.append("preserve=");
sb.append(calendarSb);
}
return sb.toString();
}
| public static String buildCalendarURL(String provId, String provTitle, String keyword, String fromStartDate, String toStartDate, String courseTitle){
StringBuilder sb = buildBasicURL(provId, provTitle, keyword, courseTitle);
StringBuilder calendarSb = new StringBuilder();
if (StringUtils.hasText(fromStartDate) || StringUtils.hasText(toStartDate) || StringUtils.hasText(courseTitle)) {
//calendarSb.append("preserve=");
if (StringUtils.hasText(fromStartDate)){
calendarSb.append("fromStartDate:" + fromStartDate);
}
if (StringUtils.hasText(toStartDate)){
if (calendarSb.length() > 0)
calendarSb.append(",");
calendarSb.append("toStartDate:" + toStartDate);
}
}
if ((sb.length() > 0) && (calendarSb.length() > 0)){
sb.append("&");
}
if (calendarSb.length() > 0) {
sb.append("preserve=");
sb.append(calendarSb);
}
return sb.toString();
}
|
diff --git a/core-api/src/main/java/no/schibstedsok/searchportal/run/QueryFactoryImpl.java b/core-api/src/main/java/no/schibstedsok/searchportal/run/QueryFactoryImpl.java
index abcd7ed30..6326487c8 100644
--- a/core-api/src/main/java/no/schibstedsok/searchportal/run/QueryFactoryImpl.java
+++ b/core-api/src/main/java/no/schibstedsok/searchportal/run/QueryFactoryImpl.java
@@ -1,112 +1,112 @@
// Copyright (2006-2007) Schibsted Søk AS
package no.schibstedsok.searchportal.run;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import no.schibstedsok.searchportal.datamodel.DataModel;
import no.schibstedsok.searchportal.datamodel.request.ParametersDataObject;
import no.schibstedsok.searchportal.site.SiteKeyedFactoryInstantiationException;
import org.apache.log4j.Logger;
/**
* QueryFactoryImpl is part of no.schibstedsok.searchportal.query.
* Use this class to create an instance of a RunningQuery.
*
* TODO Replace the code in createQuery with a RunningQueryTransformer sub-module that is
* configured per mode and permits manipulation of the datamodel before the RunningQuery is constructed.
*
* @author Ola Marius Sagli <a href="[email protected]">ola at schibstedsok</a>
* @version $Id$
*/
public final class QueryFactoryImpl extends QueryFactory {
private static final Logger LOG = Logger.getLogger(QueryFactoryImpl.class);
/**
* Create a new instance of running query. The implementation can
* be RunningWebQuery for example.
* <p/>
* <b>NewsSearch business rules:</b>
* <p/>
* Set default parameter userSortBy to "datetime" if query is empty
* Set contentsource to Norske Nyheter if query is empty and contentsource is null.
* (Kindof WEIRD business rules!!) It the query is not empty, then default is
* to search in all contentsource
*
* @param mode with SearchConfiguration passed to RunningQuery
* @param request with parameters populated with search params
* @return instance of RunningQuery
*/
public RunningQuery createQuery(
final RunningQuery.Context cxt,
final HttpServletRequest request,
final HttpServletResponse response) throws SiteKeyedFactoryInstantiationException {
final DataModel datamodel = (DataModel) request.getSession().getAttribute(DataModel.KEY);
final ParametersDataObject parametersDO = datamodel.getParameters();
final String tParam = null != parametersDO.getValue("t") ? parametersDO.getValue("t").getString() : "";
LOG.debug("createQuery() Type=" + tParam);
final RunningQueryImpl query;
if ("adv_urls".equals(tParam)) {
// Search for similar urls
final String qUrlsParam = null != parametersDO.getValue("q_urls")
? parametersDO.getValue("q_urls").getString()
: "";
final String q = "urls:" + qUrlsParam;
LOG.debug("Query modified to " + q);
query = new RunningWebQuery(cxt, q, request, response);
} else {
final String qParam = null != parametersDO.getValue("q") ? parametersDO.getValue("q").getString() : "";
query = new RunningWebQuery(cxt, qParam, request, response);
final String cParam = null != parametersDO.getValue("c") ? parametersDO.getValue("c").getString() : "";
if ("m".equals(cParam)) {
final String userSortByParam = null != parametersDO.getValue("userSortBy")
? parametersDO.getValue("userSortBy").getString()
: null;
if (null == userSortByParam || "".equals(qParam)) {
query.addParameter("userSortBy", "datetime");
}
final String contentsourceParam = null != parametersDO.getValue("contentsource")
? parametersDO.getValue("contentsource").getString()
: null;
final String newscountryParam = null != parametersDO.getValue("newscountry")
? parametersDO.getValue("newscountry").getString()
: "";
if ("".equals(qParam) && null == contentsourceParam && "".equals(newscountryParam)) {
query.addParameter("newscountry", "Norge");
}
- }else if ("t".equals(cParam)) {
- final Cookie cookies[] = request.getCookies();
+ } else if ("t".equals(cParam) || "wt".equals(cParam)) {
+ final Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if ("myChannels".equals(cookie.getName())){
query.addParameter("myChannels", cookie.getValue());
}
}
}
}
}
return query;
}
}
| true | true | public RunningQuery createQuery(
final RunningQuery.Context cxt,
final HttpServletRequest request,
final HttpServletResponse response) throws SiteKeyedFactoryInstantiationException {
final DataModel datamodel = (DataModel) request.getSession().getAttribute(DataModel.KEY);
final ParametersDataObject parametersDO = datamodel.getParameters();
final String tParam = null != parametersDO.getValue("t") ? parametersDO.getValue("t").getString() : "";
LOG.debug("createQuery() Type=" + tParam);
final RunningQueryImpl query;
if ("adv_urls".equals(tParam)) {
// Search for similar urls
final String qUrlsParam = null != parametersDO.getValue("q_urls")
? parametersDO.getValue("q_urls").getString()
: "";
final String q = "urls:" + qUrlsParam;
LOG.debug("Query modified to " + q);
query = new RunningWebQuery(cxt, q, request, response);
} else {
final String qParam = null != parametersDO.getValue("q") ? parametersDO.getValue("q").getString() : "";
query = new RunningWebQuery(cxt, qParam, request, response);
final String cParam = null != parametersDO.getValue("c") ? parametersDO.getValue("c").getString() : "";
if ("m".equals(cParam)) {
final String userSortByParam = null != parametersDO.getValue("userSortBy")
? parametersDO.getValue("userSortBy").getString()
: null;
if (null == userSortByParam || "".equals(qParam)) {
query.addParameter("userSortBy", "datetime");
}
final String contentsourceParam = null != parametersDO.getValue("contentsource")
? parametersDO.getValue("contentsource").getString()
: null;
final String newscountryParam = null != parametersDO.getValue("newscountry")
? parametersDO.getValue("newscountry").getString()
: "";
if ("".equals(qParam) && null == contentsourceParam && "".equals(newscountryParam)) {
query.addParameter("newscountry", "Norge");
}
}else if ("t".equals(cParam)) {
final Cookie cookies[] = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if ("myChannels".equals(cookie.getName())){
query.addParameter("myChannels", cookie.getValue());
}
}
}
}
}
return query;
}
| public RunningQuery createQuery(
final RunningQuery.Context cxt,
final HttpServletRequest request,
final HttpServletResponse response) throws SiteKeyedFactoryInstantiationException {
final DataModel datamodel = (DataModel) request.getSession().getAttribute(DataModel.KEY);
final ParametersDataObject parametersDO = datamodel.getParameters();
final String tParam = null != parametersDO.getValue("t") ? parametersDO.getValue("t").getString() : "";
LOG.debug("createQuery() Type=" + tParam);
final RunningQueryImpl query;
if ("adv_urls".equals(tParam)) {
// Search for similar urls
final String qUrlsParam = null != parametersDO.getValue("q_urls")
? parametersDO.getValue("q_urls").getString()
: "";
final String q = "urls:" + qUrlsParam;
LOG.debug("Query modified to " + q);
query = new RunningWebQuery(cxt, q, request, response);
} else {
final String qParam = null != parametersDO.getValue("q") ? parametersDO.getValue("q").getString() : "";
query = new RunningWebQuery(cxt, qParam, request, response);
final String cParam = null != parametersDO.getValue("c") ? parametersDO.getValue("c").getString() : "";
if ("m".equals(cParam)) {
final String userSortByParam = null != parametersDO.getValue("userSortBy")
? parametersDO.getValue("userSortBy").getString()
: null;
if (null == userSortByParam || "".equals(qParam)) {
query.addParameter("userSortBy", "datetime");
}
final String contentsourceParam = null != parametersDO.getValue("contentsource")
? parametersDO.getValue("contentsource").getString()
: null;
final String newscountryParam = null != parametersDO.getValue("newscountry")
? parametersDO.getValue("newscountry").getString()
: "";
if ("".equals(qParam) && null == contentsourceParam && "".equals(newscountryParam)) {
query.addParameter("newscountry", "Norge");
}
} else if ("t".equals(cParam) || "wt".equals(cParam)) {
final Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if ("myChannels".equals(cookie.getName())){
query.addParameter("myChannels", cookie.getValue());
}
}
}
}
}
return query;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.