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/srcj/com/sun/electric/tool/routing/InteractiveRouter.java b/srcj/com/sun/electric/tool/routing/InteractiveRouter.java
index f8f4c4be8..1a4eb5160 100644
--- a/srcj/com/sun/electric/tool/routing/InteractiveRouter.java
+++ b/srcj/com/sun/electric/tool/routing/InteractiveRouter.java
@@ -1,790 +1,791 @@
/* -*- tab-width: 4 -*-
*
* Electric(tm) VLSI Design System
*
* File: InteractiveRouter.java
*
* Copyright (c) 2003 Sun Microsystems and Static Free Software
*
* Electric(tm) 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.
*
* Electric(tm) 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 Electric(tm); see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, Mass 02111-1307, USA.
*/
package com.sun.electric.tool.routing;
import com.sun.electric.tool.user.ui.EditWindow;
import com.sun.electric.tool.user.Highlight;
import com.sun.electric.tool.user.User;
import com.sun.electric.tool.user.CircuitChanges;
import com.sun.electric.tool.user.Highlighter;
import com.sun.electric.tool.Job;
import com.sun.electric.database.geometry.Poly;
import com.sun.electric.database.hierarchy.Cell;
import com.sun.electric.database.hierarchy.Export;
import com.sun.electric.database.topology.ArcInst;
import com.sun.electric.database.topology.PortInst;
import com.sun.electric.database.topology.NodeInst;
import com.sun.electric.database.prototype.ArcProto;
import com.sun.electric.database.prototype.NodeProto;
import com.sun.electric.database.prototype.PortProto;
import com.sun.electric.database.geometry.Dimension2D;
import com.sun.electric.database.geometry.DBMath;
import com.sun.electric.database.variable.ElectricObject;
import com.sun.electric.technology.*;
import com.sun.electric.technology.technologies.Artwork;
import java.awt.geom.Point2D;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import java.util.List;
import java.util.Iterator;
import java.util.ArrayList;
/**
* An Interactive Router has several methods that build on Router
* methods to provide interactive control to user. It also
* provides methods for highlighting routes to provide visual
* feedback to the user. Finally, non-interactive routing is done only
* from PortInst to PortInst, whereas interactive routing can start and
* end on any arc, and can end in space.
* <p>
* Note: 'Interactive' is somewhat of a misnomer, as it would imply
* the route can be incremently built or changed by the user. In
* reality, it is expected that the route simply be rebuilt whenever
* the user input changes, until the user decides that the route is acceptable,
* at which point the route can be made.
* <p>
* User: gainsley
* Date: Feb 24, 2004
* Time: 4:58:24 PM
*/
public abstract class InteractiveRouter extends Router {
/** for highlighting the start of the route */ private List startRouteHighlights = new ArrayList();
/** if start has been called */ private boolean started;
/** EditWindow we are routing in */ private EditWindow wnd;
/** last bad object routed from: prevent too many error messages */ private ElectricObject badStartObject;
/** last bad object routing to: prevent too many error messages */ private ElectricObject badEndObject;
public InteractiveRouter() {
verbose = true;
started = false;
badStartObject = badEndObject = null;
wnd = null;
}
public String toString() { return "Interactive Router"; }
protected abstract boolean planRoute(Route route, Cell cell, RouteElementPort endRE,
Point2D startLoc, Point2D endLoc, Point2D clicked, VerticalRoute vroute,
boolean contactsOnEndObject);
// ----------------------- Interactive Route Control --------------------------
/**
* This stores the currently highlighted objects to highlight
* in addition to route highlighting. If routing it cancelled,
* it also restores the original highlighting.
*/
public void startInteractiveRoute(EditWindow wnd) {
this.wnd = wnd;
// copy current highlights
startRouteHighlights.clear();
for (Iterator it = wnd.getHighlighter().getHighlights().iterator(); it.hasNext(); ) {
Highlight h = (Highlight)it.next();
startRouteHighlights.add(h);
}
wnd.getHighlighter().clear();
started = true;
}
/**
* Cancels interative routing and restores original highlights
*/
public void cancelInteractiveRoute() {
// restore original highlights
Highlighter highlighter = wnd.getHighlighter();
highlighter.clear();
highlighter.setHighlightList(startRouteHighlights);
highlighter.finished();
wnd = null;
started = false;
}
/**
* Make a route between startObj and endObj in the EditWindow wnd.
* Uses the point where the user clicked as a parameter to set the route.
* @param wnd the EditWindow the user is editing
* @param cell the cell in which to create the route
* @param startObj a PortInst or ArcInst from which to start the route
* @param endObj a PortInst or ArcInst to end the route on. May be null
* if the user is drawing to empty space.
* @param clicked the point where the user clicked
*/
public void makeRoute(EditWindow wnd, Cell cell, ElectricObject startObj, ElectricObject endObj, Point2D clicked) {
if (!started) startInteractiveRoute(wnd);
// plan the route
Route route = planRoute(cell, startObj, endObj, clicked);
// restore highlights at start of planning, so that
// they will correctly show up if this job is undone.
wnd.getHighlighter().clear();
wnd.getHighlighter().setHighlightList(startRouteHighlights);
// create route
createRoute(route, cell);
started = false;
}
/**
* Make a vertical route. Will add in contacts in startPort's technology
* to be able to connect to endPort. The added contacts will be placed on
* top of startPort. The final contact will be able to connect to <i>arc</i>.
* @param wnd the EditWindow the user is editing
* @param startPort the start of the route
* @param arc the arc type that the last contact will be able to connect to
* @return true on sucess
*/
public boolean makeVerticalRoute(EditWindow wnd, PortInst startPort, ArcProto arc) {
// do nothing if startPort can already connect to arc
if (startPort.getPortProto().connectsTo(arc)) return true;
Cell cell = startPort.getNodeInst().getParent();
if (!started) startInteractiveRoute(wnd);
Point2D startLoc = new Point2D.Double(startPort.getPoly().getCenterX(), startPort.getPoly().getCenterY());
Poly poly = getConnectingSite(startPort, startLoc, -1);
RouteElementPort startRE = RouteElementPort.existingPortInst(startPort, poly);
Route route = new Route();
route.add(startRE); route.setStart(startRE);
//route.setEnd(startRE);
PrimitiveNode pn = ((PrimitiveArc)arc).findOverridablePinProto();
PortProto pp = pn.getPort(0);
VerticalRoute vroute = VerticalRoute.newRoute(startPort.getPortProto(), arc);
if (!vroute.isSpecificationSucceeded()) {
cancelInteractiveRoute();
return false;
}
vroute.buildRoute(route, startRE.getCell(), startRE, null, startLoc, startLoc, startLoc);
// restore highlights at start of planning, so that
// they will correctly show up if this job is undone.
wnd.getHighlighter().clear();
wnd.getHighlighter().setHighlightList(startRouteHighlights);
MakeVerticalRouteJob job = new MakeVerticalRouteJob(this, route, startPort.getNodeInst().getParent(), true);
started = false;
return true;
}
public static class MakeVerticalRouteJob extends Router.CreateRouteJob {
protected MakeVerticalRouteJob(Router router, Route route, Cell cell, boolean verbose) {
super(router, route, cell, false);
}
/** Implemented doIt() method to perform Job */
public boolean doIt() {
if (!super.doIt()) return false;
RouteElementPort startRE = route.getStart();
if (startRE.getAction() == RouteElement.RouteElementAction.existingPortInst) {
// if this is a pin, replace it with the first contact in vertical route
PortInst pi = startRE.getPortInst();
NodeInst ni = pi.getNodeInst();
if (ni.getProto().getFunction() == PrimitiveNode.Function.PIN) {
CircuitChanges.Reconnect re = CircuitChanges.Reconnect.erasePassThru(ni, false);
if (re != null) re.reconnectArcs();
ni.kill();
}
}
return true;
}
}
// -------------------------- Highlight Route Methods -------------------------
/**
* Make a route and highlight it in the window.
* @param cell the cell in which to create the route
* @param startObj a PortInst or ArcInst from which to start the route
* @param endObj a PortInst or ArcInst to end the route on. May be null
* if the user is drawing to empty space.
* @param clicked the point where the user clicked
*/
public void highlightRoute(EditWindow wnd, Cell cell, ElectricObject startObj, ElectricObject endObj, Point2D clicked) {
if (!started) startInteractiveRoute(wnd);
// highlight route
Route route = planRoute(cell, startObj, endObj, clicked);
highlightRoute(wnd, route, cell);
}
/**
* Highlight a route in the window
* @param route the route to be highlighted
*/
public void highlightRoute(EditWindow wnd, Route route, Cell cell) {
if (!started) startInteractiveRoute(wnd);
wnd.getHighlighter().clear();
//wnd.getHighlighter().setHighlightList(startRouteHighlights);
for (Iterator it = route.iterator(); it.hasNext(); ) {
RouteElement e = (RouteElement)it.next();
e.addHighlightArea(wnd.getHighlighter());
}
wnd.getHighlighter().finished();
}
// -------------------- Internal Router Wrapper of Router ---------------------
/**
* Plan a route from startObj to endObj, taking into account
* where the user clicked in the cell.
* @param cell the cell in which to create the arc
* @param startObj a PortInst or ArcInst from which to start the route
* @param endObj a PortInst or ArcInst to end the route on. May be null
* if the user is drawing to empty space.
* @param clicked the point where the user clicked
* @return a List of RouteElements denoting route
*/
protected Route planRoute(Cell cell, ElectricObject startObj, ElectricObject endObj, Point2D clicked) {
Route route = new Route(); // hold the route
if (cell == null) return route;
RouteElementPort startRE = null; // denote start of route
RouteElementPort endRE = null; // denote end of route
// first, convert NodeInsts to PortInsts, if it is one.
// Now we don't have to worry about NodeInsts.
startObj = filterRouteObject(startObj, clicked);
endObj = filterRouteObject(endObj, clicked);
// get the port types at each end so we can build electrical route
PortProto startPort = getRoutePort(startObj);
PortProto endPort;
if (endObj == null) {
// end object is null, we are routing to a pin. Figure out what arc to use
ArcProto useArc = getArcToUse(startPort, null);
+ if (useArc == null) return route;
PrimitiveNode pn = ((PrimitiveArc)useArc).findOverridablePinProto();
endPort = pn.getPort(0);
} else {
endPort = getRoutePort(endObj);
}
// now determine the electrical route. We need to know what
// arcs will be used (and their widths, eventually) to determine
// the Port Poly size for contacts
VerticalRoute vroute = VerticalRoute.newRoute(startPort, endPort);
if (!vroute.isSpecificationSucceeded()) return new Route();
// arc width of arcs that will connect to startObj, endObj will determine
// valid attachment points of arcs
ArcProto startArc = vroute.getStartArc();
ArcProto endArc = vroute.getEndArc();
double startArcWidth = getArcWidthToUse(startObj, startArc);
double endArcWidth = (endObj == null) ? startArcWidth : getArcWidthToUse(endObj, endArc);
// get valid connecting sites for start and end objects based on the objects
// themselves, the point the user clicked, and the width of the wire that will
// attach to each
Poly startPoly = getConnectingSite(startObj, clicked, startArcWidth);
Poly endPoly = getConnectingSite(endObj, clicked, endArcWidth);
//Poly startPoly = getConnectingSite(startObj, clicked, 3);
//Poly endPoly = getConnectingSite(endObj, clicked, 3);
// Now we can figure out where on the start and end objects the connecting
// arc(s) should connect
Point2D startPoint = new Point2D.Double(0, 0);
Point2D endPoint = new Point2D.Double(0,0);
getConnectingPoints(startObj, endObj, clicked, startPoint, endPoint, startPoly, endPoly, startArc, endArc);
PortInst existingStartPort = null;
PortInst existingEndPort = null;
// favor contact cuts on arcs
boolean contactsOnEndObject = true;
// plan start of route
if (startObj instanceof PortInst) {
// portinst: just wrap in RouteElement
existingStartPort = (PortInst)startObj;
startRE = RouteElementPort.existingPortInst(existingStartPort, startPoly);
}
if (startObj instanceof ArcInst) {
// arc: figure out where on arc to start
startRE = findArcConnectingPoint(route, (ArcInst)startObj, startPoint);
contactsOnEndObject = false;
}
if (startRE == null) {
if (startObj != badStartObject)
System.out.println(" Can't route from "+startObj+", no ports");
badStartObject = startObj;
return route;
}
// plan end of route
if (endObj != null) {
// we have somewhere to route to
if (endObj instanceof PortInst) {
// portinst: just wrap in RouteElement
existingEndPort = (PortInst)endObj;
endRE = RouteElementPort.existingPortInst(existingEndPort, endPoly);
}
if (endObj instanceof ArcInst) {
// arc: figure out where on arc to end
// use startRE location when possible if connecting to arc
endRE = findArcConnectingPoint(route, (ArcInst)endObj, endPoint);
contactsOnEndObject = true;
}
if (endRE == null) {
if (endObj != badEndObject)
System.out.println(" Can't route to "+endObj+", no ports");
badEndObject = endObj;
endObj = null;
}
}
if (endObj == null) {
// nowhere to route to, must make new pin to route to
// first we need to determine what pin to make based on
// start object
ArcProto useArc = null;
if (startObj instanceof PortInst) {
PortInst startPi = (PortInst)startObj;
useArc = getArcToUse(startPi.getPortProto(), null);
}
if (startObj instanceof ArcInst) {
ArcInst startAi = (ArcInst)startObj;
useArc = startAi.getProto();
}
if (!(useArc instanceof PrimitiveArc)) {
System.out.println(" Don't know how to determine pin for arc "+useArc);
return new Route();
}
// make new pin to route to
PrimitiveNode pn = ((PrimitiveArc)useArc).findOverridablePinProto();
SizeOffset so = pn.getProtoSizeOffset();
endRE = RouteElementPort.newNode(cell, pn, pn.getPort(0), endPoint,
pn.getDefWidth()-so.getHighXOffset()-so.getLowXOffset(),
pn.getDefHeight()-so.getHighYOffset()-so.getLowYOffset());
}
// special check: if both are existing port insts and are same port, do nothing
if ((existingEndPort != null) && (existingEndPort == existingStartPort)) return new Route();
// add startRE and endRE to route
route.add(startRE);
route.setStart(startRE);
route.setEnd(startRE);
//route.add(endRE); route.setEnd(endRE);
// Tell Router to route between startRE and endRE
if (planRoute(route, cell, endRE, startPoint, endPoint, clicked, vroute, contactsOnEndObject)) {
return route;
} else
return new Route(); // error, return empty route
}
// -------------------- Internal Router Utility Methods --------------------
/**
* If routeObj is a NodeInst, first thing we do is get the nearest PortInst
* to where the user clicked, and use that instead.
* @param routeObj the route object (possibly a NodeInst).
* @param clicked where the user clicked
* @return the PortInst on the NodeInst closest to where the user clicked,
* or just the routeObj back if it is not a NodeInst.
*/
protected static ElectricObject filterRouteObject(ElectricObject routeObj, Point2D clicked) {
if (routeObj instanceof NodeInst) {
return ((NodeInst)routeObj).findClosestPortInst(clicked);
}
if (routeObj instanceof Export) {
Export exp = (Export)routeObj;
return exp.getOriginalPort();
}
return routeObj;
}
/**
* Get the PortProto associated with routeObj (it should be either
* a ArcInst or a PortInst, otherwise this will return null).
* @param routeObj the route object
* @return the PortProto for this route object
*/
protected static PortProto getRoutePort(ElectricObject routeObj) {
assert(!(routeObj instanceof NodeInst));
if (routeObj instanceof ArcInst) {
ArcInst ai = (ArcInst)routeObj;
PrimitiveNode pn = ((PrimitiveArc)ai.getProto()).findOverridablePinProto();
return (PortProto)pn.getPort(0);
}
if (routeObj instanceof PortInst) {
PortInst pi = (PortInst)routeObj;
return pi.getPortProto();
}
return null;
}
protected static double getArcWidthToUse(ElectricObject routeObj, ArcProto ap) {
double width = -1;
if (routeObj instanceof ArcInst) {
ArcInst ai = (ArcInst)routeObj;
if (ai.getProto() == ap)
return ai.getWidth();
}
if (routeObj instanceof PortInst) {
width = Router.getArcWidthToUse((PortInst)routeObj, ap);
}
return width;
}
/**
* Get the connecting points for the start and end objects of the route. This fills in
* the two Point2D's startPoint and endPoint. These will be the end points of an arc that
* connects to either startObj or endObj.
* @param startObj the start route object
* @param endObj the end route object
* @param clicked where the user clicked
* @param startPoint point inside startPoly on startObj to connect arc to
* @param endPoint point inside endPoly on endObj to connect arc to
* @param startPoly valid port site on startObj
* @param endPoly valid port site on endObj
*/
protected static void getConnectingPoints(ElectricObject startObj, ElectricObject endObj, Point2D clicked,
Point2D startPoint, Point2D endPoint, Poly startPoly, Poly endPoly,
ArcProto startArc, ArcProto endArc) {
// just go by bounds for now
Rectangle2D startBounds = startPoly.getBounds2D();
// default is center point
startPoint.setLocation(startBounds.getCenterX(), startBounds.getCenterY());
if (startObj instanceof ArcInst) {
double x, y;
// if nothing to connect to, clicked will determine connecting point on startPoly
// endPoint will be location of new pin
x = getClosestValue(startBounds.getMinX(), startBounds.getMaxX(), clicked.getX());
y = getClosestValue(startBounds.getMinY(), startBounds.getMaxY(), clicked.getY());
startPoint.setLocation(x, y);
}
if (endPoly == null) {
// if arc, find place to connect to. Otherwise use the center point (default)
endPoint.setLocation(getClosestOrthogonalPoint(startPoint, clicked));
// however, if this is an Artwork technology, just put end point at mouse
if (startArc.getTechnology() == Artwork.tech)
endPoint.setLocation(clicked);
return;
}
Rectangle2D endBounds = endPoly.getBounds2D();
endPoint.setLocation(endBounds.getCenterX(), endBounds.getCenterY());
if (endObj instanceof ArcInst) {
double x, y;
// if nothing to connect to, clicked will determine connecting point on startPoly
// endPoint will be location of new pin
x = getClosestValue(endBounds.getMinX(), endBounds.getMaxX(), clicked.getX());
y = getClosestValue(endBounds.getMinY(), endBounds.getMaxY(), clicked.getY());
endPoint.setLocation(x, y);
}
// if bounds share x-space, use closest x within that space to clicked point
double lowerBoundX = Math.max(startBounds.getMinX(), endBounds.getMinX());
double upperBoundX = Math.min(startBounds.getMaxX(), endBounds.getMaxX());
if (lowerBoundX <= upperBoundX) {
double x = getClosestValue(lowerBoundX, upperBoundX, clicked.getX());
startPoint.setLocation(x, startPoint.getY());
endPoint.setLocation(x, endPoint.getY());
} else {
// otherwise, use closest point in bounds to the other port
// see which one is higher in X...they don't overlap, so any X coord in bounds is comparable
if (startBounds.getMinX() > endBounds.getMaxX()) {
startPoint.setLocation(startBounds.getMinX(), startPoint.getY());
endPoint.setLocation(endBounds.getMaxX(), endPoint.getY());
} else {
startPoint.setLocation(startBounds.getMaxX(), startPoint.getY());
endPoint.setLocation(endBounds.getMinX(), endPoint.getY());
}
}
// if bounds share y-space, use closest y within that space to clicked point
double lowerBoundY = Math.max(startBounds.getMinY(), endBounds.getMinY());
double upperBoundY = Math.min(startBounds.getMaxY(), endBounds.getMaxY());
if (lowerBoundY <= upperBoundY) {
double y = getClosestValue(lowerBoundY, upperBoundY, clicked.getY());
startPoint.setLocation(startPoint.getX(), y);
endPoint.setLocation(endPoint.getX(), y);
} else {
// otherwise, use closest point in bounds to the other port
// see which one is higher in Y...they don't overlap, so any Y coord in bounds is comparable
if (startBounds.getMinY() > endBounds.getMaxY()) {
startPoint.setLocation(startPoint.getX(), startBounds.getMinY());
endPoint.setLocation(endPoint.getX(), endBounds.getMaxY());
} else {
startPoint.setLocation(startPoint.getX(), startBounds.getMaxY());
endPoint.setLocation(endPoint.getX(), endBounds.getMinY());
}
}
}
/**
* Get the connecting site of the electric object.
* <ul>
* <li>For NodeInsts, this is the nearest portinst to "clicked", which is then subject to:
* <li>For PortInsts, this is the nearest site of a multisite port, or just the entire port
* <li>For ArcInsts, this is a poly composed of the head location and the tail location
* </ul>
* See NodeInst.getShapeOfPort() for more details.
* @param obj the object to get a connection site for
* @param clicked used to find the nearest portinst on a nodeinst, and nearest
* site on a multisite port
* @param arcWidth contacts port sites are restricted by the size of arcs connecting
* to them, such that the arc width does extend beyond the contact edges.
* @return a poly describing where something can connect to
*/
protected static Poly getConnectingSite(ElectricObject obj, Point2D clicked, double arcWidth) {
assert(clicked != null);
if (obj instanceof NodeInst) {
PortInst pi = ((NodeInst)obj).findClosestPortInst(clicked);
if (pi == null) return null;
obj = pi;
}
if (obj instanceof PortInst) {
PortInst pi = (PortInst)obj;
NodeInst ni = pi.getNodeInst();
PortProto pp = pi.getPortProto();
boolean compressPort = false;
if (ni.getProto() instanceof PrimitiveNode) compressPort = true;
Poly poly = ni.getShapeOfPort(pp, clicked, compressPort, arcWidth); // this is for multi-site ports
return poly;
}
if (obj instanceof ArcInst) {
// make poly out of possible connecting points on arc
ArcInst arc = (ArcInst)obj;
Point2D [] points = new Point2D[2];
points[0] = arc.getHead().getLocation();
points[1] = arc.getTail().getLocation();
Poly poly = new Poly(points);
return poly;
}
return null;
}
/**
* If drawing to/from an ArcInst, we may connect to some
* point along the arc. This may bisect the arc, in which case
* we delete the current arc, add in a pin at the appropriate
* place, and create 2 new arcs to the old arc head/tail points.
* The bisection point depends on where the user point, but it
* is always a point on the arc.
* <p>
* Note that this method adds the returned RouteElement to the
* route, and updates the route if the arc is bisected.
* This method should NOT add the returned RouteElement to the route.
* @param route the route so far
* @param arc the arc to draw from/to
* @param point point on or near arc
* @return a RouteElement holding the new pin at the bisection
* point, or a RouteElement holding an existingPortInst if
* drawing from either end of the ArcInst.
*/
protected RouteElementPort findArcConnectingPoint(Route route, ArcInst arc, Point2D point) {
Point2D head = arc.getHead().getLocation();
Point2D tail = arc.getTail().getLocation();
RouteElementPort headRE = RouteElementPort.existingPortInst(arc.getHead().getPortInst(), head);
RouteElementPort tailRE = RouteElementPort.existingPortInst(arc.getTail().getPortInst(), tail);
RouteElementPort startRE = null;
// find extents of wire
double minX, minY, maxX, maxY;
Point2D minXpin = null, minYpin = null;
if (head.getX() < tail.getX()) {
minX = head.getX(); maxX = tail.getX(); minXpin = head;
} else {
minX = tail.getX(); maxX = head.getX(); minXpin = tail;
}
if (head.getY() < tail.getY()) {
minY = head.getY(); maxY = tail.getY(); minYpin = head;
} else {
minY = tail.getY(); maxY = head.getY(); minYpin = tail;
}
// for efficiency purposes, we are going to assume the arc is
// either vertical or horizontal for bisecting the arc
if (head.getX() == tail.getX()) {
// line is vertical, see if point point bisects
if (point.getY() > minY && point.getY() < maxY) {
Point2D location = new Point2D.Double(head.getX(), point.getY());
startRE = bisectArc(route, arc, location);
}
// not within Y bounds, choose closest pin
else if (point.getY() <= minY) {
if (minYpin == head) startRE = headRE; else startRE = tailRE;
} else {
if (minYpin == head) startRE = tailRE; else startRE = headRE;
}
}
// check if arc is horizontal
else if (head.getY() == tail.getY()) {
// line is horizontal, see if point bisects
if (point.getX() > minX && point.getX() < maxX) {
Point2D location = new Point2D.Double(point.getX(), head.getY());
startRE = bisectArc(route, arc, location);
}
// not within X bounds, choose closest pin
else if (point.getX() <= minX) {
if (minXpin == head) startRE = headRE; else startRE = tailRE;
} else {
if (minXpin == head) startRE = tailRE; else startRE = headRE;
}
}
// arc is not horizontal or vertical, draw from closest pin
else {
double headDist = point.distance(head);
double tailDist = point.distance(tail);
if (headDist < tailDist)
startRE = headRE;
else
startRE = tailRE;
}
//route.add(startRE); // DON'T ADD!!
return startRE;
}
/**
* Splits an arc at bisectPoint and updates the route to reflect the change.
* This method should NOT add the returned RouteElement to the route.
*
* @param route the current route
* @param arc the arc to split
* @param bisectPoint point on arc from which to split it
* @return the RouteElement from which to continue the route
*/
protected RouteElementPort bisectArc(Route route, ArcInst arc, Point2D bisectPoint) {
Cell cell = arc.getParent();
Point2D head = arc.getHead().getLocation();
Point2D tail = arc.getTail().getLocation();
// determine pin type to use if bisecting arc
PrimitiveNode pn = ((PrimitiveArc)arc.getProto()).findOverridablePinProto();
SizeOffset so = pn.getProtoSizeOffset();
double width = pn.getDefWidth()-so.getHighXOffset()-so.getLowXOffset();
double height = pn.getDefHeight()-so.getHighYOffset()-so.getLowYOffset();
// make new pin
RouteElementPort newPinRE = RouteElementPort.newNode(cell, pn, pn.getPort(0),
bisectPoint, width, height);
newPinRE.setBisectArcPin(true);
// make dummy end pins
RouteElementPort headRE = RouteElementPort.existingPortInst(arc.getHead().getPortInst(), head);
RouteElementPort tailRE = RouteElementPort.existingPortInst(arc.getTail().getPortInst(), tail);
headRE.setShowHighlight(false);
tailRE.setShowHighlight(false);
// put name on longer arc
String name1 = null;
String name2 = null;
if (head.distance(bisectPoint) > tail.distance(bisectPoint))
name1 = arc.getName();
else
name2 = arc.getName();
// add two arcs to rebuild old startArc
RouteElement newHeadArcRE = RouteElementArc.newArc(cell, arc.getProto(), arc.getWidth(), headRE, newPinRE,
head, bisectPoint, name1, arc.getNameTextDescriptor(), arc);
RouteElement newTailArcRE = RouteElementArc.newArc(cell, arc.getProto(), arc.getWidth(), newPinRE, tailRE,
bisectPoint, tail, name2, arc.getNameTextDescriptor(), arc);
newHeadArcRE.setShowHighlight(false);
newTailArcRE.setShowHighlight(false);
// delete old arc
RouteElement deleteArcRE = RouteElementArc.deleteArc(arc);
// add new stuff to route
route.add(deleteArcRE);
//route.add(newPinRE); // DON'T ADD!!
route.add(headRE);
route.add(tailRE);
route.add(newHeadArcRE);
route.add(newTailArcRE);
return newPinRE;
}
// ------------------------- Spatial Dimension Calculations -------------------------
/**
* Get closest value to clicked within a range from min to max
*/
protected static double getClosestValue(double min, double max, double clicked) {
if (clicked >= max) {
return max;
} else if (clicked <= min) {
return min;
} else {
return clicked;
}
}
/**
* Gets the closest orthogonal point from the startPoint to the clicked point.
* This is used when the user clicks in space and the router draws only a single
* arc towards the clicked point in one dimension.
* @param startPoint start point of the arc
* @param clicked where the user clicked
* @return an end point to draw to from start point to make a single arc segment.
*/
protected static Point2D getClosestOrthogonalPoint(Point2D startPoint, Point2D clicked) {
Point2D newPoint;
if (Math.abs(startPoint.getX() - clicked.getX()) < Math.abs(startPoint.getY() - clicked.getY())) {
// draw horizontally
newPoint = new Point2D.Double(startPoint.getX(), clicked.getY());
} else {
// draw vertically
newPoint = new Point2D.Double(clicked.getX(), startPoint.getY());
}
return newPoint;
}
protected boolean withinBounds(double point, double bound1, double bound2) {
double min, max;
if (bound1 < bound2) {
min = bound1; max = bound2;
} else {
min = bound2; max = bound1;
}
return ((point >= min) && (point <= max));
}
/**
* Returns true if point is on the line segment, false otherwise.
*/
protected boolean onSegment(Point2D point, Line2D line) {
double minX, minY, maxX, maxY;
Point2D head = line.getP1();
Point2D tail = line.getP2();
if (head.getX() < tail.getX()) {
minX = head.getX(); maxX = tail.getX();
} else {
minX = tail.getX(); maxX = head.getX();
}
if (head.getY() < tail.getY()) {
minY = head.getY(); maxY = tail.getY();
} else {
minY = tail.getY(); maxY = head.getY();
}
if ((point.getX() >= minX) && (point.getX() <= maxX) &&
(point.getY() >= minY) && (point.getY() <= maxY))
return true;
return false;
}
}
| true | true | protected Route planRoute(Cell cell, ElectricObject startObj, ElectricObject endObj, Point2D clicked) {
Route route = new Route(); // hold the route
if (cell == null) return route;
RouteElementPort startRE = null; // denote start of route
RouteElementPort endRE = null; // denote end of route
// first, convert NodeInsts to PortInsts, if it is one.
// Now we don't have to worry about NodeInsts.
startObj = filterRouteObject(startObj, clicked);
endObj = filterRouteObject(endObj, clicked);
// get the port types at each end so we can build electrical route
PortProto startPort = getRoutePort(startObj);
PortProto endPort;
if (endObj == null) {
// end object is null, we are routing to a pin. Figure out what arc to use
ArcProto useArc = getArcToUse(startPort, null);
PrimitiveNode pn = ((PrimitiveArc)useArc).findOverridablePinProto();
endPort = pn.getPort(0);
} else {
endPort = getRoutePort(endObj);
}
// now determine the electrical route. We need to know what
// arcs will be used (and their widths, eventually) to determine
// the Port Poly size for contacts
VerticalRoute vroute = VerticalRoute.newRoute(startPort, endPort);
if (!vroute.isSpecificationSucceeded()) return new Route();
// arc width of arcs that will connect to startObj, endObj will determine
// valid attachment points of arcs
ArcProto startArc = vroute.getStartArc();
ArcProto endArc = vroute.getEndArc();
double startArcWidth = getArcWidthToUse(startObj, startArc);
double endArcWidth = (endObj == null) ? startArcWidth : getArcWidthToUse(endObj, endArc);
// get valid connecting sites for start and end objects based on the objects
// themselves, the point the user clicked, and the width of the wire that will
// attach to each
Poly startPoly = getConnectingSite(startObj, clicked, startArcWidth);
Poly endPoly = getConnectingSite(endObj, clicked, endArcWidth);
//Poly startPoly = getConnectingSite(startObj, clicked, 3);
//Poly endPoly = getConnectingSite(endObj, clicked, 3);
// Now we can figure out where on the start and end objects the connecting
// arc(s) should connect
Point2D startPoint = new Point2D.Double(0, 0);
Point2D endPoint = new Point2D.Double(0,0);
getConnectingPoints(startObj, endObj, clicked, startPoint, endPoint, startPoly, endPoly, startArc, endArc);
PortInst existingStartPort = null;
PortInst existingEndPort = null;
// favor contact cuts on arcs
boolean contactsOnEndObject = true;
// plan start of route
if (startObj instanceof PortInst) {
// portinst: just wrap in RouteElement
existingStartPort = (PortInst)startObj;
startRE = RouteElementPort.existingPortInst(existingStartPort, startPoly);
}
if (startObj instanceof ArcInst) {
// arc: figure out where on arc to start
startRE = findArcConnectingPoint(route, (ArcInst)startObj, startPoint);
contactsOnEndObject = false;
}
if (startRE == null) {
if (startObj != badStartObject)
System.out.println(" Can't route from "+startObj+", no ports");
badStartObject = startObj;
return route;
}
// plan end of route
if (endObj != null) {
// we have somewhere to route to
if (endObj instanceof PortInst) {
// portinst: just wrap in RouteElement
existingEndPort = (PortInst)endObj;
endRE = RouteElementPort.existingPortInst(existingEndPort, endPoly);
}
if (endObj instanceof ArcInst) {
// arc: figure out where on arc to end
// use startRE location when possible if connecting to arc
endRE = findArcConnectingPoint(route, (ArcInst)endObj, endPoint);
contactsOnEndObject = true;
}
if (endRE == null) {
if (endObj != badEndObject)
System.out.println(" Can't route to "+endObj+", no ports");
badEndObject = endObj;
endObj = null;
}
}
if (endObj == null) {
// nowhere to route to, must make new pin to route to
// first we need to determine what pin to make based on
// start object
ArcProto useArc = null;
if (startObj instanceof PortInst) {
PortInst startPi = (PortInst)startObj;
useArc = getArcToUse(startPi.getPortProto(), null);
}
if (startObj instanceof ArcInst) {
ArcInst startAi = (ArcInst)startObj;
useArc = startAi.getProto();
}
if (!(useArc instanceof PrimitiveArc)) {
System.out.println(" Don't know how to determine pin for arc "+useArc);
return new Route();
}
// make new pin to route to
PrimitiveNode pn = ((PrimitiveArc)useArc).findOverridablePinProto();
SizeOffset so = pn.getProtoSizeOffset();
endRE = RouteElementPort.newNode(cell, pn, pn.getPort(0), endPoint,
pn.getDefWidth()-so.getHighXOffset()-so.getLowXOffset(),
pn.getDefHeight()-so.getHighYOffset()-so.getLowYOffset());
}
// special check: if both are existing port insts and are same port, do nothing
if ((existingEndPort != null) && (existingEndPort == existingStartPort)) return new Route();
// add startRE and endRE to route
route.add(startRE);
route.setStart(startRE);
route.setEnd(startRE);
//route.add(endRE); route.setEnd(endRE);
// Tell Router to route between startRE and endRE
if (planRoute(route, cell, endRE, startPoint, endPoint, clicked, vroute, contactsOnEndObject)) {
return route;
} else
return new Route(); // error, return empty route
}
| protected Route planRoute(Cell cell, ElectricObject startObj, ElectricObject endObj, Point2D clicked) {
Route route = new Route(); // hold the route
if (cell == null) return route;
RouteElementPort startRE = null; // denote start of route
RouteElementPort endRE = null; // denote end of route
// first, convert NodeInsts to PortInsts, if it is one.
// Now we don't have to worry about NodeInsts.
startObj = filterRouteObject(startObj, clicked);
endObj = filterRouteObject(endObj, clicked);
// get the port types at each end so we can build electrical route
PortProto startPort = getRoutePort(startObj);
PortProto endPort;
if (endObj == null) {
// end object is null, we are routing to a pin. Figure out what arc to use
ArcProto useArc = getArcToUse(startPort, null);
if (useArc == null) return route;
PrimitiveNode pn = ((PrimitiveArc)useArc).findOverridablePinProto();
endPort = pn.getPort(0);
} else {
endPort = getRoutePort(endObj);
}
// now determine the electrical route. We need to know what
// arcs will be used (and their widths, eventually) to determine
// the Port Poly size for contacts
VerticalRoute vroute = VerticalRoute.newRoute(startPort, endPort);
if (!vroute.isSpecificationSucceeded()) return new Route();
// arc width of arcs that will connect to startObj, endObj will determine
// valid attachment points of arcs
ArcProto startArc = vroute.getStartArc();
ArcProto endArc = vroute.getEndArc();
double startArcWidth = getArcWidthToUse(startObj, startArc);
double endArcWidth = (endObj == null) ? startArcWidth : getArcWidthToUse(endObj, endArc);
// get valid connecting sites for start and end objects based on the objects
// themselves, the point the user clicked, and the width of the wire that will
// attach to each
Poly startPoly = getConnectingSite(startObj, clicked, startArcWidth);
Poly endPoly = getConnectingSite(endObj, clicked, endArcWidth);
//Poly startPoly = getConnectingSite(startObj, clicked, 3);
//Poly endPoly = getConnectingSite(endObj, clicked, 3);
// Now we can figure out where on the start and end objects the connecting
// arc(s) should connect
Point2D startPoint = new Point2D.Double(0, 0);
Point2D endPoint = new Point2D.Double(0,0);
getConnectingPoints(startObj, endObj, clicked, startPoint, endPoint, startPoly, endPoly, startArc, endArc);
PortInst existingStartPort = null;
PortInst existingEndPort = null;
// favor contact cuts on arcs
boolean contactsOnEndObject = true;
// plan start of route
if (startObj instanceof PortInst) {
// portinst: just wrap in RouteElement
existingStartPort = (PortInst)startObj;
startRE = RouteElementPort.existingPortInst(existingStartPort, startPoly);
}
if (startObj instanceof ArcInst) {
// arc: figure out where on arc to start
startRE = findArcConnectingPoint(route, (ArcInst)startObj, startPoint);
contactsOnEndObject = false;
}
if (startRE == null) {
if (startObj != badStartObject)
System.out.println(" Can't route from "+startObj+", no ports");
badStartObject = startObj;
return route;
}
// plan end of route
if (endObj != null) {
// we have somewhere to route to
if (endObj instanceof PortInst) {
// portinst: just wrap in RouteElement
existingEndPort = (PortInst)endObj;
endRE = RouteElementPort.existingPortInst(existingEndPort, endPoly);
}
if (endObj instanceof ArcInst) {
// arc: figure out where on arc to end
// use startRE location when possible if connecting to arc
endRE = findArcConnectingPoint(route, (ArcInst)endObj, endPoint);
contactsOnEndObject = true;
}
if (endRE == null) {
if (endObj != badEndObject)
System.out.println(" Can't route to "+endObj+", no ports");
badEndObject = endObj;
endObj = null;
}
}
if (endObj == null) {
// nowhere to route to, must make new pin to route to
// first we need to determine what pin to make based on
// start object
ArcProto useArc = null;
if (startObj instanceof PortInst) {
PortInst startPi = (PortInst)startObj;
useArc = getArcToUse(startPi.getPortProto(), null);
}
if (startObj instanceof ArcInst) {
ArcInst startAi = (ArcInst)startObj;
useArc = startAi.getProto();
}
if (!(useArc instanceof PrimitiveArc)) {
System.out.println(" Don't know how to determine pin for arc "+useArc);
return new Route();
}
// make new pin to route to
PrimitiveNode pn = ((PrimitiveArc)useArc).findOverridablePinProto();
SizeOffset so = pn.getProtoSizeOffset();
endRE = RouteElementPort.newNode(cell, pn, pn.getPort(0), endPoint,
pn.getDefWidth()-so.getHighXOffset()-so.getLowXOffset(),
pn.getDefHeight()-so.getHighYOffset()-so.getLowYOffset());
}
// special check: if both are existing port insts and are same port, do nothing
if ((existingEndPort != null) && (existingEndPort == existingStartPort)) return new Route();
// add startRE and endRE to route
route.add(startRE);
route.setStart(startRE);
route.setEnd(startRE);
//route.add(endRE); route.setEnd(endRE);
// Tell Router to route between startRE and endRE
if (planRoute(route, cell, endRE, startPoint, endPoint, clicked, vroute, contactsOnEndObject)) {
return route;
} else
return new Route(); // error, return empty route
}
|
diff --git a/core/src/main/java/hudson/model/AbstractProject.java b/core/src/main/java/hudson/model/AbstractProject.java
index 8d4ec59c8..d2bc5bdea 100644
--- a/core/src/main/java/hudson/model/AbstractProject.java
+++ b/core/src/main/java/hudson/model/AbstractProject.java
@@ -1,1594 +1,1596 @@
/*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Brian Westrich, Erik Ramfelt, Ertan Deniz, Jean-Baptiste Quenot, Luca Domenico Milanesio, R. Tyler Ballance, Stephen Connolly, Tom Huybrechts, id:cactusman
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.model;
import hudson.AbortException;
import hudson.FeedAdapter;
import hudson.FilePath;
import hudson.Launcher;
import hudson.Util;
import hudson.cli.declarative.CLIMethod;
import hudson.slaves.WorkspaceList;
import hudson.model.Cause.LegacyCodeCause;
import hudson.model.Cause.UserCause;
import hudson.model.Cause.RemoteCause;
import hudson.model.Descriptor.FormException;
import hudson.model.Fingerprint.RangeSet;
import hudson.model.RunMap.Constructor;
import hudson.model.Queue.WaitingItem;
import hudson.model.Queue.Executable;
import hudson.model.queue.CauseOfBlockage;
import hudson.scm.ChangeLogSet;
import hudson.scm.ChangeLogSet.Entry;
import hudson.scm.NullSCM;
import hudson.scm.SCM;
import hudson.scm.SCMS;
import hudson.search.SearchIndexBuilder;
import hudson.security.Permission;
import hudson.tasks.BuildStep;
import hudson.tasks.BuildTrigger;
import hudson.tasks.Mailer;
import hudson.tasks.Publisher;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.BuildWrapperDescriptor;
import hudson.triggers.SCMTrigger;
import hudson.triggers.Trigger;
import hudson.triggers.TriggerDescriptor;
import hudson.util.DescribableList;
import hudson.util.EditDistance;
import hudson.util.FormValidation;
import hudson.widgets.BuildHistoryWidget;
import hudson.widgets.HistoryWidget;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpRedirect;
import org.kohsuke.stapler.ForwardToView;
import javax.servlet.ServletException;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.Vector;
import java.util.concurrent.Future;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Base implementation of {@link Job}s that build software.
*
* For now this is primarily the common part of {@link Project} and MavenModule.
*
* @author Kohsuke Kawaguchi
* @see AbstractBuild
*/
public abstract class AbstractProject<P extends AbstractProject<P,R>,R extends AbstractBuild<P,R>> extends Job<P,R> implements BuildableItem {
/**
* {@link SCM} associated with the project.
* To allow derived classes to link {@link SCM} config to elsewhere,
* access to this variable should always go through {@link #getScm()}.
*/
private volatile SCM scm = new NullSCM();
/**
* All the builds keyed by their build number.
*/
protected transient /*almost final*/ RunMap<R> builds = new RunMap<R>();
/**
* The quiet period. Null to delegate to the system default.
*/
private volatile Integer quietPeriod = null;
/**
* The retry count. Null to delegate to the system default.
*/
private volatile Integer scmCheckoutRetryCount = null;
/**
* If this project is configured to be only built on a certain label,
* this value will be set to that label.
*
* For historical reasons, this is called 'assignedNode'. Also for
* a historical reason, null to indicate the affinity
* with the master node.
*
* @see #canRoam
*/
private String assignedNode;
/**
* True if this project can be built on any node.
*
* <p>
* This somewhat ugly flag combination is so that we can migrate
* existing Hudson installations nicely.
*/
private volatile boolean canRoam;
/**
* True to suspend new builds.
*/
protected volatile boolean disabled;
/**
* True to keep builds of this project in queue when upstream projects are
* building. False by default to keep from breaking existing behavior.
*/
protected volatile boolean blockBuildWhenUpstreamBuilding = false;
/**
* Identifies {@link JDK} to be used.
* Null if no explicit configuration is required.
*
* <p>
* Can't store {@link JDK} directly because {@link Hudson} and {@link Project}
* are saved independently.
*
* @see Hudson#getJDK(String)
*/
private volatile String jdk;
/**
* @deprecated since 2007-01-29.
*/
private transient boolean enableRemoteTrigger;
private volatile BuildAuthorizationToken authToken = null;
/**
* List of all {@link Trigger}s for this project.
*/
protected List<Trigger<?>> triggers = new Vector<Trigger<?>>();
/**
* {@link Action}s contributed from subsidiary objects associated with
* {@link AbstractProject}, such as from triggers, builders, publishers, etc.
*
* We don't want to persist them separately, and these actions
* come and go as configuration change, so it's kept separate.
*/
protected transient /*final*/ List<Action> transientActions = new Vector<Action>();
private boolean concurrentBuild;
protected AbstractProject(ItemGroup parent, String name) {
super(parent,name);
if(!Hudson.getInstance().getNodes().isEmpty()) {
// if a new job is configured with Hudson that already has slave nodes
// make it roamable by default
canRoam = true;
}
}
@Override
public void onLoad(ItemGroup<? extends Item> parent, String name) throws IOException {
super.onLoad(parent, name);
this.builds = new RunMap<R>();
this.builds.load(this,new Constructor<R>() {
public R create(File dir) throws IOException {
return loadBuild(dir);
}
});
if(triggers==null)
// it didn't exist in < 1.28
triggers = new Vector<Trigger<?>>();
for (Trigger t : triggers)
t.start(this,false);
if(scm==null)
scm = new NullSCM(); // perhaps it was pointing to a plugin that no longer exists.
if(transientActions==null)
transientActions = new Vector<Action>(); // happens when loaded from disk
updateTransientActions();
}
@Override
protected void performDelete() throws IOException, InterruptedException {
// prevent a new build while a delete operation is in progress
makeDisabled(true);
FilePath ws = getWorkspace();
if(ws!=null) {
Node on = getLastBuiltOn();
getScm().processWorkspaceBeforeDeletion(this, ws, on);
if(on!=null)
on.getFileSystemProvisioner().discardWorkspace(this,ws);
}
super.performDelete();
}
/**
* Does this project perform concurrent builds?
* @since 1.319
*/
public boolean isConcurrentBuild() {
return Hudson.CONCURRENT_BUILD && concurrentBuild;
}
public void setConcurrentBuild(boolean b) throws IOException {
concurrentBuild = b;
save();
}
/**
* If this project is configured to be always built on this node,
* return that {@link Node}. Otherwise null.
*/
public Label getAssignedLabel() {
if(canRoam)
return null;
if(assignedNode==null)
return Hudson.getInstance().getSelfLabel();
return Hudson.getInstance().getLabel(assignedNode);
}
/**
* Sets the assigned label.
*/
public void setAssignedLabel(Label l) throws IOException {
if(l==null) {
canRoam = true;
assignedNode = null;
} else {
canRoam = false;
if(l==Hudson.getInstance().getSelfLabel()) assignedNode = null;
else assignedNode = l.getName();
}
save();
}
/**
* Get the term used in the UI to represent this kind of {@link AbstractProject}.
* Must start with a capital letter.
*/
@Override
public String getPronoun() {
return Messages.AbstractProject_Pronoun();
}
/**
* Returns the root project value.
*
* @return the root project value.
*/
public AbstractProject getRootProject() {
if (this.getParent() instanceof Hudson) {
return this;
} else {
return ((AbstractProject) this.getParent()).getRootProject();
}
}
/**
* Gets the directory where the module is checked out.
*
* @return
* null if the workspace is on a slave that's not connected.
* @deprecated as of 1.319
* To support concurrent builds of the same project, this method is moved to {@link AbstractBuild}.
* For backward compatibility, this method returns the right {@link AbstractBuild#getWorkspace()} if called
* from {@link Executor}, and otherwise the workspace of the last build.
*
* <p>
* If you are calling this method during a build from an executor, switch it to {@link AbstractBuild#getWorkspace()}.
* If you are calling this method to serve a file from the workspace, doing a form validation, etc., then
* use {@link #getSomeWorkspace()}
*/
public final FilePath getWorkspace() {
Executor e = Executor.currentExecutor();
if(e!=null) {
Executable exe = e.getCurrentExecutable();
if (exe instanceof AbstractBuild) {
AbstractBuild b = (AbstractBuild) exe;
if(b.getProject()==this)
return b.getWorkspace();
}
}
R lb = getLastBuild();
if(lb!=null) return lb.getWorkspace();
return null;
}
/**
* Gets a workspace for some build of this project.
*
* <p>
* This is useful for obtaining a workspace for the purpose of form field validation, where exactly
* which build the workspace belonged is less important. The implementation makes a cursory effort
* to find some workspace.
*
* @return
* null if there's no available workspace.
* @since 1.319
*/
public final FilePath getSomeWorkspace() {
R b = getSomeBuildWithWorkspace();
return b!=null ? b.getWorkspace() : null;
}
/**
* Gets some build that has a live workspace.
*
* @return null if no such build exists.
*/
public final R getSomeBuildWithWorkspace() {
int cnt=0;
for (R b = getLastBuild(); cnt<5 && b!=null; b=b.getPreviousBuild()) {
FilePath ws = b.getWorkspace();
if (ws!=null) return b;
}
return null;
}
/**
* Returns the root directory of the checked-out module.
* <p>
* This is usually where <tt>pom.xml</tt>, <tt>build.xml</tt>
* and so on exists.
*
* @deprecated as of 1.319
* See {@link #getWorkspace()} for a migration strategy.
*/
public FilePath getModuleRoot() {
FilePath ws = getWorkspace();
if(ws==null) return null;
return getScm().getModuleRoot(ws);
}
/**
* Returns the root directories of all checked-out modules.
* <p>
* Some SCMs support checking out multiple modules into the same workspace.
* In these cases, the returned array will have a length greater than one.
* @return The roots of all modules checked out from the SCM.
*
* @deprecated as of 1.319
* See {@link #getWorkspace()} for a migration strategy.
*/
public FilePath[] getModuleRoots() {
return getScm().getModuleRoots(getWorkspace());
}
public int getQuietPeriod() {
return quietPeriod!=null ? quietPeriod : Hudson.getInstance().getQuietPeriod();
}
public int getScmCheckoutRetryCount() {
return scmCheckoutRetryCount !=null ? scmCheckoutRetryCount : Hudson.getInstance().getScmCheckoutRetryCount();
}
// ugly name because of EL
public boolean getHasCustomQuietPeriod() {
return quietPeriod!=null;
}
public boolean hasCustomScmCheckoutRetryCount(){
return scmCheckoutRetryCount != null;
}
public final boolean isBuildable() {
return !isDisabled();
}
/**
* Used in <tt>sidepanel.jelly</tt> to decide whether to display
* the config/delete/build links.
*/
public boolean isConfigurable() {
return true;
}
public boolean blockBuildWhenUpstreamBuilding() {
return blockBuildWhenUpstreamBuilding;
}
public void setBlockBuildWhenUpstreamBuilding(boolean b) throws IOException {
blockBuildWhenUpstreamBuilding = b;
save();
}
public boolean isDisabled() {
return disabled;
}
/**
* Validates the retry count Regex
*/
public FormValidation doCheckRetryCount(@QueryParameter String value)throws IOException,ServletException{
// retry count is optional so this is ok
if(value == null || value.trim().equals(""))
return FormValidation.ok();
if (!value.matches("[0-9]*")) {
return FormValidation.error("Invalid retry count");
}
return FormValidation.ok();
}
/**
* Marks the build as disabled.
*/
public void makeDisabled(boolean b) throws IOException {
if(disabled==b) return; // noop
this.disabled = b;
if(b)
Hudson.getInstance().getQueue().cancel(this);
save();
}
@CLIMethod(name="disable-job")
public void disable() throws IOException {
makeDisabled(true);
}
@CLIMethod(name="enable-job")
public void enable() throws IOException {
makeDisabled(false);
}
@Override
public BallColor getIconColor() {
if(isDisabled())
return BallColor.DISABLED;
else
return super.getIconColor();
}
protected void updateTransientActions() {
synchronized(transientActions) {
transientActions.clear();
for (JobProperty<? super P> p : properties) {
Action a = p.getJobAction((P)this);
if(a!=null)
transientActions.add(a);
}
for (TransientProjectActionFactory tpaf : TransientProjectActionFactory.all())
transientActions.addAll(Util.fixNull(tpaf.createFor(this))); // be defensive against null
}
}
/**
* Returns the live list of all {@link Publisher}s configured for this project.
*
* <p>
* This method couldn't be called <tt>getPublishers()</tt> because existing methods
* in sub-classes return different inconsistent types.
*/
public abstract DescribableList<Publisher,Descriptor<Publisher>> getPublishersList();
@Override
public void addProperty(JobProperty<? super P> jobProp) throws IOException {
super.addProperty(jobProp);
updateTransientActions();
}
public List<ProminentProjectAction> getProminentActions() {
List<Action> a = getActions();
List<ProminentProjectAction> pa = new Vector<ProminentProjectAction>();
for (Action action : a) {
if(action instanceof ProminentProjectAction)
pa.add((ProminentProjectAction) action);
}
return pa;
}
@Override
public void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
super.doConfigSubmit(req,rsp);
Set<AbstractProject> upstream = Collections.emptySet();
if(req.getParameter("pseudoUpstreamTrigger")!=null) {
upstream = new HashSet<AbstractProject>(Items.fromNameList(req.getParameter("upstreamProjects"),AbstractProject.class));
}
// dependency setting might have been changed by the user, so rebuild.
Hudson.getInstance().rebuildDependencyGraph();
// reflect the submission of the pseudo 'upstream build trriger'.
// this needs to be done after we release the lock on 'this',
// or otherwise we could dead-lock
for (AbstractProject<?,?> p : Hudson.getInstance().getAllItems(AbstractProject.class)) {
+ // Don't consider child projects such as MatrixConfiguration:
+ if (!p.isConfigurable()) continue;
boolean isUpstream = upstream.contains(p);
synchronized(p) {
// does 'p' include us in its BuildTrigger?
DescribableList<Publisher,Descriptor<Publisher>> pl = p.getPublishersList();
BuildTrigger trigger = pl.get(BuildTrigger.class);
List<AbstractProject> newChildProjects = trigger == null ? new ArrayList<AbstractProject>():trigger.getChildProjects();
if(isUpstream) {
if(!newChildProjects.contains(this))
newChildProjects.add(this);
} else {
newChildProjects.remove(this);
}
if(newChildProjects.isEmpty()) {
pl.remove(BuildTrigger.class);
} else {
// here, we just need to replace the old one with the new one,
// but there was a regression (we don't know when it started) that put multiple BuildTriggers
// into the list.
// for us not to lose the data, we need to merge them all.
List<BuildTrigger> existingList = pl.getAll(BuildTrigger.class);
BuildTrigger existing;
switch (existingList.size()) {
case 0:
existing = null;
break;
case 1:
existing = existingList.get(0);
break;
default:
pl.removeAll(BuildTrigger.class);
Set<AbstractProject> combinedChildren = new HashSet<AbstractProject>();
for (BuildTrigger bt : existingList)
combinedChildren.addAll(bt.getChildProjects());
existing = new BuildTrigger(new ArrayList<AbstractProject>(combinedChildren),existingList.get(0).getThreshold());
pl.add(existing);
break;
}
if(existing!=null && existing.hasSame(newChildProjects))
continue; // no need to touch
pl.replace(new BuildTrigger(newChildProjects,
existing==null?Result.SUCCESS:existing.getThreshold()));
}
}
}
// notify the queue as the project might be now tied to different node
Hudson.getInstance().getQueue().scheduleMaintenance();
// this is to reflect the upstream build adjustments done above
Hudson.getInstance().rebuildDependencyGraph();
}
/**
* @deprecated
* Use {@link #scheduleBuild(Cause)}. Since 1.283
*/
public boolean scheduleBuild() {
return scheduleBuild(new LegacyCodeCause());
}
/**
* @deprecated
* Use {@link #scheduleBuild(int, Cause)}. Since 1.283
*/
public boolean scheduleBuild(int quietPeriod) {
return scheduleBuild(quietPeriod, new LegacyCodeCause());
}
/**
* Schedules a build of this project.
*
* @return
* true if the project is actually added to the queue.
* false if the queue contained it and therefore the add()
* was noop
*/
public boolean scheduleBuild(Cause c) {
return scheduleBuild(getQuietPeriod(), c);
}
public boolean scheduleBuild(int quietPeriod, Cause c) {
return scheduleBuild(quietPeriod, c, new Action[0]);
}
/**
* Schedules a build.
*
* Important: the actions should be persistable without outside references (e.g. don't store
* references to this project). To provide parameters for a parameterized project, add a ParametersAction. If
* no ParametersAction is provided for such a project, one will be created with the default parameter values.
*
* @param quietPeriod the quiet period to observer
* @param c the cause for this build which should be recorded
* @param actions a list of Actions that will be added to the build
* @return whether the build was actually scheduled
*/
public boolean scheduleBuild(int quietPeriod, Cause c, Action... actions) {
return scheduleBuild2(quietPeriod,c,actions)!=null;
}
/**
* Schedules a build of this project, and returns a {@link Future} object
* to wait for the completion of the build.
*/
public Future<R> scheduleBuild2(int quietPeriod, Cause c, Action... actions) {
if (isDisabled())
return null;
List<Action> queueActions = new ArrayList<Action>(Arrays.asList(actions));
if (isParameterized() && Util.filter(queueActions, ParametersAction.class).isEmpty()) {
queueActions.add(new ParametersAction(getDefaultParametersValues()));
}
if (c != null) {
queueActions.add(new CauseAction(c));
}
WaitingItem i = Hudson.getInstance().getQueue().schedule(this, quietPeriod, queueActions);
if(i!=null)
return (Future)i.getFuture();
return null;
}
private List<ParameterValue> getDefaultParametersValues() {
ParametersDefinitionProperty paramDefProp = getProperty(ParametersDefinitionProperty.class);
ArrayList<ParameterValue> defValues = new ArrayList<ParameterValue>();
/*
* This check is made ONLY if someone will call this method even if isParametrized() is false.
*/
if(paramDefProp == null)
return defValues;
/* Scan for all parameter with an associated default values */
for(ParameterDefinition paramDefinition : paramDefProp.getParameterDefinitions())
{
ParameterValue defaultValue = paramDefinition.getDefaultParameterValue();
if(defaultValue != null)
defValues.add(defaultValue);
}
return defValues;
}
/**
* Schedules a build, and returns a {@link Future} object
* to wait for the completion of the build.
*
* <p>
* Production code shouldn't be using this, but for tests this is very convenient, so this isn't marked
* as deprecated.
*/
public Future<R> scheduleBuild2(int quietPeriod) {
return scheduleBuild2(quietPeriod, new LegacyCodeCause());
}
/**
* Schedules a build of this project, and returns a {@link Future} object
* to wait for the completion of the build.
*/
public Future<R> scheduleBuild2(int quietPeriod, Cause c) {
return scheduleBuild2(quietPeriod, c, new Action[0]);
}
/**
* Schedules a polling of this project.
*/
public boolean schedulePolling() {
if(isDisabled()) return false;
SCMTrigger scmt = getTrigger(SCMTrigger.class);
if(scmt==null) return false;
scmt.run();
return true;
}
/**
* Returns true if the build is in the queue.
*/
@Override
public boolean isInQueue() {
return Hudson.getInstance().getQueue().contains(this);
}
@Override
public Queue.Item getQueueItem() {
return Hudson.getInstance().getQueue().getItem(this);
}
/**
* Gets the JDK that this project is configured with, or null.
*/
public JDK getJDK() {
return Hudson.getInstance().getJDK(jdk);
}
/**
* Overwrites the JDK setting.
*/
public void setJDK(JDK jdk) throws IOException {
this.jdk = jdk.getName();
save();
}
public BuildAuthorizationToken getAuthToken() {
return authToken;
}
public SortedMap<Integer, ? extends R> _getRuns() {
return builds.getView();
}
public void removeRun(R run) {
this.builds.remove(run);
}
/**
* Determines Class<R>.
*/
protected abstract Class<R> getBuildClass();
// keep track of the previous time we started a build
private transient long lastBuildStartTime;
/**
* Creates a new build of this project for immediate execution.
*/
protected synchronized R newBuild() throws IOException {
// make sure we don't start two builds in the same second
// so the build directories will be different too
long timeSinceLast = System.currentTimeMillis() - lastBuildStartTime;
if (timeSinceLast < 1000) {
try {
Thread.sleep(1000 - timeSinceLast);
} catch (InterruptedException e) {
}
}
lastBuildStartTime = System.currentTimeMillis();
try {
R lastBuild = getBuildClass().getConstructor(getClass()).newInstance(this);
builds.put(lastBuild);
return lastBuild;
} catch (InstantiationException e) {
throw new Error(e);
} catch (IllegalAccessException e) {
throw new Error(e);
} catch (InvocationTargetException e) {
throw handleInvocationTargetException(e);
} catch (NoSuchMethodException e) {
throw new Error(e);
}
}
private IOException handleInvocationTargetException(InvocationTargetException e) {
Throwable t = e.getTargetException();
if(t instanceof Error) throw (Error)t;
if(t instanceof RuntimeException) throw (RuntimeException)t;
if(t instanceof IOException) return (IOException)t;
throw new Error(t);
}
/**
* Loads an existing build record from disk.
*/
protected R loadBuild(File dir) throws IOException {
try {
return getBuildClass().getConstructor(getClass(),File.class).newInstance(this,dir);
} catch (InstantiationException e) {
throw new Error(e);
} catch (IllegalAccessException e) {
throw new Error(e);
} catch (InvocationTargetException e) {
throw handleInvocationTargetException(e);
} catch (NoSuchMethodException e) {
throw new Error(e);
}
}
/**
* {@inheritDoc}
*
* <p>
* Note that this method returns a read-only view of {@link Action}s.
* {@link BuildStep}s and others who want to add a project action
* should do so by implementing {@link BuildStep#getProjectAction(AbstractProject)}.
*
* @see TransientProjectActionFactory
*/
@Override
public synchronized List<Action> getActions() {
// add all the transient actions, too
List<Action> actions = new Vector<Action>(super.getActions());
actions.addAll(transientActions);
// return the read only list to cause a failure on plugins who try to add an action here
return Collections.unmodifiableList(actions);
}
/**
* Gets the {@link Node} where this project was last built on.
*
* @return
* null if no information is available (for example,
* if no build was done yet.)
*/
public Node getLastBuiltOn() {
// where was it built on?
AbstractBuild b = getLastBuild();
if(b==null)
return null;
else
return b.getBuiltOn();
}
/**
* {@inheritDoc}
*
* <p>
* A project must be blocked if its own previous build is in progress,
* or if the blockBuildWhenUpstreamBuilding option is true and an upstream
* project is building, but derived classes can also check other conditions.
*/
public boolean isBuildBlocked() {
return getCauseOfBlockage()!=null;
}
public String getWhyBlocked() {
CauseOfBlockage cb = getCauseOfBlockage();
return cb!=null ? cb.getShortDescription() : null;
}
/**
* Blocked because the previous build is already in progress.
*/
public static class BecauseOfBuildInProgress extends CauseOfBlockage {
private final AbstractBuild<?,?> build;
public BecauseOfBuildInProgress(AbstractBuild<?, ?> build) {
this.build = build;
}
public String getShortDescription() {
Executor e = build.getExecutor();
String eta = "";
if (e != null)
eta = Messages.AbstractProject_ETA(e.getEstimatedRemainingTime());
int lbn = build.getNumber();
return Messages.AbstractProject_BuildInProgress(lbn, eta);
}
}
/**
* Because the upstream build is in progress, and we are configured to wait for that.
*/
public static class BecauseOfUpstreamBuildInProgress extends CauseOfBlockage {
public final AbstractProject<?,?> up;
public BecauseOfUpstreamBuildInProgress(AbstractProject<?,?> up) {
this.up = up;
}
public String getShortDescription() {
return Messages.AbstractProject_UpstreamBuildInProgress(up.getName());
}
}
public CauseOfBlockage getCauseOfBlockage() {
if (isBuilding() && !isConcurrentBuild())
return new BecauseOfBuildInProgress(getLastBuild());
if (blockBuildWhenUpstreamBuilding()) {
AbstractProject<?,?> bup = getBuildingUpstream();
if (bup!=null)
return new BecauseOfUpstreamBuildInProgress(bup);
}
return null;
}
/**
* Returns the project if any of the upstream project (or itself) is either
* building or is in the queue.
* <p>
* This means eventually there will be an automatic triggering of
* the given project (provided that all builds went smoothly.)
*/
protected AbstractProject getBuildingUpstream() {
DependencyGraph graph = Hudson.getInstance().getDependencyGraph();
Set<AbstractProject> tups = graph.getTransitiveUpstream(this);
tups.add(this);
for (AbstractProject tup : tups) {
if(tup!=this && (tup.isBuilding() || tup.isInQueue()))
return tup;
}
return null;
}
public final long getEstimatedDuration() {
AbstractBuild b = getLastSuccessfulBuild();
if(b==null) return -1;
long duration = b.getDuration();
if(duration==0) return -1;
return duration;
}
public R createExecutable() throws IOException {
if(isDisabled()) return null;
return newBuild();
}
public void checkAbortPermission() {
checkPermission(AbstractProject.ABORT);
}
public boolean hasAbortPermission() {
return hasPermission(AbstractProject.ABORT);
}
/**
* Gets the {@link Resource} that represents the workspace of this project.
* Useful for locking and mutual exclusion control.
*
* @deprecated as of 1.319
* Projects no longer have a fixed workspace, ands builds will find an available workspace via
* {@link WorkspaceList} for each build (furthermore, that happens after a build is started.)
* So a {@link Resource} representation for a workspace at the project level no longer makes sense.
*
* <p>
* If you need to lock a workspace while you do some computation, see the source code of
* {@link #pollSCMChanges(TaskListener)} for how to obtain a lock of a workspace through {@link WorkspaceList}.
*/
public Resource getWorkspaceResource() {
return new Resource(getFullDisplayName()+" workspace");
}
/**
* List of necessary resources to perform the build of this project.
*/
public ResourceList getResourceList() {
final Set<ResourceActivity> resourceActivities = getResourceActivities();
final List<ResourceList> resourceLists = new ArrayList<ResourceList>(1 + resourceActivities.size());
for (ResourceActivity activity : resourceActivities) {
if (activity != this && activity != null) {
// defensive infinite recursion and null check
resourceLists.add(activity.getResourceList());
}
}
return ResourceList.union(resourceLists);
}
/**
* Set of child resource activities of the build of this project (override in child projects).
* @return The set of child resource activities of the build of this project.
*/
protected Set<ResourceActivity> getResourceActivities() {
return Collections.emptySet();
}
public boolean checkout(AbstractBuild build, Launcher launcher, BuildListener listener, File changelogFile) throws IOException {
SCM scm = getScm();
if(scm==null)
return true; // no SCM
try {
FilePath workspace = build.getWorkspace();
workspace.mkdirs();
return scm.checkout(build, launcher, workspace, listener, changelogFile);
} catch (InterruptedException e) {
listener.getLogger().println(Messages.AbstractProject_ScmAborted());
LOGGER.log(Level.INFO,build.toString()+" aborted",e);
return false;
}
}
/**
* Checks if there's any update in SCM, and returns true if any is found.
*
* <p>
* The caller is responsible for coordinating the mutual exclusion between
* a build and polling, as both touches the workspace.
*/
public boolean pollSCMChanges( TaskListener listener ) {
SCM scm = getScm();
if(scm==null) {
listener.getLogger().println(Messages.AbstractProject_NoSCM());
return false;
}
if(isDisabled()) {
listener.getLogger().println(Messages.AbstractProject_Disabled());
return false;
}
try {
if(scm.requiresWorkspaceForPolling()) {
// lock the workspace of the last build
FilePath ws=null;
R lb = getLastBuild();
if (lb!=null) ws = lb.getWorkspace();
if (ws==null || !ws.exists()) {
// workspace offline. build now, or nothing will ever be built
Label label = getAssignedLabel();
if (label != null && label.isSelfLabel()) {
// if the build is fixed on a node, then attempting a build will do us
// no good. We should just wait for the slave to come back.
listener.getLogger().println(Messages.AbstractProject_NoWorkspace());
return false;
}
if (ws == null)
listener.getLogger().println(Messages.AbstractProject_WorkspaceOffline());
else
listener.getLogger().println(Messages.AbstractProject_NoWorkspace());
listener.getLogger().println(Messages.AbstractProject_NewBuildForWorkspace());
return true;
} else {
WorkspaceList l = lb.getBuiltOn().toComputer().getWorkspaceList();
// if doing non-concurrent build, acquite a workspace in a way that causes builds to block for this workspace.
// this prevents multiple workspaces of the same job --- the behavior of Hudson < 1.319.
//
// OTOH, if a concurrent build is chosen, the user is willing to create a multiple workspace,
// so better throughput is achieved over time (modulo the initial cost of creating that many workspaces)
// by having multiple workspaces
WorkspaceList.Lease lease = l.acquire(ws, !concurrentBuild);
try {
LOGGER.fine("Polling SCM changes of " + getName());
return scm.pollChanges(this, ws.createLauncher(listener), ws, listener);
} finally {
lease.release();
}
}
} else {
// polling without workspace
LOGGER.fine("Polling SCM changes of " + getName());
return scm.pollChanges(this, null, null, listener);
}
} catch (AbortException e) {
listener.fatalError(Messages.AbstractProject_Aborted());
LOGGER.log(Level.FINE, "Polling "+this+" aborted",e);
return false;
} catch (IOException e) {
e.printStackTrace(listener.fatalError(e.getMessage()));
return false;
} catch (InterruptedException e) {
e.printStackTrace(listener.fatalError(Messages.AbstractProject_PollingABorted()));
return false;
}
}
/**
* Returns true if this user has made a commit to this project.
*
* @since 1.191
*/
public boolean hasParticipant(User user) {
for( R build = getLastBuild(); build!=null; build=build.getPreviousBuild())
if(build.hasParticipant(user))
return true;
return false;
}
public SCM getScm() {
return scm;
}
public void setScm(SCM scm) {
this.scm = scm;
}
/**
* Adds a new {@link Trigger} to this {@link Project} if not active yet.
*/
public void addTrigger(Trigger<?> trigger) throws IOException {
addToList(trigger,triggers);
}
public void removeTrigger(TriggerDescriptor trigger) throws IOException {
removeFromList(trigger,triggers);
}
protected final synchronized <T extends Describable<T>>
void addToList( T item, List<T> collection ) throws IOException {
for( int i=0; i<collection.size(); i++ ) {
if(collection.get(i).getDescriptor()==item.getDescriptor()) {
// replace
collection.set(i,item);
save();
return;
}
}
// add
collection.add(item);
save();
}
protected final synchronized <T extends Describable<T>>
void removeFromList(Descriptor<T> item, List<T> collection) throws IOException {
for( int i=0; i< collection.size(); i++ ) {
if(collection.get(i).getDescriptor()==item) {
// found it
collection.remove(i);
save();
return;
}
}
}
public synchronized Map<TriggerDescriptor,Trigger> getTriggers() {
return (Map)Descriptor.toMap(triggers);
}
/**
* Gets the specific trigger, or null if the propert is not configured for this job.
*/
public <T extends Trigger> T getTrigger(Class<T> clazz) {
for (Trigger p : triggers) {
if(clazz.isInstance(p))
return clazz.cast(p);
}
return null;
}
//
//
// fingerprint related
//
//
/**
* True if the builds of this project produces {@link Fingerprint} records.
*/
public abstract boolean isFingerprintConfigured();
/**
* Gets the other {@link AbstractProject}s that should be built
* when a build of this project is completed.
*/
@Exported
public final List<AbstractProject> getDownstreamProjects() {
return Hudson.getInstance().getDependencyGraph().getDownstream(this);
}
@Exported
public final List<AbstractProject> getUpstreamProjects() {
return Hudson.getInstance().getDependencyGraph().getUpstream(this);
}
/**
* Returns only those upstream projects that defines {@link BuildTrigger} to this project.
* This is a subset of {@link #getUpstreamProjects()}
*
* @return A List of upstream projects that has a {@link BuildTrigger} to this project.
*/
public final List<AbstractProject> getBuildTriggerUpstreamProjects() {
ArrayList<AbstractProject> result = new ArrayList<AbstractProject>();
for (AbstractProject<?,?> ap : getUpstreamProjects()) {
BuildTrigger buildTrigger = ap.getPublishersList().get(BuildTrigger.class);
if (buildTrigger != null)
if (buildTrigger.getChildProjects().contains(this))
result.add(ap);
}
return result;
}
/**
* Gets all the upstream projects including transitive upstream projects.
*
* @since 1.138
*/
public final Set<AbstractProject> getTransitiveUpstreamProjects() {
return Hudson.getInstance().getDependencyGraph().getTransitiveUpstream(this);
}
/**
* Gets all the downstream projects including transitive downstream projects.
*
* @since 1.138
*/
public final Set<AbstractProject> getTransitiveDownstreamProjects() {
return Hudson.getInstance().getDependencyGraph().getTransitiveDownstream(this);
}
/**
* Gets the dependency relationship map between this project (as the source)
* and that project (as the sink.)
*
* @return
* can be empty but not null. build number of this project to the build
* numbers of that project.
*/
public SortedMap<Integer, RangeSet> getRelationship(AbstractProject that) {
TreeMap<Integer,RangeSet> r = new TreeMap<Integer,RangeSet>(REVERSE_INTEGER_COMPARATOR);
checkAndRecord(that, r, this.getBuilds());
// checkAndRecord(that, r, that.getBuilds());
return r;
}
/**
* Helper method for getDownstreamRelationship.
*
* For each given build, find the build number range of the given project and put that into the map.
*/
private void checkAndRecord(AbstractProject that, TreeMap<Integer, RangeSet> r, Collection<R> builds) {
for (R build : builds) {
RangeSet rs = build.getDownstreamRelationship(that);
if(rs==null || rs.isEmpty())
continue;
int n = build.getNumber();
RangeSet value = r.get(n);
if(value==null)
r.put(n,rs);
else
value.add(rs);
}
}
/**
* Builds the dependency graph.
* @see DependencyGraph
*/
protected abstract void buildDependencyGraph(DependencyGraph graph);
@Override
protected SearchIndexBuilder makeSearchIndex() {
SearchIndexBuilder sib = super.makeSearchIndex();
if(isBuildable() && hasPermission(Hudson.ADMINISTER))
sib.add("build","build");
return sib;
}
@Override
protected HistoryWidget createHistoryWidget() {
return new BuildHistoryWidget<R>(this,getBuilds(),HISTORY_ADAPTER);
}
public boolean isParameterized() {
return getProperty(ParametersDefinitionProperty.class) != null;
}
//
//
// actions
//
//
/**
* Schedules a new build command.
*/
public void doBuild( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
BuildAuthorizationToken.checkPermission(this, authToken, req, rsp);
// if a build is parameterized, let that take over
ParametersDefinitionProperty pp = getProperty(ParametersDefinitionProperty.class);
if (pp != null) {
pp._doBuild(req,rsp);
return;
}
Cause cause;
if (authToken != null && authToken.getToken() != null && req.getParameter("token") != null) {
// Optional additional cause text when starting via token
String causeText = req.getParameter("cause");
cause = new RemoteCause(req.getRemoteAddr(), causeText);
} else {
cause = new UserCause();
}
String delay = req.getParameter("delay");
if (delay!=null) {
if (!isDisabled()) {
try {
// TODO: more unit handling
if(delay.endsWith("sec")) delay=delay.substring(0,delay.length()-3);
if(delay.endsWith("secs")) delay=delay.substring(0,delay.length()-4);
Hudson.getInstance().getQueue().schedule(this, Integer.parseInt(delay),
new CauseAction(cause));
} catch (NumberFormatException e) {
throw new ServletException("Invalid delay parameter value: "+delay);
}
}
} else {
scheduleBuild(cause);
}
rsp.forwardToPreviousPage(req);
}
/**
* Supports build trigger with parameters via an HTTP GET or POST.
* Currently only String parameters are supported.
*/
public void doBuildWithParameters(StaplerRequest req, StaplerResponse rsp) throws IOException {
BuildAuthorizationToken.checkPermission(this, authToken, req, rsp);
ParametersDefinitionProperty pp = getProperty(ParametersDefinitionProperty.class);
if (pp != null) {
pp.buildWithParameters(req,rsp);
return;
} else {
throw new IllegalStateException("This build is not parameterized!");
}
}
/**
* Schedules a new SCM polling command.
*/
public void doPolling( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
BuildAuthorizationToken.checkPermission(this, authToken, req, rsp);
schedulePolling();
rsp.forwardToPreviousPage(req);
}
/**
* Cancels a scheduled build.
*/
public void doCancelQueue( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
checkPermission(BUILD);
Hudson.getInstance().getQueue().cancel(this);
rsp.forwardToPreviousPage(req);
}
@Override
protected void submit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException {
super.submit(req,rsp);
makeDisabled(req.getParameter("disable")!=null);
jdk = req.getParameter("jdk");
if(req.getParameter("hasCustomQuietPeriod")!=null) {
quietPeriod = Integer.parseInt(req.getParameter("quiet_period"));
} else {
quietPeriod = null;
}
if(req.getParameter("hasCustomScmCheckoutRetryCount")!=null) {
scmCheckoutRetryCount = Integer.parseInt(req.getParameter("scmCheckoutRetryCount"));
} else {
scmCheckoutRetryCount = null;
}
blockBuildWhenUpstreamBuilding = req.getParameter("blockBuildWhenUpstreamBuilding")!=null;
if(req.getParameter("hasSlaveAffinity")!=null) {
canRoam = false;
assignedNode = req.getParameter("slave");
if(assignedNode !=null) {
if(Hudson.getInstance().getLabel(assignedNode).isEmpty())
assignedNode = null; // no such label
}
} else {
canRoam = true;
assignedNode = null;
}
concurrentBuild = req.getSubmittedForm().has("concurrentBuild");
authToken = BuildAuthorizationToken.create(req);
setScm(SCMS.parseSCM(req,this));
for (Trigger t : triggers)
t.stop();
triggers = buildDescribable(req, Trigger.for_(this));
for (Trigger t : triggers)
t.start(this,true);
updateTransientActions();
}
/**
* @deprecated
* As of 1.261. Use {@link #buildDescribable(StaplerRequest, List)} instead.
*/
protected final <T extends Describable<T>> List<T> buildDescribable(StaplerRequest req, List<? extends Descriptor<T>> descriptors, String prefix) throws FormException, ServletException {
return buildDescribable(req,descriptors);
}
protected final <T extends Describable<T>> List<T> buildDescribable(StaplerRequest req, List<? extends Descriptor<T>> descriptors)
throws FormException, ServletException {
JSONObject data = req.getSubmittedForm();
List<T> r = new Vector<T>();
for (Descriptor<T> d : descriptors) {
String name = d.getJsonSafeClassName();
if (req.getParameter(name) != null) {
T instance = d.newInstance(req, data.getJSONObject(name));
r.add(instance);
}
}
return r;
}
/**
* Serves the workspace files.
*/
public DirectoryBrowserSupport doWs( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, InterruptedException {
checkPermission(AbstractProject.WORKSPACE);
FilePath ws = getSomeWorkspace();
if ((ws == null) || (!ws.exists())) {
// if there's no workspace, report a nice error message
// Would be good if when asked for *plain*, do something else!
// (E.g. return 404, or send empty doc.)
// Not critical; client can just check if content type is not text/plain,
// which also serves to detect old versions of Hudson.
req.getView(this,"noWorkspace.jelly").forward(req,rsp);
return null;
} else {
return new DirectoryBrowserSupport(this, ws, getDisplayName()+" workspace", "folder.gif", true);
}
}
/**
* Wipes out the workspace.
*/
public HttpResponse doDoWipeOutWorkspace() throws IOException, ServletException, InterruptedException {
checkPermission(BUILD);
R b = getSomeBuildWithWorkspace();
FilePath ws = b!=null ? b.getWorkspace() : null;
if (ws!=null && getScm().processWorkspaceBeforeDeletion(this, ws, b.getBuiltOn())) {
ws.deleteRecursive();
return new HttpRedirect(".");
} else {
// If we get here, that means the SCM blocked the workspace deletion.
return new ForwardToView(this,"wipeOutWorkspaceBlocked.jelly");
}
}
public HttpResponse doDisable() throws IOException, ServletException {
requirePOST();
checkPermission(CONFIGURE);
makeDisabled(true);
return new HttpRedirect(".");
}
public HttpResponse doEnable() throws IOException, ServletException {
requirePOST();
checkPermission(CONFIGURE);
makeDisabled(false);
return new HttpRedirect(".");
}
/**
* RSS feed for changes in this project.
*/
public void doRssChangelog( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
class FeedItem {
ChangeLogSet.Entry e;
int idx;
public FeedItem(Entry e, int idx) {
this.e = e;
this.idx = idx;
}
AbstractBuild<?,?> getBuild() {
return e.getParent().build;
}
}
List<FeedItem> entries = new ArrayList<FeedItem>();
for(R r=getLastBuild(); r!=null; r=r.getPreviousBuild()) {
int idx=0;
for( ChangeLogSet.Entry e : r.getChangeSet())
entries.add(new FeedItem(e,idx++));
}
RSS.forwardToRss(
getDisplayName()+' '+getScm().getDescriptor().getDisplayName()+" changes",
getUrl()+"changes",
entries, new FeedAdapter<FeedItem>() {
public String getEntryTitle(FeedItem item) {
return "#"+item.getBuild().number+' '+item.e.getMsg()+" ("+item.e.getAuthor()+")";
}
public String getEntryUrl(FeedItem item) {
return item.getBuild().getUrl()+"changes#detail"+item.idx;
}
public String getEntryID(FeedItem item) {
return getEntryUrl(item);
}
public String getEntryDescription(FeedItem item) {
StringBuilder buf = new StringBuilder();
for(String path : item.e.getAffectedPaths())
buf.append(path).append('\n');
return buf.toString();
}
public Calendar getEntryTimestamp(FeedItem item) {
return item.getBuild().getTimestamp();
}
public String getEntryAuthor(FeedItem entry) {
return Mailer.descriptor().getAdminAddress();
}
},
req, rsp );
}
/**
* {@link AbstractProject} subtypes should implement this base class as a descriptor.
*
* @since 1.294
*/
public static abstract class AbstractProjectDescriptor extends TopLevelItemDescriptor {
/**
* {@link AbstractProject} subtypes can override this method to veto some {@link Descriptor}s
* from showing up on their configuration screen. This is often useful when you are building
* a workflow/company specific project type, where you want to limit the number of choices
* given to the users.
*
* <p>
* Some {@link Descriptor}s define their own schemes for controlling applicability
* (such as {@link BuildStepDescriptor#isApplicable(Class)}),
* This method works like AND in conjunction with them;
* Both this method and that method need to return true in order for a given {@link Descriptor}
* to show up for the given {@link Project}.
*
* <p>
* The default implementation returns true for everything.
*
* @see BuildStepDescriptor#isApplicable(Class)
* @see BuildWrapperDescriptor#isApplicable(AbstractProject)
* @see TriggerDescriptor#isApplicable(Item)
*/
@Override
public boolean isApplicable(Descriptor descriptor) {
return true;
}
}
/**
* Finds a {@link AbstractProject} that has the name closest to the given name.
*/
public static AbstractProject findNearest(String name) {
List<AbstractProject> projects = Hudson.getInstance().getItems(AbstractProject.class);
String[] names = new String[projects.size()];
for( int i=0; i<projects.size(); i++ )
names[i] = projects.get(i).getName();
String nearest = EditDistance.findNearest(name, names);
return (AbstractProject)Hudson.getInstance().getItem(nearest);
}
private static final Comparator<Integer> REVERSE_INTEGER_COMPARATOR = new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
return o2-o1;
}
};
private static final Logger LOGGER = Logger.getLogger(AbstractProject.class.getName());
/**
* Permission to abort a build. For now, let's make it the same as {@link #BUILD}
*/
public static final Permission ABORT = BUILD;
}
| true | true | public void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
super.doConfigSubmit(req,rsp);
Set<AbstractProject> upstream = Collections.emptySet();
if(req.getParameter("pseudoUpstreamTrigger")!=null) {
upstream = new HashSet<AbstractProject>(Items.fromNameList(req.getParameter("upstreamProjects"),AbstractProject.class));
}
// dependency setting might have been changed by the user, so rebuild.
Hudson.getInstance().rebuildDependencyGraph();
// reflect the submission of the pseudo 'upstream build trriger'.
// this needs to be done after we release the lock on 'this',
// or otherwise we could dead-lock
for (AbstractProject<?,?> p : Hudson.getInstance().getAllItems(AbstractProject.class)) {
boolean isUpstream = upstream.contains(p);
synchronized(p) {
// does 'p' include us in its BuildTrigger?
DescribableList<Publisher,Descriptor<Publisher>> pl = p.getPublishersList();
BuildTrigger trigger = pl.get(BuildTrigger.class);
List<AbstractProject> newChildProjects = trigger == null ? new ArrayList<AbstractProject>():trigger.getChildProjects();
if(isUpstream) {
if(!newChildProjects.contains(this))
newChildProjects.add(this);
} else {
newChildProjects.remove(this);
}
if(newChildProjects.isEmpty()) {
pl.remove(BuildTrigger.class);
} else {
// here, we just need to replace the old one with the new one,
// but there was a regression (we don't know when it started) that put multiple BuildTriggers
// into the list.
// for us not to lose the data, we need to merge them all.
List<BuildTrigger> existingList = pl.getAll(BuildTrigger.class);
BuildTrigger existing;
switch (existingList.size()) {
case 0:
existing = null;
break;
case 1:
existing = existingList.get(0);
break;
default:
pl.removeAll(BuildTrigger.class);
Set<AbstractProject> combinedChildren = new HashSet<AbstractProject>();
for (BuildTrigger bt : existingList)
combinedChildren.addAll(bt.getChildProjects());
existing = new BuildTrigger(new ArrayList<AbstractProject>(combinedChildren),existingList.get(0).getThreshold());
pl.add(existing);
break;
}
if(existing!=null && existing.hasSame(newChildProjects))
continue; // no need to touch
pl.replace(new BuildTrigger(newChildProjects,
existing==null?Result.SUCCESS:existing.getThreshold()));
}
}
}
// notify the queue as the project might be now tied to different node
Hudson.getInstance().getQueue().scheduleMaintenance();
// this is to reflect the upstream build adjustments done above
Hudson.getInstance().rebuildDependencyGraph();
}
| public void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
super.doConfigSubmit(req,rsp);
Set<AbstractProject> upstream = Collections.emptySet();
if(req.getParameter("pseudoUpstreamTrigger")!=null) {
upstream = new HashSet<AbstractProject>(Items.fromNameList(req.getParameter("upstreamProjects"),AbstractProject.class));
}
// dependency setting might have been changed by the user, so rebuild.
Hudson.getInstance().rebuildDependencyGraph();
// reflect the submission of the pseudo 'upstream build trriger'.
// this needs to be done after we release the lock on 'this',
// or otherwise we could dead-lock
for (AbstractProject<?,?> p : Hudson.getInstance().getAllItems(AbstractProject.class)) {
// Don't consider child projects such as MatrixConfiguration:
if (!p.isConfigurable()) continue;
boolean isUpstream = upstream.contains(p);
synchronized(p) {
// does 'p' include us in its BuildTrigger?
DescribableList<Publisher,Descriptor<Publisher>> pl = p.getPublishersList();
BuildTrigger trigger = pl.get(BuildTrigger.class);
List<AbstractProject> newChildProjects = trigger == null ? new ArrayList<AbstractProject>():trigger.getChildProjects();
if(isUpstream) {
if(!newChildProjects.contains(this))
newChildProjects.add(this);
} else {
newChildProjects.remove(this);
}
if(newChildProjects.isEmpty()) {
pl.remove(BuildTrigger.class);
} else {
// here, we just need to replace the old one with the new one,
// but there was a regression (we don't know when it started) that put multiple BuildTriggers
// into the list.
// for us not to lose the data, we need to merge them all.
List<BuildTrigger> existingList = pl.getAll(BuildTrigger.class);
BuildTrigger existing;
switch (existingList.size()) {
case 0:
existing = null;
break;
case 1:
existing = existingList.get(0);
break;
default:
pl.removeAll(BuildTrigger.class);
Set<AbstractProject> combinedChildren = new HashSet<AbstractProject>();
for (BuildTrigger bt : existingList)
combinedChildren.addAll(bt.getChildProjects());
existing = new BuildTrigger(new ArrayList<AbstractProject>(combinedChildren),existingList.get(0).getThreshold());
pl.add(existing);
break;
}
if(existing!=null && existing.hasSame(newChildProjects))
continue; // no need to touch
pl.replace(new BuildTrigger(newChildProjects,
existing==null?Result.SUCCESS:existing.getThreshold()));
}
}
}
// notify the queue as the project might be now tied to different node
Hudson.getInstance().getQueue().scheduleMaintenance();
// this is to reflect the upstream build adjustments done above
Hudson.getInstance().rebuildDependencyGraph();
}
|
diff --git a/graph/src/main/java/edu/jhuapl/graphs/controller/GraphController.java b/graph/src/main/java/edu/jhuapl/graphs/controller/GraphController.java
old mode 100644
new mode 100755
index 4f5a012..c93905e
--- a/graph/src/main/java/edu/jhuapl/graphs/controller/GraphController.java
+++ b/graph/src/main/java/edu/jhuapl/graphs/controller/GraphController.java
@@ -1,1199 +1,1199 @@
/*
* Copyright (c) 2013 The Johns Hopkins University/Applied Physics Laboratory
* All rights reserved.
*
* This material may be used, modified, or reproduced by or for the U.S.
* Government pursuant to the rights granted under the clauses at
* DFARS 252.227-7013/7014 or FAR 52.227-14.
*
* 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
*
* NO WARRANTY. THIS MATERIAL IS PROVIDED "AS IS." JHU/APL DISCLAIMS ALL
* WARRANTIES IN THE MATERIAL, WHETHER EXPRESS OR IMPLIED, INCLUDING (BUT NOT
* LIMITED TO) ANY AND ALL IMPLIED WARRANTIES OF PERFORMANCE,
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT OF
* INTELLECTUAL PROPERTY RIGHTS. ANY USER OF THE MATERIAL ASSUMES THE ENTIRE
* RISK AND LIABILITY FOR USING THE MATERIAL. IN NO EVENT SHALL JHU/APL BE
* LIABLE TO ANY USER OF THE MATERIAL FOR ANY ACTUAL, INDIRECT,
* CONSEQUENTIAL, SPECIAL OR OTHER DAMAGES ARISING FROM THE USE OF, OR
* INABILITY TO USE, THE MATERIAL, INCLUDING, BUT NOT LIMITED TO, ANY DAMAGES
* FOR LOST PROFITS.
*/
package edu.jhuapl.graphs.controller;
import edu.jhuapl.graphs.DataPoint;
import edu.jhuapl.graphs.DataSeries;
import edu.jhuapl.graphs.Encoding;
import edu.jhuapl.graphs.GraphException;
import edu.jhuapl.graphs.GraphSource;
import edu.jhuapl.graphs.PointInterface;
import edu.jhuapl.graphs.RenderedGraph;
import edu.jhuapl.graphs.jfreechart.JFreeChartBarGraphSource;
import edu.jhuapl.graphs.jfreechart.JFreeChartCategoryGraphSource;
import edu.jhuapl.graphs.jfreechart.JFreeChartGraphSource;
import edu.jhuapl.graphs.jfreechart.utils.CustomLabelNumberAxis;
import edu.jhuapl.graphs.jfreechart.utils.SparselyLabeledCategoryAxis;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.LegendItem;
import org.jfree.chart.LegendItemCollection;
import org.jfree.chart.axis.AxisLocation;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.plot.PlotOrientation;
import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class GraphController {
private static final int defaultMaxLegendItems = 50;
private static final int maxCategoryLabelWidthRatio = 15;
private static final Color noDataColor = Color.GRAY;
private static final Color warningDataColor = Color.YELLOW;
private static final Color alertDataColor = Color.RED;
private static final Color severeDataColor = Color.MAGENTA;
private static final Font graphFont = new Font("Arial", Font.BOLD, 14);
private static final Font rangeAxisFont = new Font("Arial", Font.BOLD, 12);
private static final Font rangeAxisLabelFont = new Font("Arial", Font.BOLD, 12);
private static final Font domainAxisFont = new Font("Arial", Font.PLAIN, 11);
private static final Font domainAxisLabelFont = new Font("Arial", Font.BOLD, 12);
private static final Font legendFont = new Font("Arial", Font.PLAIN, 11);
private String graphDataId = null;
private GraphDataHandlerInterface graphDataHandler = null;
private int maxLegendItems = defaultMaxLegendItems;
private Map<String, String> translationMap = new HashMap<String, String>(0);
public GraphController(String graphDataId, GraphDataHandlerInterface graphDataHandler, String userId) {
if (graphDataId != null && graphDataId.length() > 0) {
this.graphDataId = graphDataId;
} else {
this.graphDataId = getUniqueId(userId);
}
this.graphDataHandler = graphDataHandler;
}
public Map<String, String> getTranslationMap() {
if (translationMap == null) {
translationMap = new HashMap<String, String>(0);
}
return translationMap;
}
/**
* Set a key value map to be used for translations.
*/
public void setTranslationMap(Map<String, String> translationMap) {
this.translationMap = translationMap;
}
/**
* Returns a translation of <code>word</code> if available. Note: matches case.
*
* @return a translation from translationMap or <code>word</code>
*/
protected String getTranslation(String word) {
if (getTranslationMap() != null && getTranslationMap().containsKey(word)) {
return getTranslationMap().get(word);
}
return word;
}
public String getGraphDataId() {
return graphDataId;
}
/**
* @param maxLegendItems Maximum number of items to display in the legend
*/
public void setMaxLegendItems(int maxLegendItems) {
this.maxLegendItems = maxLegendItems;
}
public GraphObject writeTimeSeriesGraph(PrintWriter out, GraphDataInterface graphData, boolean useImageMap,
boolean includeFooter, String callBackURL, boolean graphExpected) {
StringBuffer sb = new StringBuffer();
GraphObject graph = writeTimeSeriesGraph(sb, graphData, useImageMap, includeFooter, callBackURL, graphExpected);
out.println(sb);
return graph;
}
public GraphObject writeTimeSeriesGraph(StringBuffer sb, GraphDataInterface graphData, boolean useImageMap,
boolean includeFooter, String callBackURL, boolean graphExpected) {
return writeTimeSeriesGraph(sb, graphData, useImageMap, includeFooter, true, callBackURL, graphExpected);
}
public GraphObject writeTimeSeriesGraph(StringBuffer sb, GraphDataInterface graphData, boolean useImageMap,
boolean includeFooter, boolean includeButtons, String callBackURL,
boolean graphExpected) {
GraphObject graph = createTimeSeriesGraph(graphData, graphExpected);
writeGraph(sb, graphData, useImageMap, includeFooter, includeButtons, callBackURL, null, null, graph);
return graph;
}
public void dumpWriteTsGraph(PrintWriter out, GraphDataInterface graphData, boolean includeFooter,
String callBackURL) {
StringBuffer sb = new StringBuffer();
dumpWriteTsGraph(sb, graphData, includeFooter, callBackURL);
out.println(sb);
return;
}
public void dumpWriteTsGraph(StringBuffer sb, GraphDataInterface graphData, boolean includeFooter,
String callBackURL) {
Map<String, Object> graphMetaData = dumpGraph(graphData);
writeGraph(sb, graphData, includeFooter, callBackURL, "imageMap" + graphDataId, null, null, graphMetaData);
}
public void dumpWriteTsGraph(PrintWriter out, GraphDataInterface graphData, boolean includeFooter,
String callBackURL, String graphURL) {
StringBuffer sb = new StringBuffer();
dumpWriteTsGraph(sb, graphData, includeFooter, callBackURL, graphURL);
out.println(sb);
return;
}
public void dumpWriteTsGraph(StringBuffer sb, GraphDataInterface graphData, boolean includeFooter,
String callBackURL, String graphURL) {
Map<String, Object> graphMetaData = dumpGraph(graphData);
writeGraph(sb, graphData, includeFooter, graphURL, callBackURL, "imageMap" + graphDataId, null, null,
graphMetaData);
}
public GraphObject writePieGraph(PrintWriter out, GraphDataInterface graphData, boolean useImageMap,
String callBackURL) {
StringBuffer sb = new StringBuffer();
GraphObject graph = writePieGraph(sb, graphData, useImageMap, callBackURL);
out.println(sb);
return graph;
}
public GraphObject writePieGraph(StringBuffer sb, GraphDataInterface graphData, boolean useImageMap,
String callBackURL) {
GraphObject graph = createPieGraph(graphData);
writeGraph(sb, graphData, useImageMap, false, false, callBackURL, null, null, graph);
return graph;
}
public GraphObject writeBarGraph(PrintWriter out, GraphDataInterface graphData, boolean stackGraph,
boolean useImageMap, String callBackURL) {
StringBuffer sb = new StringBuffer();
GraphObject graph = writeBarGraph(sb, graphData, stackGraph, useImageMap, callBackURL);
out.println(sb);
return graph;
}
public GraphObject writeBarGraph(StringBuffer sb, GraphDataInterface graphData, boolean stackGraph,
boolean useImageMap, String callBackURL) {
GraphObject graph = createBarGraph(graphData, stackGraph);
writeGraph(sb, graphData, useImageMap, false, false, callBackURL, null, null, graph);
return graph;
}
public GraphObject writeSeverityGraph(PrintWriter out, GraphDataInterface graphData, boolean useImageMap,
String callBackURL) {
StringBuffer sb = new StringBuffer();
GraphObject graph = writeSeverityGraph(sb, graphData, useImageMap, callBackURL);
out.println(sb);
return graph;
}
public GraphObject writeSeverityGraph(StringBuffer sb, GraphDataInterface graphData, boolean useImageMap,
String callBackURL) {
GraphObject graph = createSeverityGraph(graphData);
writeGraph(sb, graphData, useImageMap, false, false, callBackURL, null, null, graph);
return graph;
}
public GraphObject writeDualAxisGraph(PrintWriter out, GraphDataInterface graphData,
boolean useImageMap, String callBackURL) {
StringBuffer sb = new StringBuffer();
GraphObject graph = writeDualAxisGraph(sb, graphData, useImageMap, callBackURL);
out.println(sb);
return graph;
}
public GraphObject writeDualAxisGraph(StringBuffer sb, GraphDataInterface graphData,
boolean useImageMap, String callBackURL) {
GraphObject graph = createDualAxisGraph(graphData);
writeGraph(sb, graphData, useImageMap, false, false, callBackURL, null, null, graph);
return graph;
}
public GraphObject createTimeSeriesGraph(GraphDataInterface graphData, boolean graphExpected) {
return createTimeSeriesGraph(graphData, null, null, null, graphExpected);
}
public GraphObject createTimeSeriesGraph(GraphDataInterface graphData, Double yAxisMin, Double yAxisMax,
String displayKey, boolean graphExpected) {
List<DataSeries> dataSeries = new ArrayList<DataSeries>();
LegendItemCollection legendItems = new LegendItemCollection();
Map<String, Object> graphMetaData = new HashMap<String, Object>();
double maxCount = setDataSeries(graphData, displayKey, false, dataSeries, legendItems, graphExpected);
setTimeSeriesGraphMetaData(graphData, yAxisMin, yAxisMax, maxCount, graphMetaData);
return getGraph(graphData, dataSeries, graphMetaData, legendItems, "tsgraph");
}
public GraphObject createBarGraph(GraphDataInterface graphData, boolean stackGraph) {
return createBarGraph(graphData, stackGraph, false);
}
/**
* The useItemColor is still under development to allow each bar to be a different color.
*/
public GraphObject createBarGraph(GraphDataInterface graphData, boolean stackGraph, boolean useItemColor) {
List<DataSeries> dataSeries = new ArrayList<DataSeries>();
LegendItemCollection legendItems = new LegendItemCollection();
Map<String, Object> graphMetaData = new HashMap<String, Object>();
setDataSeries(graphData, null, false, dataSeries, legendItems, useItemColor);
setBarGraphMetaData(graphData, stackGraph, graphMetaData);
return getGraph(graphData, dataSeries, graphMetaData, legendItems, "bargraph");
}
public GraphObject createPieGraph(GraphDataInterface graphData) {
return createPieGraph(graphData, Encoding.PNG);
}
public GraphObject createPieGraph(GraphDataInterface graphData, Encoding encoding) {
GraphObject graph = null;
Map<String, Object> graphMetaData = new HashMap<String, Object>();
List<PointInterface> points = new ArrayList<PointInterface>();
setPieGraphMetaData(graphData, graphMetaData, points); // I'm ashamed of this code in so many ways
String graphTitle = (String) graphMetaData.get(GraphSource.GRAPH_TITLE);
try {
// add the created chart properties
JFreeChartGraphSource graphSource = new JFreeChartGraphSource();
graphSource.setData(Arrays.asList(new DataSeries(points, new HashMap<String, Object>())));
graphSource.setParams(graphMetaData);
graphSource.initialize();
if (graphData.showLegend()) {
PiePlot plot = (PiePlot) graphSource.getChart().getPlot();
// use rectangles as the legend shapes
plot.setLegendItemShape(new Rectangle(7, 8));
// generate tooltip for the legend items in the following format: "lineSetLabels - count"
if (graphData.percentBased()) {
plot.setLegendLabelToolTipGenerator(new StandardPieSectionLabelGenerator("{0} - {1} ({2})",
new DecimalFormat("#.##"),
new DecimalFormat(
"#.##%")));
} else {
plot.setLegendLabelToolTipGenerator(new StandardPieSectionLabelGenerator("{0} - {1} ({2})",
new DecimalFormat("#"),
new DecimalFormat(
"#.##%")));
}
}
// render the graph to get the image map
RenderedGraph
renderedGraph =
graphSource.renderGraph(graphData.getGraphWidth(), graphData.getGraphHeight(), encoding);
String extension = ".dat";
switch (encoding) {
case JPEG:
extension = ".jpg";
break;
case PNG:
case PNG_WITH_TRANSPARENCY:
extension = ".png";
break;
}
String imageFileName = getCleanValue(graphTitle) + "_piegraph" + extension;
// get the image map
String imageMapName = "imageMap" + graphDataId;
String imageMap = appendImageMapTarget(renderedGraph.getImageMap(imageMapName),
graphData.getLineSetURLTarget());
try {
// store away the graph data file
graphDataHandler.putGraphData(graphData, graphDataId);
graph = new GraphObject(graphSource, renderedGraph, imageFileName, imageMapName, imageMap, graphDataId);
} catch (GraphException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
} catch (GraphException e) {
System.out.println("Could not create pie graph " + graphTitle);
e.printStackTrace();
}
return graph;
}
public GraphObject createSeverityGraph(GraphDataInterface graphData) {
List<DataSeries> dataSeries = new ArrayList<DataSeries>();
Map<String, Object> graphMetaData = new HashMap<String, Object>();
LegendItemCollection legendItems = new LegendItemCollection();
Color[] graphBaseColors = graphData.getGraphBaseColors();
Map<Double, String> tickValueToLabelMapping = new HashMap<Double, String>();
setDataSeries(graphData, null, true, dataSeries, null, false);
setBarGraphMetaData(graphData, true, graphMetaData);
// create a custom legend
legendItems.add(new LegendItem(getTranslation("Severe"), severeDataColor));
legendItems.add(new LegendItem(getTranslation("Not Severe"), graphBaseColors[0]));
legendItems.add(new LegendItem(getTranslation("No Data Available"), noDataColor));
// create custom value axis labels
String[] lineSetLabels = graphData.getLineSetLabels();
double lowestTickValue = 0.5;
int tickCount = lineSetLabels.length;
for (int i = 0; i < tickCount; i++) {
tickValueToLabelMapping.put(lowestTickValue + i, lineSetLabels[i]);
}
CustomLabelNumberAxis rangeAxis = new CustomLabelNumberAxis(tickValueToLabelMapping);
rangeAxis.setLowestTickValue(lowestTickValue);
rangeAxis.setTickCount(tickCount);
graphMetaData.put(JFreeChartCategoryGraphSource.RANGE_AXIS, rangeAxis);
return getGraph(graphData, dataSeries, graphMetaData, legendItems, "tsgraph");
}
public GraphObject createDualAxisGraph(GraphDataInterface graphData) {
List<DataSeries> dataSeries = new ArrayList<DataSeries>();
LegendItemCollection legendItems = new LegendItemCollection();
Map<String, Object> graphMetaData = new HashMap<String, Object>();
double maxCount = setDataSeries(graphData, null, false, dataSeries, legendItems, false);
setTimeSeriesGraphMetaData(graphData, null, null, maxCount, graphMetaData);
setBarGraphMetaData(graphData, false, graphMetaData);
graphMetaData.put(GraphSource.GRAPH_TYPE, GraphSource.GRAPH_TYPE_DUAL_AXIS);
return getGraph(graphData, dataSeries, graphMetaData, legendItems, "dualAxisGraph");
}
public static String zipGraphs(List<GraphObject> graphs, String tempDir, String userId) throws GraphException {
if (graphs != null && graphs.size() > 0) {
byte[] byteBuffer = new byte[1024];
String zipFileName = getUniqueId(userId) + ".zip";
try {
File zipFile = new File(tempDir, zipFileName);
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));
boolean hasGraphs = false;
for (GraphObject graph : graphs) {
if (graph != null) {
byte[] renderedGraph = graph.getRenderedGraph().getData();
ByteArrayInputStream in = new ByteArrayInputStream(renderedGraph);
int len;
zos.putNextEntry(new ZipEntry(graph.getImageFileName()));
while ((len = in.read(byteBuffer)) > 0) {
zos.write(byteBuffer, 0, len);
}
in.close();
zos.closeEntry();
hasGraphs = true;
}
}
zos.close();
if (hasGraphs) {
return zipFileName;
} else {
return null;
}
} catch (IOException e) {
throw new GraphException("Could not write zip", e);
}
}
return null;
}
private void writeSimpleLinkTSGraph(StringBuffer sb, GraphDataInterface graphData, String callbackURL,
String linkURL, GraphObject graph) {
int graphWidth = graphData.getGraphWidth();
int graphHeight = graphData.getGraphHeight();
sb.append("<div style=\"background-color:white; width:" + graphWidth + "px; height:" + graphHeight +
"px;\">\n");
sb.append("<a href=\"").append(linkURL).append("\">");
String graphURL = callbackURL + "?graphDataId=" + graphDataId;
;
sb.append("<img src=\"").append(graphURL).append("\" title=\"").append(graphData.getGraphTitle())
.append("\" border=\"0\"/></a>").append("</div>\n");
}
private void writeGraph(StringBuffer sb, GraphDataInterface graphData, boolean useImageMap, boolean includeFooter,
String callBackURL, String graphOptionsHelpLink, String downloadHelpLink,
GraphObject graph) {
writeGraph(sb, graphData, useImageMap, includeFooter, true, callBackURL, graphOptionsHelpLink, downloadHelpLink,
graph);
}
private void writeGraph(StringBuffer sb, GraphDataInterface graphData, boolean useImageMap, boolean includeFooter,
boolean includeButtons,
String callBackURL, String graphOptionsHelpLink, String downloadHelpLink,
GraphObject graph) {
int graphWidth = graphData.getGraphWidth();
int graphHeight = graphData.getGraphHeight();
String imageMapName = graph.getImageMapName();
String graphURL = callBackURL + (callBackURL.indexOf('?') > -1 ? "&" : "?")
+ "graphDataId=" + graphDataId;
sb.append("<div style=\"background-color:white; width:" + graphWidth + "px\">\n");
sb.append("<div id=\"graphDiv" + imageMapName + "\" style=\"width:" + graphWidth + "px; height:" + graphHeight +
"px;\">\n");
if (useImageMap) {
// write the graph with an image map
sb.append(graph.getImageMap());
sb.append("<img src=\"" + graphURL + "\" usemap=\"#" + imageMapName + "\" border=\"0\"/>\n");
} else {
// just write the graph with the option to turn it into an interactive graph
sb.append("<img src=\"" + graphURL +
"\" title=\"Switch to Interactive View\" onclick=\"makeInteractiveGraph('" + callBackURL + "', '"
+
imageMapName + "', '" + graphDataId + "');\" border=\"0\"/>\n");
}
sb.append("</div>\n");
JFreeChart chart = graph.getGraphSource().getChart();
String graphTitle = chart.getTitle().getText();
String xAxisLabel = "";
String yAxisLabel = "";
double yAxisMin = 0;
double yAxisMax = 0;
if (chart.getPlot() instanceof CategoryPlot) {
CategoryPlot plot = chart.getCategoryPlot();
xAxisLabel = plot.getDomainAxis().getLabel();
yAxisLabel = plot.getRangeAxis().getLabel();
// get the y-axis minimum and maximum range
yAxisMin = plot.getRangeAxis().getRange().getLowerBound();
yAxisMax = plot.getRangeAxis().getRange().getUpperBound();
// get the y-axis minimum and maximum range
graph.setYAxisMin(yAxisMin);
graph.setYAxisMax(yAxisMax);
//set series information for configuration
graph.setDataSeriesJSON(getDataSeriesJSON(graphData.getLineSetLabels(), graphData.displayAlerts(),
graphData.displaySeverityAlerts(), "\""));
}
//added option to not bring back the button area - cjh
if (includeButtons) {
// write the footer
sb.append("<div style=\"padding:5px; text-align:center;\">\n");
if (includeFooter) {
//this keys it to be a timeseries graph so we can do getCategoryPlot
String dataSeriesJSON = getDataSeriesJSON(graphData.getLineSetLabels(), graphData.displayAlerts(),
graphData.displaySeverityAlerts(), """);
sb.append(
"<input type=\"button\" style=\"font-family:Arial; font-size:0.6em;\" value=\"Graph Options\" onclick=\"showTimeSeriesGraphOptions('"
+
callBackURL + "', '" + imageMapName + "', '" + graphDataId + "', '" + graphTitle + "', '" +
xAxisLabel + "', '" + yAxisLabel + "', " + yAxisMin + ", " + yAxisMax + ", '" + dataSeriesJSON +
"');\"/>");
if (graphOptionsHelpLink != null) {
sb.append(graphOptionsHelpLink);
}
}
sb.append(
"<input type=\"button\" style=\"font-family:Arial; font-size:0.6em;\" value=\"Download\" onclick=\"showDownloadOptions('"
+
callBackURL + "', '" + imageMapName + "', '" + graphDataId + "');\"/>");
if (downloadHelpLink != null) {
sb.append(downloadHelpLink);
}
sb.append("</div>\n");
}
sb.append("</div>\n");
if (!useImageMap) {
sb.append("<div id=\"linkDiv" + imageMapName +
"\" style=\"font-family: Arial; font-size: 0.7em; text-align: right\">\n");
sb.append("*Click anywhere on the graph to <a href=\"#\" onclick=\"makeInteractiveGraph('" + callBackURL +
"', '" + imageMapName + "', '" + graphDataId +
"'); return false;\">switch to interactive view</a>\n");
sb.append("</div>\n");
}
}
private void writeGraph(StringBuffer sb, GraphDataInterface graphData, boolean includeFooter,
String callBackURL, String imageMapName, String graphOptionsHelpLink,
String downloadHelpLink, Map<String, Object> graphMetaData) {
writeGraph(sb, graphData, includeFooter, callBackURL + "?graphDataId=" + graphDataId, callBackURL, imageMapName,
graphOptionsHelpLink, downloadHelpLink, graphMetaData);
}
public void writeGraph(StringBuffer sb, GraphDataInterface graphData, boolean includeFooter,
String graphURL, String callBackURL, String imageMapName, String graphOptionsHelpLink,
String downloadHelpLink, Map<String, Object> graphMetaData) {
int graphWidth = graphData.getGraphWidth();
int graphHeight = graphData.getGraphHeight();
sb.append("<div style=\"background-color:white; width:" + graphWidth + "px\">\n");
sb.append("<div id=\"graphDiv" + imageMapName + "\" style=\"width:" + graphWidth + "px; height:" + graphHeight +
"px;\">\n");
// just write the graph with the option to turn it into an interactive graph
sb.append("<img src=\"" + graphURL +
"\" title=\"Switch to Interactive View\" onclick=\"makeInteractiveGraph('" + callBackURL + "', '" +
imageMapName + "', '" + graphDataId + "');\" border=\"0\"/>\n");
sb.append("</div>\n");
// write the footer
sb.append("<div style=\"padding:5px; text-align:center;\">\n");
if (includeFooter) {
String graphTitle = (String) graphMetaData.get(GraphSource.GRAPH_TITLE);
String xAxisLabel = (String) graphMetaData.get(GraphSource.GRAPH_X_LABEL);
String yAxisLabel = (String) graphMetaData.get(GraphSource.GRAPH_Y_LABEL);
String dataSeriesJSON = getDataSeriesJSON(graphData.getLineSetLabels(), graphData.displayAlerts(),
graphData.displaySeverityAlerts(), """);
// get the y-axis minimum and maximum range
double yAxisMin = (Double) graphMetaData.get(GraphSource.GRAPH_RANGE_LOWER_BOUND);
double yAxisMax = (Double) graphMetaData.get(GraphSource.GRAPH_RANGE_UPPER_BOUND);
sb.append(
"<input type=\"button\" style=\"font-family:Arial; font-size:0.6em;\" value=\"Graph Options\" onclick=\"showTimeSeriesGraphOptions('"
+
callBackURL + "', '" + imageMapName + "', '" + graphDataId + "', '" + graphTitle + "', '" +
xAxisLabel + "', '" + yAxisLabel + "', " + yAxisMin + ", " + yAxisMax + ", '" + dataSeriesJSON +
"');\"/>");
if (graphOptionsHelpLink != null) {
sb.append(graphOptionsHelpLink);
}
}
sb.append(
"<input type=\"button\" style=\"font-family:Arial; font-size:0.6em;\" value=\"Download\" onclick=\"showDownloadOptions('"
+
callBackURL + "', '" + imageMapName + "', '" + graphDataId + "');\"/>");
if (downloadHelpLink != null) {
sb.append(downloadHelpLink);
}
sb.append("</div>\n");
sb.append("</div>\n");
sb.append("<div id=\"linkDiv" + imageMapName +
"\" style=\"font-family: Arial; font-size: 0.7em; text-align: right\">\n");
sb.append("*Click anywhere on the graph to <a href=\"#\" onclick=\"makeInteractiveGraph('" + callBackURL +
"', '" + imageMapName + "', '" + graphDataId +
"'); return false;\">switch to interactive view</a>\n");
sb.append("</div>\n");
}
private double setDataSeries(GraphDataInterface graphData, String displayKey, boolean useNoDataColor,
List<DataSeries> dataSeries, LegendItemCollection legendItems, boolean graphExpected) {
return setDataSeries(graphData, displayKey, useNoDataColor, dataSeries, legendItems, false, graphExpected);
}
/**
* The useItemColor is still under development to allow each bar to be a different color.
*/
private double setDataSeries(GraphDataInterface graphData, String displayKey, boolean useNoDataColor,
List<DataSeries> dataSeries, LegendItemCollection legendItems, boolean useItemColor,
boolean graphExpected) {
double[][] counts = graphData.getCounts();
double[][] expecteds = graphData.getExpecteds();
int[][] colors = graphData.getColors();
String[][] altTexts = graphData.getAltTexts();
String[][] lineSetURLs = graphData.getLineSetURLs();
String[] xLabels = graphData.getXLabels();
String[] lineSetLabels = graphData.getLineSetLabels();
boolean[] displayAlerts = graphData.displayAlerts();
boolean[] displaySeverityAlerts = graphData.displaySeverityAlerts();
double[] lineSymbolSizes = graphData.getLineSymbolSizes();
Color[] graphBaseColors = graphData.getGraphBaseColors();
int displayKeyIndex = 0;
double maxCount = 0;
boolean singleAlertLegend = graphData.getShowSingleAlertLegend();
boolean singleSeverityLegend = graphData.getShowSingleSeverityLegend();
for (int i = 0; i < counts.length; i++) {
String lineSetLabel = "series" + (i + 1);
boolean displayAlert = false;
boolean displaySeverityAlert = false;
double lineSymbolSize = 7.0;
try {
lineSetLabel = lineSetLabels[i];
} catch (Exception e) {
}
try {
displayAlert = displayAlerts[i];
} catch (Exception e) {
}
try {
displaySeverityAlert = displaySeverityAlerts[i];
} catch (Exception e) {
}
try {
lineSymbolSize = lineSymbolSizes[i];
} catch (Exception e) {
}
double xy = lineSymbolSize / 2.0 * -1;
Color seriesColor = graphBaseColors[i % graphBaseColors.length];
boolean displayNormalData = displaySeries(displayKey, displayKeyIndex++) ? true : false;
boolean displayWarningData = displayAlert && displaySeries(displayKey, displayKeyIndex++) ? true : false;
boolean displayAlertData = displayAlert && displaySeries(displayKey, displayKeyIndex++) ? true : false;
boolean displaySevereData = displaySeverityAlert &&
displaySeries(displayKey, displayKeyIndex++) ? true : false;
List<DataPoint> points = new ArrayList<DataPoint>();
List<DataPoint> epoints = new ArrayList<DataPoint>();
/** get graph data */
for (int j = 0; j < counts[i].length; j++) {
boolean alertDataExists = false;
String altText = null;
String lineSetURL = null;
int color = 1;
try {
altText = altTexts[i][j];
} catch (Exception e) {
}
try {
lineSetURL = lineSetURLs[i][j];
} catch (Exception e) {
}
try {
color = colors[i][j];
} catch (Exception e) {
}
Map<String, Object> epointMetaData = new HashMap<String, Object>();
Map<String, Object> pointMetaData = new HashMap<String, Object>();
pointMetaData.put(GraphSource.ITEM_TOOL_TIP, altText);
pointMetaData.put(GraphSource.ITEM_URL, lineSetURL);
pointMetaData.put(GraphSource.ITEM_SHAPE, new Ellipse2D.Double(xy, xy, lineSymbolSize, lineSymbolSize));
pointMetaData.put(GraphSource.ITEM_COLOR, seriesColor);
epointMetaData.put(GraphSource.ITEM_COLOR, seriesColor.brighter());
epointMetaData.put(GraphSource.ITEM_SHAPE, new Rectangle2D.Double(xy, xy, 7, 7));
epointMetaData.put(GraphSource.ITEM_TOOL_TIP, altText);
// color 0 = GRAY (no data), color 2 = YELLOW (warning), 3 = RED (alert),
// 4 = PURPLE (severe)
if (useNoDataColor && color == 0) {
pointMetaData.put(GraphSource.ITEM_COLOR, noDataColor);
} else if (displayWarningData && color == 2) {
alertDataExists = true;
pointMetaData.put(GraphSource.ITEM_COLOR, warningDataColor);
} else if (displayAlertData && color == 3) {
alertDataExists = true;
pointMetaData.put(GraphSource.ITEM_COLOR, alertDataColor);
} else if (displaySevereData && color == 4) {
alertDataExists = true;
pointMetaData.put(GraphSource.ITEM_COLOR, severeDataColor);
}
if (useItemColor) {
seriesColor = graphBaseColors[j % graphBaseColors.length];
pointMetaData.put(GraphSource.ITEM_COLOR, seriesColor);
}
if (displayNormalData || alertDataExists) {
// only update the maxCount if this data point is visible
if (counts[i][j] > maxCount) {
maxCount = counts[i][j];
}
} else {
// if normal data is supposed to be hidden and no alert data exists, then hide this
// data point
pointMetaData.put(GraphSource.ITEM_VISIBLE, false);
epointMetaData.put(GraphSource.ITEM_VISIBLE, false);
}
// if the data is set to the Double.MIN_VALUE, then add it as a null.
if (counts[i][j] != Double.MIN_VALUE) {
points.add(new DataPoint(counts[i][j], xLabels[j], pointMetaData));
} else {
points.add(new DataPoint(null, xLabels[j], pointMetaData));
}
- if (expecteds[i][j] != Double.MIN_VALUE) {
+ if (expecteds != null && expecteds[i][j] != Double.MIN_VALUE) {
epoints.add(new DataPoint(expecteds[i][j], xLabels[j], epointMetaData));
} else {
epoints.add(new DataPoint(null, xLabels[j], epointMetaData));
}
}
/** add the series */
// series properties
Map<String, Object> dataSeriesMetaData = new HashMap<String, Object>();
dataSeriesMetaData.put(GraphSource.SERIES_TITLE, lineSetLabel);
dataSeriesMetaData.put(GraphSource.SERIES_COLOR, seriesColor);
// if normal data is hidden for this series, hide the series connector line
dataSeriesMetaData.put(GraphSource.SERIES_LINES_VISIBLE, displayNormalData);
dataSeries.add(new DataSeries(points, dataSeriesMetaData));
Map<String, Object> eDataSeriesMetaData = new HashMap<String, Object>();
eDataSeriesMetaData.put(GraphSource.SERIES_COLOR, seriesColor);
eDataSeriesMetaData.put(GraphSource.SERIES_STROKE, new BasicStroke(
1.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND,
1.0f, new float[]{10.0f, 6.0f}, 0.0f));
if (graphExpected) {
dataSeries.add(new DataSeries(epoints, eDataSeriesMetaData));
}
// code to set the text in the legend
if (legendItems != null) {
if (displayNormalData && legendItems.getItemCount() < maxLegendItems) {
if (displayAlert && !singleAlertLegend) {
legendItems.add(new LegendItem(lineSetLabel + ": " + getTranslation("Normal"), seriesColor));
}
if (graphExpected) {
legendItems.add(new LegendItem(lineSetLabel, seriesColor));
legendItems.add(new LegendItem(("Expected " + lineSetLabel), seriesColor));
} else {
legendItems.add(new LegendItem(lineSetLabel, seriesColor));
}
}
if (!singleAlertLegend && displayWarningData && legendItems.getItemCount() < maxLegendItems) {
legendItems.add(new LegendItem(lineSetLabel + ": " + getTranslation("Warning"), warningDataColor));
}
if (!singleAlertLegend && displayAlertData && legendItems.getItemCount() < maxLegendItems) {
legendItems.add(new LegendItem(lineSetLabel + ": " + getTranslation("Alert"), alertDataColor));
}
if (!singleSeverityLegend && displaySevereData && legendItems.getItemCount() < maxLegendItems) {
legendItems.add(new LegendItem(lineSetLabel + ": " + getTranslation("Severe"), severeDataColor));
}
}
}
if (singleAlertLegend && legendItems.getItemCount() < maxLegendItems) {
legendItems.add(new LegendItem(getTranslation("Warning"), warningDataColor));
legendItems.add(new LegendItem(getTranslation("Alert"), alertDataColor));
}
if (singleSeverityLegend && legendItems.getItemCount() < maxLegendItems) {
legendItems.add(new LegendItem(getTranslation("Severe"), severeDataColor));
}
return maxCount;
}
public void setTimeSeriesGraphMetaData(GraphDataInterface graphData, double maxCount,
Map<String, Object> graphMetaData) {
setTimeSeriesGraphMetaData(graphData, null, null, maxCount, graphMetaData);
}
public void setTimeSeriesGraphMetaData(GraphDataInterface graphData, Double yAxisMin, Double yAxisMax,
double maxCount, Map<String, Object> graphMetaData) {
String graphTitle = graphData.getGraphTitle() != null ? graphData.getGraphTitle() : "";
String xAxisLabel = graphData.getXAxisLabel() != null ? graphData.getXAxisLabel() : "";
String yAxisLabel = graphData.getYAxisLabel() != null ? graphData.getYAxisLabel() : "";
int graphWidth = graphData.getGraphWidth();
int graphHeight = graphData.getGraphHeight();
boolean percentBased = graphData.percentBased();
int maxLabeledCategoryTicks = graphData.getMaxLabeledCategoryTicks();
graphMetaData.put(GraphSource.GRAPH_TYPE, GraphSource.GRAPH_TYPE_LINE);
graphMetaData.put(GraphSource.BACKGROUND_COLOR, Color.WHITE);
graphMetaData.put(GraphSource.GRAPH_TITLE, graphTitle);
graphMetaData.put(GraphSource.GRAPH_FONT, graphFont);
graphMetaData.put(GraphSource.GRAPH_MINOR_TICKS, 0);
graphMetaData.put(GraphSource.GRAPH_LEGEND, graphData.showLegend());
graphMetaData.put(GraphSource.LEGEND_FONT, legendFont);
SparselyLabeledCategoryAxis domainAxis;
if (graphWidth >= 500 && graphHeight >= 300) {
// this is a larger graph so we can add some additional properties to pretty it up
graphMetaData.put(GraphSource.GRAPH_BORDER, true);
graphMetaData.put(GraphSource.AXIS_OFFSET, 5.0);
graphMetaData.put(GraphSource.GRAPH_RANGE_GRIDLINE_PAINT, Color.lightGray);
if (yAxisLabel == null && percentBased) {
yAxisLabel = getTranslation("Percent");
} else if (yAxisLabel == null) {
yAxisLabel = getTranslation("Counts");
}
if (xAxisLabel == null) {
xAxisLabel = getTranslation("Date");
}
domainAxis = new SparselyLabeledCategoryAxis(maxLabeledCategoryTicks, Color.lightGray);
} else {
yAxisLabel = "";
xAxisLabel = "";
domainAxis = new SparselyLabeledCategoryAxis(maxLabeledCategoryTicks);
}
domainAxis.setCategoryLabelPositions(CategoryLabelPositions.createDownRotationLabelPositions(45));
domainAxis.setMaximumCategoryLabelWidthRatio(maxCategoryLabelWidthRatio);
graphMetaData.put(JFreeChartCategoryGraphSource.DOMAIN_AXIS, domainAxis);
graphMetaData.put(GraphSource.GRAPH_RANGE_INTEGER_TICK, !percentBased);
graphMetaData.put(GraphSource.GRAPH_RANGE_MINOR_TICK_VISIBLE, false);
if (yAxisMin != null && yAxisMax != null) {
graphMetaData.put(GraphSource.GRAPH_RANGE_LOWER_BOUND, yAxisMin);
graphMetaData.put(GraphSource.GRAPH_RANGE_UPPER_BOUND, yAxisMax);
} else {
graphMetaData.put(GraphSource.GRAPH_RANGE_LOWER_BOUND, 0.0);
if (maxCount == 0) {
// if there is no data, set the upper bound to 1.0, otherwise we
// get a weird looking y-axis
graphMetaData.put(GraphSource.GRAPH_RANGE_UPPER_BOUND, 1.0);
}
// if the maxCount is less than 1, Y-Axis labels are not displayed.
// Found during testing % data that may be 1%
else if (maxCount < 1) {
graphMetaData.put(GraphSource.GRAPH_RANGE_INTEGER_TICK, false);
graphMetaData.put(GraphSource.GRAPH_RANGE_UPPER_BOUND, maxCount * 1.05);
} else {
graphMetaData.put(GraphSource.GRAPH_RANGE_UPPER_BOUND, maxCount * 1.05);
}
}
graphMetaData.put(GraphSource.GRAPH_Y_LABEL, yAxisLabel);
graphMetaData.put(GraphSource.GRAPH_Y_AXIS_FONT, rangeAxisFont);
graphMetaData.put(GraphSource.GRAPH_Y_AXIS_LABEL_FONT, rangeAxisLabelFont);
graphMetaData.put(GraphSource.GRAPH_X_LABEL, xAxisLabel);
graphMetaData.put(GraphSource.GRAPH_X_AXIS_FONT, domainAxisFont);
graphMetaData.put(GraphSource.GRAPH_X_AXIS_LABEL_FONT, domainAxisLabelFont);
}
public void setBarGraphMetaData(GraphDataInterface graphData, boolean stackGraph,
Map<String, Object> graphMetaData) {
String graphTitle = graphData.getGraphTitle() != null ? graphData.getGraphTitle() : "";
String xAxisLabel = graphData.getXAxisLabel() != null ? graphData.getXAxisLabel() : "";
String yAxisLabel = graphData.getYAxisLabel() != null ? graphData.getYAxisLabel() : "";
int graphWidth = graphData.getGraphWidth();
int graphHeight = graphData.getGraphHeight();
boolean percentBased = graphData.percentBased();
boolean plotHorizontal = graphData.plotHorizontal();
int maxLabeledCategoryTicks = graphData.getMaxLabeledCategoryTicks();
if (stackGraph) {
graphMetaData.put(GraphSource.GRAPH_TYPE, GraphSource.GRAPH_TYPE_STACKED_BAR);
} else {
graphMetaData.put(GraphSource.GRAPH_TYPE, GraphSource.GRAPH_TYPE_BAR);
}
if (plotHorizontal) {
graphMetaData.put(JFreeChartBarGraphSource.PLOT_ORIENTATION, PlotOrientation.HORIZONTAL);
}
graphMetaData.put(GraphSource.GRAPH_LABEL_BACKGROUND_COLOR, Color.WHITE);
graphMetaData.put(GraphSource.BACKGROUND_COLOR, Color.WHITE);
graphMetaData.put(GraphSource.GRAPH_TITLE, graphTitle);
graphMetaData.put(GraphSource.GRAPH_FONT, graphFont);
graphMetaData.put(GraphSource.GRAPH_BORDER, false);
graphMetaData.put(GraphSource.GRAPH_LEGEND, graphData.showLegend());
graphMetaData.put(GraphSource.LEGEND_FONT, legendFont);
SparselyLabeledCategoryAxis domainAxis;
if (graphWidth >= 500 && graphHeight >= 300) {
// this is a larger graph so we can add some additional properties to pretty it up
graphMetaData.put(GraphSource.GRAPH_BORDER, true);
graphMetaData.put(GraphSource.AXIS_OFFSET, 5.0);
graphMetaData.put(GraphSource.GRAPH_RANGE_GRIDLINE_PAINT, Color.lightGray);
domainAxis = new SparselyLabeledCategoryAxis(maxLabeledCategoryTicks, Color.lightGray);
} else {
domainAxis = new SparselyLabeledCategoryAxis(maxLabeledCategoryTicks);
}
if (!plotHorizontal) {
// don't rotate labels if this is a horizontal graph
domainAxis.setCategoryLabelPositions(CategoryLabelPositions.createDownRotationLabelPositions(45));
}
domainAxis.setMaximumCategoryLabelWidthRatio(maxCategoryLabelWidthRatio);
graphMetaData.put(JFreeChartCategoryGraphSource.DOMAIN_AXIS, domainAxis);
graphMetaData.put(GraphSource.GRAPH_RANGE_AXIS_LOCATION, AxisLocation.BOTTOM_OR_LEFT);
graphMetaData.put(GraphSource.GRAPH_RANGE_INTEGER_TICK, !percentBased);
graphMetaData.put(GraphSource.GRAPH_RANGE_MINOR_TICK_VISIBLE, false);
graphMetaData.put(GraphSource.GRAPH_Y_LABEL, yAxisLabel);
graphMetaData.put(GraphSource.GRAPH_Y_AXIS_FONT, rangeAxisFont);
graphMetaData.put(GraphSource.GRAPH_Y_AXIS_LABEL_FONT, rangeAxisLabelFont);
graphMetaData.put(GraphSource.GRAPH_X_LABEL, xAxisLabel);
graphMetaData.put(GraphSource.GRAPH_X_AXIS_FONT, domainAxisFont);
graphMetaData.put(GraphSource.GRAPH_X_AXIS_LABEL_FONT, domainAxisLabelFont);
}
public void setPieGraphMetaData(GraphDataInterface graphData, Map<String, Object> graphMetaData,
List<PointInterface> points) {
double[][] counts = graphData.getCounts();
String[][] altTexts = graphData.getAltTexts();
String[][] lineSetURLs = graphData.getLineSetURLs();
String[] lineSetLabels = graphData.getLineSetLabels();
String graphTitle = graphData.getGraphTitle() != null ? graphData.getGraphTitle() : "";
String graphNoDataMessage = graphData.getNoDataMessage();
Color[] graphBaseColors = graphData.getGraphBaseColors();
boolean graphDisplayLabel = graphData.getShowGraphLabels();
for (int i = 0; i < counts.length; i++) {
String lineSetLabel = "series" + (i + 1);
String altText = null;
String lineSetURL = null;
try {
lineSetLabel = lineSetLabels[i];
} catch (Exception e) {
}
try {
altText = altTexts[i][0];
} catch (Exception e) {
}
try {
lineSetURL = lineSetURLs[i][0];
} catch (Exception e) {
}
Map<String, Object> pointMetaData = new HashMap<String, Object>();
pointMetaData.put(GraphSource.ITEM_TOOL_TIP, altText);
pointMetaData.put(GraphSource.ITEM_URL, lineSetURL);
pointMetaData.put(GraphSource.ITEM_COLOR, graphBaseColors[i % graphBaseColors.length]);
points.add(new DataPoint(counts[i][0], lineSetLabel, pointMetaData));
}
Font font = graphFont;
if (graphData.getTitleFont() != null) {
font = graphData.getTitleFont();
}
graphMetaData.put(GraphSource.GRAPH_TYPE, GraphSource.GRAPH_TYPE_PIE);
graphMetaData.put(GraphSource.BACKGROUND_COLOR,
graphData.getBackgroundColor()); //edit to get graph data background color, defaults to white
graphMetaData.put(GraphSource.GRAPH_LABEL_BACKGROUND_COLOR, graphData.getLabelBackgroundColor());
graphMetaData.put(GraphSource.GRAPH_TITLE, graphTitle);
graphMetaData.put(GraphSource.GRAPH_FONT, font);
graphMetaData.put(GraphSource.GRAPH_BORDER, false);
graphMetaData.put(GraphSource.GRAPH_DISPLAY_LABEL, graphDisplayLabel);
graphMetaData.put(GraphSource.GRAPH_NO_DATA_MESSAGE, graphNoDataMessage);
graphMetaData.put(GraphSource.GRAPH_LEGEND, graphData.showLegend());
graphMetaData.put(GraphSource.LEGEND_FONT, legendFont);
}
private GraphObject getGraph(GraphDataInterface graphData, List<DataSeries> series,
Map<String, Object> graphMetaData, LegendItemCollection legendItems,
String graphType) {
GraphObject graph = null;
String graphTitle = graphData.getGraphTitle();
try {
// add the created chart properties
JFreeChartGraphSource graphSource = new JFreeChartGraphSource();
graphSource.setData(series);
graphSource.setParams(graphMetaData);
graphSource.initialize();
// add the custom legend
graphSource.getChart().getCategoryPlot().setFixedLegendItems(legendItems);
// render the graph to get the image map
RenderedGraph renderedGraph = graphSource.renderGraph(graphData.getGraphWidth(), graphData.getGraphHeight(),
Encoding.PNG);
String imageFileName = getCleanValue(graphTitle) + "_" + graphType + ".png";
// get the image map
String imageMapName = "imageMap" + graphDataId;
String imageMap = appendImageMapTarget(renderedGraph.getImageMap(imageMapName),
graphData.getLineSetURLTarget());
try {
// store away the graph data file
graphDataHandler.putGraphData(graphData, graphDataId);
graph = new GraphObject(graphSource, renderedGraph, imageFileName, imageMapName, imageMap, graphDataId);
} catch (GraphException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
} catch (GraphException e) {
System.out.println("Could not create graph " + graphTitle);
e.printStackTrace();
}
return graph;
}
private Map<String, Object> dumpGraph(GraphDataInterface graphData) {
// setup the default metadata
List<DataSeries> dataSeries = new ArrayList<DataSeries>();
LegendItemCollection legendItems = new LegendItemCollection();
Map<String, Object> graphMetaData = new HashMap<String, Object>();
double maxCount = setDataSeries(graphData, null, false, dataSeries, legendItems, false);
setTimeSeriesGraphMetaData(graphData, null, null, maxCount, graphMetaData);
// store away the graph data file
try {
graphDataHandler.putGraphData(graphData, graphDataId);
} catch (GraphException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
return graphMetaData;
}
private static String getUniqueId(String userId) {
Date currentTime = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMMdd_hh_mm_ss_SSS");
if (userId != null && userId.length() > 0) {
return userId + "_" + sdf.format(currentTime) + "_" + (int) (Math.random() * 10000);
} else {
return sdf.format(currentTime) + "_" + (int) (Math.random() * 10000);
}
}
private String appendImageMapTarget(String imageMap, String target) {
if (target != null && target.length() > 0) {
return imageMap.replace("<area ", "<area target=\"" + target + "\" ");
}
return imageMap;
}
private String getCleanValue(String value) {
if (value == null) {
return "";
}
// illegal characters for file names on windows are \/:*?"<>|
String cleanValue = value.replaceAll("\\\\", "-");
cleanValue = cleanValue.replaceAll("/", "-");
cleanValue = cleanValue.replaceAll(":", "-");
cleanValue = cleanValue.replaceAll("\\*", "-");
cleanValue = cleanValue.replaceAll("\\?", "-");
cleanValue = cleanValue.replaceAll("\"", "-");
cleanValue = cleanValue.replaceAll("<", "-");
cleanValue = cleanValue.replaceAll(">", "-");
cleanValue = cleanValue.replaceAll("\\|", "-");
cleanValue = cleanValue.replaceAll(";", "-");
cleanValue = cleanValue.replaceAll("\\+", "-");
return cleanValue;
}
private boolean displaySeries(String displayKey, int seriesIndex) {
if (displayKey != null && displayKey.length() > seriesIndex && displayKey.charAt(seriesIndex) == '0') {
return false;
} else {
return true;
}
}
private String getDataSeriesJSON(String[] lineSetLabels, boolean[] displayAlerts, boolean[] displaySeverityAlerts,
String quoteStr) {
String json = "";
if (lineSetLabels != null) {
for (int i = 0; i < lineSetLabels.length; i++) {
boolean displayAlert = false;
boolean displaySeverityAlert = false;
try {
displayAlert = displayAlerts[i];
} catch (Exception e) {
}
try {
displaySeverityAlert = displaySeverityAlerts[i];
} catch (Exception e) {
}
if (displayAlert) {
json +=
getDataSeriesJSONHelper(lineSetLabels[i],
lineSetLabels[i] + ": " + getTranslation("Normal"), true, quoteStr);
json += ", ";
json +=
getDataSeriesJSONHelper(lineSetLabels[i],
lineSetLabels[i] + ": " + getTranslation("Warning"), true,
quoteStr);
json += ", ";
json +=
getDataSeriesJSONHelper(lineSetLabels[i], lineSetLabels[i] + ": " + getTranslation("Alert"),
true, quoteStr);
json += ", ";
if (displaySeverityAlert) {
json +=
getDataSeriesJSONHelper(lineSetLabels[i],
lineSetLabels[i] + ": " + getTranslation("Severe"), true,
quoteStr);
json += ", ";
}
} else {
json += getDataSeriesJSONHelper(lineSetLabels[i], lineSetLabels[i], false, quoteStr);
json += ", ";
}
}
if (json.length() > 0) {
json = json.substring(0, json.length() - 2);
}
}
return "{ [ " + json + " ] }";
}
private String getDataSeriesJSONHelper(String seriesName, String displayName, boolean displayAlerts,
String quoteStr) {
String json = "";
json += "{ ";
json += "seriesName:";
json += quoteStr + seriesName + quoteStr;
json += ", displayName:";
json += quoteStr + displayName + quoteStr;
json += ", displayAlerts:" + displayAlerts + " ";
json += "}";
return json;
}
}
| true | true | private double setDataSeries(GraphDataInterface graphData, String displayKey, boolean useNoDataColor,
List<DataSeries> dataSeries, LegendItemCollection legendItems, boolean useItemColor,
boolean graphExpected) {
double[][] counts = graphData.getCounts();
double[][] expecteds = graphData.getExpecteds();
int[][] colors = graphData.getColors();
String[][] altTexts = graphData.getAltTexts();
String[][] lineSetURLs = graphData.getLineSetURLs();
String[] xLabels = graphData.getXLabels();
String[] lineSetLabels = graphData.getLineSetLabels();
boolean[] displayAlerts = graphData.displayAlerts();
boolean[] displaySeverityAlerts = graphData.displaySeverityAlerts();
double[] lineSymbolSizes = graphData.getLineSymbolSizes();
Color[] graphBaseColors = graphData.getGraphBaseColors();
int displayKeyIndex = 0;
double maxCount = 0;
boolean singleAlertLegend = graphData.getShowSingleAlertLegend();
boolean singleSeverityLegend = graphData.getShowSingleSeverityLegend();
for (int i = 0; i < counts.length; i++) {
String lineSetLabel = "series" + (i + 1);
boolean displayAlert = false;
boolean displaySeverityAlert = false;
double lineSymbolSize = 7.0;
try {
lineSetLabel = lineSetLabels[i];
} catch (Exception e) {
}
try {
displayAlert = displayAlerts[i];
} catch (Exception e) {
}
try {
displaySeverityAlert = displaySeverityAlerts[i];
} catch (Exception e) {
}
try {
lineSymbolSize = lineSymbolSizes[i];
} catch (Exception e) {
}
double xy = lineSymbolSize / 2.0 * -1;
Color seriesColor = graphBaseColors[i % graphBaseColors.length];
boolean displayNormalData = displaySeries(displayKey, displayKeyIndex++) ? true : false;
boolean displayWarningData = displayAlert && displaySeries(displayKey, displayKeyIndex++) ? true : false;
boolean displayAlertData = displayAlert && displaySeries(displayKey, displayKeyIndex++) ? true : false;
boolean displaySevereData = displaySeverityAlert &&
displaySeries(displayKey, displayKeyIndex++) ? true : false;
List<DataPoint> points = new ArrayList<DataPoint>();
List<DataPoint> epoints = new ArrayList<DataPoint>();
/** get graph data */
for (int j = 0; j < counts[i].length; j++) {
boolean alertDataExists = false;
String altText = null;
String lineSetURL = null;
int color = 1;
try {
altText = altTexts[i][j];
} catch (Exception e) {
}
try {
lineSetURL = lineSetURLs[i][j];
} catch (Exception e) {
}
try {
color = colors[i][j];
} catch (Exception e) {
}
Map<String, Object> epointMetaData = new HashMap<String, Object>();
Map<String, Object> pointMetaData = new HashMap<String, Object>();
pointMetaData.put(GraphSource.ITEM_TOOL_TIP, altText);
pointMetaData.put(GraphSource.ITEM_URL, lineSetURL);
pointMetaData.put(GraphSource.ITEM_SHAPE, new Ellipse2D.Double(xy, xy, lineSymbolSize, lineSymbolSize));
pointMetaData.put(GraphSource.ITEM_COLOR, seriesColor);
epointMetaData.put(GraphSource.ITEM_COLOR, seriesColor.brighter());
epointMetaData.put(GraphSource.ITEM_SHAPE, new Rectangle2D.Double(xy, xy, 7, 7));
epointMetaData.put(GraphSource.ITEM_TOOL_TIP, altText);
// color 0 = GRAY (no data), color 2 = YELLOW (warning), 3 = RED (alert),
// 4 = PURPLE (severe)
if (useNoDataColor && color == 0) {
pointMetaData.put(GraphSource.ITEM_COLOR, noDataColor);
} else if (displayWarningData && color == 2) {
alertDataExists = true;
pointMetaData.put(GraphSource.ITEM_COLOR, warningDataColor);
} else if (displayAlertData && color == 3) {
alertDataExists = true;
pointMetaData.put(GraphSource.ITEM_COLOR, alertDataColor);
} else if (displaySevereData && color == 4) {
alertDataExists = true;
pointMetaData.put(GraphSource.ITEM_COLOR, severeDataColor);
}
if (useItemColor) {
seriesColor = graphBaseColors[j % graphBaseColors.length];
pointMetaData.put(GraphSource.ITEM_COLOR, seriesColor);
}
if (displayNormalData || alertDataExists) {
// only update the maxCount if this data point is visible
if (counts[i][j] > maxCount) {
maxCount = counts[i][j];
}
} else {
// if normal data is supposed to be hidden and no alert data exists, then hide this
// data point
pointMetaData.put(GraphSource.ITEM_VISIBLE, false);
epointMetaData.put(GraphSource.ITEM_VISIBLE, false);
}
// if the data is set to the Double.MIN_VALUE, then add it as a null.
if (counts[i][j] != Double.MIN_VALUE) {
points.add(new DataPoint(counts[i][j], xLabels[j], pointMetaData));
} else {
points.add(new DataPoint(null, xLabels[j], pointMetaData));
}
if (expecteds[i][j] != Double.MIN_VALUE) {
epoints.add(new DataPoint(expecteds[i][j], xLabels[j], epointMetaData));
} else {
epoints.add(new DataPoint(null, xLabels[j], epointMetaData));
}
}
/** add the series */
// series properties
Map<String, Object> dataSeriesMetaData = new HashMap<String, Object>();
dataSeriesMetaData.put(GraphSource.SERIES_TITLE, lineSetLabel);
dataSeriesMetaData.put(GraphSource.SERIES_COLOR, seriesColor);
// if normal data is hidden for this series, hide the series connector line
dataSeriesMetaData.put(GraphSource.SERIES_LINES_VISIBLE, displayNormalData);
dataSeries.add(new DataSeries(points, dataSeriesMetaData));
Map<String, Object> eDataSeriesMetaData = new HashMap<String, Object>();
eDataSeriesMetaData.put(GraphSource.SERIES_COLOR, seriesColor);
eDataSeriesMetaData.put(GraphSource.SERIES_STROKE, new BasicStroke(
1.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND,
1.0f, new float[]{10.0f, 6.0f}, 0.0f));
if (graphExpected) {
dataSeries.add(new DataSeries(epoints, eDataSeriesMetaData));
}
// code to set the text in the legend
if (legendItems != null) {
if (displayNormalData && legendItems.getItemCount() < maxLegendItems) {
if (displayAlert && !singleAlertLegend) {
legendItems.add(new LegendItem(lineSetLabel + ": " + getTranslation("Normal"), seriesColor));
}
if (graphExpected) {
legendItems.add(new LegendItem(lineSetLabel, seriesColor));
legendItems.add(new LegendItem(("Expected " + lineSetLabel), seriesColor));
} else {
legendItems.add(new LegendItem(lineSetLabel, seriesColor));
}
}
if (!singleAlertLegend && displayWarningData && legendItems.getItemCount() < maxLegendItems) {
legendItems.add(new LegendItem(lineSetLabel + ": " + getTranslation("Warning"), warningDataColor));
}
if (!singleAlertLegend && displayAlertData && legendItems.getItemCount() < maxLegendItems) {
legendItems.add(new LegendItem(lineSetLabel + ": " + getTranslation("Alert"), alertDataColor));
}
if (!singleSeverityLegend && displaySevereData && legendItems.getItemCount() < maxLegendItems) {
legendItems.add(new LegendItem(lineSetLabel + ": " + getTranslation("Severe"), severeDataColor));
}
}
}
if (singleAlertLegend && legendItems.getItemCount() < maxLegendItems) {
legendItems.add(new LegendItem(getTranslation("Warning"), warningDataColor));
legendItems.add(new LegendItem(getTranslation("Alert"), alertDataColor));
}
if (singleSeverityLegend && legendItems.getItemCount() < maxLegendItems) {
legendItems.add(new LegendItem(getTranslation("Severe"), severeDataColor));
}
return maxCount;
}
| private double setDataSeries(GraphDataInterface graphData, String displayKey, boolean useNoDataColor,
List<DataSeries> dataSeries, LegendItemCollection legendItems, boolean useItemColor,
boolean graphExpected) {
double[][] counts = graphData.getCounts();
double[][] expecteds = graphData.getExpecteds();
int[][] colors = graphData.getColors();
String[][] altTexts = graphData.getAltTexts();
String[][] lineSetURLs = graphData.getLineSetURLs();
String[] xLabels = graphData.getXLabels();
String[] lineSetLabels = graphData.getLineSetLabels();
boolean[] displayAlerts = graphData.displayAlerts();
boolean[] displaySeverityAlerts = graphData.displaySeverityAlerts();
double[] lineSymbolSizes = graphData.getLineSymbolSizes();
Color[] graphBaseColors = graphData.getGraphBaseColors();
int displayKeyIndex = 0;
double maxCount = 0;
boolean singleAlertLegend = graphData.getShowSingleAlertLegend();
boolean singleSeverityLegend = graphData.getShowSingleSeverityLegend();
for (int i = 0; i < counts.length; i++) {
String lineSetLabel = "series" + (i + 1);
boolean displayAlert = false;
boolean displaySeverityAlert = false;
double lineSymbolSize = 7.0;
try {
lineSetLabel = lineSetLabels[i];
} catch (Exception e) {
}
try {
displayAlert = displayAlerts[i];
} catch (Exception e) {
}
try {
displaySeverityAlert = displaySeverityAlerts[i];
} catch (Exception e) {
}
try {
lineSymbolSize = lineSymbolSizes[i];
} catch (Exception e) {
}
double xy = lineSymbolSize / 2.0 * -1;
Color seriesColor = graphBaseColors[i % graphBaseColors.length];
boolean displayNormalData = displaySeries(displayKey, displayKeyIndex++) ? true : false;
boolean displayWarningData = displayAlert && displaySeries(displayKey, displayKeyIndex++) ? true : false;
boolean displayAlertData = displayAlert && displaySeries(displayKey, displayKeyIndex++) ? true : false;
boolean displaySevereData = displaySeverityAlert &&
displaySeries(displayKey, displayKeyIndex++) ? true : false;
List<DataPoint> points = new ArrayList<DataPoint>();
List<DataPoint> epoints = new ArrayList<DataPoint>();
/** get graph data */
for (int j = 0; j < counts[i].length; j++) {
boolean alertDataExists = false;
String altText = null;
String lineSetURL = null;
int color = 1;
try {
altText = altTexts[i][j];
} catch (Exception e) {
}
try {
lineSetURL = lineSetURLs[i][j];
} catch (Exception e) {
}
try {
color = colors[i][j];
} catch (Exception e) {
}
Map<String, Object> epointMetaData = new HashMap<String, Object>();
Map<String, Object> pointMetaData = new HashMap<String, Object>();
pointMetaData.put(GraphSource.ITEM_TOOL_TIP, altText);
pointMetaData.put(GraphSource.ITEM_URL, lineSetURL);
pointMetaData.put(GraphSource.ITEM_SHAPE, new Ellipse2D.Double(xy, xy, lineSymbolSize, lineSymbolSize));
pointMetaData.put(GraphSource.ITEM_COLOR, seriesColor);
epointMetaData.put(GraphSource.ITEM_COLOR, seriesColor.brighter());
epointMetaData.put(GraphSource.ITEM_SHAPE, new Rectangle2D.Double(xy, xy, 7, 7));
epointMetaData.put(GraphSource.ITEM_TOOL_TIP, altText);
// color 0 = GRAY (no data), color 2 = YELLOW (warning), 3 = RED (alert),
// 4 = PURPLE (severe)
if (useNoDataColor && color == 0) {
pointMetaData.put(GraphSource.ITEM_COLOR, noDataColor);
} else if (displayWarningData && color == 2) {
alertDataExists = true;
pointMetaData.put(GraphSource.ITEM_COLOR, warningDataColor);
} else if (displayAlertData && color == 3) {
alertDataExists = true;
pointMetaData.put(GraphSource.ITEM_COLOR, alertDataColor);
} else if (displaySevereData && color == 4) {
alertDataExists = true;
pointMetaData.put(GraphSource.ITEM_COLOR, severeDataColor);
}
if (useItemColor) {
seriesColor = graphBaseColors[j % graphBaseColors.length];
pointMetaData.put(GraphSource.ITEM_COLOR, seriesColor);
}
if (displayNormalData || alertDataExists) {
// only update the maxCount if this data point is visible
if (counts[i][j] > maxCount) {
maxCount = counts[i][j];
}
} else {
// if normal data is supposed to be hidden and no alert data exists, then hide this
// data point
pointMetaData.put(GraphSource.ITEM_VISIBLE, false);
epointMetaData.put(GraphSource.ITEM_VISIBLE, false);
}
// if the data is set to the Double.MIN_VALUE, then add it as a null.
if (counts[i][j] != Double.MIN_VALUE) {
points.add(new DataPoint(counts[i][j], xLabels[j], pointMetaData));
} else {
points.add(new DataPoint(null, xLabels[j], pointMetaData));
}
if (expecteds != null && expecteds[i][j] != Double.MIN_VALUE) {
epoints.add(new DataPoint(expecteds[i][j], xLabels[j], epointMetaData));
} else {
epoints.add(new DataPoint(null, xLabels[j], epointMetaData));
}
}
/** add the series */
// series properties
Map<String, Object> dataSeriesMetaData = new HashMap<String, Object>();
dataSeriesMetaData.put(GraphSource.SERIES_TITLE, lineSetLabel);
dataSeriesMetaData.put(GraphSource.SERIES_COLOR, seriesColor);
// if normal data is hidden for this series, hide the series connector line
dataSeriesMetaData.put(GraphSource.SERIES_LINES_VISIBLE, displayNormalData);
dataSeries.add(new DataSeries(points, dataSeriesMetaData));
Map<String, Object> eDataSeriesMetaData = new HashMap<String, Object>();
eDataSeriesMetaData.put(GraphSource.SERIES_COLOR, seriesColor);
eDataSeriesMetaData.put(GraphSource.SERIES_STROKE, new BasicStroke(
1.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND,
1.0f, new float[]{10.0f, 6.0f}, 0.0f));
if (graphExpected) {
dataSeries.add(new DataSeries(epoints, eDataSeriesMetaData));
}
// code to set the text in the legend
if (legendItems != null) {
if (displayNormalData && legendItems.getItemCount() < maxLegendItems) {
if (displayAlert && !singleAlertLegend) {
legendItems.add(new LegendItem(lineSetLabel + ": " + getTranslation("Normal"), seriesColor));
}
if (graphExpected) {
legendItems.add(new LegendItem(lineSetLabel, seriesColor));
legendItems.add(new LegendItem(("Expected " + lineSetLabel), seriesColor));
} else {
legendItems.add(new LegendItem(lineSetLabel, seriesColor));
}
}
if (!singleAlertLegend && displayWarningData && legendItems.getItemCount() < maxLegendItems) {
legendItems.add(new LegendItem(lineSetLabel + ": " + getTranslation("Warning"), warningDataColor));
}
if (!singleAlertLegend && displayAlertData && legendItems.getItemCount() < maxLegendItems) {
legendItems.add(new LegendItem(lineSetLabel + ": " + getTranslation("Alert"), alertDataColor));
}
if (!singleSeverityLegend && displaySevereData && legendItems.getItemCount() < maxLegendItems) {
legendItems.add(new LegendItem(lineSetLabel + ": " + getTranslation("Severe"), severeDataColor));
}
}
}
if (singleAlertLegend && legendItems.getItemCount() < maxLegendItems) {
legendItems.add(new LegendItem(getTranslation("Warning"), warningDataColor));
legendItems.add(new LegendItem(getTranslation("Alert"), alertDataColor));
}
if (singleSeverityLegend && legendItems.getItemCount() < maxLegendItems) {
legendItems.add(new LegendItem(getTranslation("Severe"), severeDataColor));
}
return maxCount;
}
|
diff --git a/tests/tests/widget/src/android/widget/cts/ListViewTest.java b/tests/tests/widget/src/android/widget/cts/ListViewTest.java
index f21b721a..f283681e 100644
--- a/tests/tests/widget/src/android/widget/cts/ListViewTest.java
+++ b/tests/tests/widget/src/android/widget/cts/ListViewTest.java
@@ -1,1071 +1,1070 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.widget.cts;
import java.util.List;
import junit.framework.Assert;
import org.xmlpull.v1.XmlPullParser;
import android.app.Activity;
import android.app.Instrumentation;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.test.ActivityInstrumentationTestCase2;
import android.test.UiThreadTest;
import android.test.suitebuilder.annotation.MediumTest;
import android.util.AttributeSet;
import android.util.SparseBooleanArray;
import android.util.Xml;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LayoutAnimationController;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import com.android.cts.stub.R;
import com.google.android.collect.Lists;
import dalvik.annotation.TestLevel;
import dalvik.annotation.TestTargetClass;
import dalvik.annotation.TestTargetNew;
import dalvik.annotation.TestTargets;
import dalvik.annotation.ToBeFixed;
@TestTargetClass(ListView.class)
public class ListViewTest extends ActivityInstrumentationTestCase2<ListViewStubActivity> {
private final String[] mCountryList = new String[] {
"Argentina", "Australia", "China", "France", "Germany", "Italy", "Japan", "United States"
};
private final String[] mNameList = new String[] {
"Jacky", "David", "Kevin", "Michael", "Andy"
};
private ListView mListView;
private Activity mActivity;
private Instrumentation mInstrumentation;
private AttributeSet mAttributeSet;
private ArrayAdapter<String> mAdapter_countries;
private ArrayAdapter<String> mAdapter_names;
public ListViewTest() {
super("com.android.cts.stub", ListViewStubActivity.class);
}
protected void setUp() throws Exception {
super.setUp();
mActivity = getActivity();
mInstrumentation = getInstrumentation();
XmlPullParser parser = mActivity.getResources().getXml(R.layout.listview_layout);
mAttributeSet = Xml.asAttributeSet(parser);
mAdapter_countries = new ArrayAdapter<String>(mActivity,
android.R.layout.simple_list_item_1, mCountryList);
mAdapter_names = new ArrayAdapter<String>(mActivity, android.R.layout.simple_list_item_1,
mNameList);
mListView = (ListView) mActivity.findViewById(R.id.listview_default);
}
@TestTargets({
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "ListView",
args = {android.content.Context.class}
),
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "ListView",
args = {android.content.Context.class, android.util.AttributeSet.class}
),
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "ListView",
args = {android.content.Context.class, android.util.AttributeSet.class, int.class}
)
})
@ToBeFixed(bug = "1695243", explanation = "Android API javadocs are incomplete")
public void testConstructor() {
new ListView(mActivity);
new ListView(mActivity, mAttributeSet);
new ListView(mActivity, mAttributeSet, 0);
try {
new ListView(null);
fail("There should be a NullPointerException thrown out. ");
} catch (NullPointerException e) {
// expected, test success.
}
try {
new ListView(null, null);
fail("There should be a NullPointerException thrown out. ");
} catch (NullPointerException e) {
// expected, test success.
}
try {
new ListView(null, null, -1);
fail("There should be a NullPointerException thrown out. ");
} catch (NullPointerException e) {
// expected, test success.
}
}
@TestTargets({
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "setAdapter",
args = {android.widget.ListAdapter.class}
),
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "getMaxScrollAmount",
args = {}
)
})
public void testGetMaxScrollAmount() {
mInstrumentation.runOnMainSync(new Runnable() {
public void run() {
mListView.setAdapter(mAdapter_countries);
}
});
mInstrumentation.waitForIdleSync();
int amount1 = mListView.getMaxScrollAmount();
assertTrue(amount1 > 0);
mInstrumentation.runOnMainSync(new Runnable() {
public void run() {
mListView.setAdapter(mAdapter_names);
}
});
mInstrumentation.waitForIdleSync();
int amount2 = mListView.getMaxScrollAmount();
assertTrue(amount2 > 0);
assertTrue(amount2 < amount1); // because NAMES list is shorter than COUNTRIES list
}
@TestTargets({
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "setDividerHeight",
args = {int.class}
),
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "getDividerHeight",
args = {}
),
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "getDivider",
args = {}
)
})
public void testAccessDividerHeight() {
mInstrumentation.runOnMainSync(new Runnable() {
public void run() {
mListView.setAdapter(mAdapter_countries);
}
});
mInstrumentation.waitForIdleSync();
Drawable d = mListView.getDivider();
Rect r = d.getBounds();
assertTrue(r.bottom - r.top > 0);
mInstrumentation.runOnMainSync(new Runnable() {
public void run() {
mListView.setDividerHeight(20);
}
});
mInstrumentation.waitForIdleSync();
assertEquals(20, mListView.getDividerHeight());
assertEquals(20, r.bottom - r.top);
mInstrumentation.runOnMainSync(new Runnable() {
public void run() {
mListView.setDividerHeight(10);
}
});
mInstrumentation.waitForIdleSync();
assertEquals(10, mListView.getDividerHeight());
assertEquals(10, r.bottom - r.top);
}
@TestTargets({
@TestTargetNew(
level = TestLevel.PARTIAL,
method = "setItemsCanFocus",
args = {boolean.class}
),
@TestTargetNew(
level = TestLevel.PARTIAL,
method = "getItemsCanFocus",
args = {}
)
})
public void testAccessItemsCanFocus() {
mListView.setItemsCanFocus(true);
assertTrue(mListView.getItemsCanFocus());
mListView.setItemsCanFocus(false);
assertFalse(mListView.getItemsCanFocus());
// TODO: how to check?
}
@TestTargets({
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "setAdapter",
args = {android.widget.ListAdapter.class}
),
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "getAdapter",
args = {}
)
})
public void testAccessAdapter() {
mInstrumentation.runOnMainSync(new Runnable() {
public void run() {
mListView.setAdapter(mAdapter_countries);
}
});
mInstrumentation.waitForIdleSync();
assertSame(mAdapter_countries, mListView.getAdapter());
assertEquals(mCountryList.length, mListView.getCount());
mInstrumentation.runOnMainSync(new Runnable() {
public void run() {
mListView.setAdapter(mAdapter_names);
}
});
mInstrumentation.waitForIdleSync();
assertSame(mAdapter_names, mListView.getAdapter());
assertEquals(mNameList.length, mListView.getCount());
}
@TestTargets({
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "setItemChecked",
args = {int.class, boolean.class}
),
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "setChoiceMode",
args = {int.class}
),
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "getChoiceMode",
args = {}
),
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "getCheckedItemPosition",
args = {}
),
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "isItemChecked",
args = {int.class}
),
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "getCheckedItemPositions",
args = {}
),
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "clearChoices",
args = {}
)
})
@UiThreadTest
@ToBeFixed(bug="2031502", explanation="setItemChecked(i,false) always unchecks all items")
public void testAccessItemChecked() {
// NONE mode
mListView.setChoiceMode(ListView.CHOICE_MODE_NONE);
assertEquals(ListView.CHOICE_MODE_NONE, mListView.getChoiceMode());
mListView.setItemChecked(1, true);
assertEquals(ListView.INVALID_POSITION, mListView.getCheckedItemPosition());
assertFalse(mListView.isItemChecked(1));
// SINGLE mode
mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
assertEquals(ListView.CHOICE_MODE_SINGLE, mListView.getChoiceMode());
mListView.setItemChecked(2, true);
assertEquals(2, mListView.getCheckedItemPosition());
assertTrue(mListView.isItemChecked(2));
mListView.setItemChecked(3, true);
assertEquals(3, mListView.getCheckedItemPosition());
assertTrue(mListView.isItemChecked(3));
assertFalse(mListView.isItemChecked(2));
// test attempt to uncheck a item that wasn't checked to begin with
mListView.setItemChecked(4, false);
- // item three should still be checked, but current ListView behavior unchecks all items
- assertEquals(ListView.INVALID_POSITION, mListView.getCheckedItemPosition());
+ // item three should still be checked
+ assertEquals(3, mListView.getCheckedItemPosition());
assertFalse(mListView.isItemChecked(4));
- // should be assertTrue
- assertFalse(mListView.isItemChecked(3));
+ assertTrue(mListView.isItemChecked(3));
assertFalse(mListView.isItemChecked(2));
mListView.setItemChecked(4, true);
assertTrue(mListView.isItemChecked(4));
mListView.clearChoices();
assertEquals(ListView.INVALID_POSITION, mListView.getCheckedItemPosition());
assertFalse(mListView.isItemChecked(4));
// MULTIPLE mode
mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
assertEquals(ListView.CHOICE_MODE_MULTIPLE, mListView.getChoiceMode());
mListView.setItemChecked(1, true);
assertEquals(ListView.INVALID_POSITION, mListView.getCheckedItemPosition());
SparseBooleanArray array = mListView.getCheckedItemPositions();
assertTrue(array.get(1));
assertFalse(array.get(2));
assertTrue(mListView.isItemChecked(1));
assertFalse(mListView.isItemChecked(2));
mListView.setItemChecked(2, true);
mListView.setItemChecked(3, false);
mListView.setItemChecked(4, true);
assertTrue(array.get(1));
assertTrue(array.get(2));
assertFalse(array.get(3));
assertTrue(array.get(4));
assertTrue(mListView.isItemChecked(1));
assertTrue(mListView.isItemChecked(2));
assertFalse(mListView.isItemChecked(3));
assertTrue(mListView.isItemChecked(4));
mListView.clearChoices();
assertFalse(array.get(1));
assertFalse(array.get(2));
assertFalse(array.get(3));
assertFalse(array.get(4));
assertFalse(mListView.isItemChecked(1));
assertFalse(mListView.isItemChecked(2));
assertFalse(mListView.isItemChecked(3));
assertFalse(mListView.isItemChecked(4));
}
@TestTargets({
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "setFooterDividersEnabled",
args = {boolean.class}
),
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "addFooterView",
args = {android.view.View.class, java.lang.Object.class, boolean.class}
),
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "addFooterView",
args = {android.view.View.class}
),
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "getFooterViewsCount",
args = {}
),
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "removeFooterView",
args = {android.view.View.class}
)
})
public void testAccessFooterView() {
final TextView footerView1 = new TextView(mActivity);
footerView1.setText("footerview1");
final TextView footerView2 = new TextView(mActivity);
footerView2.setText("footerview2");
mInstrumentation.runOnMainSync(new Runnable() {
public void run() {
mListView.setFooterDividersEnabled(true);
}
});
mInstrumentation.waitForIdleSync();
assertEquals(0, mListView.getFooterViewsCount());
mInstrumentation.runOnMainSync(new Runnable() {
public void run() {
mListView.addFooterView(footerView1, null, true);
}
});
mInstrumentation.waitForIdleSync();
assertEquals(1, mListView.getFooterViewsCount());
mInstrumentation.runOnMainSync(new Runnable() {
public void run() {
mListView.addFooterView(footerView2);
}
});
mInstrumentation.waitForIdleSync();
assertEquals(2, mListView.getFooterViewsCount());
mInstrumentation.runOnMainSync(new Runnable() {
public void run() {
mListView.setAdapter(mAdapter_countries);
}
});
mInstrumentation.waitForIdleSync();
mInstrumentation.runOnMainSync(new Runnable() {
public void run() {
mListView.removeFooterView(footerView1);
}
});
mInstrumentation.waitForIdleSync();
assertEquals(1, mListView.getFooterViewsCount());
mInstrumentation.runOnMainSync(new Runnable() {
public void run() {
mListView.removeFooterView(footerView2);
}
});
mInstrumentation.waitForIdleSync();
assertEquals(0, mListView.getFooterViewsCount());
}
@TestTargets({
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "setHeaderDividersEnabled",
args = {boolean.class}
),
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "addHeaderView",
args = {android.view.View.class, java.lang.Object.class, boolean.class}
),
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "addHeaderView",
args = {android.view.View.class}
),
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "getHeaderViewsCount",
args = {}
),
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "removeHeaderView",
args = {android.view.View.class}
)
})
@ToBeFixed(bug = "", explanation = "After add two header views, the setAdapter will fail, " +
"and throws out an java.lang.ClassCastException.")
public void testAccessHeaderView() {
final TextView headerView1 = (TextView) mActivity.findViewById(R.id.headerview1);
final TextView headerView2 = (TextView) mActivity.findViewById(R.id.headerview2);
mInstrumentation.runOnMainSync(new Runnable() {
public void run() {
mListView.setHeaderDividersEnabled(true);
}
});
mInstrumentation.waitForIdleSync();
assertEquals(0, mListView.getHeaderViewsCount());
mInstrumentation.runOnMainSync(new Runnable() {
public void run() {
mListView.addHeaderView(headerView2, null, true);
}
});
mInstrumentation.waitForIdleSync();
assertEquals(1, mListView.getHeaderViewsCount());
mInstrumentation.runOnMainSync(new Runnable() {
public void run() {
mListView.addHeaderView(headerView1);
}
});
mInstrumentation.waitForIdleSync();
assertEquals(2, mListView.getHeaderViewsCount());
}
@TestTargets({
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "setDivider",
args = {android.graphics.drawable.Drawable.class}
),
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "getDivider",
args = {}
)
})
public void testAccessDivider() {
mInstrumentation.runOnMainSync(new Runnable() {
public void run() {
mListView.setAdapter(mAdapter_countries);
}
});
mInstrumentation.waitForIdleSync();
Drawable defaultDrawable = mListView.getDivider();
Rect r = defaultDrawable.getBounds();
assertTrue(r.bottom - r.top > 0);
final Drawable d = mActivity.getResources().getDrawable(R.drawable.scenery);
r = d.getBounds();
mInstrumentation.runOnMainSync(new Runnable() {
public void run() {
mListView.setDivider(d);
}
});
mInstrumentation.waitForIdleSync();
assertSame(d, mListView.getDivider());
assertEquals(r.bottom - r.top, mListView.getDividerHeight());
mInstrumentation.runOnMainSync(new Runnable() {
public void run() {
mListView.setDividerHeight(10);
}
});
mInstrumentation.waitForIdleSync();
assertEquals(10, mListView.getDividerHeight());
assertEquals(10, r.bottom - r.top);
}
@TestTargets({
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "setSelection",
args = {int.class}
),
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "setSelectionFromTop",
args = {int.class, int.class}
),
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "setSelectionAfterHeaderView",
args = {}
)
})
public void testSetSelection() {
mInstrumentation.runOnMainSync(new Runnable() {
public void run() {
mListView.setAdapter(mAdapter_countries);
}
});
mInstrumentation.waitForIdleSync();
mInstrumentation.runOnMainSync(new Runnable() {
public void run() {
mListView.setSelection(1);
}
});
mInstrumentation.waitForIdleSync();
String item = (String) mListView.getSelectedItem();
assertEquals(mCountryList[1], item);
mInstrumentation.runOnMainSync(new Runnable() {
public void run() {
mListView.setSelectionFromTop(5, 0);
}
});
mInstrumentation.waitForIdleSync();
item = (String) mListView.getSelectedItem();
assertEquals(mCountryList[5], item);
mInstrumentation.runOnMainSync(new Runnable() {
public void run() {
mListView.setSelectionAfterHeaderView();
}
});
mInstrumentation.waitForIdleSync();
item = (String) mListView.getSelectedItem();
assertEquals(mCountryList[0], item);
}
@TestTargets({
@TestTargetNew(
level = TestLevel.NOT_NECESSARY,
method = "onKeyDown",
args = {int.class, android.view.KeyEvent.class}
),
@TestTargetNew(
level = TestLevel.NOT_NECESSARY,
method = "onKeyUp",
args = {int.class, android.view.KeyEvent.class}
),
@TestTargetNew(
level = TestLevel.NOT_NECESSARY,
method = "onKeyMultiple",
args = {int.class, int.class, android.view.KeyEvent.class}
)
})
public void testOnKeyUpDown() {
// implementation details, do NOT test
}
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "performItemClick",
args = {android.view.View.class, int.class, long.class}
)
public void testPerformItemClick() {
mInstrumentation.runOnMainSync(new Runnable() {
public void run() {
mListView.setAdapter(mAdapter_countries);
}
});
mInstrumentation.waitForIdleSync();
mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
mInstrumentation.runOnMainSync(new Runnable() {
public void run() {
mListView.setSelection(2);
}
});
mInstrumentation.waitForIdleSync();
final TextView child = (TextView) mAdapter_countries.getView(2, null, mListView);
assertNotNull(child);
assertEquals(mCountryList[2], child.getText().toString());
final long itemID = mAdapter_countries.getItemId(2);
assertEquals(2, itemID);
mInstrumentation.runOnMainSync(new Runnable() {
public void run() {
mListView.performItemClick(child, 2, itemID);
}
});
mInstrumentation.waitForIdleSync();
MockOnItemClickListener onClickListener = new MockOnItemClickListener();
mListView.setOnItemClickListener(onClickListener);
assertNull(onClickListener.getView());
assertEquals(0, onClickListener.getPosition());
assertEquals(0, onClickListener.getID());
mInstrumentation.runOnMainSync(new Runnable() {
public void run() {
mListView.performItemClick(child, 2, itemID);
}
});
mInstrumentation.waitForIdleSync();
assertSame(child, onClickListener.getView());
assertEquals(2, onClickListener.getPosition());
assertEquals(2, onClickListener.getID());
}
@TestTargets({
@TestTargetNew(
level = TestLevel.NOT_NECESSARY,
method = "onRestoreInstanceState",
args = {android.os.Parcelable.class}
),
@TestTargetNew(
level = TestLevel.NOT_NECESSARY,
method = "onSaveInstanceState",
args = {}
)
})
public void testSaveAndRestoreInstanceState() {
// implementation details, do NOT test
}
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "dispatchKeyEvent",
args = {android.view.KeyEvent.class}
)
public void testDispatchKeyEvent() {
mInstrumentation.runOnMainSync(new Runnable() {
public void run() {
mListView.setAdapter(mAdapter_countries);
}
});
mInstrumentation.waitForIdleSync();
mInstrumentation.runOnMainSync(new Runnable() {
public void run() {
mListView.setSelection(1);
}
});
mInstrumentation.waitForIdleSync();
String item = (String) mListView.getSelectedItem();
assertEquals(mCountryList[1], item);
mInstrumentation.runOnMainSync(new Runnable() {
public void run() {
KeyEvent keyEvent = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_A);
mListView.dispatchKeyEvent(keyEvent);
}
});
mInstrumentation.waitForIdleSync();
mInstrumentation.runOnMainSync(new Runnable() {
public void run() {
KeyEvent keyEvent = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_DOWN);
mListView.dispatchKeyEvent(keyEvent);
mListView.dispatchKeyEvent(keyEvent);
mListView.dispatchKeyEvent(keyEvent);
}
});
mInstrumentation.waitForIdleSync();
item = (String)mListView.getSelectedItem();
assertEquals(mCountryList[4], item);
}
@TestTargetNew(
level = TestLevel.PARTIAL,
method = "requestChildRectangleOnScreen",
args = {android.view.View.class, android.graphics.Rect.class, boolean.class}
)
public void testRequestChildRectangleOnScreen() {
mInstrumentation.runOnMainSync(new Runnable() {
public void run() {
mListView.setAdapter(mAdapter_countries);
}
});
mInstrumentation.waitForIdleSync();
TextView child = (TextView) mAdapter_countries.getView(0, null, mListView);
assertNotNull(child);
assertEquals(mCountryList[0], child.getText().toString());
Rect rect = new Rect(0, 0, 10, 10);
assertFalse(mListView.requestChildRectangleOnScreen(child, rect, false));
// TODO: how to check?
}
@TestTargetNew(
level = TestLevel.NOT_NECESSARY,
method = "onTouchEvent",
args = {android.view.MotionEvent.class}
)
public void testOnTouchEvent() {
// implementation details, do NOT test
}
@TestTargets({
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "canAnimate",
args = {}
),
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "setAdapter",
args = {android.widget.ListAdapter.class}
)
})
@UiThreadTest
public void testCanAnimate() {
MyListView listView = new MyListView(mActivity, mAttributeSet);
assertFalse(listView.canAnimate());
listView.setAdapter(mAdapter_countries);
assertFalse(listView.canAnimate());
LayoutAnimationController controller = new LayoutAnimationController(
mActivity, mAttributeSet);
listView.setLayoutAnimation(controller);
assertTrue(listView.canAnimate());
}
@TestTargetNew(
level = TestLevel.NOT_NECESSARY,
method = "dispatchDraw",
args = {android.graphics.Canvas.class}
)
@UiThreadTest
public void testDispatchDraw() {
// implementation details, do NOT test
}
@TestTargets({
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "findViewTraversal",
args = {int.class}
),
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "addHeaderView",
args = {android.view.View.class}
)
})
@UiThreadTest
public void testFindViewTraversal() {
MyListView listView = new MyListView(mActivity, mAttributeSet);
TextView headerView = (TextView) mActivity.findViewById(R.id.headerview1);
assertNull(listView.findViewTraversal(R.id.headerview1));
listView.addHeaderView(headerView);
assertNotNull(listView.findViewTraversal(R.id.headerview1));
assertSame(headerView, listView.findViewTraversal(R.id.headerview1));
}
@TestTargets({
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "findViewWithTagTraversal",
args = {java.lang.Object.class}
),
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "addHeaderView",
args = {android.view.View.class}
)
})
@UiThreadTest
public void testFindViewWithTagTraversal() {
MyListView listView = new MyListView(mActivity, mAttributeSet);
TextView headerView = (TextView) mActivity.findViewById(R.id.headerview1);
assertNull(listView.findViewWithTagTraversal("header"));
headerView.setTag("header");
listView.addHeaderView(headerView);
assertNotNull(listView.findViewWithTagTraversal("header"));
assertSame(headerView, listView.findViewWithTagTraversal("header"));
}
@TestTargetNew(
level = TestLevel.TODO,
method = "layoutChildren",
args = {}
)
@ToBeFixed(bug = "1695243", explanation = "Android API javadocs are incomplete")
public void testLayoutChildren() {
// TODO: how to test?
}
@TestTargetNew(
level = TestLevel.NOT_NECESSARY,
method = "onFinishInflate",
args = {}
)
public void testOnFinishInflate() {
// implementation details, do NOT test
}
@TestTargetNew(
level = TestLevel.NOT_NECESSARY,
method = "onFocusChanged",
args = {boolean.class, int.class, android.graphics.Rect.class}
)
public void testOnFocusChanged() {
// implementation details, do NOT test
}
@TestTargetNew(
level = TestLevel.NOT_NECESSARY,
method = "onMeasure",
args = {int.class, int.class}
)
public void testOnMeasure() {
// implementation details, do NOT test
}
/**
* MyListView for test
*/
private static class MyListView extends ListView {
public MyListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected boolean canAnimate() {
return super.canAnimate();
}
@Override
protected void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
}
@Override
protected View findViewTraversal(int id) {
return super.findViewTraversal(id);
}
@Override
protected View findViewWithTagTraversal(Object tag) {
return super.findViewWithTagTraversal(tag);
}
@Override
protected void layoutChildren() {
super.layoutChildren();
}
}
private static class MockOnItemClickListener implements OnItemClickListener {
private View mView;
private int mPosition;
private long mID;
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mView = view;
mPosition = position;
mID = id;
}
public View getView() {
return mView;
}
public int getPosition() {
return mPosition;
}
public long getID() {
return mID;
}
}
/**
* The following functions are merged from frameworktest.
*/
@TestTargets({
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "layoutChildren",
args = {}
),
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "setAdapter",
args = {android.widget.ListAdapter.class}
)
})
@MediumTest
public void testRequestLayout() throws Exception {
ListView listView = new ListView(mActivity);
List<String> items = Lists.newArrayList("hello");
Adapter<String> adapter = new Adapter<String>(mActivity, 0, items);
listView.setAdapter(adapter);
int measureSpec = View.MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.EXACTLY);
adapter.notifyDataSetChanged();
listView.measure(measureSpec, measureSpec);
listView.layout(0, 0, 100, 100);
MockView childView = (MockView) listView.getChildAt(0);
childView.requestLayout();
childView.onMeasureCalled = false;
listView.measure(measureSpec, measureSpec);
listView.layout(0, 0, 100, 100);
Assert.assertTrue(childView.onMeasureCalled);
}
@TestTargets({
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "setSelection",
args = {int.class}
),
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "setAdapter",
args = {android.widget.ListAdapter.class}
)
})
@MediumTest
public void testNoSelectableItems() throws Exception {
ListView listView = new ListView(mActivity);
// We use a header as the unselectable item to remain after the selectable one is removed.
listView.addHeaderView(new View(mActivity), null, false);
List<String> items = Lists.newArrayList("hello");
Adapter<String> adapter = new Adapter<String>(mActivity, 0, items);
listView.setAdapter(adapter);
listView.setSelection(1);
int measureSpec = View.MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.EXACTLY);
adapter.notifyDataSetChanged();
listView.measure(measureSpec, measureSpec);
listView.layout(0, 0, 100, 100);
items.remove(0);
adapter.notifyDataSetChanged();
listView.measure(measureSpec, measureSpec);
listView.layout(0, 0, 100, 100);
}
private class MockView extends View {
public boolean onMeasureCalled = false;
public MockView(Context context) {
super(context);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
onMeasureCalled = true;
}
}
private class Adapter<T> extends ArrayAdapter<T> {
public Adapter(Context context, int resource, List<T> objects) {
super(context, resource, objects);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
return new MockView(getContext());
}
}
}
| false | true | public void testAccessItemChecked() {
// NONE mode
mListView.setChoiceMode(ListView.CHOICE_MODE_NONE);
assertEquals(ListView.CHOICE_MODE_NONE, mListView.getChoiceMode());
mListView.setItemChecked(1, true);
assertEquals(ListView.INVALID_POSITION, mListView.getCheckedItemPosition());
assertFalse(mListView.isItemChecked(1));
// SINGLE mode
mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
assertEquals(ListView.CHOICE_MODE_SINGLE, mListView.getChoiceMode());
mListView.setItemChecked(2, true);
assertEquals(2, mListView.getCheckedItemPosition());
assertTrue(mListView.isItemChecked(2));
mListView.setItemChecked(3, true);
assertEquals(3, mListView.getCheckedItemPosition());
assertTrue(mListView.isItemChecked(3));
assertFalse(mListView.isItemChecked(2));
// test attempt to uncheck a item that wasn't checked to begin with
mListView.setItemChecked(4, false);
// item three should still be checked, but current ListView behavior unchecks all items
assertEquals(ListView.INVALID_POSITION, mListView.getCheckedItemPosition());
assertFalse(mListView.isItemChecked(4));
// should be assertTrue
assertFalse(mListView.isItemChecked(3));
assertFalse(mListView.isItemChecked(2));
mListView.setItemChecked(4, true);
assertTrue(mListView.isItemChecked(4));
mListView.clearChoices();
assertEquals(ListView.INVALID_POSITION, mListView.getCheckedItemPosition());
assertFalse(mListView.isItemChecked(4));
// MULTIPLE mode
mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
assertEquals(ListView.CHOICE_MODE_MULTIPLE, mListView.getChoiceMode());
mListView.setItemChecked(1, true);
assertEquals(ListView.INVALID_POSITION, mListView.getCheckedItemPosition());
SparseBooleanArray array = mListView.getCheckedItemPositions();
assertTrue(array.get(1));
assertFalse(array.get(2));
assertTrue(mListView.isItemChecked(1));
assertFalse(mListView.isItemChecked(2));
mListView.setItemChecked(2, true);
mListView.setItemChecked(3, false);
mListView.setItemChecked(4, true);
assertTrue(array.get(1));
assertTrue(array.get(2));
assertFalse(array.get(3));
assertTrue(array.get(4));
assertTrue(mListView.isItemChecked(1));
assertTrue(mListView.isItemChecked(2));
assertFalse(mListView.isItemChecked(3));
assertTrue(mListView.isItemChecked(4));
mListView.clearChoices();
assertFalse(array.get(1));
assertFalse(array.get(2));
assertFalse(array.get(3));
assertFalse(array.get(4));
assertFalse(mListView.isItemChecked(1));
assertFalse(mListView.isItemChecked(2));
assertFalse(mListView.isItemChecked(3));
assertFalse(mListView.isItemChecked(4));
}
| public void testAccessItemChecked() {
// NONE mode
mListView.setChoiceMode(ListView.CHOICE_MODE_NONE);
assertEquals(ListView.CHOICE_MODE_NONE, mListView.getChoiceMode());
mListView.setItemChecked(1, true);
assertEquals(ListView.INVALID_POSITION, mListView.getCheckedItemPosition());
assertFalse(mListView.isItemChecked(1));
// SINGLE mode
mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
assertEquals(ListView.CHOICE_MODE_SINGLE, mListView.getChoiceMode());
mListView.setItemChecked(2, true);
assertEquals(2, mListView.getCheckedItemPosition());
assertTrue(mListView.isItemChecked(2));
mListView.setItemChecked(3, true);
assertEquals(3, mListView.getCheckedItemPosition());
assertTrue(mListView.isItemChecked(3));
assertFalse(mListView.isItemChecked(2));
// test attempt to uncheck a item that wasn't checked to begin with
mListView.setItemChecked(4, false);
// item three should still be checked
assertEquals(3, mListView.getCheckedItemPosition());
assertFalse(mListView.isItemChecked(4));
assertTrue(mListView.isItemChecked(3));
assertFalse(mListView.isItemChecked(2));
mListView.setItemChecked(4, true);
assertTrue(mListView.isItemChecked(4));
mListView.clearChoices();
assertEquals(ListView.INVALID_POSITION, mListView.getCheckedItemPosition());
assertFalse(mListView.isItemChecked(4));
// MULTIPLE mode
mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
assertEquals(ListView.CHOICE_MODE_MULTIPLE, mListView.getChoiceMode());
mListView.setItemChecked(1, true);
assertEquals(ListView.INVALID_POSITION, mListView.getCheckedItemPosition());
SparseBooleanArray array = mListView.getCheckedItemPositions();
assertTrue(array.get(1));
assertFalse(array.get(2));
assertTrue(mListView.isItemChecked(1));
assertFalse(mListView.isItemChecked(2));
mListView.setItemChecked(2, true);
mListView.setItemChecked(3, false);
mListView.setItemChecked(4, true);
assertTrue(array.get(1));
assertTrue(array.get(2));
assertFalse(array.get(3));
assertTrue(array.get(4));
assertTrue(mListView.isItemChecked(1));
assertTrue(mListView.isItemChecked(2));
assertFalse(mListView.isItemChecked(3));
assertTrue(mListView.isItemChecked(4));
mListView.clearChoices();
assertFalse(array.get(1));
assertFalse(array.get(2));
assertFalse(array.get(3));
assertFalse(array.get(4));
assertFalse(mListView.isItemChecked(1));
assertFalse(mListView.isItemChecked(2));
assertFalse(mListView.isItemChecked(3));
assertFalse(mListView.isItemChecked(4));
}
|
diff --git a/luni/src/main/java/java/lang/ref/FinalizerReference.java b/luni/src/main/java/java/lang/ref/FinalizerReference.java
index a3f90248d..2d5cef20b 100644
--- a/luni/src/main/java/java/lang/ref/FinalizerReference.java
+++ b/luni/src/main/java/java/lang/ref/FinalizerReference.java
@@ -1,76 +1,76 @@
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package java.lang.ref;
import java.lang.FinalizerThread;
/**
* @hide
*/
public final class FinalizerReference<T> extends Reference<T> {
private static FinalizerReference head = null;
private T zombie;
private FinalizerReference prev;
private FinalizerReference next;
public FinalizerReference(T r, ReferenceQueue<? super T> q) {
super(r, q);
}
@Override
public T get() {
return zombie;
}
@Override
public void clear() {
zombie = null;
}
static void add(Object referent) {
ReferenceQueue<Object> queue = FinalizerThread.queue;
FinalizerReference<?> reference = new FinalizerReference<Object>(referent, queue);
synchronized (FinalizerReference.class) {
reference.prev = null;
reference.next = head;
if (head != null) {
head.prev = reference;
}
head = reference;
}
}
public static void remove(FinalizerReference reference) {
synchronized (FinalizerReference.class) {
FinalizerReference next = reference.next;
FinalizerReference prev = reference.prev;
reference.next = null;
reference.prev = null;
if (prev != null) {
prev.next = next;
} else {
- head = reference;
+ head = next;
}
if (next != null) {
next.prev = prev;
}
}
}
}
| true | true | public static void remove(FinalizerReference reference) {
synchronized (FinalizerReference.class) {
FinalizerReference next = reference.next;
FinalizerReference prev = reference.prev;
reference.next = null;
reference.prev = null;
if (prev != null) {
prev.next = next;
} else {
head = reference;
}
if (next != null) {
next.prev = prev;
}
}
}
| public static void remove(FinalizerReference reference) {
synchronized (FinalizerReference.class) {
FinalizerReference next = reference.next;
FinalizerReference prev = reference.prev;
reference.next = null;
reference.prev = null;
if (prev != null) {
prev.next = next;
} else {
head = next;
}
if (next != null) {
next.prev = prev;
}
}
}
|
diff --git a/src/com/android/mms/ui/MessageListItem.java b/src/com/android/mms/ui/MessageListItem.java
index 6dd56cd8..9b99735d 100644
--- a/src/com/android/mms/ui/MessageListItem.java
+++ b/src/com/android/mms/ui/MessageListItem.java
@@ -1,1052 +1,1055 @@
/*
* Copyright (C) 2008 Esmertec AG.
* 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.mms.ui;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Paint.FontMetricsInt;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.provider.ContactsContract.Profile;
import android.provider.Settings;
import android.provider.Telephony.Sms;
import android.telephony.PhoneNumberUtils;
import android.telephony.TelephonyManager;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.LineHeightSpan;
import android.text.style.StyleSpan;
import android.text.style.TextAppearanceSpan;
import android.text.style.URLSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.MarginLayoutParams;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.QuickContactBadge;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.android.mms.MmsApp;
import com.android.mms.R;
import com.android.mms.data.Contact;
import com.android.mms.data.WorkingMessage;
import com.android.mms.model.SlideModel;
import com.android.mms.model.SlideshowModel;
import com.android.mms.themes.ColorFilterMaker;
import com.android.mms.themes.Constants;
import com.android.mms.transaction.SmsReceiverService;
import com.android.mms.transaction.Transaction;
import com.android.mms.transaction.TransactionBundle;
import com.android.mms.transaction.TransactionService;
import com.android.mms.util.DownloadManager;
import com.android.mms.util.ItemLoadedCallback;
import com.android.mms.util.ThumbnailManager.ImageLoaded;
import com.google.android.mms.ContentType;
import com.google.android.mms.pdu.PduHeaders;
/**
* This class provides view of a message in the messages list.
*/
public class MessageListItem extends LinearLayout implements
SlideViewInterface, OnClickListener {
public static final String EXTRA_URLS = "com.android.mms.ExtraUrls";
private static final String TAG = "MessageListItem";
private static final boolean DEBUG = false;
private static final boolean DEBUG_DONT_LOAD_IMAGES = false;
static final int MSG_LIST_EDIT = 1;
static final int MSG_LIST_PLAY = 2;
static final int MSG_LIST_DETAILS = 3;
private View mMmsView;
private ImageView mImageView;
private ImageView mLockedIndicator;
private ImageView mDeliveredIndicator;
private ImageView mDetailsIndicator;
private ImageButton mSlideShowButton;
private TextView mBodyTextView;
private Button mDownloadButton;
private TextView mDownloadingLabel;
private Handler mHandler;
public MessageItem mMessageItem;
private String mDefaultCountryIso;
private TextView mDateView;
public View mMessageBlock;
private View mMessageLayout;
private QuickContactBadge mAvatar;
static private Drawable sDefaultContactImage;
private Presenter mPresenter;
private int mPosition; // for debugging
private ImageLoadedCallback mImageLoadedCallback;
private boolean mMultiRecipients;
// Theme settings
private boolean mUseContact;
private int mSentTextBgColor;
private int mRecvTextBgColor;
private SharedPreferences sp;
private Resources res;
public MessageListItem(Context context) {
super(context);
mDefaultCountryIso = MmsApp.getApplication().getCurrentCountryIso();
if (sDefaultContactImage == null) {
sDefaultContactImage = context.getResources().getDrawable(R.drawable.ic_contact_picture);
}
}
public MessageListItem(Context context, AttributeSet attrs) {
super(context, attrs);
res = mContext.getResources();
int color = res.getColor(R.color.timestamp_color);
mColorSpan = new ForegroundColorSpan(color);
mDefaultCountryIso = MmsApp.getApplication().getCurrentCountryIso();
if (sDefaultContactImage == null) {
sDefaultContactImage = context.getResources().getDrawable(R.drawable.ic_contact_picture);
}
sp = PreferenceManager.getDefaultSharedPreferences(mContext);
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
mBodyTextView = (TextView) findViewById(R.id.text_view);
mDateView = (TextView) findViewById(R.id.date_view);
mLockedIndicator = (ImageView) findViewById(R.id.locked_indicator);
mDeliveredIndicator = (ImageView) findViewById(R.id.delivered_indicator);
mDetailsIndicator = (ImageView) findViewById(R.id.details_indicator);
mAvatar = (QuickContactBadge) findViewById(R.id.avatar);
mMessageBlock = findViewById(R.id.message_block);
mMessageLayout = findViewById(R.id.message_layout);
}
// Message block background
private void getMessageBlockBackground() {
String layoutType = sp.getString(Constants.PREF_TEXT_CONV_LAYOUT, "default");
String bubbleType = sp.getString(Constants.PREF_BUBBLE_TYPE, "circle_holo");
boolean bubbleWrap = sp.getBoolean(Constants.PREF_BUBBLE_FILL_PARENT, false);
boolean layoutLeft = layoutType.equals("layoutLeft");
boolean layoutRight = layoutType.equals("layoutRight");
// Set bubble layout type
mMessageBlock.getLayoutParams().width = bubbleWrap ?
LayoutParams.MATCH_PARENT : LayoutParams.WRAP_CONTENT;
if (mMessageItem.getBoxId() == 1) {
if (bubbleType.equals("bubble_none")) {
mMessageLayout.setBackgroundColor(mRecvTextBgColor);
} else if (bubbleType.equals("bubble")) {
mMessageBlock.setBackgroundResource(R.drawable.bubble);
mMessageBlock.getBackground().setColorFilter(ColorFilterMaker.
changeColorAlpha(mRecvTextBgColor, .32f,0f));
} else if (bubbleType.equals("circle")) {
mMessageBlock.setBackgroundResource(layoutRight ?
R.drawable.bubble_circle_sent : R.drawable.bubble_circle_recv);
mMessageBlock.getBackground().setColorFilter(ColorFilterMaker.
changeColorAlpha(mRecvTextBgColor, .32f,0f));
} else if (bubbleType.equals("circle_holo")) {
mMessageBlock.setBackgroundResource(layoutRight ?
R.drawable.bubble_circle_holo_sent : R.drawable.bubble_circle_holo_recv);
mMessageBlock.getBackground().setColorFilter(ColorFilterMaker.
changeColorAlpha(mRecvTextBgColor, .32f,0f));
} else if (bubbleType.equals("rect")) {
mMessageBlock.setBackgroundResource(layoutRight ?
R.drawable.bubble_sent : R.drawable.bubble_recv);
mMessageBlock.getBackground().setColorFilter(ColorFilterMaker.
changeColorAlpha(mRecvTextBgColor, .32f,0f));
} else if (bubbleType.equals("rect_holo")) {
mMessageBlock.setBackgroundResource(layoutRight ?
R.drawable.bubble_holo_sent : R.drawable.bubble_holo_recv);
mMessageBlock.getBackground().setColorFilter(ColorFilterMaker.
changeColorAlpha(mRecvTextBgColor, .32f,0f));
} /* else if (bubbleType.equals("frame_holo")) {
mMessageBlock.setBackgroundResource(R.drawable.bubble_frame_holo);
mMessageBlock.getBackground().setColorFilter(ColorFilterMaker.
changeColorAlpha(mRecvTextBgColor, .32f,0f));
} else if (bubbleType.equals("frame2")) {
mMessageBlock.setBackgroundResource(layoutRight ?
R.drawable.bubble_frame_sent : R.drawable.bubble_frame_recv);
mMessageBlock.getBackground().setColorFilter(ColorFilterMaker.
changeColorAlpha(mRecvTextBgColor, .32f,0f));
} */
} else {
if (bubbleType.equals("bubble_none")) {
mMessageLayout.setBackgroundColor(mSentTextBgColor);
} else if (bubbleType.equals("bubble")) {
mMessageBlock.setBackgroundResource(R.drawable.bubble);
mMessageBlock.getBackground().setColorFilter(ColorFilterMaker.
changeColorAlpha(mSentTextBgColor, .32f,0f));
} else if (bubbleType.equals("circle")) {
mMessageBlock.setBackgroundResource(layoutLeft ?
R.drawable.bubble_circle_recv : R.drawable.bubble_circle_sent);
mMessageBlock.getBackground().setColorFilter(ColorFilterMaker.
changeColorAlpha(mSentTextBgColor, .32f,0f));
} else if (bubbleType.equals("circle_holo")) {
mMessageBlock.setBackgroundResource(layoutLeft ?
R.drawable.bubble_circle_holo_recv : R.drawable.bubble_circle_holo_sent);
mMessageBlock.getBackground().setColorFilter(ColorFilterMaker.
changeColorAlpha(mSentTextBgColor, .32f,0f));
} else if (bubbleType.equals("rect")) {
mMessageBlock.setBackgroundResource(layoutLeft ?
R.drawable.bubble_recv : R.drawable.bubble_sent);
mMessageBlock.getBackground().setColorFilter(ColorFilterMaker.
changeColorAlpha(mSentTextBgColor, .32f,0f));
} else if (bubbleType.equals("rect_holo")) {
mMessageBlock.setBackgroundResource(layoutLeft ?
R.drawable.bubble_holo_recv : R.drawable.bubble_holo_sent);
mMessageBlock.getBackground().setColorFilter(ColorFilterMaker.
changeColorAlpha(mSentTextBgColor, .32f,0f));
} /* else if (bubbleType.equals("frame_holo")) {
mMessageBlock.setBackgroundResource(R.drawable.bubble_frame_holo);
mMessageBlock.getBackground().setColorFilter(ColorFilterMaker.
changeColorAlpha(mSentTextBgColor, .32f,0f));
} else if (bubbleType.equals("frame2")) {
mMessageBlock.setBackgroundResource(layoutLeft ?
R.drawable.bubble_frame_recv : R.drawable.bubble_frame_sent);
mMessageBlock.getBackground().setColorFilter(ColorFilterMaker.
changeColorAlpha(mSentTextBgColor, .32f,0f));
} */
}
}
public void bind(MessageItem msgItem, boolean convHasMultiRecipients, int position) {
if (DEBUG) {
Log.v(TAG, "bind for item: " + position + " old: " +
(mMessageItem != null ? mMessageItem.toString() : "NULL" ) +
" new " + msgItem.toString());
}
boolean sameItem = mMessageItem != null && mMessageItem.mMsgId == msgItem.mMsgId;
mMessageItem = msgItem;
mPosition = position;
mMultiRecipients = convHasMultiRecipients;
// Theme settings
mSentTextBgColor = sp.getInt(Constants.PREF_SENT_TEXT_BG, res.getColor(
R.color.default_sent_text_bg));
mRecvTextBgColor = sp.getInt(Constants.PREF_RECV_TEXT_BG, res.getColor(
R.color.default_recv_text_bg));
getMessageBlockBackground();
mUseContact = sp.getBoolean(Constants.PREF_USE_CONTACT, false);
setLongClickable(false);
setClickable(false); // let the list view handle clicks on the item normally. When
// clickable is true, clicks bypass the listview and go straight
// to this listitem. We always want the listview to handle the
// clicks first.
switch (msgItem.mMessageType) {
case PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND:
bindNotifInd();
break;
default:
bindCommonMessage(sameItem);
break;
}
}
public void unbind() {
// Clear all references to the message item, which can contain attachments and other
// memory-intensive objects
if (mImageView != null) {
// Because #setOnClickListener may have set the listener to an object that has the
// message item in its closure.
mImageView.setOnClickListener(null);
}
if (mSlideShowButton != null) {
// Because #drawPlaybackButton sets the tag to mMessageItem
mSlideShowButton.setTag(null);
}
// leave the presenter in case it's needed when rebound to a different MessageItem.
if (mPresenter != null) {
mPresenter.cancelBackgroundLoading();
}
}
public MessageItem getMessageItem() {
return mMessageItem;
}
public void setMsgListItemHandler(Handler handler) {
mHandler = handler;
}
private void bindNotifInd() {
showMmsView(false);
String msgSizeText = mContext.getString(R.string.message_size_label)
+ String.valueOf((mMessageItem.mMessageSize + 1023) / 1024)
+ mContext.getString(R.string.kilobyte);
mBodyTextView.setText(formatMessage(mMessageItem, mMessageItem.mContact, null,
mMessageItem.mSubject,
mMessageItem.mHighlight,
mMessageItem.mTextContentType));
mDateView.setText(buildTimestampLine(msgSizeText + " " + mMessageItem.mTimestamp));
// Set date and background colors
int mColor = 0;
if (mMessageItem.getBoxId() == 1) {
mColor = sp.getInt(Constants.PREF_RECV_DATE_COLOR, res.getColor(
R.color.default_recv_datecolor));
} else {
mColor = sp.getInt(Constants.PREF_SENT_DATE_COLOR, res.getColor(
R.color.default_sent_datecolor));
}
mDateView.setBackgroundColor(0x00000000);
mDateView.setTextColor(mColor);
switch (mMessageItem.getMmsDownloadStatus()) {
case DownloadManager.STATE_PRE_DOWNLOADING:
case DownloadManager.STATE_DOWNLOADING:
showDownloadingAttachment();
break;
case DownloadManager.STATE_UNKNOWN:
case DownloadManager.STATE_UNSTARTED:
DownloadManager downloadManager = DownloadManager.getInstance();
boolean autoDownload = downloadManager.isAuto();
boolean dataSuspended = (MmsApp.getApplication().getTelephonyManager()
.getDataState() == TelephonyManager.DATA_SUSPENDED);
// If we're going to automatically start downloading the mms attachment, then
// don't bother showing the download button for an instant before the actual
// download begins. Instead, show downloading as taking place.
if (autoDownload && !dataSuspended) {
showDownloadingAttachment();
break;
}
case DownloadManager.STATE_TRANSIENT_FAILURE:
case DownloadManager.STATE_PERMANENT_FAILURE:
default:
setLongClickable(true);
inflateDownloadControls();
mDownloadingLabel.setVisibility(View.GONE);
mDownloadButton.setVisibility(View.VISIBLE);
mDownloadButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mDownloadingLabel.setVisibility(View.VISIBLE);
mDownloadButton.setVisibility(View.GONE);
Intent intent = new Intent(mContext, TransactionService.class);
intent.putExtra(TransactionBundle.URI, mMessageItem.mMessageUri.toString());
intent.putExtra(TransactionBundle.TRANSACTION_TYPE,
Transaction.RETRIEVE_TRANSACTION);
mContext.startService(intent);
DownloadManager.getInstance().markState(
mMessageItem.mMessageUri, DownloadManager.STATE_PRE_DOWNLOADING);
}
});
break;
}
// Hide the indicators.
mLockedIndicator.setVisibility(View.GONE);
mDeliveredIndicator.setVisibility(View.GONE);
mDetailsIndicator.setVisibility(View.GONE);
updateAvatarView(mMessageItem.mAddress, false);
}
private String buildTimestampLine(String timestamp) {
if (!mMultiRecipients || mMessageItem.isMe() || TextUtils.isEmpty(mMessageItem.mContact)) {
// Never show "Me" for messages I sent.
return timestamp;
}
// This is a group conversation, show the sender's name on the same line as the timestamp.
return mContext.getString(R.string.message_timestamp_format, mMessageItem.mContact,
timestamp);
}
private void showDownloadingAttachment() {
inflateDownloadControls();
mDownloadingLabel.setVisibility(View.VISIBLE);
mDownloadButton.setVisibility(View.GONE);
}
private void updateAvatarView(String addr, boolean isSelf) {
Drawable avatarDrawable;
if (isSelf || !TextUtils.isEmpty(addr)) {
Contact contact = isSelf ? Contact.getMe(false) : Contact.get(addr, false);
avatarDrawable = contact.getAvatar(mContext, sDefaultContactImage);
if (isSelf) {
mAvatar.assignContactUri(Profile.CONTENT_URI);
} else {
if (contact.existsInDatabase()) {
mAvatar.assignContactUri(contact.getUri());
} else {
mAvatar.assignContactFromPhone(contact.getNumber(), true);
}
}
} else {
avatarDrawable = sDefaultContactImage;
}
mAvatar.setImageDrawable(avatarDrawable);
// Show/Hide the avatar
if (sp.getBoolean(Constants.PREF_SHOW_AVATAR, true)) {
mAvatar.setVisibility(View.VISIBLE);
} else {
mAvatar.setVisibility(View.GONE);
}
}
private void bindCommonMessage(final boolean sameItem) {
if (mDownloadButton != null) {
mDownloadButton.setVisibility(View.GONE);
mDownloadingLabel.setVisibility(View.GONE);
}
// Since the message text should be concatenated with the sender's
// address(or name), I have to display it here instead of
// displaying it by the Presenter.
mBodyTextView.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
boolean haveLoadedPdu = mMessageItem.isSms() || mMessageItem.mSlideshow != null;
// Here we're avoiding reseting the avatar to the empty avatar when we're rebinding
// to the same item. This happens when there's a DB change which causes the message item
// cache in the MessageListAdapter to get cleared. When an mms MessageItem is newly
// created, it has no info in it except the message id. The info is eventually loaded
// and bindCommonMessage is called again (see onPduLoaded below). When we haven't loaded
// the pdu, we don't want to call updateAvatarView because it
// will set the avatar to the generic avatar then when this method is called again
// from onPduLoaded, it will reset to the real avatar. This test is to avoid that flash.
if (!sameItem || haveLoadedPdu) {
boolean isSelf = Sms.isOutgoingFolder(mMessageItem.mBoxId);
String addr = isSelf ? null : mMessageItem.mAddress;
updateAvatarView(addr, isSelf);
}
// Get and/or lazily set the formatted message from/on the
// MessageItem. Because the MessageItem instances come from a
// cache (currently of size ~50), the hit rate on avoiding the
// expensive formatMessage() call is very high.
CharSequence formattedMessage = mMessageItem.getCachedFormattedMessage();
if (formattedMessage == null) {
formattedMessage = formatMessage(mMessageItem, mMessageItem.mContact,
mMessageItem.mBody,
mMessageItem.mSubject,
mMessageItem.mHighlight,
mMessageItem.mTextContentType);
mMessageItem.setCachedFormattedMessage(formattedMessage);
}
if (!sameItem || haveLoadedPdu) {
mBodyTextView.setText(formattedMessage);
}
int textFontSize = sp.getInt(Constants.PREF_FONT_SIZE, 16);
mBodyTextView.setTextSize(textFontSize);
// Debugging code to put the URI of the image attachment in the body of the list item.
if (DEBUG) {
String debugText = null;
if (mMessageItem.mSlideshow == null) {
debugText = "NULL slideshow";
} else {
SlideModel slide = mMessageItem.mSlideshow.get(0);
if (slide == null) {
debugText = "NULL first slide";
} else if (!slide.hasImage()) {
debugText = "Not an image";
} else {
debugText = slide.getImage().getUri().toString();
}
}
mBodyTextView.setText(mPosition + ": " + debugText);
}
// If we're in the process of sending a message (i.e. pending), then we show a "SENDING..."
// string in place of the timestamp.
if (!sameItem || haveLoadedPdu) {
boolean isCountingDown = mMessageItem.getCountDown() > 0 &&
MessagingPreferenceActivity.getMessageSendDelayDuration(mContext) > 0;
int sendingTextResId = isCountingDown
? R.string.sent_countdown : R.string.sending_message;
mDateView.setText(buildTimestampLine(mMessageItem.isSending() ?
res.getString(sendingTextResId) : mMessageItem.mTimestamp));
}
// Set date and background colors
int mColor = 0;
if (mMessageItem.getBoxId() == 1) {
mColor = sp.getInt(Constants.PREF_RECV_DATE_COLOR, res.getColor(
R.color.default_recv_datecolor));
} else {
mColor = sp.getInt(Constants.PREF_SENT_DATE_COLOR, res.getColor(
R.color.default_sent_datecolor));
}
int dateFontSize = sp.getInt(Constants.PREF_DATE_FONT_SIZE, 16);
mDateView.setTextSize(dateFontSize);
mDateView.setBackgroundColor(0x00000000);
mDateView.setTextColor(mColor);
if (mMessageItem.isSms()) {
showMmsView(false);
mMessageItem.setOnPduLoaded(null);
} else {
if (DEBUG) {
Log.v(TAG, "bindCommonMessage for item: " + mPosition + " " +
mMessageItem.toString() +
" mMessageItem.mAttachmentType: " + mMessageItem.mAttachmentType +
" sameItem: " + sameItem);
}
if (mMessageItem.mAttachmentType != WorkingMessage.TEXT) {
if (!sameItem) {
setImage(null, null);
}
setOnClickListener(mMessageItem);
drawPlaybackButton(mMessageItem);
} else {
showMmsView(false);
}
if (mMessageItem.mSlideshow == null) {
+ final int mCurrentAttachmentType = mMessageItem.mAttachmentType;
mMessageItem.setOnPduLoaded(new MessageItem.PduLoadedCallback() {
public void onPduLoaded(MessageItem messageItem) {
if (DEBUG) {
Log.v(TAG, "PduLoadedCallback in MessageListItem for item: " + mPosition +
" " + (mMessageItem == null ? "NULL" : mMessageItem.toString()) +
" passed in item: " +
(messageItem == null ? "NULL" : messageItem.toString()));
}
if (messageItem != null && mMessageItem != null &&
messageItem.getMessageId() == mMessageItem.getMessageId()) {
mMessageItem.setCachedFormattedMessage(null);
- bindCommonMessage(true);
+ boolean isStillSame =
+ mCurrentAttachmentType == messageItem.mAttachmentType;
+ bindCommonMessage(isStillSame);
}
}
});
} else {
if (mPresenter == null) {
mPresenter = PresenterFactory.getPresenter(
"MmsThumbnailPresenter", mContext,
this, mMessageItem.mSlideshow);
} else {
mPresenter.setModel(mMessageItem.mSlideshow);
mPresenter.setView(this);
}
if (mImageLoadedCallback == null) {
mImageLoadedCallback = new ImageLoadedCallback(this);
} else {
mImageLoadedCallback.reset(this);
}
mPresenter.present(mImageLoadedCallback);
}
}
drawRightStatusIndicator(mMessageItem);
requestLayout();
}
static private class ImageLoadedCallback implements ItemLoadedCallback<ImageLoaded> {
private long mMessageId;
private final MessageListItem mListItem;
public ImageLoadedCallback(MessageListItem listItem) {
mListItem = listItem;
mMessageId = listItem.getMessageItem().getMessageId();
}
public void reset(MessageListItem listItem) {
mMessageId = listItem.getMessageItem().getMessageId();
}
public void onItemLoaded(ImageLoaded imageLoaded, Throwable exception) {
if (DEBUG_DONT_LOAD_IMAGES) {
return;
}
// Make sure we're still pointing to the same message. The list item could have
// been recycled.
MessageItem msgItem = mListItem.mMessageItem;
if (msgItem != null && msgItem.getMessageId() == mMessageId) {
if (imageLoaded.mIsVideo) {
mListItem.setVideoThumbnail(null, imageLoaded.mBitmap);
} else {
mListItem.setImage(null, imageLoaded.mBitmap);
}
}
}
}
@Override
public void startAudio() {
// TODO Auto-generated method stub
}
@Override
public void startVideo() {
// TODO Auto-generated method stub
}
@Override
public void setAudio(Uri audio, String name, Map<String, ?> extras) {
// TODO Auto-generated method stub
}
@Override
public void setImage(String name, Bitmap bitmap) {
showMmsView(true);
try {
mImageView.setImageBitmap(bitmap);
mImageView.setVisibility(VISIBLE);
} catch (java.lang.OutOfMemoryError e) {
Log.e(TAG, "setImage: out of memory: ", e);
}
}
private void showMmsView(boolean visible) {
if (mMmsView == null) {
mMmsView = findViewById(R.id.mms_view);
// if mMmsView is still null here, that mean the mms section hasn't been inflated
if (visible && mMmsView == null) {
//inflate the mms view_stub
View mmsStub = findViewById(R.id.mms_layout_view_stub);
mmsStub.setVisibility(View.VISIBLE);
mMmsView = findViewById(R.id.mms_view);
}
}
if (mMmsView != null) {
if (mImageView == null) {
mImageView = (ImageView) findViewById(R.id.image_view);
}
if (mSlideShowButton == null) {
mSlideShowButton = (ImageButton) findViewById(R.id.play_slideshow_button);
}
mMmsView.setVisibility(visible ? View.VISIBLE : View.GONE);
mImageView.setVisibility(visible ? View.VISIBLE : View.GONE);
}
}
private void inflateDownloadControls() {
if (mDownloadButton == null) {
//inflate the download controls
findViewById(R.id.mms_downloading_view_stub).setVisibility(VISIBLE);
mDownloadButton = (Button) findViewById(R.id.btn_download_msg);
mDownloadingLabel = (TextView) findViewById(R.id.label_downloading);
}
}
private LineHeightSpan mSpan = new LineHeightSpan() {
@Override
public void chooseHeight(CharSequence text, int start,
int end, int spanstartv, int v, FontMetricsInt fm) {
fm.ascent -= 10;
}
};
TextAppearanceSpan mTextSmallSpan =
new TextAppearanceSpan(mContext, android.R.style.TextAppearance_Small);
ForegroundColorSpan mColorSpan = null; // set in ctor
private CharSequence formatMessage(MessageItem msgItem, String contact, String body,
String subject, Pattern highlight,
String contentType) {
SpannableStringBuilder buf = new SpannableStringBuilder();
// Show the contact if set and apply colors
int mColor = 0;
int contactLength = 0;
if (mUseContact) {
try {
contactLength = msgItem.mContact.length() + 1;
} catch (NullPointerException e) {
}
if (mMessageItem.getBoxId() == 1) {
mColor = sp.getInt(Constants.PREF_RECV_CONTACT_COLOR, res.getColor(
R.color.default_recv_contact_color));
} else {
mColor = sp.getInt(Constants.PREF_SENT_CONTACT_COLOR, res.getColor(
R.color.default_sent_contact_color));
}
int contactFontSize = sp.getInt(Constants.PREF_CONTACT_FONT_SIZE, 16);
buf.append(msgItem.mContact + ": ");
buf.setSpan(new StyleSpan(Typeface.BOLD), 0, contactLength, 0);
buf.setSpan(new AbsoluteSizeSpan(contactFontSize, true), 0, contactLength, 0);
buf.setSpan(new ForegroundColorSpan(mColor), 0, contactLength, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
boolean hasSubject = !TextUtils.isEmpty(subject);
if (hasSubject) {
buf.append(res.getString(R.string.inline_subject, subject));
}
if (!TextUtils.isEmpty(body)) {
// Converts html to spannable if ContentType is "text/html".
if (contentType != null && ContentType.TEXT_HTML.equals(contentType)) {
buf.append("\n");
buf.append(Html.fromHtml(body));
} else {
if (hasSubject) {
buf.append(" - ");
}
buf.append(body);
}
}
// Set the color of the text for messages
mColor = 0;
if (mMessageItem.getBoxId() == 1) {
mColor = sp.getInt(Constants.PREF_RECV_TEXTCOLOR, res.getColor(
R.color.default_recv_textcolor));
} else {
mColor = sp.getInt(Constants.PREF_SENT_TEXTCOLOR, res.getColor(
R.color.default_sent_textcolor));
}
buf.setSpan(new ForegroundColorSpan(mColor), contactLength, buf.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
if (highlight != null) {
Matcher m = highlight.matcher(buf.toString());
while (m.find()) {
buf.setSpan(new StyleSpan(Typeface.BOLD), m.start(), m.end(), 0);
}
}
return buf;
}
private void drawPlaybackButton(MessageItem msgItem) {
switch (msgItem.mAttachmentType) {
case WorkingMessage.SLIDESHOW:
case WorkingMessage.AUDIO:
case WorkingMessage.VIDEO:
// Show the 'Play' button and bind message info on it.
mSlideShowButton.setTag(msgItem);
// Set call-back for the 'Play' button.
mSlideShowButton.setOnClickListener(this);
mSlideShowButton.setVisibility(View.VISIBLE);
setLongClickable(true);
// When we show the mSlideShowButton, this list item's onItemClickListener doesn't
// get called. (It gets set in ComposeMessageActivity:
// mMsgListView.setOnItemClickListener) Here we explicitly set the item's
// onClickListener. It allows the item to respond to embedded html links and at the
// same time, allows the slide show play button to work.
setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
onMessageListItemClick();
}
});
break;
default:
mSlideShowButton.setVisibility(View.GONE);
break;
}
}
// OnClick Listener for the playback button
@Override
public void onClick(View v) {
sendMessage(mMessageItem, MSG_LIST_PLAY);
}
private void sendMessage(MessageItem messageItem, int message) {
if (mHandler != null) {
Message msg = Message.obtain(mHandler, message);
msg.obj = messageItem;
msg.sendToTarget(); // See ComposeMessageActivity.mMessageListItemHandler.handleMessage
}
}
public void onMessageListItemClick() {
if (mMessageItem != null && mMessageItem.isSending() && mMessageItem.isSms()) {
SmsReceiverService.cancelSendingMessage(mMessageItem.mMessageUri);
return;
}
// If the message is a failed one, clicking it should reload it in the compose view,
// regardless of whether it has links in it
if (mMessageItem != null &&
mMessageItem.isOutgoingMessage() &&
mMessageItem.isFailedMessage() ) {
// Assuming the current message is a failed one, reload it into the compose view so
// the user can resend it.
sendMessage(mMessageItem, MSG_LIST_EDIT);
return;
}
// Check for links. If none, do nothing; if 1, open it; if >1, ask user to pick one
final URLSpan[] spans = mBodyTextView.getUrls();
if (spans.length == 0) {
sendMessage(mMessageItem, MSG_LIST_DETAILS); // show the message details dialog
} else if (spans.length == 1) {
spans[0].onClick(mBodyTextView);
} else {
ArrayAdapter<URLSpan> adapter =
new ArrayAdapter<URLSpan>(mContext, android.R.layout.select_dialog_item, spans) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = super.getView(position, convertView, parent);
try {
URLSpan span = getItem(position);
String url = span.getURL();
Uri uri = Uri.parse(url);
TextView tv = (TextView) v;
Drawable d = mContext.getPackageManager().getActivityIcon(
new Intent(Intent.ACTION_VIEW, uri));
if (d != null) {
d.setBounds(0, 0, d.getIntrinsicHeight(), d.getIntrinsicHeight());
tv.setCompoundDrawablePadding(10);
tv.setCompoundDrawables(d, null, null, null);
}
final String telPrefix = "tel:";
if (url.startsWith(telPrefix)) {
if ((mDefaultCountryIso == null) || mDefaultCountryIso.isEmpty()) {
url = url.substring(telPrefix.length());
}
else {
url = PhoneNumberUtils.formatNumber(
url.substring(telPrefix.length()), mDefaultCountryIso);
}
}
tv.setText(url);
} catch (android.content.pm.PackageManager.NameNotFoundException ex) {
// it's ok if we're unable to set the drawable for this view - the user
// can still use it
}
return v;
}
};
AlertDialog.Builder b = new AlertDialog.Builder(mContext);
DialogInterface.OnClickListener click = new DialogInterface.OnClickListener() {
@Override
public final void onClick(DialogInterface dialog, int which) {
if (which >= 0) {
spans[which].onClick(mBodyTextView);
}
dialog.dismiss();
}
};
b.setTitle(R.string.select_link_title);
b.setCancelable(true);
b.setAdapter(adapter, click);
b.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public final void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
b.show();
}
}
private void setOnClickListener(final MessageItem msgItem) {
switch(msgItem.mAttachmentType) {
case WorkingMessage.IMAGE:
case WorkingMessage.VIDEO:
mImageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
sendMessage(msgItem, MSG_LIST_PLAY);
}
});
mImageView.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return v.showContextMenu();
}
});
break;
default:
mImageView.setOnClickListener(null);
break;
}
}
private void drawRightStatusIndicator(MessageItem msgItem) {
// Locked icon
if (msgItem.mLocked) {
mLockedIndicator.setImageResource(R.drawable.ic_lock_message_sms);
mLockedIndicator.setVisibility(View.VISIBLE);
} else {
mLockedIndicator.setVisibility(View.GONE);
}
// Delivery icon - we can show a failed icon for both sms and mms, but for an actual
// delivery, we only show the icon for sms. We don't have the information here in mms to
// know whether the message has been delivered. For mms, msgItem.mDeliveryStatus set
// to MessageItem.DeliveryStatus.RECEIVED simply means the setting requesting a
// delivery report was turned on when the message was sent. Yes, it's confusing!
if ((msgItem.isOutgoingMessage() && msgItem.isFailedMessage()) ||
msgItem.mDeliveryStatus == MessageItem.DeliveryStatus.FAILED) {
mDeliveredIndicator.setImageResource(R.drawable.ic_list_alert_sms_failed);
mDeliveredIndicator.setVisibility(View.VISIBLE);
} else if (msgItem.isSms() &&
msgItem.mDeliveryStatus == MessageItem.DeliveryStatus.RECEIVED) {
mDeliveredIndicator.setImageResource(R.drawable.ic_sms_mms_delivered);
mDeliveredIndicator.setVisibility(View.VISIBLE);
} else {
mDeliveredIndicator.setVisibility(View.GONE);
}
// Message details icon - this icon is shown both for sms and mms messages. For mms,
// we show the icon if the read report or delivery report setting was set when the
// message was sent. Showing the icon tells the user there's more information
// by selecting the "View report" menu.
if (msgItem.mDeliveryStatus == MessageItem.DeliveryStatus.INFO || msgItem.mReadReport
|| (msgItem.isMms() &&
msgItem.mDeliveryStatus == MessageItem.DeliveryStatus.RECEIVED)) {
mDetailsIndicator.setImageResource(R.drawable.ic_sms_mms_details);
mDetailsIndicator.setVisibility(View.VISIBLE);
} else {
mDetailsIndicator.setVisibility(View.GONE);
}
}
@Override
public void setImageRegionFit(String fit) {
// TODO Auto-generated method stub
}
@Override
public void setImageVisibility(boolean visible) {
// TODO Auto-generated method stub
}
@Override
public void setText(String name, String text) {
// TODO Auto-generated method stub
}
@Override
public void setTextVisibility(boolean visible) {
// TODO Auto-generated method stub
}
@Override
public void setVideo(String name, Uri uri) {
}
@Override
public void setVideoThumbnail(String name, Bitmap bitmap) {
showMmsView(true);
try {
mImageView.setImageBitmap(bitmap);
mImageView.setVisibility(VISIBLE);
} catch (java.lang.OutOfMemoryError e) {
Log.e(TAG, "setVideo: out of memory: ", e);
}
}
@Override
public void setVideoVisibility(boolean visible) {
// TODO Auto-generated method stub
}
@Override
public void stopAudio() {
// TODO Auto-generated method stub
}
@Override
public void stopVideo() {
// TODO Auto-generated method stub
}
@Override
public void reset() {
}
@Override
public void setVisibility(boolean visible) {
// TODO Auto-generated method stub
}
@Override
public void pauseAudio() {
// TODO Auto-generated method stub
}
@Override
public void pauseVideo() {
// TODO Auto-generated method stub
}
@Override
public void seekAudio(int seekTo) {
// TODO Auto-generated method stub
}
@Override
public void seekVideo(int seekTo) {
// TODO Auto-generated method stub
}
public void updateDelayCountDown() {
if (mMessageItem.isSms() && mMessageItem.getCountDown() > 0 && mMessageItem.isSending()) {
String content = mContext.getResources().getQuantityString(
R.plurals.remaining_delay_time,
mMessageItem.getCountDown(), mMessageItem.getCountDown());
Spanned spanned = Html.fromHtml(buildTimestampLine(content));
mDateView.setText(spanned);
} else {
mDateView.setText(buildTimestampLine(mMessageItem.isSending()
? mContext.getResources().getString(R.string.sending_message)
: mMessageItem.mTimestamp));
}
}
}
| false | true | private void bindCommonMessage(final boolean sameItem) {
if (mDownloadButton != null) {
mDownloadButton.setVisibility(View.GONE);
mDownloadingLabel.setVisibility(View.GONE);
}
// Since the message text should be concatenated with the sender's
// address(or name), I have to display it here instead of
// displaying it by the Presenter.
mBodyTextView.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
boolean haveLoadedPdu = mMessageItem.isSms() || mMessageItem.mSlideshow != null;
// Here we're avoiding reseting the avatar to the empty avatar when we're rebinding
// to the same item. This happens when there's a DB change which causes the message item
// cache in the MessageListAdapter to get cleared. When an mms MessageItem is newly
// created, it has no info in it except the message id. The info is eventually loaded
// and bindCommonMessage is called again (see onPduLoaded below). When we haven't loaded
// the pdu, we don't want to call updateAvatarView because it
// will set the avatar to the generic avatar then when this method is called again
// from onPduLoaded, it will reset to the real avatar. This test is to avoid that flash.
if (!sameItem || haveLoadedPdu) {
boolean isSelf = Sms.isOutgoingFolder(mMessageItem.mBoxId);
String addr = isSelf ? null : mMessageItem.mAddress;
updateAvatarView(addr, isSelf);
}
// Get and/or lazily set the formatted message from/on the
// MessageItem. Because the MessageItem instances come from a
// cache (currently of size ~50), the hit rate on avoiding the
// expensive formatMessage() call is very high.
CharSequence formattedMessage = mMessageItem.getCachedFormattedMessage();
if (formattedMessage == null) {
formattedMessage = formatMessage(mMessageItem, mMessageItem.mContact,
mMessageItem.mBody,
mMessageItem.mSubject,
mMessageItem.mHighlight,
mMessageItem.mTextContentType);
mMessageItem.setCachedFormattedMessage(formattedMessage);
}
if (!sameItem || haveLoadedPdu) {
mBodyTextView.setText(formattedMessage);
}
int textFontSize = sp.getInt(Constants.PREF_FONT_SIZE, 16);
mBodyTextView.setTextSize(textFontSize);
// Debugging code to put the URI of the image attachment in the body of the list item.
if (DEBUG) {
String debugText = null;
if (mMessageItem.mSlideshow == null) {
debugText = "NULL slideshow";
} else {
SlideModel slide = mMessageItem.mSlideshow.get(0);
if (slide == null) {
debugText = "NULL first slide";
} else if (!slide.hasImage()) {
debugText = "Not an image";
} else {
debugText = slide.getImage().getUri().toString();
}
}
mBodyTextView.setText(mPosition + ": " + debugText);
}
// If we're in the process of sending a message (i.e. pending), then we show a "SENDING..."
// string in place of the timestamp.
if (!sameItem || haveLoadedPdu) {
boolean isCountingDown = mMessageItem.getCountDown() > 0 &&
MessagingPreferenceActivity.getMessageSendDelayDuration(mContext) > 0;
int sendingTextResId = isCountingDown
? R.string.sent_countdown : R.string.sending_message;
mDateView.setText(buildTimestampLine(mMessageItem.isSending() ?
res.getString(sendingTextResId) : mMessageItem.mTimestamp));
}
// Set date and background colors
int mColor = 0;
if (mMessageItem.getBoxId() == 1) {
mColor = sp.getInt(Constants.PREF_RECV_DATE_COLOR, res.getColor(
R.color.default_recv_datecolor));
} else {
mColor = sp.getInt(Constants.PREF_SENT_DATE_COLOR, res.getColor(
R.color.default_sent_datecolor));
}
int dateFontSize = sp.getInt(Constants.PREF_DATE_FONT_SIZE, 16);
mDateView.setTextSize(dateFontSize);
mDateView.setBackgroundColor(0x00000000);
mDateView.setTextColor(mColor);
if (mMessageItem.isSms()) {
showMmsView(false);
mMessageItem.setOnPduLoaded(null);
} else {
if (DEBUG) {
Log.v(TAG, "bindCommonMessage for item: " + mPosition + " " +
mMessageItem.toString() +
" mMessageItem.mAttachmentType: " + mMessageItem.mAttachmentType +
" sameItem: " + sameItem);
}
if (mMessageItem.mAttachmentType != WorkingMessage.TEXT) {
if (!sameItem) {
setImage(null, null);
}
setOnClickListener(mMessageItem);
drawPlaybackButton(mMessageItem);
} else {
showMmsView(false);
}
if (mMessageItem.mSlideshow == null) {
mMessageItem.setOnPduLoaded(new MessageItem.PduLoadedCallback() {
public void onPduLoaded(MessageItem messageItem) {
if (DEBUG) {
Log.v(TAG, "PduLoadedCallback in MessageListItem for item: " + mPosition +
" " + (mMessageItem == null ? "NULL" : mMessageItem.toString()) +
" passed in item: " +
(messageItem == null ? "NULL" : messageItem.toString()));
}
if (messageItem != null && mMessageItem != null &&
messageItem.getMessageId() == mMessageItem.getMessageId()) {
mMessageItem.setCachedFormattedMessage(null);
bindCommonMessage(true);
}
}
});
} else {
if (mPresenter == null) {
mPresenter = PresenterFactory.getPresenter(
"MmsThumbnailPresenter", mContext,
this, mMessageItem.mSlideshow);
} else {
mPresenter.setModel(mMessageItem.mSlideshow);
mPresenter.setView(this);
}
if (mImageLoadedCallback == null) {
mImageLoadedCallback = new ImageLoadedCallback(this);
} else {
mImageLoadedCallback.reset(this);
}
mPresenter.present(mImageLoadedCallback);
}
}
drawRightStatusIndicator(mMessageItem);
requestLayout();
}
| private void bindCommonMessage(final boolean sameItem) {
if (mDownloadButton != null) {
mDownloadButton.setVisibility(View.GONE);
mDownloadingLabel.setVisibility(View.GONE);
}
// Since the message text should be concatenated with the sender's
// address(or name), I have to display it here instead of
// displaying it by the Presenter.
mBodyTextView.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
boolean haveLoadedPdu = mMessageItem.isSms() || mMessageItem.mSlideshow != null;
// Here we're avoiding reseting the avatar to the empty avatar when we're rebinding
// to the same item. This happens when there's a DB change which causes the message item
// cache in the MessageListAdapter to get cleared. When an mms MessageItem is newly
// created, it has no info in it except the message id. The info is eventually loaded
// and bindCommonMessage is called again (see onPduLoaded below). When we haven't loaded
// the pdu, we don't want to call updateAvatarView because it
// will set the avatar to the generic avatar then when this method is called again
// from onPduLoaded, it will reset to the real avatar. This test is to avoid that flash.
if (!sameItem || haveLoadedPdu) {
boolean isSelf = Sms.isOutgoingFolder(mMessageItem.mBoxId);
String addr = isSelf ? null : mMessageItem.mAddress;
updateAvatarView(addr, isSelf);
}
// Get and/or lazily set the formatted message from/on the
// MessageItem. Because the MessageItem instances come from a
// cache (currently of size ~50), the hit rate on avoiding the
// expensive formatMessage() call is very high.
CharSequence formattedMessage = mMessageItem.getCachedFormattedMessage();
if (formattedMessage == null) {
formattedMessage = formatMessage(mMessageItem, mMessageItem.mContact,
mMessageItem.mBody,
mMessageItem.mSubject,
mMessageItem.mHighlight,
mMessageItem.mTextContentType);
mMessageItem.setCachedFormattedMessage(formattedMessage);
}
if (!sameItem || haveLoadedPdu) {
mBodyTextView.setText(formattedMessage);
}
int textFontSize = sp.getInt(Constants.PREF_FONT_SIZE, 16);
mBodyTextView.setTextSize(textFontSize);
// Debugging code to put the URI of the image attachment in the body of the list item.
if (DEBUG) {
String debugText = null;
if (mMessageItem.mSlideshow == null) {
debugText = "NULL slideshow";
} else {
SlideModel slide = mMessageItem.mSlideshow.get(0);
if (slide == null) {
debugText = "NULL first slide";
} else if (!slide.hasImage()) {
debugText = "Not an image";
} else {
debugText = slide.getImage().getUri().toString();
}
}
mBodyTextView.setText(mPosition + ": " + debugText);
}
// If we're in the process of sending a message (i.e. pending), then we show a "SENDING..."
// string in place of the timestamp.
if (!sameItem || haveLoadedPdu) {
boolean isCountingDown = mMessageItem.getCountDown() > 0 &&
MessagingPreferenceActivity.getMessageSendDelayDuration(mContext) > 0;
int sendingTextResId = isCountingDown
? R.string.sent_countdown : R.string.sending_message;
mDateView.setText(buildTimestampLine(mMessageItem.isSending() ?
res.getString(sendingTextResId) : mMessageItem.mTimestamp));
}
// Set date and background colors
int mColor = 0;
if (mMessageItem.getBoxId() == 1) {
mColor = sp.getInt(Constants.PREF_RECV_DATE_COLOR, res.getColor(
R.color.default_recv_datecolor));
} else {
mColor = sp.getInt(Constants.PREF_SENT_DATE_COLOR, res.getColor(
R.color.default_sent_datecolor));
}
int dateFontSize = sp.getInt(Constants.PREF_DATE_FONT_SIZE, 16);
mDateView.setTextSize(dateFontSize);
mDateView.setBackgroundColor(0x00000000);
mDateView.setTextColor(mColor);
if (mMessageItem.isSms()) {
showMmsView(false);
mMessageItem.setOnPduLoaded(null);
} else {
if (DEBUG) {
Log.v(TAG, "bindCommonMessage for item: " + mPosition + " " +
mMessageItem.toString() +
" mMessageItem.mAttachmentType: " + mMessageItem.mAttachmentType +
" sameItem: " + sameItem);
}
if (mMessageItem.mAttachmentType != WorkingMessage.TEXT) {
if (!sameItem) {
setImage(null, null);
}
setOnClickListener(mMessageItem);
drawPlaybackButton(mMessageItem);
} else {
showMmsView(false);
}
if (mMessageItem.mSlideshow == null) {
final int mCurrentAttachmentType = mMessageItem.mAttachmentType;
mMessageItem.setOnPduLoaded(new MessageItem.PduLoadedCallback() {
public void onPduLoaded(MessageItem messageItem) {
if (DEBUG) {
Log.v(TAG, "PduLoadedCallback in MessageListItem for item: " + mPosition +
" " + (mMessageItem == null ? "NULL" : mMessageItem.toString()) +
" passed in item: " +
(messageItem == null ? "NULL" : messageItem.toString()));
}
if (messageItem != null && mMessageItem != null &&
messageItem.getMessageId() == mMessageItem.getMessageId()) {
mMessageItem.setCachedFormattedMessage(null);
boolean isStillSame =
mCurrentAttachmentType == messageItem.mAttachmentType;
bindCommonMessage(isStillSame);
}
}
});
} else {
if (mPresenter == null) {
mPresenter = PresenterFactory.getPresenter(
"MmsThumbnailPresenter", mContext,
this, mMessageItem.mSlideshow);
} else {
mPresenter.setModel(mMessageItem.mSlideshow);
mPresenter.setView(this);
}
if (mImageLoadedCallback == null) {
mImageLoadedCallback = new ImageLoadedCallback(this);
} else {
mImageLoadedCallback.reset(this);
}
mPresenter.present(mImageLoadedCallback);
}
}
drawRightStatusIndicator(mMessageItem);
requestLayout();
}
|
diff --git a/Donor-Connect-App/src/test/java/controller/ProjectControllerTest.java b/Donor-Connect-App/src/test/java/controller/ProjectControllerTest.java
index 7707ff7..a734e47 100644
--- a/Donor-Connect-App/src/test/java/controller/ProjectControllerTest.java
+++ b/Donor-Connect-App/src/test/java/controller/ProjectControllerTest.java
@@ -1,65 +1,65 @@
package controller;
import models.Project;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
public class ProjectControllerTest {
private MockHttpServletResponse response;
private MockHttpServletRequest request;
private AnnotationMethodHandlerAdapter adapter;
private ProjectController controller;
private Project dummyProject;
private models.ProjectDAO ProjectDAO;
@Before
public void setUp() {
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
adapter = new AnnotationMethodHandlerAdapter();
dummyProject = new Project("name", "description", "image/path");
- request.setRequestURI("/project_detail");
+ request.setRequestURI("/project_detail.ftl");
request.setMethod("GET");
request.setParameter("project_id", "1");
controller = new ProjectController();
ProjectDAO = mock(models.ProjectDAO.class);
controller.setDao(ProjectDAO);
when(ProjectDAO.fetch((long) 1)).thenReturn(dummyProject);
}
@Test
public void shouldRenderTheProjectDetailsView() throws Exception {
ModelAndView modelView = adapter.handle(request, response, controller);
assertThat(modelView.getViewName(), is("project_detail"));
}
@Test
public void shouldFetchAProjectBasedOnTheIDProvided() throws Exception {
adapter.handle(request, response, controller);
verify(ProjectDAO, Mockito.times(1)).fetch((long) 1);
}
@Test
public void shouldExposeTheProjectFetchedToTheProjectDetailsView() throws Exception {
ModelAndView modelView = adapter.handle(request, response, controller);
ModelMap modelMap = (ModelMap) modelView.getModel().get("model");
assertThat((Project)modelMap.get("project"), is(dummyProject));
}
}
| true | true | public void setUp() {
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
adapter = new AnnotationMethodHandlerAdapter();
dummyProject = new Project("name", "description", "image/path");
request.setRequestURI("/project_detail");
request.setMethod("GET");
request.setParameter("project_id", "1");
controller = new ProjectController();
ProjectDAO = mock(models.ProjectDAO.class);
controller.setDao(ProjectDAO);
when(ProjectDAO.fetch((long) 1)).thenReturn(dummyProject);
}
| public void setUp() {
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
adapter = new AnnotationMethodHandlerAdapter();
dummyProject = new Project("name", "description", "image/path");
request.setRequestURI("/project_detail.ftl");
request.setMethod("GET");
request.setParameter("project_id", "1");
controller = new ProjectController();
ProjectDAO = mock(models.ProjectDAO.class);
controller.setDao(ProjectDAO);
when(ProjectDAO.fetch((long) 1)).thenReturn(dummyProject);
}
|
diff --git a/src/com/isaacjg/darklight/issues/PathIssue.java b/src/com/isaacjg/darklight/issues/PathIssue.java
index 5279e58..88333a1 100644
--- a/src/com/isaacjg/darklight/issues/PathIssue.java
+++ b/src/com/isaacjg/darklight/issues/PathIssue.java
@@ -1,69 +1,69 @@
package com.isaacjg.darklight.issues;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import com.ijg.darklight.sdk.core.Issue;
/*
* PathIssue - An Issue for Darklight Nova Core
* Copyright � 2013 Isaac Grant
*
* 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/>.
*/
/**
* PathIssue is an Issue for Darklight Nova Core that checks if
* given "bad paths" are present in the system path variable
*
* @author Isaac Grant
*/
public class PathIssue extends Issue {
private String[] badPaths;
public PathIssue() {
super("Path", "The path has been cleansed of its impurities");
}
public void setBadPaths(String[] badPaths) {
this.badPaths = badPaths;
}
@Override
public boolean isFixed() {
try {
- Process p = Runtime.getRuntime().exec("cmd.exe \\c echo %PATH%");
+ Process p = Runtime.getRuntime().exec("cmd.exe /c echo %PATH%");
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String path = "";
String line = "";
while ((line = br.readLine()) != null) {
path += line;
}
br.close();
for (String badPath : badPaths) {
if (path.contains(badPath)) {
return false;
}
}
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
}
| true | true | public boolean isFixed() {
try {
Process p = Runtime.getRuntime().exec("cmd.exe \\c echo %PATH%");
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String path = "";
String line = "";
while ((line = br.readLine()) != null) {
path += line;
}
br.close();
for (String badPath : badPaths) {
if (path.contains(badPath)) {
return false;
}
}
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
| public boolean isFixed() {
try {
Process p = Runtime.getRuntime().exec("cmd.exe /c echo %PATH%");
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String path = "";
String line = "";
while ((line = br.readLine()) != null) {
path += line;
}
br.close();
for (String badPath : badPaths) {
if (path.contains(badPath)) {
return false;
}
}
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
|
diff --git a/src/main/java/ch/uzh/ddis/katts/bolts/aggregate/PartitionerBolt.java b/src/main/java/ch/uzh/ddis/katts/bolts/aggregate/PartitionerBolt.java
index 23761aa..1db23c4 100644
--- a/src/main/java/ch/uzh/ddis/katts/bolts/aggregate/PartitionerBolt.java
+++ b/src/main/java/ch/uzh/ddis/katts/bolts/aggregate/PartitionerBolt.java
@@ -1,396 +1,396 @@
package ch.uzh.ddis.katts.bolts.aggregate;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import backtype.storm.task.OutputCollector;
import backtype.storm.task.TopologyContext;
import ch.uzh.ddis.katts.bolts.AbstractStreamInternSynchronizedBolt;
import ch.uzh.ddis.katts.bolts.AbstractSynchronizedBolt;
import ch.uzh.ddis.katts.bolts.Event;
import ch.uzh.ddis.katts.bolts.VariableBindings;
import ch.uzh.ddis.katts.persistence.Storage;
import ch.uzh.ddis.katts.persistence.StorageFactory;
import ch.uzh.ddis.katts.query.stream.Stream;
import ch.uzh.ddis.katts.query.stream.Variable;
/**
* A partition bolt builds aggregates on variables (fields) by building windows that slides over the time.
*
* For each slide (step) an aggregate is created. Additionally the aggregate can be grouped (partitioned) by a variable.
* This is similar to the group by in SQL like languages.
*
* The slides can be smaller, equal or greater than the windows.
*
* @author Thomas Hunziker
*
*/
public class PartitionerBolt extends AbstractSynchronizedBolt {
private Logger logger = LoggerFactory.getLogger(PartitionerBolt.class);
/**
* Map which contains for each partitioned by value a bucket list. Each bucket contains a Map of storages objects
* for each component.
*/
private Storage<Object, List<Map<String, Object>>> bucketsStorage;
/**
* The last used bucket index is used to determine, if a bucket is finished and therefore the elements need to be
* emitted and the new bucket has to be reset.
*/
private Storage<Object, Long> lastUsedBucketIndexStorage;
/**
* When we emit the bucket value as the aggregation value, we join the event to this bucket. But we emit the bucket,
* when we receive an event for the next bucket. So when we emit the bucket, we do not have an event of the bucket
* to join. This implies that we join the buckets with a total wrong event. Additionally, we emit the wrong start
* date, when we have hole in the time.
*/
private Storage<Object, Event> lastBucketEventStorage;
private List<PartitionerComponent> components = new ArrayList<PartitionerComponent>();
private long slideSizeInMilliSeconds;
private long windowSizeInMilliSeconds;
/** Number of buckets per window */
private int bucketsPerWindow;
private static final long serialVersionUID = 1L;
private PartitionerConfiguration configuration;
/**
* The field on which we build the partition. The partition is similar to the group by in SQL like languages.
*/
private Variable partitionOnField;
/**
* The field on which the aggregation is done. This is similar to the field in the aggregation function in SQL like
* languages.
*/
private Variable aggregateOnField;
private int counter = 0;
@Override
public void prepare(Map stormConf, TopologyContext context, OutputCollector collector) {
super.prepare(stormConf, context, collector);
try {
/*
* TODO: Lorenz - this.getConfiguration().getId() wird wohl nicht über alle machinen unique sein. das
* heisst, dass dies nur funktioniert, solange wir kein storage sharing über machinengrenzen hinaushaben.
* kann das sein? warum hast du hier nicht get() verwendet?
*
* Thomas: this.getConfiguration().getId() muss nicht unique sein, da wir ja genau wollen, dass wenn der
* Bolt an andere Stelle hoch fährt, dann wieder den gleichen Speicher hat. Das was wir hier zurück bekommen
* ist eine Art HashMap. D.h. das partitionFieldValue muss unique sein. Das ist zutreffend da ja
* partitionFieldValue = Wert des Ticker Symbols (also z.B. CSGN) ist.
*/
bucketsStorage = StorageFactory.createDefaultStorage(this.getConfiguration().getId() + "_buckets");
lastUsedBucketIndexStorage = StorageFactory.createDefaultStorage(this.getId() + "_last_buckets");
lastBucketEventStorage = StorageFactory.createDefaultStorage(this.getId() + "_last_events");
} catch (InstantiationException e) {
logger.error("Could not load storage object.", e);
System.exit(0);
} catch (IllegalAccessException e) {
logger.error("Could not load storage object.", e);
System.exit(0);
}
components = this.getConfiguration().getComponents();
slideSizeInMilliSeconds = this.getConfiguration().getSlideSize().getTimeInMillis(new Date(0));
windowSizeInMilliSeconds = this.getConfiguration().getWindowSize().getTimeInMillis(new Date(0));
/*
* TODO: Lorenz - Bei einer Division von longs werden alle Nachkommastellen abgeschnitten. Du musst mindestens
* eine der beiden Zahlen in einen double konvertieren bevor Du die Division durchführst. Bei der Division wird
* der "kleinere" Typ in den "grösseren" umgewandelt. Siehe auch
* http://mathbits.com/MathBits/Java/DataBasics/Mathoperators.htm
*
* Da hast du natürlich Recht. Allerdings ist eigentlich dies so oder so überflüssig, da eine Voraussetzung ist,
* dass windowSizeInMilliSeconds % slideSizeInMilliSeconds == 0 ist. Daher eigentlich alles überflüssig...
*/
bucketsPerWindow = (int) Math.ceil((double) windowSizeInMilliSeconds / slideSizeInMilliSeconds);
partitionOnField = this.getConfiguration().getPartitionOn();
aggregateOnField = getConfiguration().getAggregateOn();
}
@Override
public String getId() {
return this.getConfiguration().getId();
}
@Override
public void execute(Event event) {
String partitionFieldValue = event.getVariableValue(partitionOnField).toString().intern();
synchronized (partitionFieldValue) {
// Fix Bucket (initialize or reset)
List<Map<String, Object>> buckets = this.getBuckets(event, partitionFieldValue);
// Update Bucket (for each component update the bucket value)
this.updateBuckets(event, buckets, partitionFieldValue);
// Update the last used global index
this.lastUsedBucketIndexStorage.put(partitionFieldValue, this.getBucketGlobalIndex(event));
}
event.ack();
}
/**
* This method checks if the given event with the given partitionFieldValue is inside the same bucket as the last
* event for the same partition.
*
* @param event
* @param partitionFieldValue
* @return
*/
private boolean hasBucketNumberIncreased(Event event, Object partitionFieldValue) {
Long bucketGlobalIndex = this.getBucketGlobalIndex(event);
Long lastIndex = this.lastUsedBucketIndexStorage.get(partitionFieldValue);
if (lastIndex == null || lastIndex.compareTo(bucketGlobalIndex) < 0) {
return true;
} else {
return false;
}
}
/**
* This method returns the buckets for the current partition value. If the buckets are not initialized or they need
* to be reset, this method resets it.
*
* @param event
* @param partitionFieldValue
* @return
*/
protected synchronized List<Map<String, Object>> getBuckets(Event event, Object partitionFieldValue) {
List<Map<String, Object>> buckets = this.bucketsStorage.get(partitionFieldValue);
boolean hasWindowChanged = false;
if (buckets == null) {
buckets = new ArrayList<Map<String, Object>>();
for (int i = 0; i < bucketsPerWindow; i++) {
buckets.add(new HashMap<String, Object>());
}
hasWindowChanged = true;
this.bucketsStorage.put(partitionFieldValue, buckets);
}
if (this.hasBucketNumberIncreased(event, partitionFieldValue)) {
// If we jump more than one slide, we need to reset the intermidate slides, because they may have incorrect
// storage values in it.
Long lastIndex = this.lastUsedBucketIndexStorage.get(partitionFieldValue);
if (lastIndex != null) {
long bucketGlobalIndex = this.getBucketGlobalIndex(event);
long firstIntermediateGlobalSlideId = lastIndex + 1;
for (long slideIndex = firstIntermediateGlobalSlideId; slideIndex < bucketGlobalIndex; slideIndex++) {
Map<String, Object> storages = new HashMap<String, Object>();
for (PartitionerComponent component : this.getComponents()) {
Object storage = component.resetBucket();
storages.put(component.getName(), storage);
}
buckets.set(this.getBucketWindowIndex(slideIndex), storages);
}
}
// Check if the bucket has to be reset, because the window
// has been changed. If so, then emit the aggregates:
if (hasWindowChanged == false) {
this.emitAggregates(event, partitionFieldValue, buckets);
}
// Since we have emit the event, we can update the last bucket event:
this.lastBucketEventStorage.put(partitionFieldValue, event);
Map<String, Object> storages = new HashMap<String, Object>();
for (PartitionerComponent component : this.getComponents()) {
Object storage = component.resetBucket();
storages.put(component.getName(), storage);
}
buckets.set(this.getBucketWindowIndex(event), storages);
}
return buckets;
}
/**
* This method updates the component storages for depending on the given event.
*
* @param number
* @param buckets
* @param bucketIndex
*/
protected void updateBuckets(Event event, List<Map<String, Object>> buckets, Object partitionFieldValue) {
int bucketWindowIndex = this.getBucketWindowIndex(event);
// Check if the event is inside the given window. In case the window
// size is smaller as the slide size, we need to check, if the event
// is in the current window.
if (this.isEventInsideWindow(event)) {
double aggregateValue = (Double) event.getVariableValue(aggregateOnField);
Map<String, Object> storages = buckets.get(bucketWindowIndex);
for (PartitionerComponent component : this.getComponents()) {
Object storage = storages.get(component.getName());
storages.put(component.getName(), component.updateBucket(storage, aggregateValue));
}
buckets.set(bucketWindowIndex, storages);
}
}
/**
* This method checks if the given event is inside the window. The case that it is outside the window can only
* happen, when the window size is smaller as the slide size.
*
* @param event
* @return
*/
protected boolean isEventInsideWindow(Event event) {
if (slideSizeInMilliSeconds < windowSizeInMilliSeconds) {
return true;
} else {
long eventTime = event.getStartDate().getTime();
long residual = eventTime % slideSizeInMilliSeconds;
if (residual > windowSizeInMilliSeconds) {
return false;
} else {
return true;
}
}
}
/**
* This method emits the aggregates build on the buckets.
*
* @param event
* @param buckets
*/
protected void emitAggregates(Event event, Object partitionFieldValue, List<Map<String, Object>> buckets) {
// When no data is aggregate, then do not emit anything
if (buckets == null) {
return;
}
long bucketNumber = this.getBucketGlobalIndex(event);
// Try to get the last event:
Event eventToJoinWith = this.lastBucketEventStorage.get(partitionFieldValue);
if (eventToJoinWith == null) {
eventToJoinWith = event;
}
for (Stream stream : this.getStreams()) {
VariableBindings bindings = getEmitter().createVariableBindings(stream, eventToJoinWith);
// Copy Variables from the stream we inherit our variables from
if (stream.getInheritFrom() != null) {
for (Variable variable : stream.getInheritFrom().getAllVariables()) {
bindings.add(variable, eventToJoinWith.getVariableValue(variable));
}
}
boolean aggreationMissed = false;
for (PartitionerComponent component : this.getComponents()) {
// Build component specific bucket list:
List<Object> componentBuckets = new ArrayList<Object>();
for (Map<String, Object> storage : buckets) {
componentBuckets.add(storage.get(component.getName()));
}
Double aggregate = component.calculateAggregate(componentBuckets);
if (aggregate == null) {
- logger.info("An aggreate could not be built, because all buckets seems to be empty.");
+ logger.info("An aggreate could not be built, because all buckets seem to be empty resp. null.");
aggreationMissed = true;
break;
}
bindings.add(component.getName(), aggregate);
}
if (!aggreationMissed) {
long startTime = (bucketNumber - bucketsPerWindow + 1) * slideSizeInMilliSeconds;
// long endTime = bucketNumber * slideSizeInMilliSeconds;
long endTime = eventToJoinWith.getEndDate().getTime();
bindings.setStartDate(new Date(startTime));
bindings.setEndDate(new Date(endTime));
bindings.emit();
}
}
}
/**
* This method returns the index for the bucket inside the window. The window consists of a list of buckets. This
* index identifies exactly one such bucket depending on the events start date.
*
* @param event
* @return
*/
protected int getBucketWindowIndex(Event event) {
return getBucketWindowIndex(getBucketGlobalIndex(event));
}
/**
* This method returns the index for the bucket inside the window. The window consists of a list of buckets. This
* index identifies exactly one such bucket depending on the given global index.
*
* @param globalIndex
* @return
*/
protected int getBucketWindowIndex(Long globalIndex) {
return (int) (globalIndex % bucketsPerWindow);
}
/**
* This method returns the global (over the whole time) an index for the given event. The index identifies a certain
* bucket exactly in the whole time span.
*
* @param event
* @return
*/
protected Long getBucketGlobalIndex(Event event) {
long eventTime = event.getStartDate().getTime();
return Long.valueOf((long) (Math.floor(eventTime / (double) slideSizeInMilliSeconds)));
}
public PartitionerConfiguration getConfiguration() {
return configuration;
}
public void setConfiguration(PartitionerConfiguration configuration) {
this.configuration = configuration;
}
public List<PartitionerComponent> getComponents() {
return components;
}
@Override
public String getSynchronizationDateExpression() {
// TODO Make this configurable (May be it is not a good idea to change this, hence it make no sense to add an
// option to configure it.)
return "#event.endDate";
}
}
| true | true | protected void emitAggregates(Event event, Object partitionFieldValue, List<Map<String, Object>> buckets) {
// When no data is aggregate, then do not emit anything
if (buckets == null) {
return;
}
long bucketNumber = this.getBucketGlobalIndex(event);
// Try to get the last event:
Event eventToJoinWith = this.lastBucketEventStorage.get(partitionFieldValue);
if (eventToJoinWith == null) {
eventToJoinWith = event;
}
for (Stream stream : this.getStreams()) {
VariableBindings bindings = getEmitter().createVariableBindings(stream, eventToJoinWith);
// Copy Variables from the stream we inherit our variables from
if (stream.getInheritFrom() != null) {
for (Variable variable : stream.getInheritFrom().getAllVariables()) {
bindings.add(variable, eventToJoinWith.getVariableValue(variable));
}
}
boolean aggreationMissed = false;
for (PartitionerComponent component : this.getComponents()) {
// Build component specific bucket list:
List<Object> componentBuckets = new ArrayList<Object>();
for (Map<String, Object> storage : buckets) {
componentBuckets.add(storage.get(component.getName()));
}
Double aggregate = component.calculateAggregate(componentBuckets);
if (aggregate == null) {
logger.info("An aggreate could not be built, because all buckets seems to be empty.");
aggreationMissed = true;
break;
}
bindings.add(component.getName(), aggregate);
}
if (!aggreationMissed) {
long startTime = (bucketNumber - bucketsPerWindow + 1) * slideSizeInMilliSeconds;
// long endTime = bucketNumber * slideSizeInMilliSeconds;
long endTime = eventToJoinWith.getEndDate().getTime();
bindings.setStartDate(new Date(startTime));
bindings.setEndDate(new Date(endTime));
bindings.emit();
}
}
}
| protected void emitAggregates(Event event, Object partitionFieldValue, List<Map<String, Object>> buckets) {
// When no data is aggregate, then do not emit anything
if (buckets == null) {
return;
}
long bucketNumber = this.getBucketGlobalIndex(event);
// Try to get the last event:
Event eventToJoinWith = this.lastBucketEventStorage.get(partitionFieldValue);
if (eventToJoinWith == null) {
eventToJoinWith = event;
}
for (Stream stream : this.getStreams()) {
VariableBindings bindings = getEmitter().createVariableBindings(stream, eventToJoinWith);
// Copy Variables from the stream we inherit our variables from
if (stream.getInheritFrom() != null) {
for (Variable variable : stream.getInheritFrom().getAllVariables()) {
bindings.add(variable, eventToJoinWith.getVariableValue(variable));
}
}
boolean aggreationMissed = false;
for (PartitionerComponent component : this.getComponents()) {
// Build component specific bucket list:
List<Object> componentBuckets = new ArrayList<Object>();
for (Map<String, Object> storage : buckets) {
componentBuckets.add(storage.get(component.getName()));
}
Double aggregate = component.calculateAggregate(componentBuckets);
if (aggregate == null) {
logger.info("An aggreate could not be built, because all buckets seem to be empty resp. null.");
aggreationMissed = true;
break;
}
bindings.add(component.getName(), aggregate);
}
if (!aggreationMissed) {
long startTime = (bucketNumber - bucketsPerWindow + 1) * slideSizeInMilliSeconds;
// long endTime = bucketNumber * slideSizeInMilliSeconds;
long endTime = eventToJoinWith.getEndDate().getTime();
bindings.setStartDate(new Date(startTime));
bindings.setEndDate(new Date(endTime));
bindings.emit();
}
}
}
|
diff --git a/src/edu/jas/ring/PseudoReductionSeq.java b/src/edu/jas/ring/PseudoReductionSeq.java
index 12c51a32..c2314cb1 100644
--- a/src/edu/jas/ring/PseudoReductionSeq.java
+++ b/src/edu/jas/ring/PseudoReductionSeq.java
@@ -1,243 +1,247 @@
/*
* $Id$
*/
package edu.jas.ring;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import org.apache.log4j.Logger;
import edu.jas.poly.ExpVector;
import edu.jas.poly.GenPolynomial;
import edu.jas.structure.RingElem;
/**
* Polynomial pseudo reduction sequential use algorithm.
* Coefficients of polynomials must not be from a field,
* i.e. the fraction free reduction is implemented.
* Implements normalform.
* @author Heinz Kredel
*/
public class PseudoReductionSeq<C extends RingElem<C>>
extends ReductionAbstract<C> {
private static final Logger logger = Logger.getLogger(PseudoReductionSeq.class);
/**
* Constructor.
*/
public PseudoReductionSeq() {
}
/**
* Normalform.
* @typeparam C coefficient type.
* @param Ap polynomial.
* @param Pp polynomial list.
* @return nf(Ap) with respect to Pp.
*/
@SuppressWarnings("unchecked")
public GenPolynomial<C> normalform(List<GenPolynomial<C>> Pp,
GenPolynomial<C> Ap) {
if ( Pp == null || Pp.isEmpty() ) {
return Ap;
}
if ( Ap == null || Ap.isZERO() ) {
return Ap;
}
Map.Entry<ExpVector,C> m;
int l;
GenPolynomial<C>[] P;
synchronized (Pp) {
l = Pp.size();
P = new GenPolynomial[l];
//P = Pp.toArray();
for ( int i = 0; i < Pp.size(); i++ ) {
P[i] = Pp.get(i);
}
}
ExpVector[] htl = new ExpVector[ l ];
Object[] lbc = new Object[ l ]; // want C[]
GenPolynomial<C>[] p = new GenPolynomial[ l ];
int i;
int j = 0;
for ( i = 0; i < l; i++ ) {
p[i] = P[i];
m = p[i].leadingMonomial();
if ( m != null ) {
p[j] = p[i];
htl[j] = m.getKey();
lbc[j] = m.getValue();
j++;
}
}
l = j;
ExpVector e;
C a;
boolean mt = false;
GenPolynomial<C> R = Ap.ring.getZERO();
//GenPolynomial<C> T = null;
GenPolynomial<C> Q = null;
GenPolynomial<C> S = Ap;
while ( S.length() > 0 ) {
m = S.leadingMonomial();
e = m.getKey();
a = m.getValue();
for ( i = 0; i < l; i++ ) {
mt = ExpVector.EVMT( e, htl[i] );
if ( mt ) break;
}
if ( ! mt ) {
//logger.debug("irred");
//T = new OrderedMapPolynomial( a, e );
R = R.sum( a, e );
S = S.subtract( a, e );
// System.out.println(" S = " + S);
} else {
e = ExpVector.EVDIF( e, htl[i] );
//logger.info("red div = " + e);
C c = (C) lbc[i];
if ( a.remainder(c).isZERO() ) { //c.isUnit() ) {
a = a.divide( c );
} else {
S = S.multiply( c );
R = R.multiply( c );
}
Q = p[i].multiply( a, e );
S = S.subtract( Q );
}
}
return R;
}
/**
* Normalform with recording.
* <b>Note:</b> do not use, multiplication factor is lost.
* Will be removed or replaced in future.
* @typeparam C coefficient type.
* @param row recording matrix, is modified.
* @param Pp a polynomial list for reduction.
* @param Ap a polynomial.
* @return nf(Pp,Ap), the normal form of Ap wrt. Pp.
* @deprecated multiplication factor will be lost.
*/
public GenPolynomial<C>
normalform(List<GenPolynomial<C>> row,
List<GenPolynomial<C>> Pp,
GenPolynomial<C> Ap) {
List<C> mf = new ArrayList<C>(1);
+ mf.add(null);
logger.error("multiplication factor is lost");
return normalform(mf,row,Pp,Ap);
}
/**
* Normalform with recording.
* @typeparam C coefficient type.
* @param row recording matrix, is modified.
* @param mf multiplication factor for Ap, is modified.
* @param Pp a polynomial list for reduction.
* @param Ap a polynomial.
* @return nf(Pp,mf*Ap), the normal form of mf*Ap wrt. Pp.
*/
@SuppressWarnings("unchecked")
public GenPolynomial<C>
normalform(List<C> mf,
List<GenPolynomial<C>> row,
List<GenPolynomial<C>> Pp,
GenPolynomial<C> Ap) {
if ( Pp == null || Pp.isEmpty() ) {
return Ap;
}
if ( Ap == null || Ap.isZERO() ) {
return Ap;
}
int l = Pp.size();
GenPolynomial<C>[] P = new GenPolynomial[l];
synchronized (Pp) {
//P = Pp.toArray();
for ( int i = 0; i < Pp.size(); i++ ) {
P[i] = Pp.get(i);
}
}
ExpVector[] htl = new ExpVector[ l ];
Object[] lbc = new Object[ l ]; // want C
GenPolynomial<C>[] p = new GenPolynomial[ l ];
Map.Entry<ExpVector,C> m;
int j = 0;
int i;
for ( i = 0; i < l; i++ ) {
p[i] = P[i];
m = p[i].leadingMonomial();
if ( m != null ) {
p[j] = p[i];
htl[j] = m.getKey();
lbc[j] = m.getValue();
j++;
}
}
l = j;
ExpVector e;
C a;
boolean mt = false;
GenPolynomial<C> zero = Ap.ring.getZERO();
GenPolynomial<C> R = Ap.ring.getZERO();
C mfac = mf.get(0);
if ( mfac == null ) {
mfac = Ap.ring.getONECoefficient();
}
GenPolynomial<C> fac = null;
// GenPolynomial<C> T = null;
GenPolynomial<C> Q = null;
GenPolynomial<C> S = Ap;
while ( S.length() > 0 ) {
m = S.leadingMonomial();
e = m.getKey();
a = m.getValue();
for ( i = 0; i < l; i++ ) {
mt = ExpVector.EVMT( e, htl[i] );
if ( mt ) break;
}
if ( ! mt ) {
//logger.debug("irred");
R = R.sum( a, e );
S = S.subtract( a, e );
// System.out.println(" S = " + S);
//throw new RuntimeException("Syzygy no GB");
} else {
e = ExpVector.EVDIF( e, htl[i] );
//logger.info("red div = " + e);
C c = (C) lbc[i];
if ( a.remainder(c).isZERO() ) { //c.isUnit() ) {
a = a.divide( c );
+ //System.out.print("|");
} else {
- mfac = mfac.multiply( c );
+ //System.out.print("*");
S = S.multiply( c );
R = R.multiply( c );
+ mfac = mfac.multiply( c );
}
Q = p[i].multiply( a, e );
S = S.subtract( Q );
fac = row.get(i);
if ( fac == null ) {
fac = zero.sum( a, e );
} else {
fac = fac.sum( a, e );
}
row.set(i,fac);
}
}
+ //System.out.println(".");
mf.set(0,mfac);
return R;
}
}
| false | true | public GenPolynomial<C> normalform(List<GenPolynomial<C>> Pp,
GenPolynomial<C> Ap) {
if ( Pp == null || Pp.isEmpty() ) {
return Ap;
}
if ( Ap == null || Ap.isZERO() ) {
return Ap;
}
Map.Entry<ExpVector,C> m;
int l;
GenPolynomial<C>[] P;
synchronized (Pp) {
l = Pp.size();
P = new GenPolynomial[l];
//P = Pp.toArray();
for ( int i = 0; i < Pp.size(); i++ ) {
P[i] = Pp.get(i);
}
}
ExpVector[] htl = new ExpVector[ l ];
Object[] lbc = new Object[ l ]; // want C[]
GenPolynomial<C>[] p = new GenPolynomial[ l ];
int i;
int j = 0;
for ( i = 0; i < l; i++ ) {
p[i] = P[i];
m = p[i].leadingMonomial();
if ( m != null ) {
p[j] = p[i];
htl[j] = m.getKey();
lbc[j] = m.getValue();
j++;
}
}
l = j;
ExpVector e;
C a;
boolean mt = false;
GenPolynomial<C> R = Ap.ring.getZERO();
//GenPolynomial<C> T = null;
GenPolynomial<C> Q = null;
GenPolynomial<C> S = Ap;
while ( S.length() > 0 ) {
m = S.leadingMonomial();
e = m.getKey();
a = m.getValue();
for ( i = 0; i < l; i++ ) {
mt = ExpVector.EVMT( e, htl[i] );
if ( mt ) break;
}
if ( ! mt ) {
//logger.debug("irred");
//T = new OrderedMapPolynomial( a, e );
R = R.sum( a, e );
S = S.subtract( a, e );
// System.out.println(" S = " + S);
} else {
e = ExpVector.EVDIF( e, htl[i] );
//logger.info("red div = " + e);
C c = (C) lbc[i];
if ( a.remainder(c).isZERO() ) { //c.isUnit() ) {
a = a.divide( c );
} else {
S = S.multiply( c );
R = R.multiply( c );
}
Q = p[i].multiply( a, e );
S = S.subtract( Q );
}
}
return R;
}
/**
* Normalform with recording.
* <b>Note:</b> do not use, multiplication factor is lost.
* Will be removed or replaced in future.
* @typeparam C coefficient type.
* @param row recording matrix, is modified.
* @param Pp a polynomial list for reduction.
* @param Ap a polynomial.
* @return nf(Pp,Ap), the normal form of Ap wrt. Pp.
* @deprecated multiplication factor will be lost.
*/
public GenPolynomial<C>
normalform(List<GenPolynomial<C>> row,
List<GenPolynomial<C>> Pp,
GenPolynomial<C> Ap) {
List<C> mf = new ArrayList<C>(1);
logger.error("multiplication factor is lost");
return normalform(mf,row,Pp,Ap);
}
/**
* Normalform with recording.
* @typeparam C coefficient type.
* @param row recording matrix, is modified.
* @param mf multiplication factor for Ap, is modified.
* @param Pp a polynomial list for reduction.
* @param Ap a polynomial.
* @return nf(Pp,mf*Ap), the normal form of mf*Ap wrt. Pp.
*/
@SuppressWarnings("unchecked")
public GenPolynomial<C>
normalform(List<C> mf,
List<GenPolynomial<C>> row,
List<GenPolynomial<C>> Pp,
GenPolynomial<C> Ap) {
if ( Pp == null || Pp.isEmpty() ) {
return Ap;
}
if ( Ap == null || Ap.isZERO() ) {
return Ap;
}
int l = Pp.size();
GenPolynomial<C>[] P = new GenPolynomial[l];
synchronized (Pp) {
//P = Pp.toArray();
for ( int i = 0; i < Pp.size(); i++ ) {
P[i] = Pp.get(i);
}
}
ExpVector[] htl = new ExpVector[ l ];
Object[] lbc = new Object[ l ]; // want C
GenPolynomial<C>[] p = new GenPolynomial[ l ];
Map.Entry<ExpVector,C> m;
int j = 0;
int i;
for ( i = 0; i < l; i++ ) {
p[i] = P[i];
m = p[i].leadingMonomial();
if ( m != null ) {
p[j] = p[i];
htl[j] = m.getKey();
lbc[j] = m.getValue();
j++;
}
}
l = j;
ExpVector e;
C a;
boolean mt = false;
GenPolynomial<C> zero = Ap.ring.getZERO();
GenPolynomial<C> R = Ap.ring.getZERO();
C mfac = mf.get(0);
if ( mfac == null ) {
mfac = Ap.ring.getONECoefficient();
}
GenPolynomial<C> fac = null;
// GenPolynomial<C> T = null;
GenPolynomial<C> Q = null;
GenPolynomial<C> S = Ap;
while ( S.length() > 0 ) {
m = S.leadingMonomial();
e = m.getKey();
a = m.getValue();
for ( i = 0; i < l; i++ ) {
mt = ExpVector.EVMT( e, htl[i] );
if ( mt ) break;
}
if ( ! mt ) {
//logger.debug("irred");
R = R.sum( a, e );
S = S.subtract( a, e );
// System.out.println(" S = " + S);
//throw new RuntimeException("Syzygy no GB");
} else {
e = ExpVector.EVDIF( e, htl[i] );
//logger.info("red div = " + e);
C c = (C) lbc[i];
if ( a.remainder(c).isZERO() ) { //c.isUnit() ) {
a = a.divide( c );
} else {
mfac = mfac.multiply( c );
S = S.multiply( c );
R = R.multiply( c );
}
Q = p[i].multiply( a, e );
S = S.subtract( Q );
fac = row.get(i);
if ( fac == null ) {
fac = zero.sum( a, e );
} else {
fac = fac.sum( a, e );
}
row.set(i,fac);
}
}
mf.set(0,mfac);
return R;
}
}
| public GenPolynomial<C> normalform(List<GenPolynomial<C>> Pp,
GenPolynomial<C> Ap) {
if ( Pp == null || Pp.isEmpty() ) {
return Ap;
}
if ( Ap == null || Ap.isZERO() ) {
return Ap;
}
Map.Entry<ExpVector,C> m;
int l;
GenPolynomial<C>[] P;
synchronized (Pp) {
l = Pp.size();
P = new GenPolynomial[l];
//P = Pp.toArray();
for ( int i = 0; i < Pp.size(); i++ ) {
P[i] = Pp.get(i);
}
}
ExpVector[] htl = new ExpVector[ l ];
Object[] lbc = new Object[ l ]; // want C[]
GenPolynomial<C>[] p = new GenPolynomial[ l ];
int i;
int j = 0;
for ( i = 0; i < l; i++ ) {
p[i] = P[i];
m = p[i].leadingMonomial();
if ( m != null ) {
p[j] = p[i];
htl[j] = m.getKey();
lbc[j] = m.getValue();
j++;
}
}
l = j;
ExpVector e;
C a;
boolean mt = false;
GenPolynomial<C> R = Ap.ring.getZERO();
//GenPolynomial<C> T = null;
GenPolynomial<C> Q = null;
GenPolynomial<C> S = Ap;
while ( S.length() > 0 ) {
m = S.leadingMonomial();
e = m.getKey();
a = m.getValue();
for ( i = 0; i < l; i++ ) {
mt = ExpVector.EVMT( e, htl[i] );
if ( mt ) break;
}
if ( ! mt ) {
//logger.debug("irred");
//T = new OrderedMapPolynomial( a, e );
R = R.sum( a, e );
S = S.subtract( a, e );
// System.out.println(" S = " + S);
} else {
e = ExpVector.EVDIF( e, htl[i] );
//logger.info("red div = " + e);
C c = (C) lbc[i];
if ( a.remainder(c).isZERO() ) { //c.isUnit() ) {
a = a.divide( c );
} else {
S = S.multiply( c );
R = R.multiply( c );
}
Q = p[i].multiply( a, e );
S = S.subtract( Q );
}
}
return R;
}
/**
* Normalform with recording.
* <b>Note:</b> do not use, multiplication factor is lost.
* Will be removed or replaced in future.
* @typeparam C coefficient type.
* @param row recording matrix, is modified.
* @param Pp a polynomial list for reduction.
* @param Ap a polynomial.
* @return nf(Pp,Ap), the normal form of Ap wrt. Pp.
* @deprecated multiplication factor will be lost.
*/
public GenPolynomial<C>
normalform(List<GenPolynomial<C>> row,
List<GenPolynomial<C>> Pp,
GenPolynomial<C> Ap) {
List<C> mf = new ArrayList<C>(1);
mf.add(null);
logger.error("multiplication factor is lost");
return normalform(mf,row,Pp,Ap);
}
/**
* Normalform with recording.
* @typeparam C coefficient type.
* @param row recording matrix, is modified.
* @param mf multiplication factor for Ap, is modified.
* @param Pp a polynomial list for reduction.
* @param Ap a polynomial.
* @return nf(Pp,mf*Ap), the normal form of mf*Ap wrt. Pp.
*/
@SuppressWarnings("unchecked")
public GenPolynomial<C>
normalform(List<C> mf,
List<GenPolynomial<C>> row,
List<GenPolynomial<C>> Pp,
GenPolynomial<C> Ap) {
if ( Pp == null || Pp.isEmpty() ) {
return Ap;
}
if ( Ap == null || Ap.isZERO() ) {
return Ap;
}
int l = Pp.size();
GenPolynomial<C>[] P = new GenPolynomial[l];
synchronized (Pp) {
//P = Pp.toArray();
for ( int i = 0; i < Pp.size(); i++ ) {
P[i] = Pp.get(i);
}
}
ExpVector[] htl = new ExpVector[ l ];
Object[] lbc = new Object[ l ]; // want C
GenPolynomial<C>[] p = new GenPolynomial[ l ];
Map.Entry<ExpVector,C> m;
int j = 0;
int i;
for ( i = 0; i < l; i++ ) {
p[i] = P[i];
m = p[i].leadingMonomial();
if ( m != null ) {
p[j] = p[i];
htl[j] = m.getKey();
lbc[j] = m.getValue();
j++;
}
}
l = j;
ExpVector e;
C a;
boolean mt = false;
GenPolynomial<C> zero = Ap.ring.getZERO();
GenPolynomial<C> R = Ap.ring.getZERO();
C mfac = mf.get(0);
if ( mfac == null ) {
mfac = Ap.ring.getONECoefficient();
}
GenPolynomial<C> fac = null;
// GenPolynomial<C> T = null;
GenPolynomial<C> Q = null;
GenPolynomial<C> S = Ap;
while ( S.length() > 0 ) {
m = S.leadingMonomial();
e = m.getKey();
a = m.getValue();
for ( i = 0; i < l; i++ ) {
mt = ExpVector.EVMT( e, htl[i] );
if ( mt ) break;
}
if ( ! mt ) {
//logger.debug("irred");
R = R.sum( a, e );
S = S.subtract( a, e );
// System.out.println(" S = " + S);
//throw new RuntimeException("Syzygy no GB");
} else {
e = ExpVector.EVDIF( e, htl[i] );
//logger.info("red div = " + e);
C c = (C) lbc[i];
if ( a.remainder(c).isZERO() ) { //c.isUnit() ) {
a = a.divide( c );
//System.out.print("|");
} else {
//System.out.print("*");
S = S.multiply( c );
R = R.multiply( c );
mfac = mfac.multiply( c );
}
Q = p[i].multiply( a, e );
S = S.subtract( Q );
fac = row.get(i);
if ( fac == null ) {
fac = zero.sum( a, e );
} else {
fac = fac.sum( a, e );
}
row.set(i,fac);
}
}
//System.out.println(".");
mf.set(0,mfac);
return R;
}
}
|
diff --git a/srcj/com/sun/electric/tool/user/ui/SizeListener.java b/srcj/com/sun/electric/tool/user/ui/SizeListener.java
index da3887e23..e1218501b 100755
--- a/srcj/com/sun/electric/tool/user/ui/SizeListener.java
+++ b/srcj/com/sun/electric/tool/user/ui/SizeListener.java
@@ -1,704 +1,697 @@
/* -*- tab-width: 4 -*-
*
* Electric(tm) VLSI Design System
*
* File: SizeListener.java
*
* Copyright (c) 2004 Sun Microsystems and Static Free Software
*
* Electric(tm) 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.
*
* Electric(tm) 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 Electric(tm); see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, Mass 02111-1307, USA.
*/
package com.sun.electric.tool.user.ui;
import com.sun.electric.database.geometry.DBMath;
import com.sun.electric.database.geometry.EPoint;
import com.sun.electric.database.geometry.Geometric;
import com.sun.electric.database.geometry.Orientation;
import com.sun.electric.database.geometry.Poly;
import com.sun.electric.database.hierarchy.Cell;
import com.sun.electric.database.prototype.NodeProto;
import com.sun.electric.database.text.TextUtils;
import com.sun.electric.database.topology.ArcInst;
import com.sun.electric.database.topology.NodeInst;
import com.sun.electric.technology.ArcProto;
import com.sun.electric.technology.PrimitiveNode;
import com.sun.electric.technology.SizeOffset;
import com.sun.electric.tool.Job;
import com.sun.electric.tool.JobException;
import com.sun.electric.tool.user.CircuitChangeJobs;
import com.sun.electric.tool.user.Highlighter;
import com.sun.electric.tool.user.User;
import com.sun.electric.tool.user.dialogs.EDialog;
import java.awt.Cursor;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.util.EventListener;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;
/**
* Class to interactively resize a node.
*/
public class SizeListener
implements MouseMotionListener, MouseListener, MouseWheelListener, KeyListener
{
private Geometric stretchGeom;
private EventListener oldListener;
private Cursor oldCursor;
private Point2D farthestPoint;
private static Cursor sizeCursor = ToolBar.readCursor("CursorSize.gif", 14, 14);
private SizeListener() {}
/**
* Method to do an interactive sizing of the currently selected object.
*/
public static void sizeObjects()
{
EditWindow wnd = EditWindow.needCurrent();
if (wnd == null) return;
Highlighter highlighter = wnd.getHighlighter();
List<Geometric> geomList = highlighter.getHighlightedEObjs(true, true);
if (geomList == null) return;
if (geomList.size() != 1)
{
System.out.println("Select just one object to size");
return;
}
Geometric geom = (Geometric)geomList.get(0);
if (geom instanceof Geometric)
{
EventListener newListener = null;
// remember the listener that was there before
EventListener oldListener = WindowFrame.getListener();
Cursor oldCursor = TopLevel.getCurrentCursor();
System.out.println("Click to stretch " + geom);
newListener = oldListener;
if (newListener == null || !(newListener instanceof SizeListener))
{
newListener = new SizeListener();
WindowFrame.setListener(newListener);
}
((SizeListener)newListener).stretchGeom = geom;
((SizeListener)newListener).oldListener = oldListener;
((SizeListener)newListener).oldCursor = oldCursor;
// change the cursor
TopLevel.setCurrentCursor(sizeCursor);
}
}
/**
* Method to present a dialog to resize all selected nodes.
*/
public static void sizeAllNodes()
{
SizeObjects dialog = new SizeObjects(TopLevel.getCurrentJFrame(), true, true);
dialog.setVisible(true);
}
/**
* Method to present a dialog to resize all selected arcs.
*/
public static void sizeAllArcs()
{
SizeObjects dialog = new SizeObjects(TopLevel.getCurrentJFrame(), true, false);
dialog.setVisible(true);
}
/**
* Class to handle the "Size all selected nodes/arcs" dialog.
*/
private static class SizeObjects extends EDialog
{
private JTextField xSize, ySize;
boolean nodes;
/** Creates new form Size all selected nodes/arcs */
public SizeObjects(java.awt.Frame parent, boolean modal, boolean nodes)
{
super(parent, modal);
EditWindow wnd = EditWindow.needCurrent();
if (wnd == null) return;
Highlighter highlighter = wnd.getHighlighter();
getContentPane().setLayout(new GridBagLayout());
String label = "Width:";
this.nodes = nodes;
if (nodes)
{
label = "X Size:";
setTitle("Set Node Size");
JLabel ySizeLabel = new JLabel("Y Size:");
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 1;
gbc.insets = new java.awt.Insets(4, 4, 4, 4);
getContentPane().add(ySizeLabel, gbc);
ySize = new JTextField();
ySize.setColumns(6);
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 1;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new java.awt.Insets(4, 4, 4, 4);
getContentPane().add(ySize, gbc);
} else
{
setTitle("Set Arc Size");
}
JLabel xSizeLabel = new JLabel(label);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new java.awt.Insets(4, 4, 4, 4);
getContentPane().add(xSizeLabel, gbc);
xSize = new JTextField();
xSize.setColumns(6);
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new java.awt.Insets(4, 4, 4, 4);
getContentPane().add(xSize, gbc);
JButton ok = new JButton("OK");
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 2;
gbc.insets = new java.awt.Insets(4, 4, 4, 4);
getContentPane().add(ok, gbc);
JButton cancel = new JButton("Cancel");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 2;
gbc.insets = new java.awt.Insets(4, 4, 4, 4);
getContentPane().add(cancel, gbc);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent evt) { SizeObjectsClosing(evt); }
});
cancel.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent evt) { cancel(evt); }
});
ok.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent evt) { ok(evt); }
});
pack();
getRootPane().setDefaultButton(ok);
// determine default size
double xS = 0, yS = 0;
for(Geometric geom : highlighter.getHighlightedEObjs(true, true))
{
if (geom instanceof NodeInst && nodes)
{
NodeInst ni = (NodeInst)geom;
SizeOffset so = ni.getSizeOffset();
xS = ni.getXSize() - so.getLowXOffset() - so.getHighXOffset();
yS = ni.getYSize() - so.getLowYOffset() - so.getHighYOffset();
} else if (geom instanceof ArcInst && !nodes)
{
ArcInst ai = (ArcInst)geom;
xS = ai.getWidth() - ai.getProto().getWidthOffset();
}
}
xSize.setText(TextUtils.formatDouble(xS));
if (nodes)
ySize.setText(TextUtils.formatDouble(yS));
}
private void cancel(java.awt.event.ActionEvent evt)
{
SizeObjectsClosing(null);
}
private void ok(java.awt.event.ActionEvent evt)
{
// resize the objects
EditWindow wnd = EditWindow.needCurrent();
if (wnd == null) return;
Highlighter highlighter = wnd.getHighlighter();
List<Geometric> highlighted = highlighter.getHighlightedEObjs(true, true);
double xS = TextUtils.atof(xSize.getText());
double yS = 0;
if (nodes)
yS = TextUtils.atof(ySize.getText());
ResizeStuff job = new ResizeStuff(wnd.getCell(), highlighted, xS, yS, nodes);
SizeObjectsClosing(null);
}
private void SizeObjectsClosing(WindowEvent evt)
{
setVisible(false);
dispose();
}
}
/**
* Class to resize objects in a new thread.
*/
private static class ResizeStuff extends Job
{
private Cell cell;
private List<Geometric> highlighted;
private double xS, yS;
private boolean nodes;
protected ResizeStuff(Cell cell, List<Geometric> highlighted, double xS, double yS, boolean nodes)
{
super("Resize Objects", User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER);
this.cell = cell;
this.highlighted = highlighted;
this.xS = xS;
this.yS = yS;
this.nodes = nodes;
startJob();
}
public boolean doIt() throws JobException
{
// make sure moving the node is allowed
if (CircuitChangeJobs.cantEdit(cell, null, true) != 0) return false;
boolean didSomething = false;
for(Geometric geom : highlighted)
{
if (geom instanceof NodeInst && nodes)
{
NodeInst ni = (NodeInst)geom;
SizeOffset so = ni.getSizeOffset();
double x = xS + so.getLowXOffset() + so.getHighXOffset();
double y = yS + so.getLowYOffset() + so.getHighYOffset();
if (!ni.isCellInstance() && ((PrimitiveNode)ni.getProto()).isSquare())
{
if (y > x) x = y; else y = x;
}
ni.resize(x - ni.getXSize(), y - ni.getYSize());
didSomething = true;
} else if (geom instanceof ArcInst && !nodes)
{
ArcInst ai = (ArcInst)geom;
double w = xS + ai.getProto().getWidthOffset();
ai.modify(w - ai.getWidth(), 0, 0, 0, 0);
didSomething = true;
}
}
if (!didSomething)
{
System.out.println("Could not find any " + (nodes?"nodes":"arcs") + " to resize");
}
return true;
}
}
public void mousePressed(MouseEvent evt)
{
farthestPoint = null;
showHighlight(evt, (EditWindow)evt.getSource());
}
public void mouseMoved(MouseEvent evt)
{
farthestPoint = null;
showHighlight(evt, (EditWindow)evt.getSource());
farthestPoint = null;
}
public void mouseDragged(MouseEvent evt)
{
showHighlight(evt, (EditWindow)evt.getSource());
}
public void mouseReleased(MouseEvent evt)
{
// restore the listener to the former state
WindowFrame.setListener(oldListener);
TopLevel.setCurrentCursor(oldCursor);
EditWindow wnd = (EditWindow)evt.getSource();
showHighlight(null, wnd);
// handle scaling the selected objects
if (stretchGeom instanceof NodeInst)
{
NodeInst ni = (NodeInst)stretchGeom;
Point2D newCenter = new Point2D.Double(ni.getAnchorCenterX(), ni.getAnchorCenterY());
Point2D newSize = getNewNodeSize(evt, newCenter);
ScaleNode job = new ScaleNode(ni, new EPoint(newCenter.getX(), newCenter.getY()), newSize.getX(), newSize.getY());
} else
{
ArcInst ai = (ArcInst)stretchGeom;
double newWidth = getNewArcSize(evt);
ScaleArc job = new ScaleArc(ai, newWidth);
}
wnd.repaint();
}
public void keyPressed(KeyEvent evt)
{
int chr = evt.getKeyCode();
EditWindow wnd = (EditWindow)evt.getSource();
Cell cell = wnd.getCell();
if (cell == null) return;
// ESCAPE for abort
if (chr == KeyEvent.VK_ESCAPE)
{
// restore the listener to the former state
WindowFrame.setListener(oldListener);
TopLevel.setCurrentCursor(oldCursor);
showHighlight(null, wnd);
System.out.println("Aborted");
}
}
public void mouseClicked(MouseEvent evt) {}
public void mouseEntered(MouseEvent evt) {}
public void mouseExited(MouseEvent evt) {}
public void mouseWheelMoved(MouseWheelEvent evt) {}
public void keyReleased(KeyEvent evt) {}
public void keyTyped(KeyEvent evt) {}
private void showHighlight(MouseEvent evt, EditWindow wnd)
{
Highlighter highlighter = wnd.getHighlighter();
highlighter.clear();
highlighter.addElectricObject(stretchGeom, stretchGeom.getParent());
highlighter.finished();
if (evt != null)
{
if (stretchGeom instanceof NodeInst)
{
NodeInst ni = (NodeInst)stretchGeom;
Point2D newCenter = new Point2D.Double(ni.getAnchorCenterX(), ni.getAnchorCenterY());
Point2D newSize = getNewNodeSize(evt, newCenter);
SizeOffset so = ni.getSizeOffset();
AffineTransform trans = ni.getOrient().rotateAbout(newCenter.getX(), newCenter.getY());
double stretchedLowX = newCenter.getX() - newSize.getX()/2 + so.getLowXOffset();
double stretchedHighX = newCenter.getX() + newSize.getX()/2 - so.getHighXOffset();
double stretchedLowY = newCenter.getY() - newSize.getY()/2 + so.getLowYOffset();
double stretchedHighY = newCenter.getY() + newSize.getY()/2 - so.getHighYOffset();
Poly stretchedPoly = new Poly((stretchedLowX+stretchedHighX)/2, (stretchedLowY+stretchedHighY)/2,
stretchedHighX-stretchedLowX, stretchedHighY-stretchedLowY);
stretchedPoly.transform(trans);
Point2D [] stretchedPoints = stretchedPoly.getPoints();
for(int i=0; i<stretchedPoints.length; i++)
{
int lastI = i - 1;
if (lastI < 0) lastI = stretchedPoints.length - 1;
highlighter.addLine(stretchedPoints[lastI], stretchedPoints[i], ni.getParent());
}
} else
{
// construct the polygons that describe the basic arc
double newWidth = getNewArcSize(evt);
ArcInst ai = (ArcInst)stretchGeom;
Poly stretchedPoly = ai.makePoly(newWidth - ai.getProto().getWidthOffset(), Poly.Type.CLOSED);
if (stretchedPoly == null) return;
Point2D [] stretchedPoints = stretchedPoly.getPoints();
for(int i=0; i<stretchedPoints.length; i++)
{
int lastI = i - 1;
if (lastI < 0) lastI = stretchedPoints.length - 1;
highlighter.addLine(stretchedPoints[lastI], stretchedPoints[i], ai.getParent());
}
}
wnd.repaint();
}
}
/**
* Method to determine the proper size for the NodeInst being stretched, given a cursor location.
* @param evt the event with the current cursor location.
*/
private Point2D getNewNodeSize(MouseEvent evt, Point2D newCenter)
{
// get the coordinates of the cursor in database coordinates
EditWindow wnd = (EditWindow)evt.getSource();
int oldx = evt.getX();
int oldy = evt.getY();
Point2D pt = wnd.screenToDatabase(oldx, oldy);
// get information about the node being stretched
NodeInst ni = (NodeInst)stretchGeom;
NodeProto np = ni.getProto();
SizeOffset so = ni.getSizeOffset();
// setup outline of node with standard offset
double nodeLowX = ni.getTrueCenterX() - ni.getXSize()/2 + so.getLowXOffset();
double nodeHighX = ni.getTrueCenterX() + ni.getXSize()/2 - so.getHighXOffset();
double nodeLowY = ni.getTrueCenterY() - ni.getYSize()/2 + so.getLowYOffset();
double nodeHighY = ni.getTrueCenterY() + ni.getYSize()/2 - so.getHighYOffset();
Poly nodePoly = new Poly((nodeLowX+nodeHighX)/2, (nodeLowY+nodeHighY)/2, nodeHighX-nodeLowX, nodeHighY-nodeLowY);
AffineTransform trans = ni.rotateOutAboutTrueCenter();
nodePoly.transform(trans);
// determine the closest point on the outline
Point2D [] points = nodePoly.getPoints();
Point2D closest = null;
Point2D farthest = null;
if (farthestPoint != null)
{
for(int i=0; i<points.length; i++)
{
if (points[i].equals(farthestPoint))
{
closest = points[(i + points.length/2) % points.length];
farthest = farthestPoint;
break;
}
}
}
if (farthest == null || closest == null)
{
double closestDist = Double.MAX_VALUE;
for(int i=0; i<points.length; i++)
{
double dist = pt.distance(points[i]);
if (dist < closestDist)
{
closestDist = dist;
closest = points[i];
farthest = points[(i + points.length/2) % points.length];
}
}
}
farthestPoint = farthest;
// if Shift is held, use center-based sizing
boolean centerBased = (evt.getModifiersEx()&MouseEvent.SHIFT_DOWN_MASK) != 0 &&
(evt.getModifiersEx()&MouseEvent.CTRL_DOWN_MASK) != 0;
// determine the amount of growth of the node
AffineTransform transIn = ni.rotateIn();
double closestX = closest.getX();
double closestY = closest.getY();
double farthestX = farthestPoint.getX();
double farthestY = farthestPoint.getY();
transIn.transform(pt, pt);
transIn.transform(closest, closest);
transIn.transform(farthest, farthest);
double growthRatioX, growthRatioY;
if (centerBased)
{
double ptToCenterX = Math.abs(pt.getX() - ni.getTrueCenterX());
double closestToCenterX = Math.abs(closest.getX() - ni.getTrueCenterX());
double ptToCenterY = Math.abs(pt.getY() - ni.getTrueCenterY());
double closestToCenterY = Math.abs(closest.getY() - ni.getTrueCenterY());
growthRatioX = ptToCenterX / closestToCenterX;
growthRatioY = ptToCenterY / closestToCenterY;
} else
{
double ptToFarthestX = pt.getX() - farthest.getX();
double closestToFarthestX = closest.getX() - farthest.getX();
double ptToFarthestY = pt.getY() - farthest.getY();
double closestToFarthestY = closest.getY() - farthest.getY();
growthRatioX = ptToFarthestX / closestToFarthestX;
growthRatioY = ptToFarthestY / closestToFarthestY;
}
// see what keys are held
boolean square = !ni.isCellInstance() && ((PrimitiveNode)ni.getProto()).isSquare();
if ((evt.getModifiersEx()&MouseEvent.CTRL_DOWN_MASK) != 0 &&
(evt.getModifiersEx()&MouseEvent.SHIFT_DOWN_MASK) == 0)
{
// if Control is held, constrain to single-axis stretching
double grx = Math.abs(growthRatioX);
if (grx < 1)
{
if (grx == 0) grx = 9999; else grx = 1/grx;
}
double gry = Math.abs(growthRatioY);
if (gry < 1)
{
if (gry == 0) gry = 9999; else gry = 1/gry;
}
if (grx > gry) growthRatioY = 1; else
growthRatioX = 1;
} else if ((evt.getModifiersEx()&MouseEvent.SHIFT_DOWN_MASK) != 0 &&
(evt.getModifiersEx()&MouseEvent.CTRL_DOWN_MASK) == 0)
{
// if Shift is held, constrain proportions
square = true;
}
if (square)
{
if (Math.abs(growthRatioX) > Math.abs(growthRatioY)) growthRatioY = growthRatioX; else
growthRatioX = growthRatioY;
}
// compute the new node size
double newXSize = (ni.getXSize() - so.getLowXOffset() - so.getHighXOffset()) * growthRatioX;
double newYSize = (ni.getYSize() - so.getLowYOffset() - so.getHighYOffset()) * growthRatioY;
Point2D newSize = new Point2D.Double(newXSize, newYSize);
// grid align the new node size
- if (centerBased)
- {
- EditWindow.gridAlign(newSize);
- } else
- {
- double alignment = User.getAlignmentToGrid();
- DBMath.gridAlign(newSize, alignment);
- }
+ EditWindow.gridAlign(newSize);
// determine the new center point
if (!centerBased)
{
AffineTransform pureTrans = ni.pureRotateOut();
Point2D xformedSize = new Point2D.Double();
pureTrans.transform(newSize, xformedSize);
- if (closestX > farthestX) closestX = farthestX + xformedSize.getX(); else
- closestX = farthestX - xformedSize.getX();
- if (closestY > farthestY) closestY = farthestY + xformedSize.getY(); else
- closestY = farthestY - xformedSize.getY();
+ if (closestX > farthestX) closestX = farthestX + Math.abs(xformedSize.getX()); else
+ closestX = farthestX - Math.abs(xformedSize.getX());
+ if (closestY > farthestY) closestY = farthestY + Math.abs(xformedSize.getY()); else
+ closestY = farthestY - Math.abs(xformedSize.getY());
newCenter.setLocation((closestX + farthestX) / 2, (closestY + farthestY) / 2);
}
// adjust size offset to produce real size
newSize.setLocation(Math.abs(newSize.getX() + so.getLowXOffset() + so.getHighXOffset()),
Math.abs(newSize.getY() + so.getLowYOffset() + so.getHighYOffset()));
return newSize;
}
/**
* Method to determine the proper size for the ArcInst being stretched, given a cursor location.
* @param evt the event with the current cursor location.
* @return the new size for the ArcInst.
*/
private double getNewArcSize(MouseEvent evt)
{
// get the coordinates of the cursor in database coordinates
EditWindow wnd = (EditWindow)evt.getSource();
int oldx = evt.getX();
int oldy = evt.getY();
Point2D pt = wnd.screenToDatabase(oldx, oldy);
// get information about the arc being stretched
ArcInst ai = (ArcInst)stretchGeom;
ArcProto ap = ai.getProto();
double offset = ap.getWidthOffset();
// determine point on arc that is closest to the cursor
Point2D ptOnLine = DBMath.closestPointToLine(ai.getHeadLocation(), ai.getTailLocation(), pt);
double newWidth = ptOnLine.distance(pt)*2 + offset;
Point2D newSize = new Point2D.Double(newWidth, newWidth);
EditWindow.gridAlign(newSize);
return newSize.getX();
}
private static class ScaleNode extends Job
{
private NodeInst stretchNode;
private EPoint newCenter;
private double newWidth, newHeight;
protected ScaleNode(NodeInst stretchNode, EPoint newCenter, double newWidth, double newHeight)
{
super("Scale node", User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER);
this.stretchNode = stretchNode;
this.newCenter = newCenter;
this.newWidth = newWidth;
this.newHeight = newHeight;
startJob();
}
public boolean doIt() throws JobException
{
// make sure scaling the node is allowed
if (CircuitChangeJobs.cantEdit(stretchNode.getParent(), null, true) != 0) return false;
Point2D [] points = stretchNode.getTrace();
if (points != null)
{
double percX = newWidth / stretchNode.getXSize();
double percY = newHeight / stretchNode.getYSize();
Point2D [] newPoints = new Point2D[points.length];
for(int i=0; i<points.length; i++)
{
newPoints[i] = new Point2D.Double(points[i].getX()*percX, points[i].getY()*percY);
}
stretchNode.setTrace(newPoints);
}
double dWid = newWidth - stretchNode.getXSize();
double dHei = newHeight - stretchNode.getYSize();
stretchNode.modifyInstance(newCenter.getX() - stretchNode.getAnchorCenterX(),
newCenter.getY() - stretchNode.getAnchorCenterY(), dWid, dHei, Orientation.IDENT);
return true;
}
}
private static class ScaleArc extends Job
{
private ArcInst stretchArc;
private double newWidth;
protected ScaleArc(ArcInst stretchArc, double newWidth)
{
super("Scale arc", User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER);
this.stretchArc = stretchArc;
this.newWidth = newWidth;
startJob();
}
public boolean doIt() throws JobException
{
// make sure scaling the arc is allowed
if (CircuitChangeJobs.cantEdit(stretchArc.getParent(), null, true) != 0) return false;
stretchArc.modify(newWidth - stretchArc.getWidth(), 0, 0, 0, 0);
return true;
}
}
}
| false | true | private Point2D getNewNodeSize(MouseEvent evt, Point2D newCenter)
{
// get the coordinates of the cursor in database coordinates
EditWindow wnd = (EditWindow)evt.getSource();
int oldx = evt.getX();
int oldy = evt.getY();
Point2D pt = wnd.screenToDatabase(oldx, oldy);
// get information about the node being stretched
NodeInst ni = (NodeInst)stretchGeom;
NodeProto np = ni.getProto();
SizeOffset so = ni.getSizeOffset();
// setup outline of node with standard offset
double nodeLowX = ni.getTrueCenterX() - ni.getXSize()/2 + so.getLowXOffset();
double nodeHighX = ni.getTrueCenterX() + ni.getXSize()/2 - so.getHighXOffset();
double nodeLowY = ni.getTrueCenterY() - ni.getYSize()/2 + so.getLowYOffset();
double nodeHighY = ni.getTrueCenterY() + ni.getYSize()/2 - so.getHighYOffset();
Poly nodePoly = new Poly((nodeLowX+nodeHighX)/2, (nodeLowY+nodeHighY)/2, nodeHighX-nodeLowX, nodeHighY-nodeLowY);
AffineTransform trans = ni.rotateOutAboutTrueCenter();
nodePoly.transform(trans);
// determine the closest point on the outline
Point2D [] points = nodePoly.getPoints();
Point2D closest = null;
Point2D farthest = null;
if (farthestPoint != null)
{
for(int i=0; i<points.length; i++)
{
if (points[i].equals(farthestPoint))
{
closest = points[(i + points.length/2) % points.length];
farthest = farthestPoint;
break;
}
}
}
if (farthest == null || closest == null)
{
double closestDist = Double.MAX_VALUE;
for(int i=0; i<points.length; i++)
{
double dist = pt.distance(points[i]);
if (dist < closestDist)
{
closestDist = dist;
closest = points[i];
farthest = points[(i + points.length/2) % points.length];
}
}
}
farthestPoint = farthest;
// if Shift is held, use center-based sizing
boolean centerBased = (evt.getModifiersEx()&MouseEvent.SHIFT_DOWN_MASK) != 0 &&
(evt.getModifiersEx()&MouseEvent.CTRL_DOWN_MASK) != 0;
// determine the amount of growth of the node
AffineTransform transIn = ni.rotateIn();
double closestX = closest.getX();
double closestY = closest.getY();
double farthestX = farthestPoint.getX();
double farthestY = farthestPoint.getY();
transIn.transform(pt, pt);
transIn.transform(closest, closest);
transIn.transform(farthest, farthest);
double growthRatioX, growthRatioY;
if (centerBased)
{
double ptToCenterX = Math.abs(pt.getX() - ni.getTrueCenterX());
double closestToCenterX = Math.abs(closest.getX() - ni.getTrueCenterX());
double ptToCenterY = Math.abs(pt.getY() - ni.getTrueCenterY());
double closestToCenterY = Math.abs(closest.getY() - ni.getTrueCenterY());
growthRatioX = ptToCenterX / closestToCenterX;
growthRatioY = ptToCenterY / closestToCenterY;
} else
{
double ptToFarthestX = pt.getX() - farthest.getX();
double closestToFarthestX = closest.getX() - farthest.getX();
double ptToFarthestY = pt.getY() - farthest.getY();
double closestToFarthestY = closest.getY() - farthest.getY();
growthRatioX = ptToFarthestX / closestToFarthestX;
growthRatioY = ptToFarthestY / closestToFarthestY;
}
// see what keys are held
boolean square = !ni.isCellInstance() && ((PrimitiveNode)ni.getProto()).isSquare();
if ((evt.getModifiersEx()&MouseEvent.CTRL_DOWN_MASK) != 0 &&
(evt.getModifiersEx()&MouseEvent.SHIFT_DOWN_MASK) == 0)
{
// if Control is held, constrain to single-axis stretching
double grx = Math.abs(growthRatioX);
if (grx < 1)
{
if (grx == 0) grx = 9999; else grx = 1/grx;
}
double gry = Math.abs(growthRatioY);
if (gry < 1)
{
if (gry == 0) gry = 9999; else gry = 1/gry;
}
if (grx > gry) growthRatioY = 1; else
growthRatioX = 1;
} else if ((evt.getModifiersEx()&MouseEvent.SHIFT_DOWN_MASK) != 0 &&
(evt.getModifiersEx()&MouseEvent.CTRL_DOWN_MASK) == 0)
{
// if Shift is held, constrain proportions
square = true;
}
if (square)
{
if (Math.abs(growthRatioX) > Math.abs(growthRatioY)) growthRatioY = growthRatioX; else
growthRatioX = growthRatioY;
}
// compute the new node size
double newXSize = (ni.getXSize() - so.getLowXOffset() - so.getHighXOffset()) * growthRatioX;
double newYSize = (ni.getYSize() - so.getLowYOffset() - so.getHighYOffset()) * growthRatioY;
Point2D newSize = new Point2D.Double(newXSize, newYSize);
// grid align the new node size
if (centerBased)
{
EditWindow.gridAlign(newSize);
} else
{
double alignment = User.getAlignmentToGrid();
DBMath.gridAlign(newSize, alignment);
}
// determine the new center point
if (!centerBased)
{
AffineTransform pureTrans = ni.pureRotateOut();
Point2D xformedSize = new Point2D.Double();
pureTrans.transform(newSize, xformedSize);
if (closestX > farthestX) closestX = farthestX + xformedSize.getX(); else
closestX = farthestX - xformedSize.getX();
if (closestY > farthestY) closestY = farthestY + xformedSize.getY(); else
closestY = farthestY - xformedSize.getY();
newCenter.setLocation((closestX + farthestX) / 2, (closestY + farthestY) / 2);
}
// adjust size offset to produce real size
newSize.setLocation(Math.abs(newSize.getX() + so.getLowXOffset() + so.getHighXOffset()),
Math.abs(newSize.getY() + so.getLowYOffset() + so.getHighYOffset()));
return newSize;
}
| private Point2D getNewNodeSize(MouseEvent evt, Point2D newCenter)
{
// get the coordinates of the cursor in database coordinates
EditWindow wnd = (EditWindow)evt.getSource();
int oldx = evt.getX();
int oldy = evt.getY();
Point2D pt = wnd.screenToDatabase(oldx, oldy);
// get information about the node being stretched
NodeInst ni = (NodeInst)stretchGeom;
NodeProto np = ni.getProto();
SizeOffset so = ni.getSizeOffset();
// setup outline of node with standard offset
double nodeLowX = ni.getTrueCenterX() - ni.getXSize()/2 + so.getLowXOffset();
double nodeHighX = ni.getTrueCenterX() + ni.getXSize()/2 - so.getHighXOffset();
double nodeLowY = ni.getTrueCenterY() - ni.getYSize()/2 + so.getLowYOffset();
double nodeHighY = ni.getTrueCenterY() + ni.getYSize()/2 - so.getHighYOffset();
Poly nodePoly = new Poly((nodeLowX+nodeHighX)/2, (nodeLowY+nodeHighY)/2, nodeHighX-nodeLowX, nodeHighY-nodeLowY);
AffineTransform trans = ni.rotateOutAboutTrueCenter();
nodePoly.transform(trans);
// determine the closest point on the outline
Point2D [] points = nodePoly.getPoints();
Point2D closest = null;
Point2D farthest = null;
if (farthestPoint != null)
{
for(int i=0; i<points.length; i++)
{
if (points[i].equals(farthestPoint))
{
closest = points[(i + points.length/2) % points.length];
farthest = farthestPoint;
break;
}
}
}
if (farthest == null || closest == null)
{
double closestDist = Double.MAX_VALUE;
for(int i=0; i<points.length; i++)
{
double dist = pt.distance(points[i]);
if (dist < closestDist)
{
closestDist = dist;
closest = points[i];
farthest = points[(i + points.length/2) % points.length];
}
}
}
farthestPoint = farthest;
// if Shift is held, use center-based sizing
boolean centerBased = (evt.getModifiersEx()&MouseEvent.SHIFT_DOWN_MASK) != 0 &&
(evt.getModifiersEx()&MouseEvent.CTRL_DOWN_MASK) != 0;
// determine the amount of growth of the node
AffineTransform transIn = ni.rotateIn();
double closestX = closest.getX();
double closestY = closest.getY();
double farthestX = farthestPoint.getX();
double farthestY = farthestPoint.getY();
transIn.transform(pt, pt);
transIn.transform(closest, closest);
transIn.transform(farthest, farthest);
double growthRatioX, growthRatioY;
if (centerBased)
{
double ptToCenterX = Math.abs(pt.getX() - ni.getTrueCenterX());
double closestToCenterX = Math.abs(closest.getX() - ni.getTrueCenterX());
double ptToCenterY = Math.abs(pt.getY() - ni.getTrueCenterY());
double closestToCenterY = Math.abs(closest.getY() - ni.getTrueCenterY());
growthRatioX = ptToCenterX / closestToCenterX;
growthRatioY = ptToCenterY / closestToCenterY;
} else
{
double ptToFarthestX = pt.getX() - farthest.getX();
double closestToFarthestX = closest.getX() - farthest.getX();
double ptToFarthestY = pt.getY() - farthest.getY();
double closestToFarthestY = closest.getY() - farthest.getY();
growthRatioX = ptToFarthestX / closestToFarthestX;
growthRatioY = ptToFarthestY / closestToFarthestY;
}
// see what keys are held
boolean square = !ni.isCellInstance() && ((PrimitiveNode)ni.getProto()).isSquare();
if ((evt.getModifiersEx()&MouseEvent.CTRL_DOWN_MASK) != 0 &&
(evt.getModifiersEx()&MouseEvent.SHIFT_DOWN_MASK) == 0)
{
// if Control is held, constrain to single-axis stretching
double grx = Math.abs(growthRatioX);
if (grx < 1)
{
if (grx == 0) grx = 9999; else grx = 1/grx;
}
double gry = Math.abs(growthRatioY);
if (gry < 1)
{
if (gry == 0) gry = 9999; else gry = 1/gry;
}
if (grx > gry) growthRatioY = 1; else
growthRatioX = 1;
} else if ((evt.getModifiersEx()&MouseEvent.SHIFT_DOWN_MASK) != 0 &&
(evt.getModifiersEx()&MouseEvent.CTRL_DOWN_MASK) == 0)
{
// if Shift is held, constrain proportions
square = true;
}
if (square)
{
if (Math.abs(growthRatioX) > Math.abs(growthRatioY)) growthRatioY = growthRatioX; else
growthRatioX = growthRatioY;
}
// compute the new node size
double newXSize = (ni.getXSize() - so.getLowXOffset() - so.getHighXOffset()) * growthRatioX;
double newYSize = (ni.getYSize() - so.getLowYOffset() - so.getHighYOffset()) * growthRatioY;
Point2D newSize = new Point2D.Double(newXSize, newYSize);
// grid align the new node size
EditWindow.gridAlign(newSize);
// determine the new center point
if (!centerBased)
{
AffineTransform pureTrans = ni.pureRotateOut();
Point2D xformedSize = new Point2D.Double();
pureTrans.transform(newSize, xformedSize);
if (closestX > farthestX) closestX = farthestX + Math.abs(xformedSize.getX()); else
closestX = farthestX - Math.abs(xformedSize.getX());
if (closestY > farthestY) closestY = farthestY + Math.abs(xformedSize.getY()); else
closestY = farthestY - Math.abs(xformedSize.getY());
newCenter.setLocation((closestX + farthestX) / 2, (closestY + farthestY) / 2);
}
// adjust size offset to produce real size
newSize.setLocation(Math.abs(newSize.getX() + so.getLowXOffset() + so.getHighXOffset()),
Math.abs(newSize.getY() + so.getLowYOffset() + so.getHighYOffset()));
return newSize;
}
|
diff --git a/src/test/java/net/chat/util/HttpClientTest.java b/src/test/java/net/chat/util/HttpClientTest.java
index 3164450..d4a2183 100644
--- a/src/test/java/net/chat/util/HttpClientTest.java
+++ b/src/test/java/net/chat/util/HttpClientTest.java
@@ -1,91 +1,91 @@
package net.chat.util;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
public class HttpClientTest {
/**
* @param args
* @throws ParseException
*/
public static void main(String[] args) throws IOException, ParseException {
// yyyy_mm_dd
String s = "2013_09_20";
SimpleDateFormat sf = new SimpleDateFormat("yyyy_MM_dd");
Date d = sf.parse(s);
System.out.println(d);
// String content = "<xml>";
// content = content + " <ToUserName><![CDATA[toUser]]></ToUserName>";
// content = content
// + " <FromUserName><![CDATA[fromUser]]></FromUserName>";
// content = content + "<CreateTime>1348831860</CreateTime>";
// content = content + "<MsgType><![CDATA[text]]></MsgType>";
// content = content + "<Content><![CDATA[你好]]></Content>";
// content = content + "<MsgId>1234567890123456</MsgId>";
// content = content + "</xml>";
// String content = "<xml>";
// content = content + " <ToUserName><![CDATA[toUser]]></ToUserName>";
// content = content
// + " <FromUserName><![CDATA[fromUser]]></FromUserName>";
// content = content + " <CreateTime>1348831860</CreateTime>";
// content = content + " <MsgType><![CDATA[image]]></MsgType>";
// content = content + " <PicUrl><![CDATA[this is a url]]></PicUrl>";
// content = content + " <MsgId>1234567890123456</MsgId>";
// content = content + " </xml>";
// @SuppressWarnings("deprecation")
// HttpClient httpclient = new DefaultHttpClient();
// HttpPost httppost = new HttpPost(
// "http://localhost:8080/WeiChat/API/JzfNgyGmEQKvqnaCBLNt");
// StringEntity myEntity = new StringEntity(content, "UTF-8");
// httppost.addHeader("Content-Type", "text/xml");
// httppost.setEntity(myEntity);
// HttpResponse response = httpclient.execute(httppost);
// HttpEntity resEntity = response.getEntity();
// InputStreamReader reader = new InputStreamReader(
// resEntity.getContent(), "UTF-8");
String content = "<xml>";
content = content + " <ToUserName><![CDATA[toUser]]></ToUserName>";
content = content
+ " <FromUserName><![CDATA[fromUser]]></FromUserName>";
content = content + "<CreateTime>1348831860</CreateTime>";
- content = content + "<MsgType><![CDATA[voice]]></MsgType>";
+ content = content + "<MsgType><![CDATA[image]]></MsgType>";
content = content + "<MediaId><![CDATA[media_id]]></MediaId>";
- content = content + "<Format><![CDATA[Format]]></Format>";
+ content = content + "<PicUrl><![CDATA[this is a url]]></PicUrl>";
content = content + "<MsgId>1234567890123456</MsgId>";
content = content + "<MsgId>1234567890123456</MsgId>";
content = content + "</xml>";
@SuppressWarnings("deprecation")
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://localhost:8080/WeiChat/API/lLfMiuDuqWiqKLvHXEvF");
StringEntity myEntity = new StringEntity(content, "UTF-8");
httppost.addHeader("Content-Type", "text/xml");
httppost.setEntity(myEntity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
InputStreamReader reader = new InputStreamReader(
resEntity.getContent(), "UTF-8");
char[] buff = new char[1024];
int length = 0;
while ((length = reader.read(buff)) != -1) {
System.out.println(new String(buff, 0, length));
}
httpclient.getConnectionManager().shutdown();
}
}
| false | true | public static void main(String[] args) throws IOException, ParseException {
// yyyy_mm_dd
String s = "2013_09_20";
SimpleDateFormat sf = new SimpleDateFormat("yyyy_MM_dd");
Date d = sf.parse(s);
System.out.println(d);
// String content = "<xml>";
// content = content + " <ToUserName><![CDATA[toUser]]></ToUserName>";
// content = content
// + " <FromUserName><![CDATA[fromUser]]></FromUserName>";
// content = content + "<CreateTime>1348831860</CreateTime>";
// content = content + "<MsgType><![CDATA[text]]></MsgType>";
// content = content + "<Content><![CDATA[你好]]></Content>";
// content = content + "<MsgId>1234567890123456</MsgId>";
// content = content + "</xml>";
// String content = "<xml>";
// content = content + " <ToUserName><![CDATA[toUser]]></ToUserName>";
// content = content
// + " <FromUserName><![CDATA[fromUser]]></FromUserName>";
// content = content + " <CreateTime>1348831860</CreateTime>";
// content = content + " <MsgType><![CDATA[image]]></MsgType>";
// content = content + " <PicUrl><![CDATA[this is a url]]></PicUrl>";
// content = content + " <MsgId>1234567890123456</MsgId>";
// content = content + " </xml>";
// @SuppressWarnings("deprecation")
// HttpClient httpclient = new DefaultHttpClient();
// HttpPost httppost = new HttpPost(
// "http://localhost:8080/WeiChat/API/JzfNgyGmEQKvqnaCBLNt");
// StringEntity myEntity = new StringEntity(content, "UTF-8");
// httppost.addHeader("Content-Type", "text/xml");
// httppost.setEntity(myEntity);
// HttpResponse response = httpclient.execute(httppost);
// HttpEntity resEntity = response.getEntity();
// InputStreamReader reader = new InputStreamReader(
// resEntity.getContent(), "UTF-8");
String content = "<xml>";
content = content + " <ToUserName><![CDATA[toUser]]></ToUserName>";
content = content
+ " <FromUserName><![CDATA[fromUser]]></FromUserName>";
content = content + "<CreateTime>1348831860</CreateTime>";
content = content + "<MsgType><![CDATA[voice]]></MsgType>";
content = content + "<MediaId><![CDATA[media_id]]></MediaId>";
content = content + "<Format><![CDATA[Format]]></Format>";
content = content + "<MsgId>1234567890123456</MsgId>";
content = content + "<MsgId>1234567890123456</MsgId>";
content = content + "</xml>";
@SuppressWarnings("deprecation")
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://localhost:8080/WeiChat/API/lLfMiuDuqWiqKLvHXEvF");
StringEntity myEntity = new StringEntity(content, "UTF-8");
httppost.addHeader("Content-Type", "text/xml");
httppost.setEntity(myEntity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
InputStreamReader reader = new InputStreamReader(
resEntity.getContent(), "UTF-8");
char[] buff = new char[1024];
int length = 0;
while ((length = reader.read(buff)) != -1) {
System.out.println(new String(buff, 0, length));
}
httpclient.getConnectionManager().shutdown();
}
| public static void main(String[] args) throws IOException, ParseException {
// yyyy_mm_dd
String s = "2013_09_20";
SimpleDateFormat sf = new SimpleDateFormat("yyyy_MM_dd");
Date d = sf.parse(s);
System.out.println(d);
// String content = "<xml>";
// content = content + " <ToUserName><![CDATA[toUser]]></ToUserName>";
// content = content
// + " <FromUserName><![CDATA[fromUser]]></FromUserName>";
// content = content + "<CreateTime>1348831860</CreateTime>";
// content = content + "<MsgType><![CDATA[text]]></MsgType>";
// content = content + "<Content><![CDATA[你好]]></Content>";
// content = content + "<MsgId>1234567890123456</MsgId>";
// content = content + "</xml>";
// String content = "<xml>";
// content = content + " <ToUserName><![CDATA[toUser]]></ToUserName>";
// content = content
// + " <FromUserName><![CDATA[fromUser]]></FromUserName>";
// content = content + " <CreateTime>1348831860</CreateTime>";
// content = content + " <MsgType><![CDATA[image]]></MsgType>";
// content = content + " <PicUrl><![CDATA[this is a url]]></PicUrl>";
// content = content + " <MsgId>1234567890123456</MsgId>";
// content = content + " </xml>";
// @SuppressWarnings("deprecation")
// HttpClient httpclient = new DefaultHttpClient();
// HttpPost httppost = new HttpPost(
// "http://localhost:8080/WeiChat/API/JzfNgyGmEQKvqnaCBLNt");
// StringEntity myEntity = new StringEntity(content, "UTF-8");
// httppost.addHeader("Content-Type", "text/xml");
// httppost.setEntity(myEntity);
// HttpResponse response = httpclient.execute(httppost);
// HttpEntity resEntity = response.getEntity();
// InputStreamReader reader = new InputStreamReader(
// resEntity.getContent(), "UTF-8");
String content = "<xml>";
content = content + " <ToUserName><![CDATA[toUser]]></ToUserName>";
content = content
+ " <FromUserName><![CDATA[fromUser]]></FromUserName>";
content = content + "<CreateTime>1348831860</CreateTime>";
content = content + "<MsgType><![CDATA[image]]></MsgType>";
content = content + "<MediaId><![CDATA[media_id]]></MediaId>";
content = content + "<PicUrl><![CDATA[this is a url]]></PicUrl>";
content = content + "<MsgId>1234567890123456</MsgId>";
content = content + "<MsgId>1234567890123456</MsgId>";
content = content + "</xml>";
@SuppressWarnings("deprecation")
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://localhost:8080/WeiChat/API/lLfMiuDuqWiqKLvHXEvF");
StringEntity myEntity = new StringEntity(content, "UTF-8");
httppost.addHeader("Content-Type", "text/xml");
httppost.setEntity(myEntity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
InputStreamReader reader = new InputStreamReader(
resEntity.getContent(), "UTF-8");
char[] buff = new char[1024];
int length = 0;
while ((length = reader.read(buff)) != -1) {
System.out.println(new String(buff, 0, length));
}
httpclient.getConnectionManager().shutdown();
}
|
diff --git a/java/src/org/vinodkd/jnv/JNVBase.java b/java/src/org/vinodkd/jnv/JNVBase.java
index 882f781..3d023b2 100644
--- a/java/src/org/vinodkd/jnv/JNVBase.java
+++ b/java/src/org/vinodkd/jnv/JNVBase.java
@@ -1,219 +1,221 @@
package org.vinodkd.jnv;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import java.util.HashMap;
import java.util.List;
import java.util.Date;
abstract class JNVBase{
public JNVBase(){
Models logicalModels = createModels();
// Models viewModels = jnv.createViewModels(logicalModels);
HashMap<String,Component> ui = createUI(logicalModels); // call getInitialState to build ui.
// ignoring the urge to overengineer with state machines for now.
addBehaviors(ui,logicalModels);
ui.get("window").setVisible(true);
}
public Models createModels(){
NotesStore store = getStore();
store.setDir(System.getProperty("user.dir"));
Notes notes = new Notes(store);
Models models = new Models();
models.add("notes",notes);
return models;
}
public abstract NotesStore getStore();
// public Models createViewModels(Models logicalModels){
// ViewModels models = new ViewModels();
// Model logicalNotes = logicalModels.get("notes");
// models.add("notetitle", new NoteTitle(logicalNotes));
// models.add("searchresults", new SearchResults(logicalNotes));
// models.add("notecontents", new NoteContents(logicalNotes));
// }
public HashMap<String,Component> createUI(Models models){
HashMap<String,Component> controls = new HashMap<String,Component>();
JTextField noteName = new JTextField();
noteName.setPreferredSize(new Dimension(500,25));
controls.put("noteName", noteName);
// should createUI know about model data? no. kludge for now.
@SuppressWarnings("unchecked")
HashMap<String,Note> notes = (HashMap<String,Note>)(models.get("notes").getInitialValue());
NoteListTableModel foundNotesModel = new NoteListTableModel(notes);
JTable foundNotes = new JTable(foundNotesModel);
foundNotes.setFillsViewportHeight(true);
foundNotes.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
JScrollPane foundNotesScroller = new JScrollPane(foundNotes);
foundNotesScroller.setPreferredSize(new Dimension(500,150));
controls.put("foundNotes", foundNotes);
JTextArea noteContent = new JTextArea();
noteContent.setLineWrap(true);
noteContent.setTabSize(4);
noteContent.setWrapStyleWord(true);
JScrollPane noteContentScroller = new JScrollPane(noteContent);
noteContentScroller.setPreferredSize(new Dimension(500,400));
controls.put("noteContent", noteContent);
Box vbox = Box.createVerticalBox();
vbox.add(noteName);
vbox.add(foundNotesScroller);
vbox.add(noteContentScroller);
JFrame ui = new JFrame("jNV");
ui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ui.setPreferredSize(new Dimension(520,600));
ui.add(vbox);
ui.pack();
controls.put("window", ui);
return controls;
}
private boolean SEARCHING = false;
private int DOC_MOD_EVENT_COUNT = 0;
private final int EVENT_COUNT_TO_SAVE_AT = 20;
public void addBehaviors(HashMap<String,Component> ui, final Models models){
final JTextField noteName = (JTextField)ui.get("noteName");
final JTable foundNotes = (JTable)ui.get("foundNotes");
final JTextArea noteContent = (JTextArea)ui.get("noteContent");
final JFrame window = (JFrame)ui.get("window");
final Notes notes = (Notes) models.get("notes");
noteName.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent e){
SEARCHING = true;
String nName = noteName.getText();
List<String> searchResult = notes.search(nName);
// clear out list's model first regardless of search outcome.
@SuppressWarnings("unchecked")
DefaultTableModel fnModel = (DefaultTableModel)foundNotes.getModel();
fnModel.setRowCount(0);
if(searchResult.isEmpty()){
noteContent.requestFocus();
}
else{
for(String title:searchResult){
fnModel.addRow(new Object[] {title, notes.get(title).getLastModified()});
}
}
SEARCHING = false;
}
}
);
foundNotes.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent e){
// when still in search mode, this event is triggered by elements being added/removed
// from the model. the title should not updated then.
if(!SEARCHING){
// set the note title to the selected value
String selectedNote = (String)foundNotes.getValueAt(foundNotes.getSelectedRow(),0);
noteName.setText(selectedNote);
}
// now set the content to reflect the selection as well
setNoteContent(noteContent, notes, foundNotes);
}
});
foundNotes.addKeyListener(new KeyAdapter(){
// this is from http://stackoverflow.com/a/5043957's 'Use a keylistener' solution
public void keyPressed(KeyEvent e){
if (e.getKeyCode() == KeyEvent.VK_TAB && e.isShiftDown()){
e.consume();
KeyboardFocusManager.getCurrentKeyboardFocusManager().focusPreviousComponent();
+ noteName.selectAll();
}
}
});
noteContent.addKeyListener(new KeyAdapter(){
// this is from http://stackoverflow.com/a/5043957's 'Use a keylistener' solution
public void keyPressed(KeyEvent e){
if (e.getKeyCode() == KeyEvent.VK_TAB && e.isShiftDown()){
e.consume();
// fix for issue #6
saveIncremental(noteContent,noteName,notes);
KeyboardFocusManager.getCurrentKeyboardFocusManager().focusPreviousComponent();
+ noteName.selectAll();
}
}
});
noteContent.getDocument().addDocumentListener(new DocumentListener(){
public void insertUpdate(DocumentEvent e) {
saveIfRequired(e);
}
public void removeUpdate(DocumentEvent e) {
saveIfRequired(e);
}
public void changedUpdate(DocumentEvent e) {
//Plain text components do not fire these events
}
//TODO: do both saveIfRequired()s need to be synchronized?
private synchronized void saveIfRequired(DocumentEvent e){
if(DOC_MOD_EVENT_COUNT == EVENT_COUNT_TO_SAVE_AT){
saveIncremental(noteContent,noteName,notes);
DOC_MOD_EVENT_COUNT = 0;
}
else{
DOC_MOD_EVENT_COUNT++;
}
}
});
window.addWindowListener( new WindowAdapter(){
public void windowClosing(WindowEvent e){
saveIncremental(noteContent,noteName,notes);
}
}
);
}
private void setNoteContent(JTextArea noteContent, Notes notes,JTable foundNotes){
int selectedRow = foundNotes.getSelectedRow();
String content = "";
if(selectedRow >=0 ){ // selection exists
String selectedNoteName = (String)foundNotes.getValueAt(selectedRow,0);
Note selectedNote = notes.get(selectedNoteName);
content = selectedNote != null ? selectedNote.getContents(): "";
}
noteContent.selectAll();
noteContent.replaceSelection(content);
noteContent.setCaretPosition(0);
}
private void saveIncremental(JTextArea noteContent,JTextField noteName, Notes notes){
Document doc = noteContent.getDocument();
String title = noteName.getText();
String text = "";
try{
text = doc.getText(doc.getStartPosition().getOffset(), doc.getLength());
}catch(BadLocationException ble){
System.out.println("text exception:" + ble);
}
if( !"".equals(title) && !"".equals(text)){
notes.set(title, text);
}
notes.store();
}
}
| false | true | public void addBehaviors(HashMap<String,Component> ui, final Models models){
final JTextField noteName = (JTextField)ui.get("noteName");
final JTable foundNotes = (JTable)ui.get("foundNotes");
final JTextArea noteContent = (JTextArea)ui.get("noteContent");
final JFrame window = (JFrame)ui.get("window");
final Notes notes = (Notes) models.get("notes");
noteName.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent e){
SEARCHING = true;
String nName = noteName.getText();
List<String> searchResult = notes.search(nName);
// clear out list's model first regardless of search outcome.
@SuppressWarnings("unchecked")
DefaultTableModel fnModel = (DefaultTableModel)foundNotes.getModel();
fnModel.setRowCount(0);
if(searchResult.isEmpty()){
noteContent.requestFocus();
}
else{
for(String title:searchResult){
fnModel.addRow(new Object[] {title, notes.get(title).getLastModified()});
}
}
SEARCHING = false;
}
}
);
foundNotes.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent e){
// when still in search mode, this event is triggered by elements being added/removed
// from the model. the title should not updated then.
if(!SEARCHING){
// set the note title to the selected value
String selectedNote = (String)foundNotes.getValueAt(foundNotes.getSelectedRow(),0);
noteName.setText(selectedNote);
}
// now set the content to reflect the selection as well
setNoteContent(noteContent, notes, foundNotes);
}
});
foundNotes.addKeyListener(new KeyAdapter(){
// this is from http://stackoverflow.com/a/5043957's 'Use a keylistener' solution
public void keyPressed(KeyEvent e){
if (e.getKeyCode() == KeyEvent.VK_TAB && e.isShiftDown()){
e.consume();
KeyboardFocusManager.getCurrentKeyboardFocusManager().focusPreviousComponent();
}
}
});
noteContent.addKeyListener(new KeyAdapter(){
// this is from http://stackoverflow.com/a/5043957's 'Use a keylistener' solution
public void keyPressed(KeyEvent e){
if (e.getKeyCode() == KeyEvent.VK_TAB && e.isShiftDown()){
e.consume();
// fix for issue #6
saveIncremental(noteContent,noteName,notes);
KeyboardFocusManager.getCurrentKeyboardFocusManager().focusPreviousComponent();
}
}
});
noteContent.getDocument().addDocumentListener(new DocumentListener(){
public void insertUpdate(DocumentEvent e) {
saveIfRequired(e);
}
public void removeUpdate(DocumentEvent e) {
saveIfRequired(e);
}
public void changedUpdate(DocumentEvent e) {
//Plain text components do not fire these events
}
//TODO: do both saveIfRequired()s need to be synchronized?
private synchronized void saveIfRequired(DocumentEvent e){
if(DOC_MOD_EVENT_COUNT == EVENT_COUNT_TO_SAVE_AT){
saveIncremental(noteContent,noteName,notes);
DOC_MOD_EVENT_COUNT = 0;
}
else{
DOC_MOD_EVENT_COUNT++;
}
}
});
window.addWindowListener( new WindowAdapter(){
public void windowClosing(WindowEvent e){
saveIncremental(noteContent,noteName,notes);
}
}
);
}
| public void addBehaviors(HashMap<String,Component> ui, final Models models){
final JTextField noteName = (JTextField)ui.get("noteName");
final JTable foundNotes = (JTable)ui.get("foundNotes");
final JTextArea noteContent = (JTextArea)ui.get("noteContent");
final JFrame window = (JFrame)ui.get("window");
final Notes notes = (Notes) models.get("notes");
noteName.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent e){
SEARCHING = true;
String nName = noteName.getText();
List<String> searchResult = notes.search(nName);
// clear out list's model first regardless of search outcome.
@SuppressWarnings("unchecked")
DefaultTableModel fnModel = (DefaultTableModel)foundNotes.getModel();
fnModel.setRowCount(0);
if(searchResult.isEmpty()){
noteContent.requestFocus();
}
else{
for(String title:searchResult){
fnModel.addRow(new Object[] {title, notes.get(title).getLastModified()});
}
}
SEARCHING = false;
}
}
);
foundNotes.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent e){
// when still in search mode, this event is triggered by elements being added/removed
// from the model. the title should not updated then.
if(!SEARCHING){
// set the note title to the selected value
String selectedNote = (String)foundNotes.getValueAt(foundNotes.getSelectedRow(),0);
noteName.setText(selectedNote);
}
// now set the content to reflect the selection as well
setNoteContent(noteContent, notes, foundNotes);
}
});
foundNotes.addKeyListener(new KeyAdapter(){
// this is from http://stackoverflow.com/a/5043957's 'Use a keylistener' solution
public void keyPressed(KeyEvent e){
if (e.getKeyCode() == KeyEvent.VK_TAB && e.isShiftDown()){
e.consume();
KeyboardFocusManager.getCurrentKeyboardFocusManager().focusPreviousComponent();
noteName.selectAll();
}
}
});
noteContent.addKeyListener(new KeyAdapter(){
// this is from http://stackoverflow.com/a/5043957's 'Use a keylistener' solution
public void keyPressed(KeyEvent e){
if (e.getKeyCode() == KeyEvent.VK_TAB && e.isShiftDown()){
e.consume();
// fix for issue #6
saveIncremental(noteContent,noteName,notes);
KeyboardFocusManager.getCurrentKeyboardFocusManager().focusPreviousComponent();
noteName.selectAll();
}
}
});
noteContent.getDocument().addDocumentListener(new DocumentListener(){
public void insertUpdate(DocumentEvent e) {
saveIfRequired(e);
}
public void removeUpdate(DocumentEvent e) {
saveIfRequired(e);
}
public void changedUpdate(DocumentEvent e) {
//Plain text components do not fire these events
}
//TODO: do both saveIfRequired()s need to be synchronized?
private synchronized void saveIfRequired(DocumentEvent e){
if(DOC_MOD_EVENT_COUNT == EVENT_COUNT_TO_SAVE_AT){
saveIncremental(noteContent,noteName,notes);
DOC_MOD_EVENT_COUNT = 0;
}
else{
DOC_MOD_EVENT_COUNT++;
}
}
});
window.addWindowListener( new WindowAdapter(){
public void windowClosing(WindowEvent e){
saveIncremental(noteContent,noteName,notes);
}
}
);
}
|
diff --git a/src/org/exist/backup/Restore.java b/src/org/exist/backup/Restore.java
index 56c8af7..d146cdf 100644
--- a/src/org/exist/backup/Restore.java
+++ b/src/org/exist/backup/Restore.java
@@ -1,471 +1,471 @@
package org.exist.backup;
import org.exist.Namespaces;
import org.exist.dom.DocumentTypeImpl;
import org.exist.security.SecurityManager;
import org.exist.security.User;
import org.exist.storage.DBBroker;
import org.exist.util.EXistInputSource;
import org.exist.xmldb.CollectionImpl;
import org.exist.xmldb.CollectionManagementServiceImpl;
import org.exist.xmldb.EXistResource;
import org.exist.xmldb.UserManagementService;
import org.exist.xmldb.XmldbURI;
import org.exist.xquery.XPathException;
import org.exist.xquery.util.URIUtils;
import org.exist.xquery.value.DateTimeValue;
import org.w3c.dom.DocumentType;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xmldb.api.DatabaseManager;
import org.xmldb.api.modules.CollectionManagementService;
import org.xmldb.api.base.Collection;
import org.xmldb.api.base.Resource;
import org.xmldb.api.base.XMLDBException;
import javax.swing.*;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Date;
import java.util.Observable;
import java.util.Stack;
import java.util.Properties;
/**
* Restore.java
*
* @author Wolfgang Meier
*/
public class Restore extends DefaultHandler {
private BackupDescriptor contents;
private String uri;
private String username;
private String pass;
private XMLReader reader;
private CollectionImpl current;
private Stack stack = new Stack();
private RestoreDialog dialog = null;
private int version=0;
private RestoreListener listener;
private static final int strictUriVersion = 1;
/**
* Constructor for Restore.
* @throws XMLDBException
* @throws URISyntaxException
*/
public Restore(String user, String pass, String newAdminPass, File contents, String uri)
throws ParserConfigurationException, SAXException, XMLDBException, URISyntaxException {
this.username = user;
this.pass = pass;
this.uri = uri;
this.listener = new DefaultListener();
if (newAdminPass != null)
setAdminCredentials(newAdminPass);
SAXParserFactory saxFactory = SAXParserFactory.newInstance();
saxFactory.setNamespaceAware(true);
saxFactory.setValidating(false);
SAXParser sax = saxFactory.newSAXParser();
reader = sax.getXMLReader();
reader.setContentHandler(this);
do {
BackupDescriptor bd=null;
Properties properties = null;
try {
if(contents.isDirectory()) {
bd=new FileSystemBackupDescriptor(new File(contents,BackupDescriptor.COLLECTION_DESCRIPTOR));
} else if(contents.getName().endsWith(".zip") || contents.getName().endsWith(".ZIP")) {
bd=new ZipArchiveBackupDescriptor(contents);
} else {
bd=new FileSystemBackupDescriptor(contents);
}
properties = bd.getProperties();
} catch(Exception e) {
e.printStackTrace();
throw new SAXException("Unable to create backup descriptor object from "+contents,e);
}
stack.push(bd);
// check if the system collection is in the backup. We have to process
// this first to create users.
//TODO : find a way to make a corespondance with DBRoker's named constants
BackupDescriptor sysbd=bd.getChildBackupDescriptor("system");
if (sysbd!=null) {
stack.push(sysbd);
}
contents = null;
if (properties != null && properties.getProperty("incremental", "no").equals("yes")) {
String previous = properties.getProperty("previous", "");
if (previous.length() > 0) {
contents = new File(bd.getParentDir(), previous);
if (!contents.canRead())
throw new SAXException("Required part of incremental backup not found: " + contents.getAbsolutePath());
}
}
} while (contents != null);
}
public void setListener(RestoreListener listener) {
this.listener = listener;
}
public void restore(boolean showGUI, JFrame parent)
throws XMLDBException, FileNotFoundException, IOException, SAXException {
if (showGUI) {
dialog = new RestoreDialog(parent, "Restoring data ...", false);
dialog.setVisible(true);
Thread restoreThread = new Thread() {
public void run() {
while (!stack.isEmpty()) {
try {
contents = (BackupDescriptor) stack.pop();
dialog.setBackup(contents.getSymbolicPath());
reader.parse(contents.getInputSource());
} catch (FileNotFoundException e) {
dialog.displayMessage(e.getMessage());
} catch (IOException e) {
dialog.displayMessage(e.getMessage());
} catch (SAXException e) {
dialog.displayMessage(e.getMessage());
}
}
dialog.setVisible(false);
}
};
restoreThread.start();
if(parent == null) {
while (restoreThread.isAlive()) {
synchronized (this) {
try {
wait(20);
} catch (InterruptedException e) {
}
}
}
}
} else {
while(!stack.isEmpty()) {
contents = (BackupDescriptor) stack.pop();
EXistInputSource is = contents.getInputSource();
is.setEncoding("UTF-8");
//restoring sysId
reader.parse(is);
}
}
}
/**
* @see org.xml.sax.ContentHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes)
*/
public void startElement(String namespaceURI, String localName, String qName, Attributes atts)
throws SAXException {
if (namespaceURI.equals(Namespaces.EXIST_NS)) {
if (localName.equals("collection")) {
final String name = atts.getValue("name");
final String owner = atts.getValue("owner");
final String group = atts.getValue("group");
final String mode = atts.getValue("mode");
final String created = atts.getValue("created");
String strVersion = atts.getValue("version");
if(strVersion!=null) {
try {
this.version = Integer.parseInt(strVersion);
} catch (NumberFormatException e) {
this.version=0;
}
}
if (name == null)
throw new SAXException("collection requires a name " + "attribute");
try {
listener.createCollection(name);
XmldbURI collUri;
if(version >= strictUriVersion) {
collUri = XmldbURI.create(name);
} else {
try {
collUri = URIUtils.encodeXmldbUriFor(name);
} catch (URISyntaxException e) {
listener.warn("Could not parse document name into a URI: "+e.getMessage());
return;
}
}
Date date_created = null;
if (created != null)
try {
date_created = new DateTimeValue(created).getDate();
} catch (XPathException e2) {
}
current = mkcol(collUri, date_created);
if (current == null)
throw new SAXException("Collection not found: " + collUri);
UserManagementService service =
(UserManagementService) current.getService("UserManagementService", "1.0");
User u = new User(owner, null, group);
service.chown(u, group);
service.chmod(Integer.parseInt(mode, 8));
} catch (Exception e) {
listener.warn("An unrecoverable error occurred while restoring\ncollection '" + name + "'. " +
"Aborting restore!");
e.printStackTrace();
throw new SAXException(e.getMessage(), e);
}
if(dialog != null)
dialog.setCollection(name);
} else if (localName.equals("subcollection")) {
String name = atts.getValue("filename");
if (name == null) {
name = atts.getValue("name");
}
BackupDescriptor subbd = contents.getChildBackupDescriptor(name);
if (subbd!=null)
stack.push(subbd);
else
listener.warn(name + " does not exist or is not readable.");
} else if (localName.equals("resource")) {
String skip = atts.getValue("skip");
if (skip == null || skip.equals("no")) {
String type = atts.getValue("type");
if(type == null)
type ="XMLResource";
final String name = atts.getValue("name");
final String owner = atts.getValue("owner");
final String group = atts.getValue("group");
final String perms = atts.getValue("mode");
String filename = atts.getValue("filename");
final String mimetype = atts.getValue("mimetype");
final String created = atts.getValue("created");
final String modified = atts.getValue("modified");
final String publicid = atts.getValue("publicid");
final String systemid = atts.getValue("systemid");
final String namedoctype = atts.getValue("namedoctype");
if (filename == null) filename = name;
if (name == null) {
listener.warn("Wrong entry in backup descriptor: resource requires a name attribute.");
}
XmldbURI docUri;
if(version >= strictUriVersion) {
docUri = XmldbURI.create(name);
} else {
try {
docUri = URIUtils.encodeXmldbUriFor(name);
} catch (URISyntaxException e) {
listener.warn("Could not parse document name into a URI: "+e.getMessage());
return;
}
}
try {
if (dialog != null && current instanceof Observable) {
((Observable) current).addObserver(dialog.getObserver());
}
if(dialog != null)
dialog.setResource(name);
final Resource res =
current.createResource(docUri.toString(), type);
if (mimetype != null)
((EXistResource)res).setMimeType(mimetype);
res.setContent(contents.getContent(filename));
// Restoring name
Date date_created = null;
Date date_modified = null;
if (created != null)
try {
date_created = (new DateTimeValue(created)).getDate();
} catch (XPathException e2) {
listener.warn("Illegal creation date. Skipping ...");
}
if (modified != null)
try {
date_modified = (new DateTimeValue(modified)).getDate();
} catch (XPathException e2) {
listener.warn("Illegal modification date. Skipping ...");
}
current.storeResource(res, date_created, date_modified);
if (publicid != null || systemid != null )
{
DocumentType doctype = new DocumentTypeImpl(namedoctype,publicid,systemid );
try {
((EXistResource)res).setDocType(doctype);
} catch (XMLDBException e1) {
e1.printStackTrace();
}
}
UserManagementService service =
(UserManagementService) current.getService("UserManagementService", "1.0");
User u = new User(owner, null, group);
try {
service.chown(res, u, group);
} catch (XMLDBException e1) {
listener.warn("Failed to change owner on document '" + name + "'; skipping ...");
}
service.chmod(res, Integer.parseInt(perms, 8));
listener.restored(name);
} catch (Exception e) {
listener.warn("Failed to restore resource '" + name + "'\nfrom file '" +
contents.getSymbolicPath(name,false) + "'.\nReason: " + e.getMessage());
e.printStackTrace();
- throw new RuntimeException(e);
+// throw new RuntimeException(e);
}
}
} else if (localName.equals("deleted")) {
final String name = atts.getValue("name");
final String type = atts.getValue("type");
if (type.equals("collection")) {
try {
Collection child = current.getChildCollection(name);
if (child != null) {
CollectionManagementService cmgt = (CollectionManagementService)
current.getService("CollectionManagementService", "1.0");
cmgt.removeCollection(name);
}
} catch (XMLDBException e) {
listener.warn("Failed to remove deleted collection: " + name + ": " + e.getMessage());
}
} else if (type.equals("resource")) {
try {
Resource resource = current.getResource(name);
if (resource != null)
current.removeResource(resource);
} catch (XMLDBException e) {
listener.warn("Failed to remove deleted resource: " + name + ": " +
e.getMessage());
}
}
}
}
}
private final CollectionImpl mkcol(XmldbURI collPath, Date created) throws XMLDBException, URISyntaxException {
XmldbURI[] segments = collPath.getPathSegments();
CollectionManagementServiceImpl mgtService;
Collection c;
XmldbURI dbUri;
if (!uri.endsWith(DBBroker.ROOT_COLLECTION))
dbUri = XmldbURI.xmldbUriFor(uri + DBBroker.ROOT_COLLECTION);
else
dbUri = XmldbURI.xmldbUriFor(uri);
Collection current = DatabaseManager.getCollection(dbUri.toString(), username, pass);
XmldbURI p = XmldbURI.ROOT_COLLECTION_URI;
for(int i=1;i<segments.length;i++) {
p = p.append(segments[i]);
XmldbURI xmldbURI = dbUri.resolveCollectionPath(p);
c = DatabaseManager.getCollection(xmldbURI.toString(), username, pass);
if (c == null) {
mgtService =
(CollectionManagementServiceImpl) current.getService(
"CollectionManagementService",
"1.0");
//current = mgtService.createCollection(token);
current = mgtService.createCollection(segments[i], created);
} else
current = c;
}
return (CollectionImpl)current;
}
private void setAdminCredentials(String adminPassword) throws XMLDBException, URISyntaxException {
XmldbURI dbUri;
if (!uri.endsWith(DBBroker.ROOT_COLLECTION))
dbUri = XmldbURI.xmldbUriFor(uri + DBBroker.ROOT_COLLECTION);
else
dbUri = XmldbURI.xmldbUriFor(uri);
Collection root = DatabaseManager.getCollection(dbUri.toString(), username, pass);
UserManagementService mgmt = (UserManagementService)
root.getService("UserManagementService", "1.0");
User dba = mgmt.getUser(SecurityManager.DBA_USER);
dba.setPassword(adminPassword);
mgmt.updateUser(dba);
pass = adminPassword;
}
public static void showErrorMessage(String message) {
JTextArea msgArea = new JTextArea(message);
msgArea.setEditable(false);
msgArea.setBackground(null);
JScrollPane scroll = new JScrollPane(msgArea);
JOptionPane optionPane = new JOptionPane();
optionPane.setMessage(new Object[]{scroll});
optionPane.setMessageType(JOptionPane.ERROR_MESSAGE);
JDialog dialog = optionPane.createDialog(null, "Error");
dialog.setResizable(true);
dialog.pack();
dialog.setVisible(true);
return;
}
public interface RestoreListener {
void createCollection(String collection);
void restored(String resource);
void info(String message);
void warn(String message);
}
private class DefaultListener implements RestoreListener {
public void createCollection(String collection) {
info("creating collection " + collection);
}
public void restored(String resource) {
info("restored " + resource);
}
public void info(String message) {
if (dialog != null)
dialog.displayMessage(message);
else
System.err.println(message);
}
public void warn(String message) {
if (dialog != null)
dialog.displayMessage(message);
else
System.err.println(message);
}
}
}
| true | true | public void startElement(String namespaceURI, String localName, String qName, Attributes atts)
throws SAXException {
if (namespaceURI.equals(Namespaces.EXIST_NS)) {
if (localName.equals("collection")) {
final String name = atts.getValue("name");
final String owner = atts.getValue("owner");
final String group = atts.getValue("group");
final String mode = atts.getValue("mode");
final String created = atts.getValue("created");
String strVersion = atts.getValue("version");
if(strVersion!=null) {
try {
this.version = Integer.parseInt(strVersion);
} catch (NumberFormatException e) {
this.version=0;
}
}
if (name == null)
throw new SAXException("collection requires a name " + "attribute");
try {
listener.createCollection(name);
XmldbURI collUri;
if(version >= strictUriVersion) {
collUri = XmldbURI.create(name);
} else {
try {
collUri = URIUtils.encodeXmldbUriFor(name);
} catch (URISyntaxException e) {
listener.warn("Could not parse document name into a URI: "+e.getMessage());
return;
}
}
Date date_created = null;
if (created != null)
try {
date_created = new DateTimeValue(created).getDate();
} catch (XPathException e2) {
}
current = mkcol(collUri, date_created);
if (current == null)
throw new SAXException("Collection not found: " + collUri);
UserManagementService service =
(UserManagementService) current.getService("UserManagementService", "1.0");
User u = new User(owner, null, group);
service.chown(u, group);
service.chmod(Integer.parseInt(mode, 8));
} catch (Exception e) {
listener.warn("An unrecoverable error occurred while restoring\ncollection '" + name + "'. " +
"Aborting restore!");
e.printStackTrace();
throw new SAXException(e.getMessage(), e);
}
if(dialog != null)
dialog.setCollection(name);
} else if (localName.equals("subcollection")) {
String name = atts.getValue("filename");
if (name == null) {
name = atts.getValue("name");
}
BackupDescriptor subbd = contents.getChildBackupDescriptor(name);
if (subbd!=null)
stack.push(subbd);
else
listener.warn(name + " does not exist or is not readable.");
} else if (localName.equals("resource")) {
String skip = atts.getValue("skip");
if (skip == null || skip.equals("no")) {
String type = atts.getValue("type");
if(type == null)
type ="XMLResource";
final String name = atts.getValue("name");
final String owner = atts.getValue("owner");
final String group = atts.getValue("group");
final String perms = atts.getValue("mode");
String filename = atts.getValue("filename");
final String mimetype = atts.getValue("mimetype");
final String created = atts.getValue("created");
final String modified = atts.getValue("modified");
final String publicid = atts.getValue("publicid");
final String systemid = atts.getValue("systemid");
final String namedoctype = atts.getValue("namedoctype");
if (filename == null) filename = name;
if (name == null) {
listener.warn("Wrong entry in backup descriptor: resource requires a name attribute.");
}
XmldbURI docUri;
if(version >= strictUriVersion) {
docUri = XmldbURI.create(name);
} else {
try {
docUri = URIUtils.encodeXmldbUriFor(name);
} catch (URISyntaxException e) {
listener.warn("Could not parse document name into a URI: "+e.getMessage());
return;
}
}
try {
if (dialog != null && current instanceof Observable) {
((Observable) current).addObserver(dialog.getObserver());
}
if(dialog != null)
dialog.setResource(name);
final Resource res =
current.createResource(docUri.toString(), type);
if (mimetype != null)
((EXistResource)res).setMimeType(mimetype);
res.setContent(contents.getContent(filename));
// Restoring name
Date date_created = null;
Date date_modified = null;
if (created != null)
try {
date_created = (new DateTimeValue(created)).getDate();
} catch (XPathException e2) {
listener.warn("Illegal creation date. Skipping ...");
}
if (modified != null)
try {
date_modified = (new DateTimeValue(modified)).getDate();
} catch (XPathException e2) {
listener.warn("Illegal modification date. Skipping ...");
}
current.storeResource(res, date_created, date_modified);
if (publicid != null || systemid != null )
{
DocumentType doctype = new DocumentTypeImpl(namedoctype,publicid,systemid );
try {
((EXistResource)res).setDocType(doctype);
} catch (XMLDBException e1) {
e1.printStackTrace();
}
}
UserManagementService service =
(UserManagementService) current.getService("UserManagementService", "1.0");
User u = new User(owner, null, group);
try {
service.chown(res, u, group);
} catch (XMLDBException e1) {
listener.warn("Failed to change owner on document '" + name + "'; skipping ...");
}
service.chmod(res, Integer.parseInt(perms, 8));
listener.restored(name);
} catch (Exception e) {
listener.warn("Failed to restore resource '" + name + "'\nfrom file '" +
contents.getSymbolicPath(name,false) + "'.\nReason: " + e.getMessage());
e.printStackTrace();
throw new RuntimeException(e);
}
}
} else if (localName.equals("deleted")) {
final String name = atts.getValue("name");
final String type = atts.getValue("type");
if (type.equals("collection")) {
try {
Collection child = current.getChildCollection(name);
if (child != null) {
CollectionManagementService cmgt = (CollectionManagementService)
current.getService("CollectionManagementService", "1.0");
cmgt.removeCollection(name);
}
} catch (XMLDBException e) {
listener.warn("Failed to remove deleted collection: " + name + ": " + e.getMessage());
}
} else if (type.equals("resource")) {
try {
Resource resource = current.getResource(name);
if (resource != null)
current.removeResource(resource);
} catch (XMLDBException e) {
listener.warn("Failed to remove deleted resource: " + name + ": " +
e.getMessage());
}
}
}
}
}
| public void startElement(String namespaceURI, String localName, String qName, Attributes atts)
throws SAXException {
if (namespaceURI.equals(Namespaces.EXIST_NS)) {
if (localName.equals("collection")) {
final String name = atts.getValue("name");
final String owner = atts.getValue("owner");
final String group = atts.getValue("group");
final String mode = atts.getValue("mode");
final String created = atts.getValue("created");
String strVersion = atts.getValue("version");
if(strVersion!=null) {
try {
this.version = Integer.parseInt(strVersion);
} catch (NumberFormatException e) {
this.version=0;
}
}
if (name == null)
throw new SAXException("collection requires a name " + "attribute");
try {
listener.createCollection(name);
XmldbURI collUri;
if(version >= strictUriVersion) {
collUri = XmldbURI.create(name);
} else {
try {
collUri = URIUtils.encodeXmldbUriFor(name);
} catch (URISyntaxException e) {
listener.warn("Could not parse document name into a URI: "+e.getMessage());
return;
}
}
Date date_created = null;
if (created != null)
try {
date_created = new DateTimeValue(created).getDate();
} catch (XPathException e2) {
}
current = mkcol(collUri, date_created);
if (current == null)
throw new SAXException("Collection not found: " + collUri);
UserManagementService service =
(UserManagementService) current.getService("UserManagementService", "1.0");
User u = new User(owner, null, group);
service.chown(u, group);
service.chmod(Integer.parseInt(mode, 8));
} catch (Exception e) {
listener.warn("An unrecoverable error occurred while restoring\ncollection '" + name + "'. " +
"Aborting restore!");
e.printStackTrace();
throw new SAXException(e.getMessage(), e);
}
if(dialog != null)
dialog.setCollection(name);
} else if (localName.equals("subcollection")) {
String name = atts.getValue("filename");
if (name == null) {
name = atts.getValue("name");
}
BackupDescriptor subbd = contents.getChildBackupDescriptor(name);
if (subbd!=null)
stack.push(subbd);
else
listener.warn(name + " does not exist or is not readable.");
} else if (localName.equals("resource")) {
String skip = atts.getValue("skip");
if (skip == null || skip.equals("no")) {
String type = atts.getValue("type");
if(type == null)
type ="XMLResource";
final String name = atts.getValue("name");
final String owner = atts.getValue("owner");
final String group = atts.getValue("group");
final String perms = atts.getValue("mode");
String filename = atts.getValue("filename");
final String mimetype = atts.getValue("mimetype");
final String created = atts.getValue("created");
final String modified = atts.getValue("modified");
final String publicid = atts.getValue("publicid");
final String systemid = atts.getValue("systemid");
final String namedoctype = atts.getValue("namedoctype");
if (filename == null) filename = name;
if (name == null) {
listener.warn("Wrong entry in backup descriptor: resource requires a name attribute.");
}
XmldbURI docUri;
if(version >= strictUriVersion) {
docUri = XmldbURI.create(name);
} else {
try {
docUri = URIUtils.encodeXmldbUriFor(name);
} catch (URISyntaxException e) {
listener.warn("Could not parse document name into a URI: "+e.getMessage());
return;
}
}
try {
if (dialog != null && current instanceof Observable) {
((Observable) current).addObserver(dialog.getObserver());
}
if(dialog != null)
dialog.setResource(name);
final Resource res =
current.createResource(docUri.toString(), type);
if (mimetype != null)
((EXistResource)res).setMimeType(mimetype);
res.setContent(contents.getContent(filename));
// Restoring name
Date date_created = null;
Date date_modified = null;
if (created != null)
try {
date_created = (new DateTimeValue(created)).getDate();
} catch (XPathException e2) {
listener.warn("Illegal creation date. Skipping ...");
}
if (modified != null)
try {
date_modified = (new DateTimeValue(modified)).getDate();
} catch (XPathException e2) {
listener.warn("Illegal modification date. Skipping ...");
}
current.storeResource(res, date_created, date_modified);
if (publicid != null || systemid != null )
{
DocumentType doctype = new DocumentTypeImpl(namedoctype,publicid,systemid );
try {
((EXistResource)res).setDocType(doctype);
} catch (XMLDBException e1) {
e1.printStackTrace();
}
}
UserManagementService service =
(UserManagementService) current.getService("UserManagementService", "1.0");
User u = new User(owner, null, group);
try {
service.chown(res, u, group);
} catch (XMLDBException e1) {
listener.warn("Failed to change owner on document '" + name + "'; skipping ...");
}
service.chmod(res, Integer.parseInt(perms, 8));
listener.restored(name);
} catch (Exception e) {
listener.warn("Failed to restore resource '" + name + "'\nfrom file '" +
contents.getSymbolicPath(name,false) + "'.\nReason: " + e.getMessage());
e.printStackTrace();
// throw new RuntimeException(e);
}
}
} else if (localName.equals("deleted")) {
final String name = atts.getValue("name");
final String type = atts.getValue("type");
if (type.equals("collection")) {
try {
Collection child = current.getChildCollection(name);
if (child != null) {
CollectionManagementService cmgt = (CollectionManagementService)
current.getService("CollectionManagementService", "1.0");
cmgt.removeCollection(name);
}
} catch (XMLDBException e) {
listener.warn("Failed to remove deleted collection: " + name + ": " + e.getMessage());
}
} else if (type.equals("resource")) {
try {
Resource resource = current.getResource(name);
if (resource != null)
current.removeResource(resource);
} catch (XMLDBException e) {
listener.warn("Failed to remove deleted resource: " + name + ": " +
e.getMessage());
}
}
}
}
}
|
diff --git a/org.emftext.sdk.codegen.resource/src/org/emftext/sdk/codegen/resource/generators/util/ResourceUtilGenerator.java b/org.emftext.sdk.codegen.resource/src/org/emftext/sdk/codegen/resource/generators/util/ResourceUtilGenerator.java
index 2affe554d..bd5b18ea8 100644
--- a/org.emftext.sdk.codegen.resource/src/org/emftext/sdk/codegen/resource/generators/util/ResourceUtilGenerator.java
+++ b/org.emftext.sdk.codegen.resource/src/org/emftext/sdk/codegen/resource/generators/util/ResourceUtilGenerator.java
@@ -1,140 +1,140 @@
/*******************************************************************************
* Copyright (c) 2006-2010
* Software Technology Group, Dresden University of Technology
*
* 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:
* Software Technology Group - TU Dresden, Germany
* - initial API and implementation
******************************************************************************/
package org.emftext.sdk.codegen.resource.generators.util;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.ARRAY_LIST;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.COLLECTIONS;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.ECORE_UTIL;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.E_OBJECT;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.FILE;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.FILE_OUTPUT_STREAM;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.INTERNAL_E_OBJECT;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.IO_EXCEPTION;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.ITERATOR;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.LIST;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.MAP;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.OUTPUT_STREAM;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.RESOURCE;
import org.emftext.sdk.codegen.composites.JavaComposite;
import org.emftext.sdk.codegen.parameters.ArtifactParameter;
import org.emftext.sdk.codegen.resource.GenerationContext;
import org.emftext.sdk.codegen.resource.generators.JavaBaseGenerator;
public class ResourceUtilGenerator extends JavaBaseGenerator<ArtifactParameter<GenerationContext>> {
public void generateJavaContents(JavaComposite sc) {
sc.add("package " + getResourcePackageName() + ";");
sc.addLineBreak();
sc.addJavadoc(
"Class ResourceUtil can be used to perform common tasks on resources, " +
"such as resolving proxy object, saving resources, as well as, checking " +
"them for errors."
);
sc.add("public class " + getResourceClassName() + " {");
sc.addLineBreak();
addMethods(sc);
sc.add("}");
}
private void addMethods(JavaComposite sc) {
addFindUnresolvedProxiesMethod(sc);
addResolveAllMethod(sc);
addSaveResourceMethod(sc);
addContainsErrorsMethod(sc);
addContainsWarningsMethod(sc);
addContainsProblemsMethod(sc);
}
private void addFindUnresolvedProxiesMethod(JavaComposite sc) {
sc.addJavadoc(
"Searches for all unresolved proxy object in the given resource.",
"@param resource",
"@return all proxy object that are not resolvable"
);
sc.add("public static " + LIST + "<" + E_OBJECT + "> findUnresolvedProxies(" + RESOURCE + " resource) {");
- sc.add(LIST + "<" + E_OBJECT + "> unresolveProxies = new " + ARRAY_LIST + "<" + E_OBJECT + ">();");
+ sc.add(LIST + "<" + E_OBJECT + "> unresolvedProxies = new " + ARRAY_LIST + "<" + E_OBJECT + ">();");
sc.addLineBreak();
sc.add("for(" + ITERATOR + "<" + E_OBJECT + "> elementIt = " + ECORE_UTIL + ".getAllContents(resource, true); elementIt.hasNext(); ) {");
sc.add(INTERNAL_E_OBJECT + " nextElement = (" + INTERNAL_E_OBJECT + ") elementIt.next();");
sc.add("if (nextElement.eIsProxy()) {");
- sc.add("unresolveProxies.add(nextElement);");
+ sc.add("unresolvedProxies.add(nextElement);");
sc.add("}");
sc.add("for (" + E_OBJECT + " crElement : nextElement.eCrossReferences()) {");
sc.add("crElement = " + ECORE_UTIL + ".resolve(crElement, resource);");
sc.add("if (crElement.eIsProxy()) {");
- sc.add("unresolveProxies.add(nextElement);");
+ sc.add("unresolvedProxies.add(crElement);");
sc.add("}");
sc.add("}");
sc.add("}");
- sc.add("return unresolveProxies;");
+ sc.add("return unresolvedProxies;");
sc.add("}");
sc.addLineBreak();
}
private void addResolveAllMethod(JavaComposite sc) {
sc.addJavadoc(
"Tries to resolve all unresolved proxy objects in the " +
"given resource. If all proxies were resolved true is " +
"returned. If some could not be resolved, false is " +
"returned.",
"@param resource the resource containing the proxy object",
"@return true on success"
);
sc.add("public static boolean resolveAll(" + RESOURCE + " resource) {");
sc.add(ECORE_UTIL + ".resolveAll(resource);");
sc.add("if (findUnresolvedProxies(resource).size() > 0) {");
sc.add("return false;");
sc.add("} else {");
sc.add("return true;");
sc.add("}");
sc.add("}");
sc.addLineBreak();
}
private void addSaveResourceMethod(JavaComposite sc) {
sc.add("public static void saveResource(" + FILE + " file, " + RESOURCE + " resource) throws " + IO_EXCEPTION + " {");
sc.add(MAP + "<?, ?> options = " + COLLECTIONS + ".EMPTY_MAP;");
sc.add(OUTPUT_STREAM + " outputStream = new " + FILE_OUTPUT_STREAM + "(file);");
sc.add("resource.save(outputStream, options);");
sc.add("outputStream.close();");
sc.add("}");
sc.addLineBreak();
}
private void addContainsErrorsMethod(JavaComposite sc) {
sc.add("public static boolean containsErrors(" + RESOURCE + " resource) {");
sc.add("return !resource.getErrors().isEmpty();");
sc.add("}");
sc.addLineBreak();
}
private void addContainsWarningsMethod(JavaComposite sc) {
sc.add("public static boolean containsWarnings(" + RESOURCE + " resource) {");
sc.add("return !resource.getWarnings().isEmpty();");
sc.add("}");
sc.addLineBreak();
}
private void addContainsProblemsMethod(JavaComposite sc) {
sc.add("public static boolean containsProblems(" + RESOURCE + " resource) {");
sc.add("return containsErrors(resource) || containsWarnings(resource);");
sc.add("}");
sc.addLineBreak();
}
}
| false | true | private void addFindUnresolvedProxiesMethod(JavaComposite sc) {
sc.addJavadoc(
"Searches for all unresolved proxy object in the given resource.",
"@param resource",
"@return all proxy object that are not resolvable"
);
sc.add("public static " + LIST + "<" + E_OBJECT + "> findUnresolvedProxies(" + RESOURCE + " resource) {");
sc.add(LIST + "<" + E_OBJECT + "> unresolveProxies = new " + ARRAY_LIST + "<" + E_OBJECT + ">();");
sc.addLineBreak();
sc.add("for(" + ITERATOR + "<" + E_OBJECT + "> elementIt = " + ECORE_UTIL + ".getAllContents(resource, true); elementIt.hasNext(); ) {");
sc.add(INTERNAL_E_OBJECT + " nextElement = (" + INTERNAL_E_OBJECT + ") elementIt.next();");
sc.add("if (nextElement.eIsProxy()) {");
sc.add("unresolveProxies.add(nextElement);");
sc.add("}");
sc.add("for (" + E_OBJECT + " crElement : nextElement.eCrossReferences()) {");
sc.add("crElement = " + ECORE_UTIL + ".resolve(crElement, resource);");
sc.add("if (crElement.eIsProxy()) {");
sc.add("unresolveProxies.add(nextElement);");
sc.add("}");
sc.add("}");
sc.add("}");
sc.add("return unresolveProxies;");
sc.add("}");
sc.addLineBreak();
}
| private void addFindUnresolvedProxiesMethod(JavaComposite sc) {
sc.addJavadoc(
"Searches for all unresolved proxy object in the given resource.",
"@param resource",
"@return all proxy object that are not resolvable"
);
sc.add("public static " + LIST + "<" + E_OBJECT + "> findUnresolvedProxies(" + RESOURCE + " resource) {");
sc.add(LIST + "<" + E_OBJECT + "> unresolvedProxies = new " + ARRAY_LIST + "<" + E_OBJECT + ">();");
sc.addLineBreak();
sc.add("for(" + ITERATOR + "<" + E_OBJECT + "> elementIt = " + ECORE_UTIL + ".getAllContents(resource, true); elementIt.hasNext(); ) {");
sc.add(INTERNAL_E_OBJECT + " nextElement = (" + INTERNAL_E_OBJECT + ") elementIt.next();");
sc.add("if (nextElement.eIsProxy()) {");
sc.add("unresolvedProxies.add(nextElement);");
sc.add("}");
sc.add("for (" + E_OBJECT + " crElement : nextElement.eCrossReferences()) {");
sc.add("crElement = " + ECORE_UTIL + ".resolve(crElement, resource);");
sc.add("if (crElement.eIsProxy()) {");
sc.add("unresolvedProxies.add(crElement);");
sc.add("}");
sc.add("}");
sc.add("}");
sc.add("return unresolvedProxies;");
sc.add("}");
sc.addLineBreak();
}
|
diff --git a/src/main/java/uk/ac/ebi/fgpt/sampletab/utils/SampleTabUtils.java b/src/main/java/uk/ac/ebi/fgpt/sampletab/utils/SampleTabUtils.java
index fb1364a3..3b4fcca6 100644
--- a/src/main/java/uk/ac/ebi/fgpt/sampletab/utils/SampleTabUtils.java
+++ b/src/main/java/uk/ac/ebi/fgpt/sampletab/utils/SampleTabUtils.java
@@ -1,29 +1,29 @@
package uk.ac.ebi.fgpt.sampletab.utils;
import java.io.File;
public class SampleTabUtils {
public static File submissionDir;
public static String getPathPrefix(String submissionId){
if (submissionId.startsWith("GMS-")) return "imsr";
else if (submissionId.startsWith("GAE-")) return "ae";
- else if (submissionId.startsWith("GRP-")) return "pride";
+ else if (submissionId.startsWith("GPR-")) return "pride";
else if (submissionId.startsWith("GVA-")) return "dgva";
else if (submissionId.startsWith("GCR-")) return "coriell";
else if (submissionId.startsWith("GEN-")) return "sra";
else if (submissionId.equals("GEN")) return "encode";
else if (submissionId.equals("G1K")) return "g1k";
else if (submissionId.startsWith("GHM")) return "hapmap";
else throw new IllegalArgumentException("Unable to get path prefix for "+submissionId);
}
public static File getSubmissionFile(String submissionId){
File subdir = new File(submissionDir, getPathPrefix(submissionId));
File subsubdir = new File(subdir, submissionId);
File sampletabFile = new File(subsubdir, "sampletab.txt");
return sampletabFile;
}
}
| true | true | public static String getPathPrefix(String submissionId){
if (submissionId.startsWith("GMS-")) return "imsr";
else if (submissionId.startsWith("GAE-")) return "ae";
else if (submissionId.startsWith("GRP-")) return "pride";
else if (submissionId.startsWith("GVA-")) return "dgva";
else if (submissionId.startsWith("GCR-")) return "coriell";
else if (submissionId.startsWith("GEN-")) return "sra";
else if (submissionId.equals("GEN")) return "encode";
else if (submissionId.equals("G1K")) return "g1k";
else if (submissionId.startsWith("GHM")) return "hapmap";
else throw new IllegalArgumentException("Unable to get path prefix for "+submissionId);
}
| public static String getPathPrefix(String submissionId){
if (submissionId.startsWith("GMS-")) return "imsr";
else if (submissionId.startsWith("GAE-")) return "ae";
else if (submissionId.startsWith("GPR-")) return "pride";
else if (submissionId.startsWith("GVA-")) return "dgva";
else if (submissionId.startsWith("GCR-")) return "coriell";
else if (submissionId.startsWith("GEN-")) return "sra";
else if (submissionId.equals("GEN")) return "encode";
else if (submissionId.equals("G1K")) return "g1k";
else if (submissionId.startsWith("GHM")) return "hapmap";
else throw new IllegalArgumentException("Unable to get path prefix for "+submissionId);
}
|
diff --git a/src/main/java/br/com/caelum/tubaina/parser/latex/ImageTag.java b/src/main/java/br/com/caelum/tubaina/parser/latex/ImageTag.java
index bd1b116..7df9faf 100644
--- a/src/main/java/br/com/caelum/tubaina/parser/latex/ImageTag.java
+++ b/src/main/java/br/com/caelum/tubaina/parser/latex/ImageTag.java
@@ -1,77 +1,77 @@
package br.com.caelum.tubaina.parser.latex;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.io.FilenameUtils;
import br.com.caelum.tubaina.TubainaBuilder;
import br.com.caelum.tubaina.parser.Tag;
public class ImageTag implements Tag {
public String parse(final String path, final String options) {
- String output = "\\begin{figure}[H]\n\\begin{center}\n";
+ String output = "\n\n\\begin{figure}[H]\n\\begin{center}\n";
output = output + "\\includegraphics";
Pattern label = Pattern.compile("(?s)(?i)label=(\\S+)?");
Matcher labelMatcher = label.matcher(options);
Pattern description = Pattern.compile("(?s)(?i)\"(.+?)\"");
Matcher descriptionMatcher = description.matcher(options);
Pattern horizontalScale = Pattern.compile("(?s)(?i)w=(\\d+)%?");
Matcher horizontalMatcher = horizontalScale.matcher(options);
Pattern actualWidth = Pattern.compile("(?s)(?i)\\[(.+?),(.+?)\\]");
Matcher actualWidthMatcher = actualWidth.matcher(options);
double widthInPixels = Double.MAX_VALUE;
int dpi = 72;
if (actualWidthMatcher.find()) {
widthInPixels = Double.parseDouble(actualWidthMatcher.group(1));
dpi = Integer.parseInt(actualWidthMatcher.group(2));
}
double widthInMilimeters = widthInPixels * 25.4 / dpi;
if (horizontalMatcher.find()) {
output = output + "[width=" + TubainaBuilder.getMaximumWidth() * (Double.parseDouble(horizontalMatcher.group(1)) / 100) + "mm]";
} else if (widthInMilimeters > TubainaBuilder.getMaximumWidth()) {
output = output + "[width=\\textwidth]";
} else {
output = output + "[scale=1]";
}
String imgsrc = FilenameUtils.getName(path);
output = output + "{" + imgsrc + "}\n";
if (descriptionMatcher.find()) {
output = output + "\n\n\\caption{" + descriptionMatcher.group(1) + "}\n\n";
}
if (labelMatcher.find()) {
String givenLabel = labelMatcher.group(1);
output += "\\label{" + (givenLabel != null? givenLabel : imgsrc) + "}\n";
}
output = output + "\\end{center}\\end{figure}\n\n";
return output;
}
public Integer getScale(final String string) {
if (string == null) {
return null;
}
Pattern horizontalScale = Pattern.compile("(?s)(?i)w=(\\d+)%?");
Matcher sMatcher = horizontalScale.matcher(string);
if (sMatcher.find()) {
return Integer.parseInt(sMatcher.group(1));
}
return null;
}
}
| true | true | public String parse(final String path, final String options) {
String output = "\\begin{figure}[H]\n\\begin{center}\n";
output = output + "\\includegraphics";
Pattern label = Pattern.compile("(?s)(?i)label=(\\S+)?");
Matcher labelMatcher = label.matcher(options);
Pattern description = Pattern.compile("(?s)(?i)\"(.+?)\"");
Matcher descriptionMatcher = description.matcher(options);
Pattern horizontalScale = Pattern.compile("(?s)(?i)w=(\\d+)%?");
Matcher horizontalMatcher = horizontalScale.matcher(options);
Pattern actualWidth = Pattern.compile("(?s)(?i)\\[(.+?),(.+?)\\]");
Matcher actualWidthMatcher = actualWidth.matcher(options);
double widthInPixels = Double.MAX_VALUE;
int dpi = 72;
if (actualWidthMatcher.find()) {
widthInPixels = Double.parseDouble(actualWidthMatcher.group(1));
dpi = Integer.parseInt(actualWidthMatcher.group(2));
}
double widthInMilimeters = widthInPixels * 25.4 / dpi;
if (horizontalMatcher.find()) {
output = output + "[width=" + TubainaBuilder.getMaximumWidth() * (Double.parseDouble(horizontalMatcher.group(1)) / 100) + "mm]";
} else if (widthInMilimeters > TubainaBuilder.getMaximumWidth()) {
output = output + "[width=\\textwidth]";
} else {
output = output + "[scale=1]";
}
String imgsrc = FilenameUtils.getName(path);
output = output + "{" + imgsrc + "}\n";
if (descriptionMatcher.find()) {
output = output + "\n\n\\caption{" + descriptionMatcher.group(1) + "}\n\n";
}
if (labelMatcher.find()) {
String givenLabel = labelMatcher.group(1);
output += "\\label{" + (givenLabel != null? givenLabel : imgsrc) + "}\n";
}
output = output + "\\end{center}\\end{figure}\n\n";
return output;
}
| public String parse(final String path, final String options) {
String output = "\n\n\\begin{figure}[H]\n\\begin{center}\n";
output = output + "\\includegraphics";
Pattern label = Pattern.compile("(?s)(?i)label=(\\S+)?");
Matcher labelMatcher = label.matcher(options);
Pattern description = Pattern.compile("(?s)(?i)\"(.+?)\"");
Matcher descriptionMatcher = description.matcher(options);
Pattern horizontalScale = Pattern.compile("(?s)(?i)w=(\\d+)%?");
Matcher horizontalMatcher = horizontalScale.matcher(options);
Pattern actualWidth = Pattern.compile("(?s)(?i)\\[(.+?),(.+?)\\]");
Matcher actualWidthMatcher = actualWidth.matcher(options);
double widthInPixels = Double.MAX_VALUE;
int dpi = 72;
if (actualWidthMatcher.find()) {
widthInPixels = Double.parseDouble(actualWidthMatcher.group(1));
dpi = Integer.parseInt(actualWidthMatcher.group(2));
}
double widthInMilimeters = widthInPixels * 25.4 / dpi;
if (horizontalMatcher.find()) {
output = output + "[width=" + TubainaBuilder.getMaximumWidth() * (Double.parseDouble(horizontalMatcher.group(1)) / 100) + "mm]";
} else if (widthInMilimeters > TubainaBuilder.getMaximumWidth()) {
output = output + "[width=\\textwidth]";
} else {
output = output + "[scale=1]";
}
String imgsrc = FilenameUtils.getName(path);
output = output + "{" + imgsrc + "}\n";
if (descriptionMatcher.find()) {
output = output + "\n\n\\caption{" + descriptionMatcher.group(1) + "}\n\n";
}
if (labelMatcher.find()) {
String givenLabel = labelMatcher.group(1);
output += "\\label{" + (givenLabel != null? givenLabel : imgsrc) + "}\n";
}
output = output + "\\end{center}\\end{figure}\n\n";
return output;
}
|
diff --git a/purge-service-impl/src/main/java/de/escidoc/core/purge/internal/PurgeServiceImpl.java b/purge-service-impl/src/main/java/de/escidoc/core/purge/internal/PurgeServiceImpl.java
index 84b32e4a8..ec2cc0b68 100644
--- a/purge-service-impl/src/main/java/de/escidoc/core/purge/internal/PurgeServiceImpl.java
+++ b/purge-service-impl/src/main/java/de/escidoc/core/purge/internal/PurgeServiceImpl.java
@@ -1,67 +1,67 @@
package de.escidoc.core.purge.internal;
import de.escidoc.core.adm.business.admin.PurgeStatus;
import de.escidoc.core.common.business.fedora.FedoraUtility;
import de.escidoc.core.common.business.fedora.TripleStoreUtility;
import de.escidoc.core.common.exceptions.system.WebserverSystemException;
import de.escidoc.core.common.util.service.BeanLocator;
import de.escidoc.core.common.util.service.UserContext;
import de.escidoc.core.purge.PurgeRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
/**
* Default implementation of {@link de.escidoc.core.purge.PurgeService}.
*
* @author <a href="mailto:[email protected]">Eduard Hildebrandt</a>
*/
public class PurgeServiceImpl implements InitializingBean {
private static final Log LOG = LogFactory.getLog(PurgeServiceImpl.class);
private FedoraUtility fedoraUtility;
public void purge(final PurgeRequest purgeRequest) {
// TODO: Refector this old code.
try {
try {
boolean isInternalUser = UserContext.isInternalUser();
if (!isInternalUser) {
UserContext.setUserContext("");
UserContext.runAsInternalUser();
}
}
catch (final Exception e) {
UserContext.setUserContext("");
UserContext.runAsInternalUser();
}
for (final String componentId : TripleStoreUtility.getInstance()
- .getComponents(purgeRequest.getRequestId())) {
+ .getComponents(purgeRequest.getResourceId())) {
this.fedoraUtility.deleteObject(componentId, false);
}
- this.fedoraUtility.deleteObject(purgeRequest.getRequestId(), false);
+ this.fedoraUtility.deleteObject(purgeRequest.getResourceId(), false);
// synchronize triple store
this.fedoraUtility.sync();
} catch (final Exception e) {
LOG.error("could not dequeue message", e);
} finally {
PurgeStatus.getInstance().dec();
}
}
@Override
public void afterPropertiesSet() throws Exception {
try {
// TODO: Dependency Auflösung mit Spring wird hier umgangen. Spring kann somit rekursive Abhängigkeiten nicht auflösen. BeanLocator muss entfernt werden!
fedoraUtility = (FedoraUtility) BeanLocator.getBean(
BeanLocator.COMMON_FACTORY_ID,
"escidoc.core.business.FedoraUtility");
}
catch (WebserverSystemException e) {
LOG.error("could not localize bean", e);
}
}
}
| false | true | public void purge(final PurgeRequest purgeRequest) {
// TODO: Refector this old code.
try {
try {
boolean isInternalUser = UserContext.isInternalUser();
if (!isInternalUser) {
UserContext.setUserContext("");
UserContext.runAsInternalUser();
}
}
catch (final Exception e) {
UserContext.setUserContext("");
UserContext.runAsInternalUser();
}
for (final String componentId : TripleStoreUtility.getInstance()
.getComponents(purgeRequest.getRequestId())) {
this.fedoraUtility.deleteObject(componentId, false);
}
this.fedoraUtility.deleteObject(purgeRequest.getRequestId(), false);
// synchronize triple store
this.fedoraUtility.sync();
} catch (final Exception e) {
LOG.error("could not dequeue message", e);
} finally {
PurgeStatus.getInstance().dec();
}
}
| public void purge(final PurgeRequest purgeRequest) {
// TODO: Refector this old code.
try {
try {
boolean isInternalUser = UserContext.isInternalUser();
if (!isInternalUser) {
UserContext.setUserContext("");
UserContext.runAsInternalUser();
}
}
catch (final Exception e) {
UserContext.setUserContext("");
UserContext.runAsInternalUser();
}
for (final String componentId : TripleStoreUtility.getInstance()
.getComponents(purgeRequest.getResourceId())) {
this.fedoraUtility.deleteObject(componentId, false);
}
this.fedoraUtility.deleteObject(purgeRequest.getResourceId(), false);
// synchronize triple store
this.fedoraUtility.sync();
} catch (final Exception e) {
LOG.error("could not dequeue message", e);
} finally {
PurgeStatus.getInstance().dec();
}
}
|
diff --git a/uk.ac.gda.epics/src/gda/device/detector/addetector/triggering/SingleExposurePco.java b/uk.ac.gda.epics/src/gda/device/detector/addetector/triggering/SingleExposurePco.java
index b3eb4be8..20c078e7 100644
--- a/uk.ac.gda.epics/src/gda/device/detector/addetector/triggering/SingleExposurePco.java
+++ b/uk.ac.gda.epics/src/gda/device/detector/addetector/triggering/SingleExposurePco.java
@@ -1,61 +1,60 @@
/*-
* Copyright © 2011 Diamond Light Source Ltd.
*
* This file is part of GDA.
*
* GDA is free software: you can redistribute it and/or modify it under the
* terms of the GNU General Public License version 3 as published by the Free
* Software Foundation.
*
* GDA 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 GDA. If not, see <http://www.gnu.org/licenses/>.
*/
package gda.device.detector.addetector.triggering;
import gda.device.detector.areadetector.v17.ADBase;
import gda.device.detector.areadetector.v17.ADDriverPco;
import gda.device.detector.areadetector.v17.ADDriverPco.PcoTriggerMode;
import gda.scan.ScanInformation;
import gda.util.LiveModeUtil;
public class SingleExposurePco extends SingleExposureStandard {
private final ADDriverPco adDriverPco;
public SingleExposurePco(ADBase adBase, ADDriverPco adDriverPco, double readoutTime) {
super(adBase, readoutTime);
this.adDriverPco = adDriverPco;
}
@Override
public void prepareForCollection(double collectionTime, int numImages, ScanInformation scanInfo) throws Exception {
super.prepareForCollection(collectionTime, numImages, scanInfo);
getAdBase().setAcquirePeriod(0.); // for pco always set acq period to 0 to force delay to 0.
if (LiveModeUtil.isLiveMode()) {
adDriverPco.getArmModePV().putWait(true);
- Thread.sleep(2000); //if we do not wait here the first attempt to acquire an image stalls with the IOC in readout mode
}
}
@Override
public void completeCollection() throws Exception {
super.completeCollection();
if (LiveModeUtil.isLiveMode()) {
adDriverPco.getArmModePV().putWait(false);
}
}
@Override
protected void configureTriggerMode() throws Exception {
// Reported Epics bug: changing mode while acquiring causes an IOC crash (28oct2011 RobW)
getAdBase().stopAcquiring();
getAdBase().setTriggerMode(PcoTriggerMode.SOFTWARE.ordinal());
}
}
| true | true | public void prepareForCollection(double collectionTime, int numImages, ScanInformation scanInfo) throws Exception {
super.prepareForCollection(collectionTime, numImages, scanInfo);
getAdBase().setAcquirePeriod(0.); // for pco always set acq period to 0 to force delay to 0.
if (LiveModeUtil.isLiveMode()) {
adDriverPco.getArmModePV().putWait(true);
Thread.sleep(2000); //if we do not wait here the first attempt to acquire an image stalls with the IOC in readout mode
}
}
| public void prepareForCollection(double collectionTime, int numImages, ScanInformation scanInfo) throws Exception {
super.prepareForCollection(collectionTime, numImages, scanInfo);
getAdBase().setAcquirePeriod(0.); // for pco always set acq period to 0 to force delay to 0.
if (LiveModeUtil.isLiveMode()) {
adDriverPco.getArmModePV().putWait(true);
}
}
|
diff --git a/gae/stockyou/StockService/src/com/stockyou/data/QuotesConverter.java b/gae/stockyou/StockService/src/com/stockyou/data/QuotesConverter.java
index 13cd75d..48c1d10 100644
--- a/gae/stockyou/StockService/src/com/stockyou/data/QuotesConverter.java
+++ b/gae/stockyou/StockService/src/com/stockyou/data/QuotesConverter.java
@@ -1,41 +1,41 @@
package com.stockyou.data;
import java.util.ArrayList;
import java.util.List;
import com.stockyou.data.yahoo.YahooPortfolio;
import com.stockyou.data.yahoo.YahooQuote;
public class QuotesConverter {
public Portfolio convert(YahooPortfolio yPortfolio){
Portfolio portfolio = new Portfolio();
- if(yPortfolio != null && yPortfolio.getQuery().getResults().getQuote() != null){
+ if(yPortfolio != null && yPortfolio.getQuery().getResults() != null && yPortfolio.getQuery().getResults().getQuote() != null){
List<Quote> quotes = new ArrayList<Quote>();
for (YahooQuote yQuote : yPortfolio.getQuery().getResults().getQuote()) {
Quote quote = new Quote();
quote.setUnit("Rs");
quote.setFiftyDayAverage(quote.getUnit() + " "+yQuote.getFiftydayMovingAverage());
quote.setTwoHundredDayAverage(quote.getUnit() + " "+yQuote.getTwoHundreddayMovingAverage());
quote.setStockCode(yQuote.getSymbol());
quote.setStockPrice(quote.getUnit() + " "+yQuote.getLastTradePriceOnly());
quote.setName(yQuote.getName());
quote.setUpdatedDt(yQuote.getLastTradeDate() + " - " + yQuote.getLastTradeTime());
quote.setDayValueChange(quote.getUnit() + " "+yQuote.getDaysValueChange());
quote.setDayPercentageChange(yQuote.getPercentChange());
quote.setLogo(getImageFile(yQuote));
quotes.add(quote);
}
portfolio.setQuote(quotes);
}
return portfolio;
}
private String getImageFile(YahooQuote yQuote) {
return "images/"+yQuote.getSymbol().replaceAll("\\.(.)*", "") + ".png";
}
}
| true | true | public Portfolio convert(YahooPortfolio yPortfolio){
Portfolio portfolio = new Portfolio();
if(yPortfolio != null && yPortfolio.getQuery().getResults().getQuote() != null){
List<Quote> quotes = new ArrayList<Quote>();
for (YahooQuote yQuote : yPortfolio.getQuery().getResults().getQuote()) {
Quote quote = new Quote();
quote.setUnit("Rs");
quote.setFiftyDayAverage(quote.getUnit() + " "+yQuote.getFiftydayMovingAverage());
quote.setTwoHundredDayAverage(quote.getUnit() + " "+yQuote.getTwoHundreddayMovingAverage());
quote.setStockCode(yQuote.getSymbol());
quote.setStockPrice(quote.getUnit() + " "+yQuote.getLastTradePriceOnly());
quote.setName(yQuote.getName());
quote.setUpdatedDt(yQuote.getLastTradeDate() + " - " + yQuote.getLastTradeTime());
quote.setDayValueChange(quote.getUnit() + " "+yQuote.getDaysValueChange());
quote.setDayPercentageChange(yQuote.getPercentChange());
quote.setLogo(getImageFile(yQuote));
quotes.add(quote);
}
portfolio.setQuote(quotes);
}
return portfolio;
}
| public Portfolio convert(YahooPortfolio yPortfolio){
Portfolio portfolio = new Portfolio();
if(yPortfolio != null && yPortfolio.getQuery().getResults() != null && yPortfolio.getQuery().getResults().getQuote() != null){
List<Quote> quotes = new ArrayList<Quote>();
for (YahooQuote yQuote : yPortfolio.getQuery().getResults().getQuote()) {
Quote quote = new Quote();
quote.setUnit("Rs");
quote.setFiftyDayAverage(quote.getUnit() + " "+yQuote.getFiftydayMovingAverage());
quote.setTwoHundredDayAverage(quote.getUnit() + " "+yQuote.getTwoHundreddayMovingAverage());
quote.setStockCode(yQuote.getSymbol());
quote.setStockPrice(quote.getUnit() + " "+yQuote.getLastTradePriceOnly());
quote.setName(yQuote.getName());
quote.setUpdatedDt(yQuote.getLastTradeDate() + " - " + yQuote.getLastTradeTime());
quote.setDayValueChange(quote.getUnit() + " "+yQuote.getDaysValueChange());
quote.setDayPercentageChange(yQuote.getPercentChange());
quote.setLogo(getImageFile(yQuote));
quotes.add(quote);
}
portfolio.setQuote(quotes);
}
return portfolio;
}
|
diff --git a/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/storage/jdbc/JDBCWorkspaceDataContainer.java b/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/storage/jdbc/JDBCWorkspaceDataContainer.java
index 9913355c1..187b942ac 100644
--- a/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/storage/jdbc/JDBCWorkspaceDataContainer.java
+++ b/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/storage/jdbc/JDBCWorkspaceDataContainer.java
@@ -1,881 +1,881 @@
/*
* Copyright (C) 2009 eXo Platform SAS.
*
* 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.exoplatform.services.jcr.impl.storage.jdbc;
import org.exoplatform.services.jcr.config.RepositoryConfigurationException;
import org.exoplatform.services.jcr.config.RepositoryEntry;
import org.exoplatform.services.jcr.config.WorkspaceEntry;
import org.exoplatform.services.jcr.impl.storage.WorkspaceDataContainerBase;
import org.exoplatform.services.jcr.impl.storage.jdbc.db.GenericConnectionFactory;
import org.exoplatform.services.jcr.impl.storage.jdbc.db.HSQLDBConnectionFactory;
import org.exoplatform.services.jcr.impl.storage.jdbc.db.MySQLConnectionFactory;
import org.exoplatform.services.jcr.impl.storage.jdbc.db.OracleConnectionFactory;
import org.exoplatform.services.jcr.impl.storage.jdbc.db.WorkspaceStorageConnectionFactory;
import org.exoplatform.services.jcr.impl.storage.jdbc.init.DBInitializer;
import org.exoplatform.services.jcr.impl.storage.jdbc.init.DBInitializerException;
import org.exoplatform.services.jcr.impl.storage.jdbc.init.IngresSQLDBInitializer;
import org.exoplatform.services.jcr.impl.storage.jdbc.init.OracleDBInitializer;
import org.exoplatform.services.jcr.impl.storage.jdbc.init.PgSQLDBInitializer;
import org.exoplatform.services.jcr.impl.storage.jdbc.update.StorageUpdateManager;
import org.exoplatform.services.jcr.impl.util.io.FileCleaner;
import org.exoplatform.services.jcr.storage.WorkspaceDataContainer;
import org.exoplatform.services.jcr.storage.WorkspaceStorageConnection;
import org.exoplatform.services.jcr.storage.value.ValueStoragePluginProvider;
import org.exoplatform.services.log.ExoLogger;
import org.exoplatform.services.log.Log;
import org.exoplatform.services.naming.InitialContextInitializer;
import org.picocontainer.Startable;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.jcr.RepositoryException;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
/**
* Created by The eXo Platform SAS.
*
* @author <a href="mailto:[email protected]">Peter Nedonosko</a>
* @version $Id:GenericWorkspaceDataContainer.java 13433 2007-03-15 16:07:23Z peterit $
*/
public class JDBCWorkspaceDataContainer extends WorkspaceDataContainerBase implements Startable
{
protected static final Log LOG = ExoLogger.getLogger("jcr.JDBCWorkspaceDataContainer");
//configuration params
public final static String SOURCE_NAME = "source-name";
public final static String MULTIDB = "multi-db";
public final static String SINGLEDB = "single-db";
/**
* Describe which type of RDBMS will be used (DB creation metadata etc.)
*/
public final static String DB_DIALECT = "dialect";
public final static String DB_DRIVER = "driverClassName";
public final static String DB_URL = "url";
public final static String DB_USERNAME = "username";
public final static String DB_PASSWORD = "password";
protected final String containerName;
protected final String dbSourceName;
protected final boolean multiDb;
protected final String dbDriver;
protected final String dbDialect;
protected final String dbUrl;
protected final String dbUserName;
protected final String dbPassword;
protected final ValueStoragePluginProvider valueStorageProvider;
protected String storageVersion;
protected int maxBufferSize;
protected File swapDirectory;
protected FileCleaner swapCleaner;
protected GenericConnectionFactory connFactory;
/**
* Shared connection factory.
*
* Issued to share JDBC connection between system and regular workspace in case of same database
* used for storage.
*
*/
class SharedConnectionFactory extends GenericConnectionFactory
{
/**
* JDBC connection.
*/
final private Connection connection;
/**
* SharedConnectionFactory constructor.
*
* @param connection
* JDBC - connection
* @param containerName
* - container name
* @param multiDb
* - multidatabase status
* @param valueStorageProvider
* - external Value Storages provider
* @param maxBufferSize
* - Maximum buffer size (see configuration)
* @param swapDirectory
* - Swap directory (see configuration)
* @param swapCleaner
* - Swap cleaner (internal FileCleaner).
*/
SharedConnectionFactory(Connection connection, String containerName, boolean multiDb,
ValueStoragePluginProvider valueStorageProvider, int maxBufferSize, File swapDirectory, FileCleaner swapCleaner)
{
super(null, null, null, null, null, containerName, multiDb, valueStorageProvider, maxBufferSize,
swapDirectory, swapCleaner);
this.connection = connection;
}
/**
* {@inheritDoc}
*/
public Connection getJdbcConnection() throws RepositoryException
{
return connection;
}
}
/**
* Constructor with value storage plugins.
*
* @param wsConfig
* Workspace configuration
* @param valueStrorageProvider
* External Value Stprages provider
* @throws RepositoryConfigurationException
* if Repository configuration is wrong
* @throws NamingException
* if JNDI exception (on DataSource lookup)
*/
public JDBCWorkspaceDataContainer(WorkspaceEntry wsConfig, RepositoryEntry repConfig,
InitialContextInitializer contextInit, ValueStoragePluginProvider valueStorageProvider)
throws RepositoryConfigurationException, NamingException, RepositoryException, IOException
{
checkIntegrity(wsConfig, repConfig);
this.containerName = wsConfig.getName();
this.multiDb = Boolean.parseBoolean(wsConfig.getContainer().getParameterValue(MULTIDB));
this.valueStorageProvider = valueStorageProvider;
// ------------- Database config ------------------
String pDbDialect = null;
try
{
pDbDialect = validateDialect(wsConfig.getContainer().getParameterValue(DB_DIALECT));
}
catch (RepositoryConfigurationException e)
{
pDbDialect = DBConstants.DB_DIALECT_GENERIC;
}
String pDbDriver = null;
String pDbUrl = null;
String pDbUserName = null;
String pDbPassword = null;
try
{
pDbDriver = wsConfig.getContainer().getParameterValue(DB_DRIVER);
// username/passwd may not pesent
try
{
pDbUserName = wsConfig.getContainer().getParameterValue(DB_USERNAME);
pDbPassword = wsConfig.getContainer().getParameterValue(DB_PASSWORD);
}
catch (RepositoryConfigurationException e)
{
pDbUserName = pDbPassword = null;
}
pDbUrl = wsConfig.getContainer().getParameterValue(DB_URL); // last here!
}
catch (RepositoryConfigurationException e)
{
}
if (pDbUrl != null)
{
this.dbDriver = pDbDriver;
this.dbUrl = pDbUrl;
this.dbUserName = pDbUserName;
this.dbPassword = pDbPassword;
this.dbSourceName = null;
LOG.info("Connect to JCR database as user '" + this.dbUserName + "'");
if (pDbDialect == DBConstants.DB_DIALECT_GENERIC)
{
// try to detect via JDBC metadata
Connection jdbcConn = null;
try
{
jdbcConn =
dbUserName != null ? DriverManager.getConnection(dbUrl, dbUserName, dbPassword) : DriverManager
.getConnection(dbUrl);
this.dbDialect = DialectDetecter.detect(jdbcConn.getMetaData());
}
catch (SQLException e)
{
throw new RepositoryException(e);
}
finally
{
if (jdbcConn != null)
{
try
{
jdbcConn.close();
}
catch (SQLException e)
{
throw new RepositoryException(e);
}
}
}
}
else
{
this.dbDialect = pDbDialect;
}
}
else
{
this.dbDriver = null;
this.dbUrl = null;
this.dbUserName = null;
this.dbPassword = null;
String sn;
try
{
sn = wsConfig.getContainer().getParameterValue(SOURCE_NAME);
}
catch (RepositoryConfigurationException e)
{
sn = wsConfig.getContainer().getParameterValue("sourceName"); // TODO for backward comp,
// remove in rel.2.0
}
this.dbSourceName = sn;
if (pDbDialect == DBConstants.DB_DIALECT_GENERIC)
{
// try to detect via JDBC metadata
DataSource ds = (DataSource)new InitialContext().lookup(dbSourceName);
if (ds != null)
{
Connection jdbcConn = null;
try
{
jdbcConn = ds.getConnection();
this.dbDialect = DialectDetecter.detect(jdbcConn.getMetaData());
}
catch (SQLException e)
{
throw new RepositoryException(e);
}
finally
{
if (jdbcConn != null)
{
try
{
jdbcConn.close();
}
catch (SQLException e)
{
throw new RepositoryException(e);
}
}
}
}
else
{
throw new RepositoryException("Datasource '" + dbSourceName + "' is not bound in this context.");
}
}
else
{
this.dbDialect = pDbDialect;
}
}
- LOG.info("Using a dialect '" + pDbDialect + "'");
+ LOG.info("Using a dialect '" + this.dbDialect + "'");
// ------------- Values swap config ------------------
try
{
this.maxBufferSize = wsConfig.getContainer().getParameterInteger(MAXBUFFERSIZE_PROP);
}
catch (RepositoryConfigurationException e)
{
this.maxBufferSize = DEF_MAXBUFFERSIZE;
}
try
{
String sdParam = wsConfig.getContainer().getParameterValue(SWAPDIR_PROP);
this.swapDirectory = new File(sdParam);
}
catch (RepositoryConfigurationException e1)
{
this.swapDirectory = new File(DEF_SWAPDIR);
}
if (!swapDirectory.exists())
swapDirectory.mkdirs();
this.swapCleaner = new FileCleaner(false);
initDatabase();
String suParam = null;
boolean enableStorageUpdate = false;
try
{
suParam = wsConfig.getContainer().getParameterValue("update-storage");
enableStorageUpdate = Boolean.parseBoolean(suParam);
}
catch (RepositoryConfigurationException e)
{
if (LOG.isDebugEnabled())
LOG.debug("update-storage parameter is not set " + dbSourceName);
}
this.storageVersion =
StorageUpdateManager.checkVersion(dbSourceName, this.connFactory.getJdbcConnection(), multiDb,
enableStorageUpdate);
LOG.info(getInfo());
}
/**
* Prepare sefault connection factory.
*
* @return GenericConnectionFactory
* @throws NamingException
* on JNDI error
* @throws RepositoryException
* on Storage error
*/
protected GenericConnectionFactory defaultConnectionFactory() throws NamingException, RepositoryException
{
// by default
if (dbSourceName != null)
{
DataSource ds = (DataSource)new InitialContext().lookup(dbSourceName);
if (ds != null)
return new GenericConnectionFactory(ds, containerName, multiDb, valueStorageProvider, maxBufferSize,
swapDirectory, swapCleaner);
throw new RepositoryException("Datasource '" + dbSourceName + "' is not bound in this context.");
}
return new GenericConnectionFactory(dbDriver, dbUrl, dbUserName, dbPassword, containerName, multiDb,
valueStorageProvider, maxBufferSize, swapDirectory, swapCleaner);
}
/**
* Prepare default DB initializer.
*
* @param sqlPath
* - path to SQL script (database creation script)
* @return DBInitializer instance
* @throws NamingException
* on JNDI error
* @throws RepositoryException
* on Storage error
* @throws IOException
* on I/O error
*/
protected DBInitializer defaultDBInitializer(String sqlPath) throws NamingException, RepositoryException,
IOException
{
return new DBInitializer(containerName, this.connFactory.getJdbcConnection(), sqlPath, multiDb);
}
/**
* Checks if DataSources used in right manner.
*
* @param wsConfig
* Workspace configuration
* @param repConfig
* Repository configuration
* @throws RepositoryConfigurationException
* in case of configuration errors
*/
protected void checkIntegrity(WorkspaceEntry wsConfig, RepositoryEntry repConfig)
throws RepositoryConfigurationException
{
boolean isMulti;
for (WorkspaceEntry wsEntry : repConfig.getWorkspaceEntries())
{
if (wsEntry.getName().equals(wsConfig.getName())
|| !wsEntry.getContainer().getType().equals(wsConfig.getContainer().getType())
|| !wsEntry.getContainer().getType().equals(this.getClass().getName()))
continue;
// MULTIDB
if (!wsEntry.getContainer().getParameterValue(MULTIDB).equals(
wsConfig.getContainer().getParameterValue(MULTIDB)))
{
throw new RepositoryConfigurationException("All workspaces must be " + MULTIDB + " or " + SINGLEDB
+ ". But " + wsEntry.getName() + "- multi-db=" + wsEntry.getContainer().getParameterValue(MULTIDB)
+ " and " + wsConfig.getName() + "- multi-db=" + wsConfig.getContainer().getParameterValue(MULTIDB));
}
isMulti = Boolean.parseBoolean(wsConfig.getContainer().getParameterValue(MULTIDB));
// source name
String wsSourceName = null;
String newWsSourceName = null;
try
{
wsSourceName = wsEntry.getContainer().getParameterValue("sourceName");
newWsSourceName = wsConfig.getContainer().getParameterValue("sourceName");
}
catch (RepositoryConfigurationException e)
{
}
if (wsSourceName != null && newWsSourceName != null)
{
if (isMulti)
{
if (wsSourceName.equals(newWsSourceName))
{
throw new RepositoryConfigurationException("SourceName " + wsSourceName + " alredy in use in "
+ wsEntry.getName() + ". SourceName must be different in " + MULTIDB
+ ". Check configuration for " + wsConfig.getName());
}
}
else
{
if (!wsSourceName.equals(newWsSourceName))
{
throw new RepositoryConfigurationException("SourceName must be equals in " + SINGLEDB + " "
+ "repository." + " Check " + wsEntry.getName() + " and " + wsConfig.getName());
}
}
continue;
}
// db-url
String wsUri = null;
String newWsUri = null;
try
{
wsUri = wsEntry.getContainer().getParameterValue("db-url");
newWsUri = wsConfig.getContainer().getParameterValue("db-url");
}
catch (RepositoryConfigurationException e)
{
}
if (wsUri != null && newWsUri != null)
{
if (isMulti)
{
if (wsUri.equals(newWsUri))
{
throw new RepositoryConfigurationException("db-url " + wsUri + " alredy in use in "
+ wsEntry.getName() + ". db-url must be different in " + MULTIDB + ". Check configuration for "
+ wsConfig.getName());
}
}
else
{
if (!wsUri.equals(newWsUri))
{
throw new RepositoryConfigurationException("db-url must be equals in " + SINGLEDB + " "
+ "repository." + " Check " + wsEntry.getName() + " and " + wsConfig.getName());
}
}
}
}
}
/**
* Init storage database.
*
* @throws NamingException
* on JNDI error
* @throws RepositoryException
* on storage error
* @throws IOException
* on I/O error
*/
protected void initDatabase() throws NamingException, RepositoryException, IOException
{
DBInitializer dbInitilizer = null;
String sqlPath = null;
if (dbDialect == DBConstants.DB_DIALECT_ORACLEOCI)
{
LOG.warn(DBConstants.DB_DIALECT_ORACLEOCI + " dialect is experimental!");
// sample of connection factory customization
if (dbSourceName != null)
this.connFactory = defaultConnectionFactory();
else
this.connFactory =
new OracleConnectionFactory(dbDriver, dbUrl, dbUserName, dbPassword, containerName, multiDb,
valueStorageProvider, maxBufferSize, swapDirectory, swapCleaner);
sqlPath = "/conf/storage/jcr-" + (multiDb ? "m" : "s") + "jdbc.ora.sql";
// a particular db initializer may be configured here too
dbInitilizer = new OracleDBInitializer(containerName, this.connFactory.getJdbcConnection(), sqlPath, multiDb);
}
else if (dbDialect == DBConstants.DB_DIALECT_ORACLE)
{
this.connFactory = defaultConnectionFactory();
sqlPath = "/conf/storage/jcr-" + (multiDb ? "m" : "s") + "jdbc.ora.sql";
dbInitilizer = new OracleDBInitializer(containerName, this.connFactory.getJdbcConnection(), sqlPath, multiDb);
}
else if (dbDialect == DBConstants.DB_DIALECT_PGSQL)
{
this.connFactory = defaultConnectionFactory();
sqlPath = "/conf/storage/jcr-" + (multiDb ? "m" : "s") + "jdbc.pgsql.sql";
dbInitilizer = new PgSQLDBInitializer(containerName, this.connFactory.getJdbcConnection(), sqlPath, multiDb);
}
else if (dbDialect == DBConstants.DB_DIALECT_MYSQL)
{
// [PN] 28.06.07
if (dbSourceName != null)
{
DataSource ds = (DataSource)new InitialContext().lookup(dbSourceName);
if (ds != null)
this.connFactory =
new MySQLConnectionFactory(ds, containerName, multiDb, valueStorageProvider, maxBufferSize,
swapDirectory, swapCleaner);
else
throw new RepositoryException("Datasource '" + dbSourceName + "' is not bound in this context.");
}
else
this.connFactory =
new MySQLConnectionFactory(dbDriver, dbUrl, dbUserName, dbPassword, containerName, multiDb,
valueStorageProvider, maxBufferSize, swapDirectory, swapCleaner);
sqlPath = "/conf/storage/jcr-" + (multiDb ? "m" : "s") + "jdbc.mysql.sql";
dbInitilizer = defaultDBInitializer(sqlPath);
}
else if (dbDialect == DBConstants.DB_DIALECT_MYSQL_UTF8)
{
// [PN] 13.07.08
if (dbSourceName != null)
{
DataSource ds = (DataSource)new InitialContext().lookup(dbSourceName);
if (ds != null)
this.connFactory =
new MySQLConnectionFactory(ds, containerName, multiDb, valueStorageProvider, maxBufferSize,
swapDirectory, swapCleaner);
else
throw new RepositoryException("Datasource '" + dbSourceName + "' is not bound in this context.");
}
else
this.connFactory =
new MySQLConnectionFactory(dbDriver, dbUrl, dbUserName, dbPassword, containerName, multiDb,
valueStorageProvider, maxBufferSize, swapDirectory, swapCleaner);
sqlPath = "/conf/storage/jcr-" + (multiDb ? "m" : "s") + "jdbc.mysql-utf8.sql";
dbInitilizer = defaultDBInitializer(sqlPath);
}
else if (dbDialect == DBConstants.DB_DIALECT_MSSQL)
{
this.connFactory = defaultConnectionFactory();
sqlPath = "/conf/storage/jcr-" + (multiDb ? "m" : "s") + "jdbc.mssql.sql";
dbInitilizer = defaultDBInitializer(sqlPath);
}
else if (dbDialect == DBConstants.DB_DIALECT_DERBY)
{
this.connFactory = defaultConnectionFactory();
sqlPath = "/conf/storage/jcr-" + (multiDb ? "m" : "s") + "jdbc.derby.sql";
dbInitilizer = defaultDBInitializer(sqlPath);
}
else if (dbDialect == DBConstants.DB_DIALECT_DB2)
{
this.connFactory = defaultConnectionFactory();
sqlPath = "/conf/storage/jcr-" + (multiDb ? "m" : "s") + "jdbc.db2.sql";
dbInitilizer = defaultDBInitializer(sqlPath);
}
else if (dbDialect == DBConstants.DB_DIALECT_DB2V8)
{
this.connFactory = defaultConnectionFactory();
sqlPath = "/conf/storage/jcr-" + (multiDb ? "m" : "s") + "jdbc.db2v8.sql";
dbInitilizer = defaultDBInitializer(sqlPath);
}
else if (dbDialect == DBConstants.DB_DIALECT_SYBASE)
{
this.connFactory = defaultConnectionFactory();
sqlPath = "/conf/storage/jcr-" + (multiDb ? "m" : "s") + "jdbc.sybase.sql";
dbInitilizer = defaultDBInitializer(sqlPath);
}
else if (dbDialect == DBConstants.DB_DIALECT_INGRES)
{
this.connFactory = defaultConnectionFactory();
sqlPath = "/conf/storage/jcr-" + (multiDb ? "m" : "s") + "jdbc.ingres.sql";
// using Postgres initializer
dbInitilizer =
new IngresSQLDBInitializer(containerName, this.connFactory.getJdbcConnection(), sqlPath, multiDb);
}
else if (dbDialect == DBConstants.DB_DIALECT_HSQLDB)
{
if (dbSourceName != null)
{
DataSource ds = (DataSource)new InitialContext().lookup(dbSourceName);
if (ds != null)
this.connFactory =
new HSQLDBConnectionFactory(ds, containerName, multiDb, valueStorageProvider, maxBufferSize,
swapDirectory, swapCleaner);
else
throw new RepositoryException("Datasource '" + dbSourceName + "' is not bound in this context.");
}
else
this.connFactory =
new HSQLDBConnectionFactory(dbDriver, dbUrl, dbUserName, dbPassword, containerName, multiDb,
valueStorageProvider, maxBufferSize, swapDirectory, swapCleaner);
sqlPath = "/conf/storage/jcr-" + (multiDb ? "m" : "s") + "jdbc.sql";
dbInitilizer = defaultDBInitializer(sqlPath);
}
else
{
// generic, DB_HSQLDB
this.connFactory = defaultConnectionFactory();
sqlPath = "/conf/storage/jcr-" + (multiDb ? "m" : "s") + "jdbc.sql";
dbInitilizer = defaultDBInitializer(sqlPath);
}
// database type
try
{
dbInitilizer.init();
}
catch (DBInitializerException e)
{
LOG.error("Error of init db " + e, e);
}
}
/**
* Return ConnectionFactory.
*
* @return WorkspaceStorageConnectionFactory connection
*/
protected GenericConnectionFactory getConnectionFactory()
{
return connFactory;
}
protected String validateDialect(String confParam)
{
for (String dbType : DBConstants.DB_DIALECTS)
{
if (dbType.equalsIgnoreCase(confParam))
{
return dbType;
}
}
return DBConstants.DB_DIALECT_GENERIC; // by default
}
/**
* {@inheritDoc}
*/
public WorkspaceStorageConnection openConnection() throws RepositoryException
{
return connFactory.openConnection();
}
/**
* {@inheritDoc}
*/
public WorkspaceStorageConnection openConnection(boolean readOnly) throws RepositoryException
{
return connFactory.openConnection(readOnly);
}
/**
* {@inheritDoc}
*/
public WorkspaceStorageConnection reuseConnection(WorkspaceStorageConnection original) throws RepositoryException
{
if (original instanceof JDBCStorageConnection)
{
WorkspaceStorageConnectionFactory cFactory =
new SharedConnectionFactory(((JDBCStorageConnection)original).getJdbcConnection(), containerName, multiDb,
valueStorageProvider, maxBufferSize, swapDirectory, swapCleaner);
return cFactory.openConnection();
}
else
{
return openConnection();
}
}
/**
* {@inheritDoc}
*/
public String getName()
{
return containerName;
}
/**
* {@inheritDoc}
*/
public String getInfo()
{
String str =
"JDBC based JCR Workspace Data container \n" + "container name: " + containerName + " \n"
+ "data source JNDI name: " + dbSourceName + "\n" + "is multi database: " + multiDb + "\n"
+ "storage version: " + storageVersion + "\n" + "value storage provider: " + valueStorageProvider + "\n"
+ "max buffer size (bytes): " + maxBufferSize + "\n" + "swap directory path: "
+ swapDirectory.getAbsolutePath();
return str;
}
/**
* {@inheritDoc}
*/
public String getStorageVersion()
{
return storageVersion;
}
/**
* {@inheritDoc}
*/
public void start()
{
this.swapCleaner.start();
}
/**
* {@inheritDoc}
*/
public void stop()
{
this.swapCleaner.halt();
this.swapCleaner.interrupt();
// TODO HSQLDB Stop (debug)
// if (dbDialect.equals(DB_DIALECT_GENERIC) ||
// dbDialect.equals(DB_DIALECT_HSQLDB)) {
// // shutdown in-process HSQLDB database
// System.out.println("Shutdown in-process HSQLDB database...");
// try {
// JDBCStorageConnection conn = (JDBCStorageConnection) openConnection();
// Connection jdbcConn = conn.getJdbcConnection();
// String dbUrl = jdbcConn.getMetaData().getURL();
// if (dbUrl.startsWith("jdbc:hsqldb:file") ||
// dbUrl.startsWith("jdbc:hsqldb:mem")) {
// // yeah, there is in-process hsqldb, shutdown it now
// jdbcConn.createStatement().execute("SHUTDOWN");
// System.out.println("Shutdown in-process HSQLDB database... done.");
// }
// } catch (Throwable e) {
// log.error("JDBC Data container stop error " + e);
// e.printStackTrace();
// }
// }
}
/**
* {@inheritDoc}
*/
public boolean isSame(WorkspaceDataContainer another)
{
if (another == this)
return true;
if (another instanceof JDBCWorkspaceDataContainer)
{
JDBCWorkspaceDataContainer anotherJdbc = (JDBCWorkspaceDataContainer)another;
if (getDbSourceName() != null)
// by jndi ds name
return getDbSourceName().equals(anotherJdbc.getDbSourceName());
// by db connection params
return getDbDriver().equals(anotherJdbc.getDbDriver()) && getDbUrl().equals(anotherJdbc.getDbUrl())
&& getDbUserName().equals(anotherJdbc.getDbUserName());
}
return false;
}
/**
* Used in <code>equals()</code>.
*
* @return DataSource name
*/
protected String getDbSourceName()
{
return dbSourceName;
}
/**
* Used in <code>equals()</code>.
*
* @return JDBC driver
*/
protected String getDbDriver()
{
return dbDriver;
}
/**
* Used in <code>equals()</code>.
*
* @return Database URL
*/
protected String getDbUrl()
{
return dbUrl;
}
/**
* Used in <code>equals()</code>.
*
* @return Database username
*/
protected String getDbUserName()
{
return dbUserName;
}
}
| true | true | public JDBCWorkspaceDataContainer(WorkspaceEntry wsConfig, RepositoryEntry repConfig,
InitialContextInitializer contextInit, ValueStoragePluginProvider valueStorageProvider)
throws RepositoryConfigurationException, NamingException, RepositoryException, IOException
{
checkIntegrity(wsConfig, repConfig);
this.containerName = wsConfig.getName();
this.multiDb = Boolean.parseBoolean(wsConfig.getContainer().getParameterValue(MULTIDB));
this.valueStorageProvider = valueStorageProvider;
// ------------- Database config ------------------
String pDbDialect = null;
try
{
pDbDialect = validateDialect(wsConfig.getContainer().getParameterValue(DB_DIALECT));
}
catch (RepositoryConfigurationException e)
{
pDbDialect = DBConstants.DB_DIALECT_GENERIC;
}
String pDbDriver = null;
String pDbUrl = null;
String pDbUserName = null;
String pDbPassword = null;
try
{
pDbDriver = wsConfig.getContainer().getParameterValue(DB_DRIVER);
// username/passwd may not pesent
try
{
pDbUserName = wsConfig.getContainer().getParameterValue(DB_USERNAME);
pDbPassword = wsConfig.getContainer().getParameterValue(DB_PASSWORD);
}
catch (RepositoryConfigurationException e)
{
pDbUserName = pDbPassword = null;
}
pDbUrl = wsConfig.getContainer().getParameterValue(DB_URL); // last here!
}
catch (RepositoryConfigurationException e)
{
}
if (pDbUrl != null)
{
this.dbDriver = pDbDriver;
this.dbUrl = pDbUrl;
this.dbUserName = pDbUserName;
this.dbPassword = pDbPassword;
this.dbSourceName = null;
LOG.info("Connect to JCR database as user '" + this.dbUserName + "'");
if (pDbDialect == DBConstants.DB_DIALECT_GENERIC)
{
// try to detect via JDBC metadata
Connection jdbcConn = null;
try
{
jdbcConn =
dbUserName != null ? DriverManager.getConnection(dbUrl, dbUserName, dbPassword) : DriverManager
.getConnection(dbUrl);
this.dbDialect = DialectDetecter.detect(jdbcConn.getMetaData());
}
catch (SQLException e)
{
throw new RepositoryException(e);
}
finally
{
if (jdbcConn != null)
{
try
{
jdbcConn.close();
}
catch (SQLException e)
{
throw new RepositoryException(e);
}
}
}
}
else
{
this.dbDialect = pDbDialect;
}
}
else
{
this.dbDriver = null;
this.dbUrl = null;
this.dbUserName = null;
this.dbPassword = null;
String sn;
try
{
sn = wsConfig.getContainer().getParameterValue(SOURCE_NAME);
}
catch (RepositoryConfigurationException e)
{
sn = wsConfig.getContainer().getParameterValue("sourceName"); // TODO for backward comp,
// remove in rel.2.0
}
this.dbSourceName = sn;
if (pDbDialect == DBConstants.DB_DIALECT_GENERIC)
{
// try to detect via JDBC metadata
DataSource ds = (DataSource)new InitialContext().lookup(dbSourceName);
if (ds != null)
{
Connection jdbcConn = null;
try
{
jdbcConn = ds.getConnection();
this.dbDialect = DialectDetecter.detect(jdbcConn.getMetaData());
}
catch (SQLException e)
{
throw new RepositoryException(e);
}
finally
{
if (jdbcConn != null)
{
try
{
jdbcConn.close();
}
catch (SQLException e)
{
throw new RepositoryException(e);
}
}
}
}
else
{
throw new RepositoryException("Datasource '" + dbSourceName + "' is not bound in this context.");
}
}
else
{
this.dbDialect = pDbDialect;
}
}
LOG.info("Using a dialect '" + pDbDialect + "'");
// ------------- Values swap config ------------------
try
{
this.maxBufferSize = wsConfig.getContainer().getParameterInteger(MAXBUFFERSIZE_PROP);
}
catch (RepositoryConfigurationException e)
{
this.maxBufferSize = DEF_MAXBUFFERSIZE;
}
try
{
String sdParam = wsConfig.getContainer().getParameterValue(SWAPDIR_PROP);
this.swapDirectory = new File(sdParam);
}
catch (RepositoryConfigurationException e1)
{
this.swapDirectory = new File(DEF_SWAPDIR);
}
if (!swapDirectory.exists())
swapDirectory.mkdirs();
this.swapCleaner = new FileCleaner(false);
initDatabase();
String suParam = null;
boolean enableStorageUpdate = false;
try
{
suParam = wsConfig.getContainer().getParameterValue("update-storage");
enableStorageUpdate = Boolean.parseBoolean(suParam);
}
catch (RepositoryConfigurationException e)
{
if (LOG.isDebugEnabled())
LOG.debug("update-storage parameter is not set " + dbSourceName);
}
this.storageVersion =
StorageUpdateManager.checkVersion(dbSourceName, this.connFactory.getJdbcConnection(), multiDb,
enableStorageUpdate);
LOG.info(getInfo());
}
| public JDBCWorkspaceDataContainer(WorkspaceEntry wsConfig, RepositoryEntry repConfig,
InitialContextInitializer contextInit, ValueStoragePluginProvider valueStorageProvider)
throws RepositoryConfigurationException, NamingException, RepositoryException, IOException
{
checkIntegrity(wsConfig, repConfig);
this.containerName = wsConfig.getName();
this.multiDb = Boolean.parseBoolean(wsConfig.getContainer().getParameterValue(MULTIDB));
this.valueStorageProvider = valueStorageProvider;
// ------------- Database config ------------------
String pDbDialect = null;
try
{
pDbDialect = validateDialect(wsConfig.getContainer().getParameterValue(DB_DIALECT));
}
catch (RepositoryConfigurationException e)
{
pDbDialect = DBConstants.DB_DIALECT_GENERIC;
}
String pDbDriver = null;
String pDbUrl = null;
String pDbUserName = null;
String pDbPassword = null;
try
{
pDbDriver = wsConfig.getContainer().getParameterValue(DB_DRIVER);
// username/passwd may not pesent
try
{
pDbUserName = wsConfig.getContainer().getParameterValue(DB_USERNAME);
pDbPassword = wsConfig.getContainer().getParameterValue(DB_PASSWORD);
}
catch (RepositoryConfigurationException e)
{
pDbUserName = pDbPassword = null;
}
pDbUrl = wsConfig.getContainer().getParameterValue(DB_URL); // last here!
}
catch (RepositoryConfigurationException e)
{
}
if (pDbUrl != null)
{
this.dbDriver = pDbDriver;
this.dbUrl = pDbUrl;
this.dbUserName = pDbUserName;
this.dbPassword = pDbPassword;
this.dbSourceName = null;
LOG.info("Connect to JCR database as user '" + this.dbUserName + "'");
if (pDbDialect == DBConstants.DB_DIALECT_GENERIC)
{
// try to detect via JDBC metadata
Connection jdbcConn = null;
try
{
jdbcConn =
dbUserName != null ? DriverManager.getConnection(dbUrl, dbUserName, dbPassword) : DriverManager
.getConnection(dbUrl);
this.dbDialect = DialectDetecter.detect(jdbcConn.getMetaData());
}
catch (SQLException e)
{
throw new RepositoryException(e);
}
finally
{
if (jdbcConn != null)
{
try
{
jdbcConn.close();
}
catch (SQLException e)
{
throw new RepositoryException(e);
}
}
}
}
else
{
this.dbDialect = pDbDialect;
}
}
else
{
this.dbDriver = null;
this.dbUrl = null;
this.dbUserName = null;
this.dbPassword = null;
String sn;
try
{
sn = wsConfig.getContainer().getParameterValue(SOURCE_NAME);
}
catch (RepositoryConfigurationException e)
{
sn = wsConfig.getContainer().getParameterValue("sourceName"); // TODO for backward comp,
// remove in rel.2.0
}
this.dbSourceName = sn;
if (pDbDialect == DBConstants.DB_DIALECT_GENERIC)
{
// try to detect via JDBC metadata
DataSource ds = (DataSource)new InitialContext().lookup(dbSourceName);
if (ds != null)
{
Connection jdbcConn = null;
try
{
jdbcConn = ds.getConnection();
this.dbDialect = DialectDetecter.detect(jdbcConn.getMetaData());
}
catch (SQLException e)
{
throw new RepositoryException(e);
}
finally
{
if (jdbcConn != null)
{
try
{
jdbcConn.close();
}
catch (SQLException e)
{
throw new RepositoryException(e);
}
}
}
}
else
{
throw new RepositoryException("Datasource '" + dbSourceName + "' is not bound in this context.");
}
}
else
{
this.dbDialect = pDbDialect;
}
}
LOG.info("Using a dialect '" + this.dbDialect + "'");
// ------------- Values swap config ------------------
try
{
this.maxBufferSize = wsConfig.getContainer().getParameterInteger(MAXBUFFERSIZE_PROP);
}
catch (RepositoryConfigurationException e)
{
this.maxBufferSize = DEF_MAXBUFFERSIZE;
}
try
{
String sdParam = wsConfig.getContainer().getParameterValue(SWAPDIR_PROP);
this.swapDirectory = new File(sdParam);
}
catch (RepositoryConfigurationException e1)
{
this.swapDirectory = new File(DEF_SWAPDIR);
}
if (!swapDirectory.exists())
swapDirectory.mkdirs();
this.swapCleaner = new FileCleaner(false);
initDatabase();
String suParam = null;
boolean enableStorageUpdate = false;
try
{
suParam = wsConfig.getContainer().getParameterValue("update-storage");
enableStorageUpdate = Boolean.parseBoolean(suParam);
}
catch (RepositoryConfigurationException e)
{
if (LOG.isDebugEnabled())
LOG.debug("update-storage parameter is not set " + dbSourceName);
}
this.storageVersion =
StorageUpdateManager.checkVersion(dbSourceName, this.connFactory.getJdbcConnection(), multiDb,
enableStorageUpdate);
LOG.info(getInfo());
}
|
diff --git a/Selenium/com/jyou/selenium/util/SeleniumHelper.java b/Selenium/com/jyou/selenium/util/SeleniumHelper.java
index 86e9774..1a71422 100644
--- a/Selenium/com/jyou/selenium/util/SeleniumHelper.java
+++ b/Selenium/com/jyou/selenium/util/SeleniumHelper.java
@@ -1,49 +1,56 @@
package com.jyou.selenium.util;
import java.io.File;
import java.util.Properties;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
public class SeleniumHelper {
public static WebDriver createDriver(String browse){
WebDriver driver = null;
if(browse.equals("ie") || browse.equals("chrome")){
StringBuffer filePath = new StringBuffer();
filePath.append(System.getProperty("user.dir"));
filePath.append(File.separator);
filePath.append("SeleniumDriver");
filePath.append(File.separator);
if(browse.equals("chrome")){
filePath.append("chromedriver.exe");
System.setProperty("webdriver.chrome.driver", filePath.toString());
driver = new ChromeDriver();
}
else {
Properties props = System.getProperties();
- filePath.append(browse + "_" + props.getProperty("os.arch"));
+ String arch = props.getProperty("os.arch");
+ filePath.append(browse + "_");
+ if(arch.equals("x86")){
+ filePath.append(arch);
+ }
+ else {
+ filePath.append("amd64");
+ }
filePath.append(File.separator);
filePath.append("IEDriverServer.exe");
System.setProperty("webdriver.ie.driver", filePath.toString());
driver = new InternetExplorerDriver();
}
}
else {
driver = new FirefoxDriver();
}
return driver;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Hello World");
WebDriver driver = createDriver("ie");
driver.get("http://www.baidu.com");
}
}
| true | true | public static WebDriver createDriver(String browse){
WebDriver driver = null;
if(browse.equals("ie") || browse.equals("chrome")){
StringBuffer filePath = new StringBuffer();
filePath.append(System.getProperty("user.dir"));
filePath.append(File.separator);
filePath.append("SeleniumDriver");
filePath.append(File.separator);
if(browse.equals("chrome")){
filePath.append("chromedriver.exe");
System.setProperty("webdriver.chrome.driver", filePath.toString());
driver = new ChromeDriver();
}
else {
Properties props = System.getProperties();
filePath.append(browse + "_" + props.getProperty("os.arch"));
filePath.append(File.separator);
filePath.append("IEDriverServer.exe");
System.setProperty("webdriver.ie.driver", filePath.toString());
driver = new InternetExplorerDriver();
}
}
else {
driver = new FirefoxDriver();
}
return driver;
}
| public static WebDriver createDriver(String browse){
WebDriver driver = null;
if(browse.equals("ie") || browse.equals("chrome")){
StringBuffer filePath = new StringBuffer();
filePath.append(System.getProperty("user.dir"));
filePath.append(File.separator);
filePath.append("SeleniumDriver");
filePath.append(File.separator);
if(browse.equals("chrome")){
filePath.append("chromedriver.exe");
System.setProperty("webdriver.chrome.driver", filePath.toString());
driver = new ChromeDriver();
}
else {
Properties props = System.getProperties();
String arch = props.getProperty("os.arch");
filePath.append(browse + "_");
if(arch.equals("x86")){
filePath.append(arch);
}
else {
filePath.append("amd64");
}
filePath.append(File.separator);
filePath.append("IEDriverServer.exe");
System.setProperty("webdriver.ie.driver", filePath.toString());
driver = new InternetExplorerDriver();
}
}
else {
driver = new FirefoxDriver();
}
return driver;
}
|
diff --git a/src/main/java/com/eyeq/pivot4j/primefaces/ui/PivotGridHandler.java b/src/main/java/com/eyeq/pivot4j/primefaces/ui/PivotGridHandler.java
index c53d616..4c9b9cb 100644
--- a/src/main/java/com/eyeq/pivot4j/primefaces/ui/PivotGridHandler.java
+++ b/src/main/java/com/eyeq/pivot4j/primefaces/ui/PivotGridHandler.java
@@ -1,482 +1,486 @@
package com.eyeq.pivot4j.primefaces.ui;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.component.UISelectItem;
import javax.faces.context.FacesContext;
import org.apache.commons.lang.StringUtils;
import org.olap4j.CellSetAxis;
import org.olap4j.OlapDataSource;
import org.olap4j.OlapException;
import org.olap4j.metadata.Cube;
import org.olap4j.metadata.Schema;
import org.primefaces.component.panelgrid.PanelGrid;
import com.eyeq.pivot4j.ModelChangeEvent;
import com.eyeq.pivot4j.ModelChangeListener;
import com.eyeq.pivot4j.PivotModel;
import com.eyeq.pivot4j.QueryEvent;
import com.eyeq.pivot4j.QueryListener;
import com.eyeq.pivot4j.impl.PivotModelImpl;
import com.eyeq.pivot4j.primefaces.datasource.ConnectionMetadata;
import com.eyeq.pivot4j.transform.NonEmpty;
import com.eyeq.pivot4j.transform.SwapAxes;
import com.eyeq.pivot4j.ui.command.CellCommand;
import com.eyeq.pivot4j.ui.command.CellParameters;
import com.eyeq.pivot4j.ui.command.DrillDownCommand;
@ManagedBean(name = "pivotGridHandler")
@RequestScoped
public class PivotGridHandler implements QueryListener, ModelChangeListener {
@ManagedProperty(value = "#{pivotStateManager}")
private PivotStateManager stateManager;
@ManagedProperty(value = "#{navigatorHandler}")
private NavigatorHandler navigator;
private PivotModel model;
private PrimeFacesPivotRenderer renderer;
private List<UISelectItem> cubeItems;
private String cubeName;
private String currentMdx;
private Long duration;
@PostConstruct
protected void initialize() {
this.model = stateManager.getModel();
if (model != null) {
model.addQueryListener(this);
model.addModelChangeListener(this);
ConnectionMetadata connectionInfo = stateManager
.getConnectionInfo();
- if (!model.isInitialized() && connectionInfo != null) {
- this.cubeName = connectionInfo.getCubeName();
+ if (connectionInfo != null) {
+ if (!model.isInitialized() || cubeName == null) {
+ this.cubeName = connectionInfo.getCubeName();
- onCubeChange();
+ if (!model.isInitialized()) {
+ onCubeChange();
+ }
+ }
}
}
FacesContext context = FacesContext.getCurrentInstance();
this.renderer = new PrimeFacesPivotRenderer(context);
renderer.initialize();
Serializable state = stateManager.getRendererState();
if (state == null) {
renderer.setShowDimensionTitle(true);
renderer.setShowParentMembers(false);
renderer.setHideSpans(false);
renderer.setDrillDownMode(DrillDownCommand.MODE_POSITION);
renderer.setEnableDrillThrough(false);
renderer.setEnableColumnDrillDown(true);
renderer.setEnableRowDrillDown(true);
} else {
renderer.restoreState(state);
}
}
@PreDestroy
protected void destroy() {
if (model != null) {
model.removeQueryListener(this);
model.removeModelChangeListener(this);
}
}
/**
* @return the stateManager
*/
public PivotStateManager getStateManager() {
return stateManager;
}
/**
* @param stateManager
* the stateManager to set
*/
public void setStateManager(PivotStateManager stateManager) {
this.stateManager = stateManager;
}
/**
* @return the cubeName
*/
public String getCubeName() {
return cubeName;
}
/**
* @param cubeName
* the cubeName to set
*/
public void setCubeName(String cubeName) {
this.cubeName = cubeName;
}
/**
* @return the navigator
*/
public NavigatorHandler getNavigator() {
return navigator;
}
/**
* @param navigator
* the navigator to set
*/
public void setNavigator(NavigatorHandler navigator) {
this.navigator = navigator;
}
/**
* @return the pivotGrid
*/
public PanelGrid getPivotGrid() {
return renderer.getComponent();
}
/**
* @param pivotGrid
* the pivotGrid to set
*/
public void setPivotGrid(PanelGrid pivotGrid) {
renderer.setComponent(pivotGrid);
}
/**
* @return the duration
*/
public Long getDuration() {
return duration;
}
public List<UISelectItem> getCubes() throws OlapException, SQLException {
if (cubeItems == null) {
this.cubeItems = new ArrayList<UISelectItem>();
UISelectItem defaultItem = new UISelectItem();
defaultItem.setItemLabel("---- Please select a cube ----");
defaultItem.setItemValue("");
cubeItems.add(defaultItem);
if (model != null) {
OlapDataSource dataSource = ((PivotModelImpl) model)
.getDataSource();
Schema schema = dataSource.getConnection().getOlapSchema();
List<Cube> cubes = schema.getCubes();
for (Cube cube : cubes) {
UISelectItem item = new UISelectItem();
item.setItemLabel(cube.getCaption());
item.setItemValue(cube.getName());
cubeItems.add(item);
}
}
}
return cubeItems;
}
public void onCubeChange() {
if (StringUtils.isEmpty(cubeName)) {
if (model.isInitialized()) {
model.destroy();
}
} else {
String mdx = String.format(
"select {} on COLUMNS, {} on ROWS from [%s]", cubeName);
model.setMdx(mdx);
if (!model.isInitialized()) {
model.initialize();
}
}
}
public boolean isValid() {
if (model == null || !model.isInitialized()) {
return false;
}
List<CellSetAxis> axes = model.getCellSet().getAxes();
if (axes.size() < 2) {
return false;
}
return axes.get(0).getPositionCount() > 0
&& axes.get(1).getPositionCount() > 0;
}
public void render() {
if (model != null && model.isInitialized()) {
renderer.render(model);
stateManager.setRendererState(renderer.bookmarkState());
}
}
public void executeCommand() {
FacesContext context = FacesContext.getCurrentInstance();
Map<String, String> requestParameters = context.getExternalContext()
.getRequestParameterMap();
CellParameters parameters = new CellParameters();
if (requestParameters.containsKey("axis")) {
parameters.setAxisOrdinal(Integer.parseInt(requestParameters
.get("axis")));
}
if (requestParameters.containsKey("position")) {
parameters.setPositionOrdinal(Integer.parseInt(requestParameters
.get("position")));
}
if (requestParameters.containsKey("member")) {
parameters.setMemberOrdinal(Integer.parseInt(requestParameters
.get("member")));
}
if (requestParameters.containsKey("hierarchy")) {
parameters.setHierarchyOrdinal(Integer.parseInt(requestParameters
.get("hierarchy")));
}
if (requestParameters.containsKey("cell")) {
parameters.setCellOrdinal(Integer.parseInt(requestParameters
.get("cell")));
}
CellCommand<?> command = renderer.getCommand(requestParameters
.get("command"));
command.execute(model, parameters);
}
public void executeMdx() {
String oldMdx = model.getCurrentMdx();
try {
model.setMdx(currentMdx);
if (!model.isInitialized()) {
model.initialize();
}
} catch (Exception e) {
FacesContext context = FacesContext.getCurrentInstance();
String msg = "Failed to execute the MDX query.";
context.addMessage(null, new FacesMessage(
FacesMessage.SEVERITY_ERROR, msg, e.getMessage()));
model.setMdx(oldMdx);
}
}
/**
* @return the currentMdx
*/
public String getCurrentMdx() {
if (model == null) {
return null;
}
return model.getCurrentMdx();
}
/**
* @param currentMdx
*/
public void setCurrentMdx(String currentMdx) {
this.currentMdx = currentMdx;
}
/**
* @return the showParentMembers
*/
public boolean getShowParentMembers() {
return renderer.getShowParentMembers();
}
/**
* @param showParentMembers
* the showParentMembers to set
*/
public void setShowParentMembers(boolean showParentMembers) {
renderer.setShowParentMembers(showParentMembers);
}
/**
* @return the hideSpans
*/
public boolean getHideSpans() {
return renderer.getHideSpans();
}
/**
* @param hideSpans
* the hideSpans to set
*/
public void setHideSpans(boolean hideSpans) {
renderer.setHideSpans(hideSpans);
}
/**
* @return the drillThrough
*/
public boolean getDrillThrough() {
return renderer.getEnableDrillThrough();
}
/**
* @param drillThrough
* the drillThrough to set
*/
public void setDrillThrough(boolean drillThrough) {
renderer.setEnableDrillThrough(drillThrough);
}
/**
* @return the drillDownMode
*/
public String getDrillDownMode() {
return renderer.getDrillDownMode();
}
/**
* @param drillDownMode
* the drillDownMode to set
*/
public void setDrillDownMode(String drillDownMode) {
renderer.setDrillDownMode(drillDownMode);
}
/**
* @return the swapAxes
*/
public boolean getSwapAxes() {
if (model == null || !model.isInitialized()) {
return false;
}
SwapAxes transform = model.getTransform(SwapAxes.class);
return transform.isSwapAxes();
}
/**
* @param swapAxes
* the swapAxes to set
*/
public void setSwapAxes(boolean swapAxes) {
SwapAxes transform = model.getTransform(SwapAxes.class);
transform.setSwapAxes(swapAxes);
}
/**
* @return the nonEmpty
*/
public boolean getNonEmpty() {
if (model == null || !model.isInitialized()) {
return false;
}
NonEmpty transform = model.getTransform(NonEmpty.class);
return transform.isNonEmpty();
}
/**
* @param nonEmpty
* the nonEmpty to set
*/
public void setNonEmpty(boolean nonEmpty) {
NonEmpty transform = model.getTransform(NonEmpty.class);
transform.setNonEmpty(nonEmpty);
}
/**
* @param drillThroughRows
* the drillThroughRows to set
*/
protected void setDrillThroughRows(Integer drillThroughRows) {
FacesContext context = FacesContext.getCurrentInstance();
Map<String, Object> session = context.getExternalContext()
.getSessionMap();
if (drillThroughRows == null) {
session.remove("drillThroughRows");
} else {
session.put("drillThroughRows", drillThroughRows);
}
}
/**
* @see com.eyeq.pivot4j.QueryListener#queryExecuted(com.eyeq.pivot4j.QueryEvent)
*/
@Override
public void queryExecuted(QueryEvent e) {
this.duration = e.getDuration();
if (model.getCube() == null) {
this.cubeName = null;
} else {
this.cubeName = model.getCube().getName();
}
}
/**
* @see com.eyeq.pivot4j.ModelChangeListener#modelInitialized(com.eyeq.pivot4j.ModelChangeEvent)
*/
@Override
public void modelInitialized(ModelChangeEvent e) {
}
/**
* @see com.eyeq.pivot4j.ModelChangeListener#modelDestroyed(com.eyeq.pivot4j.ModelChangeEvent)
*/
@Override
public void modelDestroyed(ModelChangeEvent e) {
}
/**
* @see com.eyeq.pivot4j.ModelChangeListener#modelChanged(com.eyeq.pivot4j.ModelChangeEvent)
*/
@Override
public void modelChanged(ModelChangeEvent e) {
}
/**
* @see com.eyeq.pivot4j.ModelChangeListener#structureChanged(com.eyeq.pivot4j.ModelChangeEvent)
*/
@Override
public void structureChanged(ModelChangeEvent e) {
render();
}
}
| false | true | protected void initialize() {
this.model = stateManager.getModel();
if (model != null) {
model.addQueryListener(this);
model.addModelChangeListener(this);
ConnectionMetadata connectionInfo = stateManager
.getConnectionInfo();
if (!model.isInitialized() && connectionInfo != null) {
this.cubeName = connectionInfo.getCubeName();
onCubeChange();
}
}
FacesContext context = FacesContext.getCurrentInstance();
this.renderer = new PrimeFacesPivotRenderer(context);
renderer.initialize();
Serializable state = stateManager.getRendererState();
if (state == null) {
renderer.setShowDimensionTitle(true);
renderer.setShowParentMembers(false);
renderer.setHideSpans(false);
renderer.setDrillDownMode(DrillDownCommand.MODE_POSITION);
renderer.setEnableDrillThrough(false);
renderer.setEnableColumnDrillDown(true);
renderer.setEnableRowDrillDown(true);
} else {
renderer.restoreState(state);
}
}
| protected void initialize() {
this.model = stateManager.getModel();
if (model != null) {
model.addQueryListener(this);
model.addModelChangeListener(this);
ConnectionMetadata connectionInfo = stateManager
.getConnectionInfo();
if (connectionInfo != null) {
if (!model.isInitialized() || cubeName == null) {
this.cubeName = connectionInfo.getCubeName();
if (!model.isInitialized()) {
onCubeChange();
}
}
}
}
FacesContext context = FacesContext.getCurrentInstance();
this.renderer = new PrimeFacesPivotRenderer(context);
renderer.initialize();
Serializable state = stateManager.getRendererState();
if (state == null) {
renderer.setShowDimensionTitle(true);
renderer.setShowParentMembers(false);
renderer.setHideSpans(false);
renderer.setDrillDownMode(DrillDownCommand.MODE_POSITION);
renderer.setEnableDrillThrough(false);
renderer.setEnableColumnDrillDown(true);
renderer.setEnableRowDrillDown(true);
} else {
renderer.restoreState(state);
}
}
|
diff --git a/orbisgis-core/src/main/java/org/orbisgis/core/layerModel/BeanMapContext.java b/orbisgis-core/src/main/java/org/orbisgis/core/layerModel/BeanMapContext.java
index 047d6a74c..a454ba698 100644
--- a/orbisgis-core/src/main/java/org/orbisgis/core/layerModel/BeanMapContext.java
+++ b/orbisgis-core/src/main/java/org/orbisgis/core/layerModel/BeanMapContext.java
@@ -1,227 +1,227 @@
/**
* OrbisGIS is a GIS application dedicated to scientific spatial simulation.
* This cross-platform GIS is developed at French IRSTV institute and is able to
* manipulate and create vector and raster spatial information.
*
* OrbisGIS is distributed under GPL 3 license. It is produced by the "Atelier SIG"
* team of the IRSTV Institute <http://www.irstv.fr/> CNRS FR 2488.
*
* Copyright (C) 2007-1012 IRSTV (FR CNRS 2488)
*
* This file is part of OrbisGIS.
*
* OrbisGIS is free software: you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* OrbisGIS is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* OrbisGIS. If not, see <http://www.gnu.org/licenses/>.
*
* For more information, please consult: <http://www.orbisgis.org/>
* or contact directly:
* info_at_ orbisgis.org
*/
package org.orbisgis.core.layerModel;
import com.vividsolutions.jts.geom.Envelope;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import org.orbisgis.core.renderer.se.Style;
/**
* Define Map Context properties as Java Beans, add the ability to
* listen for property change.
*/
public abstract class BeanMapContext implements MapContext {
//Listener container
protected transient final PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);
//Properties
protected Envelope boundingBox = null;
protected ILayer[] selectedLayers = new ILayer[]{};
protected Style[] selectedStyles = new Style[]{};
protected ILayer activeLayer = null;
protected ILayer layerModel;
protected int epsg_code = -1;
/**
* Get the value of the EPSG code
*
* @return the value of the EPSG code
*/
public int getCoordinateReferenceSystem() {
return epsg_code;
}
/**
* Set the value of the EPSG code
*
* @param coordinateReferenceSystem new value of the EPSG code
*/
public void setCoordinateReferenceSystem(int epsg) {
int oldEPSG_code = this.epsg_code;
this.epsg_code = oldEPSG_code;
propertyChangeSupport.firePropertyChange(PROP_COORDINATEREFERENCESYSTEM, oldEPSG_code, epsg);
}
/**
* Get the value of layerModel
*
* @return the value of layerModel
*/
@Override
public ILayer getLayerModel() {
return layerModel;
}
/**
* Set the value of layerModel
*
* @param layerModel new value of layerModel
*/
protected void setLayerModel(ILayer layerModel) {
ILayer oldLayerModel = this.layerModel;
this.layerModel = layerModel;
propertyChangeSupport.firePropertyChange(PROP_LAYERMODEL, oldLayerModel, layerModel);
}
/**
* Get the value of activeLayer
*
* @return the value of activeLayer
*/
@Override
public ILayer getActiveLayer() {
return activeLayer;
}
/**
* Set the value of activeLayer
*
* @param activeLayer new value of activeLayer
*/
@Override
public void setActiveLayer(ILayer activeLayer) {
ILayer oldActiveLayer = this.activeLayer;
this.activeLayer = activeLayer;
propertyChangeSupport.firePropertyChange(PROP_ACTIVELAYER, oldActiveLayer, activeLayer);
}
/**
* sourceManager.addSourceListener(listener); Get the value of
* selectedStyles
*
* @return the value of selectedStyles
*/
@Override
public Style[] getSelectedStyles() {
return selectedStyles;
}
/**
* Set the value of selectedStyles
*
* @param selectedStyles new value of selectedStyles
*/
public void setSelectedStyles(Style[] selectedStyles) {
Style[] oldSelectedStyles = this.selectedStyles;
this.selectedStyles = selectedStyles;
propertyChangeSupport.firePropertyChange(PROP_SELECTEDSTYLES, oldSelectedStyles, selectedStyles);
}
/**
* Get the value of selectedLayers
*
* @return the value of selectedLayers
*/
@Override
public ILayer[] getSelectedLayers() {
return selectedLayers;
}
/**
* Set the value of selectedLayers
*
* @param selectedLayers new value of selectedLayers
*/
@Override
public void setSelectedLayers(ILayer[] selectedLayers) {
ILayer[] oldSelectedLayers = this.selectedLayers;
this.selectedLayers = selectedLayers;
propertyChangeSupport.firePropertyChange(PROP_SELECTEDLAYERS, oldSelectedLayers, selectedLayers);
}
/**
* Get the value of boundingBox
*
* @return the value of boundingBox
*/
@Override
public Envelope getBoundingBox() {
return boundingBox;
}
/**
* Set the value of boundingBox
*
* @param boundingBox new value of boundingBox
*/
@Override
public void setBoundingBox(Envelope boundingBox) {
- if (!boundingBox.equals(this.boundingBox)) {
+ if (boundingBox != null && !boundingBox.equals(this.boundingBox)) {
Envelope oldBoundingBox = this.boundingBox;
this.boundingBox = boundingBox;
propertyChangeSupport.firePropertyChange(PROP_BOUNDINGBOX, oldBoundingBox, boundingBox);
}
}
/**
* Add a property-change listener for all properties.
* The listener is called for all properties.
* @param listener The PropertyChangeListener instance
* @note Use EventHandler.create to build the PropertyChangeListener instance
*/
@Override
public void addPropertyChangeListener(PropertyChangeListener listener) {
propertyChangeSupport.addPropertyChangeListener(listener);
}
/**
* Add a property-change listener for a specific property.
* The listener is called only when there is a change to
* the specified property.
* @param prop The static property name PROP_..
* @param listener The PropertyChangeListener instance
* @note Use EventHandler.create to build the PropertyChangeListener instance
*/
@Override
public void addPropertyChangeListener(String prop, PropertyChangeListener listener) {
propertyChangeSupport.addPropertyChangeListener(prop, listener);
}
/**
* Remove the specified listener from the list
* @param listener The listener instance
*/
@Override
public void removePropertyChangeListener(PropertyChangeListener listener) {
propertyChangeSupport.removePropertyChangeListener(listener);
}
/**
* Remove the specified listener for a specified property from the list
* @param prop The static property name PROP_..
* @param listener The listener instance
*/
@Override
public void removePropertyChangeListener(String prop, PropertyChangeListener listener) {
propertyChangeSupport.removePropertyChangeListener(prop, listener);
}
}
| true | true | public void setBoundingBox(Envelope boundingBox) {
if (!boundingBox.equals(this.boundingBox)) {
Envelope oldBoundingBox = this.boundingBox;
this.boundingBox = boundingBox;
propertyChangeSupport.firePropertyChange(PROP_BOUNDINGBOX, oldBoundingBox, boundingBox);
}
}
| public void setBoundingBox(Envelope boundingBox) {
if (boundingBox != null && !boundingBox.equals(this.boundingBox)) {
Envelope oldBoundingBox = this.boundingBox;
this.boundingBox = boundingBox;
propertyChangeSupport.firePropertyChange(PROP_BOUNDINGBOX, oldBoundingBox, boundingBox);
}
}
|
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/TaskDataManager.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/TaskDataManager.java
index e4c4673dd..7bf1c8a31 100644
--- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/TaskDataManager.java
+++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/TaskDataManager.java
@@ -1,264 +1,264 @@
/*******************************************************************************
* 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;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OptionalDataException;
import java.util.List;
import java.util.Map;
import org.eclipse.mylar.context.core.MylarStatusHandler;
import org.eclipse.mylar.tasks.core.AbstractAttributeFactory;
import org.eclipse.mylar.tasks.core.AbstractRepositoryConnector;
import org.eclipse.mylar.tasks.core.AbstractRepositoryTask;
import org.eclipse.mylar.tasks.core.RepositoryTaskData;
import org.eclipse.mylar.tasks.ui.TasksUiPlugin;
/**
* Manager for persisting RepositoryTaskData
*
* @author Rob Elves
*/
public class TaskDataManager {
private File file;
private OfflineDataStore dataStore;
public TaskDataManager(File file, boolean read) throws IOException, ClassNotFoundException {
this.file = file;
if (file.exists() && read) {
readFile();
} else {
dataStore = new OfflineDataStore();
}
}
/**
* Add a RepositoryTaskData to the offline reports file. Previously stored
* taskData is held and can be retrieved via getOldTaskData()
*/
public void put(RepositoryTaskData newEntry) {
synchronized (file) {
String handle = AbstractRepositoryTask.getHandle(newEntry.getRepositoryUrl(), newEntry.getId());
RepositoryTaskData moveToOld = dataStore.getNewDataMap().get(handle);
if (moveToOld != null) {
dataStore.getOldDataMap().put(handle, moveToOld);
}
dataStore.getNewDataMap().put(handle, newEntry);
}
}
/**
* Add a unsubmitted RepositoryTaskData to the offline reports file.
*/
public void putUnsubmitted(RepositoryTaskData newEntry) {
String handle = AbstractRepositoryTask.getHandle(newEntry.getRepositoryUrl(), newEntry.getId());
synchronized (file) {
dataStore.getUnsubmittedTaskData().put(handle, newEntry);
}
}
public Map<String, RepositoryTaskData> getUnsubmitted() {
return dataStore.getUnsubmittedTaskData();
}
/** save task data to offline file */
public void save() {
synchronized (file) {
ObjectOutputStream out = null;
try {
out = new ObjectOutputStream(new FileOutputStream(file));
out.writeObject(dataStore);
out.close();
} catch (IOException e) {
MylarStatusHandler.fail(e, "Could not write to offline reports file.", false);
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
// ignore
}
}
}
}
}
/**
* @return The id that the next new local task should use. Incremented each
* time this method is called.
*/
public String getNextLocalTaskId() {
return "" + dataStore.getNextTaskNumber();
}
/**
* @return The id of the next new unsubmitted task. Incremented each time
* this method is called.
*/
public String getNextUnsubmittedTaskId() {
return "" + dataStore.getNextUnsubmittedTaskNumber();
}
/**
* Returns the most recent copy of the task data.
*/
public RepositoryTaskData getTaskData(String handle) {
RepositoryTaskData data = dataStore.getNewDataMap().get(handle);
if (data == null) {
data = getOldTaskData(handle);
if (data != null) {
dataStore.getNewDataMap().put(handle, data);
}
}
return data;
}
/**
* Returns the most recent copy of the task data.
*/
public RepositoryTaskData getTaskData(String repositoryUrl, String taskId) {
String handle = AbstractRepositoryTask.getHandle(repositoryUrl, taskId);
return getTaskData(handle);
}
/**
* Returns the old copy if exists, null otherwise.
*/
public RepositoryTaskData getOldTaskData(String handle) {
return dataStore.getOldDataMap().get(handle);
}
/**
* Returns the old copy if exists, null otherwise.
*/
public RepositoryTaskData getOldTaskData(String repositoryUrl, String taskId) {
String handle = AbstractRepositoryTask.getHandle(repositoryUrl, taskId);
return getOldTaskData(handle);
}
/**
* Read the offline reports in from the file on disk
*
* @throws IOException
* Error opening or closing the offline reports file
* @throws ClassNotFoundException
* @throws ClassNotFoundException
* Error deserializing objects from the offline reports file
*/
private void readFile() throws IOException, ClassNotFoundException {
synchronized (file) {
ObjectInputStream in = null;
try {
in = new ObjectInputStream(new FileInputStream(file));
dataStore = (OfflineDataStore) in.readObject();
for (RepositoryTaskData taskData : dataStore.getNewDataMap().values()) {
updateAttributeFactory(taskData);
}
for (RepositoryTaskData taskData : dataStore.getOldDataMap().values()) {
updateAttributeFactory(taskData);
}
} catch (OptionalDataException e) {
in.close();
readOldOfflineFile();
} catch (ClassCastException e) {
in.close();
readOldOfflineFile();
} finally {
in.close();
}
}
}
/**
* Migrate from old offline task data format (pre 1.0)
*/
private void readOldOfflineFile() throws IOException {
ObjectInputStream in = null;
try {
in = new ObjectInputStream(new FileInputStream(file));
// read in each of the offline reports in the file
dataStore = new OfflineDataStore();
// get the number of offline reports in the file
int size = in.readInt();
dataStore.setNextTaskNumber(in.readInt());
for (int nX = 0; nX < size; nX++) {
RepositoryTaskData taskData = null;
taskData = (RepositoryTaskData) in.readObject();
if (taskData != null) {
updateAttributeFactory(taskData);
put(taskData);
}
}
} catch (Exception ex) {
dataStore = new OfflineDataStore();
- MylarStatusHandler.fail(ex, "Migration of offline task data failed.", false);
+ MylarStatusHandler.log(ex, "Could not migrate old offline data file, created new.");
} finally {
in.close();
}
}
private void updateAttributeFactory(RepositoryTaskData taskData) {
AbstractRepositoryConnector connector = TasksUiPlugin.getRepositoryManager().getRepositoryConnector(
taskData.getRepositoryKind());
if (connector != null && connector.getOfflineTaskHandler() != null) {
AbstractAttributeFactory factory = connector.getOfflineTaskHandler().getAttributeFactory();
if (factory != null) {
taskData.setAttributeFactory(factory);
}
}
}
/**
* Remove some bugs from the offline reports list
*
* @param indicesToRemove
* An array of the indicies of the bugs to be removed
*/
public void remove(List<RepositoryTaskData> dataToRemove) {
for (RepositoryTaskData repositoryTaskData : dataToRemove) {
remove(repositoryTaskData);
}
}
public void remove(RepositoryTaskData taskData) {
String handle = AbstractRepositoryTask.getHandle(taskData.getRepositoryUrl(), taskData.getId());
dataStore.getNewDataMap().remove(handle);
dataStore.getOldDataMap().remove(handle);
}
/**
* FOR TESTING ONLY.
*/
public void clear() {
dataStore = new OfflineDataStore();
}
/**
* FOR TESTING ONLY.
*/
public void reloadFromFile() throws IOException, ClassNotFoundException {
readFile();
}
}
| true | true | private void readOldOfflineFile() throws IOException {
ObjectInputStream in = null;
try {
in = new ObjectInputStream(new FileInputStream(file));
// read in each of the offline reports in the file
dataStore = new OfflineDataStore();
// get the number of offline reports in the file
int size = in.readInt();
dataStore.setNextTaskNumber(in.readInt());
for (int nX = 0; nX < size; nX++) {
RepositoryTaskData taskData = null;
taskData = (RepositoryTaskData) in.readObject();
if (taskData != null) {
updateAttributeFactory(taskData);
put(taskData);
}
}
} catch (Exception ex) {
dataStore = new OfflineDataStore();
MylarStatusHandler.fail(ex, "Migration of offline task data failed.", false);
} finally {
in.close();
}
}
| private void readOldOfflineFile() throws IOException {
ObjectInputStream in = null;
try {
in = new ObjectInputStream(new FileInputStream(file));
// read in each of the offline reports in the file
dataStore = new OfflineDataStore();
// get the number of offline reports in the file
int size = in.readInt();
dataStore.setNextTaskNumber(in.readInt());
for (int nX = 0; nX < size; nX++) {
RepositoryTaskData taskData = null;
taskData = (RepositoryTaskData) in.readObject();
if (taskData != null) {
updateAttributeFactory(taskData);
put(taskData);
}
}
} catch (Exception ex) {
dataStore = new OfflineDataStore();
MylarStatusHandler.log(ex, "Could not migrate old offline data file, created new.");
} finally {
in.close();
}
}
|
diff --git a/src/org/mozilla/javascript/NativeJavaMethod.java b/src/org/mozilla/javascript/NativeJavaMethod.java
index 857feaa9..4dd542ab 100644
--- a/src/org/mozilla/javascript/NativeJavaMethod.java
+++ b/src/org/mozilla/javascript/NativeJavaMethod.java
@@ -1,588 +1,603 @@
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1997-1999 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Norris Boyd
* Frank Mitchell
* Mike Shaver
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU Public License (the "GPL"), in which case the
* provisions of the GPL are applicable instead of those above.
* If you wish to allow use of your version of this file only
* under the terms of the GPL and not to allow others to use your
* version of this file under the NPL, indicate your decision by
* deleting the provisions above and replace them with the notice
* and other provisions required by the GPL. If you do not delete
* the provisions above, a recipient may use your version of this
* file under either the NPL or the GPL.
*/
package org.mozilla.javascript;
import java.lang.reflect.*;
/**
* This class reflects Java methods into the JavaScript environment. It
* handles overloading of methods, and method/field name conflicts.
* All NativeJavaMethods behave as JSRef `bound' methods, in that they
* always operate on the object underlying the original NativeJavaObject
* parent regardless of any reparenting that may occur.
*
* @author Mike Shaver
* @see NativeJavaArray
* @see NativeJavaPackage
* @see NativeJavaClass
*/
public class NativeJavaMethod extends NativeFunction implements Function {
public NativeJavaMethod() {
this.functionName = null;
}
public NativeJavaMethod(Method[] methods) {
this.methods = methods;
this.functionName = methods[0].getName();
}
public NativeJavaMethod(Method method, String name) {
this.methods = new Method[1];
this.methods[0] = method;
this.functionName = name;
}
public void add(Method method) {
if (functionName == null) {
functionName = method.getName();
} else if (!functionName.equals(method.getName())) {
throw new RuntimeException("internal method name mismatch");
}
// XXX a more intelligent growth algorithm would be nice
int len = methods == null ? 0 : methods.length;
Method[] newMeths = new Method[len + 1];
for (int i = 0; i < len; i++)
newMeths[i] = methods[i];
newMeths[len] = method;
methods = newMeths;
}
static String scriptSignature(Object value) {
if (value == null) {
return "null";
}
else {
Class type = value.getClass();
if (type == ScriptRuntime.UndefinedClass)
return "undefined";
if (type == ScriptRuntime.BooleanClass)
return "boolean";
if (type == ScriptRuntime.StringClass)
return "string";
if (ScriptRuntime.NumberClass.isAssignableFrom(type))
return "number";
if (value instanceof Wrapper) {
return ((Wrapper)value).unwrap().getClass().getName();
}
if (value instanceof Scriptable) {
if (value instanceof Function)
return "function";
return "object";
}
return javaSignature(type);
}
}
static String scriptSignature(Object[] values) {
StringBuffer sig = new StringBuffer();
for (int i = 0; i < values.length; i++) {
if (i != 0)
sig.append(',');
sig.append(scriptSignature(values[i]));
}
return sig.toString();
}
static String javaSignature(Class type) {
if (type == null) {
return "null";
}
else if (type.isArray()) {
return javaSignature(type.getComponentType()) + "[]";
}
return type.getName();
}
static String javaSignature(Class[] types) {
StringBuffer sig = new StringBuffer();
for (int i = 0; i < types.length; i++) {
if (i != 0)
sig.append(',');
sig.append(javaSignature(types[i]));
}
return sig.toString();
}
static String signature(Member member) {
Class paramTypes[];
if (member instanceof Method) {
paramTypes = ((Method) member).getParameterTypes();
return member.getName() + "(" + javaSignature(paramTypes) + ")";
}
else {
paramTypes = ((Constructor) member).getParameterTypes();
return "(" + javaSignature(paramTypes) + ")";
}
}
public String decompile(Context cx, int indent, boolean justbody) {
StringBuffer sb = new StringBuffer();
if (!justbody) {
sb.append("function ");
sb.append(getFunctionName());
sb.append("() {");
}
sb.append("/*\n");
toString(sb);
sb.append(justbody ? "*/\n" : "*/}\n");
return sb.toString();
}
public String toString() {
StringBuffer sb = new StringBuffer();
toString(sb);
return sb.toString();
}
private void toString(StringBuffer sb) {
for (int i=0; i < methods.length; i++) {
sb.append(javaSignature(methods[i].getReturnType()));
sb.append(' ');
sb.append(signature(methods[i]));
sb.append('\n');
}
}
public Object call(Context cx, Scriptable scope, Scriptable thisObj,
Object[] args)
throws JavaScriptException
{
// Find a method that matches the types given.
if (methods.length == 0) {
throw new RuntimeException("No methods defined for call");
}
Method meth = (Method) findFunction(methods, args);
if (meth == null) {
Class c = methods[0].getDeclaringClass();
String sig = c.getName() + "." + functionName + "(" +
scriptSignature(args) + ")";
throw Context.reportRuntimeError1("msg.java.no_such_method", sig);
}
// OPT: already retrieved in findFunction, so we should inline that
// OPT: or pass it back somehow
Class paramTypes[] = meth.getParameterTypes();
// First, we marshall the args.
for (int i = 0; i < args.length; i++) {
args[i] = NativeJavaObject.coerceType(paramTypes[i], args[i], true);
}
Object javaObject;
if (Modifier.isStatic(meth.getModifiers())) {
javaObject = null; // don't need an object
} else {
Scriptable o = thisObj;
while (!(o instanceof Wrapper)) {
o = o.getPrototype();
if (o == null) {
throw Context.reportRuntimeError1(
"msg.nonjava.method", functionName);
}
}
javaObject = ((Wrapper) o).unwrap();
}
try {
if (debug) {
printDebug("Calling ", meth, args);
}
Object retval;
try {
retval = meth.invoke(javaObject, args);
} catch (IllegalAccessException e) {
retval = retryIllegalAccessInvoke(meth, javaObject, args, e);
}
Class staticType = meth.getReturnType();
if (debug) {
Class actualType = (retval == null) ? null
: retval.getClass();
System.err.println(" ----- Returned " + retval +
" actual = " + actualType +
" expect = " + staticType);
}
Object wrapped = NativeJavaObject.wrap(scope, retval, staticType);
if (debug) {
Class actualType = (wrapped == null) ? null
: wrapped.getClass();
System.err.println(" ----- Wrapped as " + wrapped +
" class = " + actualType);
}
if (wrapped == Undefined.instance)
return wrapped;
if (wrapped == null && staticType == Void.TYPE)
return Undefined.instance;
return wrapped;
} catch (IllegalAccessException accessEx) {
throw Context.reportRuntimeError(
"While attempting to call \"" + meth.getName() +
"\" in class \"" + meth.getDeclaringClass().getName() +
"\" receieved " + accessEx.toString());
} catch (InvocationTargetException e) {
throw JavaScriptException.wrapException(scope, e);
}
}
static Object retryIllegalAccessInvoke(Method method, Object obj,
Object[] args,
IllegalAccessException illegalAccess)
throws IllegalAccessException, InvocationTargetException
{
if (Modifier.isPublic(method.getModifiers())) {
String name = method.getName();
Class[] parms = method.getParameterTypes();
Class c = method.getDeclaringClass();
Class[] intfs = c.getInterfaces();
for (int i=0; i < intfs.length; i++) {
c = intfs[i];
try {
Method m = c.getMethod(name, parms);
return m.invoke(obj, args);
} catch (NoSuchMethodException ex) {
continue;
} catch (IllegalAccessException ex) {
continue;
}
}
}
/**
* Due to a bug in Sun's VM, public methods in private
* classes are not accessible by default (Sun Bug #4071593).
* We have to explicitly set the method accessible
* via method.setAccessible(true) but we have to use
* reflection because the setAccessible() in Method is
* not available under jdk 1.1. We wait until a failure
* to retry to avoid the overhead of this call on cases
* that don't require it.
*/
if (method_setAccessible != null) {
Object[] args_wrapper = { Boolean.TRUE };
try {
method_setAccessible.invoke(method, args_wrapper);
}
catch (IllegalAccessException ex) { }
catch (IllegalArgumentException ex) { }
catch (InvocationTargetException ex) { }
return method.invoke(obj, args);
}
throw illegalAccess;
}
/**
* Find the correct function to call given the set of methods
* or constructors and the arguments.
* If no function can be found to call, return null.
*/
static Member findFunction(Member[] methodsOrCtors, Object[] args) {
if (methodsOrCtors.length == 0)
return null;
boolean hasMethods = methodsOrCtors[0] instanceof Method;
if (Context.useJSObject &&
NativeJavaObject.jsObjectClass != null)
{
try {
for (int i = 0; i < args.length; i++) {
if (NativeJavaObject.jsObjectClass.isInstance(args[i]))
args[i] = NativeJavaObject.jsObjectGetScriptable.invoke(
args[i], ScriptRuntime.emptyArgs);
}
}
catch (InvocationTargetException e) {
// Just abandon conversion from JSObject
}
catch (IllegalAccessException e) {
// Just abandon conversion from JSObject
}
+ } else {
+ // Wrapper support
+ for (int i=0; i < args.length; i++) {
+ Object arg = args[i];
+ if (arg instanceof Wrapper) {
+ arg = ((Wrapper)arg).unwrap();
+ if (!(arg instanceof Number)) {
+ // Since numbers are internally represented as
+ // java.lang.Double, etc. then java.lang.Doubles are
+ // distinquished by being wrapped. Thus don't unwrap
+ // here or we'll get overloading wrong.
+ args[i] = arg;
+ }
+ }
+ }
}
Member bestFit = null;
Class[] bestFitTypes = null;
java.util.Vector ambiguousMethods = null;
for (int i = 0; i < methodsOrCtors.length; i++) {
Member member = methodsOrCtors[i];
Class paramTypes[] = hasMethods
? ((Method) member).getParameterTypes()
: ((Constructor) member).getParameterTypes();
if (paramTypes.length != args.length) {
continue;
}
if (bestFitTypes == null) {
int j;
for (j = 0; j < paramTypes.length; j++) {
if (!NativeJavaObject.canConvert(args[j], paramTypes[j])) {
if (debug) printDebug("Rejecting (args can't convert) ",
member, args);
break;
}
}
if (j == paramTypes.length) {
if (debug) printDebug("Found ", member, args);
bestFit = member;
bestFitTypes = paramTypes;
}
}
else {
int preference =
NativeJavaMethod.preferSignature(args,
paramTypes,
bestFitTypes);
if (preference == PREFERENCE_AMBIGUOUS) {
if (debug) printDebug("Deferring ", member, args);
// add to "ambiguity list"
if (ambiguousMethods == null)
ambiguousMethods = new java.util.Vector();
ambiguousMethods.addElement(member);
}
else if (preference == PREFERENCE_FIRST_ARG) {
if (debug) printDebug("Substituting ", member, args);
bestFit = member;
bestFitTypes = paramTypes;
}
else {
if (preference == PREFERENCE_EQUAL &&
Modifier.isStatic(bestFit.getModifiers()) &&
bestFit.getDeclaringClass().isAssignableFrom(
member.getDeclaringClass()))
{
// On some JVMs, Class.getMethods will return all
// static methods of the class heirarchy, even if
// a derived class's parameters match exactly.
// We want to call the dervied class's method.
if (debug) printDebug("Rejecting (overridden static)",
member, args);
bestFit = member;
bestFitTypes = paramTypes;
} else {
if (debug) printDebug("Rejecting ", member, args);
}
}
}
}
if (ambiguousMethods == null)
return bestFit;
// Compare ambiguous methods with best fit, in case
// the current best fit removes the ambiguities.
for (int i = ambiguousMethods.size() - 1; i >= 0 ; i--) {
Member member = (Member)ambiguousMethods.elementAt(i);
Class paramTypes[] = hasMethods
? ((Method) member).getParameterTypes()
: ((Constructor) member).getParameterTypes();
int preference =
NativeJavaMethod.preferSignature(args,
paramTypes,
bestFitTypes);
if (preference == PREFERENCE_FIRST_ARG) {
if (debug) printDebug("Substituting ", member, args);
bestFit = member;
bestFitTypes = paramTypes;
ambiguousMethods.removeElementAt(i);
}
else if (preference == PREFERENCE_SECOND_ARG) {
if (debug) printDebug("Rejecting ", member, args);
ambiguousMethods.removeElementAt(i);
}
else {
if (debug) printDebug("UNRESOLVED: ", member, args);
}
}
if (ambiguousMethods.size() > 0) {
// PENDING: report remaining ambiguity
StringBuffer buf = new StringBuffer();
boolean isCtor = (bestFit instanceof Constructor);
ambiguousMethods.addElement(bestFit);
for (int i = 0; i < ambiguousMethods.size(); i++) {
if (i != 0) {
buf.append(", ");
}
Member member = (Member)ambiguousMethods.elementAt(i);
if (!isCtor) {
Class rtnType = ((Method)member).getReturnType();
buf.append(rtnType);
buf.append(' ');
}
buf.append(NativeJavaMethod.signature(member));
}
String errMsg;
if (isCtor) {
Object errArgs[] = {
bestFit.getName(),
NativeJavaMethod.scriptSignature(args),
buf.toString()
};
errMsg =
Context.getMessage("msg.constructor.ambiguous", errArgs);
}
else {
Object errArgs[] = {
bestFit.getDeclaringClass().getName(),
bestFit.getName(),
NativeJavaMethod.scriptSignature(args),
buf.toString()
};
errMsg = Context.getMessage("msg.method.ambiguous", errArgs);
}
throw
Context.reportRuntimeError(errMsg);
}
return bestFit;
}
/** Types are equal */
static final int PREFERENCE_EQUAL = 0;
static final int PREFERENCE_FIRST_ARG = 1;
static final int PREFERENCE_SECOND_ARG = 2;
/** No clear "easy" conversion */
static final int PREFERENCE_AMBIGUOUS = 3;
/**
* Determine which of two signatures is the closer fit.
* Returns one of PREFERENCE_EQUAL, PREFERENCE_FIRST_ARG,
* PREFERENCE_SECOND_ARG, or PREFERENCE_AMBIGUOUS.
*/
public static int preferSignature(Object[] args,
Class[] sig1, Class[] sig2)
{
int preference = 0;
for (int j = 0; j < args.length; j++) {
Class type1 = sig1[j];
Class type2 = sig2[j];
if (type1 == type2) {
continue;
}
preference |=
NativeJavaMethod.preferConversion(args[j],
type1,
type2);
if (preference == PREFERENCE_AMBIGUOUS) {
break;
}
}
return preference;
}
/**
* Determine which of two types is the easier conversion.
* Returns one of PREFERENCE_EQUAL, PREFERENCE_FIRST_ARG,
* PREFERENCE_SECOND_ARG, or PREFERENCE_AMBIGUOUS.
*/
public static int preferConversion(Object fromObj,
Class toClass1, Class toClass2) {
int rank1 =
NativeJavaObject.getConversionWeight(fromObj, toClass1);
int rank2 =
NativeJavaObject.getConversionWeight(fromObj, toClass2);
if (rank1 == NativeJavaObject.CONVERSION_NONTRIVIAL &&
rank2 == NativeJavaObject.CONVERSION_NONTRIVIAL) {
if (toClass1.isAssignableFrom(toClass2)) {
return PREFERENCE_SECOND_ARG;
}
else if (toClass2.isAssignableFrom(toClass1)) {
return PREFERENCE_FIRST_ARG;
}
}
else {
if (rank1 < rank2) {
return PREFERENCE_FIRST_ARG;
}
else if (rank1 > rank2) {
return PREFERENCE_SECOND_ARG;
}
}
return PREFERENCE_AMBIGUOUS;
}
Method[] getMethods() {
return methods;
}
// Utility to call Class.getMethod and get null instead of thrown exceptions
private static Method getMethod(Class cl, String name, Class[] signature) {
try {
return cl.getMethod(name, signature);
}
catch (NoSuchMethodException ex) { }
catch (SecurityException ex) { }
return null;
}
private static final boolean debug = false;
private static void printDebug(String msg, Member member, Object[] args) {
if (debug) {
System.err.println(" ----- " + msg +
member.getDeclaringClass().getName() +
"." + signature(member) +
" for arguments (" + scriptSignature(args) + ")");
}
}
Method methods[];
private static final Method method_setAccessible
= getMethod(Method.class,
"setAccessible", new Class[] { Boolean.TYPE });
}
| true | true | static Member findFunction(Member[] methodsOrCtors, Object[] args) {
if (methodsOrCtors.length == 0)
return null;
boolean hasMethods = methodsOrCtors[0] instanceof Method;
if (Context.useJSObject &&
NativeJavaObject.jsObjectClass != null)
{
try {
for (int i = 0; i < args.length; i++) {
if (NativeJavaObject.jsObjectClass.isInstance(args[i]))
args[i] = NativeJavaObject.jsObjectGetScriptable.invoke(
args[i], ScriptRuntime.emptyArgs);
}
}
catch (InvocationTargetException e) {
// Just abandon conversion from JSObject
}
catch (IllegalAccessException e) {
// Just abandon conversion from JSObject
}
}
Member bestFit = null;
Class[] bestFitTypes = null;
java.util.Vector ambiguousMethods = null;
for (int i = 0; i < methodsOrCtors.length; i++) {
Member member = methodsOrCtors[i];
Class paramTypes[] = hasMethods
? ((Method) member).getParameterTypes()
: ((Constructor) member).getParameterTypes();
if (paramTypes.length != args.length) {
continue;
}
if (bestFitTypes == null) {
int j;
for (j = 0; j < paramTypes.length; j++) {
if (!NativeJavaObject.canConvert(args[j], paramTypes[j])) {
if (debug) printDebug("Rejecting (args can't convert) ",
member, args);
break;
}
}
if (j == paramTypes.length) {
if (debug) printDebug("Found ", member, args);
bestFit = member;
bestFitTypes = paramTypes;
}
}
else {
int preference =
NativeJavaMethod.preferSignature(args,
paramTypes,
bestFitTypes);
if (preference == PREFERENCE_AMBIGUOUS) {
if (debug) printDebug("Deferring ", member, args);
// add to "ambiguity list"
if (ambiguousMethods == null)
ambiguousMethods = new java.util.Vector();
ambiguousMethods.addElement(member);
}
else if (preference == PREFERENCE_FIRST_ARG) {
if (debug) printDebug("Substituting ", member, args);
bestFit = member;
bestFitTypes = paramTypes;
}
else {
if (preference == PREFERENCE_EQUAL &&
Modifier.isStatic(bestFit.getModifiers()) &&
bestFit.getDeclaringClass().isAssignableFrom(
member.getDeclaringClass()))
{
// On some JVMs, Class.getMethods will return all
// static methods of the class heirarchy, even if
// a derived class's parameters match exactly.
// We want to call the dervied class's method.
if (debug) printDebug("Rejecting (overridden static)",
member, args);
bestFit = member;
bestFitTypes = paramTypes;
} else {
if (debug) printDebug("Rejecting ", member, args);
}
}
}
}
if (ambiguousMethods == null)
return bestFit;
// Compare ambiguous methods with best fit, in case
// the current best fit removes the ambiguities.
for (int i = ambiguousMethods.size() - 1; i >= 0 ; i--) {
Member member = (Member)ambiguousMethods.elementAt(i);
Class paramTypes[] = hasMethods
? ((Method) member).getParameterTypes()
: ((Constructor) member).getParameterTypes();
int preference =
NativeJavaMethod.preferSignature(args,
paramTypes,
bestFitTypes);
if (preference == PREFERENCE_FIRST_ARG) {
if (debug) printDebug("Substituting ", member, args);
bestFit = member;
bestFitTypes = paramTypes;
ambiguousMethods.removeElementAt(i);
}
else if (preference == PREFERENCE_SECOND_ARG) {
if (debug) printDebug("Rejecting ", member, args);
ambiguousMethods.removeElementAt(i);
}
else {
if (debug) printDebug("UNRESOLVED: ", member, args);
}
}
if (ambiguousMethods.size() > 0) {
// PENDING: report remaining ambiguity
StringBuffer buf = new StringBuffer();
boolean isCtor = (bestFit instanceof Constructor);
ambiguousMethods.addElement(bestFit);
for (int i = 0; i < ambiguousMethods.size(); i++) {
if (i != 0) {
buf.append(", ");
}
Member member = (Member)ambiguousMethods.elementAt(i);
if (!isCtor) {
Class rtnType = ((Method)member).getReturnType();
buf.append(rtnType);
buf.append(' ');
}
buf.append(NativeJavaMethod.signature(member));
}
String errMsg;
if (isCtor) {
Object errArgs[] = {
bestFit.getName(),
NativeJavaMethod.scriptSignature(args),
buf.toString()
};
errMsg =
Context.getMessage("msg.constructor.ambiguous", errArgs);
}
else {
Object errArgs[] = {
bestFit.getDeclaringClass().getName(),
bestFit.getName(),
NativeJavaMethod.scriptSignature(args),
buf.toString()
};
errMsg = Context.getMessage("msg.method.ambiguous", errArgs);
}
throw
Context.reportRuntimeError(errMsg);
}
return bestFit;
}
| static Member findFunction(Member[] methodsOrCtors, Object[] args) {
if (methodsOrCtors.length == 0)
return null;
boolean hasMethods = methodsOrCtors[0] instanceof Method;
if (Context.useJSObject &&
NativeJavaObject.jsObjectClass != null)
{
try {
for (int i = 0; i < args.length; i++) {
if (NativeJavaObject.jsObjectClass.isInstance(args[i]))
args[i] = NativeJavaObject.jsObjectGetScriptable.invoke(
args[i], ScriptRuntime.emptyArgs);
}
}
catch (InvocationTargetException e) {
// Just abandon conversion from JSObject
}
catch (IllegalAccessException e) {
// Just abandon conversion from JSObject
}
} else {
// Wrapper support
for (int i=0; i < args.length; i++) {
Object arg = args[i];
if (arg instanceof Wrapper) {
arg = ((Wrapper)arg).unwrap();
if (!(arg instanceof Number)) {
// Since numbers are internally represented as
// java.lang.Double, etc. then java.lang.Doubles are
// distinquished by being wrapped. Thus don't unwrap
// here or we'll get overloading wrong.
args[i] = arg;
}
}
}
}
Member bestFit = null;
Class[] bestFitTypes = null;
java.util.Vector ambiguousMethods = null;
for (int i = 0; i < methodsOrCtors.length; i++) {
Member member = methodsOrCtors[i];
Class paramTypes[] = hasMethods
? ((Method) member).getParameterTypes()
: ((Constructor) member).getParameterTypes();
if (paramTypes.length != args.length) {
continue;
}
if (bestFitTypes == null) {
int j;
for (j = 0; j < paramTypes.length; j++) {
if (!NativeJavaObject.canConvert(args[j], paramTypes[j])) {
if (debug) printDebug("Rejecting (args can't convert) ",
member, args);
break;
}
}
if (j == paramTypes.length) {
if (debug) printDebug("Found ", member, args);
bestFit = member;
bestFitTypes = paramTypes;
}
}
else {
int preference =
NativeJavaMethod.preferSignature(args,
paramTypes,
bestFitTypes);
if (preference == PREFERENCE_AMBIGUOUS) {
if (debug) printDebug("Deferring ", member, args);
// add to "ambiguity list"
if (ambiguousMethods == null)
ambiguousMethods = new java.util.Vector();
ambiguousMethods.addElement(member);
}
else if (preference == PREFERENCE_FIRST_ARG) {
if (debug) printDebug("Substituting ", member, args);
bestFit = member;
bestFitTypes = paramTypes;
}
else {
if (preference == PREFERENCE_EQUAL &&
Modifier.isStatic(bestFit.getModifiers()) &&
bestFit.getDeclaringClass().isAssignableFrom(
member.getDeclaringClass()))
{
// On some JVMs, Class.getMethods will return all
// static methods of the class heirarchy, even if
// a derived class's parameters match exactly.
// We want to call the dervied class's method.
if (debug) printDebug("Rejecting (overridden static)",
member, args);
bestFit = member;
bestFitTypes = paramTypes;
} else {
if (debug) printDebug("Rejecting ", member, args);
}
}
}
}
if (ambiguousMethods == null)
return bestFit;
// Compare ambiguous methods with best fit, in case
// the current best fit removes the ambiguities.
for (int i = ambiguousMethods.size() - 1; i >= 0 ; i--) {
Member member = (Member)ambiguousMethods.elementAt(i);
Class paramTypes[] = hasMethods
? ((Method) member).getParameterTypes()
: ((Constructor) member).getParameterTypes();
int preference =
NativeJavaMethod.preferSignature(args,
paramTypes,
bestFitTypes);
if (preference == PREFERENCE_FIRST_ARG) {
if (debug) printDebug("Substituting ", member, args);
bestFit = member;
bestFitTypes = paramTypes;
ambiguousMethods.removeElementAt(i);
}
else if (preference == PREFERENCE_SECOND_ARG) {
if (debug) printDebug("Rejecting ", member, args);
ambiguousMethods.removeElementAt(i);
}
else {
if (debug) printDebug("UNRESOLVED: ", member, args);
}
}
if (ambiguousMethods.size() > 0) {
// PENDING: report remaining ambiguity
StringBuffer buf = new StringBuffer();
boolean isCtor = (bestFit instanceof Constructor);
ambiguousMethods.addElement(bestFit);
for (int i = 0; i < ambiguousMethods.size(); i++) {
if (i != 0) {
buf.append(", ");
}
Member member = (Member)ambiguousMethods.elementAt(i);
if (!isCtor) {
Class rtnType = ((Method)member).getReturnType();
buf.append(rtnType);
buf.append(' ');
}
buf.append(NativeJavaMethod.signature(member));
}
String errMsg;
if (isCtor) {
Object errArgs[] = {
bestFit.getName(),
NativeJavaMethod.scriptSignature(args),
buf.toString()
};
errMsg =
Context.getMessage("msg.constructor.ambiguous", errArgs);
}
else {
Object errArgs[] = {
bestFit.getDeclaringClass().getName(),
bestFit.getName(),
NativeJavaMethod.scriptSignature(args),
buf.toString()
};
errMsg = Context.getMessage("msg.method.ambiguous", errArgs);
}
throw
Context.reportRuntimeError(errMsg);
}
return bestFit;
}
|
diff --git a/jung-visualization/src/main/java/edu/uci/ics/jung/visualization/renderers/BasicEdgeRenderer.java b/jung-visualization/src/main/java/edu/uci/ics/jung/visualization/renderers/BasicEdgeRenderer.java
index f3efed59..ceeb44bb 100644
--- a/jung-visualization/src/main/java/edu/uci/ics/jung/visualization/renderers/BasicEdgeRenderer.java
+++ b/jung-visualization/src/main/java/edu/uci/ics/jung/visualization/renderers/BasicEdgeRenderer.java
@@ -1,476 +1,476 @@
/*
* Copyright (c) 2005, the JUNG Project and the Regents of the University of
* California All rights reserved.
*
* This software is open-source under the BSD license; see either "license.txt"
* or http://jung.sourceforge.net/license.txt for a description.
*
* Created on Aug 23, 2005
*/
package edu.uci.ics.jung.visualization.renderers;
import java.awt.Dimension;
import java.awt.Paint;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.geom.AffineTransform;
import java.awt.geom.GeneralPath;
import java.awt.geom.Line2D;
import java.awt.geom.PathIterator;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import javax.swing.JComponent;
import edu.uci.ics.jung.algorithms.layout.Layout;
import edu.uci.ics.jung.algorithms.util.Context;
import edu.uci.ics.jung.graph.Graph;
import edu.uci.ics.jung.graph.util.EdgeIndexFunction;
import edu.uci.ics.jung.graph.util.EdgeType;
import edu.uci.ics.jung.graph.util.Pair;
import edu.uci.ics.jung.visualization.Layer;
import edu.uci.ics.jung.visualization.RenderContext;
import edu.uci.ics.jung.visualization.decorators.EdgeShape;
import edu.uci.ics.jung.visualization.decorators.EdgeShape.IndexedRendering;
import edu.uci.ics.jung.visualization.transform.LensTransformer;
import edu.uci.ics.jung.visualization.transform.MutableTransformer;
import edu.uci.ics.jung.visualization.transform.shape.GraphicsDecorator;
public class BasicEdgeRenderer<V,E> implements Renderer.Edge<V,E> {
public void paintEdge(RenderContext<V,E> rc, Layout<V, E> layout, E e) {
GraphicsDecorator g2d = rc.getGraphicsContext();
Graph<V,E> graph = layout.getGraph();
if (!rc.getEdgeIncludePredicate().evaluate(Context.<Graph<V,E>,E>getInstance(graph,e)))
return;
// don't draw edge if either incident vertex is not drawn
Pair<V> endpoints = graph.getEndpoints(e);
V v1 = endpoints.getFirst();
V v2 = endpoints.getSecond();
if (!rc.getVertexIncludePredicate().evaluate(Context.<Graph<V,E>,V>getInstance(graph,v1)) ||
!rc.getVertexIncludePredicate().evaluate(Context.<Graph<V,E>,V>getInstance(graph,v2)))
return;
Stroke new_stroke = rc.getEdgeStrokeTransformer().transform(e);
Stroke old_stroke = g2d.getStroke();
if (new_stroke != null)
g2d.setStroke(new_stroke);
drawSimpleEdge(rc, layout, e);
// restore paint and stroke
if (new_stroke != null)
g2d.setStroke(old_stroke);
}
/**
* Draws the edge <code>e</code>, whose endpoints are at <code>(x1,y1)</code>
* and <code>(x2,y2)</code>, on the graphics context <code>g</code>.
* The <code>Shape</code> provided by the <code>EdgeShapeFunction</code> instance
* is scaled in the x-direction so that its width is equal to the distance between
* <code>(x1,y1)</code> and <code>(x2,y2)</code>.
*/
protected void drawSimpleEdge(RenderContext<V,E> rc, Layout<V,E> layout, E e) {
GraphicsDecorator g = rc.getGraphicsContext();
Graph<V,E> graph = layout.getGraph();
Pair<V> endpoints = graph.getEndpoints(e);
V v1 = endpoints.getFirst();
V v2 = endpoints.getSecond();
Point2D p1 = layout.transform(v1);
Point2D p2 = layout.transform(v2);
p1 = rc.getMultiLayerTransformer().transform(Layer.LAYOUT, p1);
p2 = rc.getMultiLayerTransformer().transform(Layer.LAYOUT, p2);
float x1 = (float) p1.getX();
float y1 = (float) p1.getY();
float x2 = (float) p2.getX();
float y2 = (float) p2.getY();
boolean isLoop = v1.equals(v2);
Shape s2 = rc.getVertexShapeTransformer().transform(v2);
Shape edgeShape = rc.getEdgeShapeTransformer().transform(Context.<Graph<V,E>,E>getInstance(graph, e));
boolean edgeHit = true;
boolean arrowHit = true;
Rectangle deviceRectangle = null;
JComponent vv = rc.getScreenDevice();
if(vv != null) {
Dimension d = vv.getSize();
deviceRectangle = new Rectangle(0,0,d.width,d.height);
}
AffineTransform xform = AffineTransform.getTranslateInstance(x1, y1);
if(isLoop) {
// this is a self-loop. scale it is larger than the vertex
// it decorates and translate it so that its nadir is
// at the center of the vertex.
Rectangle2D s2Bounds = s2.getBounds2D();
xform.scale(s2Bounds.getWidth(),s2Bounds.getHeight());
xform.translate(0, -edgeShape.getBounds2D().getWidth()/2);
} else if(rc.getEdgeShapeTransformer() instanceof EdgeShape.Orthogonal) {
float dx = x2-x1;
float dy = y2-y1;
int index = 0;
if(rc.getEdgeShapeTransformer() instanceof IndexedRendering) {
EdgeIndexFunction<V,E> peif =
- ((IndexedRendering)rc.getEdgeShapeTransformer()).getEdgeIndexFunction();
+ ((IndexedRendering<V,E>)rc.getEdgeShapeTransformer()).getEdgeIndexFunction();
index = peif.getIndex(graph, e);
index *= 20;
}
GeneralPath gp = new GeneralPath();
gp.moveTo(0,0);// the xform will do the translation to x1,y1
if(x1 > x2) {
if(y1 > y2) {
gp.lineTo(0, index);
gp.lineTo(dx-index, index);
gp.lineTo(dx-index, dy);
gp.lineTo(dx, dy);
} else {
gp.lineTo(0, -index);
gp.lineTo(dx-index, -index);
gp.lineTo(dx-index, dy);
gp.lineTo(dx, dy);
}
} else {
if(y1 > y2) {
gp.lineTo(0, index);
gp.lineTo(dx+index, index);
gp.lineTo(dx+index, dy);
gp.lineTo(dx, dy);
} else {
gp.lineTo(0, -index);
gp.lineTo(dx+index, -index);
gp.lineTo(dx+index, dy);
gp.lineTo(dx, dy);
}
}
edgeShape = gp;
} else {
// this is a normal edge. Rotate it to the angle between
// vertex endpoints, then scale it to the distance between
// the vertices
float dx = x2-x1;
float dy = y2-y1;
float thetaRadians = (float) Math.atan2(dy, dx);
xform.rotate(thetaRadians);
float dist = (float) Math.sqrt(dx*dx + dy*dy);
xform.scale(dist, 1.0);
}
edgeShape = xform.createTransformedShape(edgeShape);
MutableTransformer vt = rc.getMultiLayerTransformer().getTransformer(Layer.VIEW);
if(vt instanceof LensTransformer) {
vt = ((LensTransformer)vt).getDelegate();
}
edgeHit = vt.transform(edgeShape).intersects(deviceRectangle);
if(edgeHit == true) {
Paint oldPaint = g.getPaint();
// get Paints for filling and drawing
// (filling is done first so that drawing and label use same Paint)
Paint fill_paint = rc.getEdgeFillPaintTransformer().transform(e);
if (fill_paint != null)
{
g.setPaint(fill_paint);
g.fill(edgeShape);
}
Paint draw_paint = rc.getEdgeDrawPaintTransformer().transform(e);
if (draw_paint != null)
{
g.setPaint(draw_paint);
g.draw(edgeShape);
}
float scalex = (float)g.getTransform().getScaleX();
float scaley = (float)g.getTransform().getScaleY();
// see if arrows are too small to bother drawing
if(scalex < .3 || scaley < .3) return;
if (rc.getEdgeArrowPredicate().evaluate(Context.<Graph<V,E>,E>getInstance(graph, e))) {
Stroke new_stroke = rc.getEdgeArrowStrokeTransformer().transform(e);
Stroke old_stroke = g.getStroke();
if (new_stroke != null)
g.setStroke(new_stroke);
Shape destVertexShape =
rc.getVertexShapeTransformer().transform(graph.getEndpoints(e).getSecond());
AffineTransform xf = AffineTransform.getTranslateInstance(x2, y2);
destVertexShape = xf.createTransformedShape(destVertexShape);
arrowHit = rc.getMultiLayerTransformer().getTransformer(Layer.VIEW).transform(destVertexShape).intersects(deviceRectangle);
if(arrowHit) {
AffineTransform at =
getArrowTransform(rc, new GeneralPath(edgeShape), destVertexShape);
if(at == null) return;
Shape arrow = rc.getEdgeArrowTransformer().transform(Context.<Graph<V,E>,E>getInstance(graph, e));
arrow = at.createTransformedShape(arrow);
g.setPaint(rc.getArrowFillPaintTransformer().transform(e));
g.fill(arrow);
g.setPaint(rc.getArrowDrawPaintTransformer().transform(e));
g.draw(arrow);
}
if (graph.getEdgeType(e) == EdgeType.UNDIRECTED) {
Shape vertexShape =
rc.getVertexShapeTransformer().transform(graph.getEndpoints(e).getFirst());
xf = AffineTransform.getTranslateInstance(x1, y1);
vertexShape = xf.createTransformedShape(vertexShape);
arrowHit = rc.getMultiLayerTransformer().getTransformer(Layer.VIEW).transform(vertexShape).intersects(deviceRectangle);
if(arrowHit) {
AffineTransform at = getReverseArrowTransform(rc, new GeneralPath(edgeShape), vertexShape, !isLoop);
if(at == null) return;
Shape arrow = rc.getEdgeArrowTransformer().transform(Context.<Graph<V,E>,E>getInstance(graph, e));
arrow = at.createTransformedShape(arrow);
g.setPaint(rc.getArrowFillPaintTransformer().transform(e));
g.fill(arrow);
g.setPaint(rc.getArrowDrawPaintTransformer().transform(e));
g.draw(arrow);
}
}
// restore paint and stroke
if (new_stroke != null)
g.setStroke(old_stroke);
}
- // use existing paint for text if no draw paint specified
- if (draw_paint == null)
- g.setPaint(oldPaint);
+// // use existing paint for text if no draw paint specified
+// if (draw_paint == null)
+// g.setPaint(oldPaint);
// restore old paint
g.setPaint(oldPaint);
}
}
/**
* Returns a transform to position the arrowhead on this edge shape at the
* point where it intersects the passed vertex shape.
*/
public AffineTransform getArrowTransform(RenderContext<V,E> rc, GeneralPath edgeShape, Shape vertexShape) {
float[] seg = new float[6];
Point2D p1=null;
Point2D p2=null;
AffineTransform at = new AffineTransform();
// when the PathIterator is done, switch to the line-subdivide
// method to get the arrowhead closer.
for(PathIterator i=edgeShape.getPathIterator(null,1); !i.isDone(); i.next()) {
int ret = i.currentSegment(seg);
if(ret == PathIterator.SEG_MOVETO) {
p2 = new Point2D.Float(seg[0],seg[1]);
} else if(ret == PathIterator.SEG_LINETO) {
p1 = p2;
p2 = new Point2D.Float(seg[0],seg[1]);
if(vertexShape.contains(p2)) {
at = getArrowTransform(rc, new Line2D.Float(p1,p2),vertexShape);
break;
}
}
}
return at;
}
/**
* Returns a transform to position the arrowhead on this edge shape at the
* point where it intersects the passed vertex shape.
*/
public AffineTransform getReverseArrowTransform(RenderContext<V,E> rc, GeneralPath edgeShape, Shape vertexShape) {
return getReverseArrowTransform(rc, edgeShape, vertexShape, true);
}
/**
* <p>Returns a transform to position the arrowhead on this edge shape at the
* point where it intersects the passed vertex shape.</p>
*
* <p>The Loop edge is a special case because its staring point is not inside
* the vertex. The passedGo flag handles this case.</p>
*
* @param edgeShape
* @param vertexShape
* @param passedGo - used only for Loop edges
*/
public AffineTransform getReverseArrowTransform(RenderContext<V,E> rc, GeneralPath edgeShape, Shape vertexShape,
boolean passedGo) {
float[] seg = new float[6];
Point2D p1=null;
Point2D p2=null;
AffineTransform at = new AffineTransform();
for(PathIterator i=edgeShape.getPathIterator(null,1); !i.isDone(); i.next()) {
int ret = i.currentSegment(seg);
if(ret == PathIterator.SEG_MOVETO) {
p2 = new Point2D.Float(seg[0],seg[1]);
} else if(ret == PathIterator.SEG_LINETO) {
p1 = p2;
p2 = new Point2D.Float(seg[0],seg[1]);
if(passedGo == false && vertexShape.contains(p2)) {
passedGo = true;
} else if(passedGo==true &&
vertexShape.contains(p2)==false) {
at = getReverseArrowTransform(rc, new Line2D.Float(p1,p2),vertexShape);
break;
}
}
}
return at;
}
/**
* This is used for the arrow of a directed and for one of the
* arrows for non-directed edges
* Get a transform to place the arrow shape on the passed edge at the
* point where it intersects the passed shape
* @param edgeShape
* @param vertexShape
* @return
*/
public AffineTransform getArrowTransform(RenderContext<V,E> rc, Line2D edgeShape, Shape vertexShape) {
float dx = (float) (edgeShape.getX1()-edgeShape.getX2());
float dy = (float) (edgeShape.getY1()-edgeShape.getY2());
// iterate over the line until the edge shape will place the
// arrowhead closer than 'arrowGap' to the vertex shape boundary
while((dx*dx+dy*dy) > rc.getArrowPlacementTolerance()) {
try {
edgeShape = getLastOutsideSegment(edgeShape, vertexShape);
} catch(IllegalArgumentException e) {
System.err.println(e.toString());
return null;
}
dx = (float) (edgeShape.getX1()-edgeShape.getX2());
dy = (float) (edgeShape.getY1()-edgeShape.getY2());
}
double atheta = Math.atan2(dx,dy)+Math.PI/2;
AffineTransform at =
AffineTransform.getTranslateInstance(edgeShape.getX1(), edgeShape.getY1());
at.rotate(-atheta);
return at;
}
/**
* This is used for the reverse-arrow of a non-directed edge
* get a transform to place the arrow shape on the passed edge at the
* point where it intersects the passed shape
* @param edgeShape
* @param vertexShape
* @return
*/
protected AffineTransform getReverseArrowTransform(RenderContext<V,E> rc, Line2D edgeShape, Shape vertexShape) {
float dx = (float) (edgeShape.getX1()-edgeShape.getX2());
float dy = (float) (edgeShape.getY1()-edgeShape.getY2());
// iterate over the line until the edge shape will place the
// arrowhead closer than 'arrowGap' to the vertex shape boundary
while((dx*dx+dy*dy) > rc.getArrowPlacementTolerance()) {
try {
edgeShape = getFirstOutsideSegment(edgeShape, vertexShape);
} catch(IllegalArgumentException e) {
System.err.println(e.toString());
return null;
}
dx = (float) (edgeShape.getX1()-edgeShape.getX2());
dy = (float) (edgeShape.getY1()-edgeShape.getY2());
}
// calculate the angle for the arrowhead
double atheta = Math.atan2(dx,dy)-Math.PI/2;
AffineTransform at = AffineTransform.getTranslateInstance(edgeShape.getX1(),edgeShape.getY1());
at.rotate(-atheta);
return at;
}
/**
* Passed Line's point2 must be inside the passed shape or
* an IllegalArgumentException is thrown
* @param line line to subdivide
* @param shape shape to compare with line
* @return a line that intersects the shape boundary
* @throws IllegalArgumentException if the passed line's point1 is not inside the shape
*/
protected Line2D getLastOutsideSegment(Line2D line, Shape shape) {
if(shape.contains(line.getP2())==false) {
String errorString =
"line end point: "+line.getP2()+" is not contained in shape: "+shape.getBounds2D();
throw new IllegalArgumentException(errorString);
//return null;
}
Line2D left = new Line2D.Double();
Line2D right = new Line2D.Double();
// subdivide the line until its left segment intersects
// the shape boundary
do {
subdivide(line, left, right);
line = right;
} while(shape.contains(line.getP1())==false);
// now that right is completely inside shape,
// return left, which must be partially outside
return left;
}
/**
* Passed Line's point1 must be inside the passed shape or
* an IllegalArgumentException is thrown
* @param line line to subdivide
* @param shape shape to compare with line
* @return a line that intersects the shape boundary
* @throws IllegalArgumentException if the passed line's point1 is not inside the shape
*/
protected Line2D getFirstOutsideSegment(Line2D line, Shape shape) {
if(shape.contains(line.getP1())==false) {
String errorString =
"line start point: "+line.getP1()+" is not contained in shape: "+shape.getBounds2D();
throw new IllegalArgumentException(errorString);
}
Line2D left = new Line2D.Float();
Line2D right = new Line2D.Float();
// subdivide the line until its right side intersects the
// shape boundary
do {
subdivide(line, left, right);
line = left;
} while(shape.contains(line.getP2())==false);
// now that left is completely inside shape,
// return right, which must be partially outside
return right;
}
/**
* divide a Line2D into 2 new Line2Ds that are returned
* in the passed left and right instances, if non-null
* @param src the line to divide
* @param left the left side, or null
* @param right the right side, or null
*/
protected void subdivide(Line2D src,
Line2D left,
Line2D right) {
double x1 = src.getX1();
double y1 = src.getY1();
double x2 = src.getX2();
double y2 = src.getY2();
double mx = x1 + (x2-x1)/2.0;
double my = y1 + (y2-y1)/2.0;
if (left != null) {
left.setLine(x1, y1, mx, my);
}
if (right != null) {
right.setLine(mx, my, x2, y2);
}
}
}
| false | true | protected void drawSimpleEdge(RenderContext<V,E> rc, Layout<V,E> layout, E e) {
GraphicsDecorator g = rc.getGraphicsContext();
Graph<V,E> graph = layout.getGraph();
Pair<V> endpoints = graph.getEndpoints(e);
V v1 = endpoints.getFirst();
V v2 = endpoints.getSecond();
Point2D p1 = layout.transform(v1);
Point2D p2 = layout.transform(v2);
p1 = rc.getMultiLayerTransformer().transform(Layer.LAYOUT, p1);
p2 = rc.getMultiLayerTransformer().transform(Layer.LAYOUT, p2);
float x1 = (float) p1.getX();
float y1 = (float) p1.getY();
float x2 = (float) p2.getX();
float y2 = (float) p2.getY();
boolean isLoop = v1.equals(v2);
Shape s2 = rc.getVertexShapeTransformer().transform(v2);
Shape edgeShape = rc.getEdgeShapeTransformer().transform(Context.<Graph<V,E>,E>getInstance(graph, e));
boolean edgeHit = true;
boolean arrowHit = true;
Rectangle deviceRectangle = null;
JComponent vv = rc.getScreenDevice();
if(vv != null) {
Dimension d = vv.getSize();
deviceRectangle = new Rectangle(0,0,d.width,d.height);
}
AffineTransform xform = AffineTransform.getTranslateInstance(x1, y1);
if(isLoop) {
// this is a self-loop. scale it is larger than the vertex
// it decorates and translate it so that its nadir is
// at the center of the vertex.
Rectangle2D s2Bounds = s2.getBounds2D();
xform.scale(s2Bounds.getWidth(),s2Bounds.getHeight());
xform.translate(0, -edgeShape.getBounds2D().getWidth()/2);
} else if(rc.getEdgeShapeTransformer() instanceof EdgeShape.Orthogonal) {
float dx = x2-x1;
float dy = y2-y1;
int index = 0;
if(rc.getEdgeShapeTransformer() instanceof IndexedRendering) {
EdgeIndexFunction<V,E> peif =
((IndexedRendering)rc.getEdgeShapeTransformer()).getEdgeIndexFunction();
index = peif.getIndex(graph, e);
index *= 20;
}
GeneralPath gp = new GeneralPath();
gp.moveTo(0,0);// the xform will do the translation to x1,y1
if(x1 > x2) {
if(y1 > y2) {
gp.lineTo(0, index);
gp.lineTo(dx-index, index);
gp.lineTo(dx-index, dy);
gp.lineTo(dx, dy);
} else {
gp.lineTo(0, -index);
gp.lineTo(dx-index, -index);
gp.lineTo(dx-index, dy);
gp.lineTo(dx, dy);
}
} else {
if(y1 > y2) {
gp.lineTo(0, index);
gp.lineTo(dx+index, index);
gp.lineTo(dx+index, dy);
gp.lineTo(dx, dy);
} else {
gp.lineTo(0, -index);
gp.lineTo(dx+index, -index);
gp.lineTo(dx+index, dy);
gp.lineTo(dx, dy);
}
}
edgeShape = gp;
} else {
// this is a normal edge. Rotate it to the angle between
// vertex endpoints, then scale it to the distance between
// the vertices
float dx = x2-x1;
float dy = y2-y1;
float thetaRadians = (float) Math.atan2(dy, dx);
xform.rotate(thetaRadians);
float dist = (float) Math.sqrt(dx*dx + dy*dy);
xform.scale(dist, 1.0);
}
edgeShape = xform.createTransformedShape(edgeShape);
MutableTransformer vt = rc.getMultiLayerTransformer().getTransformer(Layer.VIEW);
if(vt instanceof LensTransformer) {
vt = ((LensTransformer)vt).getDelegate();
}
edgeHit = vt.transform(edgeShape).intersects(deviceRectangle);
if(edgeHit == true) {
Paint oldPaint = g.getPaint();
// get Paints for filling and drawing
// (filling is done first so that drawing and label use same Paint)
Paint fill_paint = rc.getEdgeFillPaintTransformer().transform(e);
if (fill_paint != null)
{
g.setPaint(fill_paint);
g.fill(edgeShape);
}
Paint draw_paint = rc.getEdgeDrawPaintTransformer().transform(e);
if (draw_paint != null)
{
g.setPaint(draw_paint);
g.draw(edgeShape);
}
float scalex = (float)g.getTransform().getScaleX();
float scaley = (float)g.getTransform().getScaleY();
// see if arrows are too small to bother drawing
if(scalex < .3 || scaley < .3) return;
if (rc.getEdgeArrowPredicate().evaluate(Context.<Graph<V,E>,E>getInstance(graph, e))) {
Stroke new_stroke = rc.getEdgeArrowStrokeTransformer().transform(e);
Stroke old_stroke = g.getStroke();
if (new_stroke != null)
g.setStroke(new_stroke);
Shape destVertexShape =
rc.getVertexShapeTransformer().transform(graph.getEndpoints(e).getSecond());
AffineTransform xf = AffineTransform.getTranslateInstance(x2, y2);
destVertexShape = xf.createTransformedShape(destVertexShape);
arrowHit = rc.getMultiLayerTransformer().getTransformer(Layer.VIEW).transform(destVertexShape).intersects(deviceRectangle);
if(arrowHit) {
AffineTransform at =
getArrowTransform(rc, new GeneralPath(edgeShape), destVertexShape);
if(at == null) return;
Shape arrow = rc.getEdgeArrowTransformer().transform(Context.<Graph<V,E>,E>getInstance(graph, e));
arrow = at.createTransformedShape(arrow);
g.setPaint(rc.getArrowFillPaintTransformer().transform(e));
g.fill(arrow);
g.setPaint(rc.getArrowDrawPaintTransformer().transform(e));
g.draw(arrow);
}
if (graph.getEdgeType(e) == EdgeType.UNDIRECTED) {
Shape vertexShape =
rc.getVertexShapeTransformer().transform(graph.getEndpoints(e).getFirst());
xf = AffineTransform.getTranslateInstance(x1, y1);
vertexShape = xf.createTransformedShape(vertexShape);
arrowHit = rc.getMultiLayerTransformer().getTransformer(Layer.VIEW).transform(vertexShape).intersects(deviceRectangle);
if(arrowHit) {
AffineTransform at = getReverseArrowTransform(rc, new GeneralPath(edgeShape), vertexShape, !isLoop);
if(at == null) return;
Shape arrow = rc.getEdgeArrowTransformer().transform(Context.<Graph<V,E>,E>getInstance(graph, e));
arrow = at.createTransformedShape(arrow);
g.setPaint(rc.getArrowFillPaintTransformer().transform(e));
g.fill(arrow);
g.setPaint(rc.getArrowDrawPaintTransformer().transform(e));
g.draw(arrow);
}
}
// restore paint and stroke
if (new_stroke != null)
g.setStroke(old_stroke);
}
// use existing paint for text if no draw paint specified
if (draw_paint == null)
g.setPaint(oldPaint);
// restore old paint
g.setPaint(oldPaint);
}
}
| protected void drawSimpleEdge(RenderContext<V,E> rc, Layout<V,E> layout, E e) {
GraphicsDecorator g = rc.getGraphicsContext();
Graph<V,E> graph = layout.getGraph();
Pair<V> endpoints = graph.getEndpoints(e);
V v1 = endpoints.getFirst();
V v2 = endpoints.getSecond();
Point2D p1 = layout.transform(v1);
Point2D p2 = layout.transform(v2);
p1 = rc.getMultiLayerTransformer().transform(Layer.LAYOUT, p1);
p2 = rc.getMultiLayerTransformer().transform(Layer.LAYOUT, p2);
float x1 = (float) p1.getX();
float y1 = (float) p1.getY();
float x2 = (float) p2.getX();
float y2 = (float) p2.getY();
boolean isLoop = v1.equals(v2);
Shape s2 = rc.getVertexShapeTransformer().transform(v2);
Shape edgeShape = rc.getEdgeShapeTransformer().transform(Context.<Graph<V,E>,E>getInstance(graph, e));
boolean edgeHit = true;
boolean arrowHit = true;
Rectangle deviceRectangle = null;
JComponent vv = rc.getScreenDevice();
if(vv != null) {
Dimension d = vv.getSize();
deviceRectangle = new Rectangle(0,0,d.width,d.height);
}
AffineTransform xform = AffineTransform.getTranslateInstance(x1, y1);
if(isLoop) {
// this is a self-loop. scale it is larger than the vertex
// it decorates and translate it so that its nadir is
// at the center of the vertex.
Rectangle2D s2Bounds = s2.getBounds2D();
xform.scale(s2Bounds.getWidth(),s2Bounds.getHeight());
xform.translate(0, -edgeShape.getBounds2D().getWidth()/2);
} else if(rc.getEdgeShapeTransformer() instanceof EdgeShape.Orthogonal) {
float dx = x2-x1;
float dy = y2-y1;
int index = 0;
if(rc.getEdgeShapeTransformer() instanceof IndexedRendering) {
EdgeIndexFunction<V,E> peif =
((IndexedRendering<V,E>)rc.getEdgeShapeTransformer()).getEdgeIndexFunction();
index = peif.getIndex(graph, e);
index *= 20;
}
GeneralPath gp = new GeneralPath();
gp.moveTo(0,0);// the xform will do the translation to x1,y1
if(x1 > x2) {
if(y1 > y2) {
gp.lineTo(0, index);
gp.lineTo(dx-index, index);
gp.lineTo(dx-index, dy);
gp.lineTo(dx, dy);
} else {
gp.lineTo(0, -index);
gp.lineTo(dx-index, -index);
gp.lineTo(dx-index, dy);
gp.lineTo(dx, dy);
}
} else {
if(y1 > y2) {
gp.lineTo(0, index);
gp.lineTo(dx+index, index);
gp.lineTo(dx+index, dy);
gp.lineTo(dx, dy);
} else {
gp.lineTo(0, -index);
gp.lineTo(dx+index, -index);
gp.lineTo(dx+index, dy);
gp.lineTo(dx, dy);
}
}
edgeShape = gp;
} else {
// this is a normal edge. Rotate it to the angle between
// vertex endpoints, then scale it to the distance between
// the vertices
float dx = x2-x1;
float dy = y2-y1;
float thetaRadians = (float) Math.atan2(dy, dx);
xform.rotate(thetaRadians);
float dist = (float) Math.sqrt(dx*dx + dy*dy);
xform.scale(dist, 1.0);
}
edgeShape = xform.createTransformedShape(edgeShape);
MutableTransformer vt = rc.getMultiLayerTransformer().getTransformer(Layer.VIEW);
if(vt instanceof LensTransformer) {
vt = ((LensTransformer)vt).getDelegate();
}
edgeHit = vt.transform(edgeShape).intersects(deviceRectangle);
if(edgeHit == true) {
Paint oldPaint = g.getPaint();
// get Paints for filling and drawing
// (filling is done first so that drawing and label use same Paint)
Paint fill_paint = rc.getEdgeFillPaintTransformer().transform(e);
if (fill_paint != null)
{
g.setPaint(fill_paint);
g.fill(edgeShape);
}
Paint draw_paint = rc.getEdgeDrawPaintTransformer().transform(e);
if (draw_paint != null)
{
g.setPaint(draw_paint);
g.draw(edgeShape);
}
float scalex = (float)g.getTransform().getScaleX();
float scaley = (float)g.getTransform().getScaleY();
// see if arrows are too small to bother drawing
if(scalex < .3 || scaley < .3) return;
if (rc.getEdgeArrowPredicate().evaluate(Context.<Graph<V,E>,E>getInstance(graph, e))) {
Stroke new_stroke = rc.getEdgeArrowStrokeTransformer().transform(e);
Stroke old_stroke = g.getStroke();
if (new_stroke != null)
g.setStroke(new_stroke);
Shape destVertexShape =
rc.getVertexShapeTransformer().transform(graph.getEndpoints(e).getSecond());
AffineTransform xf = AffineTransform.getTranslateInstance(x2, y2);
destVertexShape = xf.createTransformedShape(destVertexShape);
arrowHit = rc.getMultiLayerTransformer().getTransformer(Layer.VIEW).transform(destVertexShape).intersects(deviceRectangle);
if(arrowHit) {
AffineTransform at =
getArrowTransform(rc, new GeneralPath(edgeShape), destVertexShape);
if(at == null) return;
Shape arrow = rc.getEdgeArrowTransformer().transform(Context.<Graph<V,E>,E>getInstance(graph, e));
arrow = at.createTransformedShape(arrow);
g.setPaint(rc.getArrowFillPaintTransformer().transform(e));
g.fill(arrow);
g.setPaint(rc.getArrowDrawPaintTransformer().transform(e));
g.draw(arrow);
}
if (graph.getEdgeType(e) == EdgeType.UNDIRECTED) {
Shape vertexShape =
rc.getVertexShapeTransformer().transform(graph.getEndpoints(e).getFirst());
xf = AffineTransform.getTranslateInstance(x1, y1);
vertexShape = xf.createTransformedShape(vertexShape);
arrowHit = rc.getMultiLayerTransformer().getTransformer(Layer.VIEW).transform(vertexShape).intersects(deviceRectangle);
if(arrowHit) {
AffineTransform at = getReverseArrowTransform(rc, new GeneralPath(edgeShape), vertexShape, !isLoop);
if(at == null) return;
Shape arrow = rc.getEdgeArrowTransformer().transform(Context.<Graph<V,E>,E>getInstance(graph, e));
arrow = at.createTransformedShape(arrow);
g.setPaint(rc.getArrowFillPaintTransformer().transform(e));
g.fill(arrow);
g.setPaint(rc.getArrowDrawPaintTransformer().transform(e));
g.draw(arrow);
}
}
// restore paint and stroke
if (new_stroke != null)
g.setStroke(old_stroke);
}
// // use existing paint for text if no draw paint specified
// if (draw_paint == null)
// g.setPaint(oldPaint);
// restore old paint
g.setPaint(oldPaint);
}
}
|
diff --git a/src/com/slidellrobotics/reboundrumble/commands/FindDistance.java b/src/com/slidellrobotics/reboundrumble/commands/FindDistance.java
index bc994cd..6faef4a 100644
--- a/src/com/slidellrobotics/reboundrumble/commands/FindDistance.java
+++ b/src/com/slidellrobotics/reboundrumble/commands/FindDistance.java
@@ -1,117 +1,117 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.slidellrobotics.reboundrumble.commands;
import com.slidellrobotics.reboundrumble.subsystems.TrackingCamera;
/**
*
* @author 10491477
*/
public class FindDistance extends CommandBase {
double tgtHght = TrackingCamera.targetHeight; // Create a few necesarry local variables
double tgtWdth = TrackingCamera.targetWidth; // for concise code and calcs.
double tgtHghtFt; // Target Height in Feet
double tgtWdthFt; // Target Width in Feet
double ttlHght; // Total Height in Pixels
double ttlWdth; // Total Width imn Pixels
double vertFOV; // Vertical Field of View in Feet
double horFOV; // Horizontal Field of View in Feet
double vertVA; // Vertical Camera Viewing Angle
double horVA; // Horizontal Camera Viewing Angle
double leftRight; // Horizontal off-centerness of center of goal
double upDown; // Vertical off-centerness of center of goal
double wdth1Px; // Distance from the center of a Goal to the nearest Horizontal edge
double hght1Px; // Distance from the center of a Goal to the nearest Vertical edge
double horThet1; // Horizontal Angle from the Edge to Camera to center of Goal
double vertThet1; // Verticle Angle from the Edge to Camera to center of Goal
double d = 0; // Distance Variable to be used in firing Calculation
double pi = Math.PI; // Slightly shorter version using Pi
public FindDistance() {
// Use requires() here to declare subsystem dependencies
// eg. requires(chassis);
requires(leftShootingMotors); // Sets requires for Left Shooting Motors
requires(rightShootingMotors); // Sets requires for Right hooting Motors
}
// Called just before this Command runs the first time
protected void initialize() {
ttlHght = TrackingCamera.totalHeight; // Target Height from the Tracking Camera's static variable
ttlWdth = TrackingCamera.totalWidth; // Target Width from the Tracking Camera's static variable
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
if (TrackingCamera.targetGoal == null){ // If no target is found
leftShootingMotors.setSetpoint(1000); // Set Left shooting Motors to Full Speed
rightShootingMotors.setSetpoint(1000); // Set Right Shooting Motors to Full Speed
System.out.println("No target set"); // Debug Print Statement
return;
}
ttlHght = TrackingCamera.totalHeight; // Target Height from the Tracking Camera's static variable
ttlWdth = TrackingCamera.totalWidth;
tgtHght = TrackingCamera.targetGoal.boundingRectHeight; // Sets the height of our target.
tgtHghtFt = 1.5; // Defines goal's constant ft height
vertFOV = tgtHghtFt / tgtHght * ttlHght; // Gets the Foot Value of our Vertical Field of View
vertVA = 47*pi/180; // Defines the Viewing
horVA = 47*pi/180; // Angles of our camera
tgtWdth = TrackingCamera.targetGoal.boundingRectWidth; // Sets the width of our target.
tgtWdthFt = 2.0; // Defines goal's constant ft width
horFOV = tgtWdthFt / tgtWdth * ttlWdth; // Gets the ft value of our horizontal Field of View
- leftRight = Math.abs(TrackingCamera.targetGoal.center_mass_x - (ttlHght/2)); // Finds the horizontal off-centerness
- upDown = Math.abs(TrackingCamera.targetGoal.center_mass_y - (ttlWdth/2)); // Finds the vertical off-ceneterness
+ leftRight = Math.abs(TrackingCamera.targetGoal.center_mass_x - (ttlWdth/2)); // Finds the horizontal off-centerness
+ upDown = Math.abs(TrackingCamera.targetGoal.center_mass_y - (ttlHght/2)); // Finds the vertical off-ceneterness
wdth1Px = (ttlWdth/2) - leftRight; // Defines the distance from the Horizontal Edge to center of Goal in Pixels
hght1Px = (ttlHght/2) - upDown; // Defines the distance from the Vertical Edge to center of Goal in Pixels
horThet1 = horVA * wdth1Px/ttlWdth; // Finds the angle from Horizontal Edge<>camera<>center of goal
vertThet1 = vertVA * hght1Px/ttlHght; // Finds the angle from Vertical Edge<>camera<>center of goal
TrackingCamera.d1 = (hght1Px) / Math.tan(vertThet1); // Gets a distance from the center of our goal using Horizontal Theta
TrackingCamera.d2 = (wdth1Px) / Math.tan(horThet1); // Double checks distance with a Vertcial Theta
TrackingCamera.distanceToTarget = (TrackingCamera.d1 + TrackingCamera.d2) / 2; // Take the average to try get a more accurate measurement
//if distance to target is invalid, justset it to some number
if (TrackingCamera.distanceToTarget > 60 || TrackingCamera.distanceToTarget <= 0)
TrackingCamera.distanceToTarget = 60;
d = TrackingCamera.distanceToTarget; // See below Calculation for conciseness
TrackingCamera.launchSpeed = 60 * (d / Math.sqrt((11 / 6 - d) / -16.1) / (2 / 3 * pi)); //Calcs the required rpms for firing
leftShootingMotors.setSetpoint(TrackingCamera.launchSpeed); // Sets the shooting Left Shooting Motors
rightShootingMotors.setSetpoint(TrackingCamera.launchSpeed); // Sets the Right Shooting Motors
/* A String of Debug Print Statements */
System.out.println();
System.out.println("D1: "+TrackingCamera.d1);
System.out.println("D2: "+TrackingCamera.d2);
System.out.println("D: "+d);
System.out.println("Camera Launch Speed: "+TrackingCamera.launchSpeed);
System.out.println();
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
return true;
}
// Called once after isFinished returns true
protected void end() {
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
}
}
| true | true | protected void execute() {
if (TrackingCamera.targetGoal == null){ // If no target is found
leftShootingMotors.setSetpoint(1000); // Set Left shooting Motors to Full Speed
rightShootingMotors.setSetpoint(1000); // Set Right Shooting Motors to Full Speed
System.out.println("No target set"); // Debug Print Statement
return;
}
ttlHght = TrackingCamera.totalHeight; // Target Height from the Tracking Camera's static variable
ttlWdth = TrackingCamera.totalWidth;
tgtHght = TrackingCamera.targetGoal.boundingRectHeight; // Sets the height of our target.
tgtHghtFt = 1.5; // Defines goal's constant ft height
vertFOV = tgtHghtFt / tgtHght * ttlHght; // Gets the Foot Value of our Vertical Field of View
vertVA = 47*pi/180; // Defines the Viewing
horVA = 47*pi/180; // Angles of our camera
tgtWdth = TrackingCamera.targetGoal.boundingRectWidth; // Sets the width of our target.
tgtWdthFt = 2.0; // Defines goal's constant ft width
horFOV = tgtWdthFt / tgtWdth * ttlWdth; // Gets the ft value of our horizontal Field of View
leftRight = Math.abs(TrackingCamera.targetGoal.center_mass_x - (ttlHght/2)); // Finds the horizontal off-centerness
upDown = Math.abs(TrackingCamera.targetGoal.center_mass_y - (ttlWdth/2)); // Finds the vertical off-ceneterness
wdth1Px = (ttlWdth/2) - leftRight; // Defines the distance from the Horizontal Edge to center of Goal in Pixels
hght1Px = (ttlHght/2) - upDown; // Defines the distance from the Vertical Edge to center of Goal in Pixels
horThet1 = horVA * wdth1Px/ttlWdth; // Finds the angle from Horizontal Edge<>camera<>center of goal
vertThet1 = vertVA * hght1Px/ttlHght; // Finds the angle from Vertical Edge<>camera<>center of goal
TrackingCamera.d1 = (hght1Px) / Math.tan(vertThet1); // Gets a distance from the center of our goal using Horizontal Theta
TrackingCamera.d2 = (wdth1Px) / Math.tan(horThet1); // Double checks distance with a Vertcial Theta
TrackingCamera.distanceToTarget = (TrackingCamera.d1 + TrackingCamera.d2) / 2; // Take the average to try get a more accurate measurement
//if distance to target is invalid, justset it to some number
if (TrackingCamera.distanceToTarget > 60 || TrackingCamera.distanceToTarget <= 0)
TrackingCamera.distanceToTarget = 60;
d = TrackingCamera.distanceToTarget; // See below Calculation for conciseness
TrackingCamera.launchSpeed = 60 * (d / Math.sqrt((11 / 6 - d) / -16.1) / (2 / 3 * pi)); //Calcs the required rpms for firing
leftShootingMotors.setSetpoint(TrackingCamera.launchSpeed); // Sets the shooting Left Shooting Motors
rightShootingMotors.setSetpoint(TrackingCamera.launchSpeed); // Sets the Right Shooting Motors
/* A String of Debug Print Statements */
System.out.println();
System.out.println("D1: "+TrackingCamera.d1);
System.out.println("D2: "+TrackingCamera.d2);
System.out.println("D: "+d);
System.out.println("Camera Launch Speed: "+TrackingCamera.launchSpeed);
System.out.println();
}
| protected void execute() {
if (TrackingCamera.targetGoal == null){ // If no target is found
leftShootingMotors.setSetpoint(1000); // Set Left shooting Motors to Full Speed
rightShootingMotors.setSetpoint(1000); // Set Right Shooting Motors to Full Speed
System.out.println("No target set"); // Debug Print Statement
return;
}
ttlHght = TrackingCamera.totalHeight; // Target Height from the Tracking Camera's static variable
ttlWdth = TrackingCamera.totalWidth;
tgtHght = TrackingCamera.targetGoal.boundingRectHeight; // Sets the height of our target.
tgtHghtFt = 1.5; // Defines goal's constant ft height
vertFOV = tgtHghtFt / tgtHght * ttlHght; // Gets the Foot Value of our Vertical Field of View
vertVA = 47*pi/180; // Defines the Viewing
horVA = 47*pi/180; // Angles of our camera
tgtWdth = TrackingCamera.targetGoal.boundingRectWidth; // Sets the width of our target.
tgtWdthFt = 2.0; // Defines goal's constant ft width
horFOV = tgtWdthFt / tgtWdth * ttlWdth; // Gets the ft value of our horizontal Field of View
leftRight = Math.abs(TrackingCamera.targetGoal.center_mass_x - (ttlWdth/2)); // Finds the horizontal off-centerness
upDown = Math.abs(TrackingCamera.targetGoal.center_mass_y - (ttlHght/2)); // Finds the vertical off-ceneterness
wdth1Px = (ttlWdth/2) - leftRight; // Defines the distance from the Horizontal Edge to center of Goal in Pixels
hght1Px = (ttlHght/2) - upDown; // Defines the distance from the Vertical Edge to center of Goal in Pixels
horThet1 = horVA * wdth1Px/ttlWdth; // Finds the angle from Horizontal Edge<>camera<>center of goal
vertThet1 = vertVA * hght1Px/ttlHght; // Finds the angle from Vertical Edge<>camera<>center of goal
TrackingCamera.d1 = (hght1Px) / Math.tan(vertThet1); // Gets a distance from the center of our goal using Horizontal Theta
TrackingCamera.d2 = (wdth1Px) / Math.tan(horThet1); // Double checks distance with a Vertcial Theta
TrackingCamera.distanceToTarget = (TrackingCamera.d1 + TrackingCamera.d2) / 2; // Take the average to try get a more accurate measurement
//if distance to target is invalid, justset it to some number
if (TrackingCamera.distanceToTarget > 60 || TrackingCamera.distanceToTarget <= 0)
TrackingCamera.distanceToTarget = 60;
d = TrackingCamera.distanceToTarget; // See below Calculation for conciseness
TrackingCamera.launchSpeed = 60 * (d / Math.sqrt((11 / 6 - d) / -16.1) / (2 / 3 * pi)); //Calcs the required rpms for firing
leftShootingMotors.setSetpoint(TrackingCamera.launchSpeed); // Sets the shooting Left Shooting Motors
rightShootingMotors.setSetpoint(TrackingCamera.launchSpeed); // Sets the Right Shooting Motors
/* A String of Debug Print Statements */
System.out.println();
System.out.println("D1: "+TrackingCamera.d1);
System.out.println("D2: "+TrackingCamera.d2);
System.out.println("D: "+d);
System.out.println("Camera Launch Speed: "+TrackingCamera.launchSpeed);
System.out.println();
}
|
diff --git a/hygienic_common/us/joaogldarkdeagle/hygienic/Hygienic.java b/hygienic_common/us/joaogldarkdeagle/hygienic/Hygienic.java
index 15507e9..7ed4204 100644
--- a/hygienic_common/us/joaogldarkdeagle/hygienic/Hygienic.java
+++ b/hygienic_common/us/joaogldarkdeagle/hygienic/Hygienic.java
@@ -1,75 +1,76 @@
package us.joaogldarkdeagle.hygienic;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import us.joaogldarkdeagle.hygienic.lib.ModInfo;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.Init;
import cpw.mods.fml.common.Mod.Instance;
import cpw.mods.fml.common.Mod.PostInit;
import cpw.mods.fml.common.Mod.PreInit;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.network.NetworkMod;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.common.registry.LanguageRegistry;
@Mod(modid = ModInfo.MOD_ID, name = ModInfo.MOD_NAME, version = ModInfo.MOD_VERSION)
@NetworkMod(clientSideRequired = true, serverSideRequired = true)
public class Hygienic {
@Instance("Hygienic")
public Hygienic instance;
public static CreativeTabs hygienicTab = new HygienicTab("Hygienic");
public static Block mopBukket;
public static Item mop;
public static Item food;
public static Item apple;
public static Item glassBow;
static String mopBukket_Tex = "Hygienic:Blocks";
static String mop_Tex = "Hygienic:Items";
static String modFood_Tex = "Hygienic:Food";
static String modApple_Tex = "Hygienic:Apple";
static String modBow_Tex = "Hygienic:Bow";
@PreInit
public void preInit(FMLPreInitializationEvent event) {
}
@Init
public void init(FMLInitializationEvent event) {
mopBukket = new BlockMopBukket(900, Material.grass, mopBukket_Tex).setUnlocalizedName("mopBukket_UN");
mopBukket.setStepSound(Block.soundMetalFootstep);
mop = (new ItemMop(901, mop_Tex)).setUnlocalizedName("Mop").setCreativeTab(hygienicTab);
food = (new ItemModFood(902, 18, true, modFood_Tex)).setUnlocalizedName("My Food");
apple = (new ItemModApple(903, 18, false, modFood_Tex)).setUnlocalizedName("My Apple").setPotionEffect("potion.blindness");
glassBow = (new GlassBow(904, modBow_Tex)).setUnlocalizedName("Glass Bow");
GameRegistry.registerBlock(mopBukket, "mopBukket_UN");
LanguageRegistry.addName(mopBukket, "Mop Bukket");
LanguageRegistry.addName(mop, "Mop");
LanguageRegistry.addName(food, "My Food");
LanguageRegistry.addName(apple, "My Apple");
LanguageRegistry.addName(glassBow, "Glass Bow");
+ LanguageRegistry.instance().addStringLocalization("itemGroup.Hygienic", "en_US", "Hygienic");
GameRegistry.addRecipe(new ItemStack(mopBukket, 1), new Object[] {" "," X ","X X", Character.valueOf('X'), Item.ingotIron});
GameRegistry.addRecipe(new ItemStack(mop, 4), new Object[] {"XXX","XXX","XXX", Character.valueOf('X'), mopBukket});
GameRegistry.addRecipe(new ItemStack(food, 4), new Object[] {" "," X "," X ", Character.valueOf('X'), Item.ingotIron});
GameRegistry.addRecipe(new ItemStack(apple, 4), new Object[] {" X "," X "," X ", Character.valueOf('X'), Item.ingotIron});
GameRegistry.addRecipe(new ItemStack(glassBow, 1), new Object[] {" XS","X S"," XS", Character.valueOf('X'), Block.glass, Character.valueOf('S'), Item.silk});
}
@PostInit
public void postInit(FMLPostInitializationEvent event) {
}
}
| true | true | public void init(FMLInitializationEvent event) {
mopBukket = new BlockMopBukket(900, Material.grass, mopBukket_Tex).setUnlocalizedName("mopBukket_UN");
mopBukket.setStepSound(Block.soundMetalFootstep);
mop = (new ItemMop(901, mop_Tex)).setUnlocalizedName("Mop").setCreativeTab(hygienicTab);
food = (new ItemModFood(902, 18, true, modFood_Tex)).setUnlocalizedName("My Food");
apple = (new ItemModApple(903, 18, false, modFood_Tex)).setUnlocalizedName("My Apple").setPotionEffect("potion.blindness");
glassBow = (new GlassBow(904, modBow_Tex)).setUnlocalizedName("Glass Bow");
GameRegistry.registerBlock(mopBukket, "mopBukket_UN");
LanguageRegistry.addName(mopBukket, "Mop Bukket");
LanguageRegistry.addName(mop, "Mop");
LanguageRegistry.addName(food, "My Food");
LanguageRegistry.addName(apple, "My Apple");
LanguageRegistry.addName(glassBow, "Glass Bow");
GameRegistry.addRecipe(new ItemStack(mopBukket, 1), new Object[] {" "," X ","X X", Character.valueOf('X'), Item.ingotIron});
GameRegistry.addRecipe(new ItemStack(mop, 4), new Object[] {"XXX","XXX","XXX", Character.valueOf('X'), mopBukket});
GameRegistry.addRecipe(new ItemStack(food, 4), new Object[] {" "," X "," X ", Character.valueOf('X'), Item.ingotIron});
GameRegistry.addRecipe(new ItemStack(apple, 4), new Object[] {" X "," X "," X ", Character.valueOf('X'), Item.ingotIron});
GameRegistry.addRecipe(new ItemStack(glassBow, 1), new Object[] {" XS","X S"," XS", Character.valueOf('X'), Block.glass, Character.valueOf('S'), Item.silk});
}
| public void init(FMLInitializationEvent event) {
mopBukket = new BlockMopBukket(900, Material.grass, mopBukket_Tex).setUnlocalizedName("mopBukket_UN");
mopBukket.setStepSound(Block.soundMetalFootstep);
mop = (new ItemMop(901, mop_Tex)).setUnlocalizedName("Mop").setCreativeTab(hygienicTab);
food = (new ItemModFood(902, 18, true, modFood_Tex)).setUnlocalizedName("My Food");
apple = (new ItemModApple(903, 18, false, modFood_Tex)).setUnlocalizedName("My Apple").setPotionEffect("potion.blindness");
glassBow = (new GlassBow(904, modBow_Tex)).setUnlocalizedName("Glass Bow");
GameRegistry.registerBlock(mopBukket, "mopBukket_UN");
LanguageRegistry.addName(mopBukket, "Mop Bukket");
LanguageRegistry.addName(mop, "Mop");
LanguageRegistry.addName(food, "My Food");
LanguageRegistry.addName(apple, "My Apple");
LanguageRegistry.addName(glassBow, "Glass Bow");
LanguageRegistry.instance().addStringLocalization("itemGroup.Hygienic", "en_US", "Hygienic");
GameRegistry.addRecipe(new ItemStack(mopBukket, 1), new Object[] {" "," X ","X X", Character.valueOf('X'), Item.ingotIron});
GameRegistry.addRecipe(new ItemStack(mop, 4), new Object[] {"XXX","XXX","XXX", Character.valueOf('X'), mopBukket});
GameRegistry.addRecipe(new ItemStack(food, 4), new Object[] {" "," X "," X ", Character.valueOf('X'), Item.ingotIron});
GameRegistry.addRecipe(new ItemStack(apple, 4), new Object[] {" X "," X "," X ", Character.valueOf('X'), Item.ingotIron});
GameRegistry.addRecipe(new ItemStack(glassBow, 1), new Object[] {" XS","X S"," XS", Character.valueOf('X'), Block.glass, Character.valueOf('S'), Item.silk});
}
|
diff --git a/src/org/jacorb/imr/ServerStartupDaemonImpl.java b/src/org/jacorb/imr/ServerStartupDaemonImpl.java
index e9cb6ab23..8c36a817d 100644
--- a/src/org/jacorb/imr/ServerStartupDaemonImpl.java
+++ b/src/org/jacorb/imr/ServerStartupDaemonImpl.java
@@ -1,225 +1,225 @@
/*
* JacORB - a free Java ORB
*
* Copyright (C) 1999-2003 Gerald Brose
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free
* Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
package org.jacorb.imr;
/**
* This class is used to start servers on (from the view of the repository)
* remote hosts. It has a thread for forwarding output of started servers.
*
* @author Nicolas Noffke
*
* $Id$
*
*/
import org.jacorb.orb.ORB;
import org.jacorb.util.*;
import org.jacorb.util.threadpool.*;
import java.lang.*;
import java.net.*;
import java.io.*;
import org.omg.PortableServer.*;
public class ServerStartupDaemonImpl
extends org.jacorb.imr.ServerStartupDaemonPOA
{
private static ORB orb = null;
private static final String out_prefix = ">> ";
private ThreadPool stdout_pool = null;
private ThreadPool stderr_pool = null;
/**
* The constructor. It registers this daemon at the repository.
*
* @exception Exception any exception that is thrown inside is propagated upwards.
*/
public ServerStartupDaemonImpl()
throws Exception
{
Registration _registration = null;
_registration =
RegistrationHelper.narrow( orb.resolve_initial_references("ImplementationRepository"));
if( _registration == null )
- throw new java.lang.Error("ImR not found");
+ throw new RuntimeException("ImR not found");
_this_object( orb );
HostInfo _me = new HostInfo(InetAddress.getLocalHost().getHostName(),_this(),
orb.object_to_string(_this()));
_registration.register_host(_me);
stdout_pool = new ThreadPool( new OutputForwarderFactory( new InputStreamSelector(){
public InputStream getInputStream( Process p )
{
return p.getInputStream();
}
}),
100, //max threads
10 );//max idle threads
stderr_pool = new ThreadPool( new OutputForwarderFactory( new InputStreamSelector(){
public InputStream getInputStream( Process p )
{
return p.getErrorStream();
}
}),
100, //max threads
10 );//max idle threads
}
/**
* NOT IMPLEMENTED, but currently used for "pinging" purposes.
* @return 0 always
*/
public int get_system_load()
{
// Dummy method, not supported yet.
return 0;
}
/**
* This method starts a server on this host as specified by 'command'.
*
* @param command The server startup command, i.e. the servers class name and
* parameters for its main method. The interpreter is inserted automatically.
*
* @exception org.jacorb.imr.ServerStartupDaemonPackage.ServerStartupFailed Runtime.exec
* failed to execute the command.
*/
public void start_server(String command)
throws ServerStartupFailed
{
try
{
Debug.output(4,
"Starting: " + command );
Process _server = Runtime.getRuntime().exec( command );
stdout_pool.putJob(_server);
stderr_pool.putJob(_server);
}
catch (Exception _e)
{
Debug.output(4, _e);
throw new ServerStartupFailed( _e.toString() );
}
}
/**
* main method. Creates a new ServerStartupDaemonImpl instance and runs the orb.
**/
public static void main( String[] args )
{
try
{
orb = (org.jacorb.orb.ORB) ORB.init( args, null );
POA poa = POAHelper.narrow(orb.resolve_initial_references("RootPOA"));
poa.the_POAManager().activate();
ServerStartupDaemonImpl _ssd = new ServerStartupDaemonImpl();
orb.run();
}
catch( Exception _e )
{
_e.printStackTrace();
}
System.exit(0);
}
/**
* Inner class used to forward output of servers, since that would be
* invisible otherwise.
*/
private class OutputForwarder
implements Consumer
{
/**
* prefix to help distinguish between output of a
* started server and output of this SSD
*/
private InputStreamSelector selector = null;
public OutputForwarder( InputStreamSelector selector )
{
this.selector = selector;
}
public void doWork( Object job )
{
Process p = (Process) job;
BufferedReader _in = new BufferedReader(new InputStreamReader(selector.getInputStream( p )));
String _line = null;
try
{
// If we get null from readLine() we assume that the process has exited.
// Unfortunately there is no exception thrown when trying to read from
// a dead processes output stream.
while((_line = _in.readLine()) != null)
{
System.out.println(out_prefix + _line);
}
_in.close();
}
catch( Exception _e )
{
_e.printStackTrace();
}
Debug.output( 4,
"A server process exited" );
}
}//OutputForwarder
private interface InputStreamSelector
{
public InputStream getInputStream( Process p );
}
private class OutputForwarderFactory
implements ConsumerFactory
{
private InputStreamSelector selector = null;
public OutputForwarderFactory( InputStreamSelector selector )
{
this.selector = selector;
}
public Consumer create()
{
return new OutputForwarder( selector );
}
}
} // ServerStartupDaemonImpl
| true | true | public ServerStartupDaemonImpl()
throws Exception
{
Registration _registration = null;
_registration =
RegistrationHelper.narrow( orb.resolve_initial_references("ImplementationRepository"));
if( _registration == null )
throw new java.lang.Error("ImR not found");
_this_object( orb );
HostInfo _me = new HostInfo(InetAddress.getLocalHost().getHostName(),_this(),
orb.object_to_string(_this()));
_registration.register_host(_me);
stdout_pool = new ThreadPool( new OutputForwarderFactory( new InputStreamSelector(){
public InputStream getInputStream( Process p )
{
return p.getInputStream();
}
}),
100, //max threads
10 );//max idle threads
stderr_pool = new ThreadPool( new OutputForwarderFactory( new InputStreamSelector(){
public InputStream getInputStream( Process p )
{
return p.getErrorStream();
}
}),
100, //max threads
10 );//max idle threads
}
| public ServerStartupDaemonImpl()
throws Exception
{
Registration _registration = null;
_registration =
RegistrationHelper.narrow( orb.resolve_initial_references("ImplementationRepository"));
if( _registration == null )
throw new RuntimeException("ImR not found");
_this_object( orb );
HostInfo _me = new HostInfo(InetAddress.getLocalHost().getHostName(),_this(),
orb.object_to_string(_this()));
_registration.register_host(_me);
stdout_pool = new ThreadPool( new OutputForwarderFactory( new InputStreamSelector(){
public InputStream getInputStream( Process p )
{
return p.getInputStream();
}
}),
100, //max threads
10 );//max idle threads
stderr_pool = new ThreadPool( new OutputForwarderFactory( new InputStreamSelector(){
public InputStream getInputStream( Process p )
{
return p.getErrorStream();
}
}),
100, //max threads
10 );//max idle threads
}
|
diff --git a/src/minecraft/net/Harmonion/block/ModBlocks.java b/src/minecraft/net/Harmonion/block/ModBlocks.java
index 54eee00..f8dbd44 100644
--- a/src/minecraft/net/Harmonion/block/ModBlocks.java
+++ b/src/minecraft/net/Harmonion/block/ModBlocks.java
@@ -1,141 +1,141 @@
package net.Harmonion.block;
import net.Harmonion.block.power.BlockMachine;
import net.Harmonion.block.power.BlockMachinePanel;
import net.Harmonion.block.power.BlockMicro;
import net.Harmonion.creativetab.CreativeTabHarmonionB;
import net.Harmonion.creativetab.CreativeTabHarmonionP;
import net.Harmonion.item.ModItems;
import net.Harmonion.item.power.ItemExtended;
import net.Harmonion.item.power.ItemMachinePanel;
import net.Harmonion.item.power.ItemMicro;
import net.Harmonion.power.CoverLib;
import net.Harmonion.power.MicroPlacementWire;
import net.Harmonion.power.RedPowerLib;
import net.Harmonion.power.TileBatteryBox;
import net.Harmonion.power.TileBluewire;
import net.Harmonion.power.TileCovered;
import net.Harmonion.power.TileSolarPanel;
import net.Harmonion.server.Harmonion;
import net.Harmonion.util.BlockIds;
import net.Harmonion.world.WorldProviderHarmonion;
import net.Harmonion.world.gen.feature.WorldPopulator;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.FurnaceRecipes;
import net.minecraftforge.common.DimensionManager;
import net.minecraftforge.oredict.OreDictionary;
import cpw.mods.fml.common.registry.GameRegistry;
public class ModBlocks {
/* Mod Block instances */
public static Block HarmonionOre;
public static Block HarmonionBlock;
public static BlockHarmonionPortal HarmonionPortal;
public static Block HarmonionFire;
public static Block HarmonionLog;
public static Block HarmonionLeaves;
public static Block HarmonionSapling;
public static Block HarmonionDoor;
public static Block HarmonionGlass;
public static BlockMicro blockMicro;
public static BlockMachine blockMachine;
public static BlockMachinePanel blockMachinePanel;
public static int customBlockModel;
public static final CreativeTabs tabHarmonioncraftB = new CreativeTabHarmonionB(CreativeTabs.getNextID(), "HarmonionB");
public static final CreativeTabs tabHarmonioncraftW = new CreativeTabHarmonionP(CreativeTabs.getNextID(), "HarmonionP");
public static void init() {
/* Initialize each mod block individually */
HarmonionOre = new BlockHarmonionOre(BlockIds.Harmonion, 0);
HarmonionBlock = new BlockHarmonionBlock(BlockIds.Harmonion_Block, 3);
HarmonionLog = new BlockHarmonionLog(BlockIds.Harmonion_Log);
HarmonionLeaves = new BlockHarmonionLeaves(BlockIds.Harmonion_Leaves);
HarmonionSapling = new BlockHarmonionSapling(BlockIds.Harmonion_Sapling, 13);
HarmonionDoor = new BlockHarmonionDoor(BlockIds.Harmonion_Door, 11, 12, Material.iron);
HarmonionGlass = new BlockHarmonionGlass(BlockIds.Harmonion_Glass, 4, Material.glass, false);
HarmonionPortal = (BlockHarmonionPortal)((BlockHarmonionPortal)(new BlockHarmonionPortal(BlockIds.Harmonion_Portal, 14)));
HarmonionFire = (new BlockHarmonionFire(BlockIds.Harmonion_Fire, Block.fire.blockIndexInTexture));
blockMicro = new BlockMicro(609);
- blockMicro.setBlockName("rpwire");
+ blockMicro.setBlockName("Harmonionwire");
GameRegistry.registerBlock(blockMicro, ItemMicro.class, "micro");
blockMicro.addTileEntityMapping(0, TileCovered.class);
CoverLib.blockCoverPlate = blockMicro;
blockMachine = new BlockMachine(610);
blockMachine.setBlockName("rpmachine");
GameRegistry.registerBlock(blockMachine, ItemExtended.class, "machine");
blockMachine.setItemName(0, "rpbatbox");
- GameRegistry.registerTileEntity(TileBatteryBox.class, "RPBatBox");
+ GameRegistry.registerTileEntity(TileBatteryBox.class, "HarmoionBatBox");
blockMachine.addTileEntityMapping(0, TileBatteryBox.class);
blockMachinePanel = new BlockMachinePanel(611);
GameRegistry.registerBlock(blockMachinePanel, ItemMachinePanel.class, "machinePanel");
- GameRegistry.registerTileEntity(TileSolarPanel.class, "RPSolar");
+ GameRegistry.registerTileEntity(TileSolarPanel.class, "HarmonionSolar");
blockMachinePanel.addTileEntityMapping(0, TileSolarPanel.class);
blockMachinePanel.setItemName(0, "rpsolar");
int var1;
int var2;
RedPowerLib.addCompatibleMapping(0, 1);
for (var1 = 0; var1 < 16; ++var1)
{
RedPowerLib.addCompatibleMapping(0, 2 + var1);
RedPowerLib.addCompatibleMapping(1, 2 + var1);
RedPowerLib.addCompatibleMapping(65, 2 + var1);
for (var2 = 0; var2 < 16; ++var2)
{
RedPowerLib.addCompatibleMapping(19 + var2, 2 + var1);
}
RedPowerLib.addCompatibleMapping(18, 2 + var1);
RedPowerLib.addCompatibleMapping(18, 19 + var1);
}
RedPowerLib.addCompatibleMapping(0, 65);
RedPowerLib.addCompatibleMapping(1, 65);
RedPowerLib.addCompatibleMapping(64, 65);
RedPowerLib.addCompatibleMapping(64, 67);
RedPowerLib.addCompatibleMapping(65, 67);
RedPowerLib.addCompatibleMapping(66, 67);
/* Adds Blocks into the game */
OreDictionary.registerOre("HarmonionOre", HarmonionOre);
GameRegistry.registerBlock(HarmonionOre, BlockOresMeta.class);
GameRegistry.registerBlock(HarmonionLeaves);
GameRegistry.registerBlock(HarmonionLog);
GameRegistry.registerBlock(HarmonionDoor);
GameRegistry.registerBlock(HarmonionGlass);
GameRegistry.registerBlock(HarmonionBlock);
GameRegistry.registerBlock(HarmonionPortal);
GameRegistry.registerBlock(HarmonionFire);
DimensionManager.registerProviderType(BlockIds.Harmonion_Dimension, WorldProviderHarmonion.class, false);
DimensionManager.registerDimension(BlockIds.Harmonion_Dimension, BlockIds.Harmonion_Dimension);
/* WorldGen */
GameRegistry.registerWorldGenerator(new WorldPopulator());
}
public static void initBlockSmelting() {
FurnaceRecipes furnaceRecipes = FurnaceRecipes.smelting();
/* Harmonon Ore Smelting. */
furnaceRecipes.addSmelting(ModBlocks.HarmonionOre.blockID, new ItemStack(ModItems.Refinedsoundstone), 5.0F);
}
}
| false | true | public static void init() {
/* Initialize each mod block individually */
HarmonionOre = new BlockHarmonionOre(BlockIds.Harmonion, 0);
HarmonionBlock = new BlockHarmonionBlock(BlockIds.Harmonion_Block, 3);
HarmonionLog = new BlockHarmonionLog(BlockIds.Harmonion_Log);
HarmonionLeaves = new BlockHarmonionLeaves(BlockIds.Harmonion_Leaves);
HarmonionSapling = new BlockHarmonionSapling(BlockIds.Harmonion_Sapling, 13);
HarmonionDoor = new BlockHarmonionDoor(BlockIds.Harmonion_Door, 11, 12, Material.iron);
HarmonionGlass = new BlockHarmonionGlass(BlockIds.Harmonion_Glass, 4, Material.glass, false);
HarmonionPortal = (BlockHarmonionPortal)((BlockHarmonionPortal)(new BlockHarmonionPortal(BlockIds.Harmonion_Portal, 14)));
HarmonionFire = (new BlockHarmonionFire(BlockIds.Harmonion_Fire, Block.fire.blockIndexInTexture));
blockMicro = new BlockMicro(609);
blockMicro.setBlockName("rpwire");
GameRegistry.registerBlock(blockMicro, ItemMicro.class, "micro");
blockMicro.addTileEntityMapping(0, TileCovered.class);
CoverLib.blockCoverPlate = blockMicro;
blockMachine = new BlockMachine(610);
blockMachine.setBlockName("rpmachine");
GameRegistry.registerBlock(blockMachine, ItemExtended.class, "machine");
blockMachine.setItemName(0, "rpbatbox");
GameRegistry.registerTileEntity(TileBatteryBox.class, "RPBatBox");
blockMachine.addTileEntityMapping(0, TileBatteryBox.class);
blockMachinePanel = new BlockMachinePanel(611);
GameRegistry.registerBlock(blockMachinePanel, ItemMachinePanel.class, "machinePanel");
GameRegistry.registerTileEntity(TileSolarPanel.class, "RPSolar");
blockMachinePanel.addTileEntityMapping(0, TileSolarPanel.class);
blockMachinePanel.setItemName(0, "rpsolar");
int var1;
int var2;
RedPowerLib.addCompatibleMapping(0, 1);
for (var1 = 0; var1 < 16; ++var1)
{
RedPowerLib.addCompatibleMapping(0, 2 + var1);
RedPowerLib.addCompatibleMapping(1, 2 + var1);
RedPowerLib.addCompatibleMapping(65, 2 + var1);
for (var2 = 0; var2 < 16; ++var2)
{
RedPowerLib.addCompatibleMapping(19 + var2, 2 + var1);
}
RedPowerLib.addCompatibleMapping(18, 2 + var1);
RedPowerLib.addCompatibleMapping(18, 19 + var1);
}
RedPowerLib.addCompatibleMapping(0, 65);
RedPowerLib.addCompatibleMapping(1, 65);
RedPowerLib.addCompatibleMapping(64, 65);
RedPowerLib.addCompatibleMapping(64, 67);
RedPowerLib.addCompatibleMapping(65, 67);
RedPowerLib.addCompatibleMapping(66, 67);
/* Adds Blocks into the game */
OreDictionary.registerOre("HarmonionOre", HarmonionOre);
GameRegistry.registerBlock(HarmonionOre, BlockOresMeta.class);
GameRegistry.registerBlock(HarmonionLeaves);
GameRegistry.registerBlock(HarmonionLog);
GameRegistry.registerBlock(HarmonionDoor);
GameRegistry.registerBlock(HarmonionGlass);
GameRegistry.registerBlock(HarmonionBlock);
GameRegistry.registerBlock(HarmonionPortal);
GameRegistry.registerBlock(HarmonionFire);
DimensionManager.registerProviderType(BlockIds.Harmonion_Dimension, WorldProviderHarmonion.class, false);
DimensionManager.registerDimension(BlockIds.Harmonion_Dimension, BlockIds.Harmonion_Dimension);
/* WorldGen */
GameRegistry.registerWorldGenerator(new WorldPopulator());
}
| public static void init() {
/* Initialize each mod block individually */
HarmonionOre = new BlockHarmonionOre(BlockIds.Harmonion, 0);
HarmonionBlock = new BlockHarmonionBlock(BlockIds.Harmonion_Block, 3);
HarmonionLog = new BlockHarmonionLog(BlockIds.Harmonion_Log);
HarmonionLeaves = new BlockHarmonionLeaves(BlockIds.Harmonion_Leaves);
HarmonionSapling = new BlockHarmonionSapling(BlockIds.Harmonion_Sapling, 13);
HarmonionDoor = new BlockHarmonionDoor(BlockIds.Harmonion_Door, 11, 12, Material.iron);
HarmonionGlass = new BlockHarmonionGlass(BlockIds.Harmonion_Glass, 4, Material.glass, false);
HarmonionPortal = (BlockHarmonionPortal)((BlockHarmonionPortal)(new BlockHarmonionPortal(BlockIds.Harmonion_Portal, 14)));
HarmonionFire = (new BlockHarmonionFire(BlockIds.Harmonion_Fire, Block.fire.blockIndexInTexture));
blockMicro = new BlockMicro(609);
blockMicro.setBlockName("Harmonionwire");
GameRegistry.registerBlock(blockMicro, ItemMicro.class, "micro");
blockMicro.addTileEntityMapping(0, TileCovered.class);
CoverLib.blockCoverPlate = blockMicro;
blockMachine = new BlockMachine(610);
blockMachine.setBlockName("rpmachine");
GameRegistry.registerBlock(blockMachine, ItemExtended.class, "machine");
blockMachine.setItemName(0, "rpbatbox");
GameRegistry.registerTileEntity(TileBatteryBox.class, "HarmoionBatBox");
blockMachine.addTileEntityMapping(0, TileBatteryBox.class);
blockMachinePanel = new BlockMachinePanel(611);
GameRegistry.registerBlock(blockMachinePanel, ItemMachinePanel.class, "machinePanel");
GameRegistry.registerTileEntity(TileSolarPanel.class, "HarmonionSolar");
blockMachinePanel.addTileEntityMapping(0, TileSolarPanel.class);
blockMachinePanel.setItemName(0, "rpsolar");
int var1;
int var2;
RedPowerLib.addCompatibleMapping(0, 1);
for (var1 = 0; var1 < 16; ++var1)
{
RedPowerLib.addCompatibleMapping(0, 2 + var1);
RedPowerLib.addCompatibleMapping(1, 2 + var1);
RedPowerLib.addCompatibleMapping(65, 2 + var1);
for (var2 = 0; var2 < 16; ++var2)
{
RedPowerLib.addCompatibleMapping(19 + var2, 2 + var1);
}
RedPowerLib.addCompatibleMapping(18, 2 + var1);
RedPowerLib.addCompatibleMapping(18, 19 + var1);
}
RedPowerLib.addCompatibleMapping(0, 65);
RedPowerLib.addCompatibleMapping(1, 65);
RedPowerLib.addCompatibleMapping(64, 65);
RedPowerLib.addCompatibleMapping(64, 67);
RedPowerLib.addCompatibleMapping(65, 67);
RedPowerLib.addCompatibleMapping(66, 67);
/* Adds Blocks into the game */
OreDictionary.registerOre("HarmonionOre", HarmonionOre);
GameRegistry.registerBlock(HarmonionOre, BlockOresMeta.class);
GameRegistry.registerBlock(HarmonionLeaves);
GameRegistry.registerBlock(HarmonionLog);
GameRegistry.registerBlock(HarmonionDoor);
GameRegistry.registerBlock(HarmonionGlass);
GameRegistry.registerBlock(HarmonionBlock);
GameRegistry.registerBlock(HarmonionPortal);
GameRegistry.registerBlock(HarmonionFire);
DimensionManager.registerProviderType(BlockIds.Harmonion_Dimension, WorldProviderHarmonion.class, false);
DimensionManager.registerDimension(BlockIds.Harmonion_Dimension, BlockIds.Harmonion_Dimension);
/* WorldGen */
GameRegistry.registerWorldGenerator(new WorldPopulator());
}
|
diff --git a/src/gossipLearning/models/regression/NormaSVM.java b/src/gossipLearning/models/regression/NormaSVM.java
index 3cf0f6d..d991c63 100644
--- a/src/gossipLearning/models/regression/NormaSVM.java
+++ b/src/gossipLearning/models/regression/NormaSVM.java
@@ -1,374 +1,374 @@
package gossipLearning.models.regression;
import gossipLearning.DataBaseReader;
import gossipLearning.InstanceHolder;
import gossipLearning.interfaces.Model;
import gossipLearning.models.kernels.Kernel;
import gossipLearning.models.kernels.RBFKernel;
import gossipLearning.models.losses.Loss;
import gossipLearning.utils.SparseVector;
import java.io.File;
import java.io.Serializable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
import peersim.config.Configuration;
public class NormaSVM implements Model {
private static final long serialVersionUID = 18888123L;
/**
* Parameter Tau - shrinking constant
*/
protected static final String PAR_TAU = "normasvm.tau";
protected static final int DEFAULT_TAU = 100;
protected int tau = DEFAULT_TAU;
/**
* Parameter Lambda - regularization constant
*/
protected static final String PAR_LAMBDA = "normasvm.lambda";
protected static final double DEFAULT_LAMBDA = 0.0001;
protected double lambda = DEFAULT_LAMBDA;
/**
* Parameter Kernel - name of kernel class
*/
protected static final String PAR_KERNEL = "normasvm.kernel";
protected static final String DEFAULT_KERNEL = "gossipLearning.models.kernels.LinearKernel";
protected String kernelClassName = DEFAULT_KERNEL;
/**
* Parameter Loss - name of the applied loss class
*/
protected static final String PAR_LOSS = "normasvm.loss";
protected static final String DEFAULT_LOSS = "gossipLearning.models.losses.SquaredLoss";
protected String lossClassName = DEFAULT_LOSS;
/**
* Model
*/
private double b;
private BoundedQueue q;
private Kernel kernel;
private Loss loss;
private long age;
private int numberOfClasses;
public NormaSVM() {
try {
// initialize parameters using their default values
kernel = (Kernel) Class.forName(kernelClassName).newInstance();
loss = (Loss) Class.forName(lossClassName).newInstance();
// initialize model
age = 0;
q = new BoundedQueue(tau);
b = 0.0;
} catch (Exception e) {
throw new RuntimeException("Error in NormaSVM.defaultConstructor", e);
}
}
public NormaSVM(NormaSVM o) {
// copy parameters
tau = o.tau;
lambda = o.lambda;
kernelClassName = new String(o.kernelClassName);
lossClassName = new String(o.lossClassName);
// copy model
b = o.b;
q = (BoundedQueue) o.q.clone();
kernel = o.kernel; // deep copy is not needed
loss = o.loss; // deep copy is not needed
age = o.age;
numberOfClasses = o.numberOfClasses;
}
public Object clone() {
return new NormaSVM(this);
}
@Override
public void init(String prefix) {
try {
// read parameters
tau = Configuration.getInt(prefix + "." + PAR_TAU, DEFAULT_TAU);
lambda = Configuration.getDouble(prefix + "." + PAR_LAMBDA, DEFAULT_LAMBDA);
kernelClassName = Configuration.getString(prefix + "." + PAR_KERNEL, DEFAULT_KERNEL);
kernel = (Kernel) Class.forName(kernelClassName).newInstance();
lossClassName = Configuration.getString(prefix + "." + PAR_LOSS, DEFAULT_LOSS);
loss = (Loss) Class.forName(lossClassName).newInstance();
// initialize model
age = 0;
q = new BoundedQueue(tau);
b = 0.0;
} catch (Exception e) {
throw new RuntimeException("Error in NormaSVM.init", e);
}
}
@Override
public void update(SparseVector x, double y) {
// increment age
++age;
// compute nu
final double nu = nu();
// create multiplier
final double d = (1.0 - nu * lambda);
// provide prediction and gradient of loss
final double pred = predict(x);
final double lossGrad = loss.lossGrad(pred, y);
// update elementary model parts
for (ElementaryModel p : q) {
p.update(d);
}
// add new elementary model part
q.offer(new ElementaryModel(age, x, - nu * lossGrad));
// update bias
b -= nu * lossGrad;
}
/**
* It returns the value of nu depend on the current state of the model.
*
* @return value of nu
*/
protected double nu() {
return 1.0/(double) age;
}
@Override
public double predict(SparseVector x) {
double v = 0;
// sum up model parts
for (ElementaryModel p : q) {
v += p.alpha() * kernel.kernel(p.x(), x);
}
// add bias
v += b;
return v;
}
@Override
public int getNumberOfClasses() {
return numberOfClasses;
}
@Override
public void setNumberOfClasses(int numberOfClasses) {
this.numberOfClasses = numberOfClasses;
}
private class ElementaryModel implements Serializable, Comparable<ElementaryModel> {
private static final long serialVersionUID = 6124398178368647304L;
private final SparseVector x;
private double alpha;
private final long age;
public ElementaryModel(long age, SparseVector x, double initialAlpha) {
this.age = age;
this.x = (x == null) ? null : (SparseVector) x.clone();
this.alpha = initialAlpha;
}
public Object clone() {
return new ElementaryModel(age, x, alpha);
}
public void update(double multiplier) {
alpha *= multiplier;
}
public double alpha() {
return alpha;
}
public SparseVector x() {
return x;
}
@Override
public boolean equals(Object o) {
if (o != null && o instanceof ElementaryModel) {
ElementaryModel m = (ElementaryModel) o;
return m.x.equals(x) && m.alpha == alpha && m.age == age;
}
return false;
}
@Override
public int compareTo(ElementaryModel o) {
if (age < o.age) {
return 1;
}
if (age > o.age) {
return -1;
}
return 0;
}
@Override
public String toString() {
return age + "";
}
}
private class BoundedQueue implements Iterable<ElementaryModel> {
private final Queue<ElementaryModel> q;
private final int size;
public BoundedQueue(int k) {
size = k;
q = new LinkedList<ElementaryModel>();
}
public Object clone() {
BoundedQueue ret = new BoundedQueue(size);
for (ElementaryModel p : q) {
ret.offer((ElementaryModel) p.clone());
}
return ret;
}
public int size() {
return Math.min(size, q.size());
}
public Iterator<ElementaryModel> iterator() {
return new BoundedQueueIterator(q.iterator());
}
// O(1)
public boolean offer(ElementaryModel e) {
if (q.size() >= size) {
q.poll();
}
q.offer(e);
return true;
}
// O(1)
public ElementaryModel poll() {
return q.poll();
}
// O(1)
public ElementaryModel peek() {
return q.peek();
}
// O(size)
public String toString() {
StringBuffer out = new StringBuffer("Queue:");
for (ElementaryModel p : this) {
out.append('\t').append(p.toString());
}
return out.toString();
}
}
private class BoundedQueueIterator implements Iterator<ElementaryModel> {
private final Iterator<ElementaryModel> origIter;
public BoundedQueueIterator(Iterator<ElementaryModel> iter) {
origIter = iter;
}
@Override
public boolean hasNext() {
return origIter.hasNext();
}
@Override
public ElementaryModel next() {
return origIter.next();
}
@Override
public void remove() {
throw new RuntimeException("Remove is not supported!");
}
}
public void setLambda(double lambda) {
this.lambda = lambda;
}
public double getLambda() {
return this.lambda;
}
public void setKernel(Kernel kernel) {
this.kernel = kernel;
}
public Kernel getKernel() {
return this.kernel;
}
private static double evaluate(Model model, InstanceHolder evalSet) {
double MAError = 0.0;
for (int i = 0; i < evalSet.size(); i++) {
double predicted = model.predict(evalSet.getInstance(i));
double expected = evalSet.getLabel(i);
MAError += Math.abs(expected - predicted);
}
MAError /= evalSet.size();
return MAError;
}
public static void main(String[] args) throws Exception {
if (args.length == 5 || args.length == 6 || args.length == 7) {
NormaSVM svm = new NormaSVM();
svm.setLambda(Double.parseDouble(args[2]));
Kernel kernel = (Kernel) Class.forName(args[3]).newInstance();
svm.setKernel(kernel);
int iters = Integer.parseInt(args[4]);
long seed = (args.length >= 6) ? Long.parseLong(args[5]) : 1234567890;
Random rand = new Random(seed);
if (kernel instanceof RBFKernel && args.length >= 7) {
((RBFKernel)kernel).setSigma(Double.parseDouble(args[6]));
}
System.err.println("Applying NormaSVM with\n lambda=" + svm.getLambda() + "\n kernel=" + svm.getKernel().getClass().getCanonicalName() + "\n iters=" + iters + "\n seed=" + seed + ((kernel instanceof RBFKernel) ? "\n sigma=" + ((RBFKernel)kernel).getSigma() : "" ));
DataBaseReader r = DataBaseReader.createDataBaseReader("gossipLearning.DataBaseReader", new File(args[0]), new File(args[1]));
InstanceHolder train = r.getTrainingSet();
- InstanceHolder eval = r.getTrainingSet();
+ InstanceHolder eval = r.getEvalSet();
for (int iter = 0; iter < iters*train.size(); iter ++) {
int i = rand.nextInt(train.size());
SparseVector x = train.getInstance(i);
double y = train.getLabel(i);
svm.update(x, y);
System.out.println(iter + "\t" + evaluate(svm, train) + "\t" + evaluate(svm, eval));
}
} else {
System.err.println("Usage: java -cp ... gossipLearning.models.regression.NormaSVM train test lambda kernel iters [seed]");
}
}
}
| true | true | public static void main(String[] args) throws Exception {
if (args.length == 5 || args.length == 6 || args.length == 7) {
NormaSVM svm = new NormaSVM();
svm.setLambda(Double.parseDouble(args[2]));
Kernel kernel = (Kernel) Class.forName(args[3]).newInstance();
svm.setKernel(kernel);
int iters = Integer.parseInt(args[4]);
long seed = (args.length >= 6) ? Long.parseLong(args[5]) : 1234567890;
Random rand = new Random(seed);
if (kernel instanceof RBFKernel && args.length >= 7) {
((RBFKernel)kernel).setSigma(Double.parseDouble(args[6]));
}
System.err.println("Applying NormaSVM with\n lambda=" + svm.getLambda() + "\n kernel=" + svm.getKernel().getClass().getCanonicalName() + "\n iters=" + iters + "\n seed=" + seed + ((kernel instanceof RBFKernel) ? "\n sigma=" + ((RBFKernel)kernel).getSigma() : "" ));
DataBaseReader r = DataBaseReader.createDataBaseReader("gossipLearning.DataBaseReader", new File(args[0]), new File(args[1]));
InstanceHolder train = r.getTrainingSet();
InstanceHolder eval = r.getTrainingSet();
for (int iter = 0; iter < iters*train.size(); iter ++) {
int i = rand.nextInt(train.size());
SparseVector x = train.getInstance(i);
double y = train.getLabel(i);
svm.update(x, y);
System.out.println(iter + "\t" + evaluate(svm, train) + "\t" + evaluate(svm, eval));
}
} else {
System.err.println("Usage: java -cp ... gossipLearning.models.regression.NormaSVM train test lambda kernel iters [seed]");
}
}
| public static void main(String[] args) throws Exception {
if (args.length == 5 || args.length == 6 || args.length == 7) {
NormaSVM svm = new NormaSVM();
svm.setLambda(Double.parseDouble(args[2]));
Kernel kernel = (Kernel) Class.forName(args[3]).newInstance();
svm.setKernel(kernel);
int iters = Integer.parseInt(args[4]);
long seed = (args.length >= 6) ? Long.parseLong(args[5]) : 1234567890;
Random rand = new Random(seed);
if (kernel instanceof RBFKernel && args.length >= 7) {
((RBFKernel)kernel).setSigma(Double.parseDouble(args[6]));
}
System.err.println("Applying NormaSVM with\n lambda=" + svm.getLambda() + "\n kernel=" + svm.getKernel().getClass().getCanonicalName() + "\n iters=" + iters + "\n seed=" + seed + ((kernel instanceof RBFKernel) ? "\n sigma=" + ((RBFKernel)kernel).getSigma() : "" ));
DataBaseReader r = DataBaseReader.createDataBaseReader("gossipLearning.DataBaseReader", new File(args[0]), new File(args[1]));
InstanceHolder train = r.getTrainingSet();
InstanceHolder eval = r.getEvalSet();
for (int iter = 0; iter < iters*train.size(); iter ++) {
int i = rand.nextInt(train.size());
SparseVector x = train.getInstance(i);
double y = train.getLabel(i);
svm.update(x, y);
System.out.println(iter + "\t" + evaluate(svm, train) + "\t" + evaluate(svm, eval));
}
} else {
System.err.println("Usage: java -cp ... gossipLearning.models.regression.NormaSVM train test lambda kernel iters [seed]");
}
}
|
diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/full/From36to37.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/full/From36to37.java
index 30093f327..782c9265e 100644
--- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/full/From36to37.java
+++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/full/From36to37.java
@@ -1,49 +1,49 @@
/*******************************************************************************
* Copyright (c) 2011 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.equinox.p2.tests.full;
import java.io.File;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.equinox.internal.p2.engine.SimpleProfileRegistry;
import org.eclipse.equinox.p2.tests.reconciler.dropins.AbstractReconcilerTest;
import org.eclipse.equinox.p2.tests.reconciler.dropins.ReconcilerTestSuite;
public class From36to37 extends AbstractReconcilerTest {
public From36to37(String string) {
super(string);
}
public static Test suite() {
TestSuite suite = new ReconcilerTestSuite("org.eclipse.equinox.p2.reconciler.tests.lastrelease.platform.archive");
suite.addTest(new From36to37("from36To37"));
return suite;
}
public void from36To37() {
assertInitialized();
String currentBuildRepo = System.getProperty("org.eclipse.equinox.p2.tests.current.build.repo");
if (currentBuildRepo == null)
currentBuildRepo = "http://download.eclipse.org/eclipse/updates/3.7-I-builds";
runInitialize("Initializing 3.6 to get the profile paths properly setup.");
SimpleProfileRegistry registry = new SimpleProfileRegistry(getAgent(), new File(output, "eclipse/p2/org.eclipse.equinox.p2.engine/profileRegistry/"), null, false);
String initialTimestamp = Long.toString(registry.getProfile("PlatformProfile").getTimestamp());
//Take 3.6 archive, unzip, run it to update to 3.7
assertEquals(0, runDirectorToUpdate("Updating from 3.6 to 3.7", currentBuildRepo, "org.eclipse.platform.ide", "org.eclipse.platform.ide"));
assertEquals(0, installAndRunVerifierBundle(null));
// revert to 3.6
assertEquals(0, runDirectorToRevert("Reverting from 3.7 to 3.6", "http://download.eclipse.org/eclipse/updates/3.6", initialTimestamp));
- assertEquals(0, installAndRunVerifierBundle35(null));
+ assertEquals(0, installAndRunVerifierBundle(null));
}
}
| true | true | public void from36To37() {
assertInitialized();
String currentBuildRepo = System.getProperty("org.eclipse.equinox.p2.tests.current.build.repo");
if (currentBuildRepo == null)
currentBuildRepo = "http://download.eclipse.org/eclipse/updates/3.7-I-builds";
runInitialize("Initializing 3.6 to get the profile paths properly setup.");
SimpleProfileRegistry registry = new SimpleProfileRegistry(getAgent(), new File(output, "eclipse/p2/org.eclipse.equinox.p2.engine/profileRegistry/"), null, false);
String initialTimestamp = Long.toString(registry.getProfile("PlatformProfile").getTimestamp());
//Take 3.6 archive, unzip, run it to update to 3.7
assertEquals(0, runDirectorToUpdate("Updating from 3.6 to 3.7", currentBuildRepo, "org.eclipse.platform.ide", "org.eclipse.platform.ide"));
assertEquals(0, installAndRunVerifierBundle(null));
// revert to 3.6
assertEquals(0, runDirectorToRevert("Reverting from 3.7 to 3.6", "http://download.eclipse.org/eclipse/updates/3.6", initialTimestamp));
assertEquals(0, installAndRunVerifierBundle35(null));
}
| public void from36To37() {
assertInitialized();
String currentBuildRepo = System.getProperty("org.eclipse.equinox.p2.tests.current.build.repo");
if (currentBuildRepo == null)
currentBuildRepo = "http://download.eclipse.org/eclipse/updates/3.7-I-builds";
runInitialize("Initializing 3.6 to get the profile paths properly setup.");
SimpleProfileRegistry registry = new SimpleProfileRegistry(getAgent(), new File(output, "eclipse/p2/org.eclipse.equinox.p2.engine/profileRegistry/"), null, false);
String initialTimestamp = Long.toString(registry.getProfile("PlatformProfile").getTimestamp());
//Take 3.6 archive, unzip, run it to update to 3.7
assertEquals(0, runDirectorToUpdate("Updating from 3.6 to 3.7", currentBuildRepo, "org.eclipse.platform.ide", "org.eclipse.platform.ide"));
assertEquals(0, installAndRunVerifierBundle(null));
// revert to 3.6
assertEquals(0, runDirectorToRevert("Reverting from 3.7 to 3.6", "http://download.eclipse.org/eclipse/updates/3.6", initialTimestamp));
assertEquals(0, installAndRunVerifierBundle(null));
}
|
diff --git a/src/main/java/net/aufdemrand/denizen/scripts/commands/core/AnimateChestCommand.java b/src/main/java/net/aufdemrand/denizen/scripts/commands/core/AnimateChestCommand.java
index 454479d2d..e061b6e2e 100644
--- a/src/main/java/net/aufdemrand/denizen/scripts/commands/core/AnimateChestCommand.java
+++ b/src/main/java/net/aufdemrand/denizen/scripts/commands/core/AnimateChestCommand.java
@@ -1,73 +1,73 @@
package net.aufdemrand.denizen.scripts.commands.core;
import org.bukkit.Location;
import org.bukkit.Sound;
import net.aufdemrand.denizen.exceptions.CommandExecutionException;
import net.aufdemrand.denizen.exceptions.InvalidArgumentsException;
import net.aufdemrand.denizen.scripts.ScriptEntry;
import net.aufdemrand.denizen.scripts.commands.AbstractCommand;
import net.aufdemrand.denizen.utilities.arguments.aH;
import net.aufdemrand.denizen.utilities.arguments.aH.ArgumentType;
import net.aufdemrand.denizen.utilities.debugging.dB;
public class AnimateChestCommand extends AbstractCommand {
enum ChestAction { OPEN, CLOSE }
@Override
public void parseArgs(ScriptEntry scriptEntry)
throws InvalidArgumentsException {
String chestAction = "OPEN";
Location location = null;
Boolean sound = true;
for (String arg : scriptEntry.getArguments()) {
if (aH.matchesArg("OPEN, CLOSE", arg)) {
chestAction = aH.getStringFrom(arg);
dB.echoDebug("...chest action set: " + chestAction);
} else if (aH.matchesLocation(arg)) {
location = aH.getLocationFrom(arg);
dB.echoDebug("...location set");
- } else if (aH.matchesValueArg("SOUND", arg, ArgumentType.Boolean)) {
+ } else if (aH.matchesValueArg("SOUND", arg, ArgumentType.Custom)) {
sound = aH.getBooleanFrom(arg);
if (sound) dB.echoDebug("...sound enabled");
else dB.echoDebug("...sound disabled");
} else throw new InvalidArgumentsException(dB.Messages.ERROR_UNKNOWN_ARGUMENT, arg);
}
if (location == null) dB.echoError("...location is invalid");
scriptEntry.addObject("location", location)
.addObject("sound", sound)
.addObject("chestAction", chestAction);
}
@Override
public void execute(ScriptEntry scriptEntry)
throws CommandExecutionException {
Location location = (Location) scriptEntry.getObject("location");
ChestAction action = ChestAction.valueOf(((String) scriptEntry.getObject("chestAction")).toUpperCase());
Boolean sound = (Boolean) scriptEntry.getObject("sound");
switch (action) {
case OPEN:
if (sound) scriptEntry.getPlayer().playSound(location, Sound.CHEST_OPEN, 1, 1);
scriptEntry.getPlayer().playNote(location, (byte)1, (byte)1);
dB.echoDebug("...opening chest");
break;
case CLOSE:
if (sound) scriptEntry.getPlayer().playSound(location, Sound.CHEST_CLOSE, 1, 1);
scriptEntry.getPlayer().playNote(location, (byte)1, (byte)0);
dB.echoDebug("...closing chest");
break;
default:
dB.echoError("...error animating chest");
break;
}
}
}
| true | true | public void parseArgs(ScriptEntry scriptEntry)
throws InvalidArgumentsException {
String chestAction = "OPEN";
Location location = null;
Boolean sound = true;
for (String arg : scriptEntry.getArguments()) {
if (aH.matchesArg("OPEN, CLOSE", arg)) {
chestAction = aH.getStringFrom(arg);
dB.echoDebug("...chest action set: " + chestAction);
} else if (aH.matchesLocation(arg)) {
location = aH.getLocationFrom(arg);
dB.echoDebug("...location set");
} else if (aH.matchesValueArg("SOUND", arg, ArgumentType.Boolean)) {
sound = aH.getBooleanFrom(arg);
if (sound) dB.echoDebug("...sound enabled");
else dB.echoDebug("...sound disabled");
} else throw new InvalidArgumentsException(dB.Messages.ERROR_UNKNOWN_ARGUMENT, arg);
}
if (location == null) dB.echoError("...location is invalid");
scriptEntry.addObject("location", location)
.addObject("sound", sound)
.addObject("chestAction", chestAction);
}
| public void parseArgs(ScriptEntry scriptEntry)
throws InvalidArgumentsException {
String chestAction = "OPEN";
Location location = null;
Boolean sound = true;
for (String arg : scriptEntry.getArguments()) {
if (aH.matchesArg("OPEN, CLOSE", arg)) {
chestAction = aH.getStringFrom(arg);
dB.echoDebug("...chest action set: " + chestAction);
} else if (aH.matchesLocation(arg)) {
location = aH.getLocationFrom(arg);
dB.echoDebug("...location set");
} else if (aH.matchesValueArg("SOUND", arg, ArgumentType.Custom)) {
sound = aH.getBooleanFrom(arg);
if (sound) dB.echoDebug("...sound enabled");
else dB.echoDebug("...sound disabled");
} else throw new InvalidArgumentsException(dB.Messages.ERROR_UNKNOWN_ARGUMENT, arg);
}
if (location == null) dB.echoError("...location is invalid");
scriptEntry.addObject("location", location)
.addObject("sound", sound)
.addObject("chestAction", chestAction);
}
|
diff --git a/src/main/java/org/mgenterprises/java/bukkit/gmcfps/Core/Weapons/ProjectileWeapon.java b/src/main/java/org/mgenterprises/java/bukkit/gmcfps/Core/Weapons/ProjectileWeapon.java
index f532156..f2d9a94 100644
--- a/src/main/java/org/mgenterprises/java/bukkit/gmcfps/Core/Weapons/ProjectileWeapon.java
+++ b/src/main/java/org/mgenterprises/java/bukkit/gmcfps/Core/Weapons/ProjectileWeapon.java
@@ -1,95 +1,96 @@
/*
* The MIT License
*
* Copyright 2013 Manuel Gauto.
*
* 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.mgenterprises.java.bukkit.gmcfps.Core.Weapons;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.inventory.ItemStack;
import org.mgenterprises.java.bukkit.gmcfps.Core.InternalEvents.Events.WeaponFiredEvent;
/**
*
* @author Manuel Gauto
*/
public abstract class ProjectileWeapon extends Weapon {
private Material ammoMaterial;
private EntityType projectileType;
private int fireDelay;
public ProjectileWeapon(WeaponManager wm, String name, Material m, Material ammoType, EntityType projectileType, int fireDelay) {
super(wm, name, m);
this.ammoMaterial = ammoType;
this.fireDelay = fireDelay;
this.projectileType = projectileType;
}
public Material getAmmunitionType() {
return this.ammoMaterial;
}
public abstract void onWeaponFire(Player p);
@Override
public void onWeaponRightClick(WeaponFiredEvent event) {
//System.out.println(event);
if(super.getWeaponManager().waiting.contains(event.getPlayer().getName())){
return;
}
boolean hasAmmoLeft = event.getPlayer().getInventory().contains(ammoMaterial);
if (hasAmmoLeft) {
int slot = event.getPlayer().getInventory().first(ammoMaterial);
if(slot > -1){
ItemStack itemStack = event.getPlayer().getInventory().getItem(slot);
itemStack.setAmount(itemStack.getAmount()-1);
event.getPlayer().getInventory().setItem(slot,itemStack);
+ event.getPlayer().updateInventory();
onWeaponFire(event.getPlayer());
scheduleDelay(event.getPlayer());
}
}
}
@Override
public boolean isThrowable() {
return false;
}
@Override
public boolean isProjectile() {
return true;
}
public EntityType getProjectileType(){
return this.projectileType;
}
public abstract void onProjectileHit(EntityDamageByEntityEvent event);
private void scheduleDelay(Player p) {
Bukkit.getScheduler().scheduleSyncDelayedTask(super.getWeaponManager().getFPSCore().getPluginReference(), new DelayRunnable(super.getWeaponManager().getFPSCore(), p), this.fireDelay);
}
}
| true | true | public void onWeaponRightClick(WeaponFiredEvent event) {
//System.out.println(event);
if(super.getWeaponManager().waiting.contains(event.getPlayer().getName())){
return;
}
boolean hasAmmoLeft = event.getPlayer().getInventory().contains(ammoMaterial);
if (hasAmmoLeft) {
int slot = event.getPlayer().getInventory().first(ammoMaterial);
if(slot > -1){
ItemStack itemStack = event.getPlayer().getInventory().getItem(slot);
itemStack.setAmount(itemStack.getAmount()-1);
event.getPlayer().getInventory().setItem(slot,itemStack);
onWeaponFire(event.getPlayer());
scheduleDelay(event.getPlayer());
}
}
}
| public void onWeaponRightClick(WeaponFiredEvent event) {
//System.out.println(event);
if(super.getWeaponManager().waiting.contains(event.getPlayer().getName())){
return;
}
boolean hasAmmoLeft = event.getPlayer().getInventory().contains(ammoMaterial);
if (hasAmmoLeft) {
int slot = event.getPlayer().getInventory().first(ammoMaterial);
if(slot > -1){
ItemStack itemStack = event.getPlayer().getInventory().getItem(slot);
itemStack.setAmount(itemStack.getAmount()-1);
event.getPlayer().getInventory().setItem(slot,itemStack);
event.getPlayer().updateInventory();
onWeaponFire(event.getPlayer());
scheduleDelay(event.getPlayer());
}
}
}
|
diff --git a/AMBroSIA/src/game/Logic.java b/AMBroSIA/src/game/Logic.java
index 79a5fbc..257b87d 100644
--- a/AMBroSIA/src/game/Logic.java
+++ b/AMBroSIA/src/game/Logic.java
@@ -1,305 +1,306 @@
package game;
import gui.MenuGUI;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
/**
* The purpose of the
* <code>Logic</code> class is to manage all other classes and methods in such a
* way as to produce a playable game. This includes (but is not limited to)
* calling for the creation of the main menu, displaying the leaderboard or
* starting the game in either single or two player mode as appropriate,
* depending on player actions.
*
* @author Nikolaos, Michael, Anthony
*
*/
public class Logic extends KeyAdapter implements ActionListener {
/**
* Value of maximum level.
*/
final public static int MAX_LEVEL = 30;
//various essential objects
private static GameState gameState;
private static ActionListener buttonPress = new Logic();
private static KeyListener keyboard = new Logic();
private static MenuGUI gui;
private static GraphicsEngine graphicsEngine;
private static Physics physicsEngine;
private static timeToLive ttlLogic;
private static Collision collisionCheck;
private static Progression gameProgress;
private static AI gameAI;
//fire rate limiter variables
private static long initialShootTime;
private static long currentShootTime;
private static boolean shootKeyReleased = true;
private static int shootCounter = 0;
//is game paused boolean
private boolean paused = false;
//the service used to execute all update functions
private static ScheduledExecutorService timer;
//logger, global logging level
private final static Logger log = Logger.getLogger(Logic.class.getName());
/**
* Logging level control - from no logging output to full logging.
*/
public final static Level LOG_LEVEL = Level.OFF;
/**
* Main method; creates the main menu and acts as appropriate depending on
* player input.
*
* @param args
*/
public static void main(String args[]) {
GameAssets.loadSounds();
//set log configuration to defaults
BasicConfigurator.configure();
//create, display gui
gui = new MenuGUI(buttonPress, keyboard);
gui.showMenu();
log.setLevel(LOG_LEVEL);
log.info("GUI has been started");
//background music - different exception handles for jdk6 compatibility
GameAssets.theme.playLoop();
}
/**
* Start the global timer responsible for keeping all game elements up to
* date. The timer will use some form of multithreading to execute update
* tasks concurrently.
*/
public static void startTimer() {
timer = Executors.newScheduledThreadPool(4);
timer.scheduleAtFixedRate(graphicsEngine, 0, 17, TimeUnit.MILLISECONDS);
timer.scheduleAtFixedRate(physicsEngine, 0, 17, TimeUnit.MILLISECONDS);
timer.scheduleAtFixedRate(collisionCheck, 0, 17, TimeUnit.MILLISECONDS);
timer.scheduleAtFixedRate(gui, 0, 17, TimeUnit.MILLISECONDS);
timer.scheduleAtFixedRate(ttlLogic, 0, 200, TimeUnit.MILLISECONDS);
timer.scheduleAtFixedRate(gameProgress, 0, 1, TimeUnit.SECONDS);
timer.scheduleAtFixedRate(gameAI, 0, 500, TimeUnit.MILLISECONDS);
}
/**
* Stops the timer.
*/
public static void stopTimer() {
timer.shutdown();
}
/**
* ?
*
* @param command
* @param delay
* @param unit
*/
public static void executeTask(Runnable command, long delay, TimeUnit unit) {
timer.schedule(command, delay, unit);
}
/**
* Start the single player game.
*/
public static void startSinglePlayer() {
GameAssets.theme.stop();
setUpLevel(false);
}
/**
* Starts the game in 2 player mode.
*/
public static void startTwoPlayer() {
GameAssets.theme.stop();
setUpLevel(true);
}
/**
* Shows tutorial information to the player.
*/
public static void showTutorial() {
}
/**
* Checks if the game is paused.
*
* @return true if game is paused, false otherwise
*/
public boolean isPaused() {
return paused;
}
/**
* Displays "Game Over" message.
*/
public static void displayGameOver(boolean singleP) {
GameAssets.theme.stop();
gui.displayGameOver(gameState, singleP);
}
/**
* Display information relevant to player two's turn.
*/
public static void displayPlayerTwoTurn() {
}
//set up some game essentials
private static void setUpLevel(boolean twoPlayer) {
gameState = new GameState();
graphicsEngine = new GraphicsEngine(gameState);
physicsEngine = new Physics(gameState);
ttlLogic = new timeToLive(gameState);
collisionCheck = new Collision(gameState, physicsEngine);
gameProgress = new Progression(gameState,twoPlayer);
gameAI = new AI(gameState);
gameProgress.setupInitialLevel();
}
//called whenever a key is pressed (thread seperate from timer)
/**
* Handles event caused by user key presses.
*
* @param e
*/
@Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
PlayerShip player = gameState.getPlayerShip();
//handles most basic key commands. Should activate a boolean stating that the key has been pressed
if (keyCode == KeyEvent.VK_UP) {
//accelerate
if (!paused && player != null) {
player.accelerate(true);
GameAssets.thrusters.playLoop();
}
} else if (keyCode == KeyEvent.VK_LEFT) {
if (!paused && player != null) {
player.turnLeft(true);
}
} else if (keyCode == KeyEvent.VK_RIGHT) {
if (!paused && player != null) {
player.turnRight(true);
}
} else if (keyCode == KeyEvent.VK_DOWN) {
if (!paused && player != null) {
player.useBomb();
}
} else if (keyCode == KeyEvent.VK_SPACE) {
if(gameState.getPlayerShip() != null){
if (shootKeyReleased) {
initialShootTime = System.currentTimeMillis();
shootKeyReleased = false;
shootCounter = 0;
player.shoot();
} else if (!shootKeyReleased) {
currentShootTime = System.currentTimeMillis();
while ((currentShootTime - initialShootTime) > PlayerShip.FIRE_RATE * 1200 && shootCounter < 1) {
player.shootDirection();
shootCounter++;
initialShootTime = currentShootTime;
}
}
}
} else if (keyCode == KeyEvent.VK_P) {
if (!paused) {
stopTimer();
paused = true;
} else {
startTimer();
paused = false;
}
} else if (keyCode == KeyEvent.VK_B) {
if (!paused && player != null) {
player.useBomb();
}
} else if (keyCode == KeyEvent.VK_Z) {
Random randu = new Random();
gameState.addAsteroid(new Asteroid(new float[]{1.5f, 1.5f}, randu.nextInt(360), new int[]{randu.nextInt(700), randu.nextInt(500)}, gameState, Asteroid.LARGE_ASTEROID_SIZE));
//gameState.addAsteroid(new Asteroid(new float[]{Difficulty.randomAsteroidVelocity(10), Difficulty.randomHeading()}, randu.nextInt(360), new int[]{randu.nextInt(700), randu.nextInt(500)}, gameState, Asteroid.LARGE_ASTEROID_SIZE));
//gameState.addProjectile(new Projectile(gameState.getAlienShip(), randu.nextInt(360), new int[] {gameState.getAlienShip().getX(), gameState.getAlienShip().getY()}, gameState));
} else if (keyCode == KeyEvent.VK_ESCAPE) {
//may have to add if statement for two player here
stopTimer();
+ paused = false;
GameAssets.theme.stop();
displayGameOver(true);
}
}
//same as keyPressed, except when it is released
/**
* Handle events caused by release of key.
*
* @param e
*/
@Override
public void keyReleased(KeyEvent e) {
int keyCode = e.getKeyCode();
PlayerShip player = gameState.getPlayerShip();
//stops doing whatever that keypress was doing
if (keyCode == KeyEvent.VK_UP) {
//accelerate
if (player != null) {
player.accelerate(false);
GameAssets.thrusters.stop();
}
} else if (keyCode == KeyEvent.VK_LEFT) {
if (player != null) {
player.turnLeft(false);
}
} else if (keyCode == KeyEvent.VK_RIGHT) {
if (player != null) {
player.turnRight(false);
}
} else if (keyCode == KeyEvent.VK_SPACE) {
shootKeyReleased = true;
}
}
//This section needs a LOT of work....
//called when a gui button is clicked
/**
* Handles events relating to the user clicking menu buttons.
*
* @param e
*/
@Override
public void actionPerformed(ActionEvent e) {
Object action = e.getSource();
if (action == gui.singlePbutton) {
startSinglePlayer();
gui.displaySingleP(gameState);
startTimer();
} else if (action == gui.twoPbutton) {
startTwoPlayer();
gui.displayTwoP(gameState);
startTimer();
} else if (action == gui.leaderBoardButton) {
gui.displayLeaderBoard();
} else if (action == gui.tutorialButton) {
gui.displayTutorial();
} else if (action == gui.backButton) {
gui.goBack();
} else if (e.getSource() == gui.quitButton) {
System.exit(0);
}
}
}
| true | true | public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
PlayerShip player = gameState.getPlayerShip();
//handles most basic key commands. Should activate a boolean stating that the key has been pressed
if (keyCode == KeyEvent.VK_UP) {
//accelerate
if (!paused && player != null) {
player.accelerate(true);
GameAssets.thrusters.playLoop();
}
} else if (keyCode == KeyEvent.VK_LEFT) {
if (!paused && player != null) {
player.turnLeft(true);
}
} else if (keyCode == KeyEvent.VK_RIGHT) {
if (!paused && player != null) {
player.turnRight(true);
}
} else if (keyCode == KeyEvent.VK_DOWN) {
if (!paused && player != null) {
player.useBomb();
}
} else if (keyCode == KeyEvent.VK_SPACE) {
if(gameState.getPlayerShip() != null){
if (shootKeyReleased) {
initialShootTime = System.currentTimeMillis();
shootKeyReleased = false;
shootCounter = 0;
player.shoot();
} else if (!shootKeyReleased) {
currentShootTime = System.currentTimeMillis();
while ((currentShootTime - initialShootTime) > PlayerShip.FIRE_RATE * 1200 && shootCounter < 1) {
player.shootDirection();
shootCounter++;
initialShootTime = currentShootTime;
}
}
}
} else if (keyCode == KeyEvent.VK_P) {
if (!paused) {
stopTimer();
paused = true;
} else {
startTimer();
paused = false;
}
} else if (keyCode == KeyEvent.VK_B) {
if (!paused && player != null) {
player.useBomb();
}
} else if (keyCode == KeyEvent.VK_Z) {
Random randu = new Random();
gameState.addAsteroid(new Asteroid(new float[]{1.5f, 1.5f}, randu.nextInt(360), new int[]{randu.nextInt(700), randu.nextInt(500)}, gameState, Asteroid.LARGE_ASTEROID_SIZE));
//gameState.addAsteroid(new Asteroid(new float[]{Difficulty.randomAsteroidVelocity(10), Difficulty.randomHeading()}, randu.nextInt(360), new int[]{randu.nextInt(700), randu.nextInt(500)}, gameState, Asteroid.LARGE_ASTEROID_SIZE));
//gameState.addProjectile(new Projectile(gameState.getAlienShip(), randu.nextInt(360), new int[] {gameState.getAlienShip().getX(), gameState.getAlienShip().getY()}, gameState));
} else if (keyCode == KeyEvent.VK_ESCAPE) {
//may have to add if statement for two player here
stopTimer();
GameAssets.theme.stop();
displayGameOver(true);
}
}
| public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
PlayerShip player = gameState.getPlayerShip();
//handles most basic key commands. Should activate a boolean stating that the key has been pressed
if (keyCode == KeyEvent.VK_UP) {
//accelerate
if (!paused && player != null) {
player.accelerate(true);
GameAssets.thrusters.playLoop();
}
} else if (keyCode == KeyEvent.VK_LEFT) {
if (!paused && player != null) {
player.turnLeft(true);
}
} else if (keyCode == KeyEvent.VK_RIGHT) {
if (!paused && player != null) {
player.turnRight(true);
}
} else if (keyCode == KeyEvent.VK_DOWN) {
if (!paused && player != null) {
player.useBomb();
}
} else if (keyCode == KeyEvent.VK_SPACE) {
if(gameState.getPlayerShip() != null){
if (shootKeyReleased) {
initialShootTime = System.currentTimeMillis();
shootKeyReleased = false;
shootCounter = 0;
player.shoot();
} else if (!shootKeyReleased) {
currentShootTime = System.currentTimeMillis();
while ((currentShootTime - initialShootTime) > PlayerShip.FIRE_RATE * 1200 && shootCounter < 1) {
player.shootDirection();
shootCounter++;
initialShootTime = currentShootTime;
}
}
}
} else if (keyCode == KeyEvent.VK_P) {
if (!paused) {
stopTimer();
paused = true;
} else {
startTimer();
paused = false;
}
} else if (keyCode == KeyEvent.VK_B) {
if (!paused && player != null) {
player.useBomb();
}
} else if (keyCode == KeyEvent.VK_Z) {
Random randu = new Random();
gameState.addAsteroid(new Asteroid(new float[]{1.5f, 1.5f}, randu.nextInt(360), new int[]{randu.nextInt(700), randu.nextInt(500)}, gameState, Asteroid.LARGE_ASTEROID_SIZE));
//gameState.addAsteroid(new Asteroid(new float[]{Difficulty.randomAsteroidVelocity(10), Difficulty.randomHeading()}, randu.nextInt(360), new int[]{randu.nextInt(700), randu.nextInt(500)}, gameState, Asteroid.LARGE_ASTEROID_SIZE));
//gameState.addProjectile(new Projectile(gameState.getAlienShip(), randu.nextInt(360), new int[] {gameState.getAlienShip().getX(), gameState.getAlienShip().getY()}, gameState));
} else if (keyCode == KeyEvent.VK_ESCAPE) {
//may have to add if statement for two player here
stopTimer();
paused = false;
GameAssets.theme.stop();
displayGameOver(true);
}
}
|
diff --git a/src/main/java/recs/EntityWorld.java b/src/main/java/recs/EntityWorld.java
index 07cafaf..eedddec 100644
--- a/src/main/java/recs/EntityWorld.java
+++ b/src/main/java/recs/EntityWorld.java
@@ -1,406 +1,407 @@
package recs;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import recs.utils.BlockingThreadPoolExecutor;
import recs.utils.RECSBits;
import recs.utils.RECSIntSet.Items;
import com.badlogic.gdx.utils.IntMap;
import com.badlogic.gdx.utils.IntMap.Keys;
import com.badlogic.gdx.utils.ObjectMap;
/**
* The main world class connecting all the logic. Add Entities with components
* and systems to this class and call the process method.
*
* @author Enrico van Oosten
*/
public final class EntityWorld {
/**
* Global thread pool used by TaskSystems
*/
private static BlockingThreadPoolExecutor threads = new BlockingThreadPoolExecutor(2, 10);
/**
* Maps used to temporarily store added/removed components from entities
* that are not yet added to the EntityWorld.
*/
private static ObjectMap<Entity, List<Component>> scheduledAdds = new ObjectMap<Entity, List<Component>>();
private static ObjectMap<Entity, List<Component>> scheduledRemoves = new ObjectMap<Entity, List<Component>>();
/**
* Contains all the entities so they can be retrieved with getEntity
*/
private final IntMap<Entity> addedEntities;
/**
* Managers sepparate logic.
*/
private final EntitySystemManager systemManager;
private final ComponentManager componentManager;
private final EntityDataManager entitydataManager;
private final EventManager eventManager;
/**
* Values used to give entities an unique id.
*/
private final RECSBits entityIds;
private int lastUsedId = 0;
private int numFreedIds = 0;
/**
* Add Entities with components and systems to this class and call the
* process method.
*/
public EntityWorld() {
systemManager = new EntitySystemManager(this);
componentManager = new ComponentManager(this);
entitydataManager = new EntityDataManager(this);
eventManager = new EventManager();
addedEntities = new IntMap<Entity>();
entityIds = new RECSBits();
}
/**
* Process all the systems.
*
* @param deltaInSec
* The time passed in seconds since the last update.
* EntityTaskSystems are updated independantly of this delta.
*/
public void process(float deltaInSec) {
systemManager.process(deltaInSec);
}
/**
* Add an entitiy to the world so it can be processed by the systems.
*/
public void addEntity(Entity entity) {
int id = getNewEntityId();
entity.id = id;
addedEntities.put(id, entity);
+ entityIds.set(id);
Class<? extends Entity> entityClass = entity.getClass();
// Read reflection data and use it to add all the components that were
// declared as fields.
EntityReflection reflection = entitydataManager.getReflection(entityClass);
entity.data = reflection.data;
if (entity.getClass() != Entity.class) {
Keys k = reflection.componentFields.keys();
while (k.hasNext) {
int next = k.next();
Field field = reflection.componentFields.get(next);
ComponentMapper<? extends Component> mapper = componentManager.getComponentMapper(next);
try {
mapper.add(id, (Component) field.get(entity));
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
// Add all the components that were added to the entity before the
// entity was added to the world.
List<Component> scheduleAddList = scheduledAdds.remove(entity);
if (scheduleAddList != null) {
componentManager.addComponent(entity, scheduleAddList.toArray(new Component[0]));
}
// Remove all the components that were removed from the entity before
// the entity was added to the world.
List<Component> scheduledRemovesList = scheduledRemoves.remove(entity);
if (scheduledRemovesList != null) {
componentManager.removeComponent(entity, scheduledRemovesList.toArray(new Component[0]));
}
//Add the entity to the systems.
systemManager.addEntityToSystems(entity, entity.data.systemBits);
}
public Entity removeEntity(int entityId) {
numFreedIds++;
Entity e = getEntity(entityId);
if (e == null)
throw new RuntimeException("Entity was not added to this world: " + entityId);
//remove the entity from all its systems.
systemManager.removeEntityFromSystems(e, e.data.systemBits);
//Remove all the entities components from the componentmappers.
componentManager.removeEntityFromMappers(e);
//Free the entities id for reuse
entityIds.clear(entityId);
return addedEntities.remove(entityId);
}
/**
* Retrieve an entity using its id.
*/
public Entity getEntity(int entityId) {
return addedEntities.get(entityId);
}
public IntMap<Entity> getAddedEntities() {
return addedEntities;
}
/**
* Add an EntitySystem(s) to the world.
*/
public void addSystem(EntitySystem... systems) {
//register the systems
for(EntitySystem system: systems)
systemManager.addSystem(system);
if (addedEntities.size == 0)
return;
//for every entity in the world
for (Entity e : addedEntities.values()) {
//Get the updated system bits which include the bits for the new systems
RECSBits newSystemBits = systemManager.getSystemBits(e.data.componentBits);
RECSBits oldSystemBits = e.data.systemBits;
//Compare the new systembits with the old systembits and add the entity to all
//the systems that were added for the entity.
RECSBits addedSystemBits = oldSystemBits.getAddedBits(newSystemBits);
systemManager.addEntityToSystems(e, addedSystemBits);
//Set the old systembits to the new one.
e.data.systemBits.copy(newSystemBits);
}
}
/**
* Remove an EntitySystem from the world
*/
public void removeSystem(EntitySystem system) {
Items i = system.entityIds.items();
while (i.hasNext)
system.removeEntity(i.next());
entitydataManager.removeSystem(system.id);
systemManager.removeSystem(system);
}
/**
* Get a component of an entity. Always use a ComponentMapper<T> instead of
* this to retrieve components.
*
* @param entityId
* The id of the entity.
* @param componentClass
* The type of that component
* @return The component
*/
public <T extends Component> T getComponent(int entityId, Class<T> componentClass) {
return componentManager.getComponent(entityId, componentClass);
}
/**
* Get a componentMapper so you can efficiently retrieve components from Entities using
* the class of a component.
*/
public <T extends Component> ComponentMapper<T> getComponentMapper(Class<T> componentClass) {
return componentManager.getComponentMapper(componentClass);
}
/**
* Get a component with the componentId from the entity with entityId.
*/
public Component getComponent(int entityId, int componentId) {
return componentManager.getComponent(entityId, componentId);
}
/**
* Get a DestructionListener that is notified whenever a component of the
* given class is destroyed.
*/
@SuppressWarnings("rawtypes")
public ComponentDestructionListener getDestructionListener(Class<? extends Component> componentClass) {
return componentManager.getDestructionListener(componentClass);
}
/**
* Send a message to all EntitySystems that are registered to the tag of
* this event.
*
* @param event
* The event.
*/
public void sendEvent(Event event) {
eventManager.sendEvent(event);
}
public static void postRunnable(Runnable task) {
threads.execute(task);
}
/**
* Use this to clear everything in the EntityWorld. Use with care.
*/
public void reset() {
addedEntities.clear();
componentManager.clear();
systemManager.clear();
entitydataManager.clear();
entityIds.clear();
eventManager.clear();
lastUsedId = 0;
numFreedIds = 0;
System.gc();
}
static List<Component> getScheduledAdds(Entity e) {
List<Component> scheduledAdds = EntityWorld.scheduledAdds.get(e);
if (scheduledAdds == null) {
return Collections.unmodifiableList(new ArrayList<Component>());
} else {
return Collections.unmodifiableList(scheduledAdds);
}
}
static List<Component> getScheduledRemoves(Entity e) {
List<Component> scheduledRemoves = EntityWorld.scheduledRemoves.get(e);
if (scheduledRemoves == null) {
return Collections.unmodifiableList(new ArrayList<Component>());
} else {
return Collections.unmodifiableList(scheduledRemoves);
}
}
/**
* Add components to an entity, updating its EntityData and adding it to the new systems.
*/
static void addComponent(Entity e, Component... components) {
EntityData oldData = e.data;
//If an entity is not yet added to a world, its EntityData is null
if (oldData == null) {
//Schedule the component for adding so its added once the entity is added to a world.
List<Component> scheduled = scheduledAdds.get(e);
if (scheduled == null) {
scheduled = new LinkedList<Component>();
scheduledAdds.put(e, scheduled);
}
for (Component o : components)
scheduled.add(o);
//Entity is added to a world.
} else {
EntityWorld world = oldData.world;
//Save the old systemBits;
RECSBits oldSystemBits = oldData.systemBits;
world.componentManager.addComponent(e, components);
//addComponent updates the entities EntityData
EntityData newData = e.data;
RECSBits newSystemBits = newData.systemBits;
RECSBits addedSystemBits = oldSystemBits.getAddedBits(newSystemBits);
world.systemManager.addEntityToSystems(e, addedSystemBits);
}
}
/**
* Remove components to an entity, updating its EntityData and removing it from the old systems.
*/
static void removeComponent(Entity e, Component... components) {
EntityData oldData = e.data;
//If an entity is not yet added to a world, its EntityData is null
if (oldData == null) {
//Schedule the component for removal so its removed once the entity is added to a world.
List<Component> scheduled = scheduledRemoves.get(e);
if (scheduled == null) {
scheduled = new LinkedList<Component>();
scheduledRemoves.put(e, scheduled);
}
for (Component o : components)
scheduled.add(o);
//Entity is added to a world.
} else {
EntityWorld world = oldData.world;
//Save the old systemBits;
RECSBits oldSystemBits = oldData.systemBits;
world.componentManager.removeComponent(e, components);
//removeComponent updates the entities EntityData
EntityData newData = e.data;
RECSBits newSystemBits = newData.systemBits;
RECSBits removedSystemBits = oldSystemBits.getRemovedBits(newSystemBits);
world.systemManager.removeEntityFromSystems(e, removedSystemBits);
}
}
/**
* Get a RECSBits object matching an array of component classes.
*/
RECSBits getComponentBits(Class<? extends Component>[] components) {
RECSBits bits = new RECSBits();
for (Class<? extends Component> c : components)
bits.set(getComponentId(c));
return bits;
}
/**
* Register a DestructionListener to the world so it receives notifications when a component
* of the given class is destroyed.
*/
void registerDestuctionListener(ComponentDestructionListener<?> listener, Class<? extends Component> componentClass) {
componentManager.registerDestuctionListener(listener, componentClass);
}
/**
* Get the systembits matching the given componentbits.
*/
RECSBits getSystemBits(RECSBits componentBits) {
return systemManager.getSystemBits(componentBits);
}
/**
* Get the id of a system.
*/
int getSystemId() {
return systemManager.getNewSystemId();
}
/**
* Get a new EntityId.
*/
int getNewEntityId() {
// if the amount of freed ids is more than 20% of the amount of id's, recycle ids.
if (numFreedIds > entityIds.numBits() * 0.2f) {
lastUsedId = 0;
numFreedIds = 0;
}
//Search for a free id.
while (entityIds.get(++lastUsedId))
entityIds.set(lastUsedId);
return lastUsedId;
}
/**
* Get the id of a component class.
*/
int getComponentId(Class<? extends Component> component) {
return componentManager.getComponentId(component);
}
/**
* Register a system so it can receive events with the specified type.
*/
void registerEventListener(EventListener<? extends Event> listener, Class<? extends Event> eventType) {
eventManager.registerListener(listener, eventType);
}
/**
* Returns {@link EntityDataManager#getEntityData(RECSBits) EntityDataManager.getEntityData(RECSBits componentBits)}
*/
EntityData getEntityData(RECSBits componentBits) {
return entitydataManager.getEntityData(componentBits);
}
}
| true | true | public void addEntity(Entity entity) {
int id = getNewEntityId();
entity.id = id;
addedEntities.put(id, entity);
Class<? extends Entity> entityClass = entity.getClass();
// Read reflection data and use it to add all the components that were
// declared as fields.
EntityReflection reflection = entitydataManager.getReflection(entityClass);
entity.data = reflection.data;
if (entity.getClass() != Entity.class) {
Keys k = reflection.componentFields.keys();
while (k.hasNext) {
int next = k.next();
Field field = reflection.componentFields.get(next);
ComponentMapper<? extends Component> mapper = componentManager.getComponentMapper(next);
try {
mapper.add(id, (Component) field.get(entity));
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
// Add all the components that were added to the entity before the
// entity was added to the world.
List<Component> scheduleAddList = scheduledAdds.remove(entity);
if (scheduleAddList != null) {
componentManager.addComponent(entity, scheduleAddList.toArray(new Component[0]));
}
// Remove all the components that were removed from the entity before
// the entity was added to the world.
List<Component> scheduledRemovesList = scheduledRemoves.remove(entity);
if (scheduledRemovesList != null) {
componentManager.removeComponent(entity, scheduledRemovesList.toArray(new Component[0]));
}
//Add the entity to the systems.
systemManager.addEntityToSystems(entity, entity.data.systemBits);
}
| public void addEntity(Entity entity) {
int id = getNewEntityId();
entity.id = id;
addedEntities.put(id, entity);
entityIds.set(id);
Class<? extends Entity> entityClass = entity.getClass();
// Read reflection data and use it to add all the components that were
// declared as fields.
EntityReflection reflection = entitydataManager.getReflection(entityClass);
entity.data = reflection.data;
if (entity.getClass() != Entity.class) {
Keys k = reflection.componentFields.keys();
while (k.hasNext) {
int next = k.next();
Field field = reflection.componentFields.get(next);
ComponentMapper<? extends Component> mapper = componentManager.getComponentMapper(next);
try {
mapper.add(id, (Component) field.get(entity));
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
// Add all the components that were added to the entity before the
// entity was added to the world.
List<Component> scheduleAddList = scheduledAdds.remove(entity);
if (scheduleAddList != null) {
componentManager.addComponent(entity, scheduleAddList.toArray(new Component[0]));
}
// Remove all the components that were removed from the entity before
// the entity was added to the world.
List<Component> scheduledRemovesList = scheduledRemoves.remove(entity);
if (scheduledRemovesList != null) {
componentManager.removeComponent(entity, scheduledRemovesList.toArray(new Component[0]));
}
//Add the entity to the systems.
systemManager.addEntityToSystems(entity, entity.data.systemBits);
}
|
diff --git a/edu/wisc/ssec/mcidasv/control/ScatterDisplay.java b/edu/wisc/ssec/mcidasv/control/ScatterDisplay.java
index f0d01238a..64d68b4a6 100644
--- a/edu/wisc/ssec/mcidasv/control/ScatterDisplay.java
+++ b/edu/wisc/ssec/mcidasv/control/ScatterDisplay.java
@@ -1,1004 +1,1005 @@
package edu.wisc.ssec.mcidasv.control;
import edu.wisc.ssec.mcidasv.data.hydra.HydraRGBDisplayable;
import edu.wisc.ssec.mcidasv.data.hydra.HistogramField;
import edu.wisc.ssec.mcidasv.data.hydra.SubsetRubberBandBox;
import edu.wisc.ssec.mcidasv.data.hydra.MyRubberBandBoxRendererJ3D;
import edu.wisc.ssec.mcidasv.data.hydra.CurveDrawer;
import edu.wisc.ssec.mcidasv.data.hydra.MultiSpectralData;
import edu.wisc.ssec.mcidasv.data.hydra.MultiDimensionSubset;
import edu.wisc.ssec.mcidasv.data.hydra.HydraContext;
import edu.wisc.ssec.mcidasv.control.LambertAEA;
import java.util.List;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.net.URL;
import java.awt.Container;
import java.awt.Component;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Color;
import java.awt.geom.Rectangle2D;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.rmi.RemoteException;
import javax.swing.JTabbedPane;
import javax.swing.border.EmptyBorder;
import ucar.unidata.idv.control.DisplayControlImpl;
import ucar.unidata.data.DataChoice;
import ucar.unidata.util.ColorTable;
import visad.VisADException;
import visad.AxisScale;
import visad.FlatField;
import visad.FieldImpl;
import visad.CoordinateSystem;
import visad.Data;
import visad.RealType;
import visad.CellImpl;
import visad.Integer1DSet;
import visad.RealTupleType;
import visad.FunctionType;
import visad.ScalarMap;
import visad.Gridded3DSet;
import visad.Gridded2DSet;
import visad.Linear2DSet;
import visad.SampledSet;
import visad.Set;
import visad.SetType;
import visad.UnionSet;
import visad.BaseColorControl;
import visad.DisplayListener;
import visad.DisplayEvent;
import visad.DelaunayCustom;
import visad.georef.MapProjection;
import visad.data.mcidas.BaseMapAdapter;
import javax.swing.JButton;
import javax.swing.JRadioButton;
import javax.swing.ButtonGroup;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import ucar.unidata.data.DataAlias;
import ucar.unidata.data.DataChoice;
import ucar.unidata.data.DataSelection;
import ucar.unidata.idv.ViewDescriptor;
import ucar.unidata.idv.ViewManager;
import ucar.unidata.util.ColorTable;
import ucar.unidata.util.GuiUtils;
import ucar.unidata.util.LogUtil;
import ucar.unidata.util.Misc;
import ucar.unidata.util.Range;
import ucar.unidata.data.grid.GridUtil;
import ucar.unidata.view.geoloc.MapProjectionDisplayJ3D;
import ucar.unidata.view.geoloc.MapProjectionDisplay;
import ucar.visad.display.DisplayMaster;
import ucar.visad.display.DisplayableData;
import ucar.visad.display.XYDisplay;
import ucar.visad.display.RGBDisplayable;
import ucar.visad.display.LineDrawing;
import ucar.visad.display.RubberBandBox;
import ucar.visad.display.MapLines;
import ucar.unidata.idv.DisplayConventions;
public class ScatterDisplay extends DisplayControlImpl {
private Container container;
private FlatField X_field;
private FlatField Y_field;
private ViewManager scatterView = null;
private DisplayMaster dspMasterX;
private DisplayMaster dspMasterY;
private HistogramField histoField;
private FlatField mask_field;
private float[][] mask_range;
private float[][] scatterFieldRange;
private Data X_data;
private Data Y_data;
private String X_name;
private String Y_name;
private ScatterDisplayable scatterMarkDsp;
private RGBDisplayable maskX;
private RGBDisplayable maskY;
private BoxCurveSwitch boxCurveSwitch;
public DataChoice dataChoiceX = null;
public DataChoice dataChoiceY = null;
public DataSelection dataSelectionX = null;
public DataSelection dataSelectionY = null;
public ScatterDisplay() {
super();
}
@Override public boolean init(List choices) throws VisADException, RemoteException {
if ((dataChoiceX != null) && (dataChoiceY != null)) {
setupFromUnpersistence();
}
else {
setup();
}
mask_field = new FlatField(
new FunctionType(((FunctionType)X_field.getType()).getDomain(), RealType.Generic),
X_field.getDomainSet());
int len = X_field.getDomainSet().getLength();
mask_range = new float[1][len];
for (int t=0; t<len; t++) {
mask_range[0][t] = Float.NaN;
}
mask_range[0][0] = 0; //- field should not be all missing
mask_field.setSamples(mask_range, false);
try {
histoField = new HistogramField(X_field, Y_field, mask_field, 100, 10);
}
catch (Exception e) {
e.printStackTrace();
}
dspMasterX = makeImageDisplay(getDataProjection(X_field), X_field, mask_field);
dspMasterY = makeImageDisplay(getDataProjection(Y_field), Y_field, mask_field);
X_name = ((((FunctionType)X_field.getType()).getFlatRange().getRealComponents())[0]).getName();
Y_name = ((((FunctionType)Y_field.getType()).getFlatRange().getRealComponents())[0]).getName();
return true;
}
public void setup() throws VisADException, RemoteException {
dataSelectionX = getDataSelection();
dataChoiceX = getDataChoice();
X_data = dataChoiceX.getData(dataSelectionX);
if (X_data instanceof FlatField) {
X_field = (FlatField) X_data;
} else if (X_data instanceof FieldImpl) {
X_field = (FlatField) ((FieldImpl)X_data).getSample(0);
}
this.popupDataDialog("select Y Axis field", container, false, null);
dataSelectionY = getDataSelection();
dataChoiceY = getDataChoice();
dataSelectionY.setGeoSelection(dataSelectionX.getGeoSelection());
Y_data = dataChoiceY.getData(dataSelectionY);
if (Y_data instanceof FlatField) {
Y_field = (FlatField) Y_data;
} else if (X_data instanceof FieldImpl) {
Y_field = (FlatField) ((FieldImpl)Y_data).getSample(0);
}
}
public void setupFromUnpersistence() throws VisADException, RemoteException {
X_data = dataChoiceX.getData(dataSelectionX);
if (X_data instanceof FlatField) {
X_field = (FlatField) X_data;
} else if (X_data instanceof FieldImpl) {
X_field = (FlatField) ((FieldImpl)X_data).getSample(0);
}
Y_data = dataChoiceY.getData(dataSelectionY);
if (Y_data instanceof FlatField) {
Y_field = (FlatField) Y_data;
} else if (X_data instanceof FieldImpl) {
Y_field = (FlatField) ((FieldImpl)Y_data).getSample(0);
}
}
protected void popupDataDialog(final String dialogMessage,
Component from, boolean multiples,
List categories) {
List<DataChoice> choices = selectDataChoices(dialogMessage, from,
multiples, categories);
if ((choices == null) || (choices.size() == 0)) {
return;
}
final List clonedList =
DataChoice.cloneDataChoices((List) choices.get(0));
dataSelection = ((DataChoice) clonedList.get(0)).getDataSelection();
//- don't do this in a separate thread like the IDV does.
//- We want the dataChoice list updated before return.
try {
addNewData(clonedList);
} catch (Exception exc) {
logException("Selecting new data", exc);
}
}
public void initDone() {
try {
DisplayMaster master = makeScatterDisplay();
ScatterBoxSelector boxSelect = new ScatterBoxSelector(master);
ScatterCurveSelector curveSelect = new ScatterCurveSelector(master);
curveSelect.setVisible(false);
master.draw();
SubsetRubberBandBox X_subsetBox =
new SubsetRubberBandBox(getIsLatLon(X_field), X_field,
((MapProjectionDisplayJ3D)dspMasterX).getDisplayCoordinateSystem(), 1, false);
X_subsetBox.setColor(Color.magenta);
ImageBoxSelector markX = new ImageBoxSelector(X_subsetBox, X_field.getDomainSet(), dspMasterX);
X_subsetBox.addAction(markX);
CurveDrawer curveDraw = new CurveDrawer(RealType.Longitude, RealType.Latitude, 1);
curveDraw.setColor(Color.magenta);
curveDraw.setLineWidth(2);
ImageCurveSelector curveX = new ImageCurveSelector(curveDraw, X_field, dspMasterX);
curveDraw.addAction(curveX);
curveX.setVisible(false);
dspMasterX.addDisplayable(curveDraw);
SubsetRubberBandBox Y_subsetBox =
new SubsetRubberBandBox(getIsLatLon(Y_field), Y_field,
((MapProjectionDisplayJ3D)dspMasterY).getDisplayCoordinateSystem(), 1, false);
Y_subsetBox.setColor(Color.magenta);
ImageBoxSelector markY = new ImageBoxSelector(Y_subsetBox, Y_field.getDomainSet(), dspMasterY);
Y_subsetBox.addAction(markY);
dspMasterX.addDisplayable(X_subsetBox);
dspMasterY.addDisplayable(Y_subsetBox);
markX.setOther(markY);
markY.setOther(markX);
curveDraw = new CurveDrawer(RealType.Longitude, RealType.Latitude, 1);
curveDraw.setColor(Color.magenta);
curveDraw.setLineWidth(2);
ImageCurveSelector curveY = new ImageCurveSelector(curveDraw, Y_field, dspMasterY);
curveDraw.addAction(curveY);
curveY.setVisible(false);
dspMasterY.addDisplayable(curveDraw);
curveX.setOther(curveY);
curveY.setOther(curveX);
boxCurveSwitch.boxSelect = boxSelect;
boxCurveSwitch.curveSelect = curveSelect;
boxCurveSwitch.markX = markX;
boxCurveSwitch.markY = markY;
boxCurveSwitch.curveX = curveX;
boxCurveSwitch.curveY = curveY;
}
catch (Exception e) {
e.printStackTrace();
}
}
public DisplayMaster makeScatterDisplay() throws VisADException, RemoteException {
ScatterDisplayable scatterDsp = new ScatterDisplayable("scatter",
RealType.getRealType("mask"), new float[][] {{1,1},{1,0},{1,1}}, false);
float[] valsX = X_field.getFloats(false)[0];
float[] valsY = Y_field.getFloats(false)[0];
Integer1DSet set = new Integer1DSet(valsX.length);
FlatField scatter = new FlatField(
new FunctionType(RealType.Generic,
new RealTupleType(RealType.XAxis, RealType.YAxis, RealType.getRealType("mask"))), set);
float[] mask = new float[valsX.length];
for (int k=0; k<mask.length; k++) mask[k] = 0;
scatterFieldRange = new float[][] {valsX, valsY, mask};
scatter.setSamples(scatterFieldRange);
scatterDsp.setPointSize(2f);
scatterDsp.setRangeForColor(0,1);
scatterDsp.setData(scatter);
scatterMarkDsp = new ScatterDisplayable("scatter",
RealType.getRealType("mask"), new float[][] {{1,1},{1,0},{1,1}}, false);
set = new Integer1DSet(2);
scatter = new FlatField(
new FunctionType(RealType.Generic,
new RealTupleType(RealType.XAxis, RealType.YAxis, RealType.getRealType("mask"))), set);
scatterMarkDsp.setData(scatter);
scatterMarkDsp.setPointSize(2f);
scatterMarkDsp.setRangeForColor(0,1);
DisplayMaster master = scatterView.getMaster();
((XYDisplay)master).showAxisScales(true);
AxisScale scaleX = ((XYDisplay)master).getXAxisScale();
scaleX.setTitle(X_name);
AxisScale scaleY = ((XYDisplay)master).getYAxisScale();
scaleY.setTitle(Y_name);
master.addDisplayable(scatterDsp);
master.addDisplayable(scatterMarkDsp);
return master;
}
@Override public Container doMakeContents() {
JPanel pane = new JPanel(new GridLayout(1,3));
Component[] comps = new Component[] {null, null, null};
comps[0] = dspMasterX.getComponent();
comps[1] = dspMasterY.getComponent();
comps[2] = getScatterTabComponent();
JPanel panelX = new JPanel(new BorderLayout());
panelX.setBorder(new EmptyBorder(4,4,4,4));
panelX.add(comps[0], BorderLayout.CENTER);
JPanel panelY = new JPanel(new BorderLayout());
panelY.setBorder(new EmptyBorder(4,4,4,4));
panelY.add(comps[1], BorderLayout.CENTER);
JPanel panelS = new JPanel(new BorderLayout());
panelS.setBorder(new EmptyBorder(4,4,4,4));
panelS.add(comps[2], BorderLayout.CENTER);
pane.add(panelX);
pane.add(panelY);
pane.add(panelS);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
JRadioButton boxSelect = new JRadioButton("Box");
boxSelect.setSelected(true);
JRadioButton curveSelect = new JRadioButton("Curve");
ButtonGroup buttonGroup = new ButtonGroup();
buttonGroup.add(boxSelect);
buttonGroup.add(curveSelect);
buttonPanel.add(boxSelect);
buttonPanel.add(curveSelect);
boxCurveSwitch = new BoxCurveSwitch();
boxSelect.addActionListener(boxCurveSwitch);
curveSelect.addActionListener(boxCurveSwitch);
JPanel new_pane = new JPanel(new BorderLayout());
new_pane.add(pane, BorderLayout.CENTER);
new_pane.add(buttonPanel, BorderLayout.SOUTH);
//-container = pane;
container = new_pane;
return container;
}
// @Override public void doRemove() throws VisADException, RemoteException {
// super.doRemove();
// }
protected JComponent getScatterTabComponent() {
try {
scatterView = new ViewManager(getViewContext(),
new XYDisplay("Scatter", RealType.XAxis, RealType.YAxis),
new ViewDescriptor("scatter"), "showControlLegend=false;");
} catch (Exception e) {
e.printStackTrace();
}
return scatterView.getComponent();
}
public DisplayMaster makeImageDisplay(MapProjection mapProj, FlatField image, FlatField mask_image)
throws VisADException, RemoteException {
MapProjectionDisplayJ3D mapProjDsp;
DisplayMaster dspMaster;
mapProjDsp = new MapProjectionDisplayJ3D(MapProjectionDisplay.MODE_2Din3D);
mapProjDsp.enableRubberBanding(false);
dspMaster = mapProjDsp;
mapProjDsp.setMapProjection(mapProj);
RealType imageRangeType =
(((FunctionType)image.getType()).getFlatRange().getRealComponents())[0];
HydraRGBDisplayable imageDsp = new HydraRGBDisplayable("image", imageRangeType, null, false, null);
imageDsp.setData(image);
addMapDisplayables(mapProjDsp);
dspMaster.addDisplayable(imageDsp);
if (mask_image != null) {
RGBDisplayable maskDsp = new ScatterDisplayable("mask", RealType.Generic, new float[][] {{0},{1},{0}}, false);
maskDsp.setData(mask_image);
dspMaster.addDisplayable(maskDsp);
}
dspMaster.draw();
DisplayConventions dc = getDisplayConventions();
Range[] range = GridUtil.fieldMinMax(image);
Range imageRange = range[0];
String canonicalName = DataAlias.aliasToCanonical(imageRangeType.getName());
Range dfltRange = dc.getParamRange(canonicalName, null);
if (dfltRange == null) {
imageRange = range[0];
}
else if ((imageRange.getMax() - imageRange.getMin()) < (dfltRange.getMax() - dfltRange.getMin())) {
}
else {
imageRange = dfltRange;
}
ScalarMap colorMap = imageDsp.getColorMap();
colorMap.setRange(imageRange.getMin(), imageRange.getMax());
BaseColorControl clrCntrl = (BaseColorControl) colorMap.getControl();
clrCntrl.setTable(
dc.getParamColorTable(
imageRangeType.getName()).getColorTable());
return dspMaster;
}
public MapProjection getDataProjection(FlatField image)
throws VisADException, RemoteException {
MapProjection mp = null;
//- get MapProjection from incoming image. If none, use default method
FunctionType fnc_type = (FunctionType) image.getType();
RealTupleType rtt = fnc_type.getDomain();
CoordinateSystem cs = rtt.getCoordinateSystem();
if (cs instanceof MapProjection) {
return (MapProjection) cs;
}
Rectangle2D rect = MultiSpectralData.getLonLatBoundingBox(image);
try {
mp = new LambertAEA(rect);
} catch (Exception e) {
System.out.println(" getDataProjection"+e);
}
return mp;
}
public void addMapDisplayables(MapProjectionDisplayJ3D mapProjDsp)
throws VisADException, RemoteException {
MapLines mapLines = new MapLines("maplines");
URL mapSource =
mapProjDsp.getClass().getResource("/auxdata/maps/OUTLSUPU");
try {
BaseMapAdapter mapAdapter = new BaseMapAdapter(mapSource);
mapLines.setMapLines(mapAdapter.getData());
mapLines.setColor(java.awt.Color.cyan);
mapProjDsp.addDisplayable(mapLines);
} catch (Exception excp) {
System.out.println("Can't open map file " + mapSource);
System.out.println(excp);
}
mapLines = new MapLines("maplines");
mapSource =
mapProjDsp.getClass().getResource("/auxdata/maps/OUTLSUPW");
try {
BaseMapAdapter mapAdapter = new BaseMapAdapter(mapSource);
mapLines.setMapLines(mapAdapter.getData());
mapLines.setColor(java.awt.Color.cyan);
mapProjDsp.addDisplayable(mapLines);
} catch (Exception excp) {
System.out.println("Can't open map file " + mapSource);
System.out.println(excp);
}
mapLines = new MapLines("maplines");
mapSource =
mapProjDsp.getClass().getResource("/auxdata/maps/OUTLHPOL");
try {
BaseMapAdapter mapAdapter = new BaseMapAdapter(mapSource);
mapLines.setMapLines(mapAdapter.getData());
mapLines.setColor(java.awt.Color.cyan);
mapProjDsp.addDisplayable(mapLines);
} catch (Exception excp) {
System.out.println("Can't open map file " + mapSource);
System.out.println(excp);
}
}
private class ScatterDisplayable extends RGBDisplayable {
ScatterDisplayable(String name, RealType rgbRealType, float[][] colorPalette, boolean alphaflag)
throws VisADException, RemoteException {
super(name, rgbRealType, colorPalette, alphaflag);
}
}
private class ImageCurveSelector extends CellImpl implements DisplayListener {
boolean init = false;
CurveDrawer curveDraw;
DisplayMaster dspMaster;
FlatField image;
Gridded2DSet domainSet;
CoordinateSystem cs;
int domainLen_0;
int domainLen_1;
ImageCurveSelector other;
UnionSet last_uSet = null;
ImageCurveSelector(CurveDrawer curveDraw, FlatField image, DisplayMaster master) {
this.curveDraw = curveDraw;
dspMaster = master;
dspMaster.addDisplayListener(this);
this.image = image;
domainSet = (Gridded2DSet) image.getDomainSet();
int[] lens = domainSet.getLengths();
domainLen_0 = lens[0];
domainLen_1 = lens[1];
cs = ((FunctionType)image.getType()).getDomain().getCoordinateSystem();
}
public void displayChanged(DisplayEvent de)
throws VisADException, RemoteException {
if (de.getId() == DisplayEvent.MOUSE_RELEASED) {
UnionSet uSet = curveDraw.getCurves();
if (uSet == last_uSet) return;
SampledSet[] sets = uSet.getSets();
int s_idx = sets.length-1;
float[][] crv;
if (cs != null) {
crv = sets[s_idx].getSamples();
crv = cs.fromReference(crv);
crv = domainSet.valueToGrid(crv);
}
else {
crv = sets[s_idx].getSamples();
+ crv = domainSet.valueToGrid(crv);
}
float[][] onImage = new float[2][crv[0].length];
int cnt = 0;
for (int i=0; i<crv[0].length; i++) {
if ( ((crv[0][i] >= 0)&&(crv[0][i] <= domainLen_0)) &&
((crv[1][i] >= 0)&&(crv[1][i] <= domainLen_1)) ) {
onImage[0][cnt] = crv[0][i];
onImage[1][cnt] = crv[1][i];
cnt++;
}
}
uSet = new UnionSet(new SampledSet[] {sets[s_idx]});
last_uSet = uSet;
curveDraw.setCurves(uSet);
other.updateCurve(sets[s_idx]);
if (cnt == 0) {
return;
}
float[][] tmp = new float[2][cnt];
System.arraycopy(onImage[0], 0, tmp[0], 0, cnt);
System.arraycopy(onImage[1], 0, tmp[1], 0, cnt);
onImage = tmp;
float[] minmaxvals = minmax(onImage[0]);
int low_0 = Math.round(minmaxvals[0]);
int hi_0 = Math.round(minmaxvals[1]);
minmaxvals = minmax(onImage[1]);
int low_1 = Math.round(minmaxvals[0]);
int hi_1 = Math.round(minmaxvals[1]);
int len_0 = (hi_0 - low_0) + 1;
int len_1 = (hi_1 - low_1) + 1;
int len = len_0*len_1;
float[][] markScatter = new float[3][len];
for (int k=0; k<len; k++) {
markScatter[0][k] = 0;
markScatter[1][k] = 0;
markScatter[2][k] = 0;
}
for (int j=0; j<len_1; j++) {
for (int i=0; i<len_0; i++) {
int idx = (j+low_1)*domainLen_0 + (i+low_0);
int k = j*len_0 + i;
float x = (float) (i + low_0);
float y = (float) (j + low_1);
if (DelaunayCustom.inside(crv, x, y)) {
markScatter[0][k] = scatterFieldRange[0][idx];
markScatter[1][k] = scatterFieldRange[1][idx];
markScatter[2][k] = 1;
}
}
}
Integer1DSet dset = new Integer1DSet(len);
FlatField scatterFieldMark = new FlatField(
new FunctionType(RealType.Generic,
new RealTupleType(RealType.XAxis, RealType.YAxis, RealType.getRealType("mask"))), dset);
scatterFieldMark.setSamples(markScatter, false);
scatterMarkDsp.setData(scatterFieldMark);
}
}
public void reset() throws VisADException, RemoteException {
RealTupleType type = ((SetType)curveDraw.getCurves().getType()).getDomain();
curveDraw.setCurves(new UnionSet(new Gridded2DSet[]{
new Gridded2DSet(type, new float[][] {
{ 0.0f }, { 0.0f }}, 1) }));
Integer1DSet dset = new Integer1DSet(2);
FlatField scatterFieldMark = new FlatField(
new FunctionType(RealType.Generic,
new RealTupleType(RealType.XAxis, RealType.YAxis, RealType.getRealType("mask"))), dset);
float[][] markScatter = new float[3][2];
for (int k=0; k<2; k++) {
markScatter[0][k] = scatterFieldRange[0][k];
markScatter[1][k] = scatterFieldRange[1][k];
markScatter[2][k] = 0;
}
scatterFieldMark.setSamples(markScatter, false);
scatterMarkDsp.setData(scatterFieldMark);
}
public void updateCurve(SampledSet set) throws VisADException, RemoteException {
last_uSet = new UnionSet(new SampledSet[] {set});
curveDraw.setCurves(last_uSet);
}
public void setOther(ImageCurveSelector other) {
this.other = other;
}
public void doAction()
throws VisADException, RemoteException {
if (!init) {
init = true;
return;
}
}
public void setVisible(boolean visible) throws VisADException, RemoteException {
curveDraw.setVisible(visible);
}
}
private class ImageBoxSelector extends CellImpl {
boolean init = false;
SubsetRubberBandBox subsetBox;
Set imageDomain;
int domainLen_0;
int domainLen_1;
float[][] scatter;
LineDrawing lastBox;
ImageBoxSelector other;
ImageBoxSelector(SubsetRubberBandBox subsetBox, Set imageDomain, DisplayMaster master)
throws VisADException, RemoteException {
super();
this.subsetBox = subsetBox;
this.imageDomain = imageDomain;
int[] lens = ((Gridded2DSet)imageDomain).getLengths();
domainLen_0 = lens[0];
domainLen_1 = lens[1];
lastBox = new LineDrawing("last_box");
lastBox.setColor(Color.magenta);
master.addDisplayable(lastBox);
}
public void doAction()
throws VisADException, RemoteException
{
if (!init) {
init = true;
return;
}
Gridded2DSet set = subsetBox.getBounds();
float[][] corners = set.getSamples(false);
float[][] coords = corners;
if (imageDomain instanceof Linear2DSet) {
coords = ((Gridded2DSet)imageDomain).valueToGrid(corners);
}
float[] coords_0 = coords[0];
float[] coords_1 = coords[1];
int low_0 = Math.round(Math.min(coords_0[0], coords_0[1]));
int low_1 = Math.round(Math.min(coords_1[0], coords_1[1]));
int hi_0 = Math.round(Math.max(coords_0[0], coords_0[1]));
int hi_1 = Math.round(Math.max(coords_1[0], coords_1[1]));
int len_0 = (hi_0 - low_0) + 1;
int len_1 = (hi_1 - low_1) + 1;
int len = len_0*len_1;
float[][] markScatter = new float[3][len];
for (int k=0; k<len; k++) {
markScatter[0][k] = 0;
markScatter[1][k] = 0;
markScatter[2][k] = 0;
}
for (int j=0; j<len_1; j++) {
for (int i=0; i<len_0; i++) {
int idx = (j+low_1)*domainLen_0 + (i+low_0);
int k = j*len_0 + i;
markScatter[0][k] = scatterFieldRange[0][idx];
markScatter[1][k] = scatterFieldRange[1][idx];
markScatter[2][k] = 1;
}
}
Integer1DSet dset = new Integer1DSet(len);
FlatField scatterFieldMark = new FlatField(
new FunctionType(RealType.Generic,
new RealTupleType(RealType.XAxis, RealType.YAxis, RealType.getRealType("mask"))), dset);
scatterFieldMark.setSamples(markScatter, false);
scatterMarkDsp.setData(scatterFieldMark);
updateBox();
}
public void reset() throws VisADException, RemoteException {
Gridded2DSet set2D =
new Gridded2DSet(RealTupleType.SpatialCartesian2DTuple,
new float[][] {{0},{0}}, 1);
lastBox.setData(set2D);
Integer1DSet dset = new Integer1DSet(2);
FlatField scatterFieldMark = new FlatField(
new FunctionType(RealType.Generic,
new RealTupleType(RealType.XAxis, RealType.YAxis, RealType.getRealType("mask"))), dset);
float[][] markScatter = new float[3][2];
for (int k=0; k<2; k++) {
markScatter[0][k] = scatterFieldRange[0][k];
markScatter[1][k] = scatterFieldRange[1][k];
markScatter[2][k] = 0;
}
scatterFieldMark.setSamples(markScatter, false);
scatterMarkDsp.setData(scatterFieldMark);
}
public void setOther(ImageBoxSelector other) {
this.other = other;
}
public void updateBox() throws VisADException, RemoteException {
Gridded3DSet set3D = subsetBox.getLastBox();
float[][] samples = set3D.getSamples(false);
Gridded2DSet set2D =
new Gridded2DSet(RealTupleType.SpatialCartesian2DTuple,
new float[][] {samples[0], samples[1]}, samples[0].length);
lastBox.setData(set2D);
other.updateBox(set2D);
}
public void updateBox(Gridded2DSet set2D) throws VisADException, RemoteException {
lastBox.setData(set2D);
}
public void setVisible(boolean visible) throws VisADException, RemoteException {
subsetBox.setVisible(visible);
lastBox.setVisible(visible);
}
public SubsetRubberBandBox getSelector() {
return subsetBox;
}
}
private class ScatterBoxSelector extends CellImpl {
boolean init = false;
double[] x_coords = new double[2];
double[] y_coords = new double[2];
RubberBandBox rbb;
LineDrawing selectBox;
ScatterBoxSelector(DisplayMaster master) throws VisADException, RemoteException {
selectBox = new LineDrawing("select");
selectBox.setColor(Color.green);
rbb = new RubberBandBox(RealType.XAxis, RealType.YAxis, 1);
rbb.setColor(Color.green);
rbb.addAction(this);
master.addDisplayable(rbb);
master.addDisplayable(selectBox);
}
public void doAction() throws VisADException, RemoteException {
if (!init) {
init = true;
return;
}
Gridded2DSet set = rbb.getBounds();
float[] low = set.getLow();
float[] hi = set.getHi();
x_coords[0] = low[0];
x_coords[1] = hi[0];
y_coords[0] = low[1];
y_coords[1] = hi[1];
SampledSet[] sets = new SampledSet[4];
sets[0] = new Gridded2DSet(RealTupleType.SpatialCartesian2DTuple, new float[][] {{low[0], hi[0]}, {low[1], low[1]}}, 2);
sets[1] = new Gridded2DSet(RealTupleType.SpatialCartesian2DTuple, new float[][] {{hi[0], hi[0]}, {low[1], hi[1]}}, 2);
sets[2] = new Gridded2DSet(RealTupleType.SpatialCartesian2DTuple, new float[][] {{hi[0], low[0]}, {hi[1], hi[1]}}, 2);
sets[3] = new Gridded2DSet(RealTupleType.SpatialCartesian2DTuple, new float[][] {{low[0], low[0]}, {hi[1], low[1]}}, 2);
UnionSet uset = new UnionSet(sets);
selectBox.setData(uset);
try {
FlatField updateMask = histoField.markMaskFieldByRange(x_coords, y_coords, 0);
} catch (Exception e) {
e.printStackTrace();
}
}
public void setVisible(boolean visible) throws VisADException, RemoteException {
rbb.setVisible(visible);
selectBox.setVisible(visible);
}
public void reset() throws Exception {
histoField.resetMaskField(0);
}
}
private class ScatterCurveSelector extends CellImpl implements DisplayListener {
CurveDrawer curveDraw;
boolean init = false;
UnionSet last_uSet = null;
ScatterCurveSelector(DisplayMaster master) throws VisADException, RemoteException {
curveDraw = new CurveDrawer(RealType.XAxis, RealType.YAxis, 1);
curveDraw.setColor(Color.green);
curveDraw.setLineWidth(2);
curveDraw.setData(new UnionSet(new Gridded2DSet[]{
new Gridded2DSet(RealTupleType.SpatialCartesian2DTuple, new float[][] {
{ scatterFieldRange[0][0] }, { scatterFieldRange[1][0]}
}, 1) }));
master.addDisplayable(curveDraw);
curveDraw.addAction(this);
master.addDisplayListener(this);
}
public void displayChanged(DisplayEvent de)
throws VisADException, RemoteException {
if (de.getId() == DisplayEvent.MOUSE_RELEASED) {
UnionSet uSet = curveDraw.getCurves();
if (uSet == last_uSet) return;
SampledSet[] sets = uSet.getSets();
int s_idx = sets.length-1;
float[][] crv;
crv = sets[s_idx].getSamples();
last_uSet = new UnionSet(new SampledSet[] {sets[s_idx]});
curveDraw.setCurves(last_uSet);
try {
histoField.clearMaskField(0);
FlatField updateMask = histoField.markMaskFieldByCurve(crv, 0);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void doAction() throws VisADException, RemoteException {
if (!init) {
init = true;
return;
}
}
public void setVisible(boolean visible) throws VisADException, RemoteException {
curveDraw.setVisible(visible);
}
public void reset() throws Exception {
curveDraw.setData(new UnionSet(new Gridded2DSet[]{
new Gridded2DSet(RealTupleType.SpatialCartesian2DTuple, new float[][] {
{ scatterFieldRange[0][0] }, { scatterFieldRange[1][0]}
}, 1) }));
histoField.resetMaskField(0);
}
}
private class BoxCurveSwitch implements ActionListener {
public ScatterBoxSelector boxSelect;
public ScatterCurveSelector curveSelect;
public ImageBoxSelector markX;
public ImageBoxSelector markY;
public ImageCurveSelector curveX;
public ImageCurveSelector curveY;
public BoxCurveSwitch() {
}
public void actionPerformed(ActionEvent ae) {
String cmd = ae.getActionCommand();
try {
if (cmd.equals("Box")) {
curveSelect.setVisible(false);
curveSelect.reset();
curveX.setVisible(false);
curveY.setVisible(false);
curveX.reset();
curveY.reset();
boxSelect.setVisible(true);
markX.setVisible(true);
markY.setVisible(true);
} else if (cmd.equals("Curve")) {
boxSelect.setVisible(false);
markX.setVisible(false);
markY.setVisible(false);
boxSelect.reset();
markX.reset();
markY.reset();
curveSelect.setVisible(true);
curveX.setVisible(true);
curveY.setVisible(true);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
public static float[] minmax(float[] values) {
float min = Float.MAX_VALUE;
float max = -Float.MAX_VALUE;
for (int k = 0; k < values.length; k++) {
float val = values[k];
if ((val == val) && (val < Float.POSITIVE_INFINITY) && (val > Float.NEGATIVE_INFINITY)) {
if (val < min) min = val;
if (val > max) max = val;
}
}
return new float[] {min, max};
}
public boolean getIsLatLon(FlatField field) throws VisADException, RemoteException {
boolean isLL = false;
FunctionType fnc_type = (FunctionType) field.getType();
RealTupleType rtt = fnc_type.getDomain();
if (rtt.equals(RealTupleType.LatitudeLongitudeTuple)) {
isLL = true;
}
else if (!rtt.equals(RealTupleType.SpatialEarth2DTuple)) {
rtt = fnc_type.getDomain().getCoordinateSystem().getReference();
if ( rtt.equals(RealTupleType.LatitudeLongitudeTuple)) {
isLL = true;
}
}
return isLL;
}
}
| true | true | public void displayChanged(DisplayEvent de)
throws VisADException, RemoteException {
if (de.getId() == DisplayEvent.MOUSE_RELEASED) {
UnionSet uSet = curveDraw.getCurves();
if (uSet == last_uSet) return;
SampledSet[] sets = uSet.getSets();
int s_idx = sets.length-1;
float[][] crv;
if (cs != null) {
crv = sets[s_idx].getSamples();
crv = cs.fromReference(crv);
crv = domainSet.valueToGrid(crv);
}
else {
crv = sets[s_idx].getSamples();
}
float[][] onImage = new float[2][crv[0].length];
int cnt = 0;
for (int i=0; i<crv[0].length; i++) {
if ( ((crv[0][i] >= 0)&&(crv[0][i] <= domainLen_0)) &&
((crv[1][i] >= 0)&&(crv[1][i] <= domainLen_1)) ) {
onImage[0][cnt] = crv[0][i];
onImage[1][cnt] = crv[1][i];
cnt++;
}
}
uSet = new UnionSet(new SampledSet[] {sets[s_idx]});
last_uSet = uSet;
curveDraw.setCurves(uSet);
other.updateCurve(sets[s_idx]);
if (cnt == 0) {
return;
}
float[][] tmp = new float[2][cnt];
System.arraycopy(onImage[0], 0, tmp[0], 0, cnt);
System.arraycopy(onImage[1], 0, tmp[1], 0, cnt);
onImage = tmp;
float[] minmaxvals = minmax(onImage[0]);
int low_0 = Math.round(minmaxvals[0]);
int hi_0 = Math.round(minmaxvals[1]);
minmaxvals = minmax(onImage[1]);
int low_1 = Math.round(minmaxvals[0]);
int hi_1 = Math.round(minmaxvals[1]);
int len_0 = (hi_0 - low_0) + 1;
int len_1 = (hi_1 - low_1) + 1;
int len = len_0*len_1;
float[][] markScatter = new float[3][len];
for (int k=0; k<len; k++) {
markScatter[0][k] = 0;
markScatter[1][k] = 0;
markScatter[2][k] = 0;
}
for (int j=0; j<len_1; j++) {
for (int i=0; i<len_0; i++) {
int idx = (j+low_1)*domainLen_0 + (i+low_0);
int k = j*len_0 + i;
float x = (float) (i + low_0);
float y = (float) (j + low_1);
if (DelaunayCustom.inside(crv, x, y)) {
markScatter[0][k] = scatterFieldRange[0][idx];
markScatter[1][k] = scatterFieldRange[1][idx];
markScatter[2][k] = 1;
}
}
}
Integer1DSet dset = new Integer1DSet(len);
FlatField scatterFieldMark = new FlatField(
new FunctionType(RealType.Generic,
new RealTupleType(RealType.XAxis, RealType.YAxis, RealType.getRealType("mask"))), dset);
scatterFieldMark.setSamples(markScatter, false);
scatterMarkDsp.setData(scatterFieldMark);
}
}
| public void displayChanged(DisplayEvent de)
throws VisADException, RemoteException {
if (de.getId() == DisplayEvent.MOUSE_RELEASED) {
UnionSet uSet = curveDraw.getCurves();
if (uSet == last_uSet) return;
SampledSet[] sets = uSet.getSets();
int s_idx = sets.length-1;
float[][] crv;
if (cs != null) {
crv = sets[s_idx].getSamples();
crv = cs.fromReference(crv);
crv = domainSet.valueToGrid(crv);
}
else {
crv = sets[s_idx].getSamples();
crv = domainSet.valueToGrid(crv);
}
float[][] onImage = new float[2][crv[0].length];
int cnt = 0;
for (int i=0; i<crv[0].length; i++) {
if ( ((crv[0][i] >= 0)&&(crv[0][i] <= domainLen_0)) &&
((crv[1][i] >= 0)&&(crv[1][i] <= domainLen_1)) ) {
onImage[0][cnt] = crv[0][i];
onImage[1][cnt] = crv[1][i];
cnt++;
}
}
uSet = new UnionSet(new SampledSet[] {sets[s_idx]});
last_uSet = uSet;
curveDraw.setCurves(uSet);
other.updateCurve(sets[s_idx]);
if (cnt == 0) {
return;
}
float[][] tmp = new float[2][cnt];
System.arraycopy(onImage[0], 0, tmp[0], 0, cnt);
System.arraycopy(onImage[1], 0, tmp[1], 0, cnt);
onImage = tmp;
float[] minmaxvals = minmax(onImage[0]);
int low_0 = Math.round(minmaxvals[0]);
int hi_0 = Math.round(minmaxvals[1]);
minmaxvals = minmax(onImage[1]);
int low_1 = Math.round(minmaxvals[0]);
int hi_1 = Math.round(minmaxvals[1]);
int len_0 = (hi_0 - low_0) + 1;
int len_1 = (hi_1 - low_1) + 1;
int len = len_0*len_1;
float[][] markScatter = new float[3][len];
for (int k=0; k<len; k++) {
markScatter[0][k] = 0;
markScatter[1][k] = 0;
markScatter[2][k] = 0;
}
for (int j=0; j<len_1; j++) {
for (int i=0; i<len_0; i++) {
int idx = (j+low_1)*domainLen_0 + (i+low_0);
int k = j*len_0 + i;
float x = (float) (i + low_0);
float y = (float) (j + low_1);
if (DelaunayCustom.inside(crv, x, y)) {
markScatter[0][k] = scatterFieldRange[0][idx];
markScatter[1][k] = scatterFieldRange[1][idx];
markScatter[2][k] = 1;
}
}
}
Integer1DSet dset = new Integer1DSet(len);
FlatField scatterFieldMark = new FlatField(
new FunctionType(RealType.Generic,
new RealTupleType(RealType.XAxis, RealType.YAxis, RealType.getRealType("mask"))), dset);
scatterFieldMark.setSamples(markScatter, false);
scatterMarkDsp.setData(scatterFieldMark);
}
}
|
diff --git a/src/core/de/jroene/vrapper/vim/token/BeginOfLineMove.java b/src/core/de/jroene/vrapper/vim/token/BeginOfLineMove.java
index 21589df4..c829de86 100644
--- a/src/core/de/jroene/vrapper/vim/token/BeginOfLineMove.java
+++ b/src/core/de/jroene/vrapper/vim/token/BeginOfLineMove.java
@@ -1,90 +1,93 @@
package de.jroene.vrapper.vim.token;
import de.jroene.vrapper.vim.Space;
import de.jroene.vrapper.vim.VimEmulator;
import de.jroene.vrapper.vim.VimUtils;
import de.jroene.vrapper.vim.action.Action;
import de.jroene.vrapper.vim.action.HorizontalChangeMoveToAction;
/**
* Move to the begin of the line.
*
* @author Matthias Radig
*/
public abstract class BeginOfLineMove extends AbstractMove implements Move {
@Override
public boolean isHorizontal() {
return true;
}
@Override
public boolean includesTarget() {
return true;
}
/**
* Moves to the "real" begin of the line. It also extends Number, because
* it is mapped to the 0-key which is also used for specifying a count. This
* is quite a hack.
*
* @author Matthias Radig
*/
public static class Absolute extends Number implements Move {
private int target = -1;
public Absolute() {
super("0");
}
public int getTarget() {
return target;
}
public boolean isHorizontal() {
return true;
}
@Override
public boolean isOperator() {
return target == -1 && super.isOperator();
}
@Override
public boolean evaluate(VimEmulator vim, Token next)
throws TokenException {
+ if (next != null) {
+ return super.evaluate(vim, next);
+ }
target = vim.getPlatform().getLineInformation().getBeginOffset();
return true;
}
@Override
public Action getAction() {
return new HorizontalChangeMoveToAction(target);
}
@Override
public Space getSpace() {
return Space.VIEW;
}
public boolean includesTarget() {
return true;
}
}
/**
* Moves to the first non-whitespace character of the line, or the end of
* the line if the line is blank.
*
* @author Matthias Radig
*/
public static class FirstText extends BeginOfLineMove {
@Override
protected int calculateTarget(VimEmulator vim, Token next) {
return VimUtils.getFirstNonWhiteSpaceOffset(vim, vim.getPlatform().getLineInformation());
}
}
}
| true | true | public boolean evaluate(VimEmulator vim, Token next)
throws TokenException {
target = vim.getPlatform().getLineInformation().getBeginOffset();
return true;
}
| public boolean evaluate(VimEmulator vim, Token next)
throws TokenException {
if (next != null) {
return super.evaluate(vim, next);
}
target = vim.getPlatform().getLineInformation().getBeginOffset();
return true;
}
|
diff --git a/Core/src/org/sleuthkit/autopsy/ingest/GeneralIngestConfigurator.java b/Core/src/org/sleuthkit/autopsy/ingest/GeneralIngestConfigurator.java
index a183a4ac1..dde703f93 100644
--- a/Core/src/org/sleuthkit/autopsy/ingest/GeneralIngestConfigurator.java
+++ b/Core/src/org/sleuthkit/autopsy/ingest/GeneralIngestConfigurator.java
@@ -1,164 +1,164 @@
/*
* Autopsy Forensic Browser
*
* Copyright 2013 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sleuthkit.autopsy.ingest;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JPanel;
import org.openide.util.lookup.ServiceProvider;
import org.sleuthkit.autopsy.casemodule.IngestConfigurator;
import org.sleuthkit.autopsy.coreutils.ModuleSettings;
import org.sleuthkit.autopsy.ingest.IngestDialogPanel;
import org.sleuthkit.autopsy.ingest.IngestManager;
import org.sleuthkit.autopsy.ingest.IngestModuleAbstract;
import org.sleuthkit.datamodel.Content;
@ServiceProvider(service = IngestConfigurator.class)
public class GeneralIngestConfigurator implements IngestConfigurator {
public static final String ENABLED_INGEST_MODULES_KEY = "Enabled_Ingest_Modules";
public static final String PARSE_UNALLOC_SPACE_KEY = "Process_Unallocated_Space";
private List<Content> contentToIngest;
private IngestManager manager;
private IngestDialogPanel ingestDialogPanel;
private String moduleContext;
public GeneralIngestConfigurator() {
this.moduleContext = IngestManager.MODULE_PROPERTIES;
ingestDialogPanel = new IngestDialogPanel();
ingestDialogPanel.setContext(moduleContext);
manager = IngestManager.getDefault();
}
@Override
public List<String> setContext(String context) {
moduleContext = context;
ingestDialogPanel.setContext(moduleContext);
return loadSettingsForContext();
}
private List<String> loadSettingsForContext() {
List<String> messages = new ArrayList<>();
// If there is no enabled ingest modules setting for this user, default to enabling all
// of the ingest modules the IngestManager has loaded.
if (ModuleSettings.settingExists(moduleContext, ENABLED_INGEST_MODULES_KEY) == false) {
String defaultSetting = moduleListToCsv(IngestManager.getDefault().enumerateAllModules());
ModuleSettings.setConfigSetting(moduleContext, ENABLED_INGEST_MODULES_KEY, defaultSetting);
}
// Get the enabled ingest modules setting, check for missing modules, and pass the setting to
// the UI component.
List<IngestModuleAbstract> allModules = IngestManager.getDefault().enumerateAllModules();
String[] enabledModuleNames = ModuleSettings.getConfigSetting(moduleContext, ENABLED_INGEST_MODULES_KEY).split(", ");
List<IngestModuleAbstract> enabledModules = new ArrayList<>();
for (String moduleName : enabledModuleNames) {
IngestModuleAbstract moduleFound = null;
for (IngestModuleAbstract module : allModules) {
if (moduleName.equals(module.getName())) {
moduleFound = module;
break;
}
}
if (moduleFound != null) {
enabledModules.add(moduleFound);
}
else {
- messages.add("Unable to load " + moduleName + " module, it will not be available");
+ messages.add("Unable to load " + moduleName + " module");
}
}
ingestDialogPanel.setEnabledIngestModules(enabledModules);
// If there is no process unallocated space flag setting, default it to false.
if (ModuleSettings.settingExists(moduleContext, PARSE_UNALLOC_SPACE_KEY) == false) {
ModuleSettings.setConfigSetting(moduleContext, PARSE_UNALLOC_SPACE_KEY, "false");
}
// Get the process unallocated space flag setting and pass it to the UI component.
boolean processUnalloc = Boolean.parseBoolean(ModuleSettings.getConfigSetting(moduleContext, PARSE_UNALLOC_SPACE_KEY));
ingestDialogPanel.setProcessUnallocSpaceEnabled(processUnalloc);
return messages;
}
@Override
public JPanel getIngestConfigPanel() {
// Note that this panel allows for selecting modules for the ingest process,
// specifying the process unallocated space flag, and also specifying settings
// for a selected ingest module.
return ingestDialogPanel;
}
@Override
public void save() {
// Save the user's configuration of the set of enabled ingest modules.
String enabledModulesCsvList = moduleListToCsv(ingestDialogPanel.getModulesToStart());
ModuleSettings.setConfigSetting(moduleContext, ENABLED_INGEST_MODULES_KEY, enabledModulesCsvList);
// Save the user's setting for the process unallocated space flag.
String processUnalloc = Boolean.toString(ingestDialogPanel.processUnallocSpaceEnabled());
ModuleSettings.setConfigSetting(moduleContext, PARSE_UNALLOC_SPACE_KEY, processUnalloc);
// Save the user's configuration of the currently selected ingest module.
IngestModuleAbstract currentModule = ingestDialogPanel.getCurrentIngestModule();
if (currentModule != null && currentModule.hasSimpleConfiguration()) {
currentModule.saveSimpleConfiguration();
}
}
private static String moduleListToCsv(List<IngestModuleAbstract> lst) {
if (lst == null || lst.isEmpty()) {
return "";
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < lst.size() - 1; ++i) {
sb.append(lst.get(i).getName()).append(", ");
}
// and the last one
sb.append(lst.get(lst.size() - 1).getName());
return sb.toString();
}
@Override
public void setContent(List<Content> inputContent) {
this.contentToIngest = inputContent;
}
@Override
public void start() {
// Get the list of ingest modules selected by the user.
List<IngestModuleAbstract> modulesToStart = ingestDialogPanel.getModulesToStart();
// Get the user's selection of whether or not to process unallocated space.
manager.setProcessUnallocSpace(ingestDialogPanel.processUnallocSpaceEnabled());
if (!modulesToStart.isEmpty() && contentToIngest != null) {
// Queue the ingest process.
manager.execute(modulesToStart, contentToIngest);
}
}
@Override
public boolean isIngestRunning() {
return manager.isIngestRunning();
}
}
| true | true | private List<String> loadSettingsForContext() {
List<String> messages = new ArrayList<>();
// If there is no enabled ingest modules setting for this user, default to enabling all
// of the ingest modules the IngestManager has loaded.
if (ModuleSettings.settingExists(moduleContext, ENABLED_INGEST_MODULES_KEY) == false) {
String defaultSetting = moduleListToCsv(IngestManager.getDefault().enumerateAllModules());
ModuleSettings.setConfigSetting(moduleContext, ENABLED_INGEST_MODULES_KEY, defaultSetting);
}
// Get the enabled ingest modules setting, check for missing modules, and pass the setting to
// the UI component.
List<IngestModuleAbstract> allModules = IngestManager.getDefault().enumerateAllModules();
String[] enabledModuleNames = ModuleSettings.getConfigSetting(moduleContext, ENABLED_INGEST_MODULES_KEY).split(", ");
List<IngestModuleAbstract> enabledModules = new ArrayList<>();
for (String moduleName : enabledModuleNames) {
IngestModuleAbstract moduleFound = null;
for (IngestModuleAbstract module : allModules) {
if (moduleName.equals(module.getName())) {
moduleFound = module;
break;
}
}
if (moduleFound != null) {
enabledModules.add(moduleFound);
}
else {
messages.add("Unable to load " + moduleName + " module, it will not be available");
}
}
ingestDialogPanel.setEnabledIngestModules(enabledModules);
// If there is no process unallocated space flag setting, default it to false.
if (ModuleSettings.settingExists(moduleContext, PARSE_UNALLOC_SPACE_KEY) == false) {
ModuleSettings.setConfigSetting(moduleContext, PARSE_UNALLOC_SPACE_KEY, "false");
}
// Get the process unallocated space flag setting and pass it to the UI component.
boolean processUnalloc = Boolean.parseBoolean(ModuleSettings.getConfigSetting(moduleContext, PARSE_UNALLOC_SPACE_KEY));
ingestDialogPanel.setProcessUnallocSpaceEnabled(processUnalloc);
return messages;
}
| private List<String> loadSettingsForContext() {
List<String> messages = new ArrayList<>();
// If there is no enabled ingest modules setting for this user, default to enabling all
// of the ingest modules the IngestManager has loaded.
if (ModuleSettings.settingExists(moduleContext, ENABLED_INGEST_MODULES_KEY) == false) {
String defaultSetting = moduleListToCsv(IngestManager.getDefault().enumerateAllModules());
ModuleSettings.setConfigSetting(moduleContext, ENABLED_INGEST_MODULES_KEY, defaultSetting);
}
// Get the enabled ingest modules setting, check for missing modules, and pass the setting to
// the UI component.
List<IngestModuleAbstract> allModules = IngestManager.getDefault().enumerateAllModules();
String[] enabledModuleNames = ModuleSettings.getConfigSetting(moduleContext, ENABLED_INGEST_MODULES_KEY).split(", ");
List<IngestModuleAbstract> enabledModules = new ArrayList<>();
for (String moduleName : enabledModuleNames) {
IngestModuleAbstract moduleFound = null;
for (IngestModuleAbstract module : allModules) {
if (moduleName.equals(module.getName())) {
moduleFound = module;
break;
}
}
if (moduleFound != null) {
enabledModules.add(moduleFound);
}
else {
messages.add("Unable to load " + moduleName + " module");
}
}
ingestDialogPanel.setEnabledIngestModules(enabledModules);
// If there is no process unallocated space flag setting, default it to false.
if (ModuleSettings.settingExists(moduleContext, PARSE_UNALLOC_SPACE_KEY) == false) {
ModuleSettings.setConfigSetting(moduleContext, PARSE_UNALLOC_SPACE_KEY, "false");
}
// Get the process unallocated space flag setting and pass it to the UI component.
boolean processUnalloc = Boolean.parseBoolean(ModuleSettings.getConfigSetting(moduleContext, PARSE_UNALLOC_SPACE_KEY));
ingestDialogPanel.setProcessUnallocSpaceEnabled(processUnalloc);
return messages;
}
|
diff --git a/src/gov/nih/nci/cadsr/cdecurate/tool/InsACService.java b/src/gov/nih/nci/cadsr/cdecurate/tool/InsACService.java
index e25c8917..d3c2ccd6 100755
--- a/src/gov/nih/nci/cadsr/cdecurate/tool/InsACService.java
+++ b/src/gov/nih/nci/cadsr/cdecurate/tool/InsACService.java
@@ -1,6576 +1,6577 @@
// $Header: /cvsshare/content/cvsroot/cdecurate/src/gov/nih/nci/cadsr/cdecurate/tool/InsACService.java,v 1.78 2009-04-29 17:59:15 veerlah Exp $
// $Name: not supported by cvs2svn $
package gov.nih.nci.cadsr.cdecurate.tool;
import gov.nih.nci.cadsr.cdecurate.database.Alternates;
import gov.nih.nci.cadsr.cdecurate.database.DBAccess;
import gov.nih.nci.cadsr.cdecurate.database.SQLHelper;
import gov.nih.nci.cadsr.cdecurate.util.DataManager;
import gov.nih.nci.cadsr.common.Constants;
import gov.nih.nci.cadsr.persist.concept.Con_Derivation_Rules_Ext_Mgr;
import gov.nih.nci.cadsr.persist.de.DeComp;
import gov.nih.nci.cadsr.persist.de.DeErrorCodes;
import gov.nih.nci.cadsr.persist.de.DeVO;
import gov.nih.nci.cadsr.persist.evs.EvsVO;
import gov.nih.nci.cadsr.persist.evs.Evs_Mgr;
import gov.nih.nci.cadsr.persist.evs.ResultVO;
import gov.nih.nci.cadsr.persist.exception.DBException;
import gov.nih.nci.cadsr.persist.oc.Object_Classes_Ext_Mgr;
import gov.nih.nci.cadsr.persist.prop.Properties_Ext_Mgr;
import gov.nih.nci.cadsr.persist.rep.Representations_Ext_Mgr;
import java.io.Serializable;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.StringTokenizer;
import java.util.Vector;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import oracle.jdbc.driver.OracleTypes;
import org.apache.log4j.Logger;
//import org.joda.time.DateTimeUtils;
/**
* InsACService class is used in submit action of the tool for all components.
* where all calls to insert or update to the database after the validation is
* done here.
* <P>
*
* @author Sumana Hegde
* @version 3.0
*
*/
/*
* The CaCORE Software License, Version 3.0 Copyright 2002-2005 ScenPro, Inc.
* ("ScenPro") Copyright Notice. The software subject to this notice and license
* includes both human readable source code form and machine readable, binary,
* object code form ("the CaCORE Software"). The CaCORE Software was developed
* in conjunction with the National Cancer Institute ("NCI") by NCI employees
* and employees of SCENPRO. To the extent government employees are authors, any
* rights in such works shall be subject to Title 17 of the United States Code,
* section 105. This CaCORE Software License (the "License") is between NCI and
* You. "You (or "Your") shall mean a person or an entity, and all other
* entities that control, are controlled by, or are under common control with
* the entity. "Control" for purposes of this definition means (i) the direct or
* indirect power to cause the direction or management of such entity, whether
* by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of
* the outstanding shares, or (iii) beneficial ownership of such entity. This
* License is granted provided that You agree to the conditions described below.
* NCI grants You a non-exclusive, worldwide, perpetual, fully-paid-up,
* no-charge, irrevocable, transferable and royalty-free right and license in
* its rights in the CaCORE Software to (i) use, install, access, operate,
* execute, copy, modify, translate, market, publicly display, publicly perform,
* and prepare derivative works of the CaCORE Software; (ii) distribute and have
* distributed to and by third parties the CaCORE Software and any modifications
* and derivative works thereof; and (iii) sublicense the foregoing rights set
* out in (i) and (ii) to third parties, including the right to license such
* rights to further third parties. For sake of clarity, and not by way of
* limitation, NCI shall have no right of accounting or right of payment from
* You or Your sublicensees for the rights granted under this License. This
* License is granted at no charge to You. 1. Your redistributions of the source
* code for the Software must retain the above copyright notice, this list of
* conditions and the disclaimer and limitation of liability of Article 6,
* below. Your redistributions in object code form must reproduce the above
* copyright notice, this list of conditions and the disclaimer of Article 6 in
* the documentation and/or other materials provided with the distribution, if
* any. 2. Your end-user documentation included with the redistribution, if any,
* must include the following acknowledgment: "This product includes software
* developed by SCENPRO and the National Cancer Institute." If You do not
* include such end-user documentation, You shall include this acknowledgment in
* the Software itself, wherever such third-party acknowledgments normally
* appear. 3. You may not use the names "The National Cancer Institute", "NCI"
* "ScenPro, Inc." and "SCENPRO" to endorse or promote products derived from
* this Software. This License does not authorize You to use any trademarks,
* service marks, trade names, logos or product names of either NCI or SCENPRO,
* except as required to comply with the terms of this License. 4. For sake of
* clarity, and not by way of limitation, You may incorporate this Software into
* Your proprietary programs and into any third party proprietary programs.
* However, if You incorporate the Software into third party proprietary
* programs, You agree that You are solely responsible for obtaining any
* permission from such third parties required to incorporate the Software into
* such third party proprietary programs and for informing Your sublicensees,
* including without limitation Your end-users, of their obligation to secure
* any required permissions from such third parties before incorporating the
* Software into such third party proprietary software programs. In the event
* that You fail to obtain such permissions, You agree to indemnify NCI for any
* claims against NCI by such third parties, except to the extent prohibited by
* law, resulting from Your failure to obtain such permissions. 5. For sake of
* clarity, and not by way of limitation, You may add Your own copyright
* statement to Your modifications and to the derivative works, and You may
* provide additional or different license terms and conditions in Your
* sublicenses of modifications of the Software, or any derivative works of the
* Software as a whole, provided Your use, reproduction, and distribution of the
* Work otherwise complies with the conditions stated in this License. 6. THIS
* SOFTWARE IS PROVIDED "AS IS," AND ANY EXPRESSED OR IMPLIED WARRANTIES,
* (INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
* NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE) ARE DISCLAIMED. IN NO
* EVENT SHALL THE NATIONAL CANCER INSTITUTE, SCENPRO, OR THEIR AFFILIATES 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.
*/
// @SuppressWarnings("unchecked")
public class InsACService implements Serializable {
/**
*
*/
private static final long serialVersionUID = 738251122350261121L;
CurationServlet m_servlet = null;
UtilService m_util = new UtilService();
HttpServletRequest m_classReq = null;
HttpServletResponse m_classRes = null;
Logger logger = Logger.getLogger(InsACService.class.getName());
/**
* Constructs a new instance.
*
* @param req
* The HttpServletRequest object.
* @param res
* HttpServletResponse object.
* @param CurationServlet
* NCICuration servlet object.
*/
public InsACService(HttpServletRequest req, HttpServletResponse res,
CurationServlet CurationServlet) {
m_classReq = req;
m_classRes = res;
m_servlet = CurationServlet;
}
/**
* stores status message in the session
*
* @param sMsg
* string message to append to.
*/
@SuppressWarnings("unchecked")
private void storeStatusMsg(String sMsg) {
try {
m_servlet.storeStatusMsg(sMsg);
} catch (Exception e) {
logger.error(
"ERROR in InsACService-storeStatusMsg for exception : "
+ e.toString(), e);
m_classReq.setAttribute("retcode", "Message Exception");
}
}
/**
* To insert a new value domain or update the existing one in the database
* after the validation. Called from CurationServlet. Gets all the attribute
* values from the bean, sets in parameters, and registers output parameter.
* Calls oracle stored procedure "{call
* SBREXT_Set_Row.SET_VD(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}"
* to submit If no error occurs from query execute, calls 'setVD_PVS' to
* make relationship between Permissible values and value domain, calls
* 'setDES' to store selected rep term, rep qualifier, and language in the
* database,
*
* @param sAction
* Insert or update Action.
* @param vd
* VD Bean.
* @param sInsertFor
* for Versioning.
* @param oldVD
* VD IDseq.
*
* @return String return code from the stored procedure call. null if no
* error occurred.
*/
@SuppressWarnings("unchecked")
public String setVD(String sAction, VD_Bean vd, String sInsertFor,
VD_Bean oldVD) {
ResultSet rs = null;
CallableStatement cstmt = null;
HttpSession session = m_classReq.getSession();
String sReturnCode = ""; // ou
String sVDParent = "";
try {
String sOriginAction = (String) session
.getAttribute("originAction");
if (sOriginAction == null)
sOriginAction = "";
m_classReq.setAttribute("retcode", ""); // empty retcode to track it
// all through this request
if (oldVD == null)
oldVD = new VD_Bean();
String sVD_ID = vd.getVD_VD_IDSEQ();
String sName = vd.getVD_PREFERRED_NAME();
if (sName == null)
sName = "";
String pageVDType = vd.getVD_TYPE_FLAG();
String sContextID = vd.getVD_CONTE_IDSEQ();
String sLongName = vd.getVD_LONG_NAME();
String oldASLName = oldVD.getVD_ASL_NAME();
if (oldASLName == null)
oldASLName = "";
String prefType = vd.getAC_PREF_NAME_TYPE();
// do this only for insert because parent concept is not yet updated
// to get it from API
if (prefType != null && prefType.equals("SYS")
&& sAction.equals("INS")) // && sName.equals("(Generated
// by the System)"))
sName = "System Generated";
// store versioned status message
if (sInsertFor.equals("Version"))
this.storeStatusMsg("\\t Created new version successfully.");
if (!sOriginAction.equals("BlockEditVD")) // not for block edit
{
// remove vd_pvs relationship if vd type has changed from enum
// to non-enum
Vector<PV_Bean> vVDPVs = vd.getRemoved_VDPVList(); // vd.getVD_PV_List();
// //(Vector)session.getAttribute("VDPVList");
if (!pageVDType.equals("E") && sAction.equals("UPD")
&& vVDPVs != null && vVDPVs.size() > 0) {
PVServlet pvser = new PVServlet(m_classReq, m_classRes,
m_servlet);
String sStat = pvser.doRemoveVDPV(vd); // TODO -
// this.addRemoveVDPVS(vd,
// false);
if (sReturnCode != null && !sReturnCode.equals(""))
vd.setVD_TYPE_FLAG("E");
if (sStat != null && !sStat.equals(""))
this.storeStatusMsg(sStat);
}
}
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
// cstmt = conn.prepareCall("{call
// SBREXT_Set_Row.SET_VD(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}");
cstmt = m_servlet
.getConn()
.prepareCall(
"{call SBREXT_SET_ROW.SET_VD(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}");
// cstmt.registerOutParameter(1, java.sql.Types.VARCHAR);
// //ua_name
cstmt.registerOutParameter(2, java.sql.Types.VARCHAR); // return
// code
cstmt.registerOutParameter(5, java.sql.Types.VARCHAR); // vd id
cstmt.registerOutParameter(6, java.sql.Types.VARCHAR); // preferred
// name
cstmt.registerOutParameter(7, java.sql.Types.VARCHAR); // context
// id
cstmt.registerOutParameter(8, java.sql.Types.DECIMAL); // version
cstmt.registerOutParameter(9, java.sql.Types.VARCHAR); // preferred
// definition
cstmt.registerOutParameter(10, java.sql.Types.VARCHAR); // cd id
cstmt.registerOutParameter(11, java.sql.Types.VARCHAR); // asl
// name
cstmt.registerOutParameter(12, java.sql.Types.VARCHAR); // latest
// version
// ind
cstmt.registerOutParameter(13, java.sql.Types.VARCHAR); // dtl
// name
cstmt.registerOutParameter(14, java.sql.Types.NUMERIC); // Max
// Length
// Number
cstmt.registerOutParameter(15, java.sql.Types.VARCHAR); // Long
// name
cstmt.registerOutParameter(16, java.sql.Types.VARCHAR); // Forml
// Name
cstmt.registerOutParameter(17, java.sql.Types.VARCHAR); // Forml
// Description
cstmt.registerOutParameter(18, java.sql.Types.VARCHAR); // Forml
// Comment
cstmt.registerOutParameter(19, java.sql.Types.VARCHAR); // UOML
// name
cstmt.registerOutParameter(20, java.sql.Types.VARCHAR); // UOML
// Desciption
cstmt.registerOutParameter(21, java.sql.Types.VARCHAR); // UOML
// comment
cstmt.registerOutParameter(22, java.sql.Types.VARCHAR); // Low
// value
// number
cstmt.registerOutParameter(23, java.sql.Types.VARCHAR); // High
// Value
// Number
cstmt.registerOutParameter(24, java.sql.Types.NUMERIC); // Min
// Lenght
// Num
cstmt.registerOutParameter(25, java.sql.Types.NUMERIC); // Decimal
// Place
cstmt.registerOutParameter(26, java.sql.Types.VARCHAR); // Char
// set
// name
cstmt.registerOutParameter(27, java.sql.Types.VARCHAR); // begin
// date
cstmt.registerOutParameter(28, java.sql.Types.VARCHAR); // end
// date
cstmt.registerOutParameter(29, java.sql.Types.VARCHAR); // change
// note
cstmt.registerOutParameter(30, java.sql.Types.VARCHAR); // type
// flag
cstmt.registerOutParameter(31, java.sql.Types.VARCHAR); // created
// by
cstmt.registerOutParameter(32, java.sql.Types.VARCHAR); // date
// created
cstmt.registerOutParameter(33, java.sql.Types.VARCHAR); // modified
// by
cstmt.registerOutParameter(34, java.sql.Types.VARCHAR); // date
// modified
cstmt.registerOutParameter(35, java.sql.Types.VARCHAR); // deleted
// ind
cstmt.registerOutParameter(36, java.sql.Types.VARCHAR); // condr_idseq
// Get the username from the session.
String userName = (String) session.getAttribute("Username");
cstmt.setString(1, userName); // set ua_name
cstmt.setString(3, ""); // make it empty default
cstmt.setString(4, sAction); // ACTION - INS, UPD or DEL
if ((sAction.equals("UPD")) || (sAction.equals("DEL")))
cstmt.setString(5, sVD_ID); // A
// make it null for editing released elements
if (sAction.equals("UPD") && oldASLName.equals("RELEASED")
&& !sInsertFor.equals("Version")) {
cstmt.setString(6, null); // preferred name - not null for
// INS, must be null for UPD
cstmt.setString(7, null); // context id - not null for
// INS, must be null for UPD
} else // INS case
{
cstmt.setString(6, sName); // preferred name - not null for
// INS, must be null for UPD
cstmt.setString(7, sContextID); // context id - not null for
// INS, must be null for UPD
}
cstmt.setString(37, ""); // rep term idseq, null by default
cstmt.setString(38, ""); // rep qualifier - null by default
cstmt.setString(39, ""); // origin
// String sContext = vd.getVD_CONTEXT_NAME();
Double DVersion = new Double(vd.getVD_VERSION());
double dVersion = DVersion.doubleValue();
String sDefinition = vd.getVD_PREFERRED_DEFINITION();
String sCD_ID = vd.getVD_CD_IDSEQ();
// Vector sPV_ID = vd.getVD_PV_ID();
String sAslName = vd.getVD_ASL_NAME();
// String sLatestVersion = vd.getVD_LATEST_VERSION_IND();
String sDtlName = vd.getVD_DATA_TYPE();
String sTypeFlag = vd.getVD_TYPE_FLAG();
String sRepTerm = m_util.formatStringVDSubmit(sAction,
"RepTerm", vd, oldVD);
String sSource = m_util.formatStringVDSubmit(sAction, "Source",
vd, oldVD);
String sChangeNote = m_util.formatStringVDSubmit(sAction,
"ChangeNote", vd, oldVD);
String sEndDate = m_util.formatStringVDSubmit(sAction,
"EndDate", vd, oldVD);
String sBeginDate = m_util.formatStringVDSubmit(sAction,
"BeginDate", vd, oldVD);
String sUomlName = m_util.formatStringVDSubmit(sAction,
"UOMLName", vd, oldVD);
String sFormlName = m_util.formatStringVDSubmit(sAction,
"FORMLName", vd, oldVD);
String sMaxLength = m_util.formatStringVDSubmit(sAction,
"MaxLen", vd, oldVD);
String sMinLength = m_util.formatStringVDSubmit(sAction,
"MinLen", vd, oldVD);
String sLowValue = m_util.formatStringVDSubmit(sAction,
"LowValue", vd, oldVD);
String sHighValue = m_util.formatStringVDSubmit(sAction,
"HighValue", vd, oldVD);
String sDecimalPlace = m_util.formatStringVDSubmit(sAction,
"Decimal", vd, oldVD);
// create concepts and pass them in comma-delimited format
if (!sOriginAction.equals("BlockEditVD"))
sVDParent = this.setEVSParentConcept(vd); // "", sVDCondr
// = "";
if (sVDParent == null)
sVDParent = "";
// Set the In parameters (which are inherited from the
// PreparedStatement class)
cstmt.setString(3, sVDParent); // comma-delimited con idseqs
if (sVDParent.equals("removeParent"))
cstmt.setString(3, ""); // do not set vdconcepts
cstmt.setDouble(8, dVersion); // version - test says must have
// a value
cstmt.setString(9, sDefinition); // preferred definition -
// not null for INS
cstmt.setString(10, sCD_ID); // cd id - not null for INS
cstmt.setString(11, sAslName);
if (sAction.equals("INS"))
cstmt.setString(12, "Yes");
cstmt.setString(13, sDtlName);
if (sMaxLength != null && sMaxLength.length() > 0) {
Integer IntTmp = new Integer(sMaxLength);
cstmt.setInt(14, IntTmp.intValue());
}
cstmt.setString(15, sLongName); // long name - can be null
cstmt.setString(16, sFormlName);
cstmt.setString(19, sUomlName);
cstmt.setString(22, sLowValue);
cstmt.setString(23, sHighValue);
if (sMinLength != null && sMinLength.length() > 0) {
Integer IntTmp = new Integer(sMinLength);
cstmt.setInt(24, IntTmp.intValue());
}
if (sDecimalPlace != null && sDecimalPlace.length() > 0) {
Integer IntTmp = new Integer(sDecimalPlace);
cstmt.setInt(25, IntTmp.intValue());
}
cstmt.setString(27, sBeginDate);
cstmt.setString(28, sEndDate);
cstmt.setString(29, sChangeNote);
cstmt.setString(30, sTypeFlag); // type flag - E by default
if (sOriginAction.equals("BlockEditVD")
&& sInsertFor.equals("Version"))
cstmt.setString(36, vd.getVD_PAR_CONDR_IDSEQ()); // set
// as
// the
// earlier
// one.
else {
if (sAction.equals("UPD")
&& sVDParent.equals("removeParent"))
cstmt.setString(36, " "); // remove the existing
// parent if removing them
// all
}
cstmt.setString(37, sRepTerm); // rep term idseq, null by
// default
cstmt.setString(38, ""); // rep qualifier - null by default
cstmt.setString(39, sSource); // origin
cstmt.execute();
// capture the duration
// logger.info(m_servlet.getLogMessage(m_classReq, "setVD",
// "execute ok", startDate, new java.util.Date()));
if (vd.getVD_IN_FORM()) {
//Go through all the forms and set warnings for owners
SearchServlet ser = new SearchServlet(m_classReq, m_classRes, m_servlet.m_servletContext);
ser.get_m_conn();
HashMap<String,ArrayList<String[]>> display = ser.getVDAssociatedForms(vd.getIDSEQ(), null);
ArrayList<String[]> forms = display.get("Content");
String[] headers = display.get("Head").get(0);
//Last two spots.
int idseqNdx = headers.length-1;
int nameNdx = headers.length-2;
for (String[] formInfo : forms) {
m_servlet.doMonitor(formInfo[nameNdx], formInfo[idseqNdx]);
}
}
sReturnCode = cstmt.getString(2);
String prefName = cstmt.getString(6);
if (prefName != null)
vd.setVD_PREFERRED_NAME(prefName);
if (sReturnCode == null || sReturnCode.equals("")) {
m_servlet.clearBuildingBlockSessionAttributes(m_classReq,
m_classRes);
vd.setVD_REP_QUALIFIER_NAMES(null);
vd.setVD_REP_QUALIFIER_CODES(null);
vd.setVD_REP_QUALIFIER_DB(null);
}
vd.setVD_PAR_CONDR_IDSEQ(cstmt.getString(35));
sVD_ID = cstmt.getString(5);
vd.setVD_VD_IDSEQ(sVD_ID);
String sReturn = "";
if (sAction.equals("INS"))
this.storeStatusMsg("Value Domain Name : "
+ vd.getVD_LONG_NAME());
// continue update even if not null
if (sReturnCode != null && sAction.equals("INS")) {
this
.storeStatusMsg("\\t "
+ sReturnCode
+ " : Unable to create new Value Domain Successfully.");
logger
.error(sReturnCode
+ " Unable to create new Value Domain Successfully.");
} else if ((sReturnCode == null || (sReturnCode != null && sAction
.equals("UPD")))
&& !sVD_ID.equals("")) {
// store the status message in the session
if (sAction.equals("INS")) {
String sPublicID = this.getPublicID(sVD_ID);
vd.setVD_VD_ID(sPublicID);
this.storeStatusMsg("Public ID : " + vd.getVD_VD_ID());
this
.storeStatusMsg("\\t Successfully created New Value Domain");
} else if (sAction.equals("UPD") && sReturnCode != null
&& !sReturnCode.equals(""))
this.storeStatusMsg("\\t " + sReturnCode
+ " : Unable to update mandatory attributes.");
// store returncode in request to track it all through this
// request
if (sReturnCode != null && !sReturnCode.equals(""))
m_classReq.setAttribute("retcode", sReturnCode);
// create non evs parent concept in reference documents
// table
sReturn = this.setNonEVSParentConcept(vd);
// This writes the source of a Meta parent to Ref Docs
// sVDParent is string of con_idseqs for parent concepts
// if(sVDParent != null && !sVDParent.equals(""))
if (vd.getVD_PAR_CONDR_IDSEQ() != null
&& !vd.getVD_PAR_CONDR_IDSEQ().equals(""))
sReturn = this.setRDMetaConceptSource(vd);
// set create/modify attributes into bean
if (cstmt.getString(31) != null
&& !cstmt.getString(31).equals(""))
vd.setVD_CREATED_BY(getFullName(cstmt.getString(31)));
else
vd.setVD_CREATED_BY(oldVD.getVD_CREATED_BY());
if (cstmt.getString(32) != null
&& !cstmt.getString(32).equals(""))
vd.setVD_DATE_CREATED(m_util.getCurationDate(cstmt
.getString(32)));
else
vd.setVD_DATE_CREATED(oldVD.getVD_DATE_CREATED());
vd.setVD_MODIFIED_BY(getFullName(cstmt.getString(33)));
vd.setVD_DATE_MODIFIED(m_util.getCurationDate(cstmt
.getString(34)));
//===========GF32398====Insert/update/delete regstatus=======START
String sReturned = "";
if (vd.getVD_REG_STATUS() != null
&& !vd.getVD_REG_STATUS().equals("")) {
logger.debug("line 566 of InsACSErvice.java registration value is "+vd.getVD_REG_STATUS()+"************");
vd.setVD_REG_STATUS_IDSEQ(this.getAC_REG(sVD_ID));
if (vd.getVD_REG_STATUS_IDSEQ() == null
|| vd.getVD_REG_STATUS_IDSEQ().equals("")){
logger.info("line 570 of InsACSErvice.java ************");
sReturned = this.setReg_Status("INS", "", sVD_ID, vd
.getVD_REG_STATUS());
}
else{
logger.info("line 576 of InsACSErvice.java ************");
sReturned = this.setReg_Status("UPD", vd
.getVD_REG_STATUS_IDSEQ(), sVD_ID, vd
.getVD_REG_STATUS());
}
if (sReturned != null && !sReturned.equals("")){
logger.info("line 583 of InsACSErvice.java ************");
this.storeStatusMsg("\\t "
+ sReturned
+ " : Unable to update Registration Status.");
}
} else {
// delete if reg status is empty and idseq is not null
if (vd.getVD_REG_STATUS_IDSEQ() != null
&& !vd.getVD_REG_STATUS_IDSEQ().equals("")){
logger.info("line 593 of InsACSErvice.java ************");
sReturned = this.setReg_Status("DEL", vd
.getVD_REG_STATUS_IDSEQ(), sVD_ID, vd
.getVD_REG_STATUS());
}
if (sReturned != null && !sReturned.equals("")){
logger.info("line 600 of InsACSErvice.java ************");
this
.storeStatusMsg("\\t "
+ sReturned
+ " : Unable to remove Registration Status.");
}
}
// store returncode in request to track it all through this
// request
if (sAction.equals("UPD") && sReturned != null
&& !sReturned.equals(""))
m_classReq.setAttribute("retcode", sReturned);
//===========GF32398====Insert/update/delete regstatus=======END
// insert the vd pv relationships in vd_pvs table if not
// block edit
if (!sOriginAction.equals("BlockEditVD")) {
if (vd.getVD_TYPE_FLAG().equals("E")
&& (pageVDType == null || pageVDType.equals("") || pageVDType
.equals("E"))) {
PVServlet pvser = new PVServlet(m_classReq,
m_classRes, m_servlet);
String sStat = pvser.submitPV(vd);
if (sStat != null && !sStat.equals(""))
this.storeStatusMsg(sStat);
// ********************************
Vector<PV_Bean> vPV = vd.getVD_PV_List(); // (Vector)session.getAttribute("VDPVList");
// //vd.getVD_PV_NAME();
for (int j = 0; j < vPV.size(); j++) {
PV_Bean pv = (PV_Bean) vPV.elementAt(j);
VM_Bean vm = pv.getPV_VM();
if (vm != null && !vm.getVM_IDSEQ().equals("")) {
// System.out.println(vm.getVM_IDSEQ() + "
// vm alt name " + sContextID + " vd " +
// vd.getVD_VD_IDSEQ());
vm.save(session, m_servlet.getConn(), vm
.getVM_IDSEQ(), sContextID);
}
}
session.removeAttribute("AllAltNameList");
// ********************************
}
}
// reset the pv counts to reset more hyperlink
String pvName = "";
Integer pvCount = new Integer(0);
if (vd.getVD_TYPE_FLAG().equals("E")) {
Vector<PV_Bean> vPV = vd.getVD_PV_List(); // (Vector)session.getAttribute("VDPVList");
// //vd.getVD_PV_NAME();
if (vPV != null && vPV.size() > 0) {
PV_Bean pvBean = (PV_Bean) vPV.elementAt(0);
pvName = pvBean.getPV_VALUE();
pvCount = new Integer(vPV.size());
}
}
vd.setVD_Permissible_Value(pvName);
vd.setVD_Permissible_Value_Count(pvCount);
// do this for new version, to check whether we need to
// write to AC_HISTORIES table later
if (sInsertFor.equals("Version")) {
vd.setVD_DATE_CREATED(vd.getVD_DATE_MODIFIED());
vd.setVD_CREATED_BY(vd.getVD_MODIFIED_BY());
vd.setVD_VD_ID(oldVD.getVD_VD_ID()); // adds public
// id to the
// bean
}
// insert and delete ac-csi relationship
Vector vAC_CS = vd.getAC_AC_CSI_VECTOR();
GetACSearch getAC = new GetACSearch(m_classReq, m_classRes,
m_servlet);
Vector vRemove_ACCSI = getAC.doCSCSI_ACSearch(sVD_ID, ""); // (Vector)session.getAttribute("vAC_CSI");
Vector vACID = (Vector) session.getAttribute("vACId");
this.addRemoveACCSI(sVD_ID, vAC_CS, vRemove_ACCSI, vACID,
sInsertFor, sLongName);
// store back altname and ref docs to session
m_servlet.doMarkACBeanForAltRef(m_classReq, m_classRes,
"ValueDomain", "all", "submitAR");
// do alternate names create
if (sInsertFor.equalsIgnoreCase("Version"))
this.doAltVersionUpdate(sVD_ID, oldVD.getVD_VD_IDSEQ());
// ********************************
vd.save(session, m_servlet.getConn(), sVD_ID, sContextID);
session.removeAttribute("AllAltNameList");
// ********************************
/*
* Vector<ALT_NAME_Bean> tBean =
* AltNamesDefsSession.getAltNameBeans(session,
* AltNamesDefsSession._searchVD, sVD_ID, sContextID); if
* (tBean != null) DataManager.setAttribute(session,
* "AllAltNameList", tBean);
*/
String oneAlt = this.doAddRemoveAltNames(sVD_ID,
sContextID, sAction); // , "create");
vd.setALTERNATE_NAME(oneAlt);
// do reference docuemnts create
if (sInsertFor.equalsIgnoreCase("Version"))
this.doRefVersionUpdate(sVD_ID, oldVD.getVD_VD_IDSEQ());
String oneRD = this.doAddRemoveRefDocs(sVD_ID, sContextID,
sAction); // "create");
vd.setREFERENCE_DOCUMENT(oneRD);
// do contact updates
Hashtable vdConts = vd.getAC_CONTACTS();
if (vdConts != null && vdConts.size() > 0)
vd.setAC_CONTACTS(this.addRemoveAC_Contacts(vdConts,
sVD_ID, sInsertFor));
// get one concept name for this vd
vd.setAC_CONCEPT_NAME(this.getOneConName("", sVD_ID));
// add success message if no error
sReturn = (String) m_classReq.getAttribute("retcode");
if (sAction.equals("UPD")
&& (sReturn == null || sReturn.equals("")))
this
.storeStatusMsg("\\t Successfully updated Value Domain.");
}
else if (sReturnCode != null && !sReturnCode.equals("")) {
this
.storeStatusMsg("\\t Unable to update the Short Name of the Value Domain.");
logger
.error(sReturnCode
+ " Unable to update the Short Name of the Value Domain.");
}
}
this.storeStatusMsg("\\n");
// capture the duration
// logger.info(m_servlet.getLogMessage(m_classReq, "setVD", "done
// set", startDate, new java.util.Date()));
} catch (Exception e) {
logger.error("ERROR in InsAerrorice-setVD for other : "
+ e.toString(), e);
m_classReq.setAttribute("retcode", "Exception");
this
.storeStatusMsg("\\t Exception : Unable to update Value Domain attributes.");
}finally{
rs = SQLHelper.closeResultSet(rs);
cstmt = SQLHelper.closeCallableStatement(cstmt);
+ SQLHelper.closeConnection(m_servlet.getConn()); //GF32398 not related to the ticket, but found the leak and fix it
}
return sReturnCode;
}
/**
* The UpdateCRFValue method updates the quest contents table with the vp
* idseq. calls setQuestContent to update.
*
* @param pv
* PVid idseq of the permissible value
*/
public void UpdateCRFValue(PV_Bean pv) {
try {
HttpSession session = m_classReq.getSession();
String sMenuAction = (String) session
.getAttribute(Session_Data.SESSION_MENU_ACTION);
if (sMenuAction.equals("Questions")
&& pv.getVP_SUBMIT_ACTION().equals("INS")) {
// get the crf value vector to update
String sVVid = pv.getQUESTION_VALUE_IDSEQ();
String sVPid = pv.getPV_VDPVS_IDSEQ();
String ret = "";
if (sVPid != null && !sVPid.equals("") && sVVid != null
&& !sVVid.equals(""))
ret = setQuestContent(null, sVVid, sVPid);
}
} catch (RuntimeException e) {
logger.error("Error - " + e);
}
} // end of UpdateCRFValue
/**
* To insert a new DEConcept or update the existing one in the database
* after the validation. Called from CurationServlet. Gets all the attribute
* values from the bean, sets in parameters, and registers output parameter.
* Calls oracle stored procedure "{call
* SBREXT_Set_Row.SET_DEC(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}"
* to submit If no error occurs from query execute calls 'setDES' to store
* selected language in the database,
*
* @param sAction
* Insert or update Action.
* @param dec
* DEC Bean.
* @param sInsertFor
* for Versioning.
* @param oldDEC
* string dec idseq
*
* @return String return code from the stored procedure call. null if no
* error occurred.
*/
public String setDEC(String sAction, DEC_Bean dec, String sInsertFor,
DEC_Bean oldDEC) {
ResultSet rs = null;
CallableStatement cstmt = null;
HttpSession session = m_classReq.getSession();
String sReturnCode = "";
// String v_ac = "";
String oldDECID = "";
// String oldContext = "";
// String oldName = "";
// String oldContextID = "";
String oldAslName = "";
String oldSource = "";
String oldEndDate = "";
String oldBeginDate = "";
String oldChangeNote = "";
try {
m_classReq.setAttribute("retcode", ""); // empty retcode to track
// returncodes
String sInsFor = sInsertFor;
if (sInsFor.equals("BlockVersion"))
sInsertFor = "Version";
// add the dec name into the message
if (sAction.equals("INS")) {
//GF30681
//this.storeStatusMsg("Data Element Concept Name : " + dec.getDEC_LONG_NAME());
}
// store versioned status message
if (sInsertFor.equals("Version"))
this.storeStatusMsg("\\t Created new version successfully.");
if (oldDEC == null)
oldDEC = new DEC_Bean();
String sName = dec.getDEC_PREFERRED_NAME();
String sContextID = dec.getDEC_CONTE_IDSEQ();
String sContext = dec.getDEC_CONTEXT_NAME();
Double DVersion = new Double(dec.getDEC_VERSION());
double dVersion = DVersion.doubleValue();
String sDefinition = dec.getDEC_PREFERRED_DEFINITION();
String sCD_ID = dec.getDEC_CD_IDSEQ();
String sLongName = dec.getDEC_LONG_NAME();
String sBeginDate = m_util.getOracleDate(dec.getDEC_BEGIN_DATE());
String sEndDate = m_util.getOracleDate(dec.getDEC_END_DATE());
// String sLanguage = dec.getDEC_LANGUAGE();
String sSource = dec.getDEC_SOURCE();
String sDEC_ID = dec.getDEC_DEC_IDSEQ();
String sCDRName = (String)session.getAttribute(Constants.DEC_CDR_NAME); //GF30681
String sChangeNote = dec.getDEC_CHANGE_NOTE();
// check if it is valid oc/prop for block dec at submit
boolean bValidOC_PROP = true;
if (sInsFor.equals("BlockEdit") || sInsFor.equals("BlockVersion")) {
// do the oc prop pair checking only if they exist
if ((dec.getDEC_OC_CONDR_IDSEQ() == null || dec
.getDEC_OC_CONDR_IDSEQ().equals(""))
&& (dec.getDEC_PROP_CONDR_IDSEQ() == null || dec
.getDEC_PROP_CONDR_IDSEQ().equals(""))) {
// display message if sys or abbr was selected for non oc
// prop dec.
if (dec.getAC_PREF_NAME_TYPE() != null
&& (dec.getAC_PREF_NAME_TYPE().equals("SYS") || dec
.getAC_PREF_NAME_TYPE().equals("ABBR"))) {
this
.storeStatusMsg("\\t Unable to change the Short Name type to System Generated or Abbreviated"
+ "\\n\\t\\t because Object Class and Property do not exist.");
bValidOC_PROP = false;
}
} else {
// SetACService setAC = new SetACService(m_servlet);
// String validOCProp = setAC.checkUniqueOCPropPair(dec,
// m_classReq, m_classRes, "EditDEC");
String validOCProp = this.checkUniqueOCPropPair(dec,
"Unique", "EditDEC");
if (validOCProp != null && !validOCProp.equals("")
&& validOCProp.indexOf("Warning") < 0) {
bValidOC_PROP = false;
this.storeStatusMsg("\\t " + validOCProp); // append
// the
// message
// reset back to old one
dec.setDEC_OC_CONDR_IDSEQ(oldDEC
.getDEC_OC_CONDR_IDSEQ());
dec.setDEC_OCL_IDSEQ(oldDEC.getDEC_OCL_IDSEQ());
dec.setDEC_PROP_CONDR_IDSEQ(oldDEC
.getDEC_PROP_CONDR_IDSEQ());
dec.setDEC_PROPL_IDSEQ(oldDEC.getDEC_PROPL_IDSEQ());
}
}
}
String sOCID = "";
String sPropL = "";
// get the system generated name for DEC from OC and Prop if oc-prop
// combination is valid
if (bValidOC_PROP == true) {
// need to send in ids not names
String sOldOCName = "";
String sOCName = "";
if (dec.getDEC_OCL_NAME() != null)
sOCName = dec.getDEC_OCL_NAME();
if (oldDEC != null)
sOldOCName = oldDEC.getDEC_OCL_NAME();
if ((sOCName == null || sOCName.equals(""))
&& sAction.equals("UPD") && !sOCName.equals(sOldOCName)) {
sOCID = " ";
dec.setDEC_OCL_IDSEQ("");
} else
sOCID = dec.getDEC_OCL_IDSEQ();
String sOldPropName = "";
String sPropName = "";
if (dec.getDEC_PROPL_NAME() != null)
sPropName = dec.getDEC_PROPL_NAME();
if (oldDEC != null)
sOldPropName = oldDEC.getDEC_PROPL_NAME();
if ((sPropName == null || sPropName.equals(""))
&& sAction.equals("UPD")
&& !sPropName.equals(sOldPropName)) {
sPropL = " ";
dec.setDEC_PROPL_IDSEQ("");
} else
sPropL = dec.getDEC_PROPL_IDSEQ();
// make condr idseq's empty if oc or prop idseqs are emtpy
if (dec.getDEC_OCL_IDSEQ() == null
|| dec.getDEC_OCL_IDSEQ().equals(""))
dec.setDEC_OC_CONDR_IDSEQ("");
if (dec.getDEC_PROPL_IDSEQ() == null
|| dec.getDEC_PROPL_IDSEQ().equals(""))
dec.setDEC_PROP_CONDR_IDSEQ("");
// get the valid preferred name
DEC_Bean vDEC = this.changeDECPrefName(dec, oldDEC, sInsertFor,
sAction);
if (vDEC == null)
return "Unique Constraint";
else
dec = vDEC;
sName = dec.getDEC_PREFERRED_NAME(); // update submit
// variable
}
// get the old attributes from the oldbean
if (oldDEC != null && !oldDEC.equals("")) {
oldDECID = oldDEC.getDEC_DEC_IDSEQ();
// oldContext = oldDEC.getDEC_CONTEXT_NAME();
// oldName = oldDEC.getDEC_PREFERRED_NAME();
// oldContextID = oldDEC.getDEC_CONTE_IDSEQ();
oldAslName = oldDEC.getDEC_ASL_NAME();
}
if (oldDEC != null)
oldSource = oldDEC.getDEC_SOURCE();
if (oldSource == null)
oldSource = "";
if (sSource == null)
sSource = "";
if ((sSource == null || sSource.equals(""))
&& sAction.equals("UPD") && !sSource.equals(oldSource))
sSource = " ";
if (oldDEC != null)
oldChangeNote = oldDEC.getDEC_CHANGE_NOTE();
if (oldChangeNote == null)
oldChangeNote = "";
if (sChangeNote == null)
sChangeNote = "";
if ((sChangeNote == null || sChangeNote.equals(""))
&& sAction.equals("UPD")
&& !sChangeNote.equals(oldChangeNote))
sChangeNote = " ";
// pass empty string if changed to null
sBeginDate = dec.getDEC_BEGIN_DATE();
if (oldDEC != null)
oldBeginDate = oldDEC.getDEC_BEGIN_DATE();
if (oldBeginDate == null)
oldBeginDate = "";
if (sBeginDate == null)
sBeginDate = "";
if ((sBeginDate == null || sBeginDate.equals(""))
&& sAction.equals("UPD")
&& !sBeginDate.equals(oldBeginDate))
sBeginDate = " ";
else
sBeginDate = m_util.getOracleDate(dec.getDEC_BEGIN_DATE());
sEndDate = dec.getDEC_END_DATE();
if (oldDEC != null)
oldEndDate = oldDEC.getDEC_END_DATE();
if (oldEndDate == null)
oldEndDate = "";
if (sEndDate == null)
sEndDate = "";
if ((sEndDate == null || sEndDate.equals(""))
&& sAction.equals("UPD") && !sEndDate.equals(oldEndDate))
sEndDate = " ";
else
sEndDate = m_util.getOracleDate(dec.getDEC_END_DATE());
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
// cstmt = conn.prepareCall("{call
// SBREXT_Set_Row.SET_DEC(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}");
cstmt = m_servlet
.getConn()
.prepareCall(
//"{call SBREXT_SET_ROW.SET_DEC(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}");
"{call SBREXT.DEC_ACTIONS.SET_DEC(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}"); //GF30681
// cstmt.registerOutParameter(1,
// java.sql.Types.VARCHAR);//ua_name
cstmt.registerOutParameter(2, java.sql.Types.VARCHAR); // return
// code
cstmt.registerOutParameter(4, java.sql.Types.VARCHAR); // dec
// id
// ?????
// vd ID
cstmt.registerOutParameter(5, java.sql.Types.VARCHAR); // preferred
// name
cstmt.registerOutParameter(6, java.sql.Types.VARCHAR); // context
// id
cstmt.registerOutParameter(7, java.sql.Types.DECIMAL); // version
cstmt.registerOutParameter(8, java.sql.Types.VARCHAR); // preferred
// definition
cstmt.registerOutParameter(9, java.sql.Types.VARCHAR); // cd id
cstmt.registerOutParameter(10, java.sql.Types.VARCHAR); // asl
// name
cstmt.registerOutParameter(11, java.sql.Types.VARCHAR); // latest
// version
// ind
cstmt.registerOutParameter(12, java.sql.Types.VARCHAR); // long
// name
cstmt.registerOutParameter(13, java.sql.Types.VARCHAR); // OCL
// name
cstmt.registerOutParameter(14, java.sql.Types.VARCHAR); // PROPL
// Name
cstmt.registerOutParameter(15, java.sql.Types.VARCHAR); // PROPERTY
// QUALIFIER
cstmt.registerOutParameter(16, java.sql.Types.VARCHAR); // OBJ
// CLASS
// QUALIFIER
cstmt.registerOutParameter(17, java.sql.Types.VARCHAR); // begin
// date
cstmt.registerOutParameter(18, java.sql.Types.VARCHAR); // end
// date
cstmt.registerOutParameter(19, java.sql.Types.VARCHAR); // change
// note
cstmt.registerOutParameter(20, java.sql.Types.VARCHAR); // created
// by
cstmt.registerOutParameter(21, java.sql.Types.VARCHAR); // date
// created
cstmt.registerOutParameter(22, java.sql.Types.VARCHAR); // modified
// by
cstmt.registerOutParameter(23, java.sql.Types.VARCHAR); // date
// modified
cstmt.registerOutParameter(24, java.sql.Types.VARCHAR); // deleted
// ind
cstmt.registerOutParameter(25, java.sql.Types.VARCHAR); // origin
// cdr_name
cstmt.registerOutParameter(26, java.sql.Types.VARCHAR); // cdr_name
// Set the In parameters (which are inherited from the
// PreparedStatement class)
// Get the username from the session.
String userName = (String) session.getAttribute("Username");
cstmt.setString(1, userName); // set ua_name
cstmt.setString(3, sAction); // ACTION - INS, UPD or DEL
if ((sAction.equals("UPD")) || (sAction.equals("DEL"))) {
sDEC_ID = dec.getDEC_DEC_IDSEQ();
cstmt.setString(4, sDEC_ID);
}
// only for editing released elements
if (sAction.equals("UPD") && oldAslName.equals("RELEASED")
&& !sInsertFor.equals("Version")) {
cstmt.setString(6, null); // context id - not null for
// INS, must be null for UPD
cstmt.setString(5, null); // preferred name - not null for
// INS, must be null for UPD
} else // INS case
{
cstmt.setString(6, sContextID); // context id - not null for
// INS, must be null for UPD
cstmt.setString(5, sName); // preferred name - not null for
// INS, must be null for UPD
}
cstmt.setDouble(7, dVersion); // version - test says must have
// a value
cstmt.setString(8, sDefinition); // preferred definition -
// not null for INS
cstmt.setString(9, sCD_ID); // cd id - not null for INS
cstmt.setString(10, dec.getDEC_ASL_NAME()); // workflow status
if (sAction.equals("INS"))
cstmt.setString(11, "Yes");
cstmt.setString(12, sLongName); // long name - can be null
cstmt.setString(13, sOCID); // OCL id
cstmt.setString(14, sPropL); // PROPL id
cstmt.setString(15, null); // OC Qualifier name
cstmt.setString(16, null); // Property qualifier name
cstmt.setString(17, sBeginDate); // sBeginDate - can be null
cstmt.setString(18, sEndDate); // sEndDate - can be null
cstmt.setString(19, sChangeNote);
cstmt.setString(25, sSource);
cstmt.setString(26, sCDRName);
// Now we are ready to call the stored procedure
cstmt.execute();
// capture the duration
// logger.info(m_servlet.getLogMessage(m_classReq, "setDEC",
// "execute done", startDate, new java.util.Date()));
sDEC_ID = cstmt.getString(4);
dec.setDEC_DEC_IDSEQ(sDEC_ID);
sReturnCode = cstmt.getString(2);
// m_servlet.clearBuildingBlockSessionAttributes(m_classReq,
// m_classRes);
// String sOriginAction =
// (String)session.getAttribute("originAction");
if (sReturnCode == null || sReturnCode.equals("")) // (!sOriginAction.equals("BlockEditDEC"))
{
m_servlet.clearBuildingBlockSessionAttributes(m_classReq,
m_classRes);
dec.setDEC_OC_QUALIFIER_NAMES(null);
dec.setDEC_OC_QUALIFIER_CODES(null);
dec.setDEC_OC_QUALIFIER_DB(null);
dec.setDEC_PROP_QUALIFIER_NAMES(null);
dec.setDEC_PROP_QUALIFIER_CODES(null);
dec.setDEC_PROP_QUALIFIER_DB(null);
}
// insert newly created row into hold vector
if (sReturnCode != null && sAction.equals("INS")){
if (sReturnCode.equalsIgnoreCase("API_DEC_300")) {//GF30681
//Place the reuse logic here.
logger.debug("DEC already exists with DEC_Id"+sDEC_ID);
this.storeStatusMsg("Data Element Concept Name : ["
+ dec.getDEC_LONG_NAME() + "] already exists");
}else{
logger.debug("sReturnCode at 1063 of InsACService.java is" + sReturnCode);
this
.storeStatusMsg("\\t "
+ sReturnCode
+ " : Unable to create new Data Element Concept Successfully.");
}
}
else if ((sReturnCode == null || (sReturnCode != null && sAction
.equals("UPD")))
&& !sDEC_ID.equals("")) {
logger.info("******called at 1072 of InsACServie.java");
// store the status message in the session
if (sAction.equals("INS")) {
logger.debug("sReturnCode at 1063 of InsACService.java is" + sReturnCode);
String sPublicID = this.getPublicID(sDEC_ID);
dec.setDEC_DEC_ID(sPublicID);
this.storeStatusMsg("Public ID : "
+ dec.getDEC_DEC_ID());
this
.storeStatusMsg("\\t Successfully created New Data Element Concept.");
//GF30681 update the CDR in dec table
// updateDECUniqueCDRName(sPublicID, (String)session.getAttribute(Constants.DEC_CDR_NAME));
} else if (sAction.equals("UPD") && sReturnCode != null
&& !sReturnCode.equals("")){
logger.debug("sReturnCode at 1084 of InsACService.java is" + sReturnCode);
this.storeStatusMsg("\\t " + sReturnCode
+ " : Unable to update mandatory attributes.");
}
// store returncode in request to track it all through this
// request
if (sReturnCode != null && !sReturnCode.equals(""))
m_classReq.setAttribute("retcode", sReturnCode);
// set create/modify attributes into bean
if (cstmt.getString(20) != null
&& !cstmt.getString(20).equals(""))
dec.setDEC_CREATED_BY(getFullName(cstmt.getString(20)));
else
dec.setDEC_CREATED_BY(oldDEC.getDEC_CREATED_BY());
if (cstmt.getString(21) != null
&& !cstmt.getString(21).equals(""))
dec.setDEC_DATE_CREATED(m_util.getCurationDate(cstmt
.getString(21)));
else
dec.setDEC_DATE_CREATED(oldDEC.getDEC_DATE_CREATED());
dec.setDEC_MODIFIED_BY(getFullName(cstmt.getString(22)));
dec.setDEC_DATE_MODIFIED(m_util.getCurationDate(cstmt
.getString(23)));
// do this for new version, to check whether we need to
// write to AC_HISTORIES table later
if (sInsertFor.equals("Version")) {
// created and modifed are same if veriosing
dec.setDEC_CREATED_BY(dec.getDEC_MODIFIED_BY());
dec.setDEC_DATE_CREATED(dec.getDEC_DATE_MODIFIED());
dec.setDEC_DEC_ID(oldDEC.getDEC_DEC_ID()); // get the
// oldpublic
// id
}
//===========GF32398====Insert/update/delete regstatus=======START
String sReturn = "";
if (dec.getDEC_REG_STATUS() != null
&& !dec.getDEC_REG_STATUS().equals("")) {
logger.debug("line 1141 of InsACSErvice.java registration value is "+dec.getDEC_REG_STATUS()+"************"); //JT
dec.setDEC_REG_STATUS_IDSEQ(this.getAC_REG(sDEC_ID));
if (dec.getDEC_REG_STATUS_IDSEQ() == null
|| dec.getDEC_REG_STATUS_IDSEQ().equals("")){
logger.info("line 1146 of InsACSErvice.java ************");
sReturn = this.setReg_Status("INS", "", sDEC_ID, dec
.getDEC_REG_STATUS());
}
else{
logger.info("line 1151 of InsACSErvice.java ************");
sReturn = this.setReg_Status("UPD", dec
.getDEC_REG_STATUS_IDSEQ(), sDEC_ID, dec
.getDEC_REG_STATUS());
}
if (sReturn != null && !sReturn.equals("")){
logger.info("line 1158 of InsACSErvice.java ************");
this.storeStatusMsg("\\t "
+ sReturn
+ " : Unable to update Registration Status.");
}
} else {
// delete if reg status is empty and idseq is not null
if (dec.getDEC_REG_STATUS_IDSEQ() != null
&& !dec.getDEC_REG_STATUS_IDSEQ().equals("")){
logger.info("line 1168 of InsACSErvice.java ************");
sReturn = this.setReg_Status("DEL", dec
.getDEC_REG_STATUS_IDSEQ(), sDEC_ID, dec
.getDEC_REG_STATUS());
}
if (sReturn != null && !sReturn.equals("")){
logger.info("line 1175 of InsACSErvice.java ************");
this
.storeStatusMsg("\\t "
+ sReturn
+ " : Unable to remove Registration Status.");
}
}
// store returncode in request to track it all through this
// request
if (sAction.equals("UPD") && sReturn != null
&& !sReturn.equals(""))
m_classReq.setAttribute("retcode", sReturn);
//===========GF32398====Insert/update/delete regstatusw=======END
// insert and delete ac-csi relationship
Vector<AC_CSI_Bean> vAC_CS = dec.getAC_AC_CSI_VECTOR();
GetACSearch getAC = new GetACSearch(m_classReq, m_classRes,
m_servlet);
Vector<AC_CSI_Bean> vRemove_ACCSI = getAC.doCSCSI_ACSearch(
sDEC_ID, ""); // (Vector)session.getAttribute("vAC_CSI");
Vector vACID = (Vector) session.getAttribute("vACId");
this.addRemoveACCSI(sDEC_ID, vAC_CS, vRemove_ACCSI, vACID,
sInsertFor, sLongName);
// store back altname and ref docs to session
m_servlet.doMarkACBeanForAltRef(m_classReq, m_classRes,
"DataElementConcept", "all", "submitAR");
// do alternate names create
if (sInsertFor.equalsIgnoreCase("Version"))
this.doAltVersionUpdate(sDEC_ID, oldDECID);
// ********************************
dec.save(session, m_servlet.getConn(), sDEC_ID, sContextID);
session.removeAttribute("AllAltNameList");
// ********************************
/*
* Vector<ALT_NAME_Bean> tBean =
* AltNamesDefsSession.getAltNameBeans(session,
* AltNamesDefsSession._searchDEC, sDEC_ID, sContextID); if
* (tBean != null) DataManager.setAttribute(session,
* "AllAltNameList", tBean);
*/
String oneAlt = this.doAddRemoveAltNames(sDEC_ID,
sContextID, sAction); // , "create");
dec.setALTERNATE_NAME(oneAlt);
// do reference docuemnts create
if (sInsertFor.equalsIgnoreCase("Version"))
this.doRefVersionUpdate(sDEC_ID, oldDECID);
String oneRD = this.doAddRemoveRefDocs(sDEC_ID, sContextID,
sAction); // "create");
dec.setREFERENCE_DOCUMENT(oneRD);
// do contact updates
Hashtable<String, AC_CONTACT_Bean> decConts = dec
.getAC_CONTACTS();
if (decConts != null && decConts.size() > 0)
dec.setAC_CONTACTS(this.addRemoveAC_Contacts(decConts,
sDEC_ID, sInsertFor));
// get one concept name for this dec
dec.setAC_CONCEPT_NAME(this.getOneConName(sDEC_ID, ""));
sReturn = (String) m_classReq.getAttribute("retcode");
if (sAction.equals("UPD")
&& (sReturn == null || sReturn.equals(""))) {
this
.storeStatusMsg("\\t Successfully updated Data Element Concept.");
//GF30681 update the CDR in dec table
// updateDECUniqueCDRName(this.getPublicID(sDEC_ID), (String)session.getAttribute(Constants.DEC_CDR_NAME));
}
}
}
this.storeStatusMsg("\\n");
// capture the duration
// logger.info(m_servlet.getLogMessage(m_classReq, "setDEC", "end
// set", startDate, new java.util.Date()));
} catch (Exception e) {
logger.error("ERROR in InsACService-setDEC for other : "
+ e.toString(), e);
m_classReq.setAttribute("retcode", "Exception");
this
.storeStatusMsg("\\t Exception : Unable to update Data Element Concept attributes.");
}
finally{
rs = SQLHelper.closeResultSet(rs);
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
return sReturnCode;
}
private DEC_Bean changeDECPrefName(DEC_Bean dec, DEC_Bean oldDEC,
String sInsFor, String sAction) throws Exception {
EVSSearch evs = new EVSSearch(m_classReq, m_classRes, m_servlet);
String sName = dec.getDEC_PREFERRED_NAME();
if (sName == null)
sName = "";
String sNameType = dec.getAC_PREF_NAME_TYPE();
if (sNameType == null)
sNameType = "";
String oldAslName = oldDEC.getDEC_ASL_NAME();
if (oldAslName == null)
oldAslName = "";
// display messge if released dec
if (oldAslName.equals("RELEASED") && sInsFor.equals("BlockEdit")
&& !sNameType.equals("") && !sNameType.equals("USER")) {
this
.storeStatusMsg("\\t Short Name of the RELEASED Data Element Concept cannot be changed.");
return dec;
}
// get teh right sys name
String curType = "existing";
if (sNameType.equals("SYS")) {
curType = "system generated";
String sysName = this.getDECSysName(dec);
if (sysName == null)
sysName = "";
dec.setAC_SYS_PREF_NAME(sysName);
dec.setDEC_PREFERRED_NAME(sysName);
}
// abbreviated type
if (sNameType.equals("ABBR")) {
curType = "abbreviated";
// get abbr name for block edit or version
if (sInsFor.equals("BlockEdit")
|| (sAction.equals("UPD") && sInsFor.equals("Version"))) {
// GetACSearch serAC = new GetACSearch(m_classReq, m_classRes,
// m_servlet);
if (dec.getDEC_OC_CONDR_IDSEQ() != null
&& !dec.getDEC_OC_CONDR_IDSEQ().equals(""))
evs
.fillOCVectors(dec.getDEC_OC_CONDR_IDSEQ(), dec,
sAction);
if (dec.getDEC_PROP_CONDR_IDSEQ() != null
&& !dec.getDEC_PROP_CONDR_IDSEQ().equals(""))
evs.fillPropVectors(dec.getDEC_PROP_CONDR_IDSEQ(), dec,
sAction);
EVS_Bean nullEVS = null;
dec = (DEC_Bean) m_servlet.getACNames(nullEVS, "SubmitDEC", dec);
dec.setDEC_PREFERRED_NAME(dec.getAC_ABBR_PREF_NAME());
}
}
SetACService setAC = new SetACService(m_servlet);
GetACService getAC = new GetACService(m_classReq, m_classRes, m_servlet);
String sDECAction = "create";
if (sAction.equals("UPD"))
sDECAction = "Edit";
String sValid = setAC.checkUniqueInContext("Name", "DEC", null, dec,
null, getAC, sDECAction);
if (sValid != null && !sValid.equals("")) {
if (sAction.equals("UPD"))
sDECAction = "update";
String sMsg = "\\tUnable to " + sDECAction
+ " this Data Element Concept because the " + curType
+ "\\n\\t" + "Short Name " + dec.getDEC_PREFERRED_NAME()
+ " already exists in the database for this "
+ "Context and Version.";
// add moreMsg and return with error for create new dec
if (!sAction.equals("UPD")) {
String sMoreMsg = "\\n\\tClick OK to return to the Data Element Concept screen "
+ "to " + sDECAction + " a unique Short Name.";
this.storeStatusMsg(sMsg + sMoreMsg);
// return "Unique Constraint";
return null;
} else // reset pref name back to earlier name and continue with
// other submissions for upd dec
{
dec.setDEC_PREFERRED_NAME(sName); // back to the old name
this.storeStatusMsg(sMsg);
}
}
return dec;
}
/**
* to add or remove cs-csi relationship for the selected AC. Called from
* setDE, setVD, setDEC.
*
* @param ac_id
* string ac_idseq.
* @param vAC_CS
* vector of cs csi contained in the selected ac.
* @param vRemove_ACCSI
* vector of selected ac-csi.
* @param vACID
* @param acAction
* @param acName
* @throws Exception
*
*/
public void addRemoveACCSI(String ac_id, Vector<AC_CSI_Bean> vAC_CS,
Vector<AC_CSI_Bean> vRemove_ACCSI, Vector vACID, String acAction,
String acName) throws Exception {
Vector<String> vExistACCSI = new Vector<String>();
Vector<String> vExistCSCSI = new Vector<String>();
if (vAC_CS != null) // accsi list from the page for the selected cs-csi
// includes new or existing ones
{
for (int i = 0; i < vAC_CS.size(); i++) {
AC_CSI_Bean acCSI = (AC_CSI_Bean) vAC_CS.elementAt(i);
CSI_Bean csiBean = (CSI_Bean) acCSI.getCSI_BEAN();
// insert this relationship if it does not exist already
String accsiID = acCSI.getAC_CSI_IDSEQ();
String accsiName = csiBean.getCSI_NAME(); // acCSI.getCSI_NAME();
vExistCSCSI.addElement(csiBean.getCSI_CSCSI_IDSEQ());
// vExistCSCSI.addElement(acCSI.getCSCSI_IDSEQ());
if ((acName == null || acName.equals("") || acName
.equals("null"))
&& acCSI.getAC_IDSEQ().equals(ac_id))
acName = acCSI.getAC_LONG_NAME();
if (acCSI.getAC_CSI_IDSEQ() == null
|| acCSI.getAC_CSI_IDSEQ().equals("") || acCSI.getAC_CSI_IDSEQ().equals("undefined"))
accsiID = setACCSI(csiBean.getCSI_CSCSI_IDSEQ(), "INS",
ac_id, "", acName, accsiName);
// insert it if ac of the old one doesn't match new ac
else if (vACID != null && !vACID.contains(ac_id)
&& !acAction.equals("Version")) {
accsiID = setACCSI(csiBean.getCSI_CSCSI_IDSEQ(), "INS",
ac_id, "", acName, accsiName);
vExistACCSI.addElement(accsiID); // add this to not to
// remove
} else
vExistACCSI.addElement(accsiID); // add to the vector to
// use at remove
}
}
// remove ac-csi relationship
if (vRemove_ACCSI != null) // list from origial search does not include
// new ones
{
for (int j = 0; j < vRemove_ACCSI.size(); j++) {
AC_CSI_Bean acCSI = (AC_CSI_Bean) vRemove_ACCSI.elementAt(j);
CSI_Bean csiBean = (CSI_Bean) acCSI.getCSI_BEAN();
String accsiName = csiBean.getCSI_NAME(); // acCSI.getCSI_NAME();
// delete this relationship if it does not contain in the
// insert/update vector (vAC_CS)
// if ac is not same as this one and it doesn't exist in
// ExistACCCI (retained from the page)
if (acCSI.getAC_CSI_IDSEQ() != null
&& acCSI.getAC_IDSEQ().equals(ac_id)
&& (vExistACCSI == null || !vExistACCSI.contains(acCSI
.getAC_CSI_IDSEQ()))) {
if (vExistCSCSI == null
|| !vExistCSCSI.contains(csiBean
.getCSI_CSCSI_IDSEQ())) {
setACCSI(csiBean.getCSI_CSCSI_IDSEQ(), "DEL", ac_id,
acCSI.getAC_CSI_IDSEQ(), acName, accsiName);
}
}
}
}
} // end addRemoveCSCSI
/**
*
* @param sCondrString
* string condr idseq
*
* @return sCondrString
*/
public String prepCondrStringForSubmit(String sCondrString) {
if (sCondrString.length() < 1)
return "";
int index = -1;
String sComma = ",";
Vector<String> vTokens = new Vector<String>();
String sCondrStringSecondary = "";
String sNewSecondaryString = "";
String sPrimary = "";
index = sCondrString.indexOf(sComma);
if (index > -1) {
sPrimary = sCondrString.substring(0, index);
sCondrStringSecondary = sCondrString.substring(index, sCondrString
.length());
sCondrString = sPrimary;
if ((sCondrStringSecondary != null)
&& (!sCondrStringSecondary.equals(""))) {
StringTokenizer desTokens = new StringTokenizer(
sCondrStringSecondary, ",");
while (desTokens.hasMoreTokens()) {
String thisToken = desTokens.nextToken().trim();
if (thisToken != null && !thisToken.equals("")) {
vTokens.addElement(thisToken);
}
}
for (int i = (vTokens.size() - 1); i > -1; i--) {
sNewSecondaryString = (String) vTokens.elementAt(i);
sCondrString = sCondrString + "," + sNewSecondaryString;
}
}
}
return sCondrString;
}
/**
* To insert a Object Class or update the existing one in the database after
* the validation. Called from CurationServlet. Gets all the attribute
* values from the bean, sets in parameters, and registers output parameter.
* Calls oracle stored procedure "{call
* SBREXT_Set_Row.SET_OBJECT_CLASS(?,?,?,?,?,?)}" to submit
*
* @param sAction
* Insert or update Action.
* @param dec
* DEC Bean.
* @param req
* HttpServletRequest Object.
*
* @return DEC_Bean return bean updated with change attributes.
*/
public DEC_Bean setObjectClassDEC(String sAction, DEC_Bean dec,
HttpServletRequest req) {
HttpSession session = m_classReq.getSession();
ResultSet rs = null;
CallableStatement cstmt = null;
String sReturnCode = "";
String sOCL_IDSEQ = "";
try {
// String sOCLName = "";
String sContextID = "";
if (dec != null) {
sContextID = dec.getDEC_CONTE_IDSEQ();
if (sContextID == null)
sContextID = "";
}
// create concepts and pass them in comma-delimited format
Vector vObjectClass = (Vector) session.getAttribute("vObjectClass");
if (vObjectClass == null)
vObjectClass = new Vector();
String sOCCondr = "";
String sOCCondrString = "";
for (int m = 1; m < vObjectClass.size(); m++) {
EVS_Bean OCBean = (EVS_Bean) vObjectClass.elementAt(m);
if (OCBean.getCON_AC_SUBMIT_ACTION() == null)
OCBean.setCON_AC_SUBMIT_ACTION("");
// if not deleted, create and append them one by one
if (OCBean != null) {
if (!OCBean.getCON_AC_SUBMIT_ACTION().equals("DEL")) {
String sRet = "";
String conIDseq = OCBean.getIDSEQ();
// create it only if doesn't exist
if (conIDseq == null || conIDseq.equals(""))
conIDseq = this.setConcept("INS", sRet, OCBean);
if (conIDseq != null && !conIDseq.equals("")) {
// add the concept value to the conidseq
String nvp = OCBean.getNVP_CONCEPT_VALUE();
if (nvp != null && !nvp.equals(""))
conIDseq += ":" + nvp;
if (sOCCondrString.equals(""))
sOCCondrString = conIDseq;
else
sOCCondrString = sOCCondrString + ","
+ conIDseq;
}
} else if (sOCCondr == null)
sOCCondr = OCBean.getCONDR_IDSEQ();
}
}
// Primary
EVS_Bean OCBean = new EVS_Bean();
if (vObjectClass.size() > 0)
OCBean = (EVS_Bean) vObjectClass.elementAt(0);
if (OCBean != null && OCBean.getLONG_NAME() != null) {
if (sContextID == null || sContextID.equals(""))
sContextID = OCBean.getCONTE_IDSEQ();
if (sContextID == null)
sContextID = "";
if (OCBean.getCON_AC_SUBMIT_ACTION() == null)
OCBean.setCON_AC_SUBMIT_ACTION("");
if (!OCBean.getCON_AC_SUBMIT_ACTION().equals("DEL")) {
String sRet = "";
String conIDseq = OCBean.getIDSEQ();
// create it only if doesn't exist
if (conIDseq == null || conIDseq.equals(""))
conIDseq = this.setConcept("INS", sRet, OCBean);
if (conIDseq != null && !conIDseq.equals("")) {
if (sOCCondrString.equals(""))
sOCCondrString = conIDseq;
else
sOCCondrString = sOCCondrString + "," + conIDseq;
}
}
}
if (sOCCondr == null)
sOCCondr = "";
if (sContextID == null)
sContextID = "";
if (!sOCCondrString.equals("")) {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
// cstmt = conn.prepareCall("{call
// SBREXT_Set_Row.SET_OC_CONDR(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}");
cstmt = m_servlet
.getConn()
.prepareCall(
"{call SBREXT_SET_ROW.SET_OC_CONDR(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}");
// cstmt.registerOutParameter(1, java.sql.Types.VARCHAR); //
// ua_name
cstmt.registerOutParameter(4, java.sql.Types.VARCHAR); // return
// code
cstmt.registerOutParameter(5, java.sql.Types.VARCHAR); // OCL
// IDSEQ
cstmt.registerOutParameter(6, java.sql.Types.VARCHAR); // preferred_name
cstmt.registerOutParameter(7, java.sql.Types.VARCHAR); // long_name
cstmt.registerOutParameter(8, java.sql.Types.VARCHAR); // preferred_definition
cstmt.registerOutParameter(9, java.sql.Types.VARCHAR); // version
cstmt.registerOutParameter(10, java.sql.Types.VARCHAR); // asl_name
cstmt.registerOutParameter(11, java.sql.Types.VARCHAR); // latest_version_ind
cstmt.registerOutParameter(12, java.sql.Types.VARCHAR); // change_note
cstmt.registerOutParameter(13, java.sql.Types.VARCHAR); // origin
cstmt.registerOutParameter(14, java.sql.Types.VARCHAR); // definition_source
cstmt.registerOutParameter(15, java.sql.Types.VARCHAR); // begin_date
cstmt.registerOutParameter(16, java.sql.Types.VARCHAR); // end_date
cstmt.registerOutParameter(17, java.sql.Types.VARCHAR); // date_created
cstmt.registerOutParameter(18, java.sql.Types.VARCHAR); // created_by
cstmt.registerOutParameter(19, java.sql.Types.VARCHAR); // date_modified
cstmt.registerOutParameter(20, java.sql.Types.VARCHAR); // modified_by
cstmt.registerOutParameter(21, java.sql.Types.VARCHAR); // deleted_ind
cstmt.registerOutParameter(22, java.sql.Types.VARCHAR); // oc_condr_idseq
cstmt.registerOutParameter(23, java.sql.Types.VARCHAR); // oc_id
//System.out.println(OCBean.getLONG_NAME()
//+ " oc submit ready " + sOCCondrString);
// Set the In parameters (which are inherited from the
// PreparedStatement class)
// Get the username from the session.
String userName = (String) session.getAttribute("Username");
cstmt.setString(1, userName); // set ua_name
cstmt.setString(2, sOCCondrString); // comma-delimited con
// idseqs
cstmt.setString(3, sContextID);
cstmt.execute();
sReturnCode = cstmt.getString(4);
sOCL_IDSEQ = cstmt.getString(5);
if (sOCL_IDSEQ == null)
sOCL_IDSEQ = "";
String sOCL_CONDR_IDSEQ = cstmt.getString(22);
if (sOCL_CONDR_IDSEQ == null)
sOCL_CONDR_IDSEQ = "";
// DataManager.setAttribute(session, "newObjectClass", "");
// store the idseq in the bean
if (dec != null
&& (sReturnCode == null || sReturnCode.equals("") || sReturnCode
.equals("API_OC_500"))) {
dec.setDEC_OCL_IDSEQ(sOCL_IDSEQ);
dec.setDEC_OC_CONDR_IDSEQ(sOCL_CONDR_IDSEQ);
dec.setDEC_OBJ_ASL_NAME(cstmt.getString(10));
req.setAttribute("OCL_IDSEQ", sOCL_IDSEQ);
}
if (sReturnCode != null && !sReturnCode.equals("")) // &&
// !sReturnCode.equals("API_OC_500"))
{
sReturnCode = sReturnCode.replaceAll("\\n", " ");
sReturnCode = sReturnCode.replaceAll("\\t", " ");
sReturnCode = sReturnCode.replaceAll("\"", "");
this.storeStatusMsg(sReturnCode
+ " : Unable to create Object Class ");
m_classReq.setAttribute("retcode", sReturnCode);
dec.setDEC_OCL_IDSEQ("");
}
}
}
} catch (Exception e) {
logger.error("ERROR in InsACService-setObjectClassDEC for other : "
+ e.toString(), e);
m_classReq.setAttribute("retcode", "Exception");
this
.storeStatusMsg("Exception Error : Unable to create Object Class.");
}finally{
rs = SQLHelper.closeResultSet(rs);
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
return dec;
}
/**
* To insert a Property Class or update the existing one in the database
* after the validation. Called from CurationServlet. Gets all the attribute
* values from the bean, sets in parameters, and registers output parameter.
* Calls oracle stored procedure "{call
* SBREXT_Set_Row.SET_PROP_CONDR(?,?,?,?,?,?)}" to submit
*
* @param sAction
* Insert or update Action.
* @param dec
* DEC Bean.
* @param req
* HttpServletRequest Object.
*
* @return DEC_Bean return bean updated with change attributes.
*/
public DEC_Bean setPropertyDEC(String sAction, DEC_Bean dec,
HttpServletRequest req) {
// capture the duration
// java.util.Date startDate = new java.util.Date();
// logger.info(m_servlet.getLogMessage(m_classReq, "setPropertyDEC",
// "starting set", startDate, startDate));
HttpSession session = req.getSession();
// Connection conn = null;
ResultSet rs = null;
CallableStatement cstmt = null;
String sReturnCode = "";
String sPROPL_IDSEQ = "";
try {
String sContextID = ""; //
if (dec != null)
sContextID = dec.getDEC_CONTE_IDSEQ();
if (sContextID == null)
sContextID = "";
// create concepts and pass them in comma-delimited format
Vector vProperty = (Vector) session.getAttribute("vProperty");
if (vProperty == null)
vProperty = new Vector();
String sPCCondr = "";
String sPCCondrString = "";
for (int m = 1; m < vProperty.size(); m++) {
EVS_Bean PCBean = (EVS_Bean) vProperty.elementAt(m);
if (PCBean.getCON_AC_SUBMIT_ACTION() == null)
PCBean.setCON_AC_SUBMIT_ACTION("");
// if not deleted, create and append them one by one
if (PCBean != null) {
if (!PCBean.getCON_AC_SUBMIT_ACTION().equals("DEL")) {
String sRet = "";
String conIDseq = PCBean.getIDSEQ();
// create it only if doesn't exist
if (conIDseq == null || conIDseq.equals(""))
conIDseq = this.setConcept("INS", sRet, PCBean);
if (conIDseq != null && !conIDseq.equals("")) {
// add the concept value to the conidseq
String nvp = PCBean.getNVP_CONCEPT_VALUE();
if (nvp != null && !nvp.equals(""))
conIDseq += ":" + nvp;
if (sPCCondrString.equals(""))
sPCCondrString = conIDseq;
else
sPCCondrString = sPCCondrString + ","
+ conIDseq;
}
} else if (sPCCondr == null)
sPCCondr = PCBean.getCONDR_IDSEQ();
}
}
// Primary
EVS_Bean PCBean = new EVS_Bean();
if (vProperty.size() > 0)
PCBean = (EVS_Bean) vProperty.elementAt(0);
if (PCBean != null && PCBean.getLONG_NAME() != null) {
if (sContextID == null || sContextID.equals(""))
sContextID = PCBean.getCONTE_IDSEQ();
if (sContextID == null)
sContextID = "";
if (PCBean.getCON_AC_SUBMIT_ACTION() == null)
PCBean.setCON_AC_SUBMIT_ACTION("");
if (!PCBean.getCON_AC_SUBMIT_ACTION().equals("DEL")) {
String sRet = "";
String conIDseq = PCBean.getIDSEQ();
// create it only if doesn't exist
if (conIDseq == null || conIDseq.equals(""))
conIDseq = this.setConcept("INS", sRet, PCBean);
if (conIDseq != null && !conIDseq.equals("")) {
if (sPCCondrString.equals(""))
sPCCondrString = conIDseq;
else
sPCCondrString = sPCCondrString + "," + conIDseq;
}
}
}
if (sPCCondr == null)
sPCCondr = "";
if (sContextID == null)
sContextID = "";
if (!sPCCondrString.equals("")) {
// conn = m_servlet.connectDB(m_classReq, m_classRes);
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
// cstmt = conn.prepareCall("{call
// SBREXT_Set_Row.SET_PROP_CONDR(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}");
cstmt = m_servlet
.getConn()
.prepareCall(
"{call SBREXT_SET_ROW.SET_PROP_CONDR(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}");
// cstmt.registerOutParameter(1, java.sql.Types.VARCHAR); //
// ua_name
cstmt.registerOutParameter(4, java.sql.Types.VARCHAR); // return
// code
cstmt.registerOutParameter(5, java.sql.Types.VARCHAR); // PROP_IDSEQ
cstmt.registerOutParameter(6, java.sql.Types.VARCHAR); // preferred_name
cstmt.registerOutParameter(7, java.sql.Types.VARCHAR); // long_name
cstmt.registerOutParameter(8, java.sql.Types.VARCHAR); // preferred_definition
cstmt.registerOutParameter(9, java.sql.Types.VARCHAR); // version
cstmt.registerOutParameter(10, java.sql.Types.VARCHAR); // asl_name
cstmt.registerOutParameter(11, java.sql.Types.VARCHAR); // latest_version_ind
cstmt.registerOutParameter(12, java.sql.Types.VARCHAR); // change_note
cstmt.registerOutParameter(13, java.sql.Types.VARCHAR); // origin
cstmt.registerOutParameter(14, java.sql.Types.VARCHAR); // definition_source
cstmt.registerOutParameter(15, java.sql.Types.VARCHAR); // begin_date
cstmt.registerOutParameter(16, java.sql.Types.VARCHAR); // end_date
cstmt.registerOutParameter(17, java.sql.Types.VARCHAR); // date_created
cstmt.registerOutParameter(18, java.sql.Types.VARCHAR); // created_by
cstmt.registerOutParameter(19, java.sql.Types.VARCHAR); // date_modified
cstmt.registerOutParameter(20, java.sql.Types.VARCHAR); // modified_by
cstmt.registerOutParameter(21, java.sql.Types.VARCHAR); // deleted_ind
cstmt.registerOutParameter(22, java.sql.Types.VARCHAR); // prop_condr_idseq
cstmt.registerOutParameter(23, java.sql.Types.VARCHAR); // prop_id
// Set the In parameters (which are inherited from the
// PreparedStatement class)
// Get the username from the session.
String userName = (String) session.getAttribute("Username");
cstmt.setString(1, userName); // set ua_name
cstmt.setString(2, sPCCondrString); // comma-delimited con
// idseqs
cstmt.setString(3, sContextID);
// Now we are ready to call the stored procedure
cstmt.execute();
sReturnCode = cstmt.getString(4);
sPROPL_IDSEQ = cstmt.getString(5);
if (sPROPL_IDSEQ == null)
sPROPL_IDSEQ = "";
String sPROPL_CONDR_IDSEQ = cstmt.getString(22);
if (sPROPL_CONDR_IDSEQ == null)
sPROPL_CONDR_IDSEQ = "";
if (dec != null
&& (sReturnCode == null || sReturnCode.equals("") || sReturnCode
.equals("API_PROP_500"))) {
dec.setDEC_PROPL_IDSEQ(sPROPL_IDSEQ);
dec.setDEC_PROP_CONDR_IDSEQ(sPROPL_CONDR_IDSEQ);
dec.setDEC_PROP_ASL_NAME(cstmt.getString(10));
req.setAttribute("PROPL_IDSEQ", sPROPL_IDSEQ);
}
// DataManager.setAttribute(session, "newProperty", "");
if (sReturnCode != null && !sReturnCode.equals("")) // &&
// !sReturnCode.equals("API_PROP_500"))
{
this.storeStatusMsg(sReturnCode
+ " : Unable to create Property ");
m_classReq.setAttribute("retcode", sReturnCode);
dec.setDEC_PROPL_IDSEQ("");
}
}
}
} catch (Exception e) {
logger.error(
"ERROR in InsACService-setPropertyClassDEC for other : "
+ e.toString(), e);
m_classReq.setAttribute("retcode", "Exception");
this.storeStatusMsg("Exception Error : Unable to create Property.");
}finally{
rs = SQLHelper.closeResultSet(rs);
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
return dec;
}
/**
* To insert a Representation Term or update the existing one in the
* database after the validation. Called from CurationServlet. Gets all the
* attribute values from the bean, sets in parameters, and registers output
* parameter. Calls oracle stored procedure "{call
* SBREXT_Set_Row.SET_representation(?,?,?,?,?,?)}" to submit
*
* @param sAction
* Insert or update Action.
* @param sREP_IDSEQ
* string rep idseq
* @param VD
* VD Bean.
* @param rep
* rep bean
* @param req
* HttpServletRequest Object.
*
* @return String return code from the stored procedure call. null if no
* error occurred.
*/
public String setRepresentation(String sAction, String sREP_IDSEQ, // out
VD_Bean VD, EVS_Bean rep, HttpServletRequest req) {
HttpSession session = m_classReq.getSession();
ResultSet rs = null;
CallableStatement cstmt = null;
String sReturnCode = "";
try {
String sREPName = "";
String sContextID = "";
if (VD != null) {
sContextID = VD.getVD_CONTE_IDSEQ();
if (sContextID == null)
sContextID = "";
}
// get the existing property if alreay there
// create concepts and pass them in comma-delimited format
Vector vRepTerm = (Vector) session.getAttribute("vRepTerm");
if (vRepTerm == null)
vRepTerm = new Vector();
String sOCCondr = "";
String sOCCondrString = "";
for (int m = 1; m < vRepTerm.size(); m++) {
EVS_Bean REPBean = (EVS_Bean) vRepTerm.elementAt(m);
if (REPBean.getCON_AC_SUBMIT_ACTION() == null)
REPBean.setCON_AC_SUBMIT_ACTION("");
// if not deleted, create and append them one by one
if (REPBean != null) {
if (!REPBean.getCON_AC_SUBMIT_ACTION().equals("DEL")) {
String sRet = "";
String conIDseq = REPBean.getIDSEQ();
// create it only if doesn't exist
if (conIDseq == null || conIDseq.equals(""))
conIDseq = this.setConcept("INS", sRet, REPBean);
if (conIDseq != null && !conIDseq.equals("")) {
// add the concept value to the conidseq
String nvp = REPBean.getNVP_CONCEPT_VALUE();
if (nvp != null && !nvp.equals(""))
conIDseq += ":" + nvp;
if (sOCCondrString.equals(""))
sOCCondrString = conIDseq;
else
sOCCondrString = sOCCondrString + ","
+ conIDseq;
}
} else if (sOCCondr == null)
sOCCondr = REPBean.getCONDR_IDSEQ();
}
}
// Primary
EVS_Bean REPBean = (EVS_Bean) vRepTerm.elementAt(0);
if (REPBean != null && REPBean.getLONG_NAME() != null) {
if (sContextID == null || sContextID.equals(""))
sContextID = REPBean.getCONTE_IDSEQ();
if (sContextID == null)
sContextID = "";
if (REPBean.getCON_AC_SUBMIT_ACTION() == null)
REPBean.setCON_AC_SUBMIT_ACTION("");
if (!REPBean.getCON_AC_SUBMIT_ACTION().equals("DEL")) {
String sRet = "";
String conIDseq = REPBean.getIDSEQ();
// create it only if doesn't exist
if (conIDseq == null || conIDseq.equals(""))
conIDseq = this.setConcept("INS", sRet, REPBean);
if (conIDseq != null && !conIDseq.equals("")) {
if (sOCCondrString.equals(""))
sOCCondrString = conIDseq;
else
sOCCondrString = sOCCondrString + "," + conIDseq;
}
}
}
if (sOCCondr == null)
sOCCondr = "";
// if (!sContextID.equals("") && !sOCCondrString.equals(""))
if (!sOCCondrString.equals("")) {
if (sREPName != null || !sREPName.equals("")) {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
// cstmt = conn.prepareCall("{call
// SBREXT_Set_Row.SET_REP_CONDR(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}");
cstmt = m_servlet
.getConn()
.prepareCall(
"{call SBREXT_SET_ROW.SET_REP_CONDR(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}");
cstmt.registerOutParameter(4, java.sql.Types.VARCHAR); // return
// code
cstmt.registerOutParameter(5, java.sql.Types.VARCHAR); // OCL
// IDSEQ
cstmt.registerOutParameter(6, java.sql.Types.VARCHAR); // preferred_name
cstmt.registerOutParameter(7, java.sql.Types.VARCHAR); // long_name
cstmt.registerOutParameter(8, java.sql.Types.VARCHAR); // preferred_definition
cstmt.registerOutParameter(9, java.sql.Types.VARCHAR); // version
cstmt.registerOutParameter(10, java.sql.Types.VARCHAR); // asl_name
cstmt.registerOutParameter(11, java.sql.Types.VARCHAR); // latest_version_ind
cstmt.registerOutParameter(12, java.sql.Types.VARCHAR); // change_note
cstmt.registerOutParameter(13, java.sql.Types.VARCHAR); // origin
cstmt.registerOutParameter(14, java.sql.Types.VARCHAR); // definition_source
cstmt.registerOutParameter(15, java.sql.Types.VARCHAR); // begin_date
cstmt.registerOutParameter(16, java.sql.Types.VARCHAR); // end_date
cstmt.registerOutParameter(17, java.sql.Types.VARCHAR); // date_created
cstmt.registerOutParameter(18, java.sql.Types.VARCHAR); // created_by
cstmt.registerOutParameter(19, java.sql.Types.VARCHAR); // date_modified
cstmt.registerOutParameter(20, java.sql.Types.VARCHAR); // modified_by
cstmt.registerOutParameter(21, java.sql.Types.VARCHAR); // deleted_ind
cstmt.registerOutParameter(22, java.sql.Types.VARCHAR); // rep_condr_idseq
cstmt.registerOutParameter(23, java.sql.Types.VARCHAR); // rep_id
// Set the In parameters (which are inherited from the
// PreparedStatement class)
// Get the username from the session.
String userName = (String) session
.getAttribute("Username");
cstmt.setString(1, userName); // set ua_name
cstmt.setString(2, sOCCondrString); // comma-delimited
// con idseqs
cstmt.setString(3, sContextID);
cstmt.execute();
sReturnCode = cstmt.getString(4);
sREP_IDSEQ = cstmt.getString(5);
if (sREP_IDSEQ == null)
sREP_IDSEQ = "";
sREP_IDSEQ = sREP_IDSEQ.trim();
String sREP_CONDR_IDSEQ = cstmt.getString(22);
if (sREP_CONDR_IDSEQ == null)
sREP_CONDR_IDSEQ = "";
DataManager.setAttribute(session, "newRepTerm", "");
if (VD != null
&& (sReturnCode == null
|| sReturnCode.equals("") || sReturnCode
.equals("API_REP_500"))) {
VD.setVD_REP_IDSEQ(sREP_IDSEQ);
VD.setVD_REP_CONDR_IDSEQ(sREP_CONDR_IDSEQ);
VD.setVD_REP_ASL_NAME(cstmt.getString(10));
req.setAttribute("REP_IDSEQ", sREP_IDSEQ);
}
if (sReturnCode != null && !sReturnCode.equals("")
&& !sReturnCode.equals("API_REP_500")) {
this.storeStatusMsg("\\t " + sReturnCode
+ " : Unable to update Rep Term.");
m_classReq.setAttribute("retcode", sReturnCode);
VD.setVD_REP_IDSEQ("");
}
}
}
}
} catch (Exception e) {
logger.error("ERROR in InsACService-setRepresentation for other : "
+ e.toString(), e);
m_classReq.setAttribute("retcode", "Exception");
this
.storeStatusMsg("\\t Exception : Unable to update or remove Representation Term.");
}finally{
rs = SQLHelper.closeResultSet(rs);
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
return sReturnCode;
}
/**
* To check whether data is unique value in the database for the selected
* component, called from setValidatePageValuesDE, setValidatePageValuesDEC,
* setValidatePageValuesVD methods. Creates the sql queries for the selected
* field, to check if the value exists in the database. Calls
* 'getAC.doComponentExist' to execute the query.
*
* @param mDEC
* Data Element Concept Bean.
* @param editAct
* string edit action
* @param setAction
* string set action
*
* @return String retValue message if exists already. Otherwise empty
* string.
*/
public String checkUniqueOCPropPair(DEC_Bean mDEC, String editAct,
String setAction) {
ResultSet rs = null;
PreparedStatement pstmt = null;
String uniqueMsg = "";
try {
HttpSession session = m_classReq.getSession();
String menuAction = (String) session
.getAttribute(Session_Data.SESSION_MENU_ACTION);
String sContID = mDEC.getDEC_CONTE_IDSEQ();
String sPublicID = ""; // mDEC.getDEC_DEC_ID();
String sOCID = mDEC.getDEC_OCL_IDSEQ();
if (sOCID == null)
sOCID = "";
String sPropID = mDEC.getDEC_PROPL_IDSEQ();
if (sPropID == null)
sPropID = "";
// String sOCasl = mDEC.getDEC_OBJ_ASL_NAME();
// String sPROPasl = mDEC.getDEC_PROP_ASL_NAME();
String sReturnID = "";
if (setAction.equalsIgnoreCase("EditDEC")
|| setAction.equalsIgnoreCase("editDECfromDE")
|| menuAction.equals("NewDECVersion"))
sPublicID = mDEC.getDEC_DEC_ID();
logger.debug("At Line 1987 of InsACService.java,OC ID"+sOCID+"Prop ID"+sPropID+"Context Id"+sContID+"DEC Public Id"+sPublicID);
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
pstmt = m_servlet
.getConn()
.prepareStatement(
"Select Sbrext_Common_Routines.get_dec_conte(?,?,?,?) from DUAL");
pstmt.setString(1, sOCID); // oc id
pstmt.setString(2, sPropID); // prop id
pstmt.setString(3, sContID); // dec context
pstmt.setString(4, sPublicID); // dec pubilic id
rs = pstmt.executeQuery(); // call teh query
while (rs.next())
sReturnID = rs.getString(1);
rs = SQLHelper.closeResultSet(rs);
pstmt = SQLHelper.closePreparedStatement(pstmt);
// oc-prop-context is not unique
if (sReturnID != null && !sReturnID.equals("")) //GF30681
uniqueMsg = "Warning:Combination of Object Class, Property and Context already exists in DEC with Public ID(s): "
+ sReturnID + "<br>"; //GF30681---- Added "Warning" to message to enable submit button.
else // check if it exists in other contexts
{
pstmt = m_servlet
.getConn()
.prepareStatement(
"Select Sbrext_Common_Routines.get_dec_list(?,?,?) from DUAL");
pstmt.setString(1, sOCID); // oc id
pstmt.setString(2, sPropID); // prop id
pstmt.setString(3, sPublicID); // dec pubilic id
rs = pstmt.executeQuery(); // call teh query
while (rs.next())
sReturnID = rs.getString(1);
// oc-prop is not unique in other contexts
if (sReturnID != null && !sReturnID.equals(""))
uniqueMsg = "Warning:DEC's with combination of Object Class and Property already exists in other contexts with Public ID(s): "
+ sReturnID + "<br>";
}
}
} catch (Exception e) {
logger.error(
"ERROR in InsACService-checkUniqueOCPropPair for exception : "
+ e.toString(), e);
}finally{
rs = SQLHelper.closeResultSet(rs);
pstmt = SQLHelper.closePreparedStatement(pstmt);
}
return uniqueMsg;
}
public String checkDECUniqueCDRName(String cdr) {
//boolean retVal = false;
String retVal = "";
ResultSet rs = null;
PreparedStatement pstmt = null;
try {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
pstmt = m_servlet
.getConn()
.prepareStatement(
"select long_name, CDR_NAME, date_created, dec_id from sbr.data_element_concepts_view where "
+ " CDR_NAME = ?"
+ " order by date_created desc");
pstmt.setString(1, cdr);
rs = pstmt.executeQuery();
String sReturnID = "";
String sCdrReturn = "";
while (rs.next()) {
sReturnID = rs.getString("dec_id");
sCdrReturn = rs.getString("CDR_NAME");
sCdrReturn = sCdrReturn.substring(1, sCdrReturn.length());
retVal = "\\t Existing dec public id " + sReturnID
+ " already exists in the data base.\\n";
m_classReq.setAttribute("retcode", "Exception");
this.storeStatusMsg("\\t Exception : Unable to create Data Element Concept. " + retVal);
logger.debug(retVal);
// oc-prop is not unique in existing DEC
//retVal = true;
break; //in theory, according to the requirement, there should not be more than one dec!
}
}
} catch (Exception e) {
logger.error(
"ERROR in InsACService-checkUniqueOCPropPair for exception : "
+ e.toString(), e);
}finally{
rs = SQLHelper.closeResultSet(rs);
pstmt = SQLHelper.closePreparedStatement(pstmt);
}
return retVal;
}
/*
public int updateDECUniqueCDRName(String decId, String cdr) {
ResultSet rs = null;
PreparedStatement pstmt = null;
int count = -1;
try {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
pstmt = m_servlet.getConn().prepareStatement("update sbr.data_element_concepts set CDR_NAME = ? where dec_id = ?");
pstmt.setString(1, cdr); // cdr name of the DEC
pstmt.setString(2, decId);
count = pstmt.executeUpdate();
m_servlet.getConn().commit();
logger.debug("DEC [" + decId + "] cdr updated with [" + cdr + "] done.");
if(count == 0) {
throw new Exception("Not able to update CDR of DEC with public id [" + decId + "]");
}
}
} catch (Exception e) {
logger.error(
"ERROR in InsACService-checkUniqueOCPropPair for exception : "
+ e.toString(), e);
System.out.println("updateDECUniqueCDRName: Error = [" + e + "]");
}finally{
rs = SQLHelper.closeResultSet(rs);
pstmt = SQLHelper.closePreparedStatement(pstmt);
}
return count;
}
*/
/**
* to created object class, property and qualifier value from EVS into cadsr. Retrieves the session bean m_DEC.
* calls 'insAC.setDECQualifier' to insert the database.
*
* @param m_classReq
* The HttpServletRequest from the client
* @param m_classRes
* The HttpServletResponse back to the client
* @param DECBeanSR
* dec attribute bean.
*
* @return DEC_Bean return the bean with the changed attributes
* @throws Exception
*/
public DEC_Bean doInsertDECBlocks(DEC_Bean DECBeanSR)
throws Exception
{
// logger.debug("doInsertDECBlocks");
HttpSession session = m_classReq.getSession();
//InsACService insAC = new InsACService(m_classReq, m_classRes, this);
String sNewOC = (String) session.getAttribute("newObjectClass");
String sNewProp = (String) session.getAttribute("newProperty");
if (sNewOC == null)
sNewOC = "";
if (sNewProp == null)
sNewProp = "";
if (DECBeanSR == null)
DECBeanSR = (DEC_Bean) session.getAttribute("m_DEC");
String sRemoveOCBlock = (String) session.getAttribute("RemoveOCBlock");
String sRemovePropBlock = (String) session.getAttribute("RemovePropBlock");
if (sRemoveOCBlock == null)
sRemoveOCBlock = "";
if (sRemovePropBlock == null)
sRemovePropBlock = "";
/*
* if (sNewOC.equals("true")) DECBeanSR = insAC.setObjectClassDEC("INS", DECBeanSR, m_classReq); else
* if(sRemoveOCBlock.equals("true"))
*/
String sOC = DECBeanSR.getDEC_OCL_NAME();
if (sOC != null && !sOC.equals(""))
DECBeanSR = setObjectClassDEC("INS", DECBeanSR, m_classReq);
/*
* if (sNewProp.equals("true")) DECBeanSR = insAC.setPropertyDEC("INS", DECBeanSR, m_classReq); else
* if(sRemovePropBlock.equals("true"))
*/
String sProp = DECBeanSR.getDEC_PROPL_NAME();
if (sProp != null && !sProp.equals(""))
DECBeanSR = setPropertyDEC("INS", DECBeanSR, m_classReq);
return DECBeanSR;
}
/**
* To insert a Qualifier Term or update the existing one in the database
* after the validation. Called from CurationServlet. Gets all the attribute
* values from the bean, sets in parameters, and registers output parameter.
* Calls oracle stored procedure "{call
* SBREXT_Set_Row.SET_QUAL(?,?,?,?,?,?,?,?,?)}" to submit
*
* @param sAction
* Insert or update Action.
* @param sREP_IDSEQ.
* @param VD
* VD Bean.
* @param req
* HttpServletRequest Object.
*
* @return String return code from the stored procedure call. null if no
* error occurred.
*/
/*
* public String setVDQualifier(String sAction, String typeQual, //out
* VD_Bean VD, EVS_Bean cq, HttpServletRequest req) { Connection conn =
* null; ResultSet rs = null; CallableStatement cstmt = null; String
* sReturnCode = ""; try { if(cq.getPREFERRED_NAME() != null &
* !cq.getPREFERRED_NAME().equals("")) { String sName =
* VD.getVD_LONG_NAME(); String sContextID = VD.getVD_CONTE_IDSEQ(); String
* sCCVal = cq.getCONCEPT_IDENTIFIER(); // if(sCCVal.equals("No value
* returned.")) // sCCVal = cq.getUMLS_CUI_VAL(); // if(sCCVal.equals("No
* value returned.")) // sCCVal = cq.getTEMP_CUI_VAL(); String sQName = "";
* String sQDescription = ""; sQName = cq.getPREFERRED_NAME(); sQDescription =
* cq.getPREFERRED_DEFINITION(); if(sQDescription.length() > 59)
* sQDescription = sQDescription.substring(0, 59); if (sQName != "") {
* //Create a Callable Statement object. conn =
* m_servlet.connectDB(m_classReq, m_classRes); if (conn == null)
* m_servlet.ErrorLogin(m_classReq, m_classRes); else { cstmt =
* conn.prepareCall("{call SBREXT_Set_Row.SET_QUAL(?,?,?,?,?,?,?,?,?)}");
* cstmt.registerOutParameter(1,java.sql.Types.VARCHAR); //return code
* cstmt.registerOutParameter(6,java.sql.Types.VARCHAR); //created by
* cstmt.registerOutParameter(7,java.sql.Types.VARCHAR); //date created
* cstmt.registerOutParameter(8,java.sql.Types.VARCHAR); //modified by
* cstmt.registerOutParameter(9,java.sql.Types.VARCHAR); //date modified //
* Set the In parameters (which are inherited from the PreparedStatement
* class) cstmt.setString(2,sAction); //ACTION - INS, UPD or DEL
* cstmt.setString(3,sQName); //preferred name - not null for INS
* cstmt.setString(4,sQDescription); cstmt.setString(5,sCCVal); // Now we
* are ready to call the stored procedure boolean bExcuteOk =
* cstmt.execute(); HttpSession session = req.getSession(); sReturnCode =
* cstmt.getString(1); if (sReturnCode != null && !sReturnCode.equals("")) {
* if (typeQual.equalsIgnoreCase("OBJ")) this.storeStatusMsg("\\t " +
* sReturnCode + " : Unable to update Object Qualifier " + sQName + ".");
* else if (typeQual.equalsIgnoreCase("PROP")) this.storeStatusMsg("\\t " +
* sReturnCode + " : Unable to update Property Qualifier " + sQName + ".");
* else if (typeQual.equalsIgnoreCase("REP")) this.storeStatusMsg("\\t " +
* sReturnCode + " : Unable to update Rep Qualifier " + sQName + "."); } } } } }
* catch(Exception e) { logger.fatal("ERROR in InsACService-setQualifier for
* other : " + e.toString(), e); m_classReq.setAttribute("retcode",
* "Exception"); this.storeStatusMsg("\\t Exception : Unable to update or
* remove Qualifier."); } try { if(rs!=null)rs.close(); if(cstmt!=null)
* cstmt.close(); if(conn != null) conn.close(); } catch(Exception ee) {
* logger.fatal("ERROR in InsACService-setQualifier for close : " +
* ee.toString(), ee); m_classReq.setAttribute("retcode", "Exception");
* this.storeStatusMsg("\\t Exception : Unable to update or remove
* Qualifier."); } return sReturnCode; }
*/
/**
* To insert a Qualifier Term or update the existing one in the database
* after the validation. Called from CurationServlet. Gets all the attribute
* values from the bean, sets in parameters, and registers output parameter.
* Calls oracle stored procedure "{call
* SBREXT_Set_Row.SET_QUAL(?,?,?,?,?,?,?,?,?)}" to submit
*
* @param sAction
* Insert or update Action.
* @param sREP_IDSEQ.
* @param VD
* VD Bean.
* @param req
* HttpServletRequest Object.
*
* @return String return code from the stored procedure call. null if no
* error occurred.
*/
/*
* public String setDECQualifier(String sAction, String typeQual, //out
* DEC_Bean DEC, EVS_Bean cq, HttpServletRequest req) { Connection conn =
* null; ResultSet rs = null; CallableStatement cstmt = null; String
* sReturnCode = ""; try { if(cq.getPREFERRED_NAME() != null &&
* !cq.getPREFERRED_NAME().equals("")) { String sName =
* DEC.getDEC_LONG_NAME(); String sContextID = DEC.getDEC_CONTE_IDSEQ();
* String sCCVal = cq.getCONCEPT_IDENTIFIER(); // if(sCCVal.equals("No value
* returned.")) // sCCVal = cq.getUMLS_CUI_VAL(); // if(sCCVal.equals("No
* value returned.")) // sCCVal = cq.getTEMP_CUI_VAL(); String sQName = "";
* String sQDescription = ""; sQName = cq.getPREFERRED_NAME(); sQDescription =
* cq.getPREFERRED_DEFINITION(); if(sQDescription.length() > 59)
* sQDescription = sQDescription.substring(0, 59); if (sQName != "") {
* //Create a Callable Statement object. conn =
* m_servlet.connectDB(m_classReq, m_classRes); if (conn == null)
* m_servlet.ErrorLogin(m_classReq, m_classRes); else { cstmt =
* conn.prepareCall("{call SBREXT_Set_Row.SET_QUAL(?,?,?,?,?,?,?,?,?)}");
* cstmt.registerOutParameter(1,java.sql.Types.VARCHAR); //return code
* cstmt.registerOutParameter(6,java.sql.Types.VARCHAR); //created by
* cstmt.registerOutParameter(7,java.sql.Types.VARCHAR); //date created
* cstmt.registerOutParameter(8,java.sql.Types.VARCHAR); //modified by
* cstmt.registerOutParameter(9,java.sql.Types.VARCHAR); //date modified //
* Set the In parameters (which are inherited from the PreparedStatement
* class) cstmt.setString(2,sAction); //ACTION - INS, UPD or DEL
* cstmt.setString(3,sQName); //preferred name - not null for INS
* cstmt.setString(4,sQDescription); cstmt.setString(5, sCCVal); // Now we
* are ready to call the stored procedure boolean bExcuteOk =
* cstmt.execute(); HttpSession session = req.getSession(); sReturnCode =
* cstmt.getString(1); if (sReturnCode != null && !sReturnCode.equals("")) {
* if (typeQual.equalsIgnoreCase("OBJ")) this.storeStatusMsg("\\t " +
* sReturnCode + " : Unable to update Object Qualifier " + sQName + ".");
* else if (typeQual.equalsIgnoreCase("PROP")) this.storeStatusMsg("\\t " +
* sReturnCode + " : Unable to update Property Qualifier " + sQName + "."); } } } } }
* catch(Exception e) { logger.fatal("ERROR in InsACService-setDECQualifier
* for other : " + e.toString(), e); m_classReq.setAttribute("retcode",
* "Exception"); this.storeStatusMsg("\\t Exception : Unable to update or
* remove Qualifier."); } try { if(rs!=null)rs.close(); if(cstmt!=null)
* cstmt.close(); if(conn != null) conn.close(); } catch(Exception ee) {
* logger.fatal("ERROR in InsACService-setQualifier for close : " +
* ee.toString(), ee); m_classReq.setAttribute("retcode", "Exception");
* this.storeStatusMsg("\\t Exception : Unable to update or remove
* Qualifier."); } return sReturnCode; }
*/
/**
* To insert a new Data Element or update the existing one in the database
* after the validation. Called from CurationServlet. Gets all the attribute
* values from the bean, sets in parameters, and registers output parameter.
* Calls oracle stored procedure "{call
* SBREXT_Set_Row.SET_DE(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}" to
* submit If no error occurs from query execute, calls 'setDES' to create
* CDEID for new DE and to store selected language in the database, calls
* 'setRD' to store reference document and source attributes. calls
* 'getCSCSI' to insert in CSCSI relationship table for Classification
* Scheme/items/DE relationship. calls 'updCSCSI' to update in CSCSI
* relationship for edit.
*
* @param sAction
* Insert or update Action.
* @param de
* DE Bean.
* @param sInsertFor
* for Versioning.
* @param oldDE
* DE IDseq
*
* @return String return code from the stored procedure call. null if no
* error occurred.
*/
@SuppressWarnings("unchecked")
public String setDE(String sAction, DE_Bean de, String sInsertFor,
DE_Bean oldDE) {
ResultSet rs = null;
CallableStatement cstmt = null;
HttpSession session = m_classReq.getSession();
String sReturnCode = "";
String v_ac = "";
String oldDEID = "";
String oldContext = "";
String oldName = "";
String oldContextID = "";
String oldAslName = "";
String sDE_ID = "";
String oldDocText = "";
String oldSource = "";
String oldEndDate = "";
String oldBeginDate = "";
String oldChangeNote = "";
try {
m_classReq.setAttribute("retcode", ""); // set to empty retcode in
// request to track it all
// through this request
if (oldDE == null)
oldDE = new DE_Bean();
String sName = de.getDE_PREFERRED_NAME();
String sContextID = de.getDE_CONTE_IDSEQ();
String sContext = de.getDE_CONTEXT_NAME();
Double DVersion = new Double(de.getDE_VERSION());
double dVersion = DVersion.doubleValue();
String sDefinition = de.getDE_PREFERRED_DEFINITION();
String sDEC_ID = de.getDE_DEC_IDSEQ();
String sVD_ID = de.getDE_VD_IDSEQ();
String sLongName = de.getDE_LONG_NAME();
String sDocText = de.getDOC_TEXT_PREFERRED_QUESTION();
String sBeginDate = m_util.getOracleDate(de.getDE_BEGIN_DATE());
String sEndDate = m_util.getOracleDate(de.getDE_END_DATE());
String sChangeNote = de.getDE_CHANGE_NOTE();
String sSource = de.getDE_SOURCE();
String sLanguage = de.getDE_LANGUAGE();
if (sSource == null)
sSource = "";
// store versioned status message
if (sInsertFor.equals("Version"))
this.storeStatusMsg("\\t Successfully created new version.");
// get the old attributes from the oldbean
if (oldDE != null && !oldDE.equals("")) {
sDE_ID = oldDE.getDE_DE_IDSEQ();
oldDEID = oldDE.getDE_DE_IDSEQ();
oldContext = oldDE.getDE_CONTEXT_NAME();
oldName = oldDE.getDE_PREFERRED_NAME();
oldContextID = oldDE.getDE_CONTE_IDSEQ();
oldAslName = oldDE.getDE_ASL_NAME();
}
if (oldDE != null)
oldSource = oldDE.getDE_SOURCE();
if (oldSource == null)
oldSource = "";
if (sSource == null)
sSource = "";
if ((sSource == null || sSource.equals(""))
&& sAction.equals("UPD") && !sSource.equals(oldSource))
sSource = " ";
if (oldDE != null)
oldChangeNote = oldDE.getDE_CHANGE_NOTE();
if (oldChangeNote == null)
oldChangeNote = "";
if (sChangeNote == null)
sChangeNote = "";
if ((sChangeNote == null || sChangeNote.equals(""))
&& sAction.equals("UPD")
&& !sChangeNote.equals(oldChangeNote))
sChangeNote = " ";
sBeginDate = de.getDE_BEGIN_DATE();
if (sBeginDate == null)
sBeginDate = "";
if (oldDE != null)
oldBeginDate = oldDE.getDE_BEGIN_DATE();
if (oldBeginDate == null)
oldBeginDate = "";
if ((sBeginDate == null || sBeginDate.equals(""))
&& sAction.equals("UPD")
&& !sBeginDate.equals(oldBeginDate))
sBeginDate = " ";
else
sBeginDate = m_util.getOracleDate(de.getDE_BEGIN_DATE());
sEndDate = de.getDE_END_DATE();
if (oldDE != null)
oldEndDate = oldDE.getDE_END_DATE();
if (sEndDate == null)
sEndDate = "";
if ((sEndDate == null || sEndDate.equals(""))
&& sAction.equals("UPD") && !sEndDate.equals(oldEndDate))
sEndDate = " ";
else
sEndDate = m_util.getOracleDate(de.getDE_END_DATE());
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
// Get the username from the session.
String userName = (String) session.getAttribute("Username");
DeVO deVO = new DeVO();
if ((sAction.equals("UPD")) || (sAction.equals("DEL"))) {
deVO.setModified_by(userName);
} else if (sAction.equals("INS")) {
deVO.setCreated_by(userName);
}
if ((sAction.equals("UPD")) || (sAction.equals("DEL"))) {
sDE_ID = de.getDE_DE_IDSEQ();
deVO.setDe_IDSEQ(sDE_ID);
}
// make it null for editing released elements
if (sAction.equals("UPD") && oldAslName.equals("RELEASED") && !sInsertFor.equals("Version")) {
deVO.setConte_IDSEQ(null); // context id-not null for INS, must be null for UPD
deVO.setPrefferred_name(null); // preferred name-not null for INS, must be null for UPD
} else // INS case
{
deVO.setConte_IDSEQ(sContextID);// context id-not null for INS, must be null for UPD
deVO.setPrefferred_name(sName); // preferred name-not null for INS, must be null for UPD
}
deVO.setVersion(dVersion); // version-test says must have a value
deVO.setPrefferred_def(sDefinition); // preferred definition-not null for INS
deVO.setDec_IDSEQ(sDEC_ID); // dec id-not null for INS
deVO.setVd_IDSEQ(sVD_ID); // vd id-not null for INS
deVO.setAsl_name(de.getDE_ASL_NAME()); // status
if (sAction.equals("INS"))
deVO.setLastest_version_ind("Yes"); // latest version indicator
deVO.setLong_name(sLongName); // long name-can be null
deVO.setBegin_date(m_util.getSQLTimestamp(de.getDE_BEGIN_DATE())); // sBeginDate-can be null
deVO.setEnd_date(m_util.getSQLTimestamp(de.getDE_END_DATE())); // sEndDate-can be null
deVO.setChange_note(sChangeNote);
deVO.setOrigin(sSource); // origin
DeComp deComp = new DeComp();
ArrayList errorList = deComp.setDe(deVO, sAction, m_servlet.getConn());
if (errorList != null && errorList.size() > 0) {
DeErrorCodes deErrorCode = (DeErrorCodes) errorList.get(0);
sReturnCode = deErrorCode.getErrorMessage();
} else {
sReturnCode = null;
}
sDE_ID = deVO.getDe_IDSEQ();
// store ac name in the status message
if (sAction.equals("INS"))
this.storeStatusMsg("Data Element Name : " + de.getDE_LONG_NAME());
if (sReturnCode != null && sAction.equals("INS"))
this.storeStatusMsg("\\t " + sReturnCode + " : Unable to create new Data Element Successfully.");
else if ((sReturnCode == null)|| (sReturnCode != null && sAction.equals("UPD")) && !sDE_ID.equals("")) {
// store returncode in request to track it all through this request
if (sReturnCode != null && !sReturnCode.equals(""))
m_classReq.setAttribute("retcode", sReturnCode);
// store the status message in the session
if (sAction.equals("INS")) {
String sPublicID = this.getPublicID(sDE_ID);
de.setDE_MIN_CDE_ID(sPublicID);
this.storeStatusMsg("Public ID : " + de.getDE_MIN_CDE_ID());
this.storeStatusMsg("\\t Successfully created New Data Element.");
} else if (sAction.equals("UPD") && sReturnCode != null && !sReturnCode.equals(""))
this.storeStatusMsg("\\t " + sReturnCode + " : Unable to update mandatory attributes.");
de.setDE_DE_IDSEQ(sDE_ID);
// set create /mofiy attributes into bean
if (deVO.getCreated_by() != null && !deVO.getCreated_by().equals(""))
de.setDE_CREATED_BY(getFullName(deVO.getCreated_by()));
else
de.setDE_CREATED_BY(oldDE.getDE_CREATED_BY());
if (deVO.getDate_created() != null && !deVO.getDate_created().equals(""))
de.setDE_DATE_CREATED(m_util.getCurationDateFromSQLTimestamp(deVO.getDate_created()));
else
de.setDE_DATE_CREATED(oldDE.getDE_DATE_CREATED());
de.setDE_MODIFIED_BY(getFullName(deVO.getModified_by()));
de.setDE_DATE_MODIFIED(m_util.getCurationDateFromSQLTimestamp(deVO.getDate_created()));
// insert row into DES (designation) to create CDEID for new
// DE or copies from old if new version
if (sInsertFor.equals("Version")) {
// created and modifed are same if veriosing
de.setDE_CREATED_BY(de.getDE_MODIFIED_BY());
de.setDE_DATE_CREATED(de.getDE_DATE_MODIFIED());
de.setDE_MIN_CDE_ID(oldDE.getDE_MIN_CDE_ID()); // refill
// the
// oldpublic
// id
}
// insert/update row into DES (designation)
String sReturn = "";
sReturn = "";
// registration status insert or update if not null
if (de.getDE_REG_STATUS() != null
&& !de.getDE_REG_STATUS().equals("")) {
de.setDE_REG_STATUS_IDSEQ(this.getAC_REG(sDE_ID));
if (de.getDE_REG_STATUS_IDSEQ() == null
|| de.getDE_REG_STATUS_IDSEQ().equals(""))
sReturn = this.setReg_Status("INS", "", sDE_ID, de
.getDE_REG_STATUS());
else
sReturn = this.setReg_Status("UPD", de
.getDE_REG_STATUS_IDSEQ(), sDE_ID, de
.getDE_REG_STATUS());
if (sReturn != null && !sReturn.equals(""))
this.storeStatusMsg("\\t "
+ sReturn
+ " : Unable to update Registration Status.");
} else {
// delete if reg status is empty and idseq is not null
if (de.getDE_REG_STATUS_IDSEQ() != null
&& !de.getDE_REG_STATUS_IDSEQ().equals(""))
sReturn = this.setReg_Status("DEL", de
.getDE_REG_STATUS_IDSEQ(), sDE_ID, de
.getDE_REG_STATUS());
if (sReturn != null && !sReturn.equals(""))
this
.storeStatusMsg("\\t "
+ sReturn
+ " : Unable to remove Registration Status.");
}
// store returncode in request to track it all through this
// request
if (sAction.equals("UPD") && sReturn != null
&& !sReturn.equals(""))
m_classReq.setAttribute("retcode", sReturn);
// insert and delete ac-csi relationship
Vector<AC_CSI_Bean> vAC_CS = de.getAC_AC_CSI_VECTOR();
GetACSearch getAC = new GetACSearch(m_classReq, m_classRes,
m_servlet);
Vector<AC_CSI_Bean> vRemove_ACCSI = getAC.doCSCSI_ACSearch(
sDE_ID, ""); // search for cscsi again with de
// idseq.
Vector vACID = (Vector) session.getAttribute("vACId");
this.addRemoveACCSI(sDE_ID, vAC_CS, vRemove_ACCSI, vACID,
sInsertFor, sLongName);
// store back altname and ref docs to session
m_servlet.doMarkACBeanForAltRef(m_classReq, m_classRes,
"DataElement", "all", "submitAR");
// do alternate names create
if (sInsertFor.equalsIgnoreCase("Version"))
this.doAltVersionUpdate(sDE_ID, oldDEID);
// ********************************
de.save(session, m_servlet.getConn(), sDE_ID, sContextID);
session.removeAttribute("AllAltNameList");
// ********************************
/*
* Vector<ALT_NAME_Bean> tBean =
* AltNamesDefsSession.getAltNameBeans(session,
* AltNamesDefsSession._searchDE, sDE_ID, sContextID); if
* (tBean != null) DataManager.setAttribute(session,
* "AllAltNameList", tBean);
*/
String oneAlt = this.doAddRemoveAltNames(sDE_ID,
sContextID, sAction); // , "create");
de.setALTERNATE_NAME(oneAlt);
// do reference docuemnts create
if (sInsertFor.equalsIgnoreCase("Version"))
this.doRefVersionUpdate(sDE_ID, oldDEID);
// insert/upadte row into RD (REFERENCE DOCUMENTS ) //right
// now only for INS.
String sLang = "ENGLISH";
// get the rd idseq for new version
if (sInsertFor.equalsIgnoreCase("Version"))
de
.setDOC_TEXT_PREFERRED_QUESTION_IDSEQ(getRD_ID(sDE_ID));
if ((sDocText != null) && (!sDocText.equals(""))) {
if (sDocText.length() > 30)
sDocText = sDocText.substring(0, 29);
if (de.getDOC_TEXT_PREFERRED_QUESTION_IDSEQ() == null
|| de.getDOC_TEXT_PREFERRED_QUESTION_IDSEQ()
.equals(""))
sReturn = setRD("INS", sDocText, sDE_ID, de
.getDOC_TEXT_PREFERRED_QUESTION(),
"Preferred Question Text", "", sContextID,
de.getDOC_TEXT_PREFERRED_QUESTION_IDSEQ(),
sLang); // ?????
else
sReturn = setRD("UPD", sDocText, sDE_ID, de
.getDOC_TEXT_PREFERRED_QUESTION(),
"Preferred Question Text", "", sContextID,
de.getDOC_TEXT_PREFERRED_QUESTION_IDSEQ(),
sLang); // ?????
} else { // delete RD if null
if (de.getDOC_TEXT_PREFERRED_QUESTION_IDSEQ() != null
&& !de.getDOC_TEXT_PREFERRED_QUESTION_IDSEQ()
.equals("")) {
// sReturn = setRD("DEL", sDocText, sDE_ID,
// de.getDOC_TEXT_PREFERRED_QUESTION(), "Preferred
// Question Text", "", "",
// de.getDOC_TEXT_PREFERRED_QUESTION_IDSEQ(),
// sLang); //?????
// mark it deleted to do the action with other RDs.
Vector<REF_DOC_Bean> vRefDocs = (Vector) session
.getAttribute("AllRefDocList");
for (int i = 0; i < vRefDocs.size(); i++) {
REF_DOC_Bean rBean = (REF_DOC_Bean) vRefDocs
.elementAt(i);
String refID = rBean.getREF_DOC_IDSEQ();
if (refID != null
&& refID
.equalsIgnoreCase(de
.getDOC_TEXT_PREFERRED_QUESTION_IDSEQ())) {
rBean.setREF_SUBMIT_ACTION("DEL");
// System.out.println(" pqt removed " +
// rBean.getDOCUMENT_NAME());
vRefDocs.setElementAt(rBean, i);
DataManager.setAttribute(session,
"AllRefDocList", vRefDocs);
break;
}
}
}
}
// store returncode in request to track it all through this
// request
if (sAction.equals("UPD") && sReturn != null
&& !sReturn.equals(""))
m_classReq.setAttribute("retcode", sReturn);
String oneRD = this.doAddRemoveRefDocs(sDE_ID, sContextID,
sAction); // "create");
de.setREFERENCE_DOCUMENT(oneRD);
// do contact updates
Hashtable<String, AC_CONTACT_Bean> deConts = de
.getAC_CONTACTS();
if (deConts != null && deConts.size() > 0)
de.setAC_CONTACTS(this.addRemoveAC_Contacts(deConts,
sDE_ID, sInsertFor));
// get one concept name for this de
DEC_Bean de_dec = (DEC_Bean) de.getDE_DEC_Bean();
VD_Bean de_vd = (VD_Bean) de.getDE_VD_Bean();
String oneCon = "";
if (de_dec != null && de_dec.getAC_CONCEPT_NAME() != null)
oneCon = de_dec.getAC_CONCEPT_NAME();
if (de_vd != null && de_vd.getAC_CONCEPT_NAME() != null
&& oneCon.equals(""))
oneCon = de_vd.getAC_CONCEPT_NAME();
de.setAC_CONCEPT_NAME(oneCon);
String otherRet = (String) m_classReq
.getAttribute("retcode");
if (sAction.equals("UPD")
&& (otherRet == null || otherRet.equals("")))
this
.storeStatusMsg("\\t Successfully updated Data Element attributes.");
}
}
this.storeStatusMsg("\\n");
if (de.getDE_IN_FORM()) {
//Go through all the forms and set warnings for owners
SearchServlet ser = new SearchServlet(m_classReq, m_classRes, m_servlet.m_servletContext);
ser.get_m_conn();
HashMap<String,ArrayList<String[]>> display = ser.getDEAssociatedForms(de.getIDSEQ(), null);
ArrayList<String[]> forms = display.get("Content");
String[] headers = display.get("Head").get(0);
//Last two spots.
int idseqNdx = headers.length-1;
int nameNdx = headers.length-2;
for (String[] formInfo : forms) {
m_servlet.doMonitor(formInfo[nameNdx], formInfo[idseqNdx]);
}
}
} catch (Exception e) {
logger.error("ERROR in InsACService-setDE for other : "
+ e.toString(), e);
m_classReq.setAttribute("retcode", "Exception");
this
.storeStatusMsg("\\t Exception : Unable to update Data Element Attributes.");
}finally{
rs = SQLHelper.closeResultSet(rs);
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
return sReturnCode;
} // end set DE
/**
* To insert create a new version for an Administered component. Called from
* CurationServlet. Calls oracle stored procedure according to the selected
* AC. "{call META_CONFIG_MGMT.DE_VERSION(?,?,?,?)}" to create new version
* update the respective bean with the new idseq if successful
*
* @param de
* DE_Bean.
* @param dec
* DEC_Bean.
* @param vd
* VD_Bean.
* @param ACName
* String administerd component.
*
* @return String return code from the stored procedure call. null if no
* error occurred.
*/
public String setAC_VERSION(DE_Bean de, DEC_Bean dec, VD_Bean vd,
String ACName) {
ResultSet rs = null;
CallableStatement cstmt = null;
String sReturnCode = "None";
try {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
String ACID = "";
String sVersion = "";
// call the methods according to the ac componenets
if (ACName.equals("DataElement")) {
cstmt = m_servlet.getConn().prepareCall(
"{call META_CONFIG_MGMT.DE_VERSION(?,?,?,?,?)}");
ACID = de.getDE_DE_IDSEQ();
sVersion = de.getDE_VERSION();
} else if (ACName.equals("DataElementConcept")) {
cstmt = m_servlet.getConn().prepareCall(
"{call META_CONFIG_MGMT.DEC_VERSION(?,?,?,?,?)}");
ACID = dec.getDEC_DEC_IDSEQ();
sVersion = dec.getDEC_VERSION();
} else if (ACName.equals("ValueDomain")) {
cstmt = m_servlet.getConn().prepareCall(
"{call META_CONFIG_MGMT.VD_VERSION(?,?,?,?,?)}");
ACID = vd.getVD_VD_IDSEQ();
sVersion = vd.getVD_VERSION();
}
// Set the out parameters (which are inherited from the
// PreparedStatement class)
cstmt.registerOutParameter(3, java.sql.Types.VARCHAR); // NEW
// ID
cstmt.registerOutParameter(4, java.sql.Types.VARCHAR); // RETURN
// CODE
cstmt.setString(1, ACID); // AC idseq
Double DVersion = new Double(sVersion); // convert the version
// to double type
double dVersion = DVersion.doubleValue();
cstmt.setDouble(2, dVersion); // version
// Get the username from the session.
String userName = (String) m_classReq.getSession().getAttribute("Username");
cstmt.setString(5, userName); // username
// Now we are ready to call the stored procedure
cstmt.execute();
sReturnCode = cstmt.getString(4);
String newACID = cstmt.getString(3);
// trim off the extra spaces in it
if (newACID != null && !newACID.equals(""))
newACID = newACID.trim();
// update the bean if return code is null and new de id is not
// null
if (sReturnCode == null && newACID != null) {
// update the bean according to the ac componenets
if (ACName.equals("DataElement"))
de.setDE_DE_IDSEQ(newACID);
else if (ACName.equals("DataElementConcept"))
dec.setDEC_DEC_IDSEQ(newACID);
else if (ACName.equals("ValueDomain"))
vd.setVD_VD_IDSEQ(newACID);
}
}
} catch (Exception e) {
logger.error("ERROR in InsACService-AC_version for exception : "
+ e.toString(), e);
m_classReq.setAttribute("retcode", "Exception");
this
.storeStatusMsg("\\t Exception : Unable to version an Administered Component.");
}finally{
rs = SQLHelper.closeResultSet(rs);
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
return sReturnCode;
}
/**
* To insert create a new version for an Administered component. Called from
* CurationServlet. Calls oracle stored procedure according to the selected
* AC. "{call META_CONFIG_MGMT.DE_VERSION(?,?,?,?)}" to create new version
* update the respective bean with the new idseq if successful
*
* @param acIDseq
* string ac idseq
* @param ACType
* String AC type
*
* @return String return code from the stored procedure call. null if no
* error occurred.
*/
public String setOC_PROP_REP_VERSION(String acIDseq, String ACType) {
ResultSet rs = null;
CallableStatement cstmt = null;
String newACID = "";
try {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
String sReturnCode = "None";
// String sVersion = "";
acIDseq = acIDseq.trim();
// call the methods according to the ac componenets
if (ACType.equals("ObjectClass"))
cstmt = m_servlet.getConn().prepareCall(
"{call META_CONFIG_MGMT.OC_VERSION(?,?,?)}");
else if (ACType.equals("Property"))
cstmt = m_servlet.getConn().prepareCall(
"{call META_CONFIG_MGMT.PROP_VERSION(?,?,?)}");
else if (ACType.equals("RepTerm"))
cstmt = m_servlet.getConn().prepareCall(
"{call META_CONFIG_MGMT.REP_VERSION(?,?,?)}");
// Set the out parameters (which are inherited from the
// PreparedStatement class)
cstmt.registerOutParameter(2, java.sql.Types.VARCHAR); // NEW
// ID
cstmt.registerOutParameter(3, java.sql.Types.VARCHAR); // RETURN
// CODE
cstmt.setString(1, acIDseq); // AC idseq
// Now we are ready to call the stored procedure
cstmt.execute();
sReturnCode = cstmt.getString(3);
newACID = cstmt.getString(2);
// trim off the extra spaces in it
if ((sReturnCode == null || sReturnCode.equals(""))
&& newACID != null && !newACID.equals(""))
newACID = newACID.trim();
else {
newACID = "";
String stmsg = sReturnCode
+ " : Unable to version an Administered Component - "
+ ACType + ".";
logger.error(stmsg);
m_classReq.setAttribute("retcode", sReturnCode);
this.storeStatusMsg("\\t : " + stmsg);
}
}
} catch (Exception e) {
logger.error(
"ERROR in InsACService-setOC_PROP_REP_VERSION for exception : "
+ e.toString(), e);
m_classReq.setAttribute("retcode", "Exception");
this
.storeStatusMsg("\\t Exception : Unable to version an Administered Component.");
}finally{
rs = SQLHelper.closeResultSet(rs);
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
return newACID;
}
/**
* To insert a new row or update the existing one in designations table
* after the validation. Called from 'setDE', 'setVD', 'setDEC' method. Sets
* in parameters, and registers output parameter. Calls oracle stored
* procedure "{call SBREXT_Set_Row.SET_DES(?,?,?,?,?,?,?,?,?,?,?,?)}" to
* submit
*
* @param sAction
* Insert or update Action.
* @param sAC_ID
* selected component's idseq.
* @param sContextID
* selected context idseq.
* @param sContext
* context name to set
* @param desType
* designation type.
* @param sValue
* input value.
* @param sLAE
* language name.
* @param desIDSEQ
* designation idseq for update.
*
* @return String return code from the stored procedure call. null if no
* error occurred.
*/
@SuppressWarnings("unchecked")
public String setDES(String sAction, String sAC_ID, String sContextID,
String sContext, String desType, String sValue, String sLAE,
String desIDSEQ) {
// capture the duration
java.util.Date startDate = new java.util.Date();
// logger.info(m_servlet.getLogMessage(m_classReq, "setDES", "starting
// set", startDate, startDate));
ResultSet rs = null;
CallableStatement cstmt = null;
HttpSession session = m_classReq.getSession();
String sReturnCode = "";
try {
// remove the new line character before submitting
if (sValue != null && !sValue.equals(""))
sValue = m_util.removeNewLineChar(sValue);
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
// cstmt = conn.prepareCall("{call
// SBREXT_Set_Row.SET_DES(?,?,?,?,?,?,?,?,?,?,?,?,?)}");
cstmt = m_servlet
.getConn()
.prepareCall(
"{call SBREXT_SET_ROW.SET_DES(?,?,?,?,?,?,?,?,?,?,?,?,?)}");
// cstmt.registerOutParameter(1, java.sql.Types.VARCHAR); //
// ua_name
cstmt.registerOutParameter(2, java.sql.Types.VARCHAR); // return
// code
cstmt.registerOutParameter(4, java.sql.Types.VARCHAR); // des
// desig
// id
cstmt.registerOutParameter(5, java.sql.Types.VARCHAR); // des
// name
cstmt.registerOutParameter(6, java.sql.Types.VARCHAR); // des
// detl
// name
cstmt.registerOutParameter(7, java.sql.Types.VARCHAR); // des
// ac id
cstmt.registerOutParameter(8, java.sql.Types.VARCHAR); // context
// id
cstmt.registerOutParameter(9, java.sql.Types.VARCHAR); // lae
// name
cstmt.registerOutParameter(10, java.sql.Types.VARCHAR); // created
// by
cstmt.registerOutParameter(11, java.sql.Types.VARCHAR); // date
// created
cstmt.registerOutParameter(12, java.sql.Types.VARCHAR); // modified
// by
cstmt.registerOutParameter(13, java.sql.Types.VARCHAR); // date
// modified
// Set the In parameters (which are inherited from the
// PreparedStatement class)
// Get the username from the session.
String userName = (String) session.getAttribute("Username");
cstmt.setString(1, userName); // set ua_name
if ((sAction.equals("UPD")) || (sAction.equals("DEL"))) {
if ((desIDSEQ != null) && (!desIDSEQ.equals("")))
cstmt.setString(4, desIDSEQ); // desig idseq if
// updated
else
sAction = "INS"; // INSERT A NEW RECORD IF NOT
// EXISTED
}
cstmt.setString(3, sAction); // ACTION - INS, UPD or DEL
cstmt.setString(5, sValue); // selected value for rep and null
// for cde_id
cstmt.setString(6, desType); // detl name - must be string
// CDE_ID
cstmt.setString(7, sAC_ID); // ac id - must be NULL FOR UPDATE
cstmt.setString(8, sContextID); // context id - must be same as
// in set_DE
cstmt.setString(9, sLAE); // language name - can be null
// Now we are ready to call the stored procedure
boolean bExcuteOk = cstmt.execute();
sReturnCode = cstmt.getString(2);
// already exists in the database
if (sReturnCode == null || sReturnCode.equals("API_DES_300")) {
desIDSEQ = cstmt.getString(4);
// store the desIDseq in the hash table for designation
if ((sAction.equals("INS") || sAction.equals("DEL"))
&& desType.equals("USED_BY")) {
// HttpSession session = m_classReq.getSession();
Hashtable<String, String> desTable = (Hashtable) session
.getAttribute("desHashTable");
if (desTable == null)
desTable = new Hashtable<String, String>();
// add or remove from hash table according to the action
if (desIDSEQ == null || desIDSEQ.equals("")) {
this
.storeStatusMsg("\\t "
+ sReturnCode
+ " : Unable to get the ID of Alternate Name - "
+ sValue + " of Type " + desType
+ ".");
m_classReq.setAttribute("retcode", sReturnCode);
} else {
if (sAction.equals("INS")
&& !desTable.contains(sContext + ","
+ sAC_ID))
desTable.put(sContext + "," + sAC_ID, desIDSEQ);
else if (sAction.equals("DEL")
&& desTable.contains(sContext + ","
+ sAC_ID))
desTable.remove(sContext + "," + sAC_ID);
// store it back
DataManager.setAttribute(session, "desHashTable",
desTable);
// refresh used by context in the search results
// list
/*
* GetACSearch serAC = new GetACSearch(m_classReq,
* m_classRes, m_servlet);
* serAC.refreshDesData(sAC_ID, desIDSEQ, sValue,
* sContext, sContextID, sAction);
*/
}
}
} else {
if (sAction.equals("INS") || sAction.equals("UPD"))
this.storeStatusMsg("\\t " + sReturnCode
+ " : Unable to update Alternate Name - "
+ sValue + " of Type " + desType + ".");
else
this.storeStatusMsg("\\t " + sReturnCode
+ " : Unable to remove Alternate Name - "
+ sValue + " of Type " + desType + ".");
m_classReq.setAttribute("retcode", sReturnCode); // store
// returncode
// in
// request
// to
// track
// it
// all
// through
// this
// request
}
}
} catch (Exception e) {
logger.error("ERROR in InsACService-setDES for exception : "
+ e.toString(), e);
m_classReq.setAttribute("retcode", "Exception");
this
.storeStatusMsg("\\t Exception e : Unable to update or remove an Alternate Name.");
}finally{
rs = SQLHelper.closeResultSet(rs);
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
return sReturnCode;
} // end set DES
/**
* After Primary DE and Component DEs are created, insert entries to table
* complex_data_element for DDE info and complex_de_relationship for DE
* Component Calls oracle stored procedure: set_complex_de,
* set_cde_relationship This method is call by doInsertDEfromMenuAction in
* servlet
*
* @param sP_DE_IDSEQ
* string de idseq new created primary DE.
* @param sOverRideAction
* string for New DE Version/Template, use INS instead of UPD
*
* @return String return code from the stored procedure call. null if no
* error occurred.
*/
public String setDDE(String sP_DE_IDSEQ, String sOverRideAction) {
CallableStatement cstmt = null;
String sReturnCode = "";
// boolean bExcuteOk;
String sAction = "";
// Collect data first
HttpSession session = m_classReq.getSession();
// get DEComp rule... from page
String sRulesAction = (String) session.getAttribute("sRulesAction");
String sDDERepType = (String) session.getAttribute("sRepType");
if ((sRulesAction == null || sRulesAction.equals("newRule"))
&& (sDDERepType == null || sDDERepType.length() < 1)) {
// logger.error(" setDDE return nada");
return "";
}
String sDDERule = (String) session.getAttribute("sRule");
String sDDEMethod = (String) session.getAttribute("sMethod");
String sDDEConcatChar = (String) session.getAttribute("sConcatChar");
// get DEComp, DECompID and DECompOrder vector from session, which be
// set in doUpdateDDEInfo
Vector vDEComp = new Vector();
Vector vDECompID = new Vector();
Vector vDECompOrder = new Vector();
Vector vDECompRelID = new Vector();
Vector vDECompDelete = new Vector();
Vector vDECompDelName = new Vector();
vDEComp = (Vector) session.getAttribute("vDEComp");
vDECompID = (Vector) session.getAttribute("vDECompID");
vDECompOrder = (Vector) session.getAttribute("vDECompOrder");
vDECompRelID = (Vector) session.getAttribute("vDECompRelID");
vDECompDelete = (Vector) session.getAttribute("vDECompDelete");
vDECompDelName = (Vector) session.getAttribute("vDECompDelName");
// put them into DB tables
try {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
// call Set_Complex_DE to ins/upd/del rules
if (sRulesAction.equals("existedRule")) {
if (sDDERepType == null || sDDERepType.length() < 1) // existed
// rule
// be
// deleted
{
sAction = "DEL"; // action
if (!vDECompDelete.isEmpty())
deleteDEComp(m_servlet.getConn(), session,
vDECompDelete, vDECompDelName);
} else
sAction = "UPD"; // action
} else
sAction = "INS"; // action
if (sOverRideAction.length() > 0)
sAction = sOverRideAction;
// cstmt = conn.prepareCall("{call
// SBREXT_Set_Row.Set_Complex_DE(?,?,?,?,?,?,?,?,?,?,?,?)}");
cstmt = m_servlet
.getConn()
.prepareCall(
"{call SBREXT_SET_ROW.SET_Complex_DE(?,?,?,?,?,?,?,?,?,?,?,?)}");
// Set the In parameters
// cstmt.registerOutParameter(1, java.sql.Types.VARCHAR); //
// ua_name
cstmt.registerOutParameter(8, java.sql.Types.VARCHAR); // cdt_created_by
cstmt.registerOutParameter(9, java.sql.Types.VARCHAR); // cdt_date_created
cstmt.registerOutParameter(10, java.sql.Types.VARCHAR); // cdt_modified_by
cstmt.registerOutParameter(11, java.sql.Types.VARCHAR); // cdt_date_modified
cstmt.registerOutParameter(12, java.sql.Types.VARCHAR); // return
// code
// Set the In parameters (which are inherited from the
// PreparedStatement class)
// Get the username from the session.
String userName = (String) session.getAttribute("Username");
/*
logger.info("Arguments to sbrext_set_row.set_complex_de()\nuserName\t" + userName
+ "\nsAction\t" + sAction
+ "\nsP_DE_IDSEQ\t" + sP_DE_IDSEQ
+ "\nsDDEMethod\t" + sDDEMethod
+ "\nsDDERule\t" + sDDERule
+ "\nsDDEConcatChar\t" + sDDEConcatChar
+ "\nsDDERepType\t" + sDDERepType);
*/
cstmt.setString(1, userName); // set ua_name
cstmt.setString(2, sAction); // action
cstmt.setString(3, sP_DE_IDSEQ); // primary DE idseq
cstmt.setString(4, sDDEMethod); // method
cstmt.setString(5, sDDERule); // rule
cstmt.setString(6, sDDEConcatChar); // conca char
cstmt.setString(7, sDDERepType); // rep type
// Now we are ready to call the stored procedure
cstmt.execute();
sReturnCode = cstmt.getString(12);
// add error message to list
if (sReturnCode != null && !sReturnCode.equals(""))
this
.storeStatusMsg("\\t "
+ sReturnCode
+ " : Unable to update Derived Data Element attributes");
// call Set_CDE_Relationship for DEComps
// check if any DEComp removed (only for de updates) commented
// by sumana 7/14/05)
// System.out.println(vDECompDelete.isEmpty() + " before delete
// " + sRulesAction);
if (!vDECompDelete.isEmpty()
&& sRulesAction.equals("existedRule"))
deleteDEComp(m_servlet.getConn(), session, vDECompDelete,
vDECompDelName);
// insert or update DEComp
if (!vDEComp.isEmpty()) {
cstmt = SQLHelper.closeCallableStatement(cstmt);
// cstmt = conn.prepareCall("{call
// SBREXT_Set_Row.Set_CDE_Relationship(?,?,?,?,?,?,?,?,?,?,?)}");
cstmt = m_servlet
.getConn()
.prepareCall(
"{call SBREXT_SET_ROW.SET_CDE_Relationship(?,?,?,?,?,?,?,?,?,?,?)}");
// Set the In parameters
cstmt.registerOutParameter(3, java.sql.Types.VARCHAR); // cdr_idseq
cstmt.registerOutParameter(4, java.sql.Types.VARCHAR); // cdr_p_de_idseq
cstmt.registerOutParameter(5, java.sql.Types.VARCHAR); // cdr_c_de_idseq
cstmt.registerOutParameter(6, java.sql.Types.VARCHAR); // cdr_display_order
cstmt.registerOutParameter(7, java.sql.Types.VARCHAR); // cdr_created_by
cstmt.registerOutParameter(8, java.sql.Types.VARCHAR); // cdr_date_created
cstmt.registerOutParameter(9, java.sql.Types.VARCHAR); // cdr_modified_by
cstmt.registerOutParameter(10, java.sql.Types.VARCHAR); // cdr_date_modified
cstmt.registerOutParameter(11, java.sql.Types.VARCHAR); // return
// code
for (int i = 0; i < vDEComp.size(); i++) {
String sDECompName = (String) vDEComp.elementAt(i);
String sDECompID = (String) vDECompID.elementAt(i);
String sDECompOrder = (String) vDECompOrder
.elementAt(i);
String sDECompRelID = (String) vDECompRelID
.elementAt(i);
// Set the In parameters (which are inherited from the
// PreparedStatement class)
// Set the username from the session.
cstmt.setString(1, userName); // set ua_name
if (sDECompRelID.equals("newDEComp")
|| sRulesAction.equals("newRule")) // insert if
// new rule
sAction = "INS"; // action
else {
sAction = "UPD"; // action
cstmt.setString(3, sDECompRelID); // Complex DE
// Relationship
// idseq
}
if (sOverRideAction.length() > 0)
sAction = sOverRideAction;
cstmt.setString(2, sAction); // action
cstmt.setString(4, sP_DE_IDSEQ); // primary DE idseq
cstmt.setString(5, sDECompID); // DE Comp ID
cstmt.setString(6, sDECompOrder); // DE Comp Order
// Now we are ready to call the stored procedure
cstmt.execute();
sReturnCode = cstmt.getString(11);
if (sReturnCode != null && !sReturnCode.equals(""))
this
.storeStatusMsg("\\t "
+ sReturnCode
+ " : Unable to update Derived Data Element Component "
+ sDECompName);
} // end of for
} // end of if(!vDEComp.isEmpty())
} // end of if (conn == null)
} // end of try
catch (Exception e) {
logger.error("ERROR in InsACService-setDEComp for exception : "
+ e.toString(), e);
m_classReq.setAttribute("retcode", "Exception");
this
.storeStatusMsg("\\t Exception : Unable to update or remove Derived Data Elements");
}finally{
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
return sReturnCode;
} // end setDEComp
/**
* Delete DE Component Calls oracle stored procedure: set_cde_relationship
* This method is call by setDEComp
*
* @param conn
* @param session
* @param vDECompDelete
* @param vDECompDelName
*
*
*/
public void deleteDEComp(Connection conn, HttpSession session,
Vector vDECompDelete, Vector vDECompDelName) {
CallableStatement cstmt = null;
try {
String sReturnCode = "";
// call Set_CDE_Relationship for DEComps
// cstmt = conn.prepareCall("{call
// SBREXT_Set_Row.Set_CDE_Relationship(?,?,?,?,?,?,?,?,?,?,?)}");
cstmt = conn
.prepareCall("{call SBREXT_SET_ROW.SET_CDE_Relationship(?,?,?,?,?,?,?,?,?,?,?)}");
// Set the In parameters
cstmt.registerOutParameter(3, java.sql.Types.VARCHAR); // cdr_idseq
cstmt.registerOutParameter(4, java.sql.Types.VARCHAR); // cdr_p_de_idseq
cstmt.registerOutParameter(5, java.sql.Types.VARCHAR); // cdr_c_de_idseq
cstmt.registerOutParameter(6, java.sql.Types.VARCHAR); // cdr_display_order
cstmt.registerOutParameter(7, java.sql.Types.VARCHAR); // cdr_created_by
cstmt.registerOutParameter(8, java.sql.Types.VARCHAR); // cdr_date_created
cstmt.registerOutParameter(9, java.sql.Types.VARCHAR); // cdr_modified_by
cstmt.registerOutParameter(10, java.sql.Types.VARCHAR); // cdr_date_modified
cstmt.registerOutParameter(11, java.sql.Types.VARCHAR); // return
// code
for (int i = 0; i < vDECompDelete.size(); i++) {
String sDECompDeleteID = (String) vDECompDelete.elementAt(i);
String sDECompDeleteName = (String) vDECompDelName.elementAt(i);
// delete DEComp when DEL action in Set_CDE_Relationship is
// ready
if (sDECompDeleteID != null && !sDECompDeleteID.equals("")
&& !sDECompDeleteID.equalsIgnoreCase("newDEComp")) {
// Set the In parameters (which are inherited from the
// PreparedStatement class)
// PreparedStatement class)
// Set the username from the session.
String userName = (String) session.getAttribute("Username");
cstmt.setString(1, userName); // set ua_name
cstmt.setString(2, "DEL"); // action
cstmt.setString(3, sDECompDeleteID); // Complex DE
// Relationship
// idseq, key field
// System.out.println(" dde id " + sDECompDeleteID);
cstmt.setString(4, ""); // primary DE idseq
cstmt.setString(5, ""); // DE Comp ID
cstmt.setString(6, ""); // DE Comp Order
// Now we are ready to call the stored procedure
cstmt.execute();
sReturnCode = cstmt.getString(11);
if (sReturnCode != null && !sReturnCode.equals(""))
this
.storeStatusMsg("\\t "
+ sReturnCode
+ " : Unable to remove Derived Data Element Component "
+ sDECompDeleteName);
}
}
vDECompDelete.clear();
} catch (Exception ee) {
logger.error("ERROR in InsACService-deleteDEComp : "
+ ee.toString(), ee);
m_classReq.setAttribute("retcode", "Exception");
this
.storeStatusMsg("\\t Exception : Unable to remove Derived Data Element Component.");
}finally{
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
} // end of deleteDEComp()
/**
* To insert a new row or update the existing one in reference documents
* table after the validation. Called from 'setDE', 'setVD', 'setDEC'
* method. Sets in parameters, and registers output parameter. Calls oracle
* stored procedure "{call SBREXT_Set_Row.SET_RD(?,?,?,?,?,?,?,?,?,?,?,?)}"
* to submit
*
* @param sAction
* Insert or update Action.
* @param sRDName
* any text value.
* @param sDE_ID
* DE idseq.
* @param sDocText
* value of document text.
* @param sRDType
* Preferred Question Text for Doc Text and DATA_ELEMENT_SOURCE
* for source.
* @param sRDURL
* refercne document's url to set
* @param sRDCont
* reference document context to set
* @param rdIDSEQ
* reference document's idseq for update.
* @param sLang
* Rd language to set
*
* @return String return code from the stored procedure call. null if no
* error occurred.
*/
public String setRD(String sAction, String sRDName, String sDE_ID,
String sDocText, String sRDType, String sRDURL, String sRDCont,
String rdIDSEQ, String sLang) {
CallableStatement cstmt = null;
HttpSession session = m_classReq.getSession();
String sReturnCode = "";
try {
// remove the new line character before submitting
if (sRDName != null && !sRDName.equals(""))
sRDName = m_util.removeNewLineChar(sRDName);
if (sDocText != null && !sDocText.equals(""))
sDocText = m_util.removeNewLineChar(sDocText);
if (sRDURL != null && !sRDURL.equals(""))
sRDURL = m_util.removeNewLineChar(sRDURL);
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
// cstmt = conn.prepareCall("{call
// SBREXT_Set_Row.SET_RD(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}");
cstmt = m_servlet
.getConn()
.prepareCall(
"{call SBREXT_SET_ROW.SET_RD(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}");
cstmt.registerOutParameter(2, java.sql.Types.VARCHAR); // return
// code
cstmt.registerOutParameter(4, java.sql.Types.VARCHAR); // RD id
cstmt.registerOutParameter(5, java.sql.Types.VARCHAR); // name
cstmt.registerOutParameter(6, java.sql.Types.VARCHAR); // dctl
// name
cstmt.registerOutParameter(7, java.sql.Types.VARCHAR); // ac id
cstmt.registerOutParameter(8, java.sql.Types.VARCHAR); // ach
// id
cstmt.registerOutParameter(9, java.sql.Types.VARCHAR); // ar id
cstmt.registerOutParameter(10, java.sql.Types.VARCHAR); // doc
// text
cstmt.registerOutParameter(11, java.sql.Types.VARCHAR); // org
// id
cstmt.registerOutParameter(12, java.sql.Types.VARCHAR); // url
cstmt.registerOutParameter(13, java.sql.Types.VARCHAR); // created
// by
cstmt.registerOutParameter(14, java.sql.Types.VARCHAR); // date
// created
cstmt.registerOutParameter(15, java.sql.Types.VARCHAR); // modified
// by
cstmt.registerOutParameter(16, java.sql.Types.VARCHAR); // date
// modified
cstmt.registerOutParameter(17, java.sql.Types.VARCHAR); // lae
// name
// Set the In parameters (which are inherited from the
// PreparedStatement class)
// Get the username from the session.
String userName = (String) session.getAttribute("Username");
cstmt.setString(1, userName); // set ua_name
if (sAction.equals("UPD") || sAction.equals("DEL")) {
if ((rdIDSEQ != null) && (!rdIDSEQ.equals("")))
cstmt.setString(4, rdIDSEQ); // rd idseq if updated
else
sAction = "INS"; // insert new one if not existed
}
cstmt.setString(3, sAction); // ACTION - INS, UPD or DEL
cstmt.setString(5, sRDName); // rd name - cannot be null
cstmt.setString(6, sRDType); // dCtl name - long name for
// refrence document
if (sAction.equals("INS"))
cstmt.setString(7, sDE_ID); // ac id - must be NULL FOR
// UPDATE
cstmt.setString(10, sDocText); // doc text -
cstmt.setString(12, sRDURL); // URL -
cstmt.setString(17, sLang); // URL -
cstmt.setString(18, sRDCont); // context -
// Now we are ready to call the stored procedure
cstmt.execute();
sReturnCode = cstmt.getString(2);
if (sReturnCode != null && !sReturnCode.equals("API_RD_300")) {
if (sAction.equals("INS") || sAction.equals("UPD"))
this.storeStatusMsg("\\t " + sReturnCode
+ " : Unable to update Reference Documents - "
+ sRDName + " of Type " + sRDType + ".");
else
this.storeStatusMsg("\\t " + sReturnCode
+ " : Unable to remove Reference Documents - "
+ sRDName + " of Type " + sRDType + ".");
m_classReq.setAttribute("retcode", sReturnCode); // store
// returncode
// in
// request
// to
// track
// it
// all
// through
// this
// request
}
}
} catch (Exception e) {
logger.error("ERROR in InsACService-setRD for exception : "
+ e.toString(), e);
m_classReq.setAttribute("retcode", "Exception");
this
.storeStatusMsg("\\t Exception : Unable to update or remove Reference Documents");
}finally{
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
return sReturnCode;
} // end set RD
/**
* To get idseq from get_cscsi stored proc to add relationship between csCSI
* and DE. Called from 'setDE' method. Uses the sql query "SELECT
* cs_csi_idseq FROM cs_Csi_view WHERE cs_idseq = '" + csID + "' AND
* csi_idseq = '" + csiID + "'"; Calls 'setACCSI' to add a row in
* relationship table.
*
* @param csID
* classification scheme idseq.
* @param csiID
* classification scheme items idseq.
* @param sAction
* Insert or update Action.
* @param sDE_ID
* DE idseq.
*
*/
public void getCSCSI(String csID, String csiID, String sAction,
String sDE_ID) {
ResultSet rs = null;
CallableStatement cstmt = null;
try {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
cstmt = m_servlet.getConn().prepareCall(
"{call SBREXT_CDE_CURATOR_PKG.GET_CSCSI(?,?,?)}");
cstmt.setString(1, csID);
cstmt.setString(2, csiID);
cstmt.registerOutParameter(3, OracleTypes.CURSOR);
cstmt.execute();
rs = (ResultSet) cstmt.getObject(3);
String s;
while (rs.next()) {
s = rs.getString(1);
if (s != "") // cs_csi_idseq
setACCSI(s, sAction, sDE_ID, "", "", "");
}
}
} catch (Exception e) {
logger.error("ERROR in InsACService-getCSCSI for exception : "
+ e.toString(), e);
}finally{
rs = SQLHelper.closeResultSet(rs);
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
} // end cscsi
/**
* To insert a row in AC_CSI table to add relationship between csCSI and DE.
* Called from 'getCSCSI' method. Sets in parameters, and registers output
* parameter. Calls oracle stored procedure "{call
* SBREXT_Set_Row.SET_ACCSI(?,?,?,?,?,?,?,?,?)}" to submit
*
* @param CSCSIID
* cscsi idseq from cs_csi table.
* @param sAction
* Insert or update Action.
* @param sAC_ID
* String ac idseq
* @param sAC_CSI_ID
* String accsi idseq
* @param sAC_Name
* String ac name
* @param csiName
* String csi name
*
* @return String ACCSI id
*/
public String setACCSI(String CSCSIID, String sAction, String sAC_ID,
String sAC_CSI_ID, String sAC_Name, String csiName) {
ResultSet rs = null;
CallableStatement cstmt = null;
HttpSession session = m_classReq.getSession();
try {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
// cstmt = conn.prepareCall("{call
// SBREXT_Set_Row.SET_ACCSI(?,?,?,?,?,?,?,?,?,?)}");
cstmt = m_servlet
.getConn()
.prepareCall(
"{call SBREXT_SET_ROW.SET_ACCSI(?,?,?,?,?,?,?,?,?,?)}");
cstmt.registerOutParameter(2, java.sql.Types.VARCHAR); // return
// code
cstmt.registerOutParameter(4, java.sql.Types.VARCHAR); // AC_CSI
// id
cstmt.registerOutParameter(5, java.sql.Types.VARCHAR); // AC id
cstmt.registerOutParameter(6, java.sql.Types.VARCHAR); // CS_CSI
// id
cstmt.registerOutParameter(7, java.sql.Types.VARCHAR); // date
// created
cstmt.registerOutParameter(8, java.sql.Types.VARCHAR); // created
// by
cstmt.registerOutParameter(9, java.sql.Types.VARCHAR); // modified
// by
cstmt.registerOutParameter(10, java.sql.Types.VARCHAR); // date
// modified
// Set the In parameters (which are inherited from the
// PreparedStatement class)
// Get the username from the session.
String userName = (String) session.getAttribute("Username");
cstmt.setString(1, userName); // set ua_name
cstmt.setString(3, sAction); // ACTION - INS, UPD or DEL
cstmt.setString(4, sAC_CSI_ID); // AC ID - not null
cstmt.setString(5, sAC_ID); // AC ID - not null
cstmt.setString(6, CSCSIID); // CS_CSI_ID - cannot be null
// Now we are ready to call the stored procedure
cstmt.execute();
String ret = cstmt.getString(2);
// get its accsi id if already exists in the database
if (ret != null && ret.equals("API_ACCSI_300"))
sAC_CSI_ID = cstmt.getString(4);
else if (ret != null && !ret.equals("")) {
if (sAction.equals("INS") || sAction.equals("UPD"))
this.storeStatusMsg("\\t " + ret
+ " : Unable to update CSI-" + csiName + ".");
else
this.storeStatusMsg("\\t " + ret
+ " : Unable to remove CSI-" + csiName + ".");
m_classReq.setAttribute("retcode", ret); // store
// returncode in
// request to
// track it all
// through this
// request
}
}
} catch (Exception e) {
logger.error("ERROR in InsACService-setACCSI for exception : "
+ e.toString(), e);
m_classReq.setAttribute("retcode", "Exception");
this
.storeStatusMsg("\\t Exception : Unable to update or remove AC_CSI relationship.");
}finally{
rs = SQLHelper.closeResultSet(rs);
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
return sAC_CSI_ID;
}
/**
* To retrieve a row in AC_CSI table. Called from 'setDE' method. Calls
* oracle stored procedure "{call
* SBREXT_Get_Row.SET_ACCSI(?,?,?,?,?,?,?,?,?)}" to submit
*
* @param sCSCSIID
* cscsi idseq from cs_csi table.
* @param sDE_ID
* DE idseq.
* @return String accsi idseq
*
*/
public String getACCSI(String sCSCSIID, String sDE_ID) {
CallableStatement cstmt = null;
String sACCSI = "";
try {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
cstmt = m_servlet.getConn().prepareCall(
"{call SBREXT_Get_Row.GET_AC_CSI(?,?,?,?,?,?,?,?)}");
cstmt.registerOutParameter(1, java.sql.Types.VARCHAR); // return
// code
cstmt.registerOutParameter(2, java.sql.Types.VARCHAR); // accsi
// out
cstmt.registerOutParameter(3, java.sql.Types.VARCHAR); // CS_CSI
// id
cstmt.registerOutParameter(4, java.sql.Types.VARCHAR); // AC
// idseq
cstmt.registerOutParameter(6, java.sql.Types.VARCHAR); // date
// created
cstmt.registerOutParameter(5, java.sql.Types.VARCHAR); // created
// by
cstmt.registerOutParameter(7, java.sql.Types.VARCHAR); // modified
// by
cstmt.registerOutParameter(8, java.sql.Types.VARCHAR); // date
// modified
// Set the In parameters (which are inherited from the
// PreparedStatement class)
cstmt.setString(3, sCSCSIID); // AC ID - not null
cstmt.setString(4, sDE_ID); // AC ID - not null
// Now we are ready to call the stored procedure
cstmt.execute();
sACCSI = cstmt.getString(2);
}
} catch (Exception e) {
logger.error("ERROR in InsACService-setACCSI for exception : "
+ e.toString(), e);
}finally{
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
return sACCSI;
}
/**
* not using anymore because source is not a drop down list. To insert a row
* in AC_SOURCES table to add relationship between sources and DE. Called
* from 'setDE' method. Sets in parameters, and registers output parameter.
* Calls oracle stored procedure "{call
* SBREXT_Set_Row.SET_ACSRC(?,?,?,?,?,?,?,?,?,?)}" to submit
*
* @param sAction
* Insert or update Action.
* @param sDE_ID
* DE idseq.
*
*/
public void setACSRC(String sAction, String sDE_ID) {
CallableStatement cstmt = null;
HttpSession session = m_classReq.getSession();
try {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
// cstmt = conn.prepareCall("{call
// SBREXT_Set_Row.SET_ACSRC(?,?,?,?,?,?,?,?,?,?,?)}");
cstmt = m_servlet
.getConn()
.prepareCall(
"{call SBREXT_SET_ROW.SET_ACSRC(?,?,?,?,?,?,?,?,?,?,?)}");
cstmt.registerOutParameter(2, java.sql.Types.VARCHAR); // return
cstmt.registerOutParameter(4, java.sql.Types.VARCHAR); // ACS
// id
cstmt.registerOutParameter(5, java.sql.Types.VARCHAR); // AC id
cstmt.registerOutParameter(6, java.sql.Types.VARCHAR); // SRC
// name
cstmt.registerOutParameter(7, java.sql.Types.VARCHAR); // date
// submitted
cstmt.registerOutParameter(8, java.sql.Types.VARCHAR); // created
// by
cstmt.registerOutParameter(9, java.sql.Types.VARCHAR); // date
// created
cstmt.registerOutParameter(10, java.sql.Types.VARCHAR); // date
// modified
cstmt.registerOutParameter(11, java.sql.Types.VARCHAR); // modified
// by
// Set the In parameters (which are inherited from the
// PreparedStatement class)
// Get the username from the session.
String userName = (String) session.getAttribute("Username");
cstmt.setString(1, userName); // set ua_name
cstmt.setString(3, sAction); // ACTION - INS, UPD or DEL
cstmt.setString(5, sDE_ID); // AC ID - not null
cstmt.setString(6, "AJCC"); // SRC name - cannot be null ????
// Now we are ready to call the stored procedure
cstmt.execute();
}
} catch (Exception e) {
logger.error("ERROR in InsACService-setACSRC for exception : "
+ e.toString(), e);
m_classReq.setAttribute("retcode", "Exception");
this
.storeStatusMsg("\\t Exception : Unable to update or remove Origin.");
}finally{
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
} // end of setACSRC
/**
* To update relationship between sources and DE. Called from 'setDE' method
* for update. Sets in parameters, and registers output parameter. Calls
* oracle stored procedure "{call
* SBREXT_CDE_CURATOR_PKG.UPD_CS(?,?,?,?,?,?)}" to submit
*
* @param sDE_ID
* DE idseq.
* @param sCS_ID
* classification scheme idseq.
* @param sCSI_ID
* classification scheme items idseq.
*/
public void updCSCSI(String sDE_ID, String sCS_ID, String sCSI_ID) {
CallableStatement cstmt = null;
try {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
cstmt = m_servlet.getConn().prepareCall(
"{call SBREXT_CDE_CURATOR_PKG.UPD_CS(?,?,?,?,?,?)}");
cstmt.registerOutParameter(6, java.sql.Types.VARCHAR); // error
// code
// Set the In parameters (which are inherited from the
// PreparedStatement class)
cstmt.setString(1, sDE_ID); // DE idseq
cstmt.setString(2, sCS_ID); // new cs ID
cstmt.setString(3, sCSI_ID); // new csi id
cstmt.setString(4, ""); // old cs id
cstmt.setString(5, ""); // old csi id
// Now we are ready to call the stored procedure
cstmt.execute();
}
} catch (Exception e) {
logger.error("ERROR in InsACService-updCSCSI for exception : "
+ e.toString(), e);
}finally{
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
} // end of setACSRC
/**
* Called from 'setPV' method for insert of PV. Sets in parameters, and
* registers output parameter. Calls oracle stored procedure "{call
* SBREXT_GET_ROW.GET_PV(?,?,?,?,?,?,?,?,?,?,?,?,?)}" to submit
*
* @param sValue
* existing Value.
* @param sMeaning
* existing meaning.
*
* @return String existing pv_idseq from the stored procedure call.
*/
public String getExistingPV(String sValue, String sMeaning)
{
String sPV_IDSEQ = "";
CallableStatement cstmt = null;
try {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
cstmt = m_servlet
.getConn()
.prepareCall(
"{call SBREXT_GET_ROW.GET_PV(?,?,?,?,?,?,?,?,?,?,?,?,?)}");
cstmt.registerOutParameter(1, java.sql.Types.VARCHAR); // return
// code
cstmt.registerOutParameter(2, java.sql.Types.VARCHAR); // PV_IDSEQ
cstmt.registerOutParameter(5, java.sql.Types.VARCHAR); // MEANING_DESCRIPTION
cstmt.registerOutParameter(6, java.sql.Types.VARCHAR); // HIGH_VALUE_NUM
cstmt.registerOutParameter(7, java.sql.Types.VARCHAR); // LOW_VALUE_NUM
cstmt.registerOutParameter(8, java.sql.Types.VARCHAR); // BEGIN_DATE
cstmt.registerOutParameter(9, java.sql.Types.VARCHAR); // END_DATE
cstmt.registerOutParameter(10, java.sql.Types.VARCHAR); // CREATED_BY
cstmt.registerOutParameter(11, java.sql.Types.VARCHAR); // Date
// Created
cstmt.registerOutParameter(12, java.sql.Types.VARCHAR); // MODIFIED_BY
cstmt.registerOutParameter(13, java.sql.Types.VARCHAR); // DATE_MODIFIED
cstmt.setString(3, sValue); // Value
cstmt.setString(4, sMeaning); // Meaning
// Now we are ready to call the stored procedure
cstmt.execute();
sPV_IDSEQ = (String) cstmt.getObject(2);
if (sPV_IDSEQ == null)
sPV_IDSEQ = "";
}
} catch (Exception e) {
logger.error(
"ERROR in InsACService- getExistingPV for exception : "
+ e.toString(), e);
}finally{
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
return sPV_IDSEQ;
}
/**
* To copy cde_id from old de to new de when versioning. Called from 'setDE'
* method for insert at version. Sets in parameters, and registers output
* parameter. Calls oracle stored procedure "{call META_CONFIG_MGMT(?,?,?)}"
* to submit
*
* @param sOldACID
* OLD DE idseq.
* @param sNewACID
* NEW DE idseq.
*/
private void copyAC_ID(String sOldACID, String sNewACID) {
CallableStatement cstmt = null;
try {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
cstmt = m_servlet.getConn().prepareCall(
"{call META_CONFIG_MGMT.COPYACNAMES(?,?,?)}");
// Set the In parameters (which are inherited from the
// PreparedStatement class)
cstmt.setString(1, sOldACID); // DE idseq
cstmt.setString(2, sNewACID); // new DE ID
cstmt.setString(3, "V"); // new csi id
// Now we are ready to call the stored procedure
cstmt.execute();
}
} catch (Exception e) {
logger.error("ERROR in InsACService-copyACID for exception : "
+ e.toString(), e);
}finally{
cstmt = SQLHelper.closeCallableStatement(cstmt);
} }
/**
* To update history table, connecting last version to this version. Called
* from 'setDE' method for insert at version. Sets in parameters, and
* registers output parameter. Calls oracle stored procedure "{call
* META_CONFIG_MGMT.DE_VERSION(?,?,?)}" to submit
*
* @param sNewID
* New DE idseq.
* @param sOldID
* OLD DE idseq.
* @param sACType
* string ac type
*/
private void createACHistories(String sNewID, String sOldID, String sACType) {
CallableStatement cstmt = null;
try {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
cstmt = m_servlet
.getConn()
.prepareCall(
"{call META_CONFIG_MGMT.CREATE_AC_HISTORIES(?,?,?,?,?)}");
// Set the In parameters (which are inherited from the
// PreparedStatement class)
cstmt.setString(1, sOldID); // DE idseq
cstmt.setString(2, sNewID); // new DE ID
cstmt.setString(3, "VERSIONED"); // Config type
cstmt.setString(4, sACType); // type of AC
cstmt.setString(5, ""); // table name, default null
// Now we are ready to call the stored procedure
cstmt.execute();
}
} catch (Exception e) {
logger.error(
"ERROR in InsACService-createACHistory for exception : "
+ e.toString(), e);
}finally{
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
}
/**
* To get ac_idseq of latest version. Called from 'setDE' method. Sets in
* parameters, and registers output parameter.
*
* @param sName
* Short Name.
* @param sContextID .
* @param sACType
* String type of AC.
* @return ac idseq
*/
private String getVersionAC(String sName, String sContextID, String sACType) {
ResultSet rs = null;
String sReturnID = "";
PreparedStatement pstmt = null;
try {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
pstmt = m_servlet
.getConn()
.prepareStatement(
"Select Sbrext_Common_Routines.get_version_ac(?,?,?) from DUAL");
pstmt.setString(1, sName); // DE idseq
pstmt.setString(2, sContextID); // new DE ID
pstmt.setString(3, sACType); // type of AC
rs = pstmt.executeQuery();
while (rs.next()) {
sReturnID = rs.getString(1);
}
}
} catch (Exception e) {
logger.error("ERROR in InsACService-getversionac for exception : "
+ e.toString(), e);
}finally{
rs = SQLHelper.closeResultSet(rs);
pstmt = SQLHelper.closePreparedStatement(pstmt);
}
return sReturnID;
}
/**
* To update the existing Question in questionContents table after the de
* create/update or vd_pvs create for questions. Called from servlet. Sets
* in parameters, and registers output parameter. Calls oracle stored
* procedure "{call
* SBREXT_Set_Row.SET_QC(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}"
* to submit
*
* @param questBean
* Quest_Bean when this is used for questions update, else null.
* @param QCid
* string question's idseq when this is used for Valid Value
* update, else null.
* @param VPid
* string vd_pvs idseq when this is used for valid value update,
* else null
*
* @return String return code from the stored procedure call. null if no
* error occurred.
*/
public String setQuestContent(Quest_Bean questBean, String QCid, String VPid) {
// capture the duration
java.util.Date startDate = new java.util.Date();
CallableStatement cstmt = null;
HttpSession session = m_classReq.getSession();
String sReturnCode = "";
try {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
// cstmt = conn.prepareCall("{call
// SBREXT_Set_Row.SET_QC(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}");
cstmt = m_servlet
.getConn()
.prepareCall(
"{call SBREXT_SET_ROW.SET_QC(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}");
cstmt.registerOutParameter(2, java.sql.Types.VARCHAR); // return
// code
cstmt.registerOutParameter(4, java.sql.Types.VARCHAR); // oc id
cstmt.registerOutParameter(5, java.sql.Types.DECIMAL); // version
cstmt.registerOutParameter(6, java.sql.Types.VARCHAR); // Short
// Name
cstmt.registerOutParameter(7, java.sql.Types.VARCHAR); // definiton
cstmt.registerOutParameter(8, java.sql.Types.VARCHAR); // context
// id
cstmt.registerOutParameter(9, java.sql.Types.VARCHAR); // asl
// id
cstmt.registerOutParameter(10, java.sql.Types.VARCHAR); //
cstmt.registerOutParameter(11, java.sql.Types.VARCHAR); //
cstmt.registerOutParameter(12, java.sql.Types.VARCHAR); //
cstmt.registerOutParameter(13, java.sql.Types.VARCHAR); //
cstmt.registerOutParameter(14, java.sql.Types.VARCHAR); // deID
cstmt.registerOutParameter(15, java.sql.Types.VARCHAR); // vp id
cstmt.registerOutParameter(16, java.sql.Types.VARCHAR); //
cstmt.registerOutParameter(17, java.sql.Types.VARCHAR); //
cstmt.registerOutParameter(18, java.sql.Types.VARCHAR); //
cstmt.registerOutParameter(19, java.sql.Types.VARCHAR); // match
// ind
cstmt.registerOutParameter(20, java.sql.Types.VARCHAR); //
cstmt.registerOutParameter(21, java.sql.Types.VARCHAR); //
cstmt.registerOutParameter(22, java.sql.Types.VARCHAR); //
cstmt.registerOutParameter(23, java.sql.Types.VARCHAR); //
cstmt.registerOutParameter(24, java.sql.Types.VARCHAR); //
cstmt.registerOutParameter(25, java.sql.Types.VARCHAR); //
cstmt.registerOutParameter(26, java.sql.Types.VARCHAR); //
cstmt.registerOutParameter(27, java.sql.Types.VARCHAR); //
cstmt.registerOutParameter(28, java.sql.Types.VARCHAR); //
cstmt.registerOutParameter(29, java.sql.Types.VARCHAR); //
cstmt.registerOutParameter(30, java.sql.Types.VARCHAR); //
cstmt.registerOutParameter(31, java.sql.Types.VARCHAR); //
cstmt.registerOutParameter(32, java.sql.Types.VARCHAR); //
cstmt.registerOutParameter(33, java.sql.Types.VARCHAR); //
cstmt.registerOutParameter(34, java.sql.Types.VARCHAR); // submitted
// cde
// long
// name
cstmt.registerOutParameter(35, java.sql.Types.VARCHAR); //
cstmt.registerOutParameter(36, java.sql.Types.VARCHAR); // vd
// idseq
cstmt.registerOutParameter(37, java.sql.Types.VARCHAR); // created
// by
cstmt.registerOutParameter(38, java.sql.Types.VARCHAR); // date
// created
cstmt.registerOutParameter(39, java.sql.Types.VARCHAR); // modified
// by
cstmt.registerOutParameter(40, java.sql.Types.VARCHAR); // date
// modified
cstmt.registerOutParameter(41, java.sql.Types.VARCHAR); // deleted
// ind
// Set the In parameters (which are inherited from the
// PreparedStatement class)
// Get the username from the session.
String userName = (String) session.getAttribute("Username");
cstmt.setString(1, userName); // set ua_name
cstmt.setString(3, "UPD"); // ACTION - INS, UPD or DEL
if (VPid != null && !VPid.equals("")) {
cstmt.setString(4, QCid); // qc idseq if updated
cstmt.setString(15, VPid); // VP idseq for valid values
cstmt.setString(9, "EXACT MATCH"); // workflow status of
// the valid value
cstmt.setString(19, "E"); // match ind of the valid value
} else {
cstmt.setString(4, questBean.getQC_IDSEQ()); // qc idseq
// if
// updated
cstmt.setString(7, questBean.getQUEST_DEFINITION()); // QUEST
// definition
cstmt.setString(14, questBean.getDE_IDSEQ()); // de_idseq
cstmt.setString(34, questBean.getSUBMITTED_LONG_NAME()); // submitted
// long
// cde
// name
cstmt.setString(36, questBean.getVD_IDSEQ()); // vd idseq
}
cstmt.setString(42, null); // de long name
cstmt.setString(43, null); // de long name
cstmt.setString(44, null); // de long name
cstmt.setString(45, null); // de long name
cstmt.setString(46, null); // de long name
cstmt.setString(47, null); // de long name
cstmt.setString(48, null); // de long name
cstmt.setString(49, null); // questBean.getDE_LONG_NAME());
// //de long name
cstmt.setString(50, null); // questBean.getVD_LONG_NAME()); //
// vd long name
cstmt.setString(51, null);
// Now we are ready to call the stored procedure
cstmt.execute();
sReturnCode = cstmt.getString(2);
if (sReturnCode != null && !sReturnCode.equals("")) {
this.storeStatusMsg("\\t " + sReturnCode
+ " : Unable to update Question attributes.");
m_classReq.setAttribute("retcode", sReturnCode);
}
}
} catch (Exception e) {
logger.error(
"ERROR in InsACService-setQuestContent for exception : "
+ e.toString(), e);
m_classReq.setAttribute("retcode", "Exception");
this
.storeStatusMsg("\\t Exception : Unable to update Question attributes.");
}finally{
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
return sReturnCode;
} // end set quest content
/**
* To get RDidseq from get_RD_ID for the selected AC. Called from 'setDE'
* method. Uses the stored Proc call
* SBREXT_COMMON_ROUTINES.GET_RD_IDSEQ(?,?,?)}
*
* @param acID
* administed componenet idseq.
*
* @return String RD_ID.
*/
public String getRD_ID(String acID) {
ResultSet rs = null;
CallableStatement cstmt = null;
String rd_ID = "";
try {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
cstmt = m_servlet.getConn().prepareCall(
"{call SBREXT_COMMON_ROUTINES.GET_RD_IDSEQ(?,?,?)}");
cstmt.setString(1, acID);
cstmt.setString(2, "Preferred Question Text");
cstmt.registerOutParameter(3, OracleTypes.CURSOR);
cstmt.execute();
rs = (ResultSet) cstmt.getObject(3);
while (rs.next()) {
rd_ID = rs.getString(1);
if (rd_ID != null)
break;
}
if (rd_ID == null)
rd_ID = "";
}
} catch (Exception e) {
logger.error("ERROR in InsACService-getRD_ID for exception : "
+ e.toString(), e);
}finally{
rs = SQLHelper.closeResultSet(rs);
cstmt = SQLHelper.closeCallableStatement(cstmt);
// SQLHelper.closeConnection(m_servlet.getConn()); //GF32438
}
return rd_ID;
} // end RD_ID
/**
* To get UA_FullName from a UserName. Called from 'set' methods. Uses the
* stored Proc call SBREXT_COMMON_ROUTINES.GET_UA_FULL_NAME(?,?,?)}
*
* @param sName
* short Name.
*
* @return String sFullName.
*/
public String getFullName(String sName) {
ResultSet rs = null;
String sFullName = "";
PreparedStatement pstmt = null;
try {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
pstmt = m_servlet
.getConn()
.prepareStatement(
"Select SBREXT_CDE_CURATOR_PKG.GET_UA_FULL_NAME(?) from DUAL");
pstmt.setString(1, sName); // short name
rs = pstmt.executeQuery();
while (rs.next()) {
sFullName = rs.getString(1);
}
}
} catch (Exception e) {
logger.error("ERROR in InsACService-getFullName for exception : "
+ e.toString(), e);
}finally{
rs = SQLHelper.closeResultSet(rs);
pstmt = SQLHelper.closePreparedStatement(pstmt);
}
return sFullName;
} // end getFullName
/**
* To get language idseq from get_Desig_ID for the selected AC . Called from
* 'setDE', 'setDEC', 'setVD' methods. Uses the stored Proc call
* SBREXT_COMMON_ROUTINES.GET_DESIG_IDSEQ(?,?,?)}
*
* @param acID
* administed componenet idseq.
* @param DesType
* type of designation
*
* @return String Desig_ID.
*/
public String getDesig_ID(String acID, String DesType) {
ResultSet rs = null;
CallableStatement cstmt = null;
String Desig_ID = "";
try {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
cstmt = m_servlet.getConn().prepareCall(
"{call SBREXT_COMMON_ROUTINES.GET_DESIG_IDSEQ(?,?,?)}");
cstmt.setString(1, acID);
cstmt.setString(2, DesType);
cstmt.registerOutParameter(3, OracleTypes.CURSOR);
cstmt.execute();
rs = (ResultSet) cstmt.getObject(3);
while (rs.next()) {
Desig_ID = rs.getString(1);
if (Desig_ID != null)
break;
}
if (Desig_ID == null)
Desig_ID = "";
}
} catch (Exception e) {
logger.error("ERROR in InsACService-getDesig_ID for exception : "
+ e.toString(), e);
}finally{
rs = SQLHelper.closeResultSet(rs);
cstmt = SQLHelper.closeCallableStatement(cstmt);;
}
return Desig_ID;
} // end Desig_ID
/**
* To insert a row in AC_Registrations table to add relationship between
* reg_status and DE. Called from 'setDE' method. Sets in parameters, and
* registers output parameter. Calls oracle stored procedure "{call
* SBREXT_Set_Row.SET_REGISTRATION(?,?,?,?,?,?,?,?,?)}" to submit
*
* @param sAction
* Insert or update Action.
* @param sAR_ID
* idseq from ac_registratins table.
* @param sAC_ID
* AC idseq.
* @param regStatus
* registration status
*
* @return String sAR_ID
*/
public String setReg_Status(String sAction, String sAR_ID, String sAC_ID,
String regStatus) {
CallableStatement cstmt = null;
HttpSession session = m_classReq.getSession();
String ret = "";
try {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
// cstmt = conn.prepareCall("{call
// SBREXT_Set_Row.SET_REGISTRATION(?,?,?,?,?,?,?,?,?,?)}");
cstmt = m_servlet
.getConn()
.prepareCall(
"{call SBREXT_Set_Row.SET_REGISTRATION(?,?,?,?,?,?,?,?,?,?)}");
cstmt.registerOutParameter(3, java.sql.Types.VARCHAR); // sAR_ID
cstmt.registerOutParameter(4, java.sql.Types.VARCHAR); // sAC_ID
cstmt.registerOutParameter(5, java.sql.Types.VARCHAR); // regStatus
cstmt.registerOutParameter(6, java.sql.Types.VARCHAR); // created
// by
cstmt.registerOutParameter(7, java.sql.Types.VARCHAR); // date
// created
cstmt.registerOutParameter(8, java.sql.Types.VARCHAR); // modified
// by
cstmt.registerOutParameter(9, java.sql.Types.VARCHAR); // date
// modified
cstmt.registerOutParameter(10, java.sql.Types.VARCHAR); // return
// code
// Set the In parameters (which are inherited from the
// PreparedStatement class)
// Get the username from the session.
String userName = (String) session.getAttribute("Username");
cstmt.setString(1, userName); // set ua_name
cstmt.setString(2, sAction); // ACTION - INS, UPD or DEL
cstmt.setString(3, sAR_ID); // AR ID - not null if upd or del
cstmt.setString(4, sAC_ID); // AC ID - not null if ins
cstmt.setString(5, regStatus); // regStatus - cannot be null
// Now we are ready to call the stored procedure
cstmt.execute();
// get its AR id if already exists in the database
if (cstmt.getString(10) != null)
ret = cstmt.getString(10);
// else
// sAR_ID = cstmt.getString(2);
if (ret != null && !ret.equals("")) {
if (sAction.equals("DEL"))
this.storeStatusMsg("\\t " + ret
+ " : Unable to remove Registration Status - "
+ regStatus + ".");
else
this.storeStatusMsg("\\t " + ret
+ " : Unable to update Registration Status - "
+ regStatus + ".");
m_classReq.setAttribute("retcode", ret); // store
// returncode in
// request to
// track it all
// through this
// request
}
}
} catch (Exception e) {
logger.error("ERROR in InsACService-setReg_Status for exception : "
+ e.toString(), e);
m_classReq.setAttribute("retcode", "Exception");
this
.storeStatusMsg("\\t Exception : Unable to update or remove Registration Status.");
}finally{
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
return ret;
}
/**
* The getAC_REG method queries the db, checking whether component exists
* and gets idseq if exists.
*
* @param ac_id
* string ac idseq
*
* @return String idseq indicating whether component exists.
*/
public String getAC_REG(String ac_id) // returns idseq
{
ResultSet rs = null;
Statement cstmt = null;
String regID = "";
try {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
cstmt = m_servlet.getConn().createStatement();
rs = cstmt
.executeQuery("SELECT ar_idseq FROM sbr.ac_registrations_view WHERE ac_idseq = '"
+ ac_id + "'");
// loop through to printout the outstrings
while (rs.next()) {
regID = rs.getString(1);
}// end of while
}
} catch (Exception e) {
logger.error("ERROR in getAC_REG : " + e.toString(), e);
}finally{
rs = SQLHelper.closeResultSet(rs);
cstmt = SQLHelper.closeStatement(cstmt);
}
logger.debug("line 4444 of InsACSErvice.java reg id value is "+regID+"************");
return regID;
} // end getAC_REG
/**
* Classifies designated data element(s), called from servlet calls
* addRemoveACCSI to add or remove the selected cs and csi for each element.
* goes back to search results page
*
* @param desAction
* @throws Exception
*/
@SuppressWarnings("unchecked")
public void doSubmitDesDE(String desAction) throws Exception {
HttpSession session = m_classReq.getSession();
GetACSearch getAC = new GetACSearch(m_classReq, m_classRes, m_servlet);
DataManager.setAttribute(session, Session_Data.SESSION_STATUS_MESSAGE,
"");
Vector vACList = (Vector) session.getAttribute("vBEResult");
Vector<String> vACID = (Vector) session.getAttribute("vACId");
Vector<String> vNames = (Vector) session.getAttribute("vACName");
DE_Bean deBean = (DE_Bean) session.getAttribute("m_DE");
String sContextID = (String) m_classReq.getParameter("selContext");
Vector vContName = (Vector) session.getAttribute("vWriteContextDE");
Vector vContID = (Vector) session.getAttribute("vWriteContextDE_ID");
String sContext = m_util.getNameByID(vContName, vContID, sContextID);
if (vACList == null) {
vACList = new Vector();
vACID = new Vector<String>();
vACList.addElement(deBean);
vACID.addElement(deBean.getDE_DE_IDSEQ());
}
for (int k = 0; k < vACList.size(); k++) {
m_classReq.setAttribute("retcode", "");
DE_Bean thisDE = (DE_Bean) vACList.elementAt(k);
if (thisDE == null)
thisDE = new DE_Bean();
// store the ac name in the message
this.storeStatusMsg("Data Element Name : "
+ thisDE.getDE_LONG_NAME());
this.storeStatusMsg("Public ID : " + thisDE.getDE_MIN_CDE_ID());
String deID = thisDE.getDE_DE_IDSEQ();
String deName = thisDE.getDE_LONG_NAME();
String deCont = thisDE.getDE_CONTE_IDSEQ();
// add remove designated context
String desAct = this.addRemoveDesignation(deID, desAction, thisDE,
sContextID, sContext);
// add remove alternate names
String oneAlt = this.doAddRemoveAltNames(deID, deCont, desAction);
// add remove reference documents
String oneRD = this.doAddRemoveRefDocs(deID, deCont, desAction);
// insert and delete ac-csi relationship
SetACService setAC = new SetACService(m_servlet);
deBean = setAC.setDECSCSIfromPage(m_classReq, deBean);
Vector<AC_CSI_Bean> vAC_CS = deBean.getAC_AC_CSI_VECTOR();
Vector<AC_CSI_Bean> vRemove_ACCSI = getAC
.doCSCSI_ACSearch(deID, ""); // (Vector)session.getAttribute("vAC_CSI");
this.addRemoveACCSI(deID, vAC_CS, vRemove_ACCSI, vACID,
"designate", deName);
// refresh used by context in the search results list
GetACSearch serAC = new GetACSearch(m_classReq, m_classRes,
m_servlet);
serAC.refreshDesData(deID, sContext, sContextID, desAct, oneAlt,
oneRD);
// display success message if no error exists for each DE
String sReturn = (String) m_classReq.getAttribute("retcode");
if (sReturn == null || sReturn.equals(""))
this
.storeStatusMsg("\\t Successfully updated Used By Attributes");
}
}
/**
* to get one alternate name for the selected ac
*
* @param acID
* ac idseq
* @return altname from the database
*/
public String getOneAltName(String acID) {
ResultSet rs = null;
String sName = "";
PreparedStatement pstmt = null;
try {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
pstmt = m_servlet
.getConn()
.prepareStatement(
"Select SBREXT_CDE_CURATOR_PKG.GET_ONE_ALT_NAME(?) from DUAL");
pstmt.setString(1, acID); // acid
rs = pstmt.executeQuery();
while (rs.next()) {
sName = rs.getString(1);
}
}
} catch (Exception e) {
logger.error("ERROR in InsACService-getOneAltName for exception : "
+ e.toString(), e);
}finally{
rs = SQLHelper.closeResultSet(rs);
pstmt = SQLHelper.closePreparedStatement(pstmt);
}
return sName;
} // end getOneAltName
/**
* to get one reference documents for the selected ac
*
* @param acID
* ac idseq
* @return ref doc from the database
*/
public String getOneRDName(String acID) {
ResultSet rs = null;
String sName = "";
PreparedStatement pstmt = null;
try {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
pstmt = m_servlet
.getConn()
.prepareStatement(
"Select SBREXT_CDE_CURATOR_PKG.GET_ONE_RD_NAME(?) from DUAL");
pstmt.setString(1, acID); // acid
rs = pstmt.executeQuery();
while (rs.next()) {
sName = rs.getString(1);
}
}
} catch (Exception e) {
logger.error("ERROR in InsACService-getOneRDName for exception : "
+ e.toString(), e);
}finally{
rs = SQLHelper.closeResultSet(rs);
pstmt = SQLHelper.closePreparedStatement(pstmt);
}
return sName;
} // end getOneRDName
/**
* to get one concept name for the selected ac
*
* @param decID
* String dec idseq
* @param vdID
* String vd idseq
* @return altname from the database
*/
public String getOneConName(String decID, String vdID) {
ResultSet rs = null;
String sName = "";
PreparedStatement pstmt = null;
try {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
pstmt = m_servlet
.getConn()
.prepareStatement(
"Select SBREXT_CDE_CURATOR_PKG.GET_ONE_CON_NAME(?,?) from DUAL");
pstmt.setString(1, decID); // decid
pstmt.setString(2, vdID); // vdid
rs = pstmt.executeQuery();
while (rs.next()) {
sName = rs.getString(1);
}
}
} catch (Exception e) {
logger.error("ERROR in InsACService-getOneConName for exception : "
+ e.toString(), e);
}finally{
rs = SQLHelper.closeResultSet(rs);
pstmt = SQLHelper.closePreparedStatement(pstmt);
}return sName;
} // end getOneConName
/**
* submits to add or remove the designation for the selected ac Called from
* 'classifyde' method gets the 'desHashTable' table from the session and
* gets the desID using desContext and ACID.
*
* @param CompID
* String component ID
* @param desAction
* String designated submit action
* @param deBean
* DE_Bean Object
* @param useCont
* String context idseq
* @param useContName
* String context name
* @return String return code
*
* @throws Exception
*/
private String addRemoveDesignation(String CompID, String desAction,
DE_Bean deBean, String useCont, String useContName)
throws Exception {
HttpSession session = m_classReq.getSession();
// designate used by context if not exists before
String refreshAct = "";
Vector vUsedCont = (Vector) deBean.getDE_USEDBY_CONTEXT_ID();
String sLang = (String) m_classReq.getParameter("dispLanguage");
if (sLang == null || sLang.equals(""))
sLang = "ENGLISH";
if ((vUsedCont == null || !vUsedCont.contains(useCont))
&& desAction.equals("create")) {
String deCont = deBean.getDE_CONTE_IDSEQ();
// create usedby only if not in the same context as the ac is
if (!deCont.equals(useCont)) {
String sRet = this.setDES("INS", CompID, useCont, useContName,
"USED_BY", useContName, sLang, "");
if (sRet == null || sRet.equals("API_DES_300"))
refreshAct = "INS";
} else {
this
.storeStatusMsg("\\t API_DES_00: Unable to designate in the same context as the owned by context.");
m_classReq.setAttribute("retcode", "API_DES_00");
}
} else if (vUsedCont != null && vUsedCont.contains(useCont)
&& desAction.equals("remove")) {
Hashtable desTable = (Hashtable) session
.getAttribute("desHashTable");
String desID = (String) desTable.get(useContName + "," + CompID);
// call method to delete designation if desidseq is found
if (desID != null && !desID.equals("")) {
String sRet = this.setDES("DEL", CompID, useCont, useContName,
"USED_BY", useContName, sLang, desID);
if (sRet == null || sRet.equals("API_DES_300"))
refreshAct = "DEL";
}
}
return refreshAct;
}
/**
* To get public id of an administerd component. Called from 'set' methods.
* Uses the stored Proc call SBREXT_COMMON_ROUTINES.GET_PUBLIC_ID(?)}
*
* @param dec
* dec bean object
*
* @return String public ID.
*/
public String getDECSysName(DEC_Bean dec) {
ResultSet rs = null;
PreparedStatement pstmt = null;
String sysName = "";
try {
String ocIDseq = dec.getDEC_OCL_IDSEQ();
String propIDseq = dec.getDEC_PROPL_IDSEQ();
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
pstmt = m_servlet
.getConn()
.prepareStatement(
"Select SBREXT_COMMON_ROUTINES.GENERATE_DEC_PREFERRED_NAME(?,?) from DUAL");
pstmt.setString(1, ocIDseq); // oc idseq
pstmt.setString(2, propIDseq); // property idseq
rs = pstmt.executeQuery();
while (rs.next()) {
sysName = rs.getString(1);
}
if (sysName == null)
sysName = "";
if (sysName.equalsIgnoreCase("OC and PROP are null")
|| sysName.equalsIgnoreCase("Invalid Object")
|| sysName.equalsIgnoreCase("Invalid Property"))
sysName = "";
}
// }
} catch (Exception e) {
logger.error("ERROR in InsACService-getPublicID for exception : "
+ e.toString(), e);
}finally{
rs = SQLHelper.closeResultSet(rs);
pstmt = SQLHelper.closePreparedStatement(pstmt);
}
return sysName;
} // end getDEC system name
/**
* To get public id of an administerd component. Called from 'set' methods.
* Uses the stored Proc call SBREXT_COMMON_ROUTINES.GET_PUBLIC_ID(?)}
*
* @param ac_idseq
* unique id of an AC.
*
* @return String public ID.
*/
public String getPublicID(String ac_idseq) {
ResultSet rs = null;
PreparedStatement pstmt = null;
String sPublicID = "";
try {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
pstmt = m_servlet
.getConn()
.prepareStatement(
"Select SBREXT_COMMON_ROUTINES.GET_PUBLIC_ID(?) from DUAL");
pstmt.setString(1, ac_idseq); // short name
rs = pstmt.executeQuery();
while (rs.next()) {
Integer iPublic = new Integer(rs.getInt(1));
sPublicID = iPublic.toString();
}
}
} catch (Exception e) {
logger.error("ERROR in InsACService-getPublicID for exception : "
+ e.toString(), e);
}finally{
rs = SQLHelper.closeResultSet(rs);
pstmt = SQLHelper.closePreparedStatement(pstmt);
}
return sPublicID;
} // end getPublicID
@SuppressWarnings("unchecked")
private void doAltVersionUpdate(String newAC, String oldAC) {
HttpSession session = m_classReq.getSession();
GetACSearch getAC = new GetACSearch(m_classReq, m_classRes, m_servlet);
// first get the alt and ref for new version
Vector<ALT_NAME_Bean> vNewAlt = new Vector<ALT_NAME_Bean>();
Vector<ALT_NAME_Bean> vOldAlt = (Vector) session
.getAttribute("AllAltNameList");
// search if alt names exists before versioning
if (vOldAlt != null && vOldAlt.size() > 0)
vNewAlt = getAC.doAltNameSearch(newAC, "", "", "EditDesDE",
"Version");
// loop through the lists to find the old alt/ref matching ac and table
// id
if (vNewAlt != null) {
for (int i = 0; i < vOldAlt.size(); i++) {
ALT_NAME_Bean thisAlt = (ALT_NAME_Bean) vOldAlt.elementAt(i);
String altAC = thisAlt.getAC_IDSEQ();
// udpate the idseq if found
if (altAC.equals(oldAC)) {
thisAlt.setAC_IDSEQ(newAC);
// find the matching altname, context, alttype in new list
// to get altidseq
String altName = thisAlt.getALTERNATE_NAME();
if (altName == null)
altName = "";
String altCont = thisAlt.getCONTE_IDSEQ();
if (altCont == null)
altCont = "";
String altType = thisAlt.getALT_TYPE_NAME();
if (altType == null)
altType = "";
for (int k = 0; k < vNewAlt.size(); k++) {
ALT_NAME_Bean newAlt = (ALT_NAME_Bean) vNewAlt
.elementAt(k);
String nName = newAlt.getALTERNATE_NAME();
if (nName == null)
nName = "";
String nCont = newAlt.getCONTE_IDSEQ();
if (nCont == null)
nCont = "";
String nType = newAlt.getALT_TYPE_NAME();
if (nType == null)
nType = "";
// replace it in the bean if found
// System.out.println(nType + " new alts " + nName);
if (nName.equals(altName) && altCont.equals(nCont)
&& altType.equals(nType)) {
String altID = newAlt.getALT_NAME_IDSEQ();
if (altID != null && !altID.equals(""))
thisAlt.setALT_NAME_IDSEQ(altID);
break;
}
}
// update the bean and vector
vOldAlt.setElementAt(thisAlt, i);
}
}
// set it back in the session
DataManager.setAttribute(session, "AllAltNameList", vOldAlt);
}
}
/**
* @param newAC
* @param oldAC
*/
@SuppressWarnings( { "unchecked", "unchecked" })
private void doRefVersionUpdate(String newAC, String oldAC) {
HttpSession session = m_classReq.getSession();
GetACSearch getAC = new GetACSearch(m_classReq, m_classRes, m_servlet);
// first get the alt and ref for new version
Vector<REF_DOC_Bean> vNewRef = new Vector<REF_DOC_Bean>();
Vector<REF_DOC_Bean> vOldRef = (Vector) session
.getAttribute("AllRefDocList");
// search if Ref names exists before versioning
if (vOldRef != null && vOldRef.size() > 0)
vNewRef = getAC.doRefDocSearch(newAC, "ALL TYPES", "Version");
// loop through the lists to find the old Ref/ref matching ac and table
// id
if (vNewRef != null) {
for (int i = 0; i < vOldRef.size(); i++) {
REF_DOC_Bean thisRef = (REF_DOC_Bean) vOldRef.elementAt(i);
String RefAC = thisRef.getAC_IDSEQ();
// udpate the idseq if found
if (RefAC.equals(oldAC)) {
thisRef.setAC_IDSEQ(newAC);
// find the matching Refname, context, Reftype in new list
// to get Refidseq
String RefName = thisRef.getDOCUMENT_NAME();
if (RefName == null)
RefName = "";
String RefCont = thisRef.getCONTE_IDSEQ();
if (RefCont == null)
RefCont = "";
String RefType = thisRef.getDOC_TYPE_NAME();
if (RefType == null)
RefType = "";
for (int k = 0; k < vNewRef.size(); k++) {
REF_DOC_Bean newRef = (REF_DOC_Bean) vNewRef
.elementAt(k);
String nName = newRef.getDOCUMENT_NAME();
if (nName == null)
nName = "";
String nCont = newRef.getCONTE_IDSEQ();
if (nCont == null)
nCont = "";
String nType = newRef.getDOC_TYPE_NAME();
if (nType == null)
nType = "";
// System.out.println(nType + " new ref " + nName);
// replace it in the bean if found
if (nName.equals(RefName) && RefCont.equals(nCont)
&& RefType.equals(nType)) {
String RefID = newRef.getREF_DOC_IDSEQ();
if (RefID != null && !RefID.equals("")) {
thisRef.setREF_DOC_IDSEQ(RefID);
}
break;
}
}
// update the bean and vector
vOldRef.setElementAt(thisRef, i);
}
}
// set it back in the session
DataManager.setAttribute(session, "AllRefDocList", vOldRef);
}
}
/**
* add revove alternate name attributes for the selected ac loops through
* the list of selected types and looks for the matching ac calls setDES to
* create or insert according to the submit action
*
* @param sDE
* unique id of an AC.
* @param deCont
* owned by context id of the ac.
* @param desAction
* String designation action
* @return return one alt name after designation
*/
public String doAddRemoveAltNames(String sDE, String deCont,
String desAction) {
String oneAltName = "";
try {
HttpSession session = m_classReq.getSession();
String sCont = m_classReq.getParameter("selContext");
if (sCont == null)
sCont = "";
Vector vAllAltName = (Vector) session
.getAttribute("AllAltNameList");
if (vAllAltName == null)
vAllAltName = new Vector();
for (int i = 0; i < vAllAltName.size(); i++) {
ALT_NAME_Bean altNameBean = (ALT_NAME_Bean) vAllAltName
.elementAt(i);
if (altNameBean == null)
altNameBean = new ALT_NAME_Bean();
String altAC = altNameBean.getAC_IDSEQ();
// new de from owning context
if (altAC == null || altAC.equals("") || altAC.equals("new")
|| desAction.equals("INS"))
altAC = sDE;
// System.out.println(sDE + " add alt names AC " + altAC);
// remove it only for matching ac
if (altAC != null && sDE.equals(altAC)) {
String altContID = altNameBean.getCONTE_IDSEQ();
// new context from owning context
if (altContID == null || altContID.equals("")
|| altContID.equals("new"))
altContID = deCont;
if (desAction.equals("remove") && altContID != null
&& sCont != null && altContID.equals(sCont))
altNameBean.setALT_SUBMIT_ACTION("DEL");
// get other attributes
String altID = altNameBean.getALT_NAME_IDSEQ();
String altType = altNameBean.getALT_TYPE_NAME();
String altSubmit = altNameBean.getALT_SUBMIT_ACTION();
String altName = altNameBean.getALTERNATE_NAME();
String altContext = altNameBean.getCONTEXT_NAME();
String altLang = altNameBean.getAC_LANGUAGE();
// mark the new ones ins or upd according to add or remove
if (altID == null || altID.equals("")
|| altID.equals("new")) {
if (desAction.equals("remove")
|| altSubmit.equals("DEL"))
altSubmit = "UPD"; // mark new one as update so
// that it won't create
else
altSubmit = "INS";
}
String ret = "";
if (!altSubmit.equals("UPD")) // call method to create
// alternate name in the
// database
ret = this.setDES(altSubmit, altAC, altContID,
altContext, altType, altName, altLang, altID);
}
}
// get one alt name for the AC after ins or del actions
oneAltName = this.getOneAltName(sDE);
} catch (Exception e) {
logger.error(
"ERROR in InsACService-addRemoveAltNames for exception : "
+ e.toString(), e);
}
return oneAltName;
} // end doAddRemoveAltNames
/**
* add revove reference documents attributes for the selected ac loops
* through the list of selected types and looks for the matching ac calls
* setRD to create or insert according to the submit action
*
* @param sDE
* unique id of an AC.
* @param deCont
* owned by context id of the ac.
* @param desAction
* designation action
* @return String retun one ref doc
*/
public String doAddRemoveRefDocs(String sDE, String deCont, String desAction) {
String oneRD = "";
try {
HttpSession session = m_classReq.getSession();
String sCont = m_classReq.getParameter("selContext");
if (sCont == null)
sCont = "";
// get reference doc attributes
Vector vAllRefDoc = (Vector) session.getAttribute("AllRefDocList");
if (vAllRefDoc == null)
vAllRefDoc = new Vector();
for (int i = 0; i < vAllRefDoc.size(); i++) {
REF_DOC_Bean refDocBean = (REF_DOC_Bean) vAllRefDoc
.elementAt(i);
if (refDocBean == null)
refDocBean = new REF_DOC_Bean();
String refAC = refDocBean.getAC_IDSEQ();
// new de from owning context
if (refAC == null || refAC.equals("") || refAC.equals("new")
|| desAction.equals("INS"))
refAC = sDE;
if (refAC != null && sDE.equals(refAC)) {
// mark the all its alt names to be deleted if action is to
// undesignate
String refContID = refDocBean.getCONTE_IDSEQ();
// new context from owning context
if (refContID == null || refContID.equals("")
|| refContID.equals("new"))
refContID = deCont;
// System.out.println(deCont + " add refdocs context " +
// refContID);
if (desAction.equals("remove") && refContID != null
&& sCont != null && refContID.equals(sCont))
refDocBean.setREF_SUBMIT_ACTION("DEL");
String refID = refDocBean.getREF_DOC_IDSEQ();
String refType = refDocBean.getDOC_TYPE_NAME();
String refName = refDocBean.getDOCUMENT_NAME();
String refText = refDocBean.getDOCUMENT_TEXT();
String refURL = refDocBean.getDOCUMENT_URL();
String refSubmit = refDocBean.getREF_SUBMIT_ACTION();
String refContext = refDocBean.getCONTEXT_NAME();
String refLang = refDocBean.getAC_LANGUAGE();
if (refID == null || refID.equals("")
|| refID.equals("new")) {
if (desAction.equals("remove")
|| refSubmit.equals("DEL"))
refSubmit = "UPD"; // mark new one as update so
// that it won't create
else
refSubmit = "INS";
}
// check if creating used by in the same context as created
// DE
String ret = "";
if (!refSubmit.equals("UPD")) // call method to create
// reference documents in
// the database
{
// delete teh reference blobs before deleting the RD
if (refSubmit.equals("DEL")) {
RefDocAttachment RDAclass = new RefDocAttachment(
m_classReq, m_classRes, m_servlet);
String sMsg = RDAclass
.doDeleteAllAttachments(refID);
if (sMsg != null && !sMsg.equals(""))
this.storeStatusMsg("\\t" + sMsg);
}
// System.out.println(refName + " rd idseq " + refID);
ret = this.setRD(refSubmit, refName, refAC, refText,
refType, refURL, refContID, refID, refLang);
}
}
}
oneRD = this.getOneRDName(sDE); // get the one rd name for the ac
} catch (Exception e) {
logger.error(
"ERROR in InsACService-addRemoveRefDocs for exception : "
+ e.toString(), e);
}
return oneRD;
} // end doAddRemoveAltNames
/***************************************************************************
* / takes the thesaurus concept if meta was selected
*
* @param evsBean
* EVS_Bean of the selected concept
* @return EVS_Bean
*/
/*
* public EVS_Bean takeThesaurusConcept(EVS_Bean evsBean) { HttpSession
* session = m_classReq.getSession(); String sConceptName =
* evsBean.getLONG_NAME(); String sContextID = evsBean.getCONTE_IDSEQ(); //
* sConceptName = filterName(sConceptName, "js"); String sConceptDefinition =
* evsBean.getPREFERRED_DEFINITION(); if(sConceptDefinition.length()>30)
* sConceptDefinition = sConceptDefinition.substring(5,30); else
* if(sConceptDefinition.length()>20) sConceptDefinition =
* sConceptDefinition.substring(5,20); else
* if(sConceptDefinition.length()>15) sConceptDefinition =
* sConceptDefinition.substring(5,15); String sDefinition = ""; String sName =
* ""; try { GetACSearch getAC = new GetACSearch(m_classReq, m_classRes,
* m_servlet); EVSSearch evs = new EVSSearch(m_classReq, m_classRes,
* m_servlet); Vector vAC = new Vector(); DataManager.setAttribute(session,
* "creKeyword", sConceptName); //store it in the session before calling vAC =
* evs.doVocabSearch(vAC, sConceptName, "NCI_Thesarus", "Synonym", "", "",
* "Exclude", "", 100, false, -1, ""); // evs.do_EVSSearch(sConceptName,
* vAC, "NCI_Thesaurus", "Synonym", // "All Sources", 100, "termThesOnly",
* "Exclude", sContextID, -1); for(int i=0; i<(vAC.size()); i++) { EVS_Bean
* OCBean = new EVS_Bean(); OCBean = (EVS_Bean)vAC.elementAt(i); sName =
* OCBean.getLONG_NAME(); String sDefSource = OCBean.getEVS_DEF_SOURCE();
* String sConSource = OCBean.getEVS_CONCEPT_SOURCE(); sDefinition =
* OCBean.getPREFERRED_DEFINITION(); if(sDefinition.length()>30) sDefinition =
* sDefinition.substring(5,30); else if(sDefinition.length()>20) sDefinition =
* sDefinition.substring(5,20); else if(sDefinition.length()>15) sDefinition =
* sDefinition.substring(5,15); if(sName.equalsIgnoreCase(sConceptName)) {
* if(sDefinition.equalsIgnoreCase(sConceptDefinition)) return OCBean; } } }
* catch(Exception e) { logger.error("ERROR in
* InsACService-takeThesaurusConcep for other : " + e.toString()); } return
* evsBean; }
*/
/***************************************************************************
* / Puts in and takes out "_"
*
* @param String
* nodeName.
* @param String
* type.
*/
/*
* private final String filterName(String nodeName, String type) {
* if(type.equals("display")) nodeName = nodeName.replaceAll("_"," "); else
* if(type.equals("js")) nodeName = nodeName.replaceAll(" ","_"); return
* nodeName; }
*/
/**
* To insert a new concept from evs to cadsr. Gets all the attribute values
* from the bean, sets in parameters, and registers output parameter. Calls
* oracle stored procedure "{call
* SBREXT_Set_Row.SET_CONCEPT(?,?,?,?,?,?,?,?,?,?,?)}" to submit
*
* @param sAction
* Insert or update Action.
* @param sReturnCode
* string oracle error code
* @param evsBean
* EVS_Bean.
*
* @return String concept idseq from the table.
*/
public String setConcept(String sAction, String sReturnCode,
EVS_Bean evsBean) {
ResultSet rs = null;
CallableStatement cstmt = null;
HttpSession session = m_classReq.getSession();
String conIdseq = "";
try {
// If the concept is from Metathesaurus, try to take it from
// Thesaurus
/*
* if(evsBean != null && evsBean.getEVS_DATABASE() != null) {
* if(evsBean.getEVS_DATABASE().equals("NCI Metathesaurus")) {
* sEvsSource = evsBean.getEVS_DEF_SOURCE(); if(sEvsSource == null)
* sEvsSource = ""; if(sEvsSource.equalsIgnoreCase("NCI-Gloss") ||
* sEvsSource.equalsIgnoreCase("NCI04")) evsBean =
* takeThesaurusConcept(evsBean); logger.info("after takeThes " +
* evsBean.getCONCEPT_IDENTIFIER()); } }
*/
// return the concept id if the concept alredy exists in caDSR.
conIdseq = this.getConcept(sReturnCode, evsBean, false);
if (conIdseq == null || conIdseq.equals("")) {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
// cstmt = conn.prepareCall("{call
// SBREXT_SET_ROW.SET_CONCEPT(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}");
cstmt = m_servlet
.getConn()
.prepareCall(
"{call SBREXT_SET_ROW.SET_CONCEPT(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}");
// register the Out parameters
cstmt.registerOutParameter(2, java.sql.Types.VARCHAR); // return
// code
cstmt.registerOutParameter(4, java.sql.Types.VARCHAR); // con
// idseq
cstmt.registerOutParameter(5, java.sql.Types.VARCHAR); // preferred
// name
cstmt.registerOutParameter(6, java.sql.Types.VARCHAR); // long
// name
cstmt.registerOutParameter(7, java.sql.Types.VARCHAR); // prefered
// definition
cstmt.registerOutParameter(8, java.sql.Types.VARCHAR); // context
// idseq
cstmt.registerOutParameter(9, java.sql.Types.VARCHAR); // version
cstmt.registerOutParameter(10, java.sql.Types.VARCHAR); // asl
// name
cstmt.registerOutParameter(11, java.sql.Types.VARCHAR); // latest
// version
// ind
cstmt.registerOutParameter(12, java.sql.Types.VARCHAR); // change
// note
cstmt.registerOutParameter(13, java.sql.Types.VARCHAR); // origin
cstmt.registerOutParameter(14, java.sql.Types.VARCHAR); // definition
// source
cstmt.registerOutParameter(15, java.sql.Types.VARCHAR); // evs
// source
cstmt.registerOutParameter(16, java.sql.Types.VARCHAR); // begin
// date
cstmt.registerOutParameter(17, java.sql.Types.VARCHAR); // end
// date
cstmt.registerOutParameter(18, java.sql.Types.VARCHAR); // date
// created
cstmt.registerOutParameter(19, java.sql.Types.VARCHAR); // created
// by
cstmt.registerOutParameter(20, java.sql.Types.VARCHAR); // date
// modified
cstmt.registerOutParameter(21, java.sql.Types.VARCHAR); // modified
// by
cstmt.registerOutParameter(22, java.sql.Types.VARCHAR); // deleted
// ind
// truncate the definition to be 2000 long.
String sDef = evsBean.getPREFERRED_DEFINITION();
// if (sDef == null) sDef = "";
// if (sDef.length() > 2000) sDef = sDef.substring(0, 2000);
// Set the In parameters (which are inherited from the
// PreparedStatement class)
// Get the username from the session.
String userName = (String) session.getAttribute("Username");
cstmt.setString(1, userName); // set ua_name
cstmt.setString(3, sAction);
cstmt.setString(5, evsBean.getCONCEPT_IDENTIFIER());
// make sure that :: is removed from the long name
String sName = evsBean.getLONG_NAME();
int nvpInd = sName.indexOf("::");
if (nvpInd > 0)
sName = sName.substring(0, nvpInd);
nvpInd = sDef.indexOf("::");
if (nvpInd > 0)
sDef = sDef.substring(0, nvpInd);
cstmt.setString(6, sName);
cstmt.setString(7, sDef);
// cstmt.setString(7, evsBean.getCONTE_IDSEQ()); caBIG by
// default
cstmt.setString(9, "1.0");
cstmt.setString(10, "RELEASED");
cstmt.setString(11, "Yes");
cstmt.setString(13, evsBean.getEVS_DATABASE());
cstmt.setString(14, evsBean.getEVS_DEF_SOURCE());
cstmt.setString(15, evsBean.getNCI_CC_TYPE());
// Now we are ready to call the stored procedure
// logger.info("setConcept " +
// evsBean.getCONCEPT_IDENTIFIER());
cstmt.execute();
sReturnCode = cstmt.getString(2);
conIdseq = cstmt.getString(4);
evsBean.setIDSEQ(conIdseq);
if (sReturnCode != null) {
this.storeStatusMsg("\\t " + sReturnCode
+ " : Unable to update Concept attributes - "
+ evsBean.getCONCEPT_IDENTIFIER() + ": "
+ evsBean.getLONG_NAME() + ".");
m_classReq.setAttribute("retcode", sReturnCode); // store
// returncode
// in
// request
// to
// track
// it
// all
// through
// this
// request
}
}
}
} catch (Exception e) {
logger.error("ERROR in InsACService-setConcept for other : "
+ e.toString(), e);
m_classReq.setAttribute("retcode", "Exception");
this
.storeStatusMsg("\\t Exception : Unable to update Concept attributes.");
}finally{
rs = SQLHelper.closeResultSet(rs);
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
return conIdseq;
} // end concept
/**
* Called to check if the concept exists in teh database already. Sets in
* parameters, and registers output parameters and returns concept id of
* found one. Calls oracle stored procedure "{call
* SBREXT_GET_ROW.GET_CON(?,?,?,?,?,?,?,?,?,?,?,?,?)}" to submit
*
* @param sReturn
* return code to catpure errors if any
* @param evsBean
* EVS_Bean.
* @param bValidateConceptCodeUnique
* boolean to check if unique
*
* @return String con_idseq from the stored procedure call.
*/
public String getConcept(String sReturn, EVS_Bean evsBean,
boolean bValidateConceptCodeUnique) {
ResultSet rs = null;
String sCON_IDSEQ = "";
CallableStatement cstmt = null;
try {
HttpSession session = (HttpSession) m_classReq.getSession();
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
cstmt = m_servlet
.getConn()
.prepareCall(
"{call SBREXT_GET_ROW.GET_CON(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}");
cstmt.registerOutParameter(1, java.sql.Types.VARCHAR); // return
// code
cstmt.registerOutParameter(2, java.sql.Types.VARCHAR); // con
// idseq
cstmt.registerOutParameter(3, java.sql.Types.VARCHAR); // preferred
// name
cstmt.registerOutParameter(4, java.sql.Types.VARCHAR); // context
// idseq
cstmt.registerOutParameter(5, java.sql.Types.VARCHAR); // version
cstmt.registerOutParameter(6, java.sql.Types.VARCHAR); // prefered
// definition
cstmt.registerOutParameter(7, java.sql.Types.VARCHAR); // long
// name
cstmt.registerOutParameter(8, java.sql.Types.VARCHAR); // asl
// name
cstmt.registerOutParameter(9, java.sql.Types.VARCHAR); // definition
// source
cstmt.registerOutParameter(10, java.sql.Types.VARCHAR); // latest
// version
// ind
cstmt.registerOutParameter(11, java.sql.Types.VARCHAR); // evs
// source
cstmt.registerOutParameter(12, java.sql.Types.VARCHAR); // CON
// ID
cstmt.registerOutParameter(13, java.sql.Types.VARCHAR); // origin
cstmt.registerOutParameter(14, java.sql.Types.VARCHAR); // begin
// date
cstmt.registerOutParameter(15, java.sql.Types.VARCHAR); // end
// date
cstmt.registerOutParameter(16, java.sql.Types.VARCHAR); // change
// note
cstmt.registerOutParameter(17, java.sql.Types.VARCHAR); // created
// by
cstmt.registerOutParameter(18, java.sql.Types.VARCHAR); // date
// created
cstmt.registerOutParameter(19, java.sql.Types.VARCHAR); // modified
// by
cstmt.registerOutParameter(20, java.sql.Types.VARCHAR); // date
// modified
cstmt.registerOutParameter(21, java.sql.Types.VARCHAR); // deleted
// ind
cstmt.setString(2, evsBean.getIDSEQ()); // con idseq
cstmt.setString(3, evsBean.getCONCEPT_IDENTIFIER()); // concept
logger.debug("EVS Bean at Line 5252 of InsACService.java IDSEQ"+evsBean.getIDSEQ()+"CONCEPT_IDENTIFIER"+evsBean.getCONCEPT_IDENTIFIER());
// code
// Now we are ready to call the stored procedure
cstmt.execute();
sCON_IDSEQ = (String) cstmt.getObject(2);
evsBean.setIDSEQ(sCON_IDSEQ);
sReturn = (String) cstmt.getObject(1);
if (sReturn == null || sReturn.equals("")) {
// Sometimes we use this method to validate a concept code
// is unique across databases
if (bValidateConceptCodeUnique == true) {
String dbOrigin = (String) cstmt.getObject(13);
String evsOrigin = evsBean.getEVS_DATABASE();
if (evsOrigin.equals(EVSSearch.META_VALUE)) // "MetaValue"))
evsOrigin = evsBean.getEVS_ORIGIN();
if (dbOrigin != null && evsOrigin != null
&& !dbOrigin.equals(evsOrigin)) {
sCON_IDSEQ = "Another Concept Exists in caDSR with same Concept Code "
+ evsBean.getCONCEPT_IDENTIFIER()
+ ", but in a different Vocabulary ("
+ dbOrigin
+ "). New concept therefore cannot be created. Please choose another concept. <br>";
}
} else {
String dbOrigin = (String) cstmt.getObject(13);
EVS_UserBean eUser = (EVS_UserBean) m_servlet.sessionData.EvsUsrBean; // (EVS_UserBean)session.getAttribute(EVSSearch.EVS_USER_BEAN_ARG);
// //("EvsUserBean");
if (eUser == null)
eUser = new EVS_UserBean();
String sDef = (String) cstmt.getObject(6);
if (sDef == null || sDef.equals(""))
sDef = eUser.getDefDefaultValue();
EVS_Bean vmConcept = new EVS_Bean();
String evsOrigin = vmConcept.getVocabAttr(eUser,
dbOrigin, EVSSearch.VOCAB_DBORIGIN,
EVSSearch.VOCAB_NAME); // "vocabDBOrigin",
evsBean.setEVSBean(sDef, (String) cstmt.getObject(9),
(String) cstmt.getObject(7), (String) cstmt
.getObject(7), (String) cstmt
.getObject(11), (String) cstmt
.getObject(3), evsOrigin, dbOrigin, 0,
"", (String) cstmt.getObject(4), "",
(String) cstmt.getObject(8), "", "", "");
evsBean.markNVPConcept(evsBean, session); // store
// name
// value
// pair
}
}
}
} catch (Exception e) {
logger.error("ERROR in InsACService- getConcept for exception : "
+ e.toString(), e);
}finally{
rs = SQLHelper.closeResultSet(rs);
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
return sCON_IDSEQ; // TODO check what is parent concept id
} // end get concept
/**
* handles add remove actionof the vd.
*
* @param vd
* page vd bean
* @return string comma delimited conidseqs or remove parent string
* @throws java.lang.Exception
*/
private String setEVSParentConcept(VD_Bean vd) throws Exception {
Vector<EVS_Bean> vParentCon = vd.getReferenceConceptList(); // (Vector)session.getAttribute("VDParentConcept");
if (vParentCon == null)
vParentCon = new Vector<EVS_Bean>();
String sVDParent = "", sVDCondr = "";
for (int m = 0; m < vParentCon.size(); m++) {
sVDCondr = vd.getVD_PAR_CONDR_IDSEQ();
EVS_Bean parBean = (EVS_Bean) vParentCon.elementAt(m);
// if not deleted, create and append them one by one
if (parBean != null) {
// handle the only evs parent
if (parBean.getEVS_DATABASE() == null)
logger
.error("setEVSParentConcept - parent why database null?");
else if (!parBean.getEVS_DATABASE().equals("Non_EVS")) {
if (!parBean.getCON_AC_SUBMIT_ACTION().equals("DEL")) {
String sRet = "";
parBean.setCONTE_IDSEQ(vd.getVD_CONTE_IDSEQ());
String conIDseq = parBean.getIDSEQ();
// create it only if doesn't exist
if (conIDseq == null || conIDseq.equals(""))
conIDseq = this.setConcept("INS", sRet, parBean);
if (conIDseq != null && !conIDseq.equals("")) {
parBean.setIDSEQ(conIDseq);
vParentCon.setElementAt(parBean, m);
if (sVDParent.equals(""))
sVDParent = conIDseq;
else
sVDParent = sVDParent + "," + conIDseq;
}
} else if (sVDCondr == null)
sVDCondr = parBean.getCONDR_IDSEQ();
if (parBean.getCON_AC_SUBMIT_ACTION().equals("DEL")) {
if (parBean.getEVS_DATABASE() != null
&& parBean.getEVS_DATABASE().equals(
"NCI Metathesaurus"))
doRemoveMetaParentRefDoc(vd, parBean);
}
}
}
}
vd.setReferenceConceptList(vParentCon);
if (sVDParent.equals("") && sVDCondr != null && !sVDCondr.equals(""))
sVDParent = "removeParent";
return sVDParent;
} // end evs parent concept
/**
* removes the meta parent concept filter source from reference documents
*
* @param vd
* page vd bean
* @param parBean
* selected meta parent bean
* @throws java.lang.Exception
*/
private void doRemoveMetaParentRefDoc(VD_Bean vd, EVS_Bean parBean)
throws Exception {
String sCont = vd.getVD_CONTE_IDSEQ();
String sACid = vd.getVD_VD_IDSEQ();
String sCuiVal = parBean.getCONCEPT_IDENTIFIER();
String rdIDseq = "";
String sMetaSource = parBean.getEVS_CONCEPT_SOURCE();
if (sMetaSource == null)
sMetaSource = "";
String sRDMetaCUI = "";
GetACSearch getAC = new GetACSearch(m_classReq, m_classRes, m_servlet);
Vector vRef = getAC.doRefDocSearch(vd.getVD_VD_IDSEQ(),
"META_CONCEPT_SOURCE", "open");
Vector vList = (Vector) m_classReq.getAttribute("RefDocList");
if (vList != null && vList.size() > 0) {
for (int i = 0; i < vList.size(); i++) {
REF_DOC_Bean RDBean = (REF_DOC_Bean) vList.elementAt(i);
// copy rd attributes to evs attribute
if (RDBean != null && RDBean.getDOCUMENT_NAME() != null
&& !RDBean.getDOCUMENT_NAME().equals("")) {
sRDMetaCUI = RDBean.getDOCUMENT_TEXT();
if (sRDMetaCUI.equals(sCuiVal))
rdIDseq = RDBean.getREF_DOC_IDSEQ();
}
}
}
String sAction = parBean.getCON_AC_SUBMIT_ACTION();
if (sAction == null || sAction.equals(""))
sAction = "INS";
String sRet = "";
String sLang = "ENGLISH";
if (rdIDseq != null && !rdIDseq.equals("")) {
sRet = this.setRD("DEL", sMetaSource, sACid, sCuiVal,
"META_CONCEPT_SOURCE", "", sCont, rdIDseq, sLang);
}
}
/**
* creates non evs parents
*
* @param vd
* current VD_Bean
* @return returns success message
* @throws java.lang.Exception
*/
@SuppressWarnings("unchecked")
private String setNonEVSParentConcept(VD_Bean vd) throws Exception {
HttpSession session = m_classReq.getSession();
Vector vParentCon = vd.getReferenceConceptList(); // (Vector)session.getAttribute("VDParentConcept");
if (vParentCon == null)
vParentCon = new Vector();
String sRet = "";
String sLang = "ENGLISH";
for (int m = 0; m < vParentCon.size(); m++) {
EVS_Bean parBean = (EVS_Bean) vParentCon.elementAt(m);
// if not deleted, create and append them one by one
if (parBean != null) {
// handle the add/remove of non evs parent
if (parBean.getEVS_DATABASE() == null)
logger.error("setNonEVSParentConcept - why no database?");
else if (parBean.getEVS_DATABASE().equals("Non_EVS")) {
String sCont = vd.getVD_CONTE_IDSEQ();
String sACid = vd.getVD_VD_IDSEQ();
String sName = parBean.getLONG_NAME();
String sDoc = parBean.getPREFERRED_DEFINITION();
String sType = parBean.getCONCEPT_IDENTIFIER();
String sURL = parBean.getEVS_DEF_SOURCE();
String rdIDseq = parBean.getIDSEQ();
String sAction = parBean.getCON_AC_SUBMIT_ACTION();
if (sAction == null || sAction.equals(""))
sAction = "INS";
// do not delete if not existed in cadsr already
if (sAction.equals("DEL")
&& (rdIDseq == null || rdIDseq.equals("")))
continue;
// mark it to delete to be deleted later with all other
// reference documents to avoid duplicate deletion.
if (sAction.equals("DEL")) {
Vector<REF_DOC_Bean> vRefDocs = (Vector) session
.getAttribute("AllRefDocList");
for (int i = 0; i < vRefDocs.size(); i++) {
REF_DOC_Bean rBean = (REF_DOC_Bean) vRefDocs
.elementAt(i);
String refID = rBean.getREF_DOC_IDSEQ();
if (refID != null
&& refID.equalsIgnoreCase(rdIDseq)) {
rBean.setREF_SUBMIT_ACTION("DEL");
vRefDocs.setElementAt(rBean, i);
DataManager.setAttribute(session,
"AllRefDocList", vRefDocs);
break;
}
}
} else if (!sAction.equals("UPD"))
sRet = this.setRD(sAction, sName, sACid, sDoc, sType,
sURL, sCont, rdIDseq, sLang);
}
}
}
return sRet;
} // non evs parent concept
/**
* creates filtered concept source for the meta parent
*
* @param vd
* VD_Bean
* @return string success message
* @throws java.lang.Exception
*/
private String setRDMetaConceptSource(VD_Bean vd) throws Exception {
// HttpSession session = m_classReq.getSession();
Vector vParentCon = vd.getReferenceConceptList(); // (Vector)session.getAttribute("VDParentConcept");
if (vParentCon == null)
vParentCon = new Vector();
String sRet = "";
for (int m = 0; m < vParentCon.size(); m++) {
EVS_Bean parBean = (EVS_Bean) vParentCon.elementAt(m);
// if not deleted, create and append them one by one
if (parBean != null) {
// handle the add/remove of non evs parent
if (parBean.getEVS_DATABASE() == null)
logger.error("setRDMetaConceptSource - why no database?");
else if (parBean.getEVS_DATABASE() != null
&& parBean.getEVS_DATABASE()
.equals("NCI Metathesaurus")) {
String sCont = vd.getVD_CONTE_IDSEQ();
String sACid = vd.getVD_VD_IDSEQ();
String sCuiVal = parBean.getCONCEPT_IDENTIFIER();
String sMetaSource = parBean.getEVS_CONCEPT_SOURCE();
if (sMetaSource == null)
sMetaSource = "";
String rdIDseq = null; // parBean.getIDSEQ();
String sAction = parBean.getCON_AC_SUBMIT_ACTION();
if (sAction == null || sAction.equals(""))
sAction = "INS";
String sLang = "ENGLISH";
if (sAction.equals("INS") && !sMetaSource.equals("")
&& !sMetaSource.equals("All Sources")
&& !sCuiVal.equals("")) {
sRet = this.setRD("INS", sMetaSource, sACid, sCuiVal,
"META_CONCEPT_SOURCE", "", sCont, rdIDseq,
sLang);
}
}
}
}
return sRet;
} // non evs parent concept
// store the contact related info into the database
private Hashtable<String, AC_CONTACT_Bean> addRemoveAC_Contacts(
Hashtable<String, AC_CONTACT_Bean> hConts, String acID, String acAct) {
try {
// loop through the contacts in the hash table
if (hConts != null) {
Enumeration enum1 = hConts.keys();
while (enum1.hasMoreElements()) {
String sName = (String) enum1.nextElement();
AC_CONTACT_Bean acc = (AC_CONTACT_Bean) hConts.get(sName);
if (acc == null)
acc = new AC_CONTACT_Bean();
String conSubmit = acc.getACC_SUBMIT_ACTION();
if (conSubmit == null || conSubmit.equals(""))
conSubmit = "INS";
// for new version or new AC, make it a new record if not
// deleted
if (acAct.equalsIgnoreCase("Version")
|| acAct.equalsIgnoreCase("New")) {
if (conSubmit.equals("DEL"))
conSubmit = "NONE"; // do not add the deleted ones
else
conSubmit = "INS";
}
// check if contact attributes has changed
if (!conSubmit.equals("NONE")) {
acc.setAC_IDSEQ(acID);
acc.setACC_SUBMIT_ACTION(conSubmit);
String sOrgID = acc.getORG_IDSEQ();
String sPerID = acc.getPERSON_IDSEQ();
// call method to do contact comm updates
Vector<AC_COMM_Bean> vComms = acc.getACC_COMM_List();
if (vComms != null)
acc.setACC_COMM_List(this.setContact_Comms(vComms,
sOrgID, sPerID));
// call method to do contact addr update
Vector<AC_ADDR_Bean> vAddrs = acc.getACC_ADDR_List();
if (vAddrs != null)
acc.setACC_ADDR_List(this.setContact_Addrs(vAddrs,
sOrgID, sPerID));
// call method to do contact attribute updates
acc = this.setAC_Contact(acc);
hConts.put(sName, acc);
}
}
}
} catch (Exception e) {
logger.error("Error - setAC_Contacts : " + e.toString(), e);
}
return hConts;
}
private Vector<AC_COMM_Bean> setContact_Comms(Vector<AC_COMM_Bean> vCom,
String orgID, String perID) {
ResultSet rs = null;
CallableStatement cstmt = null;
HttpSession session = m_classReq.getSession();
String sReturnCode = "";
try {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
for (int i = 0; i < vCom.size(); i++) {
try {
AC_COMM_Bean comBean = (AC_COMM_Bean) vCom.elementAt(i);
String sAction = "INS";
if (comBean != null)
sAction = comBean.getCOMM_SUBMIT_ACTION();
if (!sAction.equals("NONE")) {
// cstmt = conn.prepareCall("{call
// SBREXT_Set_Row.SET_CONTACT_COMM(?,?,?,?,?,?,?,?,?,?,?,?,?)}");
cstmt = m_servlet
.getConn()
.prepareCall(
"{call SBREXT_SET_ROW.SET_CONTACT_COMM(?,?,?,?,?,?,?,?,?,?,?,?,?)}");
cstmt.registerOutParameter(2,
java.sql.Types.VARCHAR); // return code
cstmt.registerOutParameter(4,
java.sql.Types.VARCHAR); // comm idseq
cstmt.registerOutParameter(5,
java.sql.Types.VARCHAR); // org idseq
cstmt.registerOutParameter(6,
java.sql.Types.VARCHAR); // per idseq
cstmt.registerOutParameter(7,
java.sql.Types.VARCHAR); // ctlname
cstmt.registerOutParameter(8,
java.sql.Types.VARCHAR); // rank order
cstmt.registerOutParameter(9,
java.sql.Types.VARCHAR); // cyber address
cstmt.registerOutParameter(10, java.sql.Types.DATE); // .VARCHAR);
// //created
// by
cstmt.registerOutParameter(11,
java.sql.Types.VARCHAR); // date created
cstmt.registerOutParameter(12, java.sql.Types.DATE); // .VARCHAR);
// //modified
// by
cstmt.registerOutParameter(13,
java.sql.Types.VARCHAR); // date modified
// Set the In parameters (which are inherited from
// the PreparedStatement class)
// Get the username from the session.
String userName = (String) session
.getAttribute("Username");
cstmt.setString(1, userName); // set ua_name
if ((sAction.equals("UPD"))
|| (sAction.equals("DEL"))) {
if ((comBean.getAC_COMM_IDSEQ() != null)
&& (!comBean.getAC_COMM_IDSEQ().equals(
"")))
cstmt.setString(4, comBean
.getAC_COMM_IDSEQ()); // comm
// idseq if
// updated
else
sAction = "INS"; // INSERT A NEW RECORD
// IF NOT EXISTED
}
cstmt.setString(3, sAction); // ACTION - INS, UPD
// or DEL
cstmt.setString(5, orgID); // org idseq
cstmt.setString(6, perID); // per idseq
cstmt.setString(7, comBean.getCTL_NAME()); // selected
// comm
// type
cstmt.setString(8, comBean.getRANK_ORDER()); // rank
// order
// for
// the
// comm
cstmt.setString(9, comBean.getCYBER_ADDR()); // comm
// value
// Now we are ready to call the stored procedure
cstmt.execute();
sReturnCode = cstmt.getString(2);
if (sReturnCode != null && !sReturnCode.equals("")) // &&
// !sReturnCode.equals("API_OC_500"))
{
String comName = comBean.getCTL_NAME() + "_"
+ comBean.getRANK_ORDER() + "_"
+ comBean.getCYBER_ADDR();
this
.storeStatusMsg(sReturnCode
+ " : Unable to update contact communication - "
+ comName);
m_classReq.setAttribute("retcode", sReturnCode);
} else {
comBean.setAC_COMM_IDSEQ(cstmt.getString(4));
comBean.setCOMM_SUBMIT_ACTION("NONE");
vCom.setElementAt(comBean, i);
}
}
} catch (Exception ee) {
logger.error(
"ERROR in InsACService-setContact_Comms for bean : "
+ ee.toString(), ee);
m_classReq.setAttribute("retcode", "Exception");
this
.storeStatusMsg("\\t Exception ee : Unable to update or remove Communication attributes.");
continue; // continue with other ones
}
}
}
} catch (Exception e) {
logger.error("Error - setContact_Comms : " + e.toString(), e);
}
finally{
rs = SQLHelper.closeResultSet(rs);
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
return vCom;
}
private Vector<AC_ADDR_Bean> setContact_Addrs(Vector<AC_ADDR_Bean> vAdr,
String orgID, String perID) {
ResultSet rs = null;
CallableStatement cstmt = null;
HttpSession session = m_classReq.getSession();
String sReturnCode = "";
try {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
for (int i = 0; i < vAdr.size(); i++) {
try {
AC_ADDR_Bean adrBean = (AC_ADDR_Bean) vAdr.elementAt(i);
String sAction = "INS";
if (adrBean != null)
sAction = adrBean.getADDR_SUBMIT_ACTION();
if (!sAction.equals("NONE")) {
// cstmt = conn.prepareCall("{call
// SBREXT_Set_Row.SET_CONTACT_ADDR(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}");
cstmt = m_servlet
.getConn()
.prepareCall(
"{call SBREXT_SET_ROW.SET_CONTACT_ADDR(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}");
cstmt.registerOutParameter(2,
java.sql.Types.VARCHAR); // return code
cstmt.registerOutParameter(4,
java.sql.Types.VARCHAR); // addr idseq
cstmt.registerOutParameter(5,
java.sql.Types.VARCHAR); // org idseq
cstmt.registerOutParameter(6,
java.sql.Types.VARCHAR); // per idseq
cstmt.registerOutParameter(7,
java.sql.Types.VARCHAR); // atlname
cstmt.registerOutParameter(8,
java.sql.Types.VARCHAR); // rank order
cstmt.registerOutParameter(9,
java.sql.Types.VARCHAR); // address line
// 1
cstmt.registerOutParameter(10,
java.sql.Types.VARCHAR); // address line
// 2
cstmt.registerOutParameter(11,
java.sql.Types.VARCHAR); // city
cstmt.registerOutParameter(12,
java.sql.Types.VARCHAR); // state
cstmt.registerOutParameter(13,
java.sql.Types.VARCHAR); // postal code
cstmt.registerOutParameter(14,
java.sql.Types.VARCHAR); // country
cstmt.registerOutParameter(15, java.sql.Types.DATE); // .VARCHAR);
// //created
// by
cstmt.registerOutParameter(16,
java.sql.Types.VARCHAR); // date created
cstmt.registerOutParameter(17, java.sql.Types.DATE); // .VARCHAR);
// //modified
// by
cstmt.registerOutParameter(18,
java.sql.Types.VARCHAR); // date modified
// Set the In parameters (which are inherited from
// the PreparedStatement class)
// Get the username from the session.
String userName = (String) session
.getAttribute("Username");
cstmt.setString(1, userName); // set ua_name
if ((sAction.equals("UPD"))
|| (sAction.equals("DEL"))) {
if ((adrBean.getAC_ADDR_IDSEQ() != null)
&& (!adrBean.getAC_ADDR_IDSEQ().equals(
"")))
cstmt.setString(4, adrBean
.getAC_ADDR_IDSEQ()); // comm
// idseq if
// updated
else
sAction = "INS"; // INSERT A NEW RECORD
// IF NOT EXISTED
}
cstmt.setString(3, sAction); // ACTION - INS, UPD
// or DEL
cstmt.setString(5, orgID); // org idseq
cstmt.setString(6, perID); // per idseq
cstmt.setString(7, adrBean.getATL_NAME()); // selected
// addr
// type
cstmt.setString(8, adrBean.getRANK_ORDER()); // rank
// order
// for
// the
// addr
cstmt.setString(9, adrBean.getADDR_LINE1()); // addr
// line
// 1
String A2 = adrBean.getADDR_LINE2();
if (A2 == null || A2.equals(""))
A2 = " ";
cstmt.setString(10, A2); // addr line 2
cstmt.setString(11, adrBean.getCITY()); // city
cstmt.setString(12, adrBean.getSTATE_PROV()); // state
cstmt.setString(13, adrBean.getPOSTAL_CODE()); // zip
// code
String Ct = adrBean.getCOUNTRY();
if (Ct == null || Ct.equals(""))
Ct = " ";
cstmt.setString(14, Ct); // country
// Now we are ready to call the stored procedure
cstmt.execute();
sReturnCode = cstmt.getString(2);
if (sReturnCode != null && !sReturnCode.equals("")) // &&
// !sReturnCode.equals("API_OC_500"))
{
String adrName = adrBean.getATL_NAME() + "_"
+ adrBean.getRANK_ORDER() + "_"
+ adrBean.getADDR_LINE1();
this
.storeStatusMsg(sReturnCode
+ " : Unable to update contact address - "
+ adrName);
m_classReq.setAttribute("retcode", sReturnCode);
} else {
adrBean.setAC_ADDR_IDSEQ(cstmt.getString(4));
adrBean.setADDR_SUBMIT_ACTION("NONE");
vAdr.setElementAt(adrBean, i);
}
}
} catch (Exception ee) {
logger.error(
"ERROR in InsACService-setContact_Addrs for bean : "
+ ee.toString(), ee);
m_classReq.setAttribute("retcode", "Exception");
this
.storeStatusMsg("\\t Exception ee : Unable to update or remove Address attributes.");
continue; // continue with other ones
}
}
}
} catch (Exception e) {
logger.error("Error - setContact_Addrs : " + e.toString(), e);
m_classReq.setAttribute("retcode", "Exception");
this
.storeStatusMsg("\\t Exception ee : Unable to update or remove Address attributes.");
}finally{
rs = SQLHelper.closeResultSet(rs);
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
return vAdr;
}
private AC_CONTACT_Bean setAC_Contact(AC_CONTACT_Bean accB) {
ResultSet rs = null;
CallableStatement cstmt = null;
HttpSession session = m_classReq.getSession();
String sReturnCode = "";
try {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
String sAction = accB.getACC_SUBMIT_ACTION();
if (sAction == null || sAction.equals(""))
sAction = "INS";
if (!sAction.equals("NONE")) {
// cstmt = conn.prepareCall("{call
// SBREXT_Set_Row.SET_AC_CONTACT(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}");
cstmt = m_servlet
.getConn()
.prepareCall(
"{call SBREXT_SET_ROW.SET_AC_CONTACT(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}");
cstmt.registerOutParameter(2, java.sql.Types.VARCHAR); // return
// code
cstmt.registerOutParameter(4, java.sql.Types.VARCHAR); // comm
// idseq
cstmt.registerOutParameter(5, java.sql.Types.VARCHAR); // org
// idseq
cstmt.registerOutParameter(6, java.sql.Types.VARCHAR); // per
// idseq
cstmt.registerOutParameter(7, java.sql.Types.VARCHAR); // AC
// idseq
cstmt.registerOutParameter(8, java.sql.Types.VARCHAR); // rank
// order
cstmt.registerOutParameter(9, java.sql.Types.DATE); // .VARCHAR);
// //created
// by
cstmt.registerOutParameter(10, java.sql.Types.VARCHAR); // date
// created
cstmt.registerOutParameter(11, java.sql.Types.DATE); // .VARCHAR);
// //modified
// by
cstmt.registerOutParameter(12, java.sql.Types.VARCHAR); // date
// modified
cstmt.registerOutParameter(13, java.sql.Types.VARCHAR); // p_cscsi_idseq
cstmt.registerOutParameter(14, java.sql.Types.VARCHAR); // p_csi_idseq
cstmt.registerOutParameter(15, java.sql.Types.VARCHAR); // p_contact
// role
// Set the In parameters (which are inherited from the
// PreparedStatement class)
// Get the username from the session.
String userName = (String) session.getAttribute("Username");
cstmt.setString(1, userName); // set ua_name
if ((sAction.equals("UPD")) || (sAction.equals("DEL"))) {
if ((accB.getAC_CONTACT_IDSEQ() != null)
&& (!accB.getAC_CONTACT_IDSEQ().equals("")))
cstmt.setString(4, accB.getAC_CONTACT_IDSEQ()); // acc
// idseq
// if
// updated
else
sAction = "INS"; // INSERT A NEW RECORD IF NOT
// EXISTED
}
cstmt.setString(3, sAction); // ACTION - INS, UPD or DEL
cstmt.setString(5, accB.getORG_IDSEQ()); // org idseq
cstmt.setString(6, accB.getPERSON_IDSEQ()); // per idseq
cstmt.setString(7, accB.getAC_IDSEQ()); // ac idseq
cstmt.setString(8, accB.getRANK_ORDER()); // rank order
cstmt.setString(15, accB.getCONTACT_ROLE()); // contact
// role
// Now we are ready to call the stored procedure
cstmt.execute();
sReturnCode = cstmt.getString(2);
if (sReturnCode != null && !sReturnCode.equals("")) // &&
// !sReturnCode.equals("API_OC_500"))
{
String accName = accB.getORG_NAME();
if (accName == null || accName.equals(""))
accName = accB.getPERSON_NAME();
this.storeStatusMsg(sReturnCode
+ " : Unable to update contact attributes - "
+ accName);
m_classReq.setAttribute("retcode", sReturnCode);
} else {
accB.setAC_CONTACT_IDSEQ(cstmt.getString(4));
accB.setACC_SUBMIT_ACTION("NONE");
}
}
}
} catch (Exception e) {
logger.error("Error - setAC_Contact : " + e.toString(), e);
m_classReq.setAttribute("retcode", "Exception");
this
.storeStatusMsg("\\t Exception ee : Unable to update or remove contact attributes.");
}finally{
rs = SQLHelper.closeResultSet(rs);
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
return accB;
}
public ArrayList getConBeanList(Vector evsBean, boolean isAllConceptsExists){
ArrayList<ConBean> conBeanList = new ArrayList();
if (evsBean != null){
int display_order = evsBean.size() - 1;
for (int i = 1; i < evsBean.size(); i++) {
EVS_Bean ocBean = (EVS_Bean) evsBean.elementAt(i);
String conIdseq = ocBean.getIDSEQ();
if((!isAllConceptsExists) && (conIdseq == null || conIdseq.equals(""))){
conIdseq = this.setConcept("INS", "", ocBean);
}
if (conIdseq != null || conIdseq.equals("")) {
ConBean conBean = new ConBean();
conBean.setCon_IDSEQ(conIdseq);
conBean.setConcept_value(ocBean.getNVP_CONCEPT_VALUE());
conBean.setDisplay_order(display_order);
display_order = display_order - 1;
conBeanList.add(conBean);
}
}
// primary
EVS_Bean ocBean = (EVS_Bean) evsBean.elementAt(0);
String conIdseq = ocBean.getIDSEQ();
if((!isAllConceptsExists) && (conIdseq == null || conIdseq.equals(""))){
conIdseq = this.setConcept("INS", "", ocBean);
}
if (conIdseq != null || conIdseq.equals("")) {
ConBean conBean = new ConBean();
conBean.setCon_IDSEQ(ocBean.getIDSEQ());
conBean.setConcept_value(ocBean.getNVP_CONCEPT_VALUE());
conBean.setDisplay_order(0);
conBeanList.add(conBean);
}
}
return conBeanList;
}
public String getName(Vector evsBean){
String name ="";
if (evsBean != null) {
for (int i = 1; i < evsBean.size(); i++) {
EVS_Bean eBean = (EVS_Bean) evsBean.elementAt(i);
if (name.equals("")) {
name = eBean.getCONCEPT_IDENTIFIER();
} else {
name = name + ":" + eBean.getCONCEPT_IDENTIFIER();
}
}
// primary
EVS_Bean eBean = (EVS_Bean) evsBean.elementAt(0);
if (name.equals("")) {
name = eBean.getCONCEPT_IDENTIFIER();
} else {
name = name + ":" + eBean.getCONCEPT_IDENTIFIER();
}
}
return name;
}
public String doSetDEC(String sAction, DEC_Bean dec, String sInsertFor, DEC_Bean oldDEC){
String sReturnCode = "";
HttpSession session = m_classReq.getSession();
ValidationStatusBean ocStatusBean = new ValidationStatusBean();
ValidationStatusBean propStatusBean = new ValidationStatusBean();
Vector vObjectClass = (Vector) session.getAttribute("vObjectClass");
Vector vProperty = (Vector) session.getAttribute("vProperty");
String userName = (String)session.getAttribute("Username");
HashMap<String, String> defaultContext = (HashMap)session.getAttribute("defaultContext");
String conteIdseq= (String)defaultContext.get("idseq");
String checkValidityOC = (String)session.getAttribute("checkValidityOC");
String checkValidityProp = (String)session.getAttribute("checkValidityProp");
try{
m_classReq.setAttribute("retcode", "");
if (checkValidityOC.equals("Yes")){
if ((vObjectClass != null && vObjectClass.size()>0) && (defaultContext != null && defaultContext.size()>0)){
ocStatusBean = this.evsBeanCheck(vObjectClass, defaultContext, "", "Object Class");
}
}
if (checkValidityProp.equals("Yes")){
if ((vProperty != null && vProperty.size()>0) && (defaultContext != null && defaultContext.size()>0)){
propStatusBean = this.evsBeanCheck(vProperty, defaultContext, "", "Property");
}
}
//GF30681 ---- begin new CDR rule !!!
//use the existing DEC if exists based on the new CDR for DEC
//DEC_Bean m_DEC = (DEC_Bean) session.getAttribute("m_DEC");
String strInValid = checkDECUniqueCDRName((String)session.getAttribute(Constants.DEC_CDR_NAME));
if (strInValid != null && !strInValid.equals("")) {
// statusBean.setStatusMessage(strInValid);
// statusBean.setCondrExists(true);
// statusBean.setCondrIDSEQ(condrIDSEQ);
// statusBean.setEvsBeanExists(true);
// statusBean.setEvsBeanIDSEQ(idseq);
sReturnCode = strInValid;
}
//GF30681 ---- end new CDR rule !!!
if(sReturnCode != null && !sReturnCode.equals("")) { //begin of GF30681 final duplicate check (new)
//do nothing
logger.info("Exising DEC found with CDR!");
} else { //existing check continues
if (checkValidityOC.equals("Yes")){
//set OC if it is null
if ((vObjectClass != null && vObjectClass.size()>0)){
if (!ocStatusBean.isEvsBeanExists()){
if (ocStatusBean.isCondrExists()) {
dec.setDEC_OC_CONDR_IDSEQ(ocStatusBean.getCondrIDSEQ());
// Create Object Class
String ocIdseq = this.createEvsBean(userName, ocStatusBean.getCondrIDSEQ(), conteIdseq, "Object Class");
if (ocIdseq != null && !ocIdseq.equals("")) {
dec.setDEC_OCL_IDSEQ(ocIdseq);
logger.debug("At Line 6044 of InsACService.java DEC_OCL_IDSEQ"+ocIdseq+"DEC_OC_CONDR_IDSEQ"+ocStatusBean.getCondrIDSEQ());
}
} else {
// Create Condr
String condrIdseq = this.createCondr(vObjectClass, ocStatusBean.isAllConceptsExists());
String ocIdseq = "";
// Create Object Class
if (condrIdseq != null && !condrIdseq.equals("")) {
dec.setDEC_OC_CONDR_IDSEQ(condrIdseq);
logger.debug("At Line 6053 DEC_OC_CONDR_IDSEQ"+condrIdseq);
ocIdseq = this.createEvsBean(userName, condrIdseq, conteIdseq, "Object Class");
}
if (ocIdseq != null && !ocIdseq.equals("")) {
dec.setDEC_OCL_IDSEQ(ocIdseq);
logger.debug("At Line 6058 of InsACService.java DEC_OCL_IDSEQ"+ocIdseq);
}
}
}else{
if (ocStatusBean.isNewVersion()) {
if (ocStatusBean.getEvsBeanIDSEQ() != null && !ocStatusBean.getEvsBeanIDSEQ().equals("")){
String newID = "";
newID = this.setOC_PROP_REP_VERSION(ocStatusBean.getEvsBeanIDSEQ(), "ObjectClass");
if (newID != null && !newID.equals("")){
dec.setDEC_OC_CONDR_IDSEQ(ocStatusBean.getCondrIDSEQ());
dec.setDEC_OCL_IDSEQ(newID);
}
}
} else {
dec.setDEC_OC_CONDR_IDSEQ(ocStatusBean.getCondrIDSEQ());
dec.setDEC_OCL_IDSEQ(ocStatusBean.getEvsBeanIDSEQ());
}
}
}
}
if (checkValidityProp.equals("Yes")){
//set property if it is null
if ((vProperty != null && vProperty.size()>0)){
if (!propStatusBean.isEvsBeanExists()){
if (propStatusBean.isCondrExists()) {
dec.setDEC_PROP_CONDR_IDSEQ(propStatusBean.getCondrIDSEQ());
// Create Property
String propIdseq = this.createEvsBean(userName, propStatusBean.getCondrIDSEQ(), conteIdseq, "Property");
if (propIdseq != null && !propIdseq.equals("")) {
dec.setDEC_PROPL_IDSEQ(propIdseq);
logger.debug("At Line 6089 of InsACService.java DEC_PROPL_IDSEQ"+propIdseq+"DEC_PROP_CONDR_IDSEQ"+propStatusBean.getCondrIDSEQ());
}
} else {
// Create Condr
String condrIdseq = this.createCondr(vProperty, propStatusBean.isAllConceptsExists());
String propIdseq = "";
// Create Property
if (condrIdseq != null && !condrIdseq.equals("")) {
dec.setDEC_PROP_CONDR_IDSEQ(condrIdseq);
logger.debug("At Line 6098 of InsACService.java DEC_PROP_CONDR_IDSEQ"+condrIdseq);
propIdseq = this.createEvsBean(userName, condrIdseq, conteIdseq,"Property");
}
if (propIdseq != null && !propIdseq.equals("")) {
dec.setDEC_PROPL_IDSEQ(propIdseq);
logger.debug("At Line 6103 of InsACService.java DEC_PROPL_IDSEQ"+propIdseq);
}
}
}else{
if (propStatusBean.isNewVersion()) {
if (propStatusBean.getEvsBeanIDSEQ() != null && !propStatusBean.getEvsBeanIDSEQ().equals("")){
String newID = "";
newID = this.setOC_PROP_REP_VERSION(propStatusBean.getEvsBeanIDSEQ(), "Property");
if (newID != null && !newID.equals("")){
dec.setDEC_PROP_CONDR_IDSEQ(propStatusBean.getCondrIDSEQ());
dec.setDEC_PROPL_IDSEQ(newID);
}
}
} else {
dec.setDEC_PROP_CONDR_IDSEQ(propStatusBean.getCondrIDSEQ());
dec.setDEC_PROPL_IDSEQ(propStatusBean.getEvsBeanIDSEQ());
}
}
}
}
sReturnCode = this.setDEC(sAction, dec, sInsertFor, oldDEC);
} //end of GF30681 final duplicate check (new)
}catch(Exception e){
logger.error("ERROR in InsACService-setDEC for other : "+ e.toString(), e);
m_classReq.setAttribute("retcode", "Exception");
this.storeStatusMsg("\\t Exception : Unable to update Data Element Concept attributes.");
}
return sReturnCode;
}
public String createCondr(Vector vConceptList, boolean isAllConceptsExists){
String condrIdseq = "";
try {
ArrayList<ConBean> conBeanList = this.getConBeanList(vConceptList, isAllConceptsExists);
String name = this.getName(vConceptList);
Con_Derivation_Rules_Ext_Mgr mgr = new Con_Derivation_Rules_Ext_Mgr();
condrIdseq = mgr.setCondr(conBeanList, name, m_servlet.getConn());
} catch (DBException e) {
logger.error("ERROR in InsACService-createCondr: "+ e.toString(), e);
m_classReq.setAttribute("retcode", "Exception");
this.storeStatusMsg("Exception Error : Unable to create Condr");
}
return condrIdseq;
}
/**
* Gets validation string for rep term, object class and property
* @param evsBeanList
* @param defaultContext
* @param lName
* @param type
* @return
* @throws Exception
*/
public ValidationStatusBean evsBeanCheck(Vector evsBeanList, HashMap<String,String> defaultContext, String lName, String type)throws Exception{
ValidationStatusBean statusBean = new ValidationStatusBean();
HttpSession session = m_classReq.getSession();
String id = null;
String name =null;
if (type.equals("Object Class")){
DEC_Bean m_DEC = (DEC_Bean) session.getAttribute("m_DEC");
id = m_DEC.getDEC_OCL_IDSEQ();
name = "ocStatusBean";
}
if (type.equals("Property")){
DEC_Bean m_DEC = (DEC_Bean) session.getAttribute("m_DEC");
id = m_DEC.getDEC_PROPL_IDSEQ();
name = "propStatusBean";
}
if (type.equals("Representation Term")){
VD_Bean m_VD = (VD_Bean) session.getAttribute("m_VD");
id = m_VD.getVD_REP_IDSEQ();
name = "vdStatusBean";
String newRepTerm = "";
newRepTerm = (String)session.getAttribute("newRepTerm");
//Don't search for rep term if we're creating new one.
if (newRepTerm != null && newRepTerm.equals("true"))
id = "";
}
//If user selected existing OC or Prop or Rep Term in any context
if (id != null && !id.equals("")){
statusBean = (ValidationStatusBean)session.getAttribute(name);
}else{
//If user selected by concepts
statusBean = this.evsBeanCheckDB(evsBeanList, defaultContext, lName, type);
}
return statusBean;
}
public ValidationStatusBean evsBeanCheckDB(Vector evsBeanList, HashMap<String,String> defaultContext, String lName, String type)throws Exception{
ValidationStatusBean statusBean = new ValidationStatusBean();
ArrayList<ResultVO> resultList = new ArrayList();
Evs_Mgr mgr = null;
if (type.equals("Object Class")){
mgr = new Object_Classes_Ext_Mgr();
} else if (type.equals("Property")){
mgr = new Properties_Ext_Mgr();
} else if (type.equals("Representation Term")){
mgr = new Representations_Ext_Mgr();
}
statusBean.setAllConceptsExists(true);
for(int i=0; i<evsBeanList.size(); i++){
EVS_Bean conceptBean = (EVS_Bean) evsBeanList.elementAt(i);
String conIdseq = this.getConcept("", conceptBean, false);
if (conIdseq == null || conIdseq.equals("")){
statusBean.setAllConceptsExists(false); //GF30681
break;
}else {
logger.debug("conIdseq at Line 6204 of InsACService.java"+conIdseq);
}
}
//if all the concepts exists
if (statusBean.isAllConceptsExists()) {
ArrayList<ConBean> conBeanList = this.getConBeanList(evsBeanList, statusBean.isAllConceptsExists());
try {
resultList = mgr.isCondrExists(conBeanList, m_servlet.getConn());
} catch (DBException e) {
logger.error("ERROR in InsACService-evsBeanCheck : "+ e.toString(), e);
throw new Exception(e);
}
//if nothing found, create new oc or prop or rep term
if (resultList == null || resultList.size() < 1) {
statusBean.setStatusMessage("** Creating a new "+type + " in caBIG");
statusBean.setCondrExists(false);
statusBean.setEvsBeanExists(false);
logger.info("At Line 6222 of InsACService.java");
} else {
String idseq = null;
String condrIDSEQ = null;
String longName = null;
String publicID = null;
String version = null;
String idseqM = null;
String condrIDSEQM = null;
String longNameM = null;
String publicIDM = null;
String versionM = null;
ArrayList<ResultVO> foundBeanList = new ArrayList();
//select all which are owned by the default(caBIG) Context
for (int i = 0; i < resultList.size(); i++) {
ResultVO vo = resultList.get(i);
if (vo.getContext() != null) {
if (vo.getContext().equals(defaultContext.get("name"))) { //TBD - JT if it is caBIG context, add it, but based on the user's latest requirement, check should be based on other context as well!
foundBeanList.add(vo);
}
}
}
//If none are found owned by the default(caBIG) Context
if (foundBeanList == null || foundBeanList.size() < 1) {
for (int i = 0; i < resultList.size(); i++) {
ResultVO vo = resultList.get(i);
//select the one in different context, create new (oc or prop or rep term) in default(caBIG) context
if (vo.getContext() != null) {
statusBean.setStatusMessage("** Matched "+type+" with "
+ vo.getLong_name() + " (" + vo.getPublicId()
+ "v" + vo.getVersion() + ") in " + vo.getContext()
+ " context; will create a new "+type+" in caBIG.");
statusBean.setCondrExists(true);
statusBean.setCondrIDSEQ(vo.getCondr_IDSEQ());
statusBean.setEvsBeanExists(false);
logger.debug("At Line 6259 of InsACService.java"+statusBean.statusMessage);
return statusBean;
}
}
//if none are found in different context and condr exists, create new (oc or prop or rep term) in caBIG
ResultVO vo = resultList.get(0);
if (vo.getCondr_IDSEQ() != null) {
statusBean.setStatusMessage("** Creating a new "+type + " in caBIG");
statusBean.setCondrExists(true);
statusBean.setCondrIDSEQ(vo.getCondr_IDSEQ());
statusBean.setEvsBeanExists(false);
logger.info("At Line 6271 of InsACService.java");
return statusBean;
}
}//go thru all the records owned by the default(caBIG) Context
else if (foundBeanList != null && foundBeanList.size() > 0) {
//select the one with a Workflow Status RELEASED
for (int i = 0; i < foundBeanList.size(); i++) {
ResultVO vo = foundBeanList.get(i);
if (vo.getAsl_name().equals("RELEASED")) {
condrIDSEQ = vo.getCondr_IDSEQ();
idseq = vo.getIDSEQ();
longName = vo.getLong_name();
publicID = vo.getPublicId();
version = vo.getVersion();
break;
}
}
//use the released existing one if exists
if ((idseq != null) && !(idseq.equals(""))) {
statusBean.setStatusMessage("** Using existing "+type+" "+longName+" ("+publicID+"v"+version+") from caBIG");
statusBean.setCondrExists(true);
statusBean.setCondrIDSEQ(condrIDSEQ);
statusBean.setEvsBeanExists(true);
statusBean.setEvsBeanIDSEQ(idseq);
logger.debug("Condr_IDSEQ at Line 6296 of InsACService.java"+condrIDSEQ);
} else {
if (foundBeanList != null && foundBeanList.size() > 0) {
//if none are found with a Workflow Status RELEASED, select one with a Workflow Status DRAFT NEW or DRAFT MOD.
for (int i = 0; i < foundBeanList.size(); i++) {
ResultVO vo = foundBeanList.get(i);
if (vo.getAsl_name().equals("DRAFT NEW") || vo.getAsl_name().equals("DRAFT MOD")) {
condrIDSEQM = vo.getCondr_IDSEQ();
idseqM = vo.getIDSEQ();
longNameM = vo.getLong_name();
publicIDM = vo.getPublicId();
versionM = vo.getVersion();
break;
}
}
}
//use the recommended existing data
if ((idseqM != null) && !(idseqM.equals(""))) {
statusBean.setStatusMessage("** Recommending to use "+type+" "+longNameM+" ("+publicIDM+"v"+versionM+") from caBIG");
statusBean.setCondrExists(true);
statusBean.setCondrIDSEQ(condrIDSEQM);
statusBean.setEvsBeanExists(true);
statusBean.setEvsBeanIDSEQ(idseqM);
logger.info("At Line 6320 of InsACService.java");
} else {
//If none are found, select any other Workflow Status and create a New Version of it.
ResultVO vo = foundBeanList.get(0);
statusBean.setStatusMessage("** Creating new Version of "+type+" "+vo.getLong_name()+" ("+vo.getPublicId()+"v"+vo.getVersion()+") in caBIG");
statusBean.setNewVersion(true);
statusBean.setCondrExists(true);
statusBean.setCondrIDSEQ(vo.getCondr_IDSEQ());
statusBean.setEvsBeanExists(true);
statusBean.setEvsBeanIDSEQ(vo.getIDSEQ());
logger.info("At Line 6330 of InsACService.java");
}
}
}
}
} else {//if all the concepts does not exist
statusBean.setStatusMessage("** Creating a new "+type + " in caBIG");
}
return statusBean;
}
/**
*
* @param userName
* @param condrIdseq
* @param defaultContextIdseq
* @param type
* @return
*/
public String createEvsBean(String userName, String condrIdseq, String defaultContextIdseq, String type){
String idseq= "";
Evs_Mgr mgr = null;
try{
if (type.equals("Object Class")){
mgr = new Object_Classes_Ext_Mgr();
}else if (type.equals("Property")){
mgr = new Properties_Ext_Mgr();
}else if (type.equals("Representation Term")){
mgr = new Representations_Ext_Mgr();
}
EvsVO vo = new EvsVO();
vo.setCondr_IDSEQ(condrIdseq);
vo.setConte_IDSEQ(defaultContextIdseq);
vo.setCreated_by(userName);
idseq = mgr.insert(vo, m_servlet.getConn());
}catch (DBException e){
logger.error("ERROR in InsACService-createEvsBean: "+ e.toString(), e);
m_classReq.setAttribute("retcode", "Exception");
this.storeStatusMsg("Exception Error : Unable to create " + type);
}
return idseq;
}
}// close the class
| true | true | public String setVD(String sAction, VD_Bean vd, String sInsertFor,
VD_Bean oldVD) {
ResultSet rs = null;
CallableStatement cstmt = null;
HttpSession session = m_classReq.getSession();
String sReturnCode = ""; // ou
String sVDParent = "";
try {
String sOriginAction = (String) session
.getAttribute("originAction");
if (sOriginAction == null)
sOriginAction = "";
m_classReq.setAttribute("retcode", ""); // empty retcode to track it
// all through this request
if (oldVD == null)
oldVD = new VD_Bean();
String sVD_ID = vd.getVD_VD_IDSEQ();
String sName = vd.getVD_PREFERRED_NAME();
if (sName == null)
sName = "";
String pageVDType = vd.getVD_TYPE_FLAG();
String sContextID = vd.getVD_CONTE_IDSEQ();
String sLongName = vd.getVD_LONG_NAME();
String oldASLName = oldVD.getVD_ASL_NAME();
if (oldASLName == null)
oldASLName = "";
String prefType = vd.getAC_PREF_NAME_TYPE();
// do this only for insert because parent concept is not yet updated
// to get it from API
if (prefType != null && prefType.equals("SYS")
&& sAction.equals("INS")) // && sName.equals("(Generated
// by the System)"))
sName = "System Generated";
// store versioned status message
if (sInsertFor.equals("Version"))
this.storeStatusMsg("\\t Created new version successfully.");
if (!sOriginAction.equals("BlockEditVD")) // not for block edit
{
// remove vd_pvs relationship if vd type has changed from enum
// to non-enum
Vector<PV_Bean> vVDPVs = vd.getRemoved_VDPVList(); // vd.getVD_PV_List();
// //(Vector)session.getAttribute("VDPVList");
if (!pageVDType.equals("E") && sAction.equals("UPD")
&& vVDPVs != null && vVDPVs.size() > 0) {
PVServlet pvser = new PVServlet(m_classReq, m_classRes,
m_servlet);
String sStat = pvser.doRemoveVDPV(vd); // TODO -
// this.addRemoveVDPVS(vd,
// false);
if (sReturnCode != null && !sReturnCode.equals(""))
vd.setVD_TYPE_FLAG("E");
if (sStat != null && !sStat.equals(""))
this.storeStatusMsg(sStat);
}
}
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
// cstmt = conn.prepareCall("{call
// SBREXT_Set_Row.SET_VD(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}");
cstmt = m_servlet
.getConn()
.prepareCall(
"{call SBREXT_SET_ROW.SET_VD(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}");
// cstmt.registerOutParameter(1, java.sql.Types.VARCHAR);
// //ua_name
cstmt.registerOutParameter(2, java.sql.Types.VARCHAR); // return
// code
cstmt.registerOutParameter(5, java.sql.Types.VARCHAR); // vd id
cstmt.registerOutParameter(6, java.sql.Types.VARCHAR); // preferred
// name
cstmt.registerOutParameter(7, java.sql.Types.VARCHAR); // context
// id
cstmt.registerOutParameter(8, java.sql.Types.DECIMAL); // version
cstmt.registerOutParameter(9, java.sql.Types.VARCHAR); // preferred
// definition
cstmt.registerOutParameter(10, java.sql.Types.VARCHAR); // cd id
cstmt.registerOutParameter(11, java.sql.Types.VARCHAR); // asl
// name
cstmt.registerOutParameter(12, java.sql.Types.VARCHAR); // latest
// version
// ind
cstmt.registerOutParameter(13, java.sql.Types.VARCHAR); // dtl
// name
cstmt.registerOutParameter(14, java.sql.Types.NUMERIC); // Max
// Length
// Number
cstmt.registerOutParameter(15, java.sql.Types.VARCHAR); // Long
// name
cstmt.registerOutParameter(16, java.sql.Types.VARCHAR); // Forml
// Name
cstmt.registerOutParameter(17, java.sql.Types.VARCHAR); // Forml
// Description
cstmt.registerOutParameter(18, java.sql.Types.VARCHAR); // Forml
// Comment
cstmt.registerOutParameter(19, java.sql.Types.VARCHAR); // UOML
// name
cstmt.registerOutParameter(20, java.sql.Types.VARCHAR); // UOML
// Desciption
cstmt.registerOutParameter(21, java.sql.Types.VARCHAR); // UOML
// comment
cstmt.registerOutParameter(22, java.sql.Types.VARCHAR); // Low
// value
// number
cstmt.registerOutParameter(23, java.sql.Types.VARCHAR); // High
// Value
// Number
cstmt.registerOutParameter(24, java.sql.Types.NUMERIC); // Min
// Lenght
// Num
cstmt.registerOutParameter(25, java.sql.Types.NUMERIC); // Decimal
// Place
cstmt.registerOutParameter(26, java.sql.Types.VARCHAR); // Char
// set
// name
cstmt.registerOutParameter(27, java.sql.Types.VARCHAR); // begin
// date
cstmt.registerOutParameter(28, java.sql.Types.VARCHAR); // end
// date
cstmt.registerOutParameter(29, java.sql.Types.VARCHAR); // change
// note
cstmt.registerOutParameter(30, java.sql.Types.VARCHAR); // type
// flag
cstmt.registerOutParameter(31, java.sql.Types.VARCHAR); // created
// by
cstmt.registerOutParameter(32, java.sql.Types.VARCHAR); // date
// created
cstmt.registerOutParameter(33, java.sql.Types.VARCHAR); // modified
// by
cstmt.registerOutParameter(34, java.sql.Types.VARCHAR); // date
// modified
cstmt.registerOutParameter(35, java.sql.Types.VARCHAR); // deleted
// ind
cstmt.registerOutParameter(36, java.sql.Types.VARCHAR); // condr_idseq
// Get the username from the session.
String userName = (String) session.getAttribute("Username");
cstmt.setString(1, userName); // set ua_name
cstmt.setString(3, ""); // make it empty default
cstmt.setString(4, sAction); // ACTION - INS, UPD or DEL
if ((sAction.equals("UPD")) || (sAction.equals("DEL")))
cstmt.setString(5, sVD_ID); // A
// make it null for editing released elements
if (sAction.equals("UPD") && oldASLName.equals("RELEASED")
&& !sInsertFor.equals("Version")) {
cstmt.setString(6, null); // preferred name - not null for
// INS, must be null for UPD
cstmt.setString(7, null); // context id - not null for
// INS, must be null for UPD
} else // INS case
{
cstmt.setString(6, sName); // preferred name - not null for
// INS, must be null for UPD
cstmt.setString(7, sContextID); // context id - not null for
// INS, must be null for UPD
}
cstmt.setString(37, ""); // rep term idseq, null by default
cstmt.setString(38, ""); // rep qualifier - null by default
cstmt.setString(39, ""); // origin
// String sContext = vd.getVD_CONTEXT_NAME();
Double DVersion = new Double(vd.getVD_VERSION());
double dVersion = DVersion.doubleValue();
String sDefinition = vd.getVD_PREFERRED_DEFINITION();
String sCD_ID = vd.getVD_CD_IDSEQ();
// Vector sPV_ID = vd.getVD_PV_ID();
String sAslName = vd.getVD_ASL_NAME();
// String sLatestVersion = vd.getVD_LATEST_VERSION_IND();
String sDtlName = vd.getVD_DATA_TYPE();
String sTypeFlag = vd.getVD_TYPE_FLAG();
String sRepTerm = m_util.formatStringVDSubmit(sAction,
"RepTerm", vd, oldVD);
String sSource = m_util.formatStringVDSubmit(sAction, "Source",
vd, oldVD);
String sChangeNote = m_util.formatStringVDSubmit(sAction,
"ChangeNote", vd, oldVD);
String sEndDate = m_util.formatStringVDSubmit(sAction,
"EndDate", vd, oldVD);
String sBeginDate = m_util.formatStringVDSubmit(sAction,
"BeginDate", vd, oldVD);
String sUomlName = m_util.formatStringVDSubmit(sAction,
"UOMLName", vd, oldVD);
String sFormlName = m_util.formatStringVDSubmit(sAction,
"FORMLName", vd, oldVD);
String sMaxLength = m_util.formatStringVDSubmit(sAction,
"MaxLen", vd, oldVD);
String sMinLength = m_util.formatStringVDSubmit(sAction,
"MinLen", vd, oldVD);
String sLowValue = m_util.formatStringVDSubmit(sAction,
"LowValue", vd, oldVD);
String sHighValue = m_util.formatStringVDSubmit(sAction,
"HighValue", vd, oldVD);
String sDecimalPlace = m_util.formatStringVDSubmit(sAction,
"Decimal", vd, oldVD);
// create concepts and pass them in comma-delimited format
if (!sOriginAction.equals("BlockEditVD"))
sVDParent = this.setEVSParentConcept(vd); // "", sVDCondr
// = "";
if (sVDParent == null)
sVDParent = "";
// Set the In parameters (which are inherited from the
// PreparedStatement class)
cstmt.setString(3, sVDParent); // comma-delimited con idseqs
if (sVDParent.equals("removeParent"))
cstmt.setString(3, ""); // do not set vdconcepts
cstmt.setDouble(8, dVersion); // version - test says must have
// a value
cstmt.setString(9, sDefinition); // preferred definition -
// not null for INS
cstmt.setString(10, sCD_ID); // cd id - not null for INS
cstmt.setString(11, sAslName);
if (sAction.equals("INS"))
cstmt.setString(12, "Yes");
cstmt.setString(13, sDtlName);
if (sMaxLength != null && sMaxLength.length() > 0) {
Integer IntTmp = new Integer(sMaxLength);
cstmt.setInt(14, IntTmp.intValue());
}
cstmt.setString(15, sLongName); // long name - can be null
cstmt.setString(16, sFormlName);
cstmt.setString(19, sUomlName);
cstmt.setString(22, sLowValue);
cstmt.setString(23, sHighValue);
if (sMinLength != null && sMinLength.length() > 0) {
Integer IntTmp = new Integer(sMinLength);
cstmt.setInt(24, IntTmp.intValue());
}
if (sDecimalPlace != null && sDecimalPlace.length() > 0) {
Integer IntTmp = new Integer(sDecimalPlace);
cstmt.setInt(25, IntTmp.intValue());
}
cstmt.setString(27, sBeginDate);
cstmt.setString(28, sEndDate);
cstmt.setString(29, sChangeNote);
cstmt.setString(30, sTypeFlag); // type flag - E by default
if (sOriginAction.equals("BlockEditVD")
&& sInsertFor.equals("Version"))
cstmt.setString(36, vd.getVD_PAR_CONDR_IDSEQ()); // set
// as
// the
// earlier
// one.
else {
if (sAction.equals("UPD")
&& sVDParent.equals("removeParent"))
cstmt.setString(36, " "); // remove the existing
// parent if removing them
// all
}
cstmt.setString(37, sRepTerm); // rep term idseq, null by
// default
cstmt.setString(38, ""); // rep qualifier - null by default
cstmt.setString(39, sSource); // origin
cstmt.execute();
// capture the duration
// logger.info(m_servlet.getLogMessage(m_classReq, "setVD",
// "execute ok", startDate, new java.util.Date()));
if (vd.getVD_IN_FORM()) {
//Go through all the forms and set warnings for owners
SearchServlet ser = new SearchServlet(m_classReq, m_classRes, m_servlet.m_servletContext);
ser.get_m_conn();
HashMap<String,ArrayList<String[]>> display = ser.getVDAssociatedForms(vd.getIDSEQ(), null);
ArrayList<String[]> forms = display.get("Content");
String[] headers = display.get("Head").get(0);
//Last two spots.
int idseqNdx = headers.length-1;
int nameNdx = headers.length-2;
for (String[] formInfo : forms) {
m_servlet.doMonitor(formInfo[nameNdx], formInfo[idseqNdx]);
}
}
sReturnCode = cstmt.getString(2);
String prefName = cstmt.getString(6);
if (prefName != null)
vd.setVD_PREFERRED_NAME(prefName);
if (sReturnCode == null || sReturnCode.equals("")) {
m_servlet.clearBuildingBlockSessionAttributes(m_classReq,
m_classRes);
vd.setVD_REP_QUALIFIER_NAMES(null);
vd.setVD_REP_QUALIFIER_CODES(null);
vd.setVD_REP_QUALIFIER_DB(null);
}
vd.setVD_PAR_CONDR_IDSEQ(cstmt.getString(35));
sVD_ID = cstmt.getString(5);
vd.setVD_VD_IDSEQ(sVD_ID);
String sReturn = "";
if (sAction.equals("INS"))
this.storeStatusMsg("Value Domain Name : "
+ vd.getVD_LONG_NAME());
// continue update even if not null
if (sReturnCode != null && sAction.equals("INS")) {
this
.storeStatusMsg("\\t "
+ sReturnCode
+ " : Unable to create new Value Domain Successfully.");
logger
.error(sReturnCode
+ " Unable to create new Value Domain Successfully.");
} else if ((sReturnCode == null || (sReturnCode != null && sAction
.equals("UPD")))
&& !sVD_ID.equals("")) {
// store the status message in the session
if (sAction.equals("INS")) {
String sPublicID = this.getPublicID(sVD_ID);
vd.setVD_VD_ID(sPublicID);
this.storeStatusMsg("Public ID : " + vd.getVD_VD_ID());
this
.storeStatusMsg("\\t Successfully created New Value Domain");
} else if (sAction.equals("UPD") && sReturnCode != null
&& !sReturnCode.equals(""))
this.storeStatusMsg("\\t " + sReturnCode
+ " : Unable to update mandatory attributes.");
// store returncode in request to track it all through this
// request
if (sReturnCode != null && !sReturnCode.equals(""))
m_classReq.setAttribute("retcode", sReturnCode);
// create non evs parent concept in reference documents
// table
sReturn = this.setNonEVSParentConcept(vd);
// This writes the source of a Meta parent to Ref Docs
// sVDParent is string of con_idseqs for parent concepts
// if(sVDParent != null && !sVDParent.equals(""))
if (vd.getVD_PAR_CONDR_IDSEQ() != null
&& !vd.getVD_PAR_CONDR_IDSEQ().equals(""))
sReturn = this.setRDMetaConceptSource(vd);
// set create/modify attributes into bean
if (cstmt.getString(31) != null
&& !cstmt.getString(31).equals(""))
vd.setVD_CREATED_BY(getFullName(cstmt.getString(31)));
else
vd.setVD_CREATED_BY(oldVD.getVD_CREATED_BY());
if (cstmt.getString(32) != null
&& !cstmt.getString(32).equals(""))
vd.setVD_DATE_CREATED(m_util.getCurationDate(cstmt
.getString(32)));
else
vd.setVD_DATE_CREATED(oldVD.getVD_DATE_CREATED());
vd.setVD_MODIFIED_BY(getFullName(cstmt.getString(33)));
vd.setVD_DATE_MODIFIED(m_util.getCurationDate(cstmt
.getString(34)));
//===========GF32398====Insert/update/delete regstatus=======START
String sReturned = "";
if (vd.getVD_REG_STATUS() != null
&& !vd.getVD_REG_STATUS().equals("")) {
logger.debug("line 566 of InsACSErvice.java registration value is "+vd.getVD_REG_STATUS()+"************");
vd.setVD_REG_STATUS_IDSEQ(this.getAC_REG(sVD_ID));
if (vd.getVD_REG_STATUS_IDSEQ() == null
|| vd.getVD_REG_STATUS_IDSEQ().equals("")){
logger.info("line 570 of InsACSErvice.java ************");
sReturned = this.setReg_Status("INS", "", sVD_ID, vd
.getVD_REG_STATUS());
}
else{
logger.info("line 576 of InsACSErvice.java ************");
sReturned = this.setReg_Status("UPD", vd
.getVD_REG_STATUS_IDSEQ(), sVD_ID, vd
.getVD_REG_STATUS());
}
if (sReturned != null && !sReturned.equals("")){
logger.info("line 583 of InsACSErvice.java ************");
this.storeStatusMsg("\\t "
+ sReturned
+ " : Unable to update Registration Status.");
}
} else {
// delete if reg status is empty and idseq is not null
if (vd.getVD_REG_STATUS_IDSEQ() != null
&& !vd.getVD_REG_STATUS_IDSEQ().equals("")){
logger.info("line 593 of InsACSErvice.java ************");
sReturned = this.setReg_Status("DEL", vd
.getVD_REG_STATUS_IDSEQ(), sVD_ID, vd
.getVD_REG_STATUS());
}
if (sReturned != null && !sReturned.equals("")){
logger.info("line 600 of InsACSErvice.java ************");
this
.storeStatusMsg("\\t "
+ sReturned
+ " : Unable to remove Registration Status.");
}
}
// store returncode in request to track it all through this
// request
if (sAction.equals("UPD") && sReturned != null
&& !sReturned.equals(""))
m_classReq.setAttribute("retcode", sReturned);
//===========GF32398====Insert/update/delete regstatus=======END
// insert the vd pv relationships in vd_pvs table if not
// block edit
if (!sOriginAction.equals("BlockEditVD")) {
if (vd.getVD_TYPE_FLAG().equals("E")
&& (pageVDType == null || pageVDType.equals("") || pageVDType
.equals("E"))) {
PVServlet pvser = new PVServlet(m_classReq,
m_classRes, m_servlet);
String sStat = pvser.submitPV(vd);
if (sStat != null && !sStat.equals(""))
this.storeStatusMsg(sStat);
// ********************************
Vector<PV_Bean> vPV = vd.getVD_PV_List(); // (Vector)session.getAttribute("VDPVList");
// //vd.getVD_PV_NAME();
for (int j = 0; j < vPV.size(); j++) {
PV_Bean pv = (PV_Bean) vPV.elementAt(j);
VM_Bean vm = pv.getPV_VM();
if (vm != null && !vm.getVM_IDSEQ().equals("")) {
// System.out.println(vm.getVM_IDSEQ() + "
// vm alt name " + sContextID + " vd " +
// vd.getVD_VD_IDSEQ());
vm.save(session, m_servlet.getConn(), vm
.getVM_IDSEQ(), sContextID);
}
}
session.removeAttribute("AllAltNameList");
// ********************************
}
}
// reset the pv counts to reset more hyperlink
String pvName = "";
Integer pvCount = new Integer(0);
if (vd.getVD_TYPE_FLAG().equals("E")) {
Vector<PV_Bean> vPV = vd.getVD_PV_List(); // (Vector)session.getAttribute("VDPVList");
// //vd.getVD_PV_NAME();
if (vPV != null && vPV.size() > 0) {
PV_Bean pvBean = (PV_Bean) vPV.elementAt(0);
pvName = pvBean.getPV_VALUE();
pvCount = new Integer(vPV.size());
}
}
vd.setVD_Permissible_Value(pvName);
vd.setVD_Permissible_Value_Count(pvCount);
// do this for new version, to check whether we need to
// write to AC_HISTORIES table later
if (sInsertFor.equals("Version")) {
vd.setVD_DATE_CREATED(vd.getVD_DATE_MODIFIED());
vd.setVD_CREATED_BY(vd.getVD_MODIFIED_BY());
vd.setVD_VD_ID(oldVD.getVD_VD_ID()); // adds public
// id to the
// bean
}
// insert and delete ac-csi relationship
Vector vAC_CS = vd.getAC_AC_CSI_VECTOR();
GetACSearch getAC = new GetACSearch(m_classReq, m_classRes,
m_servlet);
Vector vRemove_ACCSI = getAC.doCSCSI_ACSearch(sVD_ID, ""); // (Vector)session.getAttribute("vAC_CSI");
Vector vACID = (Vector) session.getAttribute("vACId");
this.addRemoveACCSI(sVD_ID, vAC_CS, vRemove_ACCSI, vACID,
sInsertFor, sLongName);
// store back altname and ref docs to session
m_servlet.doMarkACBeanForAltRef(m_classReq, m_classRes,
"ValueDomain", "all", "submitAR");
// do alternate names create
if (sInsertFor.equalsIgnoreCase("Version"))
this.doAltVersionUpdate(sVD_ID, oldVD.getVD_VD_IDSEQ());
// ********************************
vd.save(session, m_servlet.getConn(), sVD_ID, sContextID);
session.removeAttribute("AllAltNameList");
// ********************************
/*
* Vector<ALT_NAME_Bean> tBean =
* AltNamesDefsSession.getAltNameBeans(session,
* AltNamesDefsSession._searchVD, sVD_ID, sContextID); if
* (tBean != null) DataManager.setAttribute(session,
* "AllAltNameList", tBean);
*/
String oneAlt = this.doAddRemoveAltNames(sVD_ID,
sContextID, sAction); // , "create");
vd.setALTERNATE_NAME(oneAlt);
// do reference docuemnts create
if (sInsertFor.equalsIgnoreCase("Version"))
this.doRefVersionUpdate(sVD_ID, oldVD.getVD_VD_IDSEQ());
String oneRD = this.doAddRemoveRefDocs(sVD_ID, sContextID,
sAction); // "create");
vd.setREFERENCE_DOCUMENT(oneRD);
// do contact updates
Hashtable vdConts = vd.getAC_CONTACTS();
if (vdConts != null && vdConts.size() > 0)
vd.setAC_CONTACTS(this.addRemoveAC_Contacts(vdConts,
sVD_ID, sInsertFor));
// get one concept name for this vd
vd.setAC_CONCEPT_NAME(this.getOneConName("", sVD_ID));
// add success message if no error
sReturn = (String) m_classReq.getAttribute("retcode");
if (sAction.equals("UPD")
&& (sReturn == null || sReturn.equals("")))
this
.storeStatusMsg("\\t Successfully updated Value Domain.");
}
else if (sReturnCode != null && !sReturnCode.equals("")) {
this
.storeStatusMsg("\\t Unable to update the Short Name of the Value Domain.");
logger
.error(sReturnCode
+ " Unable to update the Short Name of the Value Domain.");
}
}
this.storeStatusMsg("\\n");
// capture the duration
// logger.info(m_servlet.getLogMessage(m_classReq, "setVD", "done
// set", startDate, new java.util.Date()));
} catch (Exception e) {
logger.error("ERROR in InsAerrorice-setVD for other : "
+ e.toString(), e);
m_classReq.setAttribute("retcode", "Exception");
this
.storeStatusMsg("\\t Exception : Unable to update Value Domain attributes.");
}finally{
rs = SQLHelper.closeResultSet(rs);
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
return sReturnCode;
}
| public String setVD(String sAction, VD_Bean vd, String sInsertFor,
VD_Bean oldVD) {
ResultSet rs = null;
CallableStatement cstmt = null;
HttpSession session = m_classReq.getSession();
String sReturnCode = ""; // ou
String sVDParent = "";
try {
String sOriginAction = (String) session
.getAttribute("originAction");
if (sOriginAction == null)
sOriginAction = "";
m_classReq.setAttribute("retcode", ""); // empty retcode to track it
// all through this request
if (oldVD == null)
oldVD = new VD_Bean();
String sVD_ID = vd.getVD_VD_IDSEQ();
String sName = vd.getVD_PREFERRED_NAME();
if (sName == null)
sName = "";
String pageVDType = vd.getVD_TYPE_FLAG();
String sContextID = vd.getVD_CONTE_IDSEQ();
String sLongName = vd.getVD_LONG_NAME();
String oldASLName = oldVD.getVD_ASL_NAME();
if (oldASLName == null)
oldASLName = "";
String prefType = vd.getAC_PREF_NAME_TYPE();
// do this only for insert because parent concept is not yet updated
// to get it from API
if (prefType != null && prefType.equals("SYS")
&& sAction.equals("INS")) // && sName.equals("(Generated
// by the System)"))
sName = "System Generated";
// store versioned status message
if (sInsertFor.equals("Version"))
this.storeStatusMsg("\\t Created new version successfully.");
if (!sOriginAction.equals("BlockEditVD")) // not for block edit
{
// remove vd_pvs relationship if vd type has changed from enum
// to non-enum
Vector<PV_Bean> vVDPVs = vd.getRemoved_VDPVList(); // vd.getVD_PV_List();
// //(Vector)session.getAttribute("VDPVList");
if (!pageVDType.equals("E") && sAction.equals("UPD")
&& vVDPVs != null && vVDPVs.size() > 0) {
PVServlet pvser = new PVServlet(m_classReq, m_classRes,
m_servlet);
String sStat = pvser.doRemoveVDPV(vd); // TODO -
// this.addRemoveVDPVS(vd,
// false);
if (sReturnCode != null && !sReturnCode.equals(""))
vd.setVD_TYPE_FLAG("E");
if (sStat != null && !sStat.equals(""))
this.storeStatusMsg(sStat);
}
}
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
// cstmt = conn.prepareCall("{call
// SBREXT_Set_Row.SET_VD(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}");
cstmt = m_servlet
.getConn()
.prepareCall(
"{call SBREXT_SET_ROW.SET_VD(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}");
// cstmt.registerOutParameter(1, java.sql.Types.VARCHAR);
// //ua_name
cstmt.registerOutParameter(2, java.sql.Types.VARCHAR); // return
// code
cstmt.registerOutParameter(5, java.sql.Types.VARCHAR); // vd id
cstmt.registerOutParameter(6, java.sql.Types.VARCHAR); // preferred
// name
cstmt.registerOutParameter(7, java.sql.Types.VARCHAR); // context
// id
cstmt.registerOutParameter(8, java.sql.Types.DECIMAL); // version
cstmt.registerOutParameter(9, java.sql.Types.VARCHAR); // preferred
// definition
cstmt.registerOutParameter(10, java.sql.Types.VARCHAR); // cd id
cstmt.registerOutParameter(11, java.sql.Types.VARCHAR); // asl
// name
cstmt.registerOutParameter(12, java.sql.Types.VARCHAR); // latest
// version
// ind
cstmt.registerOutParameter(13, java.sql.Types.VARCHAR); // dtl
// name
cstmt.registerOutParameter(14, java.sql.Types.NUMERIC); // Max
// Length
// Number
cstmt.registerOutParameter(15, java.sql.Types.VARCHAR); // Long
// name
cstmt.registerOutParameter(16, java.sql.Types.VARCHAR); // Forml
// Name
cstmt.registerOutParameter(17, java.sql.Types.VARCHAR); // Forml
// Description
cstmt.registerOutParameter(18, java.sql.Types.VARCHAR); // Forml
// Comment
cstmt.registerOutParameter(19, java.sql.Types.VARCHAR); // UOML
// name
cstmt.registerOutParameter(20, java.sql.Types.VARCHAR); // UOML
// Desciption
cstmt.registerOutParameter(21, java.sql.Types.VARCHAR); // UOML
// comment
cstmt.registerOutParameter(22, java.sql.Types.VARCHAR); // Low
// value
// number
cstmt.registerOutParameter(23, java.sql.Types.VARCHAR); // High
// Value
// Number
cstmt.registerOutParameter(24, java.sql.Types.NUMERIC); // Min
// Lenght
// Num
cstmt.registerOutParameter(25, java.sql.Types.NUMERIC); // Decimal
// Place
cstmt.registerOutParameter(26, java.sql.Types.VARCHAR); // Char
// set
// name
cstmt.registerOutParameter(27, java.sql.Types.VARCHAR); // begin
// date
cstmt.registerOutParameter(28, java.sql.Types.VARCHAR); // end
// date
cstmt.registerOutParameter(29, java.sql.Types.VARCHAR); // change
// note
cstmt.registerOutParameter(30, java.sql.Types.VARCHAR); // type
// flag
cstmt.registerOutParameter(31, java.sql.Types.VARCHAR); // created
// by
cstmt.registerOutParameter(32, java.sql.Types.VARCHAR); // date
// created
cstmt.registerOutParameter(33, java.sql.Types.VARCHAR); // modified
// by
cstmt.registerOutParameter(34, java.sql.Types.VARCHAR); // date
// modified
cstmt.registerOutParameter(35, java.sql.Types.VARCHAR); // deleted
// ind
cstmt.registerOutParameter(36, java.sql.Types.VARCHAR); // condr_idseq
// Get the username from the session.
String userName = (String) session.getAttribute("Username");
cstmt.setString(1, userName); // set ua_name
cstmt.setString(3, ""); // make it empty default
cstmt.setString(4, sAction); // ACTION - INS, UPD or DEL
if ((sAction.equals("UPD")) || (sAction.equals("DEL")))
cstmt.setString(5, sVD_ID); // A
// make it null for editing released elements
if (sAction.equals("UPD") && oldASLName.equals("RELEASED")
&& !sInsertFor.equals("Version")) {
cstmt.setString(6, null); // preferred name - not null for
// INS, must be null for UPD
cstmt.setString(7, null); // context id - not null for
// INS, must be null for UPD
} else // INS case
{
cstmt.setString(6, sName); // preferred name - not null for
// INS, must be null for UPD
cstmt.setString(7, sContextID); // context id - not null for
// INS, must be null for UPD
}
cstmt.setString(37, ""); // rep term idseq, null by default
cstmt.setString(38, ""); // rep qualifier - null by default
cstmt.setString(39, ""); // origin
// String sContext = vd.getVD_CONTEXT_NAME();
Double DVersion = new Double(vd.getVD_VERSION());
double dVersion = DVersion.doubleValue();
String sDefinition = vd.getVD_PREFERRED_DEFINITION();
String sCD_ID = vd.getVD_CD_IDSEQ();
// Vector sPV_ID = vd.getVD_PV_ID();
String sAslName = vd.getVD_ASL_NAME();
// String sLatestVersion = vd.getVD_LATEST_VERSION_IND();
String sDtlName = vd.getVD_DATA_TYPE();
String sTypeFlag = vd.getVD_TYPE_FLAG();
String sRepTerm = m_util.formatStringVDSubmit(sAction,
"RepTerm", vd, oldVD);
String sSource = m_util.formatStringVDSubmit(sAction, "Source",
vd, oldVD);
String sChangeNote = m_util.formatStringVDSubmit(sAction,
"ChangeNote", vd, oldVD);
String sEndDate = m_util.formatStringVDSubmit(sAction,
"EndDate", vd, oldVD);
String sBeginDate = m_util.formatStringVDSubmit(sAction,
"BeginDate", vd, oldVD);
String sUomlName = m_util.formatStringVDSubmit(sAction,
"UOMLName", vd, oldVD);
String sFormlName = m_util.formatStringVDSubmit(sAction,
"FORMLName", vd, oldVD);
String sMaxLength = m_util.formatStringVDSubmit(sAction,
"MaxLen", vd, oldVD);
String sMinLength = m_util.formatStringVDSubmit(sAction,
"MinLen", vd, oldVD);
String sLowValue = m_util.formatStringVDSubmit(sAction,
"LowValue", vd, oldVD);
String sHighValue = m_util.formatStringVDSubmit(sAction,
"HighValue", vd, oldVD);
String sDecimalPlace = m_util.formatStringVDSubmit(sAction,
"Decimal", vd, oldVD);
// create concepts and pass them in comma-delimited format
if (!sOriginAction.equals("BlockEditVD"))
sVDParent = this.setEVSParentConcept(vd); // "", sVDCondr
// = "";
if (sVDParent == null)
sVDParent = "";
// Set the In parameters (which are inherited from the
// PreparedStatement class)
cstmt.setString(3, sVDParent); // comma-delimited con idseqs
if (sVDParent.equals("removeParent"))
cstmt.setString(3, ""); // do not set vdconcepts
cstmt.setDouble(8, dVersion); // version - test says must have
// a value
cstmt.setString(9, sDefinition); // preferred definition -
// not null for INS
cstmt.setString(10, sCD_ID); // cd id - not null for INS
cstmt.setString(11, sAslName);
if (sAction.equals("INS"))
cstmt.setString(12, "Yes");
cstmt.setString(13, sDtlName);
if (sMaxLength != null && sMaxLength.length() > 0) {
Integer IntTmp = new Integer(sMaxLength);
cstmt.setInt(14, IntTmp.intValue());
}
cstmt.setString(15, sLongName); // long name - can be null
cstmt.setString(16, sFormlName);
cstmt.setString(19, sUomlName);
cstmt.setString(22, sLowValue);
cstmt.setString(23, sHighValue);
if (sMinLength != null && sMinLength.length() > 0) {
Integer IntTmp = new Integer(sMinLength);
cstmt.setInt(24, IntTmp.intValue());
}
if (sDecimalPlace != null && sDecimalPlace.length() > 0) {
Integer IntTmp = new Integer(sDecimalPlace);
cstmt.setInt(25, IntTmp.intValue());
}
cstmt.setString(27, sBeginDate);
cstmt.setString(28, sEndDate);
cstmt.setString(29, sChangeNote);
cstmt.setString(30, sTypeFlag); // type flag - E by default
if (sOriginAction.equals("BlockEditVD")
&& sInsertFor.equals("Version"))
cstmt.setString(36, vd.getVD_PAR_CONDR_IDSEQ()); // set
// as
// the
// earlier
// one.
else {
if (sAction.equals("UPD")
&& sVDParent.equals("removeParent"))
cstmt.setString(36, " "); // remove the existing
// parent if removing them
// all
}
cstmt.setString(37, sRepTerm); // rep term idseq, null by
// default
cstmt.setString(38, ""); // rep qualifier - null by default
cstmt.setString(39, sSource); // origin
cstmt.execute();
// capture the duration
// logger.info(m_servlet.getLogMessage(m_classReq, "setVD",
// "execute ok", startDate, new java.util.Date()));
if (vd.getVD_IN_FORM()) {
//Go through all the forms and set warnings for owners
SearchServlet ser = new SearchServlet(m_classReq, m_classRes, m_servlet.m_servletContext);
ser.get_m_conn();
HashMap<String,ArrayList<String[]>> display = ser.getVDAssociatedForms(vd.getIDSEQ(), null);
ArrayList<String[]> forms = display.get("Content");
String[] headers = display.get("Head").get(0);
//Last two spots.
int idseqNdx = headers.length-1;
int nameNdx = headers.length-2;
for (String[] formInfo : forms) {
m_servlet.doMonitor(formInfo[nameNdx], formInfo[idseqNdx]);
}
}
sReturnCode = cstmt.getString(2);
String prefName = cstmt.getString(6);
if (prefName != null)
vd.setVD_PREFERRED_NAME(prefName);
if (sReturnCode == null || sReturnCode.equals("")) {
m_servlet.clearBuildingBlockSessionAttributes(m_classReq,
m_classRes);
vd.setVD_REP_QUALIFIER_NAMES(null);
vd.setVD_REP_QUALIFIER_CODES(null);
vd.setVD_REP_QUALIFIER_DB(null);
}
vd.setVD_PAR_CONDR_IDSEQ(cstmt.getString(35));
sVD_ID = cstmt.getString(5);
vd.setVD_VD_IDSEQ(sVD_ID);
String sReturn = "";
if (sAction.equals("INS"))
this.storeStatusMsg("Value Domain Name : "
+ vd.getVD_LONG_NAME());
// continue update even if not null
if (sReturnCode != null && sAction.equals("INS")) {
this
.storeStatusMsg("\\t "
+ sReturnCode
+ " : Unable to create new Value Domain Successfully.");
logger
.error(sReturnCode
+ " Unable to create new Value Domain Successfully.");
} else if ((sReturnCode == null || (sReturnCode != null && sAction
.equals("UPD")))
&& !sVD_ID.equals("")) {
// store the status message in the session
if (sAction.equals("INS")) {
String sPublicID = this.getPublicID(sVD_ID);
vd.setVD_VD_ID(sPublicID);
this.storeStatusMsg("Public ID : " + vd.getVD_VD_ID());
this
.storeStatusMsg("\\t Successfully created New Value Domain");
} else if (sAction.equals("UPD") && sReturnCode != null
&& !sReturnCode.equals(""))
this.storeStatusMsg("\\t " + sReturnCode
+ " : Unable to update mandatory attributes.");
// store returncode in request to track it all through this
// request
if (sReturnCode != null && !sReturnCode.equals(""))
m_classReq.setAttribute("retcode", sReturnCode);
// create non evs parent concept in reference documents
// table
sReturn = this.setNonEVSParentConcept(vd);
// This writes the source of a Meta parent to Ref Docs
// sVDParent is string of con_idseqs for parent concepts
// if(sVDParent != null && !sVDParent.equals(""))
if (vd.getVD_PAR_CONDR_IDSEQ() != null
&& !vd.getVD_PAR_CONDR_IDSEQ().equals(""))
sReturn = this.setRDMetaConceptSource(vd);
// set create/modify attributes into bean
if (cstmt.getString(31) != null
&& !cstmt.getString(31).equals(""))
vd.setVD_CREATED_BY(getFullName(cstmt.getString(31)));
else
vd.setVD_CREATED_BY(oldVD.getVD_CREATED_BY());
if (cstmt.getString(32) != null
&& !cstmt.getString(32).equals(""))
vd.setVD_DATE_CREATED(m_util.getCurationDate(cstmt
.getString(32)));
else
vd.setVD_DATE_CREATED(oldVD.getVD_DATE_CREATED());
vd.setVD_MODIFIED_BY(getFullName(cstmt.getString(33)));
vd.setVD_DATE_MODIFIED(m_util.getCurationDate(cstmt
.getString(34)));
//===========GF32398====Insert/update/delete regstatus=======START
String sReturned = "";
if (vd.getVD_REG_STATUS() != null
&& !vd.getVD_REG_STATUS().equals("")) {
logger.debug("line 566 of InsACSErvice.java registration value is "+vd.getVD_REG_STATUS()+"************");
vd.setVD_REG_STATUS_IDSEQ(this.getAC_REG(sVD_ID));
if (vd.getVD_REG_STATUS_IDSEQ() == null
|| vd.getVD_REG_STATUS_IDSEQ().equals("")){
logger.info("line 570 of InsACSErvice.java ************");
sReturned = this.setReg_Status("INS", "", sVD_ID, vd
.getVD_REG_STATUS());
}
else{
logger.info("line 576 of InsACSErvice.java ************");
sReturned = this.setReg_Status("UPD", vd
.getVD_REG_STATUS_IDSEQ(), sVD_ID, vd
.getVD_REG_STATUS());
}
if (sReturned != null && !sReturned.equals("")){
logger.info("line 583 of InsACSErvice.java ************");
this.storeStatusMsg("\\t "
+ sReturned
+ " : Unable to update Registration Status.");
}
} else {
// delete if reg status is empty and idseq is not null
if (vd.getVD_REG_STATUS_IDSEQ() != null
&& !vd.getVD_REG_STATUS_IDSEQ().equals("")){
logger.info("line 593 of InsACSErvice.java ************");
sReturned = this.setReg_Status("DEL", vd
.getVD_REG_STATUS_IDSEQ(), sVD_ID, vd
.getVD_REG_STATUS());
}
if (sReturned != null && !sReturned.equals("")){
logger.info("line 600 of InsACSErvice.java ************");
this
.storeStatusMsg("\\t "
+ sReturned
+ " : Unable to remove Registration Status.");
}
}
// store returncode in request to track it all through this
// request
if (sAction.equals("UPD") && sReturned != null
&& !sReturned.equals(""))
m_classReq.setAttribute("retcode", sReturned);
//===========GF32398====Insert/update/delete regstatus=======END
// insert the vd pv relationships in vd_pvs table if not
// block edit
if (!sOriginAction.equals("BlockEditVD")) {
if (vd.getVD_TYPE_FLAG().equals("E")
&& (pageVDType == null || pageVDType.equals("") || pageVDType
.equals("E"))) {
PVServlet pvser = new PVServlet(m_classReq,
m_classRes, m_servlet);
String sStat = pvser.submitPV(vd);
if (sStat != null && !sStat.equals(""))
this.storeStatusMsg(sStat);
// ********************************
Vector<PV_Bean> vPV = vd.getVD_PV_List(); // (Vector)session.getAttribute("VDPVList");
// //vd.getVD_PV_NAME();
for (int j = 0; j < vPV.size(); j++) {
PV_Bean pv = (PV_Bean) vPV.elementAt(j);
VM_Bean vm = pv.getPV_VM();
if (vm != null && !vm.getVM_IDSEQ().equals("")) {
// System.out.println(vm.getVM_IDSEQ() + "
// vm alt name " + sContextID + " vd " +
// vd.getVD_VD_IDSEQ());
vm.save(session, m_servlet.getConn(), vm
.getVM_IDSEQ(), sContextID);
}
}
session.removeAttribute("AllAltNameList");
// ********************************
}
}
// reset the pv counts to reset more hyperlink
String pvName = "";
Integer pvCount = new Integer(0);
if (vd.getVD_TYPE_FLAG().equals("E")) {
Vector<PV_Bean> vPV = vd.getVD_PV_List(); // (Vector)session.getAttribute("VDPVList");
// //vd.getVD_PV_NAME();
if (vPV != null && vPV.size() > 0) {
PV_Bean pvBean = (PV_Bean) vPV.elementAt(0);
pvName = pvBean.getPV_VALUE();
pvCount = new Integer(vPV.size());
}
}
vd.setVD_Permissible_Value(pvName);
vd.setVD_Permissible_Value_Count(pvCount);
// do this for new version, to check whether we need to
// write to AC_HISTORIES table later
if (sInsertFor.equals("Version")) {
vd.setVD_DATE_CREATED(vd.getVD_DATE_MODIFIED());
vd.setVD_CREATED_BY(vd.getVD_MODIFIED_BY());
vd.setVD_VD_ID(oldVD.getVD_VD_ID()); // adds public
// id to the
// bean
}
// insert and delete ac-csi relationship
Vector vAC_CS = vd.getAC_AC_CSI_VECTOR();
GetACSearch getAC = new GetACSearch(m_classReq, m_classRes,
m_servlet);
Vector vRemove_ACCSI = getAC.doCSCSI_ACSearch(sVD_ID, ""); // (Vector)session.getAttribute("vAC_CSI");
Vector vACID = (Vector) session.getAttribute("vACId");
this.addRemoveACCSI(sVD_ID, vAC_CS, vRemove_ACCSI, vACID,
sInsertFor, sLongName);
// store back altname and ref docs to session
m_servlet.doMarkACBeanForAltRef(m_classReq, m_classRes,
"ValueDomain", "all", "submitAR");
// do alternate names create
if (sInsertFor.equalsIgnoreCase("Version"))
this.doAltVersionUpdate(sVD_ID, oldVD.getVD_VD_IDSEQ());
// ********************************
vd.save(session, m_servlet.getConn(), sVD_ID, sContextID);
session.removeAttribute("AllAltNameList");
// ********************************
/*
* Vector<ALT_NAME_Bean> tBean =
* AltNamesDefsSession.getAltNameBeans(session,
* AltNamesDefsSession._searchVD, sVD_ID, sContextID); if
* (tBean != null) DataManager.setAttribute(session,
* "AllAltNameList", tBean);
*/
String oneAlt = this.doAddRemoveAltNames(sVD_ID,
sContextID, sAction); // , "create");
vd.setALTERNATE_NAME(oneAlt);
// do reference docuemnts create
if (sInsertFor.equalsIgnoreCase("Version"))
this.doRefVersionUpdate(sVD_ID, oldVD.getVD_VD_IDSEQ());
String oneRD = this.doAddRemoveRefDocs(sVD_ID, sContextID,
sAction); // "create");
vd.setREFERENCE_DOCUMENT(oneRD);
// do contact updates
Hashtable vdConts = vd.getAC_CONTACTS();
if (vdConts != null && vdConts.size() > 0)
vd.setAC_CONTACTS(this.addRemoveAC_Contacts(vdConts,
sVD_ID, sInsertFor));
// get one concept name for this vd
vd.setAC_CONCEPT_NAME(this.getOneConName("", sVD_ID));
// add success message if no error
sReturn = (String) m_classReq.getAttribute("retcode");
if (sAction.equals("UPD")
&& (sReturn == null || sReturn.equals("")))
this
.storeStatusMsg("\\t Successfully updated Value Domain.");
}
else if (sReturnCode != null && !sReturnCode.equals("")) {
this
.storeStatusMsg("\\t Unable to update the Short Name of the Value Domain.");
logger
.error(sReturnCode
+ " Unable to update the Short Name of the Value Domain.");
}
}
this.storeStatusMsg("\\n");
// capture the duration
// logger.info(m_servlet.getLogMessage(m_classReq, "setVD", "done
// set", startDate, new java.util.Date()));
} catch (Exception e) {
logger.error("ERROR in InsAerrorice-setVD for other : "
+ e.toString(), e);
m_classReq.setAttribute("retcode", "Exception");
this
.storeStatusMsg("\\t Exception : Unable to update Value Domain attributes.");
}finally{
rs = SQLHelper.closeResultSet(rs);
cstmt = SQLHelper.closeCallableStatement(cstmt);
SQLHelper.closeConnection(m_servlet.getConn()); //GF32398 not related to the ticket, but found the leak and fix it
}
return sReturnCode;
}
|
diff --git a/src/main/java/rinde/evo4mas/gendreau06/HeuristicTruck.java b/src/main/java/rinde/evo4mas/gendreau06/HeuristicTruck.java
index 106fe82..a2570d1 100644
--- a/src/main/java/rinde/evo4mas/gendreau06/HeuristicTruck.java
+++ b/src/main/java/rinde/evo4mas/gendreau06/HeuristicTruck.java
@@ -1,308 +1,309 @@
package rinde.evo4mas.gendreau06;
import static com.google.common.collect.Sets.newLinkedHashSet;
import java.util.Collection;
import java.util.Set;
import rinde.ecj.Heuristic;
import rinde.evo4mas.common.TruckContext;
import rinde.sim.core.TimeLapse;
import rinde.sim.core.graph.Point;
import rinde.sim.core.model.pdp.PDPModel;
import rinde.sim.core.model.pdp.PDPModel.ParcelState;
import rinde.sim.core.model.pdp.Parcel;
import rinde.sim.core.model.road.RoadModel;
import rinde.sim.event.Event;
import rinde.sim.event.Listener;
import rinde.sim.problem.common.DefaultParcel;
import rinde.sim.problem.common.DefaultVehicle;
import rinde.sim.problem.common.ParcelDTO;
import rinde.sim.problem.common.VehicleDTO;
import rinde.sim.util.fsm.StateMachine;
import rinde.sim.util.fsm.StateMachine.State;
public class HeuristicTruck extends DefaultVehicle implements Listener {
protected final Heuristic<TruckContext> program;
protected boolean hasChanged = true;
protected Parcel currentTarget;
protected CoordinationModel coordinationModel;
protected final StateMachine<TruckEvent, HeuristicTruck> stateMachine;
enum TruckEvent {
CHANGE, END_OF_DAY, READY, ARRIVE, DONE, CONTINUE, YES, NO;
}
public HeuristicTruck(VehicleDTO pDto, Heuristic<TruckContext> p) {
super(pDto);
program = p;
stateMachine = StateMachine.create(TruckState.IDLE)/* */
.addTransition(TruckState.IDLE, TruckEvent.CHANGE, TruckState.HAS_TARGET) /* */
.addTransition(TruckState.IDLE, TruckEvent.END_OF_DAY, TruckState.GO_HOME) /* */
.addTransition(TruckState.HAS_TARGET, TruckEvent.YES, TruckState.IS_EARLY) /* */
.addTransition(TruckState.HAS_TARGET, TruckEvent.NO, TruckState.IS_END_OF_DAY) /* */
.addTransition(TruckState.IS_END_OF_DAY, TruckEvent.YES, TruckState.GO_HOME) /* */
.addTransition(TruckState.IS_END_OF_DAY, TruckEvent.NO, TruckState.IDLE) /* */
.addTransition(TruckState.IS_EARLY, TruckEvent.YES, TruckState.EARLY_TARGET) /* */
.addTransition(TruckState.IS_EARLY, TruckEvent.NO, TruckState.IS_IN_CARGO) /* */
.addTransition(TruckState.IS_IN_CARGO, TruckEvent.YES, TruckState.GOTO_DELIVERY) /* */
.addTransition(TruckState.IS_IN_CARGO, TruckEvent.NO, TruckState.GOTO_PICKUP) /* */
.addTransition(TruckState.EARLY_TARGET, TruckEvent.CHANGE, TruckState.HAS_TARGET) /* */
.addTransition(TruckState.EARLY_TARGET, TruckEvent.READY, TruckState.HAS_TARGET) /* */
.addTransition(TruckState.GOTO_DELIVERY, TruckEvent.ARRIVE, TruckState.DELIVER) /* */
.addTransition(TruckState.GOTO_PICKUP, TruckEvent.ARRIVE, TruckState.PICKUP) /* */
.addTransition(TruckState.DELIVER, TruckEvent.DONE, TruckState.HAS_TARGET) /* */
.addTransition(TruckState.PICKUP, TruckEvent.DONE, TruckState.HAS_TARGET) /* */
.addTransition(TruckState.GO_HOME, TruckEvent.CHANGE, TruckState.HAS_TARGET) /* */
.addTransition(TruckState.GO_HOME, TruckEvent.ARRIVE, TruckState.IDLE) /* */
.build();
// System.out.println(stateMachine.toDot());
}
protected Parcel next(long time) {
return next(program, dto, pdpModel.getParcels(ParcelState.ANNOUNCED, ParcelState.AVAILABLE), pdpModel.getContents(this), coordinationModel
.getClaims(), roadModel.getPosition(this), time);
}
protected static Parcel next(Heuristic<TruckContext> program, VehicleDTO dto, Collection<Parcel> todo,
Collection<Parcel> contents, Set<Parcel> alreadyClaimed, Point truckPos, long time) {
Parcel best = null;
double bestValue = Double.POSITIVE_INFINITY;
boolean isPickup = true;
+ final StringBuilder sb = new StringBuilder();
final Collection<ParcelDTO> contentDTOs = convert(contents);
for (final Parcel p : todo) {
// filter out the already claimed parcels
if (!alreadyClaimed.contains(p)) {
final double v = program.compute(new TruckContext(dto, truckPos, contentDTOs, ((DefaultParcel) p).dto,
time, false));
- if (v < bestValue) {
+ if (v < bestValue || (v == Double.POSITIVE_INFINITY && bestValue == v)) {
best = p;
bestValue = v;
}
}
}
for (final Parcel p : contents) {
final double v = program.compute(new TruckContext(dto, truckPos, contentDTOs, ((DefaultParcel) p).dto,
time, true));
- if (v < bestValue) {
+ if (v < bestValue || (v == Double.POSITIVE_INFINITY && bestValue == v)) {
best = p;
bestValue = v;
isPickup = false;
}
}
return best;
}
protected boolean isTooEarly(Parcel p, Point truckPos, long time) {
final boolean isPickup = pdpModel.getParcelState(currentTarget) == ParcelState.IN_CARGO;
final Point loc = isPickup ? ((DefaultParcel) p).dto.pickupLocation : p.getDestination();
final long travelTime = (long) ((Point.distance(loc, truckPos) / 30d) * 3600000d);
final long timeToBegin = (isPickup ? p.getPickupTimeWindow().begin : p.getDeliveryTimeWindow().begin) - time;
return timeToBegin >= 0 && timeToBegin - travelTime > 1000;
}
TimeLapse currentTime;
HeuristicTruck truck;
@Override
protected void tickImpl(TimeLapse time) {
currentTime = time;
truck = this;
if (hasChanged && stateMachine.isSupported(TruckEvent.CHANGE)) {
stateMachine.handle(TruckEvent.CHANGE, this);
hasChanged = false;
} else {
stateMachine.handle(this);
}
if (time.hasTimeLeft() && !stateMachine.stateIsOneOf(TruckState.IDLE, TruckState.EARLY_TARGET)) {
System.err.println(time.getTimeLeft() + " not used");
}
}
protected boolean isEndOfDay(TimeLapse time) {
return time.hasTimeLeft()
&& time.getTime() > dto.availabilityTimeWindow.end
- ((Point.distance(roadModel.getPosition(this), dto.startPosition) / getSpeed()) * 3600000);
}
enum TruckState implements State<TruckEvent, HeuristicTruck> {
IDLE {
@Override
public TruckEvent handle(TruckEvent event, HeuristicTruck context) {
return null;
}
},
HAS_TARGET {
@Override
public TruckEvent handle(TruckEvent event, HeuristicTruck context) {
context.currentTarget = context.next(context.currentTime.getTime());
return context.currentTarget != null ? TruckEvent.YES : TruckEvent.NO;
}
},
IS_END_OF_DAY {
@Override
public TruckEvent handle(TruckEvent event, HeuristicTruck context) {
if (context.isEndOfDay(context.currentTime)) {
return TruckEvent.YES;
} else {
return TruckEvent.NO;
}
}
},
IS_EARLY {
@Override
public TruckEvent handle(TruckEvent event, HeuristicTruck context) {
return context
.isTooEarly(context.currentTarget, context.roadModel.getPosition(context), context.currentTime
.getTime()) ? TruckEvent.YES : TruckEvent.NO;
}
},
IS_IN_CARGO {
@Override
public TruckEvent handle(TruckEvent event, HeuristicTruck context) {
return context.pdpModel.getParcelState(context.currentTarget) == ParcelState.IN_CARGO ? TruckEvent.YES
: TruckEvent.NO;
}
},
// DECIDE {
// @Override
// public TruckEvent handle(TruckEvent event, Truck context) {
// context.currentTarget = context.next(context.currentTime.getTime());
// if (context.currentTarget == null) {
// if (context.isEndOfDay(context.currentTime)) {
// return TruckEvent.END_OF_DAY;
// } else {
// return TruckEvent.NO_TARGET;
// }
// } else if (context
// .isTooEarly(context.currentTarget,
// context.roadModel.getPosition(context), context.currentTime
// .getTime())) {
// return TruckEvent.EARLY;
// } else if (context.pdpModel.getParcelState(context.currentTarget) ==
// ParcelState.IN_CARGO) {
// return TruckEvent.IN_CARGO;
// } else {
// return TruckEvent.IS_AVAILABLE;
// }
// }
// },
EARLY_TARGET {
@Override
public TruckEvent handle(TruckEvent event, HeuristicTruck context) {
if (!context
.isTooEarly(context.currentTarget, context.roadModel.getPosition(context.truck), context.currentTime
.getTime())) {
return TruckEvent.READY;
}
return null;
}
},
GOTO_DELIVERY {
@Override
public TruckEvent handle(TruckEvent event, HeuristicTruck context) {
context.roadModel.moveTo(context.truck, context.currentTarget.getDestination(), context.currentTime);
if (context.roadModel.getPosition(context.truck).equals(context.currentTarget.getDestination())) {
return TruckEvent.ARRIVE;
}
return null;
}
},
DELIVER {
@Override
public void onEntry(TruckEvent event, HeuristicTruck context) {
context.pdpModel.deliver(context.truck, context.currentTarget, context.currentTime);
}
@Override
public TruckEvent handle(TruckEvent event, HeuristicTruck context) {
if (context.currentTime.hasTimeLeft()) {
return TruckEvent.DONE;
}
return null;
}
},
GOTO_PICKUP {
@Override
public void onEntry(TruckEvent event, HeuristicTruck context) {
context.coordinationModel.claim(context.currentTarget);
}
@Override
public TruckEvent handle(TruckEvent event, HeuristicTruck context) {
context.roadModel.moveTo(context.truck, context.currentTarget, context.currentTime);
if (context.roadModel.equalPosition(context.truck, context.currentTarget)) {
return TruckEvent.ARRIVE;
}
return null;
}
},
PICKUP {
@Override
public void onEntry(TruckEvent event, HeuristicTruck context) {
context.pdpModel.pickup(context.truck, context.currentTarget, context.currentTime);
}
@Override
public TruckEvent handle(TruckEvent event, HeuristicTruck context) {
if (context.currentTime.hasTimeLeft()) {
return TruckEvent.DONE;
}
return null;
}
},
GO_HOME {
@Override
public TruckEvent handle(TruckEvent event, HeuristicTruck context) {
context.roadModel.moveTo(context.truck, context.dto.startPosition, context.currentTime);
if (context.roadModel.getPosition(context.truck).equals(context.dto.startPosition)) {
return TruckEvent.ARRIVE;
}
return null;
}
};
public abstract TruckEvent handle(TruckEvent event, HeuristicTruck context);
public void onEntry(TruckEvent event, HeuristicTruck context) {}
public void onExit(TruckEvent event, HeuristicTruck context) {}
}
public void setCoordinationModel(CoordinationModel cm) {
coordinationModel = cm;
}
public Heuristic<TruckContext> getProgram() {
return program;
}
@Override
public void initRoadPDP(RoadModel rm, PDPModel pdp) {
super.initRoadPDP(rm, pdp);
pdpModel.getEventAPI().addListener(this, PDPModel.PDPModelEventType.NEW_PARCEL);
}
static Set<ParcelDTO> convert(Collection<Parcel> parcels) {
final Set<ParcelDTO> dtos = newLinkedHashSet();
for (final Parcel p : parcels) {
dtos.add(((DefaultParcel) p).dto);
}
return dtos;
}
public void handleEvent(Event e) {
hasChanged = true;
}
}
| false | true | protected static Parcel next(Heuristic<TruckContext> program, VehicleDTO dto, Collection<Parcel> todo,
Collection<Parcel> contents, Set<Parcel> alreadyClaimed, Point truckPos, long time) {
Parcel best = null;
double bestValue = Double.POSITIVE_INFINITY;
boolean isPickup = true;
final Collection<ParcelDTO> contentDTOs = convert(contents);
for (final Parcel p : todo) {
// filter out the already claimed parcels
if (!alreadyClaimed.contains(p)) {
final double v = program.compute(new TruckContext(dto, truckPos, contentDTOs, ((DefaultParcel) p).dto,
time, false));
if (v < bestValue) {
best = p;
bestValue = v;
}
}
}
for (final Parcel p : contents) {
final double v = program.compute(new TruckContext(dto, truckPos, contentDTOs, ((DefaultParcel) p).dto,
time, true));
if (v < bestValue) {
best = p;
bestValue = v;
isPickup = false;
}
}
return best;
}
| protected static Parcel next(Heuristic<TruckContext> program, VehicleDTO dto, Collection<Parcel> todo,
Collection<Parcel> contents, Set<Parcel> alreadyClaimed, Point truckPos, long time) {
Parcel best = null;
double bestValue = Double.POSITIVE_INFINITY;
boolean isPickup = true;
final StringBuilder sb = new StringBuilder();
final Collection<ParcelDTO> contentDTOs = convert(contents);
for (final Parcel p : todo) {
// filter out the already claimed parcels
if (!alreadyClaimed.contains(p)) {
final double v = program.compute(new TruckContext(dto, truckPos, contentDTOs, ((DefaultParcel) p).dto,
time, false));
if (v < bestValue || (v == Double.POSITIVE_INFINITY && bestValue == v)) {
best = p;
bestValue = v;
}
}
}
for (final Parcel p : contents) {
final double v = program.compute(new TruckContext(dto, truckPos, contentDTOs, ((DefaultParcel) p).dto,
time, true));
if (v < bestValue || (v == Double.POSITIVE_INFINITY && bestValue == v)) {
best = p;
bestValue = v;
isPickup = false;
}
}
return best;
}
|
diff --git a/src/guitarra/Guitarra.java b/src/guitarra/Guitarra.java
old mode 100644
new mode 100755
index 4dc7b40..09043cd
--- a/src/guitarra/Guitarra.java
+++ b/src/guitarra/Guitarra.java
@@ -1,82 +1,83 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package guitarra;
import java.awt.Graphics;
import java.util.ArrayList;
import javaPlay.GameObject;
import utilidades.Utilidades;
/**
*
* @author fernando_mota
*/
public class Guitarra extends GameObject{
public static Guitarra instancia = null;
public boolean podeEspecial() {
return Utilidades.sorteia() && this.podeEspecial();
}
protected int[][] notas;
protected Esfera[] esferas;
protected int level;
protected ArrayList<Esfera> notasEsferas;
protected long timeElapsed;
public Guitarra(){
this.esferas = new Esfera[5];
this.esferas[0] = new Verde();
this.esferas[1] = new Vermelha();
this.esferas[2] = new Amarela();
this.esferas[3] = new Azul();
this.esferas[4] = new Laranja();
for(int c=0;c<this.esferas.length;c++){
this.esferas[c].setSerie(c+1);
}
this.notasEsferas = new ArrayList<Esfera>();
}
static Guitarra getInstance() {
if(Guitarra.instancia == null){
Guitarra.instancia = new Guitarra();
}
return Guitarra.instancia;
}
public void setLevel(int level){
this.level = level+1;
}
private Esfera[] getNotas(){
for(int[] nota: notas){
if(nota.length<this.level){
continue;//Ignora notas com menos de 1 elemento
}
if(this.getSecondsElapsed() == nota[0]){//Verifica se é a nota à ser considerada
Esfera[] esferasNotas = new Esfera[this.level];
for(int c=0;c<this.level;c++){
esferasNotas[c] = this.esferas[nota[c]].getNewInstance();
}
return esferasNotas;
}
}
+ return new Esfera[0];
}
protected int getSecondsElapsed(){
return (int) (this.timeElapsed/1000);
}
public void step(long timeElapsed) {
this.timeElapsed += timeElapsed;
for(Esfera nota: this.notasEsferas){
nota.step(timeElapsed);
}
}
@Override
public void draw(Graphics g) {
for(Esfera nota: this.notasEsferas){
nota.draw(g);
}
}
void adicionaPontos(int pontos) {
}
}
| true | true | private Esfera[] getNotas(){
for(int[] nota: notas){
if(nota.length<this.level){
continue;//Ignora notas com menos de 1 elemento
}
if(this.getSecondsElapsed() == nota[0]){//Verifica se é a nota à ser considerada
Esfera[] esferasNotas = new Esfera[this.level];
for(int c=0;c<this.level;c++){
esferasNotas[c] = this.esferas[nota[c]].getNewInstance();
}
return esferasNotas;
}
}
}
| private Esfera[] getNotas(){
for(int[] nota: notas){
if(nota.length<this.level){
continue;//Ignora notas com menos de 1 elemento
}
if(this.getSecondsElapsed() == nota[0]){//Verifica se é a nota à ser considerada
Esfera[] esferasNotas = new Esfera[this.level];
for(int c=0;c<this.level;c++){
esferasNotas[c] = this.esferas[nota[c]].getNewInstance();
}
return esferasNotas;
}
}
return new Esfera[0];
}
|
diff --git a/src/org/openjump/core/ui/plugin/layer/SortCategoryByNamePlugIn.java b/src/org/openjump/core/ui/plugin/layer/SortCategoryByNamePlugIn.java
index 3e8c1285..c069b161 100644
--- a/src/org/openjump/core/ui/plugin/layer/SortCategoryByNamePlugIn.java
+++ b/src/org/openjump/core/ui/plugin/layer/SortCategoryByNamePlugIn.java
@@ -1,108 +1,110 @@
/*
* The Unified Mapping Platform (JUMP) is an extensible, interactive GUI
* for visualizing and manipulating spatial features with geometry and attributes.
*
* JUMP is Copyright (C) 2003 Vivid Solutions
*
* This program implements extensions to JUMP and is
* Copyright (C) 2004 Integrated Systems Analysts, Inc.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* For more information, contact:
*
* Integrated Systems Analysts, Inc.
* 630C Anchors St., Suite 101
* Fort Walton Beach, Florida
* USA
*
* (850)862-7321
* www.ashs.isa.com
*/
package org.openjump.core.ui.plugin.layer;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import javax.swing.ImageIcon;
import com.vividsolutions.jump.I18N;
import com.vividsolutions.jump.workbench.model.Category;
import com.vividsolutions.jump.workbench.model.Layerable;
import com.vividsolutions.jump.workbench.plugin.PlugInContext;
/**
* Sort categories by name
*
* @author clark4444
*
*/
public class SortCategoryByNamePlugIn extends SortCategoryAbstractPlugIn implements ActionListener {
private static final ImageIcon ICON = null;
private String submenuLabel = "By Name";
private String descending = "Descending";
private String ascending = "Ascending";
@Override
protected void addMenuOptions(PlugInContext context) {
this.submenuLabel = I18N
.get("org.openjump.core.ui.plugin.layer.SortCategoryByNamePlugIn.By-Name");
this.descending = I18N
.get("org.openjump.core.ui.plugin.layer.SortCategoryByNamePlugIn.Descending");
this.ascending = I18N
.get("org.openjump.core.ui.plugin.layer.SortCategoryByNamePlugIn.Ascending");
- context.getFeatureInstaller().addMainMenuItemWithJava14Fix(this,
+//addMainMenuItemWithJava14Fix causing error with ja_JP language, but worked with others
+// context.getFeatureInstaller().addMainMenuItemWithJava14Fix(this,
+ context.getFeatureInstaller().addMainMenuItem(this,
getMenuLocation(submenuLabel), ascending, false, ICON,
createEnableCheck(context.getWorkbenchContext()));
- context.getFeatureInstaller().addMainMenuItemWithJava14Fix(this,
+ context.getFeatureInstaller().addMainMenuItem(this,
getMenuLocation(submenuLabel), descending, false, ICON,
createEnableCheck(context.getWorkbenchContext()));
}
@Override
protected String getSubMenuLabel() {
return submenuLabel;
}
@Override
ArrayList<Layerable> getOrderedLayersInCategory(Category category, String sortLabel) {
ArrayList<Layerable> layers = getCategoryArrayList(category);
if (sortLabel.equals(ascending)) {
Collections.sort(layers, new LayerableNameSort());
}
else if (sortLabel.equals(descending)) {
Collections.sort(layers, Collections.reverseOrder(new LayerableNameSort()));
}
else
throw new IllegalStateException();
return layers;
}
class LayerableNameSort implements Comparator<Layerable> {
public int compare(Layerable layer1, Layerable layer2) {
return layer2.getName().compareTo(layer1.getName());
}
}
}
| false | true | protected void addMenuOptions(PlugInContext context) {
this.submenuLabel = I18N
.get("org.openjump.core.ui.plugin.layer.SortCategoryByNamePlugIn.By-Name");
this.descending = I18N
.get("org.openjump.core.ui.plugin.layer.SortCategoryByNamePlugIn.Descending");
this.ascending = I18N
.get("org.openjump.core.ui.plugin.layer.SortCategoryByNamePlugIn.Ascending");
context.getFeatureInstaller().addMainMenuItemWithJava14Fix(this,
getMenuLocation(submenuLabel), ascending, false, ICON,
createEnableCheck(context.getWorkbenchContext()));
context.getFeatureInstaller().addMainMenuItemWithJava14Fix(this,
getMenuLocation(submenuLabel), descending, false, ICON,
createEnableCheck(context.getWorkbenchContext()));
}
| protected void addMenuOptions(PlugInContext context) {
this.submenuLabel = I18N
.get("org.openjump.core.ui.plugin.layer.SortCategoryByNamePlugIn.By-Name");
this.descending = I18N
.get("org.openjump.core.ui.plugin.layer.SortCategoryByNamePlugIn.Descending");
this.ascending = I18N
.get("org.openjump.core.ui.plugin.layer.SortCategoryByNamePlugIn.Ascending");
//addMainMenuItemWithJava14Fix causing error with ja_JP language, but worked with others
// context.getFeatureInstaller().addMainMenuItemWithJava14Fix(this,
context.getFeatureInstaller().addMainMenuItem(this,
getMenuLocation(submenuLabel), ascending, false, ICON,
createEnableCheck(context.getWorkbenchContext()));
context.getFeatureInstaller().addMainMenuItem(this,
getMenuLocation(submenuLabel), descending, false, ICON,
createEnableCheck(context.getWorkbenchContext()));
}
|
diff --git a/java/examples/CreateDisk.java b/java/examples/CreateDisk.java
index 381fae1f2..83e0ff621 100644
--- a/java/examples/CreateDisk.java
+++ b/java/examples/CreateDisk.java
@@ -1,84 +1,84 @@
// Example showing how to create a disk image.
import java.io.*;
import java.util.Map;
import java.util.HashMap;
import com.redhat.et.libguestfs.*;
public class CreateDisk
{
static String output = "disk.img";
public static void main (String[] argv)
{
try {
GuestFS g = new GuestFS ();
// Create a raw-format sparse disk image, 512 MB in size.
RandomAccessFile f = new RandomAccessFile (output, "rw");
f.setLength (512 * 1024 * 1024);
f.close ();
// Set the trace flag so that we can see each libguestfs call.
g.set_trace (true);
// Attach the disk image to libguestfs.
Map<String, Object> optargs = new HashMap<String, Object>() {
{
put ("format", "raw");
put ("readonly", Boolean.FALSE);
}
};
g.add_drive_opts (output, optargs);
// Run the libguestfs back-end.
g.launch ();
// Get the list of devices. Because we only added one drive
// above, we expect that this list should contain a single
// element.
String[] devices = g.list_devices ();
if (devices.length != 1)
throw new Error ("expected a single device from list-devices");
// Partition the disk as one single MBR partition.
g.part_disk (devices[0], "mbr");
// Get the list of partitions. We expect a single element, which
// is the partition we have just created.
String[] partitions = g.list_partitions ();
if (partitions.length != 1)
throw new Error ("expected a single partition from list-partitions");
// Create a filesystem on the partition.
g.mkfs ("ext4", partitions[0]);
// Now mount the filesystem so that we can add files.
- g.mount_options ("", partitions[0], "/");
+ g.mount (partitions[0], "/");
// Create some files and directories.
g.touch ("/empty");
String message = "Hello, world\n";
g.write ("/hello", message.getBytes());
g.mkdir ("/foo");
// This one uploads the local file /etc/resolv.conf into
// the disk image.
g.upload ("/etc/resolv.conf", "/foo/resolv.conf");
// Because we wrote to the disk and we want to detect write
// errors, call g.shutdown. You don't need to do this:
// g.close will do it implicitly.
g.shutdown ();
// Note also that handles are automatically closed if they are
// reaped by the garbage collector. You only need to call close
// if you want to close the handle right away.
g.close ();
}
catch (Exception exn) {
System.err.println (exn);
System.exit (1);
}
}
}
| true | true | public static void main (String[] argv)
{
try {
GuestFS g = new GuestFS ();
// Create a raw-format sparse disk image, 512 MB in size.
RandomAccessFile f = new RandomAccessFile (output, "rw");
f.setLength (512 * 1024 * 1024);
f.close ();
// Set the trace flag so that we can see each libguestfs call.
g.set_trace (true);
// Attach the disk image to libguestfs.
Map<String, Object> optargs = new HashMap<String, Object>() {
{
put ("format", "raw");
put ("readonly", Boolean.FALSE);
}
};
g.add_drive_opts (output, optargs);
// Run the libguestfs back-end.
g.launch ();
// Get the list of devices. Because we only added one drive
// above, we expect that this list should contain a single
// element.
String[] devices = g.list_devices ();
if (devices.length != 1)
throw new Error ("expected a single device from list-devices");
// Partition the disk as one single MBR partition.
g.part_disk (devices[0], "mbr");
// Get the list of partitions. We expect a single element, which
// is the partition we have just created.
String[] partitions = g.list_partitions ();
if (partitions.length != 1)
throw new Error ("expected a single partition from list-partitions");
// Create a filesystem on the partition.
g.mkfs ("ext4", partitions[0]);
// Now mount the filesystem so that we can add files.
g.mount_options ("", partitions[0], "/");
// Create some files and directories.
g.touch ("/empty");
String message = "Hello, world\n";
g.write ("/hello", message.getBytes());
g.mkdir ("/foo");
// This one uploads the local file /etc/resolv.conf into
// the disk image.
g.upload ("/etc/resolv.conf", "/foo/resolv.conf");
// Because we wrote to the disk and we want to detect write
// errors, call g.shutdown. You don't need to do this:
// g.close will do it implicitly.
g.shutdown ();
// Note also that handles are automatically closed if they are
// reaped by the garbage collector. You only need to call close
// if you want to close the handle right away.
g.close ();
}
catch (Exception exn) {
System.err.println (exn);
System.exit (1);
}
}
| public static void main (String[] argv)
{
try {
GuestFS g = new GuestFS ();
// Create a raw-format sparse disk image, 512 MB in size.
RandomAccessFile f = new RandomAccessFile (output, "rw");
f.setLength (512 * 1024 * 1024);
f.close ();
// Set the trace flag so that we can see each libguestfs call.
g.set_trace (true);
// Attach the disk image to libguestfs.
Map<String, Object> optargs = new HashMap<String, Object>() {
{
put ("format", "raw");
put ("readonly", Boolean.FALSE);
}
};
g.add_drive_opts (output, optargs);
// Run the libguestfs back-end.
g.launch ();
// Get the list of devices. Because we only added one drive
// above, we expect that this list should contain a single
// element.
String[] devices = g.list_devices ();
if (devices.length != 1)
throw new Error ("expected a single device from list-devices");
// Partition the disk as one single MBR partition.
g.part_disk (devices[0], "mbr");
// Get the list of partitions. We expect a single element, which
// is the partition we have just created.
String[] partitions = g.list_partitions ();
if (partitions.length != 1)
throw new Error ("expected a single partition from list-partitions");
// Create a filesystem on the partition.
g.mkfs ("ext4", partitions[0]);
// Now mount the filesystem so that we can add files.
g.mount (partitions[0], "/");
// Create some files and directories.
g.touch ("/empty");
String message = "Hello, world\n";
g.write ("/hello", message.getBytes());
g.mkdir ("/foo");
// This one uploads the local file /etc/resolv.conf into
// the disk image.
g.upload ("/etc/resolv.conf", "/foo/resolv.conf");
// Because we wrote to the disk and we want to detect write
// errors, call g.shutdown. You don't need to do this:
// g.close will do it implicitly.
g.shutdown ();
// Note also that handles are automatically closed if they are
// reaped by the garbage collector. You only need to call close
// if you want to close the handle right away.
g.close ();
}
catch (Exception exn) {
System.err.println (exn);
System.exit (1);
}
}
|
diff --git a/src/main/java/org/apache/hadoop/hbase/master/handler/ServerShutdownHandler.java b/src/main/java/org/apache/hadoop/hbase/master/handler/ServerShutdownHandler.java
index 34067afee..4754ff081 100644
--- a/src/main/java/org/apache/hadoop/hbase/master/handler/ServerShutdownHandler.java
+++ b/src/main/java/org/apache/hadoop/hbase/master/handler/ServerShutdownHandler.java
@@ -1,397 +1,393 @@
/**
* Copyright 2010 The Apache Software Foundation
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.master.handler;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HRegionInfo;
import org.apache.hadoop.hbase.Server;
import org.apache.hadoop.hbase.ServerName;
import org.apache.hadoop.hbase.catalog.CatalogTracker;
import org.apache.hadoop.hbase.catalog.MetaEditor;
import org.apache.hadoop.hbase.catalog.MetaReader;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.executor.EventHandler;
import org.apache.hadoop.hbase.master.AssignmentManager;
import org.apache.hadoop.hbase.master.AssignmentManager.RegionState;
import org.apache.hadoop.hbase.master.DeadServer;
import org.apache.hadoop.hbase.master.MasterServices;
import org.apache.hadoop.hbase.master.ServerManager;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.Writables;
import org.apache.zookeeper.KeeperException;
/**
* Process server shutdown.
* Server-to-handle must be already in the deadservers lists. See
* {@link ServerManager#expireServer(ServerName)}
*/
public class ServerShutdownHandler extends EventHandler {
private static final Log LOG = LogFactory.getLog(ServerShutdownHandler.class);
private final ServerName serverName;
private final MasterServices services;
private final DeadServer deadServers;
public ServerShutdownHandler(final Server server, final MasterServices services,
final DeadServer deadServers, final ServerName serverName) {
this(server, services, deadServers, serverName, EventType.M_SERVER_SHUTDOWN);
}
ServerShutdownHandler(final Server server, final MasterServices services,
final DeadServer deadServers, final ServerName serverName, EventType type) {
super(server, type);
this.serverName = serverName;
this.server = server;
this.services = services;
this.deadServers = deadServers;
if (!this.deadServers.contains(this.serverName)) {
LOG.warn(this.serverName + " is NOT in deadservers; it should be!");
}
}
@Override
public String getInformativeName() {
if (serverName != null) {
return this.getClass().getSimpleName() + " for " + serverName;
} else {
return super.getInformativeName();
}
}
/**
* Before assign the ROOT region, ensure it haven't
* been assigned by other place
* <p>
* Under some scenarios, the ROOT region can be opened twice, so it seemed online
* in two regionserver at the same time.
* If the ROOT region has been assigned, so the operation can be canceled.
* @throws InterruptedException
* @throws IOException
* @throws KeeperException
*/
private void verifyAndAssignRoot()
throws InterruptedException, IOException, KeeperException {
long timeout = this.server.getConfiguration().
getLong("hbase.catalog.verification.timeout", 1000);
if (!this.server.getCatalogTracker().verifyRootRegionLocation(timeout)) {
this.services.getAssignmentManager().assignRoot();
}
}
/**
* Failed many times, shutdown processing
* @throws IOException
*/
private void verifyAndAssignRootWithRetries() throws IOException {
int iTimes = this.server.getConfiguration().getInt(
"hbase.catalog.verification.retries", 10);
long waitTime = this.server.getConfiguration().getLong(
"hbase.catalog.verification.timeout", 1000);
int iFlag = 0;
while (true) {
try {
verifyAndAssignRoot();
break;
} catch (KeeperException e) {
this.server.abort("In server shutdown processing, assigning root", e);
throw new IOException("Aborting", e);
} catch (Exception e) {
if (iFlag >= iTimes) {
this.server.abort("verifyAndAssignRoot failed after" + iTimes
+ " times retries, aborting", e);
throw new IOException("Aborting", e);
}
try {
Thread.sleep(waitTime);
} catch (InterruptedException e1) {
LOG.warn("Interrupted when is the thread sleep", e1);
Thread.currentThread().interrupt();
throw new IOException("Interrupted", e1);
}
iFlag++;
}
}
}
/**
* @return True if the server we are processing was carrying <code>-ROOT-</code>
*/
boolean isCarryingRoot() {
return false;
}
/**
* @return True if the server we are processing was carrying <code>.META.</code>
*/
boolean isCarryingMeta() {
return false;
}
@Override
public String toString() {
String name = "UnknownServerName";
if(server != null && server.getServerName() != null) {
name = server.getServerName().toString();
}
return getClass().getSimpleName() + "-" + name + "-" + getSeqid();
}
@Override
public void process() throws IOException {
final ServerName serverName = this.serverName;
LOG.info("Splitting logs for " + serverName);
this.services.getMasterFileSystem().splitLog(serverName);
// Clean out anything in regions in transition. Being conservative and
// doing after log splitting. Could do some states before -- OPENING?
// OFFLINE? -- and then others after like CLOSING that depend on log
// splitting.
List<RegionState> regionsInTransition =
this.services.getAssignmentManager().processServerShutdown(this.serverName);
// Assign root and meta if we were carrying them.
if (isCarryingRoot()) { // -ROOT-
- LOG.info("Server " + serverName + " was carrying ROOT. Trying to assign.");
verifyAndAssignRootWithRetries();
}
// Carrying meta?
- if (isCarryingMeta()) {
- LOG.info("Server " + serverName + " was carrying META. Trying to assign.");
- this.services.getAssignmentManager().assignMeta();
- }
+ if (isCarryingMeta()) this.services.getAssignmentManager().assignMeta();
// Wait on meta to come online; we need it to progress.
// TODO: Best way to hold strictly here? We should build this retry logic
// into the MetaReader operations themselves.
// TODO: Is the reading of .META. necessary when the Master has state of
// cluster in its head? It should be possible to do without reading .META.
// in all but one case. On split, the RS updates the .META.
// table and THEN informs the master of the split via zk nodes in
// 'unassigned' dir. Currently the RS puts ephemeral nodes into zk so if
// the regionserver dies, these nodes do not stick around and this server
// shutdown processing does fixup (see the fixupDaughters method below).
// If we wanted to skip the .META. scan, we'd have to change at least the
// final SPLIT message to be permanent in zk so in here we'd know a SPLIT
// completed (zk is updated after edits to .META. have gone in). See
// {@link SplitTransaction}. We'd also have to be figure another way for
// doing the below .META. daughters fixup.
NavigableMap<HRegionInfo, Result> hris = null;
while (!this.server.isStopped()) {
try {
this.server.getCatalogTracker().waitForMeta();
hris = MetaReader.getServerUserRegions(this.server.getCatalogTracker(),
this.serverName);
break;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IOException("Interrupted", e);
} catch (IOException ioe) {
LOG.info("Received exception accessing META during server shutdown of " +
serverName + ", retrying META read", ioe);
}
}
// Skip regions that were in transition unless CLOSING or PENDING_CLOSE
for (RegionState rit : regionsInTransition) {
if (!rit.isClosing() && !rit.isPendingClose()) {
LOG.debug("Removed " + rit.getRegion().getRegionNameAsString() +
" from list of regions to assign because in RIT");
hris.remove(rit.getRegion());
}
}
LOG.info("Reassigning " + (hris == null? 0: hris.size()) +
" region(s) that " + serverName +
" was carrying (skipping " + regionsInTransition.size() +
" regions(s) that are already in transition)");
// Iterate regions that were on this server and assign them
if (hris != null) {
for (Map.Entry<HRegionInfo, Result> e: hris.entrySet()) {
if (processDeadRegion(e.getKey(), e.getValue(),
this.services.getAssignmentManager(),
this.server.getCatalogTracker())) {
this.services.getAssignmentManager().assign(e.getKey(), true);
}
}
}
this.deadServers.finish(serverName);
LOG.info("Finished processing of shutdown of " + serverName);
}
/**
* Process a dead region from a dead RS. Checks if the region is disabled
* or if the region has a partially completed split.
* @param hri
* @param result
* @param assignmentManager
* @param catalogTracker
* @return Returns true if specified region should be assigned, false if not.
* @throws IOException
*/
public static boolean processDeadRegion(HRegionInfo hri, Result result,
AssignmentManager assignmentManager, CatalogTracker catalogTracker)
throws IOException {
// If table is not disabled but the region is offlined,
boolean disabled = assignmentManager.getZKTable().isDisabledTable(
hri.getTableNameAsString());
if (disabled) return false;
if (hri.isOffline() && hri.isSplit()) {
LOG.debug("Offlined and split region " + hri.getRegionNameAsString() +
"; checking daughter presence");
fixupDaughters(result, assignmentManager, catalogTracker);
return false;
}
return true;
}
/**
* Check that daughter regions are up in .META. and if not, add them.
* @param hris All regions for this server in meta.
* @param result The contents of the parent row in .META.
* @throws IOException
*/
static void fixupDaughters(final Result result,
final AssignmentManager assignmentManager,
final CatalogTracker catalogTracker)
throws IOException {
fixupDaughter(result, HConstants.SPLITA_QUALIFIER, assignmentManager,
catalogTracker);
fixupDaughter(result, HConstants.SPLITB_QUALIFIER, assignmentManager,
catalogTracker);
}
/**
* Check individual daughter is up in .META.; fixup if its not.
* @param result The contents of the parent row in .META.
* @param qualifier Which daughter to check for.
* @throws IOException
*/
static void fixupDaughter(final Result result, final byte [] qualifier,
final AssignmentManager assignmentManager,
final CatalogTracker catalogTracker)
throws IOException {
HRegionInfo daughter = getHRegionInfo(result, qualifier);
if (daughter == null) return;
if (isDaughterMissing(catalogTracker, daughter)) {
LOG.info("Fixup; missing daughter " + daughter.getRegionNameAsString());
MetaEditor.addDaughter(catalogTracker, daughter, null);
// And assign it.
assignmentManager.assign(daughter, true);
} else {
LOG.debug("Daughter " + daughter.getRegionNameAsString() + " present");
}
}
/**
* Interpret the content of the cell at {@link HConstants#CATALOG_FAMILY} and
* <code>qualifier</code> as an HRegionInfo and return it, or null.
* @param r Result instance to pull from.
* @param qualifier Column family qualifier
* @return An HRegionInfo instance or null.
* @throws IOException
*/
private static HRegionInfo getHRegionInfo(final Result r, byte [] qualifier)
throws IOException {
byte [] bytes = r.getValue(HConstants.CATALOG_FAMILY, qualifier);
if (bytes == null || bytes.length <= 0) return null;
return Writables.getHRegionInfoOrNull(bytes);
}
/**
* Look for presence of the daughter OR of a split of the daughter in .META.
* Daughter could have been split over on regionserver before a run of the
* catalogJanitor had chance to clear reference from parent.
* @param daughter Daughter region to search for.
* @throws IOException
*/
private static boolean isDaughterMissing(final CatalogTracker catalogTracker,
final HRegionInfo daughter) throws IOException {
FindDaughterVisitor visitor = new FindDaughterVisitor(daughter);
// Start the scan at what should be the daughter's row in the .META.
// We will either 1., find the daughter or some derivative split of the
// daughter (will have same table name and start row at least but will sort
// after because has larger regionid -- the regionid is timestamp of region
// creation), OR, we will not find anything with same table name and start
// row. If the latter, then assume daughter missing and do fixup.
byte [] startrow = daughter.getRegionName();
MetaReader.fullScan(catalogTracker, visitor, startrow);
return !visitor.foundDaughter();
}
/**
* Looks for daughter. Sets a flag if daughter or some progeny of daughter
* is found up in <code>.META.</code>.
*/
static class FindDaughterVisitor implements MetaReader.Visitor {
private final HRegionInfo daughter;
private boolean found = false;
FindDaughterVisitor(final HRegionInfo daughter) {
this.daughter = daughter;
}
/**
* @return True if we found a daughter region during our visiting.
*/
boolean foundDaughter() {
return this.found;
}
@Override
public boolean visit(Result r) throws IOException {
HRegionInfo hri = getHRegionInfo(r, HConstants.REGIONINFO_QUALIFIER);
if (hri == null) {
LOG.warn("No serialized HRegionInfo in " + r);
return true;
}
byte [] value = r.getValue(HConstants.CATALOG_FAMILY,
HConstants.SERVER_QUALIFIER);
// See if daughter is assigned to some server
if (value == null) return false;
// Now see if we have gone beyond the daughter's startrow.
if (!Bytes.equals(daughter.getTableName(),
hri.getTableName())) {
// We fell into another table. Stop scanning.
return false;
}
// If our start rows do not compare, move on.
if (!Bytes.equals(daughter.getStartKey(), hri.getStartKey())) {
return false;
}
// Else, table name and start rows compare. It means that the daughter
// or some derivative split of the daughter is up in .META. Daughter
// exists.
this.found = true;
return false;
}
}
}
| false | true | public void process() throws IOException {
final ServerName serverName = this.serverName;
LOG.info("Splitting logs for " + serverName);
this.services.getMasterFileSystem().splitLog(serverName);
// Clean out anything in regions in transition. Being conservative and
// doing after log splitting. Could do some states before -- OPENING?
// OFFLINE? -- and then others after like CLOSING that depend on log
// splitting.
List<RegionState> regionsInTransition =
this.services.getAssignmentManager().processServerShutdown(this.serverName);
// Assign root and meta if we were carrying them.
if (isCarryingRoot()) { // -ROOT-
LOG.info("Server " + serverName + " was carrying ROOT. Trying to assign.");
verifyAndAssignRootWithRetries();
}
// Carrying meta?
if (isCarryingMeta()) {
LOG.info("Server " + serverName + " was carrying META. Trying to assign.");
this.services.getAssignmentManager().assignMeta();
}
// Wait on meta to come online; we need it to progress.
// TODO: Best way to hold strictly here? We should build this retry logic
// into the MetaReader operations themselves.
// TODO: Is the reading of .META. necessary when the Master has state of
// cluster in its head? It should be possible to do without reading .META.
// in all but one case. On split, the RS updates the .META.
// table and THEN informs the master of the split via zk nodes in
// 'unassigned' dir. Currently the RS puts ephemeral nodes into zk so if
// the regionserver dies, these nodes do not stick around and this server
// shutdown processing does fixup (see the fixupDaughters method below).
// If we wanted to skip the .META. scan, we'd have to change at least the
// final SPLIT message to be permanent in zk so in here we'd know a SPLIT
// completed (zk is updated after edits to .META. have gone in). See
// {@link SplitTransaction}. We'd also have to be figure another way for
// doing the below .META. daughters fixup.
NavigableMap<HRegionInfo, Result> hris = null;
while (!this.server.isStopped()) {
try {
this.server.getCatalogTracker().waitForMeta();
hris = MetaReader.getServerUserRegions(this.server.getCatalogTracker(),
this.serverName);
break;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IOException("Interrupted", e);
} catch (IOException ioe) {
LOG.info("Received exception accessing META during server shutdown of " +
serverName + ", retrying META read", ioe);
}
}
// Skip regions that were in transition unless CLOSING or PENDING_CLOSE
for (RegionState rit : regionsInTransition) {
if (!rit.isClosing() && !rit.isPendingClose()) {
LOG.debug("Removed " + rit.getRegion().getRegionNameAsString() +
" from list of regions to assign because in RIT");
hris.remove(rit.getRegion());
}
}
LOG.info("Reassigning " + (hris == null? 0: hris.size()) +
" region(s) that " + serverName +
" was carrying (skipping " + regionsInTransition.size() +
" regions(s) that are already in transition)");
// Iterate regions that were on this server and assign them
if (hris != null) {
for (Map.Entry<HRegionInfo, Result> e: hris.entrySet()) {
if (processDeadRegion(e.getKey(), e.getValue(),
this.services.getAssignmentManager(),
this.server.getCatalogTracker())) {
this.services.getAssignmentManager().assign(e.getKey(), true);
}
}
}
this.deadServers.finish(serverName);
LOG.info("Finished processing of shutdown of " + serverName);
}
| public void process() throws IOException {
final ServerName serverName = this.serverName;
LOG.info("Splitting logs for " + serverName);
this.services.getMasterFileSystem().splitLog(serverName);
// Clean out anything in regions in transition. Being conservative and
// doing after log splitting. Could do some states before -- OPENING?
// OFFLINE? -- and then others after like CLOSING that depend on log
// splitting.
List<RegionState> regionsInTransition =
this.services.getAssignmentManager().processServerShutdown(this.serverName);
// Assign root and meta if we were carrying them.
if (isCarryingRoot()) { // -ROOT-
verifyAndAssignRootWithRetries();
}
// Carrying meta?
if (isCarryingMeta()) this.services.getAssignmentManager().assignMeta();
// Wait on meta to come online; we need it to progress.
// TODO: Best way to hold strictly here? We should build this retry logic
// into the MetaReader operations themselves.
// TODO: Is the reading of .META. necessary when the Master has state of
// cluster in its head? It should be possible to do without reading .META.
// in all but one case. On split, the RS updates the .META.
// table and THEN informs the master of the split via zk nodes in
// 'unassigned' dir. Currently the RS puts ephemeral nodes into zk so if
// the regionserver dies, these nodes do not stick around and this server
// shutdown processing does fixup (see the fixupDaughters method below).
// If we wanted to skip the .META. scan, we'd have to change at least the
// final SPLIT message to be permanent in zk so in here we'd know a SPLIT
// completed (zk is updated after edits to .META. have gone in). See
// {@link SplitTransaction}. We'd also have to be figure another way for
// doing the below .META. daughters fixup.
NavigableMap<HRegionInfo, Result> hris = null;
while (!this.server.isStopped()) {
try {
this.server.getCatalogTracker().waitForMeta();
hris = MetaReader.getServerUserRegions(this.server.getCatalogTracker(),
this.serverName);
break;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IOException("Interrupted", e);
} catch (IOException ioe) {
LOG.info("Received exception accessing META during server shutdown of " +
serverName + ", retrying META read", ioe);
}
}
// Skip regions that were in transition unless CLOSING or PENDING_CLOSE
for (RegionState rit : regionsInTransition) {
if (!rit.isClosing() && !rit.isPendingClose()) {
LOG.debug("Removed " + rit.getRegion().getRegionNameAsString() +
" from list of regions to assign because in RIT");
hris.remove(rit.getRegion());
}
}
LOG.info("Reassigning " + (hris == null? 0: hris.size()) +
" region(s) that " + serverName +
" was carrying (skipping " + regionsInTransition.size() +
" regions(s) that are already in transition)");
// Iterate regions that were on this server and assign them
if (hris != null) {
for (Map.Entry<HRegionInfo, Result> e: hris.entrySet()) {
if (processDeadRegion(e.getKey(), e.getValue(),
this.services.getAssignmentManager(),
this.server.getCatalogTracker())) {
this.services.getAssignmentManager().assign(e.getKey(), true);
}
}
}
this.deadServers.finish(serverName);
LOG.info("Finished processing of shutdown of " + serverName);
}
|
diff --git a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/actions/AddExternalFolderAction.java b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/actions/AddExternalFolderAction.java
index f07e0dcad..736f3867e 100644
--- a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/actions/AddExternalFolderAction.java
+++ b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/actions/AddExternalFolderAction.java
@@ -1,64 +1,64 @@
package org.eclipse.jdt.internal.debug.ui.actions;
/**********************************************************************
Copyright (c) 2000, 2002 IBM Corp. All rights reserved.
This file is 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
**********************************************************************/
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.jdt.internal.debug.ui.launcher.RuntimeClasspathViewer;
import org.eclipse.jdt.launching.IRuntimeClasspathEntry;
import org.eclipse.jdt.launching.JavaRuntime;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.DirectoryDialog;
/**
* Adds an external folder to the runtime class path.
*/
public class AddExternalFolderAction extends OpenDialogAction {
public AddExternalFolderAction(RuntimeClasspathViewer viewer, String dialogSettingsPrefix) {
super(ActionMessages.getString("AddExternalFolderAction.Add_External_Folder_1"), viewer, dialogSettingsPrefix); //$NON-NLS-1$
}
/**
* Prompts for a folder to add.
*
* @see IAction#run()
*/
public void run() {
String lastUsedPath= getDialogSetting(LAST_PATH_SETTING);
if (lastUsedPath == null) {
lastUsedPath= ""; //$NON-NLS-1$
}
DirectoryDialog dialog= new DirectoryDialog(getShell(), SWT.MULTI);
dialog.setText(ActionMessages.getString("AddExternalFolderAction.Folder_Selection_3")); //$NON-NLS-1$
dialog.setFilterPath(lastUsedPath);
String res= dialog.open();
if (res == null) {
return;
}
IPath filterPath= new Path(dialog.getFilterPath());
IRuntimeClasspathEntry[] elems= new IRuntimeClasspathEntry[1];
- IPath path= filterPath.append(res).makeAbsolute();
+ IPath path= new Path(res).makeAbsolute();
elems[0]= JavaRuntime.newArchiveRuntimeClasspathEntry(path);
setDialogSetting(LAST_PATH_SETTING, filterPath.toOSString());
getViewer().addEntries(elems);
}
/**
* @see SelectionListenerAction#updateSelection(IStructuredSelection)
*/
protected boolean updateSelection(IStructuredSelection selection) {
return getViewer().isEnabled();
}
}
| true | true | public void run() {
String lastUsedPath= getDialogSetting(LAST_PATH_SETTING);
if (lastUsedPath == null) {
lastUsedPath= ""; //$NON-NLS-1$
}
DirectoryDialog dialog= new DirectoryDialog(getShell(), SWT.MULTI);
dialog.setText(ActionMessages.getString("AddExternalFolderAction.Folder_Selection_3")); //$NON-NLS-1$
dialog.setFilterPath(lastUsedPath);
String res= dialog.open();
if (res == null) {
return;
}
IPath filterPath= new Path(dialog.getFilterPath());
IRuntimeClasspathEntry[] elems= new IRuntimeClasspathEntry[1];
IPath path= filterPath.append(res).makeAbsolute();
elems[0]= JavaRuntime.newArchiveRuntimeClasspathEntry(path);
setDialogSetting(LAST_PATH_SETTING, filterPath.toOSString());
getViewer().addEntries(elems);
}
| public void run() {
String lastUsedPath= getDialogSetting(LAST_PATH_SETTING);
if (lastUsedPath == null) {
lastUsedPath= ""; //$NON-NLS-1$
}
DirectoryDialog dialog= new DirectoryDialog(getShell(), SWT.MULTI);
dialog.setText(ActionMessages.getString("AddExternalFolderAction.Folder_Selection_3")); //$NON-NLS-1$
dialog.setFilterPath(lastUsedPath);
String res= dialog.open();
if (res == null) {
return;
}
IPath filterPath= new Path(dialog.getFilterPath());
IRuntimeClasspathEntry[] elems= new IRuntimeClasspathEntry[1];
IPath path= new Path(res).makeAbsolute();
elems[0]= JavaRuntime.newArchiveRuntimeClasspathEntry(path);
setDialogSetting(LAST_PATH_SETTING, filterPath.toOSString());
getViewer().addEntries(elems);
}
|
diff --git a/src/main/java/com/tinkerpop/blueprints/pgm/impls/sail/impls/LinkedDataSailGraph.java b/src/main/java/com/tinkerpop/blueprints/pgm/impls/sail/impls/LinkedDataSailGraph.java
index 667ceeb9..e2d76fb3 100644
--- a/src/main/java/com/tinkerpop/blueprints/pgm/impls/sail/impls/LinkedDataSailGraph.java
+++ b/src/main/java/com/tinkerpop/blueprints/pgm/impls/sail/impls/LinkedDataSailGraph.java
@@ -1,23 +1,24 @@
package com.tinkerpop.blueprints.pgm.impls.sail.impls;
import com.tinkerpop.blueprints.pgm.impls.sail.SailGraph;
import net.fortytwo.linkeddata.sail.LinkedDataSail;
import net.fortytwo.ripple.Ripple;
import net.fortytwo.ripple.URIMap;
import org.openrdf.sail.Sail;
/**
* @author Marko A. Rodriguez (http://markorodriguez.com)
*/
public class LinkedDataSailGraph extends SailGraph {
public LinkedDataSailGraph(SailGraph storageGraph) {
try {
Ripple.initialize();
final Sail sail = new LinkedDataSail(storageGraph.getRawGraph(), new URIMap());
+ sail.initialize();
this.startSail(sail);
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
}
}
| true | true | public LinkedDataSailGraph(SailGraph storageGraph) {
try {
Ripple.initialize();
final Sail sail = new LinkedDataSail(storageGraph.getRawGraph(), new URIMap());
this.startSail(sail);
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
}
| public LinkedDataSailGraph(SailGraph storageGraph) {
try {
Ripple.initialize();
final Sail sail = new LinkedDataSail(storageGraph.getRawGraph(), new URIMap());
sail.initialize();
this.startSail(sail);
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
}
|
diff --git a/src/net/clonecomputers/lab/todo/ScheduledAlarm.java b/src/net/clonecomputers/lab/todo/ScheduledAlarm.java
index e5d41a3..75ae176 100644
--- a/src/net/clonecomputers/lab/todo/ScheduledAlarm.java
+++ b/src/net/clonecomputers/lab/todo/ScheduledAlarm.java
@@ -1,42 +1,42 @@
package net.clonecomputers.lab.todo;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class ScheduledAlarm {
public static final int NO_VALUE = 0;
public static final int WILDCARD = 60;
private final Calendar NOW = new GregorianCalendar();
private final int ye;
private final int mo;
private final int da;
private final int ho;
private final int mi;
public ScheduledAlarm(int year, int month, int day, int hour, int minute) {
ye = year;
mo = month;
da = day;
ho = hour;
mi = minute;
}
Date getSoonestDate() {
Calendar alarmTime = new GregorianCalendar(1,1,1,0,0,0);
NOW.setTime(new Date());
alarmTime.set(ye,mo,da,ho,mi);
if(ye != 60) {
return NOW.getTime().before(alarmTime.getTime()) ? alarmTime.getTime() : null;
} else {
alarmTime.set(Calendar.YEAR, NOW.get(Calendar.YEAR));
- while(NOW.getTime().before(alarmTime.getTime())) {
+ while(!NOW.getTime().before(alarmTime.getTime())) {
alarmTime.add(Calendar.YEAR, 1);
}
return alarmTime.getTime();
}
}
}
| true | true | Date getSoonestDate() {
Calendar alarmTime = new GregorianCalendar(1,1,1,0,0,0);
NOW.setTime(new Date());
alarmTime.set(ye,mo,da,ho,mi);
if(ye != 60) {
return NOW.getTime().before(alarmTime.getTime()) ? alarmTime.getTime() : null;
} else {
alarmTime.set(Calendar.YEAR, NOW.get(Calendar.YEAR));
while(NOW.getTime().before(alarmTime.getTime())) {
alarmTime.add(Calendar.YEAR, 1);
}
return alarmTime.getTime();
}
}
| Date getSoonestDate() {
Calendar alarmTime = new GregorianCalendar(1,1,1,0,0,0);
NOW.setTime(new Date());
alarmTime.set(ye,mo,da,ho,mi);
if(ye != 60) {
return NOW.getTime().before(alarmTime.getTime()) ? alarmTime.getTime() : null;
} else {
alarmTime.set(Calendar.YEAR, NOW.get(Calendar.YEAR));
while(!NOW.getTime().before(alarmTime.getTime())) {
alarmTime.add(Calendar.YEAR, 1);
}
return alarmTime.getTime();
}
}
|
diff --git a/alitheia/logger/src/eu/sqooss/impl/service/LoggingActivator.java b/alitheia/logger/src/eu/sqooss/impl/service/LoggingActivator.java
index 048b6dee..312734e4 100644
--- a/alitheia/logger/src/eu/sqooss/impl/service/LoggingActivator.java
+++ b/alitheia/logger/src/eu/sqooss/impl/service/LoggingActivator.java
@@ -1,33 +1,32 @@
package eu.sqooss.impl.service;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import eu.sqooss.impl.service.logging.LogManagerImpl;
import eu.sqooss.service.logging.LogManager;
import eu.sqooss.service.logging.Logger;
public class LoggingActivator implements BundleActivator {
private ServiceRegistration sReg;
public void start(BundleContext bc) throws Exception {
//registers a log manager service
LogManagerImpl.logManager.setBundleContext(bc);
sReg = bc.registerService(LogManager.class.getName(), LogManagerImpl.logManager, null);
Logger l = LogManagerImpl.logManager.createLogger("sqooss");
l.setConfigurationProperty("file.name","alitheia.log");
l.setConfigurationProperty("message.format","text/plain");
l.info("Logging bundle started.");
- System.out.println("Look ma, I'm smoking crack!");
}
public void stop(BundleContext bc) throws Exception {
//unregisters a log manager service
if (sReg != null) {
sReg.unregister();
}
LogManagerImpl.logManager.close();
}
}
| true | true | public void start(BundleContext bc) throws Exception {
//registers a log manager service
LogManagerImpl.logManager.setBundleContext(bc);
sReg = bc.registerService(LogManager.class.getName(), LogManagerImpl.logManager, null);
Logger l = LogManagerImpl.logManager.createLogger("sqooss");
l.setConfigurationProperty("file.name","alitheia.log");
l.setConfigurationProperty("message.format","text/plain");
l.info("Logging bundle started.");
System.out.println("Look ma, I'm smoking crack!");
}
| public void start(BundleContext bc) throws Exception {
//registers a log manager service
LogManagerImpl.logManager.setBundleContext(bc);
sReg = bc.registerService(LogManager.class.getName(), LogManagerImpl.logManager, null);
Logger l = LogManagerImpl.logManager.createLogger("sqooss");
l.setConfigurationProperty("file.name","alitheia.log");
l.setConfigurationProperty("message.format","text/plain");
l.info("Logging bundle started.");
}
|
diff --git a/src/main/java/de/cismet/cids/custom/butler/Butler1ProductPanel.java b/src/main/java/de/cismet/cids/custom/butler/Butler1ProductPanel.java
index f6c008fc..048e2299 100644
--- a/src/main/java/de/cismet/cids/custom/butler/Butler1ProductPanel.java
+++ b/src/main/java/de/cismet/cids/custom/butler/Butler1ProductPanel.java
@@ -1,686 +1,687 @@
/***************************************************
*
* cismet GmbH, Saarbruecken, Germany
*
* ... and it just works.
*
****************************************************/
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package de.cismet.cids.custom.butler;
import Sirius.navigator.connection.SessionManager;
import Sirius.navigator.exception.ConnectionException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.vividsolutions.jts.geom.Geometry;
import org.apache.log4j.Logger;
import org.jdesktop.beansbinding.Binding;
import org.jdesktop.beansbinding.Property;
import org.openide.util.Exceptions;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import de.cismet.cids.custom.nas.NasFeeCalculator;
import de.cismet.cids.custom.utils.butler.ButlerFormat;
import de.cismet.cids.custom.utils.butler.ButlerProduct;
import de.cismet.cids.custom.utils.butler.ButlerResolution;
import de.cismet.cids.custom.wunda_blau.search.actions.NasZaehlObjekteSearch;
import de.cismet.tools.StaticDecimalTools;
/**
* DOCUMENT ME!
*
* @author daniel
* @version $Revision$, $Date$
*/
public class Butler1ProductPanel extends javax.swing.JPanel implements ListSelectionListener {
//~ Static fields/initializers ---------------------------------------------
private static final Logger LOG = Logger.getLogger(Butler1ProductPanel.class);
//~ Instance fields --------------------------------------------------------
ArrayList<ButlerProductGroup> productGroups;
ArrayList<ButlerProduct> products;
ArrayList<ButlerResolution> resolutions;
ArrayList<ButlerFormat> formats;
private Geometry geom;
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.ButtonGroup btGroupFormat;
private javax.swing.JComboBox cbProduktGruppe;
private javax.swing.JComboBox cbResolution;
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JLabel lblAuflösung;
private javax.swing.JLabel lblFiller;
private javax.swing.JLabel lblFormat;
private javax.swing.JLabel lblProdukt;
private javax.swing.JLabel lblProduktGruppe;
private javax.swing.JLabel lblVolumeParam;
private javax.swing.JLabel lblVolumeParamKey;
private javax.swing.JLabel lblVolumeParamTitle;
private javax.swing.JList lstProdukt;
private javax.swing.JPanel pnlFeeParrameter;
private javax.swing.JPanel pnlFormat;
private javax.swing.JRadioButton rbDxf;
private javax.swing.JRadioButton rbGeoTif;
private javax.swing.JRadioButton rbShp;
private javax.swing.JRadioButton rbTif;
private org.jdesktop.beansbinding.BindingGroup bindingGroup;
// End of variables declaration//GEN-END:variables
//~ Constructors -----------------------------------------------------------
/**
* Creates new form Butler1ProductPanel.
*/
public Butler1ProductPanel() {
loadPrductDescriptions();
initComponents();
lstProdukt.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
lstProdukt.addListSelectionListener(this);
}
//~ Methods ----------------------------------------------------------------
/**
* 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();
btGroupFormat = new javax.swing.ButtonGroup();
lblProduktGruppe = new javax.swing.JLabel();
cbProduktGruppe = new javax.swing.JComboBox();
lblProdukt = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
lstProdukt = new javax.swing.JList();
lblFormat = new javax.swing.JLabel();
pnlFormat = new javax.swing.JPanel();
rbDxf = new javax.swing.JRadioButton();
rbShp = new javax.swing.JRadioButton();
rbTif = new javax.swing.JRadioButton();
rbGeoTif = new javax.swing.JRadioButton();
lblFiller = new javax.swing.JLabel();
lblAuflösung = new javax.swing.JLabel();
cbResolution = new javax.swing.JComboBox();
jSeparator1 = new javax.swing.JSeparator();
pnlFeeParrameter = new javax.swing.JPanel();
lblVolumeParamTitle = new javax.swing.JLabel();
lblVolumeParamKey = new javax.swing.JLabel();
lblVolumeParam = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
setBorder(null);
setMinimumSize(new java.awt.Dimension(400, 291));
setLayout(new java.awt.GridBagLayout());
org.openide.awt.Mnemonics.setLocalizedText(
lblProduktGruppe,
org.openide.util.NbBundle.getMessage(
Butler1ProductPanel.class,
"Butler1ProductPanel.lblProduktGruppe.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 40);
add(lblProduktGruppe, gridBagConstraints);
org.jdesktop.beansbinding.ELProperty eLProperty = org.jdesktop.beansbinding.ELProperty.create(
"${productGroups}");
org.jdesktop.swingbinding.JComboBoxBinding jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings
.createJComboBoxBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
eLProperty,
cbProduktGruppe);
bindingGroup.addBinding(jComboBoxBinding);
cbProduktGruppe.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cbProduktGruppeActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.insets = new java.awt.Insets(10, 0, 10, 10);
add(cbProduktGruppe, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(
lblProdukt,
org.openide.util.NbBundle.getMessage(Butler1ProductPanel.class, "Butler1ProductPanel.lblProdukt.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 10, 40);
add(lblProdukt, gridBagConstraints);
jScrollPane1.setMinimumSize(new java.awt.Dimension(250, 150));
jScrollPane1.setPreferredSize(new java.awt.Dimension(258, 150));
eLProperty = org.jdesktop.beansbinding.ELProperty.create("${products}");
final org.jdesktop.swingbinding.JListBinding jListBinding = org.jdesktop.swingbinding.SwingBindings
.createJListBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
eLProperty,
lstProdukt,
"productBinding");
bindingGroup.addBinding(jListBinding);
jScrollPane1.setViewportView(lstProdukt);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 10, 10);
add(jScrollPane1, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(
lblFormat,
org.openide.util.NbBundle.getMessage(Butler1ProductPanel.class, "Butler1ProductPanel.lblFormat.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 10, 40);
add(lblFormat, gridBagConstraints);
pnlFormat.setLayout(new java.awt.GridBagLayout());
btGroupFormat.add(rbDxf);
org.openide.awt.Mnemonics.setLocalizedText(
rbDxf,
org.openide.util.NbBundle.getMessage(Butler1ProductPanel.class, "Butler1ProductPanel.rbDxf.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5);
pnlFormat.add(rbDxf, gridBagConstraints);
btGroupFormat.add(rbShp);
org.openide.awt.Mnemonics.setLocalizedText(
rbShp,
org.openide.util.NbBundle.getMessage(Butler1ProductPanel.class, "Butler1ProductPanel.rbShp.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5);
pnlFormat.add(rbShp, gridBagConstraints);
btGroupFormat.add(rbTif);
org.openide.awt.Mnemonics.setLocalizedText(
rbTif,
org.openide.util.NbBundle.getMessage(Butler1ProductPanel.class, "Butler1ProductPanel.rbTif.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5);
pnlFormat.add(rbTif, gridBagConstraints);
btGroupFormat.add(rbGeoTif);
org.openide.awt.Mnemonics.setLocalizedText(
rbGeoTif,
org.openide.util.NbBundle.getMessage(Butler1ProductPanel.class, "Butler1ProductPanel.rbGeoTif.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5);
pnlFormat.add(rbGeoTif, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(
lblFiller,
org.openide.util.NbBundle.getMessage(Butler1ProductPanel.class, "Butler1ProductPanel.lblFiller.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 4;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
pnlFormat.add(lblFiller, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 10, 10);
add(pnlFormat, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(
lblAuflösung,
org.openide.util.NbBundle.getMessage(Butler1ProductPanel.class, "Butler1ProductPanel.lblAuflösung.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 10, 40);
add(lblAuflösung, gridBagConstraints);
eLProperty = org.jdesktop.beansbinding.ELProperty.create("${resolutions}");
jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
eLProperty,
cbResolution,
"resolutionBinding");
bindingGroup.addBinding(jComboBoxBinding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 10);
add(cbResolution, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10);
add(jSeparator1, gridBagConstraints);
pnlFeeParrameter.setBackground(new java.awt.Color(255, 255, 255));
pnlFeeParrameter.setBorder(javax.swing.BorderFactory.createEtchedBorder());
pnlFeeParrameter.setLayout(new java.awt.GridBagLayout());
lblVolumeParamTitle.setFont(new java.awt.Font("DejaVu Sans", 1, 14)); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(
lblVolumeParamTitle,
org.openide.util.NbBundle.getMessage(
Butler1ProductPanel.class,
"Butler1ProductPanel.lblVolumeParamTitle.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
+ gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 20, 10);
pnlFeeParrameter.add(lblVolumeParamTitle, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(
lblVolumeParamKey,
org.openide.util.NbBundle.getMessage(
Butler1ProductPanel.class,
"Butler1ProductPanel.lblVolumeParamKey.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(0, 10, 0, 0);
pnlFeeParrameter.add(lblVolumeParamKey, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(
lblVolumeParam,
org.openide.util.NbBundle.getMessage(Butler1ProductPanel.class, "Butler1ProductPanel.lblVolumeParam.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 10);
pnlFeeParrameter.add(lblVolumeParam, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(
jLabel1,
org.openide.util.NbBundle.getMessage(Butler1ProductPanel.class, "Butler1ProductPanel.jLabel1.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL;
gridBagConstraints.weighty = 1.0;
pnlFeeParrameter.add(jLabel1, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 5;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 10, 10);
add(pnlFeeParrameter, gridBagConstraints);
bindingGroup.bind();
} // </editor-fold>//GEN-END:initComponents
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void cbProduktGruppeActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_cbProduktGruppeActionPerformed
final ButlerProductGroup productGroup = ((ButlerProductGroup)cbProduktGruppe.getSelectedItem());
if (productGroup != null) {
final Binding productBinding = bindingGroup.getBinding("productBinding");
final Property productProp = productBinding.getSourceProperty();
productProp.setValue(this, productGroup.getButlerProducts());
final Binding resolutionBinding = bindingGroup.getBinding("resolutionBinding");
final Property resolutionProp = resolutionBinding.getSourceProperty();
resolutionProp.setValue(this, productGroup.getButlerResolutions());
productGroup.getButlerFormats();
updateFormatButtons(productGroup.getButlerFormats());
}
} //GEN-LAST:event_cbProduktGruppeActionPerformed
/**
* DOCUMENT ME!
*/
private void loadPrductDescriptions() {
try {
final ObjectMapper mapper = new ObjectMapper();
final ButlerProductInfo tester = mapper.readValue(ButlerProductInfo.class.getResourceAsStream(
"/de/cismet/cids/custom/butler/productDescription.json"),
ButlerProductInfo.class);
productGroups = tester.getButler1ProductGroups();
products = productGroups.get(0).getButlerProducts();
resolutions = productGroups.get(0).getButlerResolutions();
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public ArrayList<ButlerProductGroup> getProductGroups() {
return productGroups;
}
/**
* DOCUMENT ME!
*
* @param productGroups DOCUMENT ME!
*/
public void setProductGroups(final ArrayList<ButlerProductGroup> productGroups) {
this.productGroups = productGroups;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public ArrayList<ButlerProduct> getProducts() {
return products;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public ButlerProduct getSelectedProduct() {
final ButlerProduct bp = (ButlerProduct)lstProdukt.getSelectedValue();
if (bp != null) {
if (rbDxf.isSelected()) {
bp.setFormat(new ButlerFormat("dxf"));
} else if (rbGeoTif.isSelected()) {
bp.setFormat(new ButlerFormat("geotif"));
} else if (rbShp.isSelected()) {
bp.setFormat(new ButlerFormat("shp"));
} else if (rbTif.isSelected()) {
bp.setFormat(new ButlerFormat("tif"));
}
final ButlerResolution res = (ButlerResolution)cbResolution.getSelectedItem();
bp.setResolution(res);
}
return bp;
}
/**
* DOCUMENT ME!
*
* @param products args products DOCUMENT ME!
*/
public void setProducts(final ArrayList<ButlerProduct> products) {
this.products = products;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public ArrayList<ButlerResolution> getResolutions() {
return resolutions;
}
/**
* DOCUMENT ME!
*
* @param resolution args resolution DOCUMENT ME!
*/
public void setResolutions(final ArrayList<ButlerResolution> resolution) {
this.resolutions = resolution;
}
/**
* DOCUMENT ME!
*
* @param args DOCUMENT ME!
*/
public static void main(final String[] args) {
final JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.getContentPane().add(new Butler1ProductPanel());
f.pack();
f.setVisible(true);
}
/**
* DOCUMENT ME!
*
* @param allowedButlerFormats DOCUMENT ME!
*/
private void updateFormatButtons(final ArrayList<ButlerFormat> allowedButlerFormats) {
// remove selection for all
btGroupFormat.clearSelection();
// set them all disabled
rbDxf.setEnabled(false);
rbGeoTif.setEnabled(false);
rbShp.setEnabled(false);
rbTif.setEnabled(false);
// enable the ones that are currentyl allowed
for (final ButlerFormat f : allowedButlerFormats) {
if (f.getKey().equals("TIF")) {
rbTif.setEnabled(true);
} else if (f.getKey().equals("GEOTIF")) {
rbGeoTif.setEnabled(true);
} else if (f.getKey().equals("DXF")) {
rbDxf.setEnabled(true);
} else if (f.getKey().equals("SHAPE")) {
rbShp.setEnabled(true);
}
}
}
@Override
public void valueChanged(final ListSelectionEvent e) {
final ButlerProduct selectedProduct = (ButlerProduct)lstProdukt.getSelectedValue();
if (selectedProduct != null) {
final String text = (selectedProduct.getVolumeParamText() == null) ? ""
: selectedProduct.getVolumeParamText();
lblVolumeParamKey.setText(text);
calculateVolumePram();
}
}
/**
* DOCUMENT ME!
*/
private void calculateVolumePram() {
final ButlerProduct product = (ButlerProduct)lstProdukt.getSelectedValue();
if ((product == null) || (geom == null)) {
lblVolumeParam.setText("0");
return;
}
final String productKey = product.getKey();
if (productKey != null) {
String volumeParamText = "";
if (productKey.equals("0108")) {
volumeParamText = getDachPunkteCount();
} else if (productKey.equals("0109")) {
volumeParamText = getBodenPuntkeCount();
} else if (productKey.equals("0501")) {
volumeParamText = getGebauedeCount();
} else if (productKey.equals("0502")) {
volumeParamText = getFlurstueckeCount();
} else if (productKey.equals("0503")) {
volumeParamText = getAdressCount();
} else {
volumeParamText = getFlaeche();
}
lblVolumeParam.setText(volumeParamText);
}
}
/**
* DOCUMENT ME!
*
* @param g DOCUMENT ME!
*/
public void setGeometry(final Geometry g) {
geom = g;
calculateVolumePram();
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
private String getDachPunkteCount() {
if (geom != null) {
final int dachPunkteCount;
try {
dachPunkteCount = NasFeeCalculator.getDachPunkteAmount(geom);
return "" + dachPunkteCount;
} catch (ConnectionException ex) {
LOG.error("Error during Dachpunkte search in butler 1 prduct panel", ex);
}
}
return "0";
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
private String getBodenPuntkeCount() {
if (geom != null) {
final int bodenPuntkeCount;
try {
bodenPuntkeCount = NasFeeCalculator.getBodenPunkteAmount(geom);
return "" + bodenPuntkeCount;
} catch (ConnectionException ex) {
LOG.error("Error during Dachpunkte search in butler 1 prduct panel", ex);
}
}
return "0";
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
private String getGebauedeCount() {
if (geom != null) {
final int gebaeudeCount;
try {
gebaeudeCount = NasFeeCalculator.getGebaeudeAmount(geom);
return "" + gebaeudeCount;
} catch (ConnectionException ex) {
LOG.error("Error during Gebaeude search in butler 1 prduct panel", ex);
}
}
return "0";
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
private String getFlurstueckeCount() {
if (geom != null) {
final int flurstueckCount;
try {
flurstueckCount = NasFeeCalculator.getFlurstueckAmount(geom);
return "" + flurstueckCount;
} catch (ConnectionException ex) {
LOG.error("Error during Flurstuecksearch in butler 1 prduct panel");
}
}
return "0";
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
private String getAdressCount() {
if (geom != null) {
final NasZaehlObjekteSearch flurstueckSearch = new NasZaehlObjekteSearch(
geom,
NasZaehlObjekteSearch.NasSearchType.ADRESSE);
final ArrayList<Integer> c;
try {
c = (ArrayList<Integer>)SessionManager.getProxy()
.customServerSearch(SessionManager.getSession().getUser(), flurstueckSearch);
return "" + c.get(0);
} catch (ConnectionException ex) {
Exceptions.printStackTrace(ex);
}
return "0";
}
return "0";
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
private String getFlaeche() {
if (geom == null) {
return null;
}
final double areaInKm = geom.getArea() / (1000 * 1000);
return StaticDecimalTools.round("0.0", areaInKm);
}
}
| true | true | private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
bindingGroup = new org.jdesktop.beansbinding.BindingGroup();
btGroupFormat = new javax.swing.ButtonGroup();
lblProduktGruppe = new javax.swing.JLabel();
cbProduktGruppe = new javax.swing.JComboBox();
lblProdukt = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
lstProdukt = new javax.swing.JList();
lblFormat = new javax.swing.JLabel();
pnlFormat = new javax.swing.JPanel();
rbDxf = new javax.swing.JRadioButton();
rbShp = new javax.swing.JRadioButton();
rbTif = new javax.swing.JRadioButton();
rbGeoTif = new javax.swing.JRadioButton();
lblFiller = new javax.swing.JLabel();
lblAuflösung = new javax.swing.JLabel();
cbResolution = new javax.swing.JComboBox();
jSeparator1 = new javax.swing.JSeparator();
pnlFeeParrameter = new javax.swing.JPanel();
lblVolumeParamTitle = new javax.swing.JLabel();
lblVolumeParamKey = new javax.swing.JLabel();
lblVolumeParam = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
setBorder(null);
setMinimumSize(new java.awt.Dimension(400, 291));
setLayout(new java.awt.GridBagLayout());
org.openide.awt.Mnemonics.setLocalizedText(
lblProduktGruppe,
org.openide.util.NbBundle.getMessage(
Butler1ProductPanel.class,
"Butler1ProductPanel.lblProduktGruppe.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 40);
add(lblProduktGruppe, gridBagConstraints);
org.jdesktop.beansbinding.ELProperty eLProperty = org.jdesktop.beansbinding.ELProperty.create(
"${productGroups}");
org.jdesktop.swingbinding.JComboBoxBinding jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings
.createJComboBoxBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
eLProperty,
cbProduktGruppe);
bindingGroup.addBinding(jComboBoxBinding);
cbProduktGruppe.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cbProduktGruppeActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.insets = new java.awt.Insets(10, 0, 10, 10);
add(cbProduktGruppe, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(
lblProdukt,
org.openide.util.NbBundle.getMessage(Butler1ProductPanel.class, "Butler1ProductPanel.lblProdukt.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 10, 40);
add(lblProdukt, gridBagConstraints);
jScrollPane1.setMinimumSize(new java.awt.Dimension(250, 150));
jScrollPane1.setPreferredSize(new java.awt.Dimension(258, 150));
eLProperty = org.jdesktop.beansbinding.ELProperty.create("${products}");
final org.jdesktop.swingbinding.JListBinding jListBinding = org.jdesktop.swingbinding.SwingBindings
.createJListBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
eLProperty,
lstProdukt,
"productBinding");
bindingGroup.addBinding(jListBinding);
jScrollPane1.setViewportView(lstProdukt);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 10, 10);
add(jScrollPane1, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(
lblFormat,
org.openide.util.NbBundle.getMessage(Butler1ProductPanel.class, "Butler1ProductPanel.lblFormat.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 10, 40);
add(lblFormat, gridBagConstraints);
pnlFormat.setLayout(new java.awt.GridBagLayout());
btGroupFormat.add(rbDxf);
org.openide.awt.Mnemonics.setLocalizedText(
rbDxf,
org.openide.util.NbBundle.getMessage(Butler1ProductPanel.class, "Butler1ProductPanel.rbDxf.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5);
pnlFormat.add(rbDxf, gridBagConstraints);
btGroupFormat.add(rbShp);
org.openide.awt.Mnemonics.setLocalizedText(
rbShp,
org.openide.util.NbBundle.getMessage(Butler1ProductPanel.class, "Butler1ProductPanel.rbShp.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5);
pnlFormat.add(rbShp, gridBagConstraints);
btGroupFormat.add(rbTif);
org.openide.awt.Mnemonics.setLocalizedText(
rbTif,
org.openide.util.NbBundle.getMessage(Butler1ProductPanel.class, "Butler1ProductPanel.rbTif.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5);
pnlFormat.add(rbTif, gridBagConstraints);
btGroupFormat.add(rbGeoTif);
org.openide.awt.Mnemonics.setLocalizedText(
rbGeoTif,
org.openide.util.NbBundle.getMessage(Butler1ProductPanel.class, "Butler1ProductPanel.rbGeoTif.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5);
pnlFormat.add(rbGeoTif, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(
lblFiller,
org.openide.util.NbBundle.getMessage(Butler1ProductPanel.class, "Butler1ProductPanel.lblFiller.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 4;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
pnlFormat.add(lblFiller, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 10, 10);
add(pnlFormat, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(
lblAuflösung,
org.openide.util.NbBundle.getMessage(Butler1ProductPanel.class, "Butler1ProductPanel.lblAuflösung.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 10, 40);
add(lblAuflösung, gridBagConstraints);
eLProperty = org.jdesktop.beansbinding.ELProperty.create("${resolutions}");
jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
eLProperty,
cbResolution,
"resolutionBinding");
bindingGroup.addBinding(jComboBoxBinding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 10);
add(cbResolution, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10);
add(jSeparator1, gridBagConstraints);
pnlFeeParrameter.setBackground(new java.awt.Color(255, 255, 255));
pnlFeeParrameter.setBorder(javax.swing.BorderFactory.createEtchedBorder());
pnlFeeParrameter.setLayout(new java.awt.GridBagLayout());
lblVolumeParamTitle.setFont(new java.awt.Font("DejaVu Sans", 1, 14)); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(
lblVolumeParamTitle,
org.openide.util.NbBundle.getMessage(
Butler1ProductPanel.class,
"Butler1ProductPanel.lblVolumeParamTitle.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 20, 10);
pnlFeeParrameter.add(lblVolumeParamTitle, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(
lblVolumeParamKey,
org.openide.util.NbBundle.getMessage(
Butler1ProductPanel.class,
"Butler1ProductPanel.lblVolumeParamKey.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(0, 10, 0, 0);
pnlFeeParrameter.add(lblVolumeParamKey, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(
lblVolumeParam,
org.openide.util.NbBundle.getMessage(Butler1ProductPanel.class, "Butler1ProductPanel.lblVolumeParam.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 10);
pnlFeeParrameter.add(lblVolumeParam, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(
jLabel1,
org.openide.util.NbBundle.getMessage(Butler1ProductPanel.class, "Butler1ProductPanel.jLabel1.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL;
gridBagConstraints.weighty = 1.0;
pnlFeeParrameter.add(jLabel1, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 5;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 10, 10);
add(pnlFeeParrameter, gridBagConstraints);
bindingGroup.bind();
} // </editor-fold>//GEN-END:initComponents
| private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
bindingGroup = new org.jdesktop.beansbinding.BindingGroup();
btGroupFormat = new javax.swing.ButtonGroup();
lblProduktGruppe = new javax.swing.JLabel();
cbProduktGruppe = new javax.swing.JComboBox();
lblProdukt = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
lstProdukt = new javax.swing.JList();
lblFormat = new javax.swing.JLabel();
pnlFormat = new javax.swing.JPanel();
rbDxf = new javax.swing.JRadioButton();
rbShp = new javax.swing.JRadioButton();
rbTif = new javax.swing.JRadioButton();
rbGeoTif = new javax.swing.JRadioButton();
lblFiller = new javax.swing.JLabel();
lblAuflösung = new javax.swing.JLabel();
cbResolution = new javax.swing.JComboBox();
jSeparator1 = new javax.swing.JSeparator();
pnlFeeParrameter = new javax.swing.JPanel();
lblVolumeParamTitle = new javax.swing.JLabel();
lblVolumeParamKey = new javax.swing.JLabel();
lblVolumeParam = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
setBorder(null);
setMinimumSize(new java.awt.Dimension(400, 291));
setLayout(new java.awt.GridBagLayout());
org.openide.awt.Mnemonics.setLocalizedText(
lblProduktGruppe,
org.openide.util.NbBundle.getMessage(
Butler1ProductPanel.class,
"Butler1ProductPanel.lblProduktGruppe.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 40);
add(lblProduktGruppe, gridBagConstraints);
org.jdesktop.beansbinding.ELProperty eLProperty = org.jdesktop.beansbinding.ELProperty.create(
"${productGroups}");
org.jdesktop.swingbinding.JComboBoxBinding jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings
.createJComboBoxBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
eLProperty,
cbProduktGruppe);
bindingGroup.addBinding(jComboBoxBinding);
cbProduktGruppe.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cbProduktGruppeActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.insets = new java.awt.Insets(10, 0, 10, 10);
add(cbProduktGruppe, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(
lblProdukt,
org.openide.util.NbBundle.getMessage(Butler1ProductPanel.class, "Butler1ProductPanel.lblProdukt.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 10, 40);
add(lblProdukt, gridBagConstraints);
jScrollPane1.setMinimumSize(new java.awt.Dimension(250, 150));
jScrollPane1.setPreferredSize(new java.awt.Dimension(258, 150));
eLProperty = org.jdesktop.beansbinding.ELProperty.create("${products}");
final org.jdesktop.swingbinding.JListBinding jListBinding = org.jdesktop.swingbinding.SwingBindings
.createJListBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
eLProperty,
lstProdukt,
"productBinding");
bindingGroup.addBinding(jListBinding);
jScrollPane1.setViewportView(lstProdukt);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 10, 10);
add(jScrollPane1, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(
lblFormat,
org.openide.util.NbBundle.getMessage(Butler1ProductPanel.class, "Butler1ProductPanel.lblFormat.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 10, 40);
add(lblFormat, gridBagConstraints);
pnlFormat.setLayout(new java.awt.GridBagLayout());
btGroupFormat.add(rbDxf);
org.openide.awt.Mnemonics.setLocalizedText(
rbDxf,
org.openide.util.NbBundle.getMessage(Butler1ProductPanel.class, "Butler1ProductPanel.rbDxf.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5);
pnlFormat.add(rbDxf, gridBagConstraints);
btGroupFormat.add(rbShp);
org.openide.awt.Mnemonics.setLocalizedText(
rbShp,
org.openide.util.NbBundle.getMessage(Butler1ProductPanel.class, "Butler1ProductPanel.rbShp.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5);
pnlFormat.add(rbShp, gridBagConstraints);
btGroupFormat.add(rbTif);
org.openide.awt.Mnemonics.setLocalizedText(
rbTif,
org.openide.util.NbBundle.getMessage(Butler1ProductPanel.class, "Butler1ProductPanel.rbTif.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5);
pnlFormat.add(rbTif, gridBagConstraints);
btGroupFormat.add(rbGeoTif);
org.openide.awt.Mnemonics.setLocalizedText(
rbGeoTif,
org.openide.util.NbBundle.getMessage(Butler1ProductPanel.class, "Butler1ProductPanel.rbGeoTif.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5);
pnlFormat.add(rbGeoTif, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(
lblFiller,
org.openide.util.NbBundle.getMessage(Butler1ProductPanel.class, "Butler1ProductPanel.lblFiller.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 4;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
pnlFormat.add(lblFiller, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 10, 10);
add(pnlFormat, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(
lblAuflösung,
org.openide.util.NbBundle.getMessage(Butler1ProductPanel.class, "Butler1ProductPanel.lblAuflösung.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 10, 40);
add(lblAuflösung, gridBagConstraints);
eLProperty = org.jdesktop.beansbinding.ELProperty.create("${resolutions}");
jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
eLProperty,
cbResolution,
"resolutionBinding");
bindingGroup.addBinding(jComboBoxBinding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 10);
add(cbResolution, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10);
add(jSeparator1, gridBagConstraints);
pnlFeeParrameter.setBackground(new java.awt.Color(255, 255, 255));
pnlFeeParrameter.setBorder(javax.swing.BorderFactory.createEtchedBorder());
pnlFeeParrameter.setLayout(new java.awt.GridBagLayout());
lblVolumeParamTitle.setFont(new java.awt.Font("DejaVu Sans", 1, 14)); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(
lblVolumeParamTitle,
org.openide.util.NbBundle.getMessage(
Butler1ProductPanel.class,
"Butler1ProductPanel.lblVolumeParamTitle.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 20, 10);
pnlFeeParrameter.add(lblVolumeParamTitle, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(
lblVolumeParamKey,
org.openide.util.NbBundle.getMessage(
Butler1ProductPanel.class,
"Butler1ProductPanel.lblVolumeParamKey.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(0, 10, 0, 0);
pnlFeeParrameter.add(lblVolumeParamKey, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(
lblVolumeParam,
org.openide.util.NbBundle.getMessage(Butler1ProductPanel.class, "Butler1ProductPanel.lblVolumeParam.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 10);
pnlFeeParrameter.add(lblVolumeParam, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(
jLabel1,
org.openide.util.NbBundle.getMessage(Butler1ProductPanel.class, "Butler1ProductPanel.jLabel1.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL;
gridBagConstraints.weighty = 1.0;
pnlFeeParrameter.add(jLabel1, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 5;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 10, 10);
add(pnlFeeParrameter, gridBagConstraints);
bindingGroup.bind();
} // </editor-fold>//GEN-END:initComponents
|
diff --git a/de.gebit.integrity.eclipse/src/de/gebit/integrity/eclipse/classpath/IntegrityClasspathContainer.java b/de.gebit.integrity.eclipse/src/de/gebit/integrity/eclipse/classpath/IntegrityClasspathContainer.java
index f02fcd37..c0e784d1 100644
--- a/de.gebit.integrity.eclipse/src/de/gebit/integrity/eclipse/classpath/IntegrityClasspathContainer.java
+++ b/de.gebit.integrity.eclipse/src/de/gebit/integrity/eclipse/classpath/IntegrityClasspathContainer.java
@@ -1,196 +1,195 @@
/**
*
*/
package de.gebit.integrity.eclipse.classpath;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.jdt.core.IClasspathContainer;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.osgi.service.datalocation.Location;
import org.osgi.framework.Bundle;
import org.osgi.framework.FrameworkUtil;
import de.gebit.integrity.eclipse.Activator;
/**
* Classpath container which adds the Integrity bundles required to run tests as well as their immediate dependencies.
* Note that not all declared dependencies (and their sub-dependencies) are actually added! This is due to a lot of them
* actually not being required for simple test execution. If you're using an environment that does enforce full
* dependency resolution (OSGi!), you'll have to add all necessary dependencies there yourself (for example on the
* target platform in Eclipse PDE).
*
* @author Rene Schneider
*
*/
public class IntegrityClasspathContainer implements IClasspathContainer {
/**
* The container path.
*/
private IPath path;
/**
* Creates a new instance.
*
* @param aPath
* the container path
*/
public IntegrityClasspathContainer(IPath aPath) {
path = aPath;
}
@Override
public IClasspathEntry[] getClasspathEntries() {
ArrayList<IClasspathEntry> tempEntryList = new ArrayList<IClasspathEntry>();
addToList(tempEntryList, "de.gebit.integrity.runner");
addToList(tempEntryList, "de.gebit.integrity.remoting");
addToList(tempEntryList, "de.gebit.integrity.dsl");
addToList(tempEntryList, "javax.inject");
addToList(tempEntryList, "com.google.inject");
addToList(tempEntryList, "com.google.guava");
addToList(tempEntryList, "org.antlr.runtime");
addToList(tempEntryList, "org.apache.log4j");
addToList(tempEntryList, "org.eclipse.core.contenttype");
addToList(tempEntryList, "org.eclipse.core.jobs");
addToList(tempEntryList, "org.eclipse.core.resources");
addToList(tempEntryList, "org.eclipse.core.runtime");
addToList(tempEntryList, "org.eclipse.emf.common");
addToList(tempEntryList, "org.eclipse.emf.ecore");
addToList(tempEntryList, "org.eclipse.emf.ecore.xmi");
addToList(tempEntryList, "org.eclipse.emf.mwe.utils");
addToList(tempEntryList, "org.eclipse.equinox.preferences");
addToList(tempEntryList, "org.eclipse.text");
addToList(tempEntryList, "org.eclipse.xtext");
addToList(tempEntryList, "org.eclipse.xtext.util");
addToList(tempEntryList, "org.eclipse.xtext.common.types");
addToList(tempEntryList, "org.jdom");
// convert the list to an array and return it
IClasspathEntry[] tempEntryArray = new IClasspathEntry[tempEntryList.size()];
return (IClasspathEntry[]) tempEntryList.toArray(tempEntryArray);
}
private void addToList(List<IClasspathEntry> aList, String aBundleName) {
IClasspathEntry tempEntry = getPluginEntry(findBundle(aBundleName));
if (tempEntry != null) {
aList.add(tempEntry);
} else {
Activator
.getInstance()
.getLog()
.log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Was unable to find bundle '" + aBundleName
+ "' to add it to a projects' classpath!"));
}
}
private Bundle findBundle(String aSymbolicName) {
for (Bundle tempBundle : FrameworkUtil.getBundle(JavaCore.class).getBundleContext().getBundles()) {
if (tempBundle.getSymbolicName().equals(aSymbolicName)) {
return tempBundle;
}
}
return null;
}
@Override
public String getDescription() {
return "Integrity";
}
@Override
public int getKind() {
return IClasspathContainer.K_APPLICATION;
}
@Override
public IPath getPath() {
return path;
}
/**
* Resolves a bundle to its installation directory and creates an {@link IClasspathEntry} with it.
*
* @param aBundle
* the bundle
* @return The classpath entry, or null if no path was determinable.
*/
private IClasspathEntry getPluginEntry(Bundle aBundle) {
if (aBundle == null) {
return null;
}
IPath tempPluginPath = getInstallationDirectoryFor(aBundle);
if (tempPluginPath == null) {
return null;
} else {
return getLibrary(tempPluginPath);
}
}
/**
* Returns the installation directory for the given bundle or <code>null</code> if it cannot be determined.
*/
private IPath getInstallationDirectoryFor(Bundle aBundle) {
String tempBundleLocation = aBundle.getLocation();
if (tempBundleLocation == null || tempBundleLocation.length() == 0) {
return null;
}
- IPath tempBundlePath = new Path(tempBundleLocation);
- if (tempBundlePath.isAbsolute()) {
- return tempBundlePath;
- }
- if (tempBundlePath.toString().startsWith("reference:file:")) {
- String tempPathString = tempBundlePath.toString().substring(15);
+ IPath tempBundlePath;
+ if (tempBundleLocation.startsWith("reference:file:")) {
+ String tempPathString = tempBundleLocation.substring(15);
if (tempPathString.endsWith("/")) {
// This is a directory! Happens during development, when an Eclipse instance is started from another
// Eclipse with the Integrity projects living there as projects and thus being included in the "inner"
// Eclipse as directories. We'll return the right subdir in that case to allow for inclusion of the
// compiled classes
return new Path(tempPathString + "target/classes/");
}
tempBundlePath = new Path(tempPathString);
+ } else {
+ tempBundlePath = new Path(tempBundleLocation);
}
if (tempBundlePath.isAbsolute()) {
return tempBundlePath;
}
Location tempInstallLocation = Platform.getInstallLocation();
if (tempInstallLocation == null || !tempInstallLocation.isSet()) {
return null;
}
Path tempPath = new Path(tempInstallLocation.getURL().getPath());
return tempPath.append(tempBundlePath);
}
/**
* Creates an IClasspathEntry for the given jar file in the given path.
*
* @param aLibPath
* the path where to find the jar
* @param aJarName
* the file name of the jar file
* @return the library IClasspath entry
*/
private IClasspathEntry getLibrary(IPath aLibPath) {
String tempJarName = aLibPath.removeFileExtension().lastSegment();
String tempSourceSuffix = aLibPath.toString().contains("de.gebit.integrity") ? "" : "_src";
IPath tempSourceJar = aLibPath.removeLastSegments(1).append(tempJarName + tempSourceSuffix)
.addFileExtension("jar");
return JavaCore.newLibraryEntry(aLibPath, tempSourceJar, null);
}
}
| false | true | private IPath getInstallationDirectoryFor(Bundle aBundle) {
String tempBundleLocation = aBundle.getLocation();
if (tempBundleLocation == null || tempBundleLocation.length() == 0) {
return null;
}
IPath tempBundlePath = new Path(tempBundleLocation);
if (tempBundlePath.isAbsolute()) {
return tempBundlePath;
}
if (tempBundlePath.toString().startsWith("reference:file:")) {
String tempPathString = tempBundlePath.toString().substring(15);
if (tempPathString.endsWith("/")) {
// This is a directory! Happens during development, when an Eclipse instance is started from another
// Eclipse with the Integrity projects living there as projects and thus being included in the "inner"
// Eclipse as directories. We'll return the right subdir in that case to allow for inclusion of the
// compiled classes
return new Path(tempPathString + "target/classes/");
}
tempBundlePath = new Path(tempPathString);
}
if (tempBundlePath.isAbsolute()) {
return tempBundlePath;
}
Location tempInstallLocation = Platform.getInstallLocation();
if (tempInstallLocation == null || !tempInstallLocation.isSet()) {
return null;
}
Path tempPath = new Path(tempInstallLocation.getURL().getPath());
return tempPath.append(tempBundlePath);
}
| private IPath getInstallationDirectoryFor(Bundle aBundle) {
String tempBundleLocation = aBundle.getLocation();
if (tempBundleLocation == null || tempBundleLocation.length() == 0) {
return null;
}
IPath tempBundlePath;
if (tempBundleLocation.startsWith("reference:file:")) {
String tempPathString = tempBundleLocation.substring(15);
if (tempPathString.endsWith("/")) {
// This is a directory! Happens during development, when an Eclipse instance is started from another
// Eclipse with the Integrity projects living there as projects and thus being included in the "inner"
// Eclipse as directories. We'll return the right subdir in that case to allow for inclusion of the
// compiled classes
return new Path(tempPathString + "target/classes/");
}
tempBundlePath = new Path(tempPathString);
} else {
tempBundlePath = new Path(tempBundleLocation);
}
if (tempBundlePath.isAbsolute()) {
return tempBundlePath;
}
Location tempInstallLocation = Platform.getInstallLocation();
if (tempInstallLocation == null || !tempInstallLocation.isSet()) {
return null;
}
Path tempPath = new Path(tempInstallLocation.getURL().getPath());
return tempPath.append(tempBundlePath);
}
|
diff --git a/modules/pm_struts/src/org/jpos/ee/pm/struts/converter/EditCollectionConverter.java b/modules/pm_struts/src/org/jpos/ee/pm/struts/converter/EditCollectionConverter.java
index de13763..a209b43 100644
--- a/modules/pm_struts/src/org/jpos/ee/pm/struts/converter/EditCollectionConverter.java
+++ b/modules/pm_struts/src/org/jpos/ee/pm/struts/converter/EditCollectionConverter.java
@@ -1,68 +1,68 @@
/*
* jPOS Presentation Manager [http://jpospm.blogspot.com]
* Copyright (C) 2010 Jeronimo Paoletti [[email protected]]
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jpos.ee.pm.struts.converter;
import java.util.Collection;
import java.util.List;
import org.jpos.ee.pm.converter.ConverterException;
import org.jpos.ee.pm.core.Entity;
import org.jpos.ee.pm.core.EntityInstanceWrapper;
import org.jpos.ee.pm.core.Field;
import org.jpos.ee.pm.core.Operation;
import org.jpos.ee.pm.core.PMLogger;
import org.jpos.ee.pm.struts.PMEntitySupport;
public class EditCollectionConverter extends StrutsEditConverter {
public Object build(Entity entity, Field field, Operation operation,
EntityInstanceWrapper einstance, Object value) throws ConverterException {
try{
String collection_class = getConfig("collection-class");
if(collection_class == null) throw new ConverterException("collection-class must be defined");
Collection<Object> result = (Collection<Object>) PMEntitySupport.getInstance().getPmservice().getFactory().newInstance (collection_class);
String s = (String)value;
if(s.trim().compareTo("")==0) return result;
String[] ss = s.split(";");
if(ss.length > 0 ){
String eid = ss[0].split("@")[0];
PMEntitySupport es = PMEntitySupport.getInstance();
Entity e = es.getPmservice().getEntity(eid);
if(e==null) throw new ConverterException("Cannot find entity "+eid);
- List<Object> list = es.getItems(es.getDb(), e, getConfig("filter")).getContents();
+ List<?> list = e.getList();
for (int i = 0; i < ss.length; i++) {
Integer x = Integer.parseInt(ss[i].split("@")[1]);
result.add(list.get(x));
}
}
return result;
} catch (ConverterException e2) {
throw e2;
} catch (Exception e1) {
PMLogger.error(e1);
throw new ConverterException("Cannot convert collection");
}
}
public String visualize(Entity entity, Field field, Operation operation,
EntityInstanceWrapper einstance, String extra) throws ConverterException {
return super.visualize("collection_converter.jsp?filter="+getConfig("filter")+"&entity="+getConfig("entity"));
}
}
| true | true | public Object build(Entity entity, Field field, Operation operation,
EntityInstanceWrapper einstance, Object value) throws ConverterException {
try{
String collection_class = getConfig("collection-class");
if(collection_class == null) throw new ConverterException("collection-class must be defined");
Collection<Object> result = (Collection<Object>) PMEntitySupport.getInstance().getPmservice().getFactory().newInstance (collection_class);
String s = (String)value;
if(s.trim().compareTo("")==0) return result;
String[] ss = s.split(";");
if(ss.length > 0 ){
String eid = ss[0].split("@")[0];
PMEntitySupport es = PMEntitySupport.getInstance();
Entity e = es.getPmservice().getEntity(eid);
if(e==null) throw new ConverterException("Cannot find entity "+eid);
List<Object> list = es.getItems(es.getDb(), e, getConfig("filter")).getContents();
for (int i = 0; i < ss.length; i++) {
Integer x = Integer.parseInt(ss[i].split("@")[1]);
result.add(list.get(x));
}
}
return result;
} catch (ConverterException e2) {
throw e2;
} catch (Exception e1) {
PMLogger.error(e1);
throw new ConverterException("Cannot convert collection");
}
}
| public Object build(Entity entity, Field field, Operation operation,
EntityInstanceWrapper einstance, Object value) throws ConverterException {
try{
String collection_class = getConfig("collection-class");
if(collection_class == null) throw new ConverterException("collection-class must be defined");
Collection<Object> result = (Collection<Object>) PMEntitySupport.getInstance().getPmservice().getFactory().newInstance (collection_class);
String s = (String)value;
if(s.trim().compareTo("")==0) return result;
String[] ss = s.split(";");
if(ss.length > 0 ){
String eid = ss[0].split("@")[0];
PMEntitySupport es = PMEntitySupport.getInstance();
Entity e = es.getPmservice().getEntity(eid);
if(e==null) throw new ConverterException("Cannot find entity "+eid);
List<?> list = e.getList();
for (int i = 0; i < ss.length; i++) {
Integer x = Integer.parseInt(ss[i].split("@")[1]);
result.add(list.get(x));
}
}
return result;
} catch (ConverterException e2) {
throw e2;
} catch (Exception e1) {
PMLogger.error(e1);
throw new ConverterException("Cannot convert collection");
}
}
|
diff --git a/src/main/java/pl/agh/enrollme/repository/SubjectDAO.java b/src/main/java/pl/agh/enrollme/repository/SubjectDAO.java
index 9cc75b8..5815e00 100644
--- a/src/main/java/pl/agh/enrollme/repository/SubjectDAO.java
+++ b/src/main/java/pl/agh/enrollme/repository/SubjectDAO.java
@@ -1,149 +1,150 @@
package pl.agh.enrollme.repository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import pl.agh.enrollme.model.*;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @author Michal Partyka
*/
@Repository
public class SubjectDAO extends GenericDAO<Subject> implements ISubjectDAO {
private final static Logger LOGGER = LoggerFactory.getLogger(SubjectDAO.class.getName());
@Autowired
IEnrollmentDAO enrollmentDAO;
@Autowired
IPersonDAO personDAO;
@Autowired
IStudentPointsPerTermDAO pointsDAO;
@Autowired
ITermDAO termDAO;
public SubjectDAO() {
super(Subject.class);
}
@PersistenceContext
EntityManager em;
/**
* Add subjects to the current user subjects list
* @param subjects - array of subjects.
*/
@Override
@Transactional
public void fillCurrentUserSubjectList(Subject[] subjects) {
UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
Person person = personDAO.findByUsername(userDetails.getUsername());
LOGGER.debug("User: " + person.getUsername() + " [" + person.getIndeks() + "] submitted subjects: " +
Arrays.asList(subjects));
final List<Subject> toRemove = new ArrayList<>();
final List<Subject> personSubjects = person.getSubjects();
for (Subject s : personSubjects) {
boolean contained = false;
for (Subject s2 : subjects) {
if (s2.equals(s)) {
contained = true;
break;
}
}
if (!contained) {
toRemove.add(s);
}
}
LOGGER.debug("To remove list computed: " + toRemove);
//Removing points assigned to terms belonging to subjects that are no longer choosen
for (Subject s : toRemove) {
s = getByPK(s.getSubjectID());
final List<Term> termsBySubject = termDAO.getTermsBySubject(s);
LOGGER.debug("Terms of subject: " + s + " retrieved");
for (Term t : termsBySubject) {
final StudentPointsPerTerm byPersonAndTerm = pointsDAO.getByPersonAndTerm(person, t);
if (byPersonAndTerm != null) {
pointsDAO.remove(byPersonAndTerm);
LOGGER.debug("Points of term: " + t + " removed");
}
}
s.getPersons().remove(person);
LOGGER.debug("Person removed from subject");
}
personSubjects.removeAll(toRemove);
LOGGER.debug("Unnecessary subjects removed");
for (Subject subject : subjects) {
+ subject = getByPK(subject.getSubjectID());
subject.addPerson(person);
person.addSubject(subject);
LOGGER.debug("add new subject to student: " + subject);
}
em.merge(person);
LOGGER.debug("Person updated");
}
@Override
@Transactional
public List<Subject> getSubjectsByPerson(Person person) {
person = personDAO.getByPK(person.getId());
return person.getSubjects();
}
@Override
@Transactional
/**
* @return list of subjects assigned to the given enrollment
*/
public List<Subject> getSubjectsByEnrollment(Enroll enrollment) {
LOGGER.debug("getSubjectsByEnrollment: enrollment: " + enrollment.getEnrollID() + " " + enrollment.getName());
enrollment = enrollmentDAO.getByPK(enrollment.getEnrollID());
return enrollment.getSubjects();
}
@Override
@Transactional
@Deprecated
public Subject getSubject(Integer id) {
return em.find(Subject.class, id);
}
@Override
@Transactional
@Deprecated
public List<Subject> getSubjectsWithGroups(Enroll enroll) {
// Teacher teacher1 = new Teacher("dr", "Stanisław", "Sobieszko", "4.11");
// Teacher teacher2 = new Teacher("dr", "Stasio", "Mieszko", "4.11");
// Subject subject1 = new Subject(enroll, null, "Mikroprocki", 2, "#00ffff", "4.33", teacher1, DayOfWeek.MONDAY,
// null, null);
// Subject subject2 = new Subject(enroll, null, "PSI 2", 4, "#ff0000", "4.11", teacher2, DayOfWeek.FRIDAY,
// null, null);
//subject1.setSubjectID(1);
//subject2.setSubjectID(2);
// List<Subject> subjects = new ArrayList<Subject>(2);
// subjects.add(subject1);
// subjects.add(subject2);
//em.merge(enroll);
//em.persist(enroll);
//em.merge(subject1);
// em.persist(subject1);
//em.merge(subject2);
// em.persist(subject2);
return null;
}
}
| true | true | public void fillCurrentUserSubjectList(Subject[] subjects) {
UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
Person person = personDAO.findByUsername(userDetails.getUsername());
LOGGER.debug("User: " + person.getUsername() + " [" + person.getIndeks() + "] submitted subjects: " +
Arrays.asList(subjects));
final List<Subject> toRemove = new ArrayList<>();
final List<Subject> personSubjects = person.getSubjects();
for (Subject s : personSubjects) {
boolean contained = false;
for (Subject s2 : subjects) {
if (s2.equals(s)) {
contained = true;
break;
}
}
if (!contained) {
toRemove.add(s);
}
}
LOGGER.debug("To remove list computed: " + toRemove);
//Removing points assigned to terms belonging to subjects that are no longer choosen
for (Subject s : toRemove) {
s = getByPK(s.getSubjectID());
final List<Term> termsBySubject = termDAO.getTermsBySubject(s);
LOGGER.debug("Terms of subject: " + s + " retrieved");
for (Term t : termsBySubject) {
final StudentPointsPerTerm byPersonAndTerm = pointsDAO.getByPersonAndTerm(person, t);
if (byPersonAndTerm != null) {
pointsDAO.remove(byPersonAndTerm);
LOGGER.debug("Points of term: " + t + " removed");
}
}
s.getPersons().remove(person);
LOGGER.debug("Person removed from subject");
}
personSubjects.removeAll(toRemove);
LOGGER.debug("Unnecessary subjects removed");
for (Subject subject : subjects) {
subject.addPerson(person);
person.addSubject(subject);
LOGGER.debug("add new subject to student: " + subject);
}
em.merge(person);
LOGGER.debug("Person updated");
}
| public void fillCurrentUserSubjectList(Subject[] subjects) {
UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
Person person = personDAO.findByUsername(userDetails.getUsername());
LOGGER.debug("User: " + person.getUsername() + " [" + person.getIndeks() + "] submitted subjects: " +
Arrays.asList(subjects));
final List<Subject> toRemove = new ArrayList<>();
final List<Subject> personSubjects = person.getSubjects();
for (Subject s : personSubjects) {
boolean contained = false;
for (Subject s2 : subjects) {
if (s2.equals(s)) {
contained = true;
break;
}
}
if (!contained) {
toRemove.add(s);
}
}
LOGGER.debug("To remove list computed: " + toRemove);
//Removing points assigned to terms belonging to subjects that are no longer choosen
for (Subject s : toRemove) {
s = getByPK(s.getSubjectID());
final List<Term> termsBySubject = termDAO.getTermsBySubject(s);
LOGGER.debug("Terms of subject: " + s + " retrieved");
for (Term t : termsBySubject) {
final StudentPointsPerTerm byPersonAndTerm = pointsDAO.getByPersonAndTerm(person, t);
if (byPersonAndTerm != null) {
pointsDAO.remove(byPersonAndTerm);
LOGGER.debug("Points of term: " + t + " removed");
}
}
s.getPersons().remove(person);
LOGGER.debug("Person removed from subject");
}
personSubjects.removeAll(toRemove);
LOGGER.debug("Unnecessary subjects removed");
for (Subject subject : subjects) {
subject = getByPK(subject.getSubjectID());
subject.addPerson(person);
person.addSubject(subject);
LOGGER.debug("add new subject to student: " + subject);
}
em.merge(person);
LOGGER.debug("Person updated");
}
|
diff --git a/source/nl.esciencecenter.vlet.vrs.core/src/nl/esciencecenter/vlet/vrs/vrl/VRLStreamHandlerFactory.java b/source/nl.esciencecenter.vlet.vrs.core/src/nl/esciencecenter/vlet/vrs/vrl/VRLStreamHandlerFactory.java
index 7e113fc0..445e472c 100644
--- a/source/nl.esciencecenter.vlet.vrs.core/src/nl/esciencecenter/vlet/vrs/vrl/VRLStreamHandlerFactory.java
+++ b/source/nl.esciencecenter.vlet.vrs.core/src/nl/esciencecenter/vlet/vrs/vrl/VRLStreamHandlerFactory.java
@@ -1,220 +1,221 @@
/*
* Copyright 2006-2010 Virtual Laboratory for e-Science (www.vl-e.nl)
* Copyright 2012-2013 Netherlands eScience Center.
*
* 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 the following location:
*
* 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.
*
* For the full license, see: LICENSE.txt (located in the root folder of this distribution).
* ---
*/
// source:
package nl.esciencecenter.vlet.vrs.vrl;
import java.net.URLStreamHandler;
import java.net.URLStreamHandlerFactory;
import nl.esciencecenter.ptk.util.logging.ClassLogger;
import nl.esciencecenter.vlet.VletConfig;
import nl.esciencecenter.vlet.net.ssl.VrsSslUtil;
/**
* The VRLStreamHandlerFactory.
*
* It extends URLStreamHandler with the supported protocols from the VRS
* Registry. Important: At startup this StreamHandleFactory has to be created
* and set as default in:
*
* <pre>
* URL.setURLStreamHandlerFactory();
* </pre>
*
* Currently this is done in the Global class. After this, the URL class can be
* use to VRS protocols !
* <p>
* Examples:
* <li>URL url=new URL("gftp://fs2.da2.nikhef.nl/");</li>
*
* @author P.T. de Boer
*/
public class VRLStreamHandlerFactory implements URLStreamHandlerFactory
{
private static VRLStreamHandlerFactory instance = null;
// no constructor:
// Whether to use SUN's 'file://' URL reader !
private static boolean use_sun_file_handler = true;
public synchronized static VRLStreamHandlerFactory getDefault()
{
if (instance == null)
instance = new VRLStreamHandlerFactory();
return instance;
}
// =========================================================================
// //
//
// =========================================================================
// //
private Class<? extends URLStreamHandler> httpsURLHandlerClass;
private Class<? extends URLStreamHandler> httpgURLHandlerClass;
private VRLStreamHandlerFactory()
{
this.httpsURLHandlerClass = VrsSslUtil.createHttpsHandler().getClass();
}
public URLStreamHandler createURLStreamHandler(String protocol)
{
ClassLogger.getLogger(URLStreamHandler.class).debugPrintf("createURLStreamHandler() for:%s\n",protocol);
if (protocol.compareToIgnoreCase("jar") == 0)
{
// return sun's default HTTP handler !
return new sun.net.www.protocol.jar.Handler();
}
// sun http handler !
else if (protocol.compareToIgnoreCase("mailto") == 0)
{
// return sun's default HTTP handler !
return new sun.net.www.protocol.mailto.Handler();
}
// sun http handler !
else if (protocol.compareToIgnoreCase("ftp") == 0)
{
// return sun's default HTTP handler !
return new sun.net.www.protocol.ftp.Handler();
}
- else if (protocol.compareToIgnoreCase("gopher") == 0)
- {
- // return sun's default HTTP handler !
- return new sun.net.www.protocol.gopher.Handler();
- }
+ // Not in Java 1.8:
+// else if (protocol.compareToIgnoreCase("gopher") == 0)
+// {
+// // return sun's default HTTP handler !
+// return new sun.net.www.protocol.gopher.Handler();
+// }
// not in java 1.7 :
/*
* else if (protocol.compareToIgnoreCase("verbatim")==0) { // return
* sun's default HTTP handler ! return new
* sun.net.www.protocol.verbatim.Handler(); } else if
* (protocol.compareToIgnoreCase("systemresource")==0) { // return sun's
* default HTTP handler ! return new
* sun.net.www.protocol.systemresource.Handler(); }
*/
else if (protocol.compareToIgnoreCase("https") == 0)
{
// return sun's default HTTP handler !
// this.httpsURLHandlerClass=SslUtil.createHttpsHandler().getClass();
try
{
return this.httpsURLHandlerClass.newInstance();
}
catch (Exception e)
{
throw new Error(e);
}
}
else if ((protocol.compareToIgnoreCase("httpg") == 0) && (httpgURLHandlerClass != null))
{
try
{
// Use Globus GSS/GSI URL socket handler
return this.httpgURLHandlerClass.newInstance();
}
catch (Exception e)
{
throw new Error(e);
}
}
else if (protocol.compareToIgnoreCase("http") == 0)
{
String proxyHost = null;
int proxyPort = 0;
// if (VletConfig.getUseHttpProxy())
// {
//
// proxyHost = VletConfig.getHttpProxyHost();
// proxyPort = VletConfig.getHttpProxyPort();
//
// ClassLogger.getLogger(getClass()).infoPrintf("Using HTTP Proxy=%s:%d\n",proxyHost,proxyPort);
//
// // return sun's default HTTP handler !
// return new sun.net.www.protocol.http.Handler(proxyHost, proxyPort);
// }
// else
{
//Global.infoPrintln(this, "Using plain HTTP connection");
// return sun's default HTTP handler !
return new sun.net.www.protocol.http.Handler();
}
}
//
// Use own https handler so that server certificates
// can be added.
//
/*
* // sun https handler ! else if
* (protocol.compareToIgnoreCase("https")==0) { // return sun's default
* HTTPS handler ! return new sun.net.www.protocol.https.Handler(); }
*/
else if (use_sun_file_handler)
{
//
// Following protocols could be handled by the VRS Registry
// but only AFTER the Reigstry has been initialized.
// Currently the Registry sets the VRLStreamHandler after
// initialition
// so the following code isn't necessary :
//
// WINDOWS PATH: [aA]:,[bB]:,[cC]:,[dD]:,... !
if (protocol.charAt(1) == ':')
{
return new sun.net.www.protocol.file.Handler();
}
// sun jar handler !
else if (protocol.compareToIgnoreCase("file") == 0)
{
// return sun's default HTTP handler !
return new sun.net.www.protocol.file.Handler();
}
}
// return VRStreamHandler
return new VRLStreamHandler();
}
public void setHTTPGUrlHandlerClass(Class<? extends URLStreamHandler> handlerClass)
{
// Todo: Better GSS/GSI/SSL integration:
this.httpgURLHandlerClass = handlerClass;
}
}
| true | true | public URLStreamHandler createURLStreamHandler(String protocol)
{
ClassLogger.getLogger(URLStreamHandler.class).debugPrintf("createURLStreamHandler() for:%s\n",protocol);
if (protocol.compareToIgnoreCase("jar") == 0)
{
// return sun's default HTTP handler !
return new sun.net.www.protocol.jar.Handler();
}
// sun http handler !
else if (protocol.compareToIgnoreCase("mailto") == 0)
{
// return sun's default HTTP handler !
return new sun.net.www.protocol.mailto.Handler();
}
// sun http handler !
else if (protocol.compareToIgnoreCase("ftp") == 0)
{
// return sun's default HTTP handler !
return new sun.net.www.protocol.ftp.Handler();
}
else if (protocol.compareToIgnoreCase("gopher") == 0)
{
// return sun's default HTTP handler !
return new sun.net.www.protocol.gopher.Handler();
}
// not in java 1.7 :
/*
* else if (protocol.compareToIgnoreCase("verbatim")==0) { // return
* sun's default HTTP handler ! return new
* sun.net.www.protocol.verbatim.Handler(); } else if
* (protocol.compareToIgnoreCase("systemresource")==0) { // return sun's
* default HTTP handler ! return new
* sun.net.www.protocol.systemresource.Handler(); }
*/
else if (protocol.compareToIgnoreCase("https") == 0)
{
// return sun's default HTTP handler !
// this.httpsURLHandlerClass=SslUtil.createHttpsHandler().getClass();
try
{
return this.httpsURLHandlerClass.newInstance();
}
catch (Exception e)
{
throw new Error(e);
}
}
else if ((protocol.compareToIgnoreCase("httpg") == 0) && (httpgURLHandlerClass != null))
{
try
{
// Use Globus GSS/GSI URL socket handler
return this.httpgURLHandlerClass.newInstance();
}
catch (Exception e)
{
throw new Error(e);
}
}
else if (protocol.compareToIgnoreCase("http") == 0)
{
String proxyHost = null;
int proxyPort = 0;
// if (VletConfig.getUseHttpProxy())
// {
//
// proxyHost = VletConfig.getHttpProxyHost();
// proxyPort = VletConfig.getHttpProxyPort();
//
// ClassLogger.getLogger(getClass()).infoPrintf("Using HTTP Proxy=%s:%d\n",proxyHost,proxyPort);
//
// // return sun's default HTTP handler !
// return new sun.net.www.protocol.http.Handler(proxyHost, proxyPort);
// }
// else
{
//Global.infoPrintln(this, "Using plain HTTP connection");
// return sun's default HTTP handler !
return new sun.net.www.protocol.http.Handler();
}
}
//
// Use own https handler so that server certificates
// can be added.
//
/*
* // sun https handler ! else if
* (protocol.compareToIgnoreCase("https")==0) { // return sun's default
* HTTPS handler ! return new sun.net.www.protocol.https.Handler(); }
*/
else if (use_sun_file_handler)
{
//
// Following protocols could be handled by the VRS Registry
// but only AFTER the Reigstry has been initialized.
// Currently the Registry sets the VRLStreamHandler after
// initialition
// so the following code isn't necessary :
//
// WINDOWS PATH: [aA]:,[bB]:,[cC]:,[dD]:,... !
if (protocol.charAt(1) == ':')
{
return new sun.net.www.protocol.file.Handler();
}
// sun jar handler !
else if (protocol.compareToIgnoreCase("file") == 0)
{
// return sun's default HTTP handler !
return new sun.net.www.protocol.file.Handler();
}
}
// return VRStreamHandler
return new VRLStreamHandler();
}
| public URLStreamHandler createURLStreamHandler(String protocol)
{
ClassLogger.getLogger(URLStreamHandler.class).debugPrintf("createURLStreamHandler() for:%s\n",protocol);
if (protocol.compareToIgnoreCase("jar") == 0)
{
// return sun's default HTTP handler !
return new sun.net.www.protocol.jar.Handler();
}
// sun http handler !
else if (protocol.compareToIgnoreCase("mailto") == 0)
{
// return sun's default HTTP handler !
return new sun.net.www.protocol.mailto.Handler();
}
// sun http handler !
else if (protocol.compareToIgnoreCase("ftp") == 0)
{
// return sun's default HTTP handler !
return new sun.net.www.protocol.ftp.Handler();
}
// Not in Java 1.8:
// else if (protocol.compareToIgnoreCase("gopher") == 0)
// {
// // return sun's default HTTP handler !
// return new sun.net.www.protocol.gopher.Handler();
// }
// not in java 1.7 :
/*
* else if (protocol.compareToIgnoreCase("verbatim")==0) { // return
* sun's default HTTP handler ! return new
* sun.net.www.protocol.verbatim.Handler(); } else if
* (protocol.compareToIgnoreCase("systemresource")==0) { // return sun's
* default HTTP handler ! return new
* sun.net.www.protocol.systemresource.Handler(); }
*/
else if (protocol.compareToIgnoreCase("https") == 0)
{
// return sun's default HTTP handler !
// this.httpsURLHandlerClass=SslUtil.createHttpsHandler().getClass();
try
{
return this.httpsURLHandlerClass.newInstance();
}
catch (Exception e)
{
throw new Error(e);
}
}
else if ((protocol.compareToIgnoreCase("httpg") == 0) && (httpgURLHandlerClass != null))
{
try
{
// Use Globus GSS/GSI URL socket handler
return this.httpgURLHandlerClass.newInstance();
}
catch (Exception e)
{
throw new Error(e);
}
}
else if (protocol.compareToIgnoreCase("http") == 0)
{
String proxyHost = null;
int proxyPort = 0;
// if (VletConfig.getUseHttpProxy())
// {
//
// proxyHost = VletConfig.getHttpProxyHost();
// proxyPort = VletConfig.getHttpProxyPort();
//
// ClassLogger.getLogger(getClass()).infoPrintf("Using HTTP Proxy=%s:%d\n",proxyHost,proxyPort);
//
// // return sun's default HTTP handler !
// return new sun.net.www.protocol.http.Handler(proxyHost, proxyPort);
// }
// else
{
//Global.infoPrintln(this, "Using plain HTTP connection");
// return sun's default HTTP handler !
return new sun.net.www.protocol.http.Handler();
}
}
//
// Use own https handler so that server certificates
// can be added.
//
/*
* // sun https handler ! else if
* (protocol.compareToIgnoreCase("https")==0) { // return sun's default
* HTTPS handler ! return new sun.net.www.protocol.https.Handler(); }
*/
else if (use_sun_file_handler)
{
//
// Following protocols could be handled by the VRS Registry
// but only AFTER the Reigstry has been initialized.
// Currently the Registry sets the VRLStreamHandler after
// initialition
// so the following code isn't necessary :
//
// WINDOWS PATH: [aA]:,[bB]:,[cC]:,[dD]:,... !
if (protocol.charAt(1) == ':')
{
return new sun.net.www.protocol.file.Handler();
}
// sun jar handler !
else if (protocol.compareToIgnoreCase("file") == 0)
{
// return sun's default HTTP handler !
return new sun.net.www.protocol.file.Handler();
}
}
// return VRStreamHandler
return new VRLStreamHandler();
}
|
diff --git a/examples/src/main/java/org/apache/mahout/ga/watchmaker/cd/CDFitness.java b/examples/src/main/java/org/apache/mahout/ga/watchmaker/cd/CDFitness.java
index 5071d9503..426813f79 100644
--- a/examples/src/main/java/org/apache/mahout/ga/watchmaker/cd/CDFitness.java
+++ b/examples/src/main/java/org/apache/mahout/ga/watchmaker/cd/CDFitness.java
@@ -1,133 +1,133 @@
/**
* 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.mahout.ga.watchmaker.cd;
import org.apache.hadoop.io.Writable;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
/**
* Fitness of the class discovery problem.
*/
public class CDFitness implements Writable {
/** True positive */
private int tp;
/** False positive */
private int fp;
/** True negative */
private int tn;
/** False negative */
private int fn;
public CDFitness() {
}
public CDFitness(CDFitness f) {
tp = f.getTp();
fp = f.getFp();
tn = f.getTn();
fn = f.getFn();
}
public CDFitness(int tp, int fp, int tn, int fn) {
this.tp = tp;
this.fp = fp;
this.tn = tn;
this.fn = fn;
}
public int getTp() {
return tp;
}
public int getFp() {
return fp;
}
public int getTn() {
return tn;
}
public int getFn() {
return fn;
}
public void add(CDFitness f) {
tp += f.getTp();
fp += f.getFp();
tn += f.getTn();
fn += f.getFn();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || !(obj instanceof CDFitness))
return false;
CDFitness f = (CDFitness) obj;
- return tp == f.getFp() && fp == f.getFp() && tn == f.getTn() && fn == f.getTn();
+ return tp == f.getTp() && fp == f.getFp() && tn == f.getTn() && fn == f.getFn();
}
@Override
public int hashCode() {
return tp + 31 * (fp + 31 * (tn + 31 * fn));
}
@Override
public String toString() {
return "[TP=" + tp + ", FP=" + fp + ", TN=" + tn + ", FN=" + fn + ']';
}
/**
* Calculates the fitness corresponding to this evaluation.
*/
public double get() {
double se = ((double) tp) / (tp + fn); // sensitivity
double sp = ((double) tn) / (tn + fp); // specificity
return se * sp;
}
@Override
public void readFields(DataInput in) throws IOException {
tp = in.readInt();
fp = in.readInt();
tn = in.readInt();
fn = in.readInt();
}
@Override
public void write(DataOutput out) throws IOException {
out.writeInt(tp);
out.writeInt(fp);
out.writeInt(tn);
out.writeInt(fn);
}
}
| true | true | public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || !(obj instanceof CDFitness))
return false;
CDFitness f = (CDFitness) obj;
return tp == f.getFp() && fp == f.getFp() && tn == f.getTn() && fn == f.getTn();
}
| public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || !(obj instanceof CDFitness))
return false;
CDFitness f = (CDFitness) obj;
return tp == f.getTp() && fp == f.getFp() && tn == f.getTn() && fn == f.getFn();
}
|
diff --git a/code/src/commands/ExportCommand.java b/code/src/commands/ExportCommand.java
index 340a2e9..2342549 100644
--- a/code/src/commands/ExportCommand.java
+++ b/code/src/commands/ExportCommand.java
@@ -1,48 +1,48 @@
package commands;
import java.io.IOException;
import java.util.ArrayList;
import UI.UI;
import exporter.FileExporter;
import exporter.ListGenerator;
public class ExportCommand implements Command {
UI ui;
public ExportCommand(UI ui) {
this.ui = ui;
}
@Override
public void execute() {
// TODO Auto-generated method stub
ExportParameters param = ui.getExportParameters();
switch(param.type){
case Email:
System.err.println("not implemented");
- return;
+ break;
case File:
FileExporter exp = new FileExporter(param.startDate, param.endDate);
try {
exp.export();
} catch (IOException e1) {
System.err.println("encountered IO error while exporting to a file.");
e1.printStackTrace();
}
- return;
+ break;
case UI:
// TODO: need to refactor this to remove println
ListGenerator listGen = new ListGenerator(param.startDate, param.endDate);
ArrayList<String> list = listGen.getList();
//TODO: Replace with Email/FileExporter depending on user input
for(String e : list) {
System.out.println(e);
}
- default: return;
+ default: break;
}
}
}
| false | true | public void execute() {
// TODO Auto-generated method stub
ExportParameters param = ui.getExportParameters();
switch(param.type){
case Email:
System.err.println("not implemented");
return;
case File:
FileExporter exp = new FileExporter(param.startDate, param.endDate);
try {
exp.export();
} catch (IOException e1) {
System.err.println("encountered IO error while exporting to a file.");
e1.printStackTrace();
}
return;
case UI:
// TODO: need to refactor this to remove println
ListGenerator listGen = new ListGenerator(param.startDate, param.endDate);
ArrayList<String> list = listGen.getList();
//TODO: Replace with Email/FileExporter depending on user input
for(String e : list) {
System.out.println(e);
}
default: return;
}
}
| public void execute() {
// TODO Auto-generated method stub
ExportParameters param = ui.getExportParameters();
switch(param.type){
case Email:
System.err.println("not implemented");
break;
case File:
FileExporter exp = new FileExporter(param.startDate, param.endDate);
try {
exp.export();
} catch (IOException e1) {
System.err.println("encountered IO error while exporting to a file.");
e1.printStackTrace();
}
break;
case UI:
// TODO: need to refactor this to remove println
ListGenerator listGen = new ListGenerator(param.startDate, param.endDate);
ArrayList<String> list = listGen.getList();
//TODO: Replace with Email/FileExporter depending on user input
for(String e : list) {
System.out.println(e);
}
default: break;
}
}
|
diff --git a/src/Board.java b/src/Board.java
index f992200..ff339d6 100644
--- a/src/Board.java
+++ b/src/Board.java
@@ -1,282 +1,283 @@
/**
* This class represents a 9x9 sudoku Board.
* Each cell contains either the numeric value of the cell, or all the values
* that could potentially be placed within the cell. This board is designed
* to make solving the sudoku board easy.
* @author Aaron Balsara, Nicholas Figueira, David Loyzaga
*/
public class Board {
/**
* The default value of a cell if is empty.
* This value represents all the possible numbers that
* can be put into this cell.
*
* The 0 is put in as a flag to distinguish between when the value has been
* assigned by the user and when there is only one option remaining.
* For example, if a cell can only have the number 1, its string value
* will be "01" until assign is called and its value will be "1".
*/
private final String DEFAULT = "0123456789";
/**
* The array of strings representing the board.
*/
private String[][] board;
/**
* Creates a sudoku board from a given string.
*
* The string should be in the form of 81 characters, with numbers
* representing numbers in the board and a '.' representing whitespace.
* @param layout The string to create the board from.
*/
public Board (String layout) {
board = new String[9][9];
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
board[i][j] = DEFAULT;
}
}
if (layout != "") {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (layout.charAt(9 * i + j) != '.') {
assign(i, j, layout.charAt(9 * i + j) - '0');
}
}
}
}
}
/**
* Returns a string which shows the possible moves for this cell.
*
* This cell will need to be edited by a solver which utilises
* removeOption() to return a correct value, otherwise all possible
* options will be returned regardless of legality.
* @param row The row of the cell.
* @param col The column of the cell.
* @return The cell's possible values.
*/
public String getOptions (int row, int col) {
char[] chars = board[row][col].toCharArray();
java.util.Arrays.sort(chars);
board[row][col] = new String(chars);
return board[row][col];
}
/**
* Returns a cells value. Returns 0 if no value is assigned.
* @param row
* @param col
* @return
*/
public int cellValue (int row, int col) {
if (board[row][col].length() == 1) {
int cellValue = Integer.parseInt(board[row][col]);
if (cellValue > 9) {
return 0;
} else {
return cellValue;
}
}
return 0;
}
/**
* Assigns a cell a particular value.
*
* This method first checks if a move such as this would be considered
* legal, and will only make the move if it does not immediately
* break and constraints.
* @param row The row of the cell to be changed (0-8).
* @param col The column of the cell to be changed (0-8).
* @param num The new value of that cell.
* @return Returns true if the assignment was made.
*/
public boolean assign (int row, int col, int num) {
if (isLegal(row, col, num)) {
board[row][col] = String.valueOf(num);
constrain (row, col);
return true;
}
return false;
}
/**
* Constrains the board to the value of the current cell.
*
* Constrains all cells of the same row, column and box with the
* value in this cell.
* @param row The row of the cell.
* @param col The column of the cell.
*/
public void constrain (int row, int col) {
int removeValue = Integer.valueOf(board[row][col]);
int boxRow = row / 3;
int boxCol = col / 3;
for (int i = 0; i < 9; i++) {
removeOption (row, i, removeValue);
removeOption (i, col, removeValue);
removeOption ((boxRow * 3) + i % 3, (boxCol * 3) + i / 3, removeValue);
}
}
/**
* Removes an option for a number
* @param row The row of cell to be edited (0-8).
* @param col The column of the cell to be edited (0-8).
* @param num The number which should be removed from that cell.
*/
public void removeOption (int row, int col, int num) {
if (num >= 1 && num <= 9 && board[row][col].length() != 1) {
String remove = String.valueOf(num);
board[row][col] = board[row][col].replace(remove, "");
}
}
/**
* Clears the value in the given cell.
* @param row The row of the cell to be cleared.
* @param col The column of the cell to be cleared.
*/
public void clearCell (int row, int col) {
if (board[row][col].length() != 1) {
return;
}
String removed = board[row][col];
for (int i = 0; i < 9; i++) {
- if (board[row][i].length() != 1) {
+ if (board[row][i].length() != 1 || board[row][i].equals("0")) {
if (!board[row][i].contains(removed)) {
board[row][i] = board[row][i].concat(removed);
}
}
- if (board[i][col].length() != 1) {
+ if (board[i][col].length() != 1 || board[i][col].equals("0")) {
if (!board[i][col].contains(removed)) {
board[i][col] = board[i][col].concat(removed);
}
}
- if (board[(row/3)*3 + (i%3)][(col/3)*3 + (i/3)].length() != 1) {
+ if (board[(row/3)*3 + (i%3)][(col/3)*3 + (i/3)].length() != 1
+ || board[(row/3)*3 + (i%3)][(col/3)*3 + (i/3)].equals("0")) {
if (!board[(row/3)*3 + (i%3)][(col/3)*3 + (i/3)].contains(removed)) {
board[(row/3)*3 + (i%3)][(col/3)*3 + (i/3)] =
board[(row/3)*3 + (i%3)][(col/3)*3 + (i/3)].concat(removed);
}
}
}
board[row][col] = DEFAULT;
setCellConstraints(row, col);
}
/**
* Constrains the given cell in line with the rules of sudoku.
* After this method is run, this cells options will only contain the
* numbers that can be legally placed within the confines of sudoku.
* @param row The row of the cell to be constrained.
* @param col The column of the cell to be constrained.
*/
public void setCellConstraints (int row, int col) {
board[row][col] = DEFAULT;
for (int i = 0; i < 9; i++) {
if (i != col) {
if (board[row][i].length() == 1) {
board[row][col] = board[row][col].replace(board[row][i], "");
}
}
if (i != row) {
if (board[i][col].length() == 1) {
board[row][col] = board[row][col].replace(board[i][col], "");
}
}
int boxRow = (row/3)*3+i%3;
int boxCol = (col/3)*3+i/3;
if (boxRow != row && boxCol != col) {
if (board[boxRow][boxCol].length() == 1) {
board[row][col] = board[row][col].replace(board[boxRow][boxCol], "");
}
}
}
}
/**
* Returns true if this board has no solution.
* If this method returns false, this still does not guarantee a solution.
* @return
*/
public boolean hasNoSolution () {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j].length() == 1) {
if (board[i][j].charAt(0) == '0') {
return true;
}
}
}
}
return false;
}
/**
* Checks if the cell contained by row and column can contain the value num.
* @param row The row of the cell to be checked.
* @param col The column of the cell to be checked.
* @param num The number to be checked.
* @return True if the number can be legally placed in the cell.
*/
public boolean isLegal (int row, int col, int num) {
return board[row][col].contains(String.valueOf(num));
}
/**
* Returns the string value of this board.
*
* If a new board is used using this value the cells will initially
* show all options, regardless of legality.
* @return the string value of this board.
*/
public String toString () {
String value = new String();
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j].length() == 1) {
if (board[i][j].charAt(0) == '0') {
value = value.concat(".");
} else {
value = value.concat(board[i][j]);
}
} else {
value = value.concat(".");
}
}
}
return value;
}
/**
* Creates another copy of this board.
* @return A copy of this board.
*/
public Board clone () {
return new Board(toString());
}
/**
* Prints the board to the standard System.out.
*/
public void printToOut () {
System.out.println("_____________________________________");
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j].length() == 1) {
System.out.print("| " + board[i][j] + " ");
} else {
System.out.print("| ");
}
}
System.out.println("|");
System.out.println("_____________________________________");
}
}
}
| false | true | public void clearCell (int row, int col) {
if (board[row][col].length() != 1) {
return;
}
String removed = board[row][col];
for (int i = 0; i < 9; i++) {
if (board[row][i].length() != 1) {
if (!board[row][i].contains(removed)) {
board[row][i] = board[row][i].concat(removed);
}
}
if (board[i][col].length() != 1) {
if (!board[i][col].contains(removed)) {
board[i][col] = board[i][col].concat(removed);
}
}
if (board[(row/3)*3 + (i%3)][(col/3)*3 + (i/3)].length() != 1) {
if (!board[(row/3)*3 + (i%3)][(col/3)*3 + (i/3)].contains(removed)) {
board[(row/3)*3 + (i%3)][(col/3)*3 + (i/3)] =
board[(row/3)*3 + (i%3)][(col/3)*3 + (i/3)].concat(removed);
}
}
}
board[row][col] = DEFAULT;
setCellConstraints(row, col);
}
| public void clearCell (int row, int col) {
if (board[row][col].length() != 1) {
return;
}
String removed = board[row][col];
for (int i = 0; i < 9; i++) {
if (board[row][i].length() != 1 || board[row][i].equals("0")) {
if (!board[row][i].contains(removed)) {
board[row][i] = board[row][i].concat(removed);
}
}
if (board[i][col].length() != 1 || board[i][col].equals("0")) {
if (!board[i][col].contains(removed)) {
board[i][col] = board[i][col].concat(removed);
}
}
if (board[(row/3)*3 + (i%3)][(col/3)*3 + (i/3)].length() != 1
|| board[(row/3)*3 + (i%3)][(col/3)*3 + (i/3)].equals("0")) {
if (!board[(row/3)*3 + (i%3)][(col/3)*3 + (i/3)].contains(removed)) {
board[(row/3)*3 + (i%3)][(col/3)*3 + (i/3)] =
board[(row/3)*3 + (i%3)][(col/3)*3 + (i/3)].concat(removed);
}
}
}
board[row][col] = DEFAULT;
setCellConstraints(row, col);
}
|
diff --git a/clustering/src/org/clustering/model/Item.java b/clustering/src/org/clustering/model/Item.java
index 50ad41b..5f915d1 100644
--- a/clustering/src/org/clustering/model/Item.java
+++ b/clustering/src/org/clustering/model/Item.java
@@ -1,51 +1,51 @@
package org.clustering.model;
import java.util.HashMap;
import java.util.HashSet;
public class Item {
private final int itemNumber;
private HashSet<String> keywords;
private HashMap<Item, Double> distances;
public Item(int itemNumber) {
this.itemNumber = itemNumber;
keywords = new HashSet<String>();
distances = new HashMap<Item, Double>();
}
public double getDistance(Item item) {
Double dist = distances.get(item);
return dist;
}
public void addKeyword(String keyword) {
keywords.add(keyword);
}
public void calcDistance(Item item, int numKeywords) {
- int mutualKeywords = 0;
+ double mutualKeywords = 0;
for(String keyword : getKeywords()) {
if(item.getKeywords().contains(keyword)) mutualKeywords++;
}
double distance = mutualKeywords/numKeywords;
setDistance(item, distance);
item.setDistance(this, distance);
}
private void setDistance(Item item, double distance) {
distances.put(item, distance);
}
private HashSet<String> getKeywords() {
return keywords;
}
@Override
public String toString() {
return "Item "+itemNumber+" keywords: "+keywords.size();
}
}
| true | true | public void calcDistance(Item item, int numKeywords) {
int mutualKeywords = 0;
for(String keyword : getKeywords()) {
if(item.getKeywords().contains(keyword)) mutualKeywords++;
}
double distance = mutualKeywords/numKeywords;
setDistance(item, distance);
item.setDistance(this, distance);
}
| public void calcDistance(Item item, int numKeywords) {
double mutualKeywords = 0;
for(String keyword : getKeywords()) {
if(item.getKeywords().contains(keyword)) mutualKeywords++;
}
double distance = mutualKeywords/numKeywords;
setDistance(item, distance);
item.setDistance(this, distance);
}
|
diff --git a/android/phoenix/src/org/retroarch/browser/CoreSelection.java b/android/phoenix/src/org/retroarch/browser/CoreSelection.java
index 70675051f3..44f59f267e 100644
--- a/android/phoenix/src/org/retroarch/browser/CoreSelection.java
+++ b/android/phoenix/src/org/retroarch/browser/CoreSelection.java
@@ -1,384 +1,385 @@
package org.retroarch.browser;
import org.retroarch.R;
import java.io.*;
import android.content.*;
import android.annotation.TargetApi;
import android.app.*;
import android.media.AudioManager;
import android.media.AudioTrack;
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.*;
// JELLY_BEAN_MR1 = 17
public class CoreSelection extends Activity implements
AdapterView.OnItemClickListener {
private IconAdapter<ModuleWrapper> adapter;
static private final int ACTIVITY_LOAD_ROM = 0;
static private String libretro_path;
static private final String TAG = "CoreSelection";
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");
}
@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);
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
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 if ((getApplicationInfo().dataDir) != null)
return (getApplicationInfo().dataDir) + File.separator + "retroarch.cfg";
else // emergency fallback, all else failed
return "/mnt/sd/retroarch.cfg";
}
@TargetApi(17)
private int getLowLatencyOptimalSamplingRate() {
AudioManager manager = (AudioManager)getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
return Integer.parseInt(manager.getProperty(AudioManager.PROPERTY_OUTPUT_SAMPLE_RATE));
}
private int getOptimalSamplingRate() {
int ret;
if (android.os.Build.VERSION.SDK_INT >= 17)
ret = getLowLatencyOptimalSamplingRate();
else
ret = AudioTrack.getNativeOutputSampleRate(AudioManager.STREAM_MUSIC);
Log.i(TAG, "Using sampling rate: " + ret + " Hz");
return ret;
}
private void updateConfigFile() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
config.setBoolean("audio_rate_control", prefs.getBoolean("audio_rate_control", true));
config.setInt("audio_out_rate", getOptimalSamplingRate());
+ config.setInt("audio_latency", prefs.getBoolean("audio_high_latency", false) ? 160 : 64);
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", true));
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_back_behavior", Integer.valueOf(prefs.getString("input_back_behavior", "0")));
config.setInt("input_autodetect_icade_profile_pad1", Integer.valueOf(prefs.getString("input_autodetect_icade_profile_pad1", "0")));
config.setInt("input_autodetect_icade_profile_pad2", Integer.valueOf(prefs.getString("input_autodetect_icade_profile_pad2", "0")));
config.setInt("input_autodetect_icade_profile_pad3", Integer.valueOf(prefs.getString("input_autodetect_icade_profile_pad3", "0")));
config.setInt("input_autodetect_icade_profile_pad4", Integer.valueOf(prefs.getString("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_shader", "");
config.setString("video_shader", shaderPath);
config.setBoolean("video_shader_enable",
prefs.getBoolean("video_shader_enable", false)
&& new File(shaderPath).exists());
boolean useOverlay = prefs.getBoolean("input_overlay_enable", true);
if (useOverlay) {
String overlayPath = prefs.getString("input_overlay", (getApplicationInfo().dataDir) + "/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.setString("system_directory", prefs.getBoolean("system_directory_enable", false) ?
prefs.getString("system_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, RetroActivity.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;
default:
return false;
}
}
}
| true | true | private void updateConfigFile() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
config.setBoolean("audio_rate_control", prefs.getBoolean("audio_rate_control", true));
config.setInt("audio_out_rate", getOptimalSamplingRate());
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", true));
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_back_behavior", Integer.valueOf(prefs.getString("input_back_behavior", "0")));
config.setInt("input_autodetect_icade_profile_pad1", Integer.valueOf(prefs.getString("input_autodetect_icade_profile_pad1", "0")));
config.setInt("input_autodetect_icade_profile_pad2", Integer.valueOf(prefs.getString("input_autodetect_icade_profile_pad2", "0")));
config.setInt("input_autodetect_icade_profile_pad3", Integer.valueOf(prefs.getString("input_autodetect_icade_profile_pad3", "0")));
config.setInt("input_autodetect_icade_profile_pad4", Integer.valueOf(prefs.getString("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_shader", "");
config.setString("video_shader", shaderPath);
config.setBoolean("video_shader_enable",
prefs.getBoolean("video_shader_enable", false)
&& new File(shaderPath).exists());
boolean useOverlay = prefs.getBoolean("input_overlay_enable", true);
if (useOverlay) {
String overlayPath = prefs.getString("input_overlay", (getApplicationInfo().dataDir) + "/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.setString("system_directory", prefs.getBoolean("system_directory_enable", false) ?
prefs.getString("system_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.setInt("audio_out_rate", getOptimalSamplingRate());
config.setInt("audio_latency", prefs.getBoolean("audio_high_latency", false) ? 160 : 64);
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", true));
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_back_behavior", Integer.valueOf(prefs.getString("input_back_behavior", "0")));
config.setInt("input_autodetect_icade_profile_pad1", Integer.valueOf(prefs.getString("input_autodetect_icade_profile_pad1", "0")));
config.setInt("input_autodetect_icade_profile_pad2", Integer.valueOf(prefs.getString("input_autodetect_icade_profile_pad2", "0")));
config.setInt("input_autodetect_icade_profile_pad3", Integer.valueOf(prefs.getString("input_autodetect_icade_profile_pad3", "0")));
config.setInt("input_autodetect_icade_profile_pad4", Integer.valueOf(prefs.getString("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_shader", "");
config.setString("video_shader", shaderPath);
config.setBoolean("video_shader_enable",
prefs.getBoolean("video_shader_enable", false)
&& new File(shaderPath).exists());
boolean useOverlay = prefs.getBoolean("input_overlay_enable", true);
if (useOverlay) {
String overlayPath = prefs.getString("input_overlay", (getApplicationInfo().dataDir) + "/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.setString("system_directory", prefs.getBoolean("system_directory_enable", false) ?
prefs.getString("system_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/java/drbd/utilities/Tools.java b/src/java/drbd/utilities/Tools.java
index 574f1cc0..01855e7e 100644
--- a/src/java/drbd/utilities/Tools.java
+++ b/src/java/drbd/utilities/Tools.java
@@ -1,2732 +1,2734 @@
/*
* This file is part of DRBD Management Console by LINBIT HA-Solutions GmbH
* written by Rasto Levrinc.
*
* Copyright (C) 2009, LINBIT HA-Solutions GmbH.
*
* DRBD Management Console 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.
*
* DRBD Management Console is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with drbd; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package drbd.utilities;
import drbd.data.ConfigData;
import drbd.data.Host;
import drbd.data.Cluster;
import drbd.data.Clusters;
import drbd.data.DrbdGuiXML;
import drbd.configs.DistResource;
import drbd.gui.resources.DrbdResourceInfo;
import drbd.gui.resources.Info;
import drbd.gui.resources.ServiceInfo;
import drbd.gui.ClusterBrowser;
import drbd.gui.GUIData;
import drbd.gui.dialog.ConfirmDialog;
import drbd.Exceptions;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.regex.PatternSyntaxException;
import java.util.List;
import java.util.ArrayList;
import java.util.ResourceBundle;
import java.util.Properties;
import java.util.Locale;
import java.util.Enumeration;
import java.util.Map;
import java.util.HashMap;
import java.util.Random;
import java.util.Set;
import java.util.Collection;
import java.util.TreeSet;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.io.File;
import java.io.InputStream;
import java.io.FileNotFoundException;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.JEditorPane;
import javax.swing.JScrollPane;
import javax.swing.border.TitledBorder;
import javax.swing.BorderFactory;
import javax.swing.JTextArea;
import javax.swing.DefaultListModel;
import javax.swing.text.html.HTMLDocument;
import javax.swing.UIManager;
import javax.swing.JTable;
import javax.swing.JCheckBox;
import javax.swing.SwingUtilities;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.JComponent;
import javax.swing.JPopupMenu;
import javax.swing.JViewport;
import javax.swing.JDialog;
import java.awt.Component;
import java.awt.Color;
import java.awt.Font;
import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;
import java.awt.Cursor;
import java.awt.image.MemoryImageSource;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.GraphicsConfiguration;
import java.awt.Insets;
import java.awt.event.KeyEvent;
import java.awt.event.KeyAdapter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileReader;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URI;
import java.net.InetAddress;
import java.lang.reflect.InvocationTargetException;
import java.net.URLClassLoader;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
/**
* This class provides tools, that are not classified.
*
* @author Rasto Levrinc
* @version $Id$
*
*/
public final class Tools {
/** Singleton. */
private static Tools instance = null;
/** Release version. */
private static String release = null;
/** Debug level. */
private static int debugLevel = -1;
/** Whether the warnings should be shown. */
private static boolean appWarning;
/** Whether application errors should show a dialog. */
private static boolean appError;
/** Map with all warnings, so that they don't appear more than once. */
private static Set<String> appWarningHash = new HashSet<String>();
/** Map with all errors, so that they don't appear more than once. */
private static Set<String> appErrorHash = new HashSet<String>();
/** Image icon cache. */
private static Map<String, ImageIcon> imageIcons =
new HashMap<String, ImageIcon>();
/** Locales. */
private static String localeLang = ""; //TODO: not needed?
/** Locales. */
private static String localeCountry = ""; //TODO: not needed?
/** Resource bundle. */
private static ResourceBundle resource = null;
/** Application defaults bundle. */
private static ResourceBundle resourceAppDefaults = null;
/** Config data object. */
private static ConfigData configData;
/** Gui data object. */
private static GUIData guiData;
/** Drbd gui xml object. */
private static DrbdGuiXML drbdGuiXML = new DrbdGuiXML();
/** String that starts error messages. */
private static final String ERROR_STRING = "ERROR: ";
/** String that starts info messages. */
private static final String INFO_STRING = "INFO: ";
/** String that starts debug messages. */
private static final String DEBUG_STRING = "DEBUG: ";
/** string that starts application warnings. */
private static final String APPWARNING_STRING = "APPWARNING: ";
/** String that starts application errors. */
private static final String APPERROR_STRING = "APPERROR: ";
/** Default dialog panel width. */
private static final int DIALOG_PANEL_WIDTH = 400;
/** Default dialog panel height. */
private static final int DIALOG_PANEL_HEIGHT = 300;
/** Default dialog panel size. */
private static final Dimension DIALOG_PANEL_SIZE = new Dimension(
DIALOG_PANEL_WIDTH,
DIALOG_PANEL_HEIGHT);
/** Previous index in the scrolling menu. */
private static volatile int prevScrollingMenuIndex = -1;
/** Text/html mime type. */
public static final String MIME_TYPE_TEXT_HTML = "text/html";
/** Text/plain mime type. */
public static final String MIME_TYPE_TEXT_PLAIN = "text/plain";
/** Pattern that matches a number and unit. */
private static final Pattern UNIT_PATTERN = Pattern.compile("(\\d*)(\\D*)");
/** Random number generator. */
private static final Random RANDOM = new Random();
/** Hash mit classes from plugin. */
private static final Map<String, RemotePlugin> PLUGIN_OBJECTS =
new HashMap<String, RemotePlugin>();
/** Local plugin directory. */
private static final String PLUGIN_DIR = System.getProperty("user.home")
+ "/.drbd-mc/plugins/";
/** Remote plugin location. */
private static final String PLUGIN_LOCATION =
"oss.linbit.com/drbd-mc/drbd-mc-plugins/";
/** Private constructor. */
private Tools() {
/* no instantiation possible. */
}
/** This is to make this class a singleton. */
public static Tools getInstance() {
synchronized (Tools.class) {
if (instance == null) {
instance = new Tools();
}
}
return instance;
}
/** Inits this class. */
public static void init() {
setDefaults();
configData = new ConfigData();
guiData = new GUIData();
}
/**
* Returns an ImageIcon, or null if the path was invalid.
*
* return image icon object.
*/
public static ImageIcon createImageIcon(final String imageFilename) {
final ImageIcon imageIcon = imageIcons.get(imageFilename);
if (imageIcon != null) {
return imageIcon;
}
final java.net.URL imgURL =
Tools.class.getResource("/images/" + imageFilename);
if (imgURL == null) {
Tools.appWarning("Couldn't find image: " + imageFilename);
return null;
} else {
final ImageIcon newIcon = new ImageIcon(imgURL);
imageIcons.put(imageFilename, newIcon);
return newIcon;
}
}
/** Returns the drbd gui release version. */
public static String getRelease() {
if (release != null) {
return release;
}
final Properties p = new Properties();
try {
p.load(Tools.class.getResourceAsStream("/drbd/release.properties"));
release = p.getProperty("release");
return release;
} catch (IOException e) {
appError("cannot open release file", "", e);
return "unknown";
}
}
/** Prints info message to the stdout. */
public static void info(final String msg) {
System.out.println(INFO_STRING + msg);
}
/** Sets defaults from AppDefaults bundle. */
public static void setDefaults() {
debugLevel = getDefaultInt("DebugLevel");
if (getDefault("AppWarning").equals("y")) {
appWarning = true;
}
if (getDefault("AppError").equals("y")) {
appError = true;
}
localeLang = getDefault("Locale.Lang");
localeCountry = getDefault("Locale.Country");
}
/** Increments the debug level. */
public static void incrementDebugLevel() {
debugLevel++;
info("debug level: " + debugLevel);
}
/** Decrements the debug level. */
public static void decrementDebugLevel() {
debugLevel--;
info("debug level: " + debugLevel);
}
/**
* Sets debug level.
*
* @param level
* debug level usually from 0 to 2. 0 means no debug output.
*/
public static void setDebugLevel(final int level) {
debugLevel = level;
}
/**
* Prints debug message to the stdout.
*
* @param msg
* debug message
*/
private static void debug(final String msg) {
if (debugLevel > 0) {
System.out.println(DEBUG_STRING + msg + " (drbd.utilities.Tools)");
}
}
/**
* Prints debug message to the stdout. Only messages with level smaller
* or equal than debug level will be printed.
*
* @param msg
* debug message
*
* @param level
* level of this message.
*/
private static void debug(final String msg, final int level) {
if (level <= debugLevel) {
System.out.println(DEBUG_STRING
+ "(" + level + ") "
+ msg + " (drbd.utilities.Tools)");
}
}
/**
* Prints debug message to the stdout.
*
* @param object
* object from which this message originated. Use "this" by
* caller for this.
* @param msg
* debug message
*/
public static void debug(final Object object, final String msg) {
if (debugLevel > -1) {
if (object == null) {
System.out.println(DEBUG_STRING + msg);
} else {
System.out.println(DEBUG_STRING + msg
+ " (" + object.getClass().getName() + ")");
}
}
}
/**
* Prints debug message to the stdout. Only messages with level smaller
* or equal than debug level will be printed.
*
* @param object
* object from which this message originated. Use "this" by
* caller for this.
* @param msg
* debug message
* @param level
* level of this message.
*/
public static void debug(final Object object,
final String msg,
final int level) {
if (level <= debugLevel) {
String from = "";
if (object != null) {
from = " (" + object.getClass().getName() + ")";
}
System.out.println(DEBUG_STRING
+ "(" + level + ") "
+ msg
+ from);
}
}
/**
* Shows error message dialog and prints error to the stdout.
*
* @param msg
* error message
*/
public static void error(final String msg) {
System.out.println(ERROR_STRING + getErrorString(msg));
SwingUtilities.invokeLater(new Runnable() {
@Override public void run() {
JOptionPane.showMessageDialog(
guiData.getMainFrame(),
new JScrollPane(new JTextArea(getErrorString(msg),
20,
60)),
Tools.getString("Error.Title"),
JOptionPane.ERROR_MESSAGE);
}
});
}
/** Show an ssh error message. */
public static void sshError(final Host host,
final String command,
final String ans,
final String stacktrace,
final int exitCode) {
final StringBuilder onHost = new StringBuilder("");
if (host != null) {
onHost.append(" on host ");
final Cluster cluster = host.getCluster();
if (cluster != null) {
onHost.append(cluster.getName());
onHost.append(" / ");
}
onHost.append(host.getName());
}
Tools.appWarning(Tools.getString("Tools.sshError.command")
+ " '" + command + "'" + onHost.toString() + "\n"
+ Tools.getString("Tools.sshError.returned")
+ " " + exitCode + "\n"
+ ans + "\n"
+ stacktrace);
}
/**
* Shows confirm dialog with yes and no options and returns true if yes
* button was pressed.
*/
public static boolean confirmDialog(final String title,
final String desc,
final String yesButton,
final String noButton) {
final ConfirmDialog cd = new ConfirmDialog(title,
desc,
yesButton,
noButton);
cd.showDialog();
return cd.isPressedYesButton();
}
/** Executes a command with progress indicator. */
public static SSH.SSHOutput execCommandProgressIndicator(
final Host host,
final String command,
final ExecCallback execCallback,
final boolean outputVisible,
final String text,
final int commandTimeout) {
ExecCallback ec;
final String hostName = host.getName();
Tools.startProgressIndicator(hostName, text);
final StringBuilder output = new StringBuilder("");
final Integer[] exitCodeHolder = new Integer[]{0};
if (execCallback == null) {
final String stacktrace = getStackTrace();
ec = new ExecCallback() {
@Override public void done(final String ans) {
output.append(ans);
}
@Override public void doneError(
final String ans,
final int exitCode) {
Tools.appWarning(ERROR_STRING
+ command
+ " "
+ ans + " rc: "
+ exitCode);
if (outputVisible) {
Tools.sshError(host,
command,
ans,
stacktrace,
exitCode);
}
exitCodeHolder[0] = exitCode;
output.append(ans);
}
};
} else {
ec = execCallback;
}
final Thread commandThread = host.execCommandRaw(command,
ec,
outputVisible,
true,
commandTimeout);
try {
if (commandThread != null) {
commandThread.join(0);
}
} catch (java.lang.InterruptedException e) {
Thread.currentThread().interrupt();
}
Tools.stopProgressIndicator(hostName, text);
return new SSH.SSHOutput(output.toString(), exitCodeHolder[0]);
}
/** Executes a command. */
public static SSH.SSHOutput execCommand(final Host host,
final String command,
final ExecCallback execCallback,
final boolean outputVisible,
final int commandTimeout) {
ExecCallback ec;
final StringBuilder output = new StringBuilder("");
final Integer[] exitCodeHolder = new Integer[]{0};
if (execCallback == null) {
final String stacktrace = getStackTrace();
ec = new ExecCallback() {
@Override public void done(final String ans) {
output.append(ans);
}
@Override public void doneError(
final String ans,
final int exitCode) {
if (outputVisible) {
Tools.sshError(host,
command,
ans,
stacktrace,
exitCode);
}
exitCodeHolder[0] = exitCode;
output.append(ans);
}
};
} else {
ec = execCallback;
}
final Thread commandThread = host.execCommandRaw(command,
ec,
outputVisible,
true,
commandTimeout);
try {
if (commandThread != null) {
commandThread.join(0);
}
} catch (java.lang.InterruptedException e) {
Thread.currentThread().interrupt();
}
return new SSH.SSHOutput(output.toString(), exitCodeHolder[0]);
}
/**
* Shows application warning message dialog if application warning messages
* are enabled.
*
* @param msg
* warning message
*/
public static void appWarning(final String msg) {
if (!appWarningHash.contains(msg)) {
appWarningHash.add(msg);
if (appWarning) {
System.out.println(APPWARNING_STRING + msg);
} else {
debug(APPWARNING_STRING + msg, 2);
}
}
}
/** Warning with exception error message. */
public static void appWarning(final String msg, final Exception e) {
if (!appWarningHash.contains(msg)) {
appWarningHash.add(msg);
if (appWarning) {
System.out.println(APPWARNING_STRING + msg + ": "
+ e.getMessage());
} else {
debug(APPWARNING_STRING + msg, 2);
}
}
}
/**
* Shows application error message dialog if application error messages
* are enabled.
*
* @param msg
* error message
*/
public static void appError(final String msg) {
appError(msg, "", null);
}
/**
* Shows application error message dialog if application error messages
* are enabled.
*
* @param msg
* error message
* @param msg2
* second error message in a new line.
*/
public static void appError(final String msg, final String msg2) {
appError(msg, msg2, null);
}
/** Shows application error message dialog, with a stacktrace. */
public static void appError(final String msg, final Exception e) {
appError(msg, "", e);
}
/**
* Shows application error message dialog with stack trace if
* application error messages are enabled.
*
* @param msg
* error message
* @param msg2
* second error message in a new line.
*
* @param e
* Exception object.
*/
public static void appError(final String msg,
final String msg2,
final Exception e) {
if (appErrorHash.contains(msg + msg2)) {
return;
}
appErrorHash.add(msg + msg2);
final StringBuilder errorString = new StringBuilder(300);
errorString.append(getErrorString("AppError.Text"));
errorString.append("\nrelease: ");
errorString.append(getRelease());
errorString.append("\njava: ");
errorString.append(System.getProperty("java.vendor"));
errorString.append(' ');
errorString.append(System.getProperty("java.version"));
errorString.append("\n\n");
errorString.append(getErrorString(msg));
errorString.append('\n');
errorString.append(msg2);
if (e != null) {
errorString.append('\n');
errorString.append(e.getMessage());
final StackTraceElement[] st = e.getStackTrace();
for (int i = 0; i < st.length; i++) {
errorString.append('\n');
errorString.append(e.getStackTrace()[i].toString());
}
}
if (e == null) {
/* stack trace */
final Throwable th = new Throwable();
final StringWriter sw = new StringWriter();
final PrintWriter pw = new PrintWriter(sw);
th.printStackTrace(pw);
pw.close();
errorString.append('\n');
errorString.append(sw.toString());
}
System.out.println(APPERROR_STRING + errorString);
if (!appError) {
return;
}
final JEditorPane errorPane = new JEditorPane(MIME_TYPE_TEXT_PLAIN,
errorString.toString());
errorPane.setEditable(false);
errorPane.setMinimumSize(DIALOG_PANEL_SIZE);
errorPane.setMaximumSize(DIALOG_PANEL_SIZE);
errorPane.setPreferredSize(DIALOG_PANEL_SIZE);
SwingUtilities.invokeLater(new Runnable() {
@Override public void run() {
JOptionPane.showMessageDialog(guiData.getMainFrame(),
new JScrollPane(errorPane),
getErrorString("AppError.Title"),
JOptionPane.ERROR_MESSAGE);
}
});
}
/** Dialog that informs a user about something with ok button. */
public static void infoDialog(final String title,
final String info1,
final String info2) {
final JEditorPane infoPane = new JEditorPane(MIME_TYPE_TEXT_PLAIN,
info1 + "\n" + info2);
infoPane.setEditable(false);
infoPane.setMinimumSize(DIALOG_PANEL_SIZE);
infoPane.setMaximumSize(DIALOG_PANEL_SIZE);
infoPane.setPreferredSize(DIALOG_PANEL_SIZE);
SwingUtilities.invokeLater(new Runnable() {
@Override public void run() {
JOptionPane.showMessageDialog(guiData.getMainFrame(),
new JScrollPane(infoPane),
getErrorString(title),
JOptionPane.ERROR_MESSAGE);
}
});
}
/**
* Checks string if it is an ip.
*
* @param ipString
* Ip string to be checked.
*
* @return whether string is ip or not.
*/
public static boolean isIp(final String ipString) {
boolean wasValid = true;
// Inet4Address ip;
Pattern pattern = null;
final String ipPattern =
"([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})";
if ("".equals(ipString)) {
wasValid = false;
} else {
try {
pattern = Pattern.compile(ipPattern);
} catch (PatternSyntaxException exception) {
return true;
}
final Matcher myMatcher = pattern.matcher(ipString);
if (myMatcher.matches()) {
for (int i = 1; i < 5; i++) {
if (Integer.parseInt(myMatcher.group(i)) > 255) {
wasValid = false;
break;
}
}
} else {
wasValid = false;
}
}
return wasValid;
}
/** Prints stack trace with text. */
public static void printStackTrace(final String text) {
System.out.println(text);
printStackTrace();
}
/** Prints stack trace. */
public static void printStackTrace() {
System.out.println(getStackTrace());
}
/** Returns stack trace. */
public static String getStackTrace() {
final Throwable th = new Throwable();
final StringWriter sw = new StringWriter();
final PrintWriter pw = new PrintWriter(sw);
th.printStackTrace(pw);
pw.close();
return sw.toString();
}
/**
* Loads the save file and returns its content as string. Return null, if
* nothing was loaded.
*/
public static String loadFile(final String filename,
final boolean showError) {
BufferedReader in = null;
final StringBuilder content = new StringBuilder("");
//Tools.startProgressIndicator(Tools.getString("Tools.Loading"));
try {
in = new BufferedReader(new FileReader(filename));
String line = "";
while ((line = in.readLine()) != null) {
content.append(line);
}
} catch (Exception ex) {
if (showError) {
infoDialog("Load Error",
"The file " + filename + " failed to load",
ex.getMessage());
}
return null;
}
if (in != null) {
try {
in.close();
} catch (IOException ex) {
Tools.appError("Could not close: " + filename, ex);
}
}
return content.toString();
}
/** Loads config data from the specified file. */
public static void loadConfigData(final String filename) {
debug("load", 0);
final String xml = loadFile(filename, true);
if (xml == null) {
return;
}
drbdGuiXML.startClusters(null);
Tools.getGUIData().allHostsUpdate();
}
/**
* Starts the specified clusters and connects to the hosts of these
* clusters.
*/
public static void startClusters(final List<Cluster> selectedClusters) {
drbdGuiXML.startClusters(selectedClusters);
}
/** Stops the specified clusters in the gui. */
public static void stopClusters(final List<Cluster> selectedClusters) {
for (final Cluster cluster : selectedClusters) {
cluster.removeCluster();
for (final Host host : cluster.getHosts()) {
// TODO: can be run concurrently.
host.disconnect();
}
getGUIData().getClustersPanel().removeTab(cluster);
}
}
/** Removes the specified clusters from the gui. */
public static void removeClusters(final List<Cluster> selectedClusters) {
for (final Cluster cluster : selectedClusters) {
getConfigData().removeClusterFromClusters(cluster);
for (final Host host : cluster.getHosts()) {
host.setCluster(null);
}
}
}
/** Returns cluster names from the parsed save file. */
public static void loadXML(final String xml) {
drbdGuiXML.loadXML(xml);
}
/** Removes all the hosts and clusters from all the panels and data. */
public static void removeEverything() {
Tools.startProgressIndicator("Removing Everything");
Tools.getConfigData().disconnectAllHosts();
getGUIData().getClustersPanel().removeAllTabs();
Tools.stopProgressIndicator("Removing Everything");
}
/**
* Saves config data.
*
* @param filename
* filename where are the data stored.
*/
public static void save(final String filename) {
debug("save");
final String text =
Tools.getString("Tools.Saving").replaceAll("@FILENAME@", filename);
startProgressIndicator(text);
try {
final FileOutputStream fileOut = new FileOutputStream(filename);
drbdGuiXML.saveXML(fileOut);
debug("saved: " + filename, 0);
} catch (IOException e) {
appError("error saving: " + filename, "", e);
} finally {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
final Clusters clusters = Tools.getConfigData().getClusters();
if (clusters != null) {
for (final Cluster cluster : clusters.getClusterSet()) {
final ClusterBrowser cb = cluster.getBrowser();
if (cb != null) {
cb.saveGraphPositions();
}
}
}
stopProgressIndicator(text);
}
}
/**
* Gets config data object.
*
* @return config data object.
*/
public static ConfigData getConfigData() {
return configData;
}
/**
* Gets gui data object.
*
* @return gui data object.
*/
public static GUIData getGUIData() {
return guiData;
}
/**
* Returns default value for option from AppDefaults resource bundle.
*
* @param option
* String that holds option.
*
* @return string with default value.
*/
public static String getDefault(final String option) {
synchronized (Tools.class) {
if (resourceAppDefaults == null) {
resourceAppDefaults =
ResourceBundle.getBundle("drbd.configs.AppDefaults");
}
}
try {
return resourceAppDefaults.getString(option);
} catch (Exception e) {
appError("unresolved config resource", option, e);
return option;
}
}
/**
* Returns default color for option from AppDefaults resource bundle.
*
* @param option
* String that holds option.
*
* @return default color.
*/
public static Color getDefaultColor(final String option) {
synchronized (Tools.class) {
if (resourceAppDefaults == null) {
resourceAppDefaults =
ResourceBundle.getBundle("drbd.configs.AppDefaults");
}
}
try {
return (Color) resourceAppDefaults.getObject(option);
} catch (Exception e) {
appError("unresolved config resource", option, e);
return Color.WHITE;
}
}
/**
* Returns default value for integer option from AppDefaults resource
* bundle.
*
* @param option
* String that holds option.
*
* @return integer with default value.
*/
public static int getDefaultInt(final String option) {
synchronized (Tools.class) {
if (resourceAppDefaults == null) {
resourceAppDefaults =
ResourceBundle.getBundle("drbd.configs.AppDefaults");
}
}
try {
return (Integer) resourceAppDefaults.getObject(option);
} catch (Exception e) {
appError("AppError.getInt.Exception",
option + ": " + getDefault(option),
e);
return 0;
}
/*
try {
return Integer.parseInt(getDefault(option));
} catch (Exception e) {
appError("AppError.getInt.Exception",
option + ": " + getDefault(option),
e);
return 0;
}
*/
}
/**
* Returns localized string from TextResource resource bundle.
*
* @param text
* String that holds text.
*
* @return localized string.
*/
public static String getString(final String text) {
synchronized (Tools.class) {
if (resource == null) {
/* set locale */
final Locale currentLocale = Locale.getDefault();
resource =
ResourceBundle.getBundle("drbd.configs.TextResource",
currentLocale);
}
}
try {
return resource.getString(text);
} catch (Exception e) {
appError("unresolved resource: " + text);
return text;
}
}
/**
* Returns converted error string. TODO: at the moment there is no
* conversion.
* TODO: ?
*/
public static String getErrorString(final String text) {
return text;
}
/** Returns string that is specific to a distribution and version. */
public static String getDistString(final String text,
String dist,
String version,
final String arch) {
if (dist == null) {
dist = "";
}
if (version == null) {
version = "";
}
final Locale locale = new Locale(dist, version);
debug("getDistString text: "
+ text
+ " dist: "
+ dist
+ " version: "
+ version, 2);
final ResourceBundle resourceString =
ResourceBundle.getBundle("drbd.configs.DistResource", locale);
String ret;
try {
ret = resourceString.getString(text + "." + arch);
} catch (Exception e) {
ret = null;
}
if (ret == null) {
try {
if (ret == null) {
ret = resourceString.getString(text);
}
debug("ret: " + ret, 2);
return ret;
} catch (Exception e) {
return null;
}
}
return ret;
}
/**
* Returns command from DistResource resource bundle for specific
* distribution and version.
*
* @param text
* text that should be found.
* @param dist
* distribution
* @param version
* version of this distribution.
*
* @return command.
*/
public static String getDistCommand(
final String text,
final String dist,
final String version,
final String arch,
final ConvertCmdCallback convertCmdCallback,
final boolean inBash) {
if (text == null) {
return null;
}
final String[] texts = text.split(";;;");
final List<String> results = new ArrayList<String>();
int i = 0;
for (final String t : texts) {
String distString = getDistString(t, dist, version, arch);
if (distString == null) {
Tools.appWarning("unknown command: " + t);
distString = t;
}
if (inBash && i == 0) {
results.add(DistResource.SUDO + "bash -c \""
+ Tools.escapeQuotes(distString, 1)
+ "\"");
} else {
results.add(distString);
}
i++;
}
String ret;
if (results.isEmpty()) {
ret = text;
} else {
ret = Tools.join(";;;",
results.toArray(new String[results.size()]));
}
if (convertCmdCallback != null && ret != null) {
ret = convertCmdCallback.convert(ret);
}
return ret;
}
/**
* Returns service definiton from ServiceDefinitions resource bundle.
*
* @param service
* service name.
*
* @return service definition as array of strings.
*/
public static String[] getServiceDefinition(final String service) {
final ResourceBundle resourceSD =
ResourceBundle.getBundle("drbd.configs.ServiceDefinitions");
try {
return resourceSD.getStringArray(service);
} catch (Exception e) {
Tools.appWarning("cannot get service definition for service: "
+ service, e);
return new String[]{};
}
}
/**
* Converts kernelVersion as parsed from uname to a version that is used
* in the download area on the website.
*/
public static String getKernelDownloadDir(final String kernelVersion,
final String dist,
final String version,
final String arch) {
final String regexp = getDistString("kerneldir", dist, version, arch);
if (regexp != null && kernelVersion != null) {
final Pattern p = Pattern.compile(regexp);
final Matcher m = p.matcher(kernelVersion);
if (m.matches()) {
return m.group(1);
}
}
return null;
}
/**
* Gets compact representation of distribution and version. Distribution
* and version are joined with "_" and all spaces and '.' are replaced by
* "_" as well.
*
* @param dist
* distribution
* @param version
* version of this distribution
* @return string that represents distribution and version.
*/
public static String getDistVersionString(String dist,
final String version) {
if (dist == null) {
dist = "";
}
debug("dist: " + dist + ", version: " + version, 2);
final Locale locale = new Locale(dist, "");
final ResourceBundle resourceCommand =
ResourceBundle.getBundle("drbd.configs.DistResource", locale);
String distVersion = null;
try {
distVersion = resourceCommand.getString("version:" + version);
} catch (Exception e) {
/* with wildcard */
final StringBuilder buf = new StringBuilder(version);
for (int i = version.length() - 1; i >= 0; i--) {
try {
distVersion = resourceCommand.getString("version:"
+ buf.toString()
+ "*");
} catch (Exception e2) {
distVersion = null;
}
if (distVersion != null) {
break;
}
buf.setLength(i);
}
if (distVersion == null) {
distVersion = version;
}
}
debug("dist version: " + distVersion, 2);
return distVersion;
}
/**
* Joins String array into one string with specified delimiter.
*
* @param delim
* delimiter
* @param strings
* array of strings
*
* @return
* joined string from array
*/
public static String join(final String delim, final String[] strings) {
if (strings == null || strings.length == 0) {
return "";
}
if (strings.length == 1 && strings[0] == null) {
return "";
}
final StringBuilder ret = new StringBuilder("");
for (int i = 0; i < strings.length - 1; i++) {
ret.append(strings[i]);
if (delim != null) {
ret.append(delim);
}
}
ret.append(strings[strings.length - 1]);
return ret.toString();
}
/** Joins String list into one string with specified delimiter. */
public static String join(final String delim,
final Collection<String> strings) {
if (strings == null) {
return "";
}
return join(delim, strings.toArray(new String[strings.size()]));
}
/**
* Joins String array into one string with specified delimiter.
*
* @param delim
* delimiter
* @param strings
* array of strings
* @param length
* length of the string array
*
* @return
* joined string from array
*/
public static String join(final String delim,
final String[] strings,
final int length) {
if (strings == null || strings.length == 0 || length <= 0) {
return "";
}
final StringBuilder ret = new StringBuilder("");
int i;
for (i = 0; i < length - 1 && i < strings.length - 1; i++) {
ret.append(strings[i]);
if (delim != null) {
ret.append(delim);
}
}
i++;
ret.append(strings[i - 1]);
return ret.toString();
}
/** Uppercases the first character. */
public static String ucfirst(final String s) {
if (s == null || s.length() == 0) {
return s;
}
final String f = s.substring(0, 1);
return s.replaceFirst(".", f.toUpperCase(Locale.US));
}
/**
* Converts enumeration to the string array.
*
* @param e
* enumeration
* @return string array
*/
public static String[] enumToStringArray(final Enumeration<String> e) {
if (e == null) {
return null;
}
final List<String> list = new ArrayList<String>();
while (e.hasMoreElements()) {
list.add(e.nextElement());
}
return list.toArray(new String[list.size()]);
}
/**
* returns intersection of two string lists as List of string.
*
* @param setA
* set A
* @param setB
* set B
* @return
* intersection of set A and B.
*/
public static Set<String> getIntersection(final Set<String> setA,
final Set<String> setB) {
final Set<String> resultSet = new TreeSet<String>();
if (setB == null) {
return setA;
}
if (setA == null) {
return setB;
}
for (final String item : setA) {
if (setB.contains(item)) {
resultSet.add(item);
}
}
return resultSet;
}
/**
* Convert text to html.
*
* @param text
* text to convert
*
* @return html
*/
public static String html(final String text) {
if (text == null) {
return "<html>\n</html>";
}
return "<html><p>" + text.replaceAll("\n", "<br>") + "\n</html>";
}
/**
* Checks if object is of the string class. Returns true if object is null.
*
* @param o
* object to be checked
* @return true if object is of string class
*/
public static boolean isStringClass(final Object o) {
if (o == null || o instanceof String) {
return true;
}
return false;
}
/** Returns thrue if object is in StringInfo class. */
public static boolean isStringInfoClass(final Object o) {
if (o != null
&& o.getClass().getName().equals("drbd.gui.resources.StringInfo")) {
return true;
}
return false;
}
/** Escapes for config file. */
public static String escapeConfig(final String value) {
if (value == null) {
return null;
}
if (value.indexOf(' ') > -1 || value.indexOf('"') > -1) {
return "\"" + value.replaceAll("\"", "\\\\\"") + "\"";
}
return value;
}
/** Starts progress indicator with specified text. */
public static void startProgressIndicator(final String text) {
final boolean rightMovement = RANDOM.nextBoolean();
getGUIData().getMainGlassPane().start(text, null, rightMovement);
}
/** Starts progress indicator for host or cluster command. */
public static void startProgressIndicator(final String name,
final String text) {
startProgressIndicator(name + ": " + text);
}
/** Stops progress indicator with specified text. */
public static void stopProgressIndicator(final String text) {
getGUIData().getMainGlassPane().stop(text);
}
/** Stops progress indicator for host or cluster command. */
public static void stopProgressIndicator(final String name,
final String text) {
stopProgressIndicator(name + ": " + text);
}
/** Progress indicator with failure message. */
public static void progressIndicatorFailed(final String text) {
getGUIData().getMainGlassPane().failure(text);
}
/** Progress indicator with failure message for host or cluster command. */
public static void progressIndicatorFailed(final String name,
final String text) {
progressIndicatorFailed(name + ": " + text);
}
/** Progress indicator with failure message that shows for n seconds. */
public static void progressIndicatorFailed(final String text, final int n) {
getGUIData().getMainGlassPane().failure(text, n);
}
/**
* Progress indicator with failure message for host or cluster command,
* that shows for n seconds.
*/
public static void progressIndicatorFailed(final String name,
final String text,
final int n) {
progressIndicatorFailed(name + ": " + text, n);
}
/** Sets fixed size for component. */
public static void setSize(final Component c,
final int width,
final int height) {
final Dimension d = new Dimension(width, height);
c.setMaximumSize(d);
c.setMinimumSize(d);
c.setPreferredSize(d);
}
/**
* Returns -1 if version1 is smaller that version2, 0 if version1 equals
* version2 and 1 if version1 is bigger than version2.
* @Throws Exceptions.IllegalVersionException
*/
public static int compareVersions(final String version1,
final String version2)
throws Exceptions.IllegalVersionException {
if (version1 == null || version2 == null) {
throw new Exceptions.IllegalVersionException(version1, version2);
}
final Pattern p = Pattern.compile("(.*\\d+)rc(\\d+)$");
final Matcher m1 = p.matcher(version1);
String version1a;
int rc1 = Integer.MAX_VALUE;
if (m1.matches()) {
version1a = m1.group(1);
try {
rc1 = Integer.parseInt(m1.group(2));
} catch (java.lang.NumberFormatException e) {
e.printStackTrace();
}
} else {
version1a = version1;
}
final Matcher m2 = p.matcher(version2);
String version2a;
int rc2 = Integer.MAX_VALUE;
if (m2.matches()) {
version2a = m2.group(1);
try {
rc2 = Integer.parseInt(m2.group(2));
} catch (java.lang.NumberFormatException e) {
e.printStackTrace();
}
} else {
version2a = version2;
}
final String[] v1a = version1a.split("\\.");
final String[] v2a = version2a.split("\\.");
if (v1a.length < 1 || v2a.length < 1) {
throw new Exceptions.IllegalVersionException(version1, version2);
}
int i = 0;
while (true) {
if (i >= v1a.length && i >= v2a.length) {
break;
} else if (i >= v1a.length || i >= v2a.length) {
return 0;
}
int v1i = 0;
if (i < v1a.length) {
final String v1 = v1a[i];
try {
v1i = Integer.parseInt(v1);
} catch (java.lang.NumberFormatException e) {
throw new Exceptions.IllegalVersionException(version1);
}
}
int v2i = 0;
if (i < v2a.length) {
final String v2 = v2a[i];
try {
v2i = Integer.parseInt(v2);
} catch (java.lang.NumberFormatException e) {
throw new Exceptions.IllegalVersionException(version2);
}
}
if (v1i < v2i) {
return -1;
} else if (v1i > v2i) {
return 1;
}
i++;
}
if (rc1 < rc2) {
return -1;
} else if (rc1 > rc2) {
return 1;
}
return 0;
}
/** Returns number of characters 'c' in a string 's'. */
public static int charCount(final String s, final char c) {
if (s == null) {
return 0;
}
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == c) {
count++;
}
}
return count;
}
/**
* Creates config on all hosts with specified name in the specified
* directory.
*
* @param config
* config content as a string
* @param fileName
* file name of the config
* @param dir
* directory where the config should be stored
* @param mode
* mode, e.g. "0700"
* @param makeBackup
* whether to make backup or not
*/
public static void createConfigOnAllHosts(final Host[] hosts,
final String config,
final String fileName,
final String dir,
final String mode,
final boolean makeBackup) {
for (Host host : hosts) {
host.getSSH().createConfig(config,
fileName,
dir,
mode,
makeBackup,
null,
null);
}
}
/** Returns border with title. */
public static TitledBorder getBorder(final String text) {
final TitledBorder titledBorder = new TitledBorder(
BorderFactory.createLineBorder(Color.BLACK, 1), text);
titledBorder.setTitleJustification(TitledBorder.LEFT);
return titledBorder;
}
/** Returns a popup in a scrolling pane. */
public static boolean getScrollingMenu(
final String name,
final MyMenu menu,
final MyListModel dlm,
final MyList list,
final Info infoObject,
final List<JDialog> popups,
final Map<MyMenuItem, ButtonCallback> callbackHash) {
final int maxSize = dlm.getSize();
if (maxSize <= 0) {
return false;
}
prevScrollingMenuIndex = -1;
list.setFixedCellHeight(25);
if (maxSize > 20) {
list.setVisibleRowCount(20);
} else {
list.setVisibleRowCount(maxSize);
}
final JScrollPane sp = new JScrollPane(list);
sp.setViewportBorder(null);
sp.setBorder(null);
final JTextField typeToSearchField = dlm.getFilterField();
final JDialog popup = new JDialog(new JFrame(), name, false);
final JPanel popupPanel = new JPanel();
popupPanel.setLayout(new BoxLayout(popupPanel, BoxLayout.PAGE_AXIS));
popupPanel.add(typeToSearchField);
popupPanel.add(sp);
popup.setContentPane(popupPanel);
- popup.pack();
popups.add(popup);
list.addMouseListener(new MouseAdapter() {
@Override public void mouseExited(final MouseEvent evt) {
prevScrollingMenuIndex = -1;
if (callbackHash != null) {
for (final MyMenuItem item : callbackHash.keySet()) {
callbackHash.get(item).mouseOut();
list.clearSelection();
}
}
}
@Override public void mouseEntered(final MouseEvent evt) {
/* request focus here causes the applet making all
textfields to be not editable. */
list.requestFocus();
}
@Override public void mousePressed(final MouseEvent evt) {
prevScrollingMenuIndex = -1;
if (callbackHash != null) {
for (final MyMenuItem item : callbackHash.keySet()) {
callbackHash.get(item).mouseOut();
}
}
final Thread thread = new Thread(new Runnable() {
@Override public void run() {
final int index = list.locationToIndex(evt.getPoint());
SwingUtilities.invokeLater(new Runnable() {
@Override public void run() {
list.setSelectedIndex(index);
//TODO: some submenus stay visible, during
//ptest, but this breaks group popup menu
//setMenuVisible(menu, false);
menu.setSelected(false);
}
});
final MyMenuItem item =
(MyMenuItem) dlm.getElementAt(index);
item.action();
}
});
thread.start();
}
});
list.addMouseMotionListener(new MouseMotionAdapter() {
@Override public void mouseMoved(final MouseEvent evt) {
final Thread thread = new Thread(new Runnable() {
@Override public void run() {
int pIndex = list.locationToIndex(evt.getPoint());
if (!list.getCellBounds(pIndex, pIndex).contains(
evt.getPoint())) {
pIndex = -1;
}
final int index = pIndex;
final int lastIndex = prevScrollingMenuIndex;
if (index == lastIndex) {
return;
}
prevScrollingMenuIndex = index;
SwingUtilities.invokeLater(new Runnable() {
@Override public void run() {
list.setSelectedIndex(index);
}
});
if (callbackHash != null) {
if (lastIndex >= 0) {
final MyMenuItem lastItem =
(MyMenuItem) dlm.getElementAt(lastIndex);
callbackHash.get(lastItem).mouseOut();
}
if (index >= 0) {
final MyMenuItem item =
(MyMenuItem) dlm.getElementAt(index);
callbackHash.get(item).mouseOver();
}
}
}
});
thread.start();
}
});
list.addKeyListener(new KeyAdapter() {
@Override public void keyTyped(final KeyEvent e) {
final char ch = e.getKeyChar();
if (ch == 27) { /* escape */
for (final JDialog otherP : popups) {
otherP.dispose();
}
infoObject.hidePopup();
} else if (ch == ' ' || ch == '\n') {
final MyMenuItem item =
(MyMenuItem) list.getSelectedValue();
//SwingUtilities.invokeLater(new Runnable() {
// @Override public void run() {
// //menu.setPopupMenuVisible(false);
// setMenuVisible(menu, false);
// }
//});
if (item != null) {
item.action();
}
} else {
if (Character.isLetterOrDigit(ch)) {
final Thread t = new Thread(new Runnable() {
@Override public void run() {
getGUIData().getMainGlassPane().start("" + ch,
null,
true);
stopProgressIndicator("" + ch);
}
});
t.start();
}
}
}
});
menu.addMenuListener(new MenuListener() {
public void menuCanceled(final MenuEvent e) {
SwingUtilities.invokeLater(new Runnable() {
@Override public void run() {
for (final JDialog otherP : popups) {
otherP.dispose();
}
}
});
}
public void menuDeselected(final MenuEvent e) {
SwingUtilities.invokeLater(new Runnable() {
@Override public void run() {
for (final JDialog otherP : popups) {
if (popup != otherP) {
otherP.dispose();
}
}
}
});
}
public void menuSelected(final MenuEvent e) {
final Point l = menu.getLocationOnScreen();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
for (final JDialog otherP : popups) {
otherP.dispose();
}
popup.setLocation(
(int) (l.getX() + menu.getBounds().getWidth()),
- (int) l.getY());
+ (int) l.getY() - 1);
+ popup.pack();
popup.setVisible(true);
}
});
SwingUtilities.invokeLater(new Runnable() {
@Override public void run() {
+ /* Setting location again. Moving it one pixel fixes
+ the "gray window" problem. */
popup.setLocation(
(int) (l.getX() + menu.getBounds().getWidth()),
(int) l.getY());
}
});
}
});
return true;
}
/** Returns whether the computer, where this program is run, is Linux. */
public static boolean isLinux() {
return "Linux".equals(System.getProperty("os.name"));
}
/** Returns whether the computer, where this program is run, is Windows. */
public static boolean isWindows() {
return System.getProperty("os.name").indexOf("Windows") == 0;
}
/** Sets the html font of the editor pane to be the default font. */
public static void setEditorFont(final JEditorPane ep) {
final Font font = UIManager.getFont("Label.font");
final String bodyRule = "body { font-family: " + font.getFamily()
+ "; "
+ "font-size: " + font.getSize() + "pt; }";
((HTMLDocument) ep.getDocument()).getStyleSheet().addRule(bodyRule);
}
/** Reads and returns a content of a text file. */
public static String getFile(final String fileName) {
if (fileName == null) {
return null;
}
final URL url = Tools.class.getResource(fileName);
if (url == null) {
return null;
}
try {
final BufferedReader br =
new BufferedReader(
new InputStreamReader(url.openStream()));
final StringBuilder content = new StringBuilder("");
while (br.ready()) {
content.append(br.readLine());
content.append('\n');
}
return content.toString();
} catch (IOException e) {
Tools.appError("could not read: " + fileName, "", e);
return null;
}
}
/**
* Parses arguments from --auto command line option, it makes some
* automatical gui actions, that help to test the gui and can find some
* other uses later.
* To find out which options are available, you'd have to grep for
* getAutoOptionHost and getAutoOptionCluster
*/
public static void parseAutoArgs(final String line) {
if (line == null) {
return;
}
final String[] args = line.split(",");
String host = null;
String cluster = null;
boolean global = false;
for (final String arg : args) {
final String[] pair = arg.split(":");
if (pair == null || pair.length != 2) {
appWarning("cannot parse: " + line);
return;
}
final String option = pair[0];
final String value = pair[1];
if ("host".equals(option)) {
cluster = null;
host = value;
Tools.getConfigData().addAutoHost(host);
continue;
} else if ("cluster".equals(option)) {
host = null;
cluster = value;
Tools.getConfigData().addAutoCluster(cluster);
continue;
} else if ("global".equals(option)) {
host = null;
cluster = null;
global = true;
continue;
}
if (host != null) {
Tools.getConfigData().addAutoOption(host, option, value);
} else if (cluster != null) {
Tools.getConfigData().addAutoOption(cluster, option, value);
} else if (global) {
Tools.getConfigData().addAutoOption("global", option, value);
} else {
appWarning("cannot parse: " + line);
return;
}
}
}
/** Convenience sleep wrapper. */
public static void sleep(final int ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
/** Convenience sleep wrapper with float argument. */
public static void sleep(final float ms) {
sleep((int) ms);
}
/** Returns the latest version of this application. */
public static String getLatestVersion() {
String version = null;
final Pattern vp = Pattern.compile(
".*<a\\s+href=\"drbd-mc-([0-9.]*?)\\.tar\\..*");
try {
final String url = "http://oss.linbit.com/drbd-mc/?drbd-mc-check-"
+ getRelease();
final BufferedReader reader = new BufferedReader(
new InputStreamReader(new URL(url).openStream()));
String line;
do {
line = reader.readLine();
if (line == null) {
break;
}
final Matcher m = vp.matcher(line);
if (m.matches()) {
final String v = m.group(1);
try {
if (version == null
|| compareVersions(v, version) > 0) {
version = v;
}
} catch (Exceptions.IllegalVersionException e) {
Tools.appWarning(e.getMessage(), e);
}
}
} while (true);
} catch (MalformedURLException mue) {
return null;
} catch (IOException ioe) {
return version;
}
return version;
}
/** Opens default browser. */
public static void openBrowser(final String url) {
try {
java.awt.Desktop.getDesktop().browse(new URI(url));
} catch (java.io.IOException e) {
Tools.appError("wrong uri", e);
} catch (java.net.URISyntaxException e) {
Tools.appError("error opening browser", e);
}
}
/**
* Prepares vnc viewer, gets the port and creates ssh tunnel. Returns true
* if ssh tunnel was created.
*/
private static int prepareVncViewer(final Host host,
final int remotePort) {
if (remotePort < 0 || host == null) {
return -1;
}
if (Tools.isLocalIp(host.getIp())) {
return remotePort;
}
final int localPort = remotePort + getConfigData().getVncPortOffset();
debug("start port forwarding " + remotePort + " -> " + localPort);
try {
host.getSSH().startVncPortForwarding(host.getIp(), remotePort);
} catch (final java.io.IOException e) {
Tools.appError("unable to create tunnel", e);
return -1;
}
return localPort;
}
/** Cleans up after vnc viewer. It stops ssh tunnel. */
private static void cleanupVncViewer(final Host host,
final int localPort) {
if (Tools.isLocalIp(host.getIp())) {
return;
}
final int remotePort = localPort - getConfigData().getVncPortOffset();
debug("stop port forwarding " + remotePort);
try {
host.getSSH().stopVncPortForwarding(remotePort);
} catch (final java.io.IOException e) {
Tools.appError("unable to close tunnel", e);
}
}
/** Starts Tight VNC viewer. */
public static void startTightVncViewer(final Host host,
final int remotePort) {
final int localPort = prepareVncViewer(host, remotePort);
if (localPort < 0) {
return;
}
final tightvnc.VncViewer v = new tightvnc.VncViewer(
new String[]{"HOST",
"127.0.0.1",
"PORT",
Integer.toString(localPort)},
false,
true);
v.init();
v.start();
v.join();
cleanupVncViewer(host, localPort);
}
/** Starts Ultra VNC viewer. */
public static void startUltraVncViewer(final Host host,
final int remotePort) {
final int localPort = prepareVncViewer(host, remotePort);
if (localPort < 0) {
return;
}
final JavaViewer.VncViewer v = new JavaViewer.VncViewer(
new String[]{"HOST",
"127.0.0.1",
"PORT",
Integer.toString(localPort)},
false,
true);
v.init();
v.start();
v.join();
cleanupVncViewer(host, localPort);
}
/** Starts Real VNC viewer. */
public static void startRealVncViewer(final Host host,
final int remotePort) {
final int localPort = prepareVncViewer(host, remotePort);
if (localPort < 0) {
return;
}
final vncviewer.VNCViewer v = new vncviewer.VNCViewer(
new String[]{"127.0.0.1:"
+ (Integer.toString(localPort - 5900))});
v.start();
v.join();
cleanupVncViewer(host, localPort);
}
/** Hides mouse pointer. */
public static void hideMousePointer(final Component c) {
final int[] pixels = new int[16 * 16];
final Image image = Toolkit.getDefaultToolkit().createImage(
new MemoryImageSource(16, 16, pixels, 0, 16));
final Cursor transparentCursor =
Toolkit.getDefaultToolkit().createCustomCursor(image,
new Point(0, 0),
"invisibleCursor");
c.setCursor(transparentCursor);
}
/** Check whether the string is number. */
public static boolean isNumber(final String s) {
try {
Long.parseLong(s);
return true;
} catch (final NumberFormatException nfe) {
return false;
}
}
/** Returns list that is expandable by shell. {'a','b'...} */
public static String shellList(final String[] items) {
final StringBuilder list = new StringBuilder("");
if (items == null || items.length == 0) {
return null;
} else if (items.length == 1) {
list.append(items[0]);
} else {
list.append('{');
for (int i = 0; i < items.length - 1; i++) {
list.append('\'');
list.append(items[i]);
list.append("',");
}
if (items.length != 0) {
list.append('\'');
list.append(items[items.length - 1]);
list.append('\'');
}
list.append('}');
}
return list.toString();
}
/**
* Returns whether two objects are equal. Special handling for Units and
* StringInfo objects.
*/
public static boolean areEqual(final Object o1, final Object o2) {
if (o1 == null && o2 == null) {
return true;
} else if (o1 != null && o1 instanceof DrbdResourceInfo) {
/* this is special case, because this object represents devices in
* filesystem ra and also after field in drbd.conf. */
final String device = ((DrbdResourceInfo) o1).getStringValue();
if (device.equals(o2)) {
return true;
}
final String res = ((DrbdResourceInfo) o1).getName();
if (res == null) {
return res == o2;
}
if (res.equals(o2)) {
return true;
}
return false;
} else if (o1 != null && o1 instanceof Info) {
final String s1 = ((Info) o1).getStringValue();
if (s1 == null) {
return o2 == null;
}
if (o2 == null) {
return false;
}
if (o2 instanceof Info) {
return s1.equals(((Info) o2).getStringValue());
} else {
return s1.equals(o2) || o1.toString().equals(o2);
}
} else if (o2 != null && o2 instanceof Info) {
final String s2 = ((Info) o2).getStringValue();
if (s2 == null) {
return o1 == null;
}
if (o1 == null) {
return false;
}
if (o1 instanceof Info) {
return s2.equals(((Info) o1).getStringValue());
} else {
return s2.equals(o1) || o2.toString().equals(o1);
}
} else if (o1 == null && o2 != null) {
return o2.toString().equals("");
} else if (o2 == null && o1 != null) {
return o1.toString().equals("");
} else if (o1 instanceof Object[]
&& o2 instanceof Object[]) {
final Object[] array1 = (Object[]) o1;
final Object[] array2 = (Object[]) o2;
for (int i = 0; i < array1.length; i++) {
if (!areEqual(array1[i], array2[i])) {
return false;
}
}
return true;
} else if (o1 instanceof Unit) {
return ((Unit) o1).equals(o2);
} else if (o2 instanceof Unit) {
return ((Unit) o2).equals(o1);
} else if (o1 instanceof ComboInfo) {
return ((ComboInfo) o1).equals(o2);
} else if (o2 instanceof ComboInfo) {
return ((ComboInfo) o2).equals(o1);
} else {
return o1.equals(o2);
}
}
/**
* Returns value unit pair extracting from string. E.g. "10min" becomes 10
* and "min" pair.
*/
public static Object[] extractUnit(final String time) {
final Object[] o = new Object[]{null, null};
if (time == null) {
return o;
}
final Matcher m = UNIT_PATTERN.matcher(time);
if (m.matches()) {
o[0] = m.group(1);
o[1] = m.group(2);
}
return o;
}
/** Returns random secret of the specified lenght. */
public static String getRandomSecret(final int len) {
final Random rand = new Random();
final ArrayList<Character> charsL = new ArrayList<Character>();
for (int a = 'a'; a <= 'z'; a++) {
charsL.add((char) a);
charsL.add(Character.toUpperCase((char) a));
}
for (int a = '0'; a <= '9'; a++) {
charsL.add((char) a);
}
final Character[] chars = charsL.toArray(new Character[charsL.size()]);
final StringBuilder s = new StringBuilder(len + 1);
for (int i = 0; i < len; i++) {
s.append(chars[rand.nextInt(chars.length)]);
}
return s.toString();
}
/** Returns whether the ip is localhost. */
public static boolean isLocalIp(final String ip) {
if (ip == null
|| "127.0.0.1".equals(ip)
|| "127.0.1.1".equals(ip)) {
return true;
}
try {
final String localIp = InetAddress.getLocalHost().getHostAddress();
return ip.equals(localIp);
} catch (java.net.UnknownHostException e) {
return false;
}
}
/** Converts value in kilobytes. */
public static String convertKilobytes(final String kb) {
if (!isNumber(kb)) {
return kb;
}
final double k = Long.parseLong(kb);
if (k == 0) {
return "0K";
}
if (k / 1024 != (long) (k / 1024)) {
return kb + "K";
}
final double m = k / 1024;
if (m / 1024 != (long) (m / 1024)) {
return Long.toString((long) m) + "M";
}
final double g = m / 1024;
if (g / 1024 != (long) (g / 1024)) {
return Long.toString((long) g) + "G";
}
final double t = g / 1024;
if (t / 1024 != (long) (t / 1024)) {
return Long.toString((long) t) + "T";
}
return Long.toString((long) (t / 1024)) + "P";
}
/** Converts value with unit to kilobites. */
public static long convertToKilobytes(final String value) {
final Object[] v = Tools.extractUnit(value);
if (v.length == 2 && Tools.isNumber((String) v[0])) {
long num = Long.parseLong((String) v[0]);
final String unit = (String) v[1];
if ("P".equalsIgnoreCase(unit)) {
num = num * 1024 * 1024 * 1024 * 1024;
} else if ("T".equalsIgnoreCase(unit)) {
num = num * 1024 * 1024 * 1024;
} else if ("G".equalsIgnoreCase(unit)) {
num = num * 1024 * 1024;
} else if ("M".equalsIgnoreCase(unit)) {
num = num * 1024;
} else if ("K".equalsIgnoreCase(unit)) {
} else {
return -1;
}
return num;
}
return -1;
}
/** Resize table. */
public static void resizeTable(final JTable table,
final Map<Integer, Integer> defaultWidths) {
final int margin = 3;
for (int i = 0; i < table.getColumnCount(); i++) {
final int vColIndex = i;
final DefaultTableColumnModel colModel =
(DefaultTableColumnModel) table.getColumnModel();
final TableColumn col = colModel.getColumn(vColIndex);
int width = 0;
TableCellRenderer renderer = col.getHeaderRenderer();
if (renderer == null) {
renderer = table.getTableHeader().getDefaultRenderer();
}
if (renderer == null) {
continue;
}
Component comp = renderer.getTableCellRendererComponent(
table,
col.getHeaderValue(),
false,
false,
0,
0);
Integer dw = null;
if (defaultWidths != null) {
dw = defaultWidths.get(i);
}
if (dw == null) {
width = comp.getPreferredSize().width;
for (int r = 0; r < table.getRowCount(); r++) {
renderer = table.getCellRenderer(r, vColIndex);
if (renderer == null) {
continue;
}
comp = renderer.getTableCellRendererComponent(
table,
table.getValueAt(r, vColIndex),
false,
false,
r, vColIndex);
width = Math.max(width, comp.getPreferredSize().width);
}
} else {
width = dw;
col.setMaxWidth(width);
}
width += 2 * margin;
col.setPreferredWidth(width);
}
((DefaultTableCellRenderer) table.getTableHeader().getDefaultRenderer())
.setHorizontalAlignment(SwingConstants.CENTER);
}
/** Sets the menu and all its parents visible, not visible. */
public static void setMenuVisible(final JComponent menu,
final boolean visible) {
JComponent parent = (JComponent) menu.getParent();
if (parent instanceof JViewport) {
/* MyList */
parent = (JComponent) parent.getParent();
parent = (JComponent) parent.getParent();
}
if (parent instanceof JPopupMenu) {
JComponent inv = (JComponent) ((JPopupMenu) parent).getInvoker();
while (inv != null) {
final JComponent invP = (JComponent) inv.getParent();
if (!(invP instanceof JPopupMenu)) {
break;
}
invP.setVisible(visible);
for (final java.awt.Component c : invP.getComponents()) {
((JComponent) c).setVisible(visible);
}
final JComponent pp = (JComponent) invP.getParent();
if (pp != null) {
pp.setVisible(visible);
}
inv = (JComponent) ((JPopupMenu) invP).getInvoker();
}
menu.setVisible(visible);
parent.setVisible(visible);
final JComponent pp = (JComponent) parent.getParent();
if (pp != null) {
pp.setVisible(visible);
}
for (final java.awt.Component c : parent.getComponents()) {
((JComponent) c).setVisible(visible);
}
parent.repaint();
}
}
/** Sets the menu and all its parents opaque, not opaque. */
public static void setMenuOpaque(final JComponent menu,
final boolean opaque) {
JComponent parent = (JComponent) menu.getParent();
if (parent instanceof JViewport) {
/* MyList */
parent = (JComponent) parent.getParent();
parent = (JComponent) parent.getParent();
}
if (parent instanceof JPopupMenu) {
JComponent inv = (JComponent) ((JPopupMenu) parent).getInvoker();
while (inv != null) {
final JComponent invP = (JComponent) inv.getParent();
if (!(invP instanceof JPopupMenu)) {
break;
}
invP.setOpaque(opaque);
for (final java.awt.Component c : invP.getComponents()) {
((JComponent) c).setOpaque(opaque);
}
final JComponent pp = (JComponent) invP.getParent();
if (pp != null) {
pp.setOpaque(opaque);
}
inv = (JComponent) ((JPopupMenu) invP).getInvoker();
}
menu.setOpaque(opaque);
parent.setOpaque(opaque);
final JComponent pp = (JComponent) parent.getParent();
if (pp != null) {
pp.setOpaque(opaque);
}
for (final java.awt.Component c : parent.getComponents()) {
((JComponent) c).setOpaque(opaque);
}
parent.repaint();
}
}
/** Converts windows path to unix path. */
public static String getUnixPath(final String dir) {
if (dir == null) {
return null;
}
String unixPath;
if (isWindows()) {
unixPath = dir.replaceAll("\\\\", "/");
if (unixPath.length() >= 2
&& ":".equalsIgnoreCase(unixPath.substring(1, 2))) {
unixPath = unixPath.substring(2);
}
} else {
unixPath = dir;
}
return unixPath;
}
/** Returns bounds of the whole screen. */
public static Rectangle getScreenBounds(final JComponent component) {
final GraphicsConfiguration gc = component.getGraphicsConfiguration();
final Rectangle sBounds = gc.getBounds();
final Insets screenInsets =
Toolkit.getDefaultToolkit().getScreenInsets(gc);
/* Take into account screen insets, decrease viewport */
sBounds.x += screenInsets.left;
sBounds.y += screenInsets.top;
sBounds.width -= (screenInsets.left + screenInsets.right);
sBounds.height -= (screenInsets.top + screenInsets.bottom);
return sBounds;
}
/** Compares two Lists with services if thery are equal. The order does not
* matter. */
public static boolean serviceInfoListEquals(final Set<ServiceInfo> l1,
final Set<ServiceInfo> l2) {
if (l1 == l2) {
return true;
}
if (l1 == null || l2 == null) {
return false;
}
if (l1.size() != l2.size()) {
return false;
}
for (final ServiceInfo s1 : l1) {
if (!l2.contains(s1)) {
return false;
}
}
return true;
}
/** Trims text to have displayable width. */
public static String trimText(final String text) {
final int width = 80;
if (text == null || text.length() <= width) {
return text;
}
final StringBuilder out = new StringBuilder(text.length() + 10);
/* find next space */
String t = text;
while (true) {
final int pos = t.indexOf(' ', width);
if (pos > 0) {
out.append(t.substring(0, pos));
out.append('\n');
t = t.substring(pos + 1);
} else {
break;
}
}
out.append(t);
return out.toString();
}
/** Wait for next swing threads to finish. It's used for synchronization */
public static void waitForSwing() {
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override public void run() {
/* just wait */
}
});
} catch (final InterruptedException ix) {
Thread.currentThread().interrupt();
} catch (final InvocationTargetException x) {
Tools.printStackTrace();
}
}
/** Convenience invoke and wait function. */
public static void invokeAndWait(final Runnable runnable) {
try {
SwingUtilities.invokeAndWait(runnable);
} catch (final InterruptedException ix) {
Thread.currentThread().interrupt();
} catch (final InvocationTargetException x) {
Tools.printStackTrace();
}
}
/** Return directory part (to the /) of the filename. */
public static String getDirectoryPart(final String filename) {
if (filename == null) {
return null;
}
final int i = filename.lastIndexOf('/');
if (i < 0) {
return filename;
}
return filename.substring(0, i + 1);
}
/** Returns list of plugins. */
public static Set<String> getPluginList() {
final Pattern p = Pattern.compile(
".*<img src=\"/icons/folder.gif\" alt=\"\\[DIR\\]\">"
+ "</td><td><a href=\".*?/\">(.*?)/</a>.*");
final Set<String> pluginList = new LinkedHashSet<String>();
try {
final String url = "http://" + PLUGIN_LOCATION
+ "/?drbd-mc-plugin-check-" + getRelease();
final BufferedReader reader = new BufferedReader(
new InputStreamReader(new URL(url).openStream()));
do {
final String line = reader.readLine();
if (line == null) {
break;
}
final Matcher m = p.matcher(line);
if (m.matches()) {
final String pluginName = m.group(1);
final String checkURL = "http://" + PLUGIN_LOCATION
+ pluginName + "/" + getRelease()
+ "/?drbd-mc-plugin-check-" + getRelease();
try {
new URL(checkURL).openStream();
pluginList.add(pluginName);
} catch (MalformedURLException mue) {
Tools.appWarning("malformed URL");
} catch (IOException ioe) {
/* don't show this in the menu */
}
}
} while (true);
} catch (MalformedURLException mue) {
Tools.appWarning("malformed URL");
} catch (IOException ioe) {
}
final File dir = new File(PLUGIN_DIR);
final String[] l = dir.list();
if (dir != null && l != null) {
for (final String fn : l) {
pluginList.add(fn);
}
}
return pluginList;
}
/** Loads one plugin. */
private static Class loadPlugin(final String pluginName,
final String url) {
final String user = getConfigData().getPluginUser();
final String passwd = getConfigData().getPluginPassword();
if (user != null && passwd != null) {
Authenticator.setDefault(new java.net.Authenticator() {
protected PasswordAuthentication
getPasswordAuthentication() {
return new PasswordAuthentication(user,
passwd.toCharArray());
}
});
}
URLClassLoader loader;
final String[] dirs = pluginName.split(":");
try {
loader = new URLClassLoader(new URL[] {
new URL(url + pluginName + "/" + getRelease() + "/")
});
} catch (java.net.MalformedURLException e) {
Tools.appWarning("could not get: " + url, e);
return null;
}
Class c = null;
final String className = "plugins." + dirs[dirs.length - 1];
try {
c = loader.loadClass(className);
} catch (java.lang.ClassNotFoundException e) {
Tools.debug("could not load " + url + " " + className, 1);
return null;
}
return c;
}
/** Saves the class. */
private static void savePluginClass(final String pluginName,
final Class c) {
for (final Class sc : c.getDeclaredClasses()) {
savePluginClass(pluginName, sc);
}
try {
final String className = c.getName();
final String classAsPath = className.replace('.', '/') + ".class";
final String dirToCreate = PLUGIN_DIR
+ pluginName
+ "/"
+ getRelease()
+ "/";
(new File(dirToCreate + "plugins/")).mkdirs();
final FileOutputStream fileOut = new FileOutputStream(
dirToCreate
+ classAsPath);
final InputStream stream =
c.getClassLoader().getResourceAsStream(classAsPath);
final byte[] buff = new byte[512];
while (stream.available() > 0) {
final int l = stream.read(buff);
fileOut.write(buff, 0, l);
}
fileOut.close();
} catch (FileNotFoundException e) {
Tools.appWarning("plugin not found", e);
return;
} catch (IOException e) {
Tools.appWarning("could not save plugin", e);
return;
}
}
/** Load all plugins. */
public static void loadPlugins() {
final Set<String> pluginList = getPluginList();
getGUIData().getMainMenu().reloadPluginsMenu(pluginList);
for (final String pluginName : pluginList) {
Class c = loadPlugin(pluginName, "http://" + PLUGIN_LOCATION);
if (c == null) {
c = loadPlugin(pluginName, "file://" + PLUGIN_DIR);
if (c == null) {
continue;
}
} else {
savePluginClass(pluginName, c);
/* cache it. */
}
final Class pluginClass = c;
RemotePlugin remotePlugin = null;
try {
remotePlugin = (RemotePlugin) pluginClass.newInstance();
} catch (java.lang.InstantiationException e) {
Tools.appWarning("could not instantiate plugin: " + pluginName,
e);
continue;
} catch (java.lang.IllegalAccessException e) {
Tools.appWarning("could not access plugin: " + pluginName, e);
continue;
}
remotePlugin.init();
PLUGIN_OBJECTS.put(pluginName, remotePlugin);
SwingUtilities.invokeLater(new Runnable() {
@Override public void run() {
getGUIData().getMainMenu().enablePluginMenu(
pluginName,
pluginClass != null);
if (pluginClass != null) {
Tools.info(pluginName + " was enabled");
}
}
});
}
}
/** Show plugin description. */
public static void showPluginDescription(final String pluginName) {
final RemotePlugin remotePlugin = PLUGIN_OBJECTS.get(pluginName);
if (remotePlugin != null) {
remotePlugin.showDescription();
}
}
/** Adds menu items from plugins. */
public static void addPluginMenuItems(final Info info,
final List<UpdatableItem> items) {
for (final String pluginName : PLUGIN_OBJECTS.keySet()) {
PLUGIN_OBJECTS.get(pluginName).addPluginMenuItems(info, items);
}
}
/** Escapes the quotes for the stacked ssh commands. */
public static String escapeQuotes(final String s, final int count) {
if (s == null) {
return null;
}
if (count <= 0) {
return s;
}
final StringBuilder sb = new StringBuilder("");
for (int i = 0; i < s.length(); i++) {
final char c = s.charAt(i);
if (c == '\\') {
sb.append("\\\\");
} else if (c == '"' || c == '$' || c == '`') {
sb.append('\\');
sb.append(c);
} else {
sb.append(c);
}
}
return escapeQuotes(sb.toString(), count - 1);
}
/** Returns array of host checkboxes in the specified cluster. */
public static Map<Host, JCheckBox> getHostCheckboxes(
final Cluster cluster) {
final Map<Host, JCheckBox> components =
new LinkedHashMap<Host, JCheckBox>();
for (final Host host : cluster.getHosts()) {
final JCheckBox button = new JCheckBox(host.getName());
button.setBackground(
Tools.getDefaultColor("ConfigDialog.Background.Light"));
components.put(host, button);
}
return components;
}
/**
* Returns true if the hb version on the host is smaller or equal
* Heartbeat 2.1.4.
*/
public static boolean versionBeforePacemaker(final Host host) {
final String hbV = host.getHeartbeatVersion();
final String pcmkV = host.getPacemakerVersion();
try {
return pcmkV == null
&& hbV != null
&& Tools.compareVersions(hbV, "2.99.0") < 0;
} catch (Exceptions.IllegalVersionException e) {
Tools.appWarning(e.getMessage(), e);
return false;
}
}
}
| false | true | public static boolean getScrollingMenu(
final String name,
final MyMenu menu,
final MyListModel dlm,
final MyList list,
final Info infoObject,
final List<JDialog> popups,
final Map<MyMenuItem, ButtonCallback> callbackHash) {
final int maxSize = dlm.getSize();
if (maxSize <= 0) {
return false;
}
prevScrollingMenuIndex = -1;
list.setFixedCellHeight(25);
if (maxSize > 20) {
list.setVisibleRowCount(20);
} else {
list.setVisibleRowCount(maxSize);
}
final JScrollPane sp = new JScrollPane(list);
sp.setViewportBorder(null);
sp.setBorder(null);
final JTextField typeToSearchField = dlm.getFilterField();
final JDialog popup = new JDialog(new JFrame(), name, false);
final JPanel popupPanel = new JPanel();
popupPanel.setLayout(new BoxLayout(popupPanel, BoxLayout.PAGE_AXIS));
popupPanel.add(typeToSearchField);
popupPanel.add(sp);
popup.setContentPane(popupPanel);
popup.pack();
popups.add(popup);
list.addMouseListener(new MouseAdapter() {
@Override public void mouseExited(final MouseEvent evt) {
prevScrollingMenuIndex = -1;
if (callbackHash != null) {
for (final MyMenuItem item : callbackHash.keySet()) {
callbackHash.get(item).mouseOut();
list.clearSelection();
}
}
}
@Override public void mouseEntered(final MouseEvent evt) {
/* request focus here causes the applet making all
textfields to be not editable. */
list.requestFocus();
}
@Override public void mousePressed(final MouseEvent evt) {
prevScrollingMenuIndex = -1;
if (callbackHash != null) {
for (final MyMenuItem item : callbackHash.keySet()) {
callbackHash.get(item).mouseOut();
}
}
final Thread thread = new Thread(new Runnable() {
@Override public void run() {
final int index = list.locationToIndex(evt.getPoint());
SwingUtilities.invokeLater(new Runnable() {
@Override public void run() {
list.setSelectedIndex(index);
//TODO: some submenus stay visible, during
//ptest, but this breaks group popup menu
//setMenuVisible(menu, false);
menu.setSelected(false);
}
});
final MyMenuItem item =
(MyMenuItem) dlm.getElementAt(index);
item.action();
}
});
thread.start();
}
});
list.addMouseMotionListener(new MouseMotionAdapter() {
@Override public void mouseMoved(final MouseEvent evt) {
final Thread thread = new Thread(new Runnable() {
@Override public void run() {
int pIndex = list.locationToIndex(evt.getPoint());
if (!list.getCellBounds(pIndex, pIndex).contains(
evt.getPoint())) {
pIndex = -1;
}
final int index = pIndex;
final int lastIndex = prevScrollingMenuIndex;
if (index == lastIndex) {
return;
}
prevScrollingMenuIndex = index;
SwingUtilities.invokeLater(new Runnable() {
@Override public void run() {
list.setSelectedIndex(index);
}
});
if (callbackHash != null) {
if (lastIndex >= 0) {
final MyMenuItem lastItem =
(MyMenuItem) dlm.getElementAt(lastIndex);
callbackHash.get(lastItem).mouseOut();
}
if (index >= 0) {
final MyMenuItem item =
(MyMenuItem) dlm.getElementAt(index);
callbackHash.get(item).mouseOver();
}
}
}
});
thread.start();
}
});
list.addKeyListener(new KeyAdapter() {
@Override public void keyTyped(final KeyEvent e) {
final char ch = e.getKeyChar();
if (ch == 27) { /* escape */
for (final JDialog otherP : popups) {
otherP.dispose();
}
infoObject.hidePopup();
} else if (ch == ' ' || ch == '\n') {
final MyMenuItem item =
(MyMenuItem) list.getSelectedValue();
//SwingUtilities.invokeLater(new Runnable() {
// @Override public void run() {
// //menu.setPopupMenuVisible(false);
// setMenuVisible(menu, false);
// }
//});
if (item != null) {
item.action();
}
} else {
if (Character.isLetterOrDigit(ch)) {
final Thread t = new Thread(new Runnable() {
@Override public void run() {
getGUIData().getMainGlassPane().start("" + ch,
null,
true);
stopProgressIndicator("" + ch);
}
});
t.start();
}
}
}
});
menu.addMenuListener(new MenuListener() {
public void menuCanceled(final MenuEvent e) {
SwingUtilities.invokeLater(new Runnable() {
@Override public void run() {
for (final JDialog otherP : popups) {
otherP.dispose();
}
}
});
}
public void menuDeselected(final MenuEvent e) {
SwingUtilities.invokeLater(new Runnable() {
@Override public void run() {
for (final JDialog otherP : popups) {
if (popup != otherP) {
otherP.dispose();
}
}
}
});
}
public void menuSelected(final MenuEvent e) {
final Point l = menu.getLocationOnScreen();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
for (final JDialog otherP : popups) {
otherP.dispose();
}
popup.setLocation(
(int) (l.getX() + menu.getBounds().getWidth()),
(int) l.getY());
popup.setVisible(true);
}
});
SwingUtilities.invokeLater(new Runnable() {
@Override public void run() {
popup.setLocation(
(int) (l.getX() + menu.getBounds().getWidth()),
(int) l.getY());
}
});
}
});
return true;
}
| public static boolean getScrollingMenu(
final String name,
final MyMenu menu,
final MyListModel dlm,
final MyList list,
final Info infoObject,
final List<JDialog> popups,
final Map<MyMenuItem, ButtonCallback> callbackHash) {
final int maxSize = dlm.getSize();
if (maxSize <= 0) {
return false;
}
prevScrollingMenuIndex = -1;
list.setFixedCellHeight(25);
if (maxSize > 20) {
list.setVisibleRowCount(20);
} else {
list.setVisibleRowCount(maxSize);
}
final JScrollPane sp = new JScrollPane(list);
sp.setViewportBorder(null);
sp.setBorder(null);
final JTextField typeToSearchField = dlm.getFilterField();
final JDialog popup = new JDialog(new JFrame(), name, false);
final JPanel popupPanel = new JPanel();
popupPanel.setLayout(new BoxLayout(popupPanel, BoxLayout.PAGE_AXIS));
popupPanel.add(typeToSearchField);
popupPanel.add(sp);
popup.setContentPane(popupPanel);
popups.add(popup);
list.addMouseListener(new MouseAdapter() {
@Override public void mouseExited(final MouseEvent evt) {
prevScrollingMenuIndex = -1;
if (callbackHash != null) {
for (final MyMenuItem item : callbackHash.keySet()) {
callbackHash.get(item).mouseOut();
list.clearSelection();
}
}
}
@Override public void mouseEntered(final MouseEvent evt) {
/* request focus here causes the applet making all
textfields to be not editable. */
list.requestFocus();
}
@Override public void mousePressed(final MouseEvent evt) {
prevScrollingMenuIndex = -1;
if (callbackHash != null) {
for (final MyMenuItem item : callbackHash.keySet()) {
callbackHash.get(item).mouseOut();
}
}
final Thread thread = new Thread(new Runnable() {
@Override public void run() {
final int index = list.locationToIndex(evt.getPoint());
SwingUtilities.invokeLater(new Runnable() {
@Override public void run() {
list.setSelectedIndex(index);
//TODO: some submenus stay visible, during
//ptest, but this breaks group popup menu
//setMenuVisible(menu, false);
menu.setSelected(false);
}
});
final MyMenuItem item =
(MyMenuItem) dlm.getElementAt(index);
item.action();
}
});
thread.start();
}
});
list.addMouseMotionListener(new MouseMotionAdapter() {
@Override public void mouseMoved(final MouseEvent evt) {
final Thread thread = new Thread(new Runnable() {
@Override public void run() {
int pIndex = list.locationToIndex(evt.getPoint());
if (!list.getCellBounds(pIndex, pIndex).contains(
evt.getPoint())) {
pIndex = -1;
}
final int index = pIndex;
final int lastIndex = prevScrollingMenuIndex;
if (index == lastIndex) {
return;
}
prevScrollingMenuIndex = index;
SwingUtilities.invokeLater(new Runnable() {
@Override public void run() {
list.setSelectedIndex(index);
}
});
if (callbackHash != null) {
if (lastIndex >= 0) {
final MyMenuItem lastItem =
(MyMenuItem) dlm.getElementAt(lastIndex);
callbackHash.get(lastItem).mouseOut();
}
if (index >= 0) {
final MyMenuItem item =
(MyMenuItem) dlm.getElementAt(index);
callbackHash.get(item).mouseOver();
}
}
}
});
thread.start();
}
});
list.addKeyListener(new KeyAdapter() {
@Override public void keyTyped(final KeyEvent e) {
final char ch = e.getKeyChar();
if (ch == 27) { /* escape */
for (final JDialog otherP : popups) {
otherP.dispose();
}
infoObject.hidePopup();
} else if (ch == ' ' || ch == '\n') {
final MyMenuItem item =
(MyMenuItem) list.getSelectedValue();
//SwingUtilities.invokeLater(new Runnable() {
// @Override public void run() {
// //menu.setPopupMenuVisible(false);
// setMenuVisible(menu, false);
// }
//});
if (item != null) {
item.action();
}
} else {
if (Character.isLetterOrDigit(ch)) {
final Thread t = new Thread(new Runnable() {
@Override public void run() {
getGUIData().getMainGlassPane().start("" + ch,
null,
true);
stopProgressIndicator("" + ch);
}
});
t.start();
}
}
}
});
menu.addMenuListener(new MenuListener() {
public void menuCanceled(final MenuEvent e) {
SwingUtilities.invokeLater(new Runnable() {
@Override public void run() {
for (final JDialog otherP : popups) {
otherP.dispose();
}
}
});
}
public void menuDeselected(final MenuEvent e) {
SwingUtilities.invokeLater(new Runnable() {
@Override public void run() {
for (final JDialog otherP : popups) {
if (popup != otherP) {
otherP.dispose();
}
}
}
});
}
public void menuSelected(final MenuEvent e) {
final Point l = menu.getLocationOnScreen();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
for (final JDialog otherP : popups) {
otherP.dispose();
}
popup.setLocation(
(int) (l.getX() + menu.getBounds().getWidth()),
(int) l.getY() - 1);
popup.pack();
popup.setVisible(true);
}
});
SwingUtilities.invokeLater(new Runnable() {
@Override public void run() {
/* Setting location again. Moving it one pixel fixes
the "gray window" problem. */
popup.setLocation(
(int) (l.getX() + menu.getBounds().getWidth()),
(int) l.getY());
}
});
}
});
return true;
}
|
diff --git a/src/main/java/casino/InDoor.java b/src/main/java/casino/InDoor.java
index 8b97c72..bb0bc40 100644
--- a/src/main/java/casino/InDoor.java
+++ b/src/main/java/casino/InDoor.java
@@ -1,207 +1,207 @@
package casino;
import java.util.UUID;
import org.nr.roulette.exceptions.ValidationException;
import talk.BetRequest;
import talk.BetResponse;
import talk.RegisterRequest;
import talk.RegisterResponse;
import talk.Response;
import bets.Bet;
import bets.ColourBet;
import bets.ColumnBet;
import bets.CornerBet;
import bets.DozenBet;
import bets.HalfBet;
import bets.LineBet;
import bets.ParityBet;
import bets.SplitHorizontalBet;
import bets.SplitVerticalBet;
import bets.StreetBet;
import bets.StrightBet;
public class InDoor {
//nr update
final static String ANSWER_OK = "OK";
final static String ANSWER_BAD = "Fail";
final static String NO_ID = "NO_ID";
final static String BET_COMMAND = "NO_ID";
final static String REGISTER_COMMAND = "register";
public static Response processBetRequest (BetRequest request) throws ValidationException {
String command = BET_COMMAND;
String answer = "";
String reason = "";
String userid = request.getUserid();
BetResponse response = null;
OperationResult regBetResult = null;
// - create object Bet
// - send bet to croupie
Bet bet = null;
try {
// Password check
// TODO Add hash check instead of plain text password
if(!Croupie.newInstance().isPasswordValidForUserId(userid, request.getPlayerPassword()))
{
throw new ValidationException("Player's password is not valid");
}
if ( request.getBetType().equals("StrightBet" )) {
bet = new StrightBet(request.getNumber(), request.getStake() );
}
else if ( request.getBetType().equals("ColourBet" )) {
bet = new ColourBet(request.getNumber(), request.getStake() );
}
else if ( request.getBetType().equals("ColumnBet" )) {
bet = new ColumnBet(request.getNumber(), request.getStake() );
}
else if ( request.getBetType().equals("CornerBet" )) {
bet = new CornerBet(request.getNumber(), request.getStake() );
}
else if ( request.getBetType().equals("DozenBet" )) {
bet = new DozenBet(request.getNumber(), request.getStake() );
}
else if ( request.getBetType().equals("HalfBet" )) {
bet = new HalfBet(request.getNumber(), request.getStake() );
}
else if ( request.getBetType().equals("LineBet" )) {
bet = new LineBet(request.getNumber(), request.getStake() );
}
else if ( request.getBetType().equals("ParityBet" )) {
bet = new ParityBet(request.getNumber(), request.getStake() );
}
else if ( request.getBetType().equals("SplitHorizontalBet" )) {
bet = new SplitHorizontalBet(request.getNumber(), request.getStake() );
}
else if ( request.getBetType().equals("SplitVerticalBet" )) {
bet = new SplitVerticalBet(request.getNumber(), request.getStake() );
}
else if ( request.getBetType().equals("StreetBet" )) {
bet = new StreetBet(request.getNumber(), request.getStake() );
}
else {
// ERORR
- System.out.println( "Wrong Bet Type: "+request.getBetType()+ " from player: " +request.getPlayerName() );
+ throw new ValidationException("Wrong Bet Type: "+request.getBetType()+ " from player: " +request.getPlayerName() );
}
}
catch (ValidationException vex) {
answer = ANSWER_BAD;
reason = vex.getMessage();
//return response = new BetResponse (userid, command, answer, reason );
}
// if we a here then Bet created successfully
answer = ANSWER_OK;
UUID playerId = UUID.fromString(request.getUserid());
try {
regBetResult = Croupie.newInstance().registerBet(bet, playerId);
} catch (NullPointerException ex) {
answer = ANSWER_BAD;
reason = ex.getMessage();
}
response = new BetResponse( request.getUserid(),
"bet request",
answer,
request.getTableType(),
request.getStake(),
request.getNumber(),
request.getBetType(),
reason);
return response;
}
public static Response processRegisterRequest(RegisterRequest request){
System.out.println( "Register request received from "+request.getPlayerName() );
// answer Strings
String userid;
String command = REGISTER_COMMAND;
String answer;
Player player = null;
RegisterResponse response = null;
try {
String nameFromRequest = request.getPlayerName();
String passwordFromRequest = request.getPlayerPassword();
player = new Player(nameFromRequest, passwordFromRequest);
}
catch (ValidationException vex) {
userid = NO_ID;
answer = ANSWER_BAD;
String reason = vex.getMessage();
response = new RegisterResponse (userid, command, answer, reason );
}
//update
// OperationResult regPlayerResult = croupie_need_to_be_created.registerPlayer(player);
OperationResult regPlayerResult = Croupie.newInstance().registerPlayer(player);
if ( regPlayerResult == OperationResult.PLAYER_REGISTERED) {
System.out.println( "Player successfully registered: "+request.getPlayerName() );
userid = player.getId().toString();
answer = ANSWER_OK;
response = new RegisterResponse (userid, command, answer);
}
else if ( regPlayerResult == OperationResult.PLAYER_ALREADY_REGISTERED ) {
userid = player.getId().toString();
answer = ANSWER_BAD;
String reason = "Error: Player already registered";
response = new RegisterResponse (userid, command, answer, reason );
}
return response;
}
/*
commands:
user commands:
- register Player
set Player Name
set Password
/* */
/*
- all bets done, perform spin (test table)
UUID
password
/* */
/*
- take Bet from user
UUID
password
table type
bet type
stake
number
/* */
/*
administrator commands:
- deleteAllPlayers
administrator UUID
password
/* */
}
| true | true | public static Response processBetRequest (BetRequest request) throws ValidationException {
String command = BET_COMMAND;
String answer = "";
String reason = "";
String userid = request.getUserid();
BetResponse response = null;
OperationResult regBetResult = null;
// - create object Bet
// - send bet to croupie
Bet bet = null;
try {
// Password check
// TODO Add hash check instead of plain text password
if(!Croupie.newInstance().isPasswordValidForUserId(userid, request.getPlayerPassword()))
{
throw new ValidationException("Player's password is not valid");
}
if ( request.getBetType().equals("StrightBet" )) {
bet = new StrightBet(request.getNumber(), request.getStake() );
}
else if ( request.getBetType().equals("ColourBet" )) {
bet = new ColourBet(request.getNumber(), request.getStake() );
}
else if ( request.getBetType().equals("ColumnBet" )) {
bet = new ColumnBet(request.getNumber(), request.getStake() );
}
else if ( request.getBetType().equals("CornerBet" )) {
bet = new CornerBet(request.getNumber(), request.getStake() );
}
else if ( request.getBetType().equals("DozenBet" )) {
bet = new DozenBet(request.getNumber(), request.getStake() );
}
else if ( request.getBetType().equals("HalfBet" )) {
bet = new HalfBet(request.getNumber(), request.getStake() );
}
else if ( request.getBetType().equals("LineBet" )) {
bet = new LineBet(request.getNumber(), request.getStake() );
}
else if ( request.getBetType().equals("ParityBet" )) {
bet = new ParityBet(request.getNumber(), request.getStake() );
}
else if ( request.getBetType().equals("SplitHorizontalBet" )) {
bet = new SplitHorizontalBet(request.getNumber(), request.getStake() );
}
else if ( request.getBetType().equals("SplitVerticalBet" )) {
bet = new SplitVerticalBet(request.getNumber(), request.getStake() );
}
else if ( request.getBetType().equals("StreetBet" )) {
bet = new StreetBet(request.getNumber(), request.getStake() );
}
else {
// ERORR
System.out.println( "Wrong Bet Type: "+request.getBetType()+ " from player: " +request.getPlayerName() );
}
}
catch (ValidationException vex) {
answer = ANSWER_BAD;
reason = vex.getMessage();
//return response = new BetResponse (userid, command, answer, reason );
}
// if we a here then Bet created successfully
answer = ANSWER_OK;
UUID playerId = UUID.fromString(request.getUserid());
try {
regBetResult = Croupie.newInstance().registerBet(bet, playerId);
} catch (NullPointerException ex) {
answer = ANSWER_BAD;
reason = ex.getMessage();
}
response = new BetResponse( request.getUserid(),
"bet request",
answer,
request.getTableType(),
request.getStake(),
request.getNumber(),
request.getBetType(),
reason);
return response;
}
| public static Response processBetRequest (BetRequest request) throws ValidationException {
String command = BET_COMMAND;
String answer = "";
String reason = "";
String userid = request.getUserid();
BetResponse response = null;
OperationResult regBetResult = null;
// - create object Bet
// - send bet to croupie
Bet bet = null;
try {
// Password check
// TODO Add hash check instead of plain text password
if(!Croupie.newInstance().isPasswordValidForUserId(userid, request.getPlayerPassword()))
{
throw new ValidationException("Player's password is not valid");
}
if ( request.getBetType().equals("StrightBet" )) {
bet = new StrightBet(request.getNumber(), request.getStake() );
}
else if ( request.getBetType().equals("ColourBet" )) {
bet = new ColourBet(request.getNumber(), request.getStake() );
}
else if ( request.getBetType().equals("ColumnBet" )) {
bet = new ColumnBet(request.getNumber(), request.getStake() );
}
else if ( request.getBetType().equals("CornerBet" )) {
bet = new CornerBet(request.getNumber(), request.getStake() );
}
else if ( request.getBetType().equals("DozenBet" )) {
bet = new DozenBet(request.getNumber(), request.getStake() );
}
else if ( request.getBetType().equals("HalfBet" )) {
bet = new HalfBet(request.getNumber(), request.getStake() );
}
else if ( request.getBetType().equals("LineBet" )) {
bet = new LineBet(request.getNumber(), request.getStake() );
}
else if ( request.getBetType().equals("ParityBet" )) {
bet = new ParityBet(request.getNumber(), request.getStake() );
}
else if ( request.getBetType().equals("SplitHorizontalBet" )) {
bet = new SplitHorizontalBet(request.getNumber(), request.getStake() );
}
else if ( request.getBetType().equals("SplitVerticalBet" )) {
bet = new SplitVerticalBet(request.getNumber(), request.getStake() );
}
else if ( request.getBetType().equals("StreetBet" )) {
bet = new StreetBet(request.getNumber(), request.getStake() );
}
else {
// ERORR
throw new ValidationException("Wrong Bet Type: "+request.getBetType()+ " from player: " +request.getPlayerName() );
}
}
catch (ValidationException vex) {
answer = ANSWER_BAD;
reason = vex.getMessage();
//return response = new BetResponse (userid, command, answer, reason );
}
// if we a here then Bet created successfully
answer = ANSWER_OK;
UUID playerId = UUID.fromString(request.getUserid());
try {
regBetResult = Croupie.newInstance().registerBet(bet, playerId);
} catch (NullPointerException ex) {
answer = ANSWER_BAD;
reason = ex.getMessage();
}
response = new BetResponse( request.getUserid(),
"bet request",
answer,
request.getTableType(),
request.getStake(),
request.getNumber(),
request.getBetType(),
reason);
return response;
}
|
diff --git a/astCreator/src/main/java/com/lausdahl/ast/creator/methods/ConstructorTreeFieldsOnlyMethod.java b/astCreator/src/main/java/com/lausdahl/ast/creator/methods/ConstructorTreeFieldsOnlyMethod.java
index 63f8dd4..0a2def6 100644
--- a/astCreator/src/main/java/com/lausdahl/ast/creator/methods/ConstructorTreeFieldsOnlyMethod.java
+++ b/astCreator/src/main/java/com/lausdahl/ast/creator/methods/ConstructorTreeFieldsOnlyMethod.java
@@ -1,133 +1,133 @@
package com.lausdahl.ast.creator.methods;
import java.util.List;
import java.util.Vector;
import com.lausdahl.ast.creator.definitions.Field;
import com.lausdahl.ast.creator.definitions.Field.StructureType;
import com.lausdahl.ast.creator.definitions.IClassDefinition;
import com.lausdahl.ast.creator.definitions.JavaTypes;
import com.lausdahl.ast.creator.env.Environment;
import com.lausdahl.ast.creator.utils.NameUtil;
public class ConstructorTreeFieldsOnlyMethod extends ConstructorMethod
{
public ConstructorTreeFieldsOnlyMethod(IClassDefinition c, Environment env)
{
super(c, env);
this.name = classDefinition.getName().getName();
}
@Override
protected void prepare()
{
skip = true;
// skip = classDefinition.getFields().isEmpty();
// if(!skip)
{
List<Field> allFields = new Vector<Field>();
if (env.isTreeNode(classDefinition ))
{
allFields.addAll(classDefinition.getInheritedFields());
}
allFields.addAll(classDefinition.getFields());
for (Field field : allFields)
{
if (field.structureType == StructureType.Graph)
{
skip = false;
break;
}
}
}
if (skip)
{
return;
}
this.name = classDefinition.getName().getName();
this.returnType = "";
StringBuilder sbDoc = new StringBuilder();
sbDoc.append("\t");
sbDoc.append("/**\n");
sbDoc.append("\t");
sbDoc.append("* Creates a new {@code " + classDefinition.getName()
+ "} node with the given nodes as children.\n");
sbDoc.append("\t");
sbDoc.append("* @deprecated This method should not be used, use AstFactory instead.");
- sbDoc.append("\t");
+ sbDoc.append("\n\t");
sbDoc.append("* The basic child nodes are removed from their previous parents.\n");
StringBuilder sb = new StringBuilder();
sb.append("\t\tsuper(");
List<Field> fields = new Vector<Field>();
fields.addAll(classDefinition.getInheritedFields());
skip = skip && fields.isEmpty();
for (Field f : fields)
{
if (classDefinition.refinesField(f.getName()))
{
// This field is refined in the sub class, so skip it and null the super class field.
sb.append(JavaTypes.getDefaultValue(f.getType())+",");
} else
{
if (f.structureType == StructureType.Tree)
{
String name = f.getName().replaceAll("_", "") + "_";
this.arguments.add(new Argument(f.getMethodArgumentType(), name));
sb.append(name + ",");
} else
{
sb.append(JavaTypes.getDefaultValue(f.getType())+",");
}
}
}
if (!fields.isEmpty())
{
sb.delete(sb.length() - 1, sb.length());
}
sb.append(");\n");
for (Field f : classDefinition.getFields())
{
if (f.structureType == StructureType.Tree)
{
String name = f.getName().replaceAll("_", "");
this.arguments.add(new Argument(f.getMethodArgumentType(), name
+ "_"));
sb.append("\t\t");
sb.append("this.set");
sb.append(NameUtil.javaClassName(f.getName()));
sb.append("(");
sb.append(name + "_");
sb.append(");\n");
sbDoc.append("\t* @param " + name + "_ the {@link "
+ NameUtil.stripGenerics(f.getType()) + "} node for the {@code " + name
+ "} child of this {@link " + classDefinition.getName().getName()
+ "} node\n");
}else if(JavaTypes.isPrimitiveType(f.getType()))
{
sb.append("\t\t");
sb.append("this.set");
sb.append(NameUtil.javaClassName(f.getName()));
sb.append("(");
sb.append(JavaTypes.getDefaultValue(f.getType()));
sb.append(");\n");
// sbDoc.append("\t* @param " + name + " the {@link "
// + f.getType() + "} node for the {@code " + name
// + "} child of this {@link " + classDefinition.getName()
// + "} node\n");
}
}
sbDoc.append("\t*/");
this.javaDoc = sbDoc.toString();
this.body = sb.toString();
}
}
| true | true | protected void prepare()
{
skip = true;
// skip = classDefinition.getFields().isEmpty();
// if(!skip)
{
List<Field> allFields = new Vector<Field>();
if (env.isTreeNode(classDefinition ))
{
allFields.addAll(classDefinition.getInheritedFields());
}
allFields.addAll(classDefinition.getFields());
for (Field field : allFields)
{
if (field.structureType == StructureType.Graph)
{
skip = false;
break;
}
}
}
if (skip)
{
return;
}
this.name = classDefinition.getName().getName();
this.returnType = "";
StringBuilder sbDoc = new StringBuilder();
sbDoc.append("\t");
sbDoc.append("/**\n");
sbDoc.append("\t");
sbDoc.append("* Creates a new {@code " + classDefinition.getName()
+ "} node with the given nodes as children.\n");
sbDoc.append("\t");
sbDoc.append("* @deprecated This method should not be used, use AstFactory instead.");
sbDoc.append("\t");
sbDoc.append("* The basic child nodes are removed from their previous parents.\n");
StringBuilder sb = new StringBuilder();
sb.append("\t\tsuper(");
List<Field> fields = new Vector<Field>();
fields.addAll(classDefinition.getInheritedFields());
skip = skip && fields.isEmpty();
for (Field f : fields)
{
if (classDefinition.refinesField(f.getName()))
{
// This field is refined in the sub class, so skip it and null the super class field.
sb.append(JavaTypes.getDefaultValue(f.getType())+",");
} else
{
if (f.structureType == StructureType.Tree)
{
String name = f.getName().replaceAll("_", "") + "_";
this.arguments.add(new Argument(f.getMethodArgumentType(), name));
sb.append(name + ",");
} else
{
sb.append(JavaTypes.getDefaultValue(f.getType())+",");
}
}
}
if (!fields.isEmpty())
{
sb.delete(sb.length() - 1, sb.length());
}
sb.append(");\n");
for (Field f : classDefinition.getFields())
{
if (f.structureType == StructureType.Tree)
{
String name = f.getName().replaceAll("_", "");
this.arguments.add(new Argument(f.getMethodArgumentType(), name
+ "_"));
sb.append("\t\t");
sb.append("this.set");
sb.append(NameUtil.javaClassName(f.getName()));
sb.append("(");
sb.append(name + "_");
sb.append(");\n");
sbDoc.append("\t* @param " + name + "_ the {@link "
+ NameUtil.stripGenerics(f.getType()) + "} node for the {@code " + name
+ "} child of this {@link " + classDefinition.getName().getName()
+ "} node\n");
}else if(JavaTypes.isPrimitiveType(f.getType()))
{
sb.append("\t\t");
sb.append("this.set");
sb.append(NameUtil.javaClassName(f.getName()));
sb.append("(");
sb.append(JavaTypes.getDefaultValue(f.getType()));
sb.append(");\n");
// sbDoc.append("\t* @param " + name + " the {@link "
// + f.getType() + "} node for the {@code " + name
// + "} child of this {@link " + classDefinition.getName()
// + "} node\n");
}
}
sbDoc.append("\t*/");
this.javaDoc = sbDoc.toString();
this.body = sb.toString();
}
| protected void prepare()
{
skip = true;
// skip = classDefinition.getFields().isEmpty();
// if(!skip)
{
List<Field> allFields = new Vector<Field>();
if (env.isTreeNode(classDefinition ))
{
allFields.addAll(classDefinition.getInheritedFields());
}
allFields.addAll(classDefinition.getFields());
for (Field field : allFields)
{
if (field.structureType == StructureType.Graph)
{
skip = false;
break;
}
}
}
if (skip)
{
return;
}
this.name = classDefinition.getName().getName();
this.returnType = "";
StringBuilder sbDoc = new StringBuilder();
sbDoc.append("\t");
sbDoc.append("/**\n");
sbDoc.append("\t");
sbDoc.append("* Creates a new {@code " + classDefinition.getName()
+ "} node with the given nodes as children.\n");
sbDoc.append("\t");
sbDoc.append("* @deprecated This method should not be used, use AstFactory instead.");
sbDoc.append("\n\t");
sbDoc.append("* The basic child nodes are removed from their previous parents.\n");
StringBuilder sb = new StringBuilder();
sb.append("\t\tsuper(");
List<Field> fields = new Vector<Field>();
fields.addAll(classDefinition.getInheritedFields());
skip = skip && fields.isEmpty();
for (Field f : fields)
{
if (classDefinition.refinesField(f.getName()))
{
// This field is refined in the sub class, so skip it and null the super class field.
sb.append(JavaTypes.getDefaultValue(f.getType())+",");
} else
{
if (f.structureType == StructureType.Tree)
{
String name = f.getName().replaceAll("_", "") + "_";
this.arguments.add(new Argument(f.getMethodArgumentType(), name));
sb.append(name + ",");
} else
{
sb.append(JavaTypes.getDefaultValue(f.getType())+",");
}
}
}
if (!fields.isEmpty())
{
sb.delete(sb.length() - 1, sb.length());
}
sb.append(");\n");
for (Field f : classDefinition.getFields())
{
if (f.structureType == StructureType.Tree)
{
String name = f.getName().replaceAll("_", "");
this.arguments.add(new Argument(f.getMethodArgumentType(), name
+ "_"));
sb.append("\t\t");
sb.append("this.set");
sb.append(NameUtil.javaClassName(f.getName()));
sb.append("(");
sb.append(name + "_");
sb.append(");\n");
sbDoc.append("\t* @param " + name + "_ the {@link "
+ NameUtil.stripGenerics(f.getType()) + "} node for the {@code " + name
+ "} child of this {@link " + classDefinition.getName().getName()
+ "} node\n");
}else if(JavaTypes.isPrimitiveType(f.getType()))
{
sb.append("\t\t");
sb.append("this.set");
sb.append(NameUtil.javaClassName(f.getName()));
sb.append("(");
sb.append(JavaTypes.getDefaultValue(f.getType()));
sb.append(");\n");
// sbDoc.append("\t* @param " + name + " the {@link "
// + f.getType() + "} node for the {@code " + name
// + "} child of this {@link " + classDefinition.getName()
// + "} node\n");
}
}
sbDoc.append("\t*/");
this.javaDoc = sbDoc.toString();
this.body = sb.toString();
}
|
diff --git a/src/butchery/common/blocks/TileEntityTub.java b/src/butchery/common/blocks/TileEntityTub.java
index afea463..60e2153 100644
--- a/src/butchery/common/blocks/TileEntityTub.java
+++ b/src/butchery/common/blocks/TileEntityTub.java
@@ -1,350 +1,351 @@
/**
* Copyright (c) Beliar, 2012
* https://github.com/Beliaar/Butchery
*
* Butchery is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* https://github.com/Beliaar/Butchery/wiki/License
*/
package butchery.common.blocks;
import butchery.api.ITubWaterModifier;
import cpw.mods.fml.common.Side;
import cpw.mods.fml.common.asm.SideOnly;
import net.minecraft.src.EntityPlayer;
import net.minecraft.src.EntityPlayerMP;
import net.minecraft.src.IInventory;
import net.minecraft.src.Item;
import net.minecraft.src.ItemStack;
import net.minecraft.src.NBTTagCompound;
import net.minecraft.src.NBTTagList;
import net.minecraft.src.NetworkManager;
import net.minecraft.src.Packet;
import net.minecraft.src.Packet132TileEntityData;
import net.minecraft.src.TileEntity;
import net.minecraft.src.Vec3;
import net.minecraft.src.World;
import net.minecraft.src.WorldClient;
import net.minecraft.src.WorldServer;
public class TileEntityTub extends TileEntity implements IInventory {
public int waterLevel = 0;
public float soakProgress = 0.0F;
public int currentSoakTime = 0;
private ItemStack[] tubItemStacks;
public TileEntityTub() {
this.tubItemStacks = new ItemStack[3];
}
public boolean processActivate(EntityPlayer player, World world,
ItemStack currentItem) {
if (world.isRemote) {
return true;
}
if (currentItem.itemID == Item.bucketWater.shiftedIndex) {
if (this.waterLevel < 100) {
if (!player.capabilities.isCreativeMode) {
player.inventory.setInventorySlotContents(
player.inventory.currentItem, new ItemStack(
Item.bucketEmpty));
}
this.waterLevel = 100;
world.notifyBlockChange(this.xCoord, this.yCoord, this.zCoord,
0);
sendUpdateToWatchingPlayers(world, this.xCoord, this.zCoord);
}
return true;
}
return false;
}
public void fillWithRain(World world, int par2, int par3, int par4) {
if (world.isRemote) {
return;
}
if (this.waterLevel < 100) {
this.waterLevel += 1;
checkWaterLevel();
world.notifyBlockChange(this.xCoord, this.yCoord, this.zCoord, 0);
sendUpdateToWatchingPlayers(world, par2, par4);
}
}
private void sendUpdateToWatchingPlayers(World world, int par2, int par4) {
if (world.isRemote) {
return;
}
WorldServer serverWorld = (WorldServer) world;
for (Object player_obj : world.playerEntities) {
EntityPlayerMP player = (EntityPlayerMP) player_obj;
if (serverWorld.getPlayerManager().isPlayerWatchingChunk(player,
par2 >> 4, par4 >> 4)) {
player.serverForThisPlayer
.sendPacketToPlayer(getAuxillaryInfoPacket());
}
}
}
public void checkWaterLevel() {
if (this.waterLevel >= 100) {
this.waterLevel = 100;
}
}
@Override
public void readFromNBT(NBTTagCompound nbt) {
super.readFromNBT(nbt);
NBTTagList var2 = nbt.getTagList("Items");
this.tubItemStacks = new ItemStack[this.getSizeInventory()];
for (int var3 = 0; var3 < var2.tagCount(); ++var3) {
NBTTagCompound var4 = (NBTTagCompound) var2.tagAt(var3);
byte var5 = var4.getByte("Slot");
if (var5 >= 0 && var5 < this.tubItemStacks.length) {
this.tubItemStacks[var5] = ItemStack.loadItemStackFromNBT(var4);
}
}
this.waterLevel = nbt.getInteger("waterLevel");
this.soakProgress = nbt.getFloat("soakProgress");
this.currentSoakTime = nbt.getInteger("currentSoakTime");
checkWaterLevel();
}
@Override
public void writeToNBT(NBTTagCompound nbt) {
super.writeToNBT(nbt);
checkWaterLevel();
nbt.setInteger("waterLevel", this.waterLevel);
NBTTagList var2 = new NBTTagList();
for (int var3 = 0; var3 < this.tubItemStacks.length; ++var3) {
if (this.tubItemStacks[var3] != null) {
NBTTagCompound var4 = new NBTTagCompound();
var4.setByte("Slot", (byte) var3);
this.tubItemStacks[var3].writeToNBT(var4);
var2.appendTag(var4);
}
}
nbt.setTag("Items", var2);
nbt.setFloat("soakProgress", this.soakProgress);
nbt.setInteger("currentSoakTime", this.currentSoakTime);
}
@Override
public Packet getAuxillaryInfoPacket() {
NBTTagCompound tag = new NBTTagCompound();
this.writeToNBT(tag);
return new Packet132TileEntityData(this.xCoord, this.yCoord,
this.zCoord, 1, tag);
}
@Override
public void onDataPacket(NetworkManager net, Packet132TileEntityData packet) {
NBTTagCompound tag = packet.customParam1;
this.waterLevel = tag.getInteger("waterLevel");
this.soakProgress = tag.getFloat("soakProgress");
this.currentSoakTime = tag.getInteger("currentSoakTime");
}
@Override
public int getSizeInventory() {
return this.tubItemStacks.length;
}
@Override
public ItemStack getStackInSlot(int slot) {
return this.tubItemStacks[slot];
}
@Override
public ItemStack decrStackSize(int slot, int amount) {
ItemStack stack = getStackInSlot(slot);
if (stack != null) {
if (stack.stackSize <= amount) {
setInventorySlotContents(slot, null);
} else {
stack = stack.splitStack(amount);
if (stack.stackSize == 0) {
setInventorySlotContents(amount, null);
}
}
}
return stack;
}
@Override
public ItemStack getStackInSlotOnClosing(int slot) {
ItemStack stack = getStackInSlot(slot);
if (stack != null) {
setInventorySlotContents(slot, null);
}
return stack;
}
@Override
public void setInventorySlotContents(int slot, ItemStack stack) {
tubItemStacks[slot] = stack;
if (stack != null && stack.stackSize > getInventoryStackLimit()) {
stack.stackSize = getInventoryStackLimit();
}
}
@Override
public String getInvName() {
return "butchery.container.tub";
}
@Override
public int getInventoryStackLimit() {
return 64;
}
@Override
public boolean isUseableByPlayer(EntityPlayer player) {
return worldObj.getBlockTileEntity(xCoord, yCoord, zCoord) == this
&& player.getDistanceSq(xCoord + 0.5, yCoord + 0.5,
zCoord + 0.5) < 64;
}
@Override
public void openChest() {
}
@Override
public void closeChest() {
}
@SideOnly(Side.CLIENT)
/**
* Returns an integer between 0 and the passed value representing the
* current water level.
*/
public int getWaterLevelScaled(int max) {
return this.waterLevel * max / 100;
}
@SideOnly(Side.CLIENT)
/**
* Returns an integer between 0 and the passed value representing how close
* the current item is to being completely soaked.
*/
public int getSoakProgressScaled(int max) {
return (int) (this.soakProgress * max);
}
public boolean isSoaking() {
return this.currentSoakTime > 0;
}
/**
* Allows the entity to update its state. Overridden in most subclasses,
* e.g. the mob spawner uses this to count ticks and creates a new spawn
* inside its implementation.
*/
@Override
public void updateEntity() {
boolean inventoryChanged = false;
if (!canSoak()) {
this.currentSoakTime = 0;
this.soakProgress = 0;
}
if (this.currentSoakTime > 0) {
--this.currentSoakTime;
ITubWaterModifier modifier;
modifier = (ITubWaterModifier) this.tubItemStacks[0].getItem();
int ticksNeeded = modifier.getTicksNeeded(this.tubItemStacks[1]);
int ticksPassed = ticksNeeded - this.currentSoakTime;
this.soakProgress = (float) ticksPassed / (float) ticksNeeded;
+ inventoryChanged = true;
}
if (!this.worldObj.isRemote) {
if (this.currentSoakTime == 0 && canSoak()) {
ITubWaterModifier modifier;
modifier = (ITubWaterModifier) this.tubItemStacks[0].getItem();
this.currentSoakTime = modifier
.getTicksNeeded(this.tubItemStacks[1]);
this.soakProgress = 0.0F;
inventoryChanged = true;
}
if (this.currentSoakTime == 1) {
soakItem();
this.soakProgress = 0.0F;
inventoryChanged = true;
}
}
if (inventoryChanged) {
this.onInventoryChanged();
sendUpdateToWatchingPlayers(this.worldObj, this.xCoord, this.zCoord);
}
}
/**
* Returns true if an item can be soaked in the tub with the current
* modifier
*
*/
public boolean canSoak() {
if (this.tubItemStacks[0] == null) {
return false;
}
if (this.tubItemStacks[1] == null) {
return false;
}
if (this.tubItemStacks[0].getItem() instanceof ITubWaterModifier) {
ITubWaterModifier modifier;
modifier = (ITubWaterModifier) this.tubItemStacks[0].getItem();
if (this.waterLevel < modifier.getWaterUsage(this.tubItemStacks[1])) {
return false;
}
ItemStack output = modifier.getOutput(this.tubItemStacks[1]);
if (output == null) {
return false;
}
if (this.tubItemStacks[2] == null) {
return true;
}
if (!this.tubItemStacks[2].isItemEqual(output)) {
return false;
}
int result = this.tubItemStacks[2].stackSize + output.stackSize;
return (result < getInventoryStackLimit() && result < output
.getMaxStackSize());
}
return false;
}
/**
* Transform items from the input stack into the output items
*/
public void soakItem() {
if (canSoak()) {
ITubWaterModifier modifier;
modifier = (ITubWaterModifier) this.tubItemStacks[0].getItem();
ItemStack output = modifier.getOutput(this.tubItemStacks[1]);
if (this.tubItemStacks[2] == null) {
this.tubItemStacks[2] = output.copy();
} else if (this.tubItemStacks[2].isItemEqual(output)) {
this.tubItemStacks[2].stackSize += output.stackSize;
}
this.waterLevel -= modifier.getWaterUsage(this.tubItemStacks[1]);
--this.tubItemStacks[0].stackSize;
if (this.tubItemStacks[0].stackSize <= 0) {
this.tubItemStacks[0] = null;
}
this.tubItemStacks[1].stackSize -= output.stackSize;
if (this.tubItemStacks[1].stackSize <= 0) {
this.tubItemStacks[1] = null;
}
}
}
}
| true | true | public void updateEntity() {
boolean inventoryChanged = false;
if (!canSoak()) {
this.currentSoakTime = 0;
this.soakProgress = 0;
}
if (this.currentSoakTime > 0) {
--this.currentSoakTime;
ITubWaterModifier modifier;
modifier = (ITubWaterModifier) this.tubItemStacks[0].getItem();
int ticksNeeded = modifier.getTicksNeeded(this.tubItemStacks[1]);
int ticksPassed = ticksNeeded - this.currentSoakTime;
this.soakProgress = (float) ticksPassed / (float) ticksNeeded;
}
if (!this.worldObj.isRemote) {
if (this.currentSoakTime == 0 && canSoak()) {
ITubWaterModifier modifier;
modifier = (ITubWaterModifier) this.tubItemStacks[0].getItem();
this.currentSoakTime = modifier
.getTicksNeeded(this.tubItemStacks[1]);
this.soakProgress = 0.0F;
inventoryChanged = true;
}
if (this.currentSoakTime == 1) {
soakItem();
this.soakProgress = 0.0F;
inventoryChanged = true;
}
}
if (inventoryChanged) {
this.onInventoryChanged();
sendUpdateToWatchingPlayers(this.worldObj, this.xCoord, this.zCoord);
}
}
| public void updateEntity() {
boolean inventoryChanged = false;
if (!canSoak()) {
this.currentSoakTime = 0;
this.soakProgress = 0;
}
if (this.currentSoakTime > 0) {
--this.currentSoakTime;
ITubWaterModifier modifier;
modifier = (ITubWaterModifier) this.tubItemStacks[0].getItem();
int ticksNeeded = modifier.getTicksNeeded(this.tubItemStacks[1]);
int ticksPassed = ticksNeeded - this.currentSoakTime;
this.soakProgress = (float) ticksPassed / (float) ticksNeeded;
inventoryChanged = true;
}
if (!this.worldObj.isRemote) {
if (this.currentSoakTime == 0 && canSoak()) {
ITubWaterModifier modifier;
modifier = (ITubWaterModifier) this.tubItemStacks[0].getItem();
this.currentSoakTime = modifier
.getTicksNeeded(this.tubItemStacks[1]);
this.soakProgress = 0.0F;
inventoryChanged = true;
}
if (this.currentSoakTime == 1) {
soakItem();
this.soakProgress = 0.0F;
inventoryChanged = true;
}
}
if (inventoryChanged) {
this.onInventoryChanged();
sendUpdateToWatchingPlayers(this.worldObj, this.xCoord, this.zCoord);
}
}
|
diff --git a/sirocco-cimi-command-line-tools/src/main/java/org/ow2/sirocco/apis/rest/cimi/tools/MachineImageShowCommand.java b/sirocco-cimi-command-line-tools/src/main/java/org/ow2/sirocco/apis/rest/cimi/tools/MachineImageShowCommand.java
index 82a66f1..9414f1e 100644
--- a/sirocco-cimi-command-line-tools/src/main/java/org/ow2/sirocco/apis/rest/cimi/tools/MachineImageShowCommand.java
+++ b/sirocco-cimi-command-line-tools/src/main/java/org/ow2/sirocco/apis/rest/cimi/tools/MachineImageShowCommand.java
@@ -1,84 +1,76 @@
/**
*
* SIROCCO
* Copyright (C) 2011 France Telecom
* Contact: [email protected]
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* $Id$
*
*/
package org.ow2.sirocco.apis.rest.cimi.tools;
import java.util.List;
import org.nocrala.tools.texttablefmt.Table;
import org.ow2.sirocco.apis.rest.cimi.sdk.CimiClient;
import org.ow2.sirocco.apis.rest.cimi.sdk.CimiClientException;
import org.ow2.sirocco.apis.rest.cimi.sdk.MachineImage;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
import com.beust.jcommander.ParametersDelegate;
@Parameters(commandDescription = "show machine image")
public class MachineImageShowCommand implements Command {
@Parameter(description = "<machine image id>", required = true)
private List<String> machineImageIds;
@ParametersDelegate
private ResourceSelectExpandParams showParams = new ResourceSelectExpandParams();
@Override
public String getName() {
return "machineimage-show";
}
@Override
public void execute(final CimiClient cimiClient) throws CimiClientException {
MachineImage machineImage = MachineImage.getMachineImageByReference(cimiClient, this.machineImageIds.get(0),
this.showParams.getQueryParams());
MachineImageShowCommand.printMachineImage(machineImage, this.showParams);
}
public static void printMachineImage(final MachineImage machineImage, final ResourceSelectExpandParams showParams) {
Table table = CommandHelper.createResourceShowTable(machineImage, showParams);
- if (showParams.isSelected("state")) {
+ if (showParams.isSelected("state") && machineImage.getState() != null) {
table.addCell("state");
table.addCell(machineImage.getState().toString());
}
- if (showParams.isSelected("type")) {
+ if (showParams.isSelected("type") && machineImage.getType() != null) {
table.addCell("type");
- if (machineImage.getType() != null) {
- table.addCell(machineImage.getType().toString());
- } else {
- table.addCell("");
- }
+ table.addCell(machineImage.getType().toString());
}
- if (showParams.isSelected("imageLocation")) {
+ if (showParams.isSelected("imageLocation") && machineImage.getImageLocation() != null) {
table.addCell("image location");
table.addCell(machineImage.getImageLocation());
}
- if (showParams.isSelected("related image")) {
- table.addCell("related image");
- // TODO
- }
System.out.println(table.render());
}
}
| false | true | public static void printMachineImage(final MachineImage machineImage, final ResourceSelectExpandParams showParams) {
Table table = CommandHelper.createResourceShowTable(machineImage, showParams);
if (showParams.isSelected("state")) {
table.addCell("state");
table.addCell(machineImage.getState().toString());
}
if (showParams.isSelected("type")) {
table.addCell("type");
if (machineImage.getType() != null) {
table.addCell(machineImage.getType().toString());
} else {
table.addCell("");
}
}
if (showParams.isSelected("imageLocation")) {
table.addCell("image location");
table.addCell(machineImage.getImageLocation());
}
if (showParams.isSelected("related image")) {
table.addCell("related image");
// TODO
}
System.out.println(table.render());
}
| public static void printMachineImage(final MachineImage machineImage, final ResourceSelectExpandParams showParams) {
Table table = CommandHelper.createResourceShowTable(machineImage, showParams);
if (showParams.isSelected("state") && machineImage.getState() != null) {
table.addCell("state");
table.addCell(machineImage.getState().toString());
}
if (showParams.isSelected("type") && machineImage.getType() != null) {
table.addCell("type");
table.addCell(machineImage.getType().toString());
}
if (showParams.isSelected("imageLocation") && machineImage.getImageLocation() != null) {
table.addCell("image location");
table.addCell(machineImage.getImageLocation());
}
System.out.println(table.render());
}
|
diff --git a/test-integration/db/src/main/java/org/teiid/test/client/TestClientTransaction.java b/test-integration/db/src/main/java/org/teiid/test/client/TestClientTransaction.java
index d5e0346bbb..f6d38b0511 100644
--- a/test-integration/db/src/main/java/org/teiid/test/client/TestClientTransaction.java
+++ b/test-integration/db/src/main/java/org/teiid/test/client/TestClientTransaction.java
@@ -1,211 +1,211 @@
/*
* JBoss, Home of Professional Open Source.
* See the COPYRIGHT.txt file distributed with this work for information
* regarding copyright ownership. Some portions may be licensed
* to Red Hat, Inc. under one or more contributor license agreements.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*/
package org.teiid.test.client;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.teiid.test.client.results.TestResultStat;
import org.teiid.test.framework.TestLogger;
import org.teiid.test.framework.exception.QueryTestFailedException;
import org.teiid.test.framework.exception.TransactionRuntimeException;
import org.teiid.test.framework.query.AbstractQueryTransactionTest;
/**
* TestClientTransaction
*
* @author vanhalbert
*
*/
public class TestClientTransaction extends AbstractQueryTransactionTest {
private QueryScenario querySet = null;
private ExpectedResults expectedResults = null;
private QueryTest query = null;
private long endTS = 0;
private long beginTS = 0;
private int testStatus = TestResult.RESULT_STATE.TEST_SUCCESS;
private boolean errorExpected = false;
private String sql = null;
private boolean resultFromQuery = false;
private TestResultsSummary testResultsSummary;
public TestClientTransaction(QueryScenario querySet) {
super(querySet.getQueryScenarioIdentifier());
this.querySet = querySet;
}
public void init(TestResultsSummary testResultsSummary, ExpectedResults expectedResults, QueryTest query) {
this.query = query;
this.testResultsSummary = testResultsSummary;
this.expectedResults = expectedResults;
endTS = 0;
beginTS = 0;
testStatus = TestResult.RESULT_STATE.TEST_SUCCESS;
errorExpected = false;
resultFromQuery = false;
}
public String getTestName() {
return query.geQuerySetID() + ":" + (query.getQueryID()!=null?query.getQueryID():"NA");
}
@Override
public void before() {
// TODO Auto-generated method stub
super.before();
try {
this.errorExpected = expectedResults
.isExceptionExpected(query.getQueryID());
} catch (QueryTestFailedException e) {
// TODO Auto-generated catch block
throw new TransactionRuntimeException("ProgramError: "
+ e.getMessage());
}
}
@Override
public void testCase() throws Exception {
TestLogger.logDebug("expected error: " + this.errorExpected);
TestLogger.logDebug("ID: " + query.geQuerySetID() + "-" + query.getQueryID());
QuerySQL[] queries = query.getQueries();
int l = queries.length;
try {
// need to set this so the underlying query execution handles an
// error properly.
beginTS = System.currentTimeMillis();
for (int i= 0; i < l; i++) {
QuerySQL qsql = queries[i];
this.sql = qsql.getSql();
resultFromQuery = execute(sql, qsql.getParms());
- if (!resultFromQuery) {
+ if (qsql.getUpdateCnt() >= 0) {
this.assertUpdateCount(qsql.getUpdateCnt());
} else if (qsql.getRowCnt() >= 0) {
this.assertRowCount(qsql.getRowCnt());
}
}
} catch (Throwable t) {
this.setApplicationException(t);
} finally {
// Capture resp time
endTS = System.currentTimeMillis();
}
}
@Override
public void after() {
// TODO Auto-generated method stub
super.after();
TestResult rs = null;
Throwable resultException = null;
resultException = (this.getLastException() != null ? this
.getLastException() : this.getApplicationException());
if (resultException != null) {
if (this.exceptionExpected()) {
testStatus = TestResult.RESULT_STATE.TEST_EXPECTED_EXCEPTION;
} else {
testStatus = TestResult.RESULT_STATE.TEST_EXCEPTION;
}
}
rs = new TestResultStat(query.geQuerySetID(), query.getQueryID(), sql,
testStatus, beginTS, endTS, resultException, null);
this.querySet.handleTestResult(rs, this.internalResultSet, this.updateCount, resultFromQuery, sql);
this.testResultsSummary.addTestResult(query.geQuerySetID(), rs);
}
@Override
protected Statement createStatement() throws SQLException {
return this.internalConnection.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
}
// need to override this method because the abstract logic for throwing
// exceptions depends on this
@Override
public boolean exceptionExpected() {
return this.errorExpected;
}
/**
* Override the super cleanup() so that the connection to Teiid is not
* cleaned up at this time.
*
* This will be handled after all queries in the set have been executed.
*
* @see TestClient#runTest();
*
*/
@Override
public void cleanup() {
//
// NOTE: do not cleanup TestResults because {@link #getTestResult} is called
// after cleanup
}
}
| true | true | public void testCase() throws Exception {
TestLogger.logDebug("expected error: " + this.errorExpected);
TestLogger.logDebug("ID: " + query.geQuerySetID() + "-" + query.getQueryID());
QuerySQL[] queries = query.getQueries();
int l = queries.length;
try {
// need to set this so the underlying query execution handles an
// error properly.
beginTS = System.currentTimeMillis();
for (int i= 0; i < l; i++) {
QuerySQL qsql = queries[i];
this.sql = qsql.getSql();
resultFromQuery = execute(sql, qsql.getParms());
if (!resultFromQuery) {
this.assertUpdateCount(qsql.getUpdateCnt());
} else if (qsql.getRowCnt() >= 0) {
this.assertRowCount(qsql.getRowCnt());
}
}
} catch (Throwable t) {
this.setApplicationException(t);
} finally {
// Capture resp time
endTS = System.currentTimeMillis();
}
}
| public void testCase() throws Exception {
TestLogger.logDebug("expected error: " + this.errorExpected);
TestLogger.logDebug("ID: " + query.geQuerySetID() + "-" + query.getQueryID());
QuerySQL[] queries = query.getQueries();
int l = queries.length;
try {
// need to set this so the underlying query execution handles an
// error properly.
beginTS = System.currentTimeMillis();
for (int i= 0; i < l; i++) {
QuerySQL qsql = queries[i];
this.sql = qsql.getSql();
resultFromQuery = execute(sql, qsql.getParms());
if (qsql.getUpdateCnt() >= 0) {
this.assertUpdateCount(qsql.getUpdateCnt());
} else if (qsql.getRowCnt() >= 0) {
this.assertRowCount(qsql.getRowCnt());
}
}
} catch (Throwable t) {
this.setApplicationException(t);
} finally {
// Capture resp time
endTS = System.currentTimeMillis();
}
}
|
diff --git a/src/mmb/foss/aueb/icong/DrawableAreaView.java b/src/mmb/foss/aueb/icong/DrawableAreaView.java
index fddb5c7..2e75b22 100644
--- a/src/mmb/foss/aueb/icong/DrawableAreaView.java
+++ b/src/mmb/foss/aueb/icong/DrawableAreaView.java
@@ -1,307 +1,306 @@
package mmb.foss.aueb.icong;
import java.io.InputStream;
import java.util.ArrayList;
import mmb.foss.aueb.icong.boxes.Box;
import mmb.foss.aueb.icong.boxes.SavedState;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
public class DrawableAreaView extends View {
private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
private ArrayList<Box> boxes = new ArrayList<Box>();
private Context mContext;
private Box selectedBox = null;
private int pressedX, pressedY;
private int originalX, originalY;
private int[] buttonCenter = new int[2];
private int WIDTH, HEIGHT;
private ArrayList<BoxButtonPair[]> lines = new ArrayList<BoxButtonPair[]>();
private Box box = null;
private int buttonPressed = -1;
private int buttonHovered = -1;
private boolean drawingline = false;
private boolean foundPair = false;
private int lineStartX, lineStartY, lineCurrentX, lineCurrentY;
private long tap;
private final int DOUBLE_TAP_INTERVAL = (int) (0.3 * 1000);
private BitmapDrawable trash;
private boolean showTrash;
private int trashX, trashY;
private Box possibleTrash;
public DrawableAreaView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
mContext = context;
paint.setColor(Color.BLACK);
WIDTH = MainActivity.width;
HEIGHT = MainActivity.height;
boxes = SavedState.getBoxes();
lines = SavedState.getLines();
}
protected void onDraw(Canvas c) {
if (WIDTH == 0 || trash == null) {
WIDTH = this.getWidth();
HEIGHT = this.getHeight();
InputStream is = mContext.getResources().openRawResource(
R.drawable.trash);
Bitmap originalBitmap = BitmapFactory.decodeStream(is);
int w = WIDTH / 10, h = (w * originalBitmap.getHeight())
/ originalBitmap.getWidth();
trash = new BitmapDrawable(mContext.getResources(),
Bitmap.createScaledBitmap(originalBitmap, w, h, true));
trashX = (WIDTH - trash.getBitmap().getWidth()) / 2;
trashY = HEIGHT - 40;
}
for (Box box : boxes) {
// TODO: Zooming to be removed
box.setZoom(1.8);
c.drawBitmap(box.getBitmap(), box.getX(), box.getY(), null);
for (int i = 0; i < box.getNumOfButtons(); i++) {
if (box.isPressed(i)) {
buttonCenter = box.getButtonCenter(i);
c.drawCircle(buttonCenter[0], buttonCenter[1],
box.getButtonRadius(i), paint);
}
}
}
for (BoxButtonPair[] line : lines) {
Box box0 = line[0].getBox(), box1 = line[1].getBox();
int button0 = line[0].getButton(), button1 = line[1].getButton();
int[] center0 = box0.getButtonCenter(button0), center1 = box1
.getButtonCenter(button1);
c.drawLine(center0[0], center0[1], center1[0], center1[1], paint);
}
if (drawingline) {
c.drawLine(lineStartX, lineStartY, lineCurrentX, lineCurrentY,
paint);
}
if (showTrash) {
c.drawBitmap(trash.getBitmap(), trashX, trashY, paint);
}
}
public void addBox(Box box) {
int x, y;
if (mContext.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
y = getLower() + 15;
x = (WIDTH / 2) - (box.getWidth() / 2);
} else {
y = (HEIGHT / 2) - (box.getHeight() / 2);
x = getRighter() + 15;
}
box.setY(y);
box.setX(x);
boxes.add(box);
SavedState.addBox(box);
invalidate();
}
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (showTrash && onTrash(event.getX(), event.getY())) {
// if trash icon is visible and clicked delete the possibleTrash
// box
deleteBox(possibleTrash);
possibleTrash = null;
}
box = getBoxTouched((int) event.getX(), (int) event.getY());
if (box != null) {
// if we have touched inside a box
selectedBox = box;
buttonPressed = box.isButton((int) event.getX(),
(int) event.getY());
// TODO double tap implementation
long tap = System.currentTimeMillis();
if (System.currentTimeMillis() - this.tap < DOUBLE_TAP_INTERVAL) {
// if we have double tapped inside a box
System.out.println("this is double tap");
} else {
System.out.println("this is NOT double tap");
}
this.tap = tap;
if (buttonPressed == -1) {
// if we haven't touched the box's button
pressedX = (int) event.getX();
pressedY = (int) event.getY();
originalX = box.getX();
originalY = box.getY();
showTrash = true;
possibleTrash = box;
} else {
// if we have touched the box's button
showTrash = false;
possibleTrash = null;
if (buttonPressed >= box.getNoOfInputs()) {
// if button pressed is an output button
if (!box.isPressed(buttonPressed)) {
// if the button pressed wasn't pressed before
box.setButtonPressed(buttonPressed);
} else {
// if the button pressed was pressed before deletes
// this connection/line
removeLine(box,buttonPressed);
}
int[] center = box.getButtonCenter(buttonPressed);
lineStartX = center[0];
lineStartY = center[1];
lineCurrentX = lineStartX;
lineCurrentY = lineStartY;
drawingline = true;
}
invalidate();
selectedBox = null;
}
} else {
// if we haven't touched inside a box
showTrash = false;
possibleTrash = null;
}
break;
case MotionEvent.ACTION_MOVE:
if (selectedBox != null) {
// if we have selected a box by tapping once in it
selectedBox.setX((int) event.getX() - (pressedX - originalX));
selectedBox.setY((int) event.getY() - (pressedY - originalY));
invalidate();
}
if (drawingline) {
// if we have pressed a previously not pressed box's output
// button
lineCurrentX = (int) event.getX();
lineCurrentY = (int) event.getY();
Box boxHovered = getBoxTouched((int) event.getX(),
(int) event.getY());
if (boxHovered != null) {
// if we have drawned a line on another box
buttonHovered = boxHovered.isButton((int) event.getX(),
(int) event.getY());
if (buttonHovered != -1) {
- // if we have drawned a line on FIXME another's box's
- // button
- if (buttonHovered < boxHovered.getNoOfInputs()) {
+ // if we have drawned a line on another's box's button
+ if (buttonHovered < boxHovered.getNoOfInputs() && !boxHovered.isPressed(buttonHovered)) {
// if we have drawned a line on another's box's
// input button
int[] center = boxHovered
.getButtonCenter(buttonHovered);
lineStartX = center[0];
lineStartY = center[1];
boxHovered.setButtonPressed(buttonHovered);
drawingline = false;
BoxButtonPair[] line = {
new BoxButtonPair(box, buttonPressed),
new BoxButtonPair(boxHovered, buttonHovered) };
lines.add(line);
SavedState.addLine(line);
foundPair = true;
}
}
}
}
invalidate();
break;
case MotionEvent.ACTION_UP:
drawingline = false;
selectedBox = null;
// if when drawing a line stops and we haven'd reached another box's
// input button then erase the line and unpress the button
if (!foundPair && buttonPressed != -1 && box != null)
if (!((buttonPressed + 1) <= box.getNoOfInputs()))
box.unsetButtonPressed(buttonPressed);
foundPair = false;
pressedX = pressedY = originalX = originalY = 0;
// TODO implement here to pou peftei
invalidate();
return false;
}
return true;
}
// returns the lower pixel of the lower element
private int getLower() {
int y = 0;
for (Box box : boxes) {
if (y < box.getYY())
y = box.getYY();
}
return y;
}
// returns the righter pixel of the righter element
private int getRighter() {
int x = 0;
for (Box box : boxes) {
if (x < box.getXX())
x = box.getXX();
}
return x;
}
// returns the box that was touched
private Box getBoxTouched(int x, int y) {
for (Box b : boxes) {
if (b.isOnBox(x, y)) {
return b;
}
}
return null;
}
private boolean onTrash(float f, float g) {
boolean isOnTrash = false;
if (f >= trashX && f <= (trashX + trash.getBitmap().getWidth())
&& g >= trashY && g <= (trashY + trash.getBitmap().getHeight())) {
isOnTrash = true;
}
return isOnTrash;
}
private void deleteBox(Box box2del) {
boxes.remove(box2del);
removeLines(box2del);
SavedState.removeBox(box2del);
}
private void removeLine(Box box, int button) {
BoxButtonPair pair = new BoxButtonPair(box, button);
for (BoxButtonPair[] line : lines) {
if (line[0].equals(pair)) {
Box otherBox = line[1].getBox();
int otherButton = line[1].getButton();
lines.remove(line);
SavedState.removeLine(line);
otherBox.unsetButtonPressed(otherButton);
break;
} else if (line[1].equals(pair)) {
Box otherBox = line[0].getBox();
int otherButton = line[0].getButton();
lines.remove(line);
SavedState.removeLine(line);
otherBox.unsetButtonPressed(otherButton);
break;
}
}
}
private void removeLines(Box box) {
for (int i = 0; i < box.getNumOfButtons(); i++) {
removeLine(box, i);
}
}
}
| true | true | public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (showTrash && onTrash(event.getX(), event.getY())) {
// if trash icon is visible and clicked delete the possibleTrash
// box
deleteBox(possibleTrash);
possibleTrash = null;
}
box = getBoxTouched((int) event.getX(), (int) event.getY());
if (box != null) {
// if we have touched inside a box
selectedBox = box;
buttonPressed = box.isButton((int) event.getX(),
(int) event.getY());
// TODO double tap implementation
long tap = System.currentTimeMillis();
if (System.currentTimeMillis() - this.tap < DOUBLE_TAP_INTERVAL) {
// if we have double tapped inside a box
System.out.println("this is double tap");
} else {
System.out.println("this is NOT double tap");
}
this.tap = tap;
if (buttonPressed == -1) {
// if we haven't touched the box's button
pressedX = (int) event.getX();
pressedY = (int) event.getY();
originalX = box.getX();
originalY = box.getY();
showTrash = true;
possibleTrash = box;
} else {
// if we have touched the box's button
showTrash = false;
possibleTrash = null;
if (buttonPressed >= box.getNoOfInputs()) {
// if button pressed is an output button
if (!box.isPressed(buttonPressed)) {
// if the button pressed wasn't pressed before
box.setButtonPressed(buttonPressed);
} else {
// if the button pressed was pressed before deletes
// this connection/line
removeLine(box,buttonPressed);
}
int[] center = box.getButtonCenter(buttonPressed);
lineStartX = center[0];
lineStartY = center[1];
lineCurrentX = lineStartX;
lineCurrentY = lineStartY;
drawingline = true;
}
invalidate();
selectedBox = null;
}
} else {
// if we haven't touched inside a box
showTrash = false;
possibleTrash = null;
}
break;
case MotionEvent.ACTION_MOVE:
if (selectedBox != null) {
// if we have selected a box by tapping once in it
selectedBox.setX((int) event.getX() - (pressedX - originalX));
selectedBox.setY((int) event.getY() - (pressedY - originalY));
invalidate();
}
if (drawingline) {
// if we have pressed a previously not pressed box's output
// button
lineCurrentX = (int) event.getX();
lineCurrentY = (int) event.getY();
Box boxHovered = getBoxTouched((int) event.getX(),
(int) event.getY());
if (boxHovered != null) {
// if we have drawned a line on another box
buttonHovered = boxHovered.isButton((int) event.getX(),
(int) event.getY());
if (buttonHovered != -1) {
// if we have drawned a line on FIXME another's box's
// button
if (buttonHovered < boxHovered.getNoOfInputs()) {
// if we have drawned a line on another's box's
// input button
int[] center = boxHovered
.getButtonCenter(buttonHovered);
lineStartX = center[0];
lineStartY = center[1];
boxHovered.setButtonPressed(buttonHovered);
drawingline = false;
BoxButtonPair[] line = {
new BoxButtonPair(box, buttonPressed),
new BoxButtonPair(boxHovered, buttonHovered) };
lines.add(line);
SavedState.addLine(line);
foundPair = true;
}
}
}
}
invalidate();
break;
case MotionEvent.ACTION_UP:
drawingline = false;
selectedBox = null;
// if when drawing a line stops and we haven'd reached another box's
// input button then erase the line and unpress the button
if (!foundPair && buttonPressed != -1 && box != null)
if (!((buttonPressed + 1) <= box.getNoOfInputs()))
box.unsetButtonPressed(buttonPressed);
foundPair = false;
pressedX = pressedY = originalX = originalY = 0;
// TODO implement here to pou peftei
invalidate();
return false;
}
return true;
}
| public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (showTrash && onTrash(event.getX(), event.getY())) {
// if trash icon is visible and clicked delete the possibleTrash
// box
deleteBox(possibleTrash);
possibleTrash = null;
}
box = getBoxTouched((int) event.getX(), (int) event.getY());
if (box != null) {
// if we have touched inside a box
selectedBox = box;
buttonPressed = box.isButton((int) event.getX(),
(int) event.getY());
// TODO double tap implementation
long tap = System.currentTimeMillis();
if (System.currentTimeMillis() - this.tap < DOUBLE_TAP_INTERVAL) {
// if we have double tapped inside a box
System.out.println("this is double tap");
} else {
System.out.println("this is NOT double tap");
}
this.tap = tap;
if (buttonPressed == -1) {
// if we haven't touched the box's button
pressedX = (int) event.getX();
pressedY = (int) event.getY();
originalX = box.getX();
originalY = box.getY();
showTrash = true;
possibleTrash = box;
} else {
// if we have touched the box's button
showTrash = false;
possibleTrash = null;
if (buttonPressed >= box.getNoOfInputs()) {
// if button pressed is an output button
if (!box.isPressed(buttonPressed)) {
// if the button pressed wasn't pressed before
box.setButtonPressed(buttonPressed);
} else {
// if the button pressed was pressed before deletes
// this connection/line
removeLine(box,buttonPressed);
}
int[] center = box.getButtonCenter(buttonPressed);
lineStartX = center[0];
lineStartY = center[1];
lineCurrentX = lineStartX;
lineCurrentY = lineStartY;
drawingline = true;
}
invalidate();
selectedBox = null;
}
} else {
// if we haven't touched inside a box
showTrash = false;
possibleTrash = null;
}
break;
case MotionEvent.ACTION_MOVE:
if (selectedBox != null) {
// if we have selected a box by tapping once in it
selectedBox.setX((int) event.getX() - (pressedX - originalX));
selectedBox.setY((int) event.getY() - (pressedY - originalY));
invalidate();
}
if (drawingline) {
// if we have pressed a previously not pressed box's output
// button
lineCurrentX = (int) event.getX();
lineCurrentY = (int) event.getY();
Box boxHovered = getBoxTouched((int) event.getX(),
(int) event.getY());
if (boxHovered != null) {
// if we have drawned a line on another box
buttonHovered = boxHovered.isButton((int) event.getX(),
(int) event.getY());
if (buttonHovered != -1) {
// if we have drawned a line on another's box's button
if (buttonHovered < boxHovered.getNoOfInputs() && !boxHovered.isPressed(buttonHovered)) {
// if we have drawned a line on another's box's
// input button
int[] center = boxHovered
.getButtonCenter(buttonHovered);
lineStartX = center[0];
lineStartY = center[1];
boxHovered.setButtonPressed(buttonHovered);
drawingline = false;
BoxButtonPair[] line = {
new BoxButtonPair(box, buttonPressed),
new BoxButtonPair(boxHovered, buttonHovered) };
lines.add(line);
SavedState.addLine(line);
foundPair = true;
}
}
}
}
invalidate();
break;
case MotionEvent.ACTION_UP:
drawingline = false;
selectedBox = null;
// if when drawing a line stops and we haven'd reached another box's
// input button then erase the line and unpress the button
if (!foundPair && buttonPressed != -1 && box != null)
if (!((buttonPressed + 1) <= box.getNoOfInputs()))
box.unsetButtonPressed(buttonPressed);
foundPair = false;
pressedX = pressedY = originalX = originalY = 0;
// TODO implement here to pou peftei
invalidate();
return false;
}
return true;
}
|
diff --git a/buildSrc/src/main/java/com/pieceof8/gradle/snapshot/SnapshotPlugin.java b/buildSrc/src/main/java/com/pieceof8/gradle/snapshot/SnapshotPlugin.java
index 32dfb75..6fa8355 100644
--- a/buildSrc/src/main/java/com/pieceof8/gradle/snapshot/SnapshotPlugin.java
+++ b/buildSrc/src/main/java/com/pieceof8/gradle/snapshot/SnapshotPlugin.java
@@ -1,77 +1,77 @@
// vi: set softtabstop=4 shiftwidth=4 expandtab:
/*
* Copyright 2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pieceof8.gradle.snapshot;
import org.gradle.api.Action;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.plugins.JavaPlugin;
import org.gradle.api.plugins.PluginContainer;
import org.gradle.api.tasks.Copy;
import org.gradle.api.tasks.SourceSetContainer;
import org.gradle.api.tasks.TaskContainer;
import lombok.*;
/**
* A Gradle plugin to generate build-time metadata from Source Control
* Management (SCM) tools.
*/
public class SnapshotPlugin implements Plugin<Project> {
/** The name of the snapshot task exposed to Gradle. */
public static final String SNAPSHOT_TASK_NAME = "snapshot";
/** {@inheritDoc} */
@Override
public void apply(final @NonNull Project project) {
project.getExtensions().add("snapshot",
new SnapshotPluginExtension(project));
configureSnapshot(project);
}
/**
* Configures the Snapshot task with the Gradle project and adds the task
* to the project. If the {@code JavaPlugin} is available, the snapshot
* task is configured to run just before it's <i>processResources</i> task.
*
* @param project The project POJO for this plugin.
*/
private void configureSnapshot(final @NonNull Project project) {
final TaskContainer tasks = project.getTasks();
final PluginContainer plugins = project.getPlugins();
- val task = tasks.add(SNAPSHOT_TASK_NAME, SnapshotTask.class);
+ val task = tasks.create(SNAPSHOT_TASK_NAME, SnapshotTask.class);
task.setDescription("Generates build information from an SCM repository.");
plugins.withType(JavaPlugin.class, new Action<JavaPlugin>() {
@Override
public void execute(final @NonNull JavaPlugin plugin) {
SourceSetContainer sourceSets = (SourceSetContainer)
project.getProperties().get("sourceSets");
sourceSets.getByName("main").getResources()
.srcDir(task.getSnapshotFile().getParentFile());
Copy resourcesTask = (Copy) tasks
.getByName(JavaPlugin.PROCESS_RESOURCES_TASK_NAME);
resourcesTask.dependsOn(task);
}
});
}
}
| true | true | private void configureSnapshot(final @NonNull Project project) {
final TaskContainer tasks = project.getTasks();
final PluginContainer plugins = project.getPlugins();
val task = tasks.add(SNAPSHOT_TASK_NAME, SnapshotTask.class);
task.setDescription("Generates build information from an SCM repository.");
plugins.withType(JavaPlugin.class, new Action<JavaPlugin>() {
@Override
public void execute(final @NonNull JavaPlugin plugin) {
SourceSetContainer sourceSets = (SourceSetContainer)
project.getProperties().get("sourceSets");
sourceSets.getByName("main").getResources()
.srcDir(task.getSnapshotFile().getParentFile());
Copy resourcesTask = (Copy) tasks
.getByName(JavaPlugin.PROCESS_RESOURCES_TASK_NAME);
resourcesTask.dependsOn(task);
}
});
}
| private void configureSnapshot(final @NonNull Project project) {
final TaskContainer tasks = project.getTasks();
final PluginContainer plugins = project.getPlugins();
val task = tasks.create(SNAPSHOT_TASK_NAME, SnapshotTask.class);
task.setDescription("Generates build information from an SCM repository.");
plugins.withType(JavaPlugin.class, new Action<JavaPlugin>() {
@Override
public void execute(final @NonNull JavaPlugin plugin) {
SourceSetContainer sourceSets = (SourceSetContainer)
project.getProperties().get("sourceSets");
sourceSets.getByName("main").getResources()
.srcDir(task.getSnapshotFile().getParentFile());
Copy resourcesTask = (Copy) tasks
.getByName(JavaPlugin.PROCESS_RESOURCES_TASK_NAME);
resourcesTask.dependsOn(task);
}
});
}
|
diff --git a/project/src/main/java/org/springframework/roo/project/PomManagementServiceImpl.java b/project/src/main/java/org/springframework/roo/project/PomManagementServiceImpl.java
index bf67e1769..dcb9d0ae1 100644
--- a/project/src/main/java/org/springframework/roo/project/PomManagementServiceImpl.java
+++ b/project/src/main/java/org/springframework/roo/project/PomManagementServiceImpl.java
@@ -1,320 +1,320 @@
package org.springframework.roo.project;
import static org.springframework.roo.support.util.FileUtils.CURRENT_DIRECTORY;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.osgi.service.component.ComponentContext;
import org.springframework.roo.file.monitor.FileMonitorService;
import org.springframework.roo.metadata.MetadataDependencyRegistry;
import org.springframework.roo.metadata.MetadataService;
import org.springframework.roo.process.manager.FileManager;
import org.springframework.roo.project.maven.Pom;
import org.springframework.roo.project.maven.PomFactory;
import org.springframework.roo.shell.Shell;
import org.springframework.roo.support.osgi.OSGiUtils;
import org.springframework.roo.support.util.Assert;
import org.springframework.roo.support.util.FileUtils;
import org.springframework.roo.support.util.StringUtils;
import org.springframework.roo.support.util.XmlUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
@Component
@Service
public class PomManagementServiceImpl implements PomManagementService {
// Constants
private static final String DEFAULT_POM_NAME = "pom.xml";
private static final String DEFAULT_RELATIVE_PATH = "../" + DEFAULT_POM_NAME;
// Fields
@Reference FileManager fileManager;
@Reference FileMonitorService fileMonitorService;
@Reference MetadataDependencyRegistry metadataDependencyRegistry;
@Reference MetadataService metadataService;
@Reference PomFactory pomFactory;
@Reference Shell shell;
private final Set<String> toBeParsed = new HashSet<String>();
private final Map<String, Pom> pomMap = new LinkedHashMap<String, Pom>(); // linked to preserve sort order
private String focusedModulePath;
private String projectRootDirectory;
// ------------------------ OSGi lifecycle callbacks -----------------------
protected void activate(final ComponentContext context) {
final File projectDirectory = new File(StringUtils.defaultIfEmpty(OSGiUtils.getRooWorkingDirectory(context), CURRENT_DIRECTORY));
projectRootDirectory = FileUtils.getCanonicalPath(projectDirectory);
}
// --------------------- PomManagementService methods ----------------------
public Pom getModuleForFileIdentifier(final String fileIdentifier) {
updatePomCache();
String startingPoint = FileUtils.getFirstDirectory(fileIdentifier);
String pomPath = FileUtils.ensureTrailingSeparator(startingPoint) + DEFAULT_POM_NAME;
File pom = new File(pomPath);
while (!pom.exists()) {
if (startingPoint.equals(File.separator)) {
break;
}
startingPoint = FileUtils.backOneDirectory(startingPoint);
pomPath = FileUtils.ensureTrailingSeparator(startingPoint) + DEFAULT_POM_NAME;
pom = new File(pomPath);
}
return getPomFromPath(pomPath);
}
public Pom getPomFromPath(final String pomPath) {
updatePomCache();
return pomMap.get(pomPath);
}
public Pom getPomFromModuleName(final String moduleName) {
for (final Pom pom : getPoms()) {
if (pom.getModuleName().equals(moduleName)) {
return pom;
}
}
return null;
}
public Collection<String> getModuleNames() {
final Set<String> moduleNames = new HashSet<String>();
for (final Pom module : pomMap.values()) {
moduleNames.add(module.getModuleName());
}
return moduleNames;
}
public Pom getRootPom() {
updatePomCache();
return pomMap.get(projectRootDirectory + File.separator + DEFAULT_POM_NAME);
}
public Pom getFocusedModule() {
updatePomCache();
if (focusedModulePath == null && getRootPom() != null) {
focusedModulePath = getRootPom().getPath();
}
return getPomFromPath(focusedModulePath);
}
public String getFocusedModuleName() {
if (getFocusedModule() == null) {
return "";
}
return getFocusedModule().getModuleName();
}
public void setFocusedModule(final Pom focusedModule) {
setFocusedModule(focusedModule.getPath());
}
public void setFocusedModule(final String focusedModulePath) {
Assert.hasText(focusedModulePath, "Module path required");
if (focusedModulePath.equals(this.focusedModulePath)) {
return;
}
this.focusedModulePath = focusedModulePath;
shell.setPromptPath(pomMap.get(focusedModulePath).getModuleName());
}
private void updatePomCache() {
findUnparsedPoms();
final Collection<Pom> newPoms = parseUnparsedPoms();
if (!newPoms.isEmpty()) {
sortPomMap();
}
updateProjectMetadataForModules(newPoms);
}
private void findUnparsedPoms() {
for (final String change : fileMonitorService.getDirtyFiles(getClass().getName())) {
if (change.endsWith(DEFAULT_POM_NAME)) {
toBeParsed.add(change);
}
}
}
private Set<Pom> parseUnparsedPoms() {
final Map<String, String> pomModuleMap = new HashMap<String, String>();
final Set<Pom> newPoms = new HashSet<Pom>();
for (final Iterator<String> iter = toBeParsed.iterator(); iter.hasNext();) {
final String pathToChangedPom = iter.next();
if (new File(pathToChangedPom).exists()) {
final String pomContents = FileUtils.read(new File(pathToChangedPom));
if (StringUtils.hasText(pomContents)) {
final Element rootElement = XmlUtils.stringToElement(pomContents);
resolvePoms(rootElement, pathToChangedPom, pomModuleMap);
final String moduleName = getModuleName(FileUtils.getFirstDirectory(pathToChangedPom));
final Pom pom = pomFactory.getInstance(rootElement, pathToChangedPom, moduleName);
Assert.notNull(pom, "POM is null for module = '" + moduleName + "' and path = '" + pathToChangedPom + "'");
pomMap.put(pathToChangedPom, pom);
newPoms.add(pom);
iter.remove();
}
}
}
return newPoms;
}
private String getModuleName(final String pomDirectory) {
final String normalisedRootPath = FileUtils.ensureTrailingSeparator(projectRootDirectory);
final String normalisedPomDirectory = FileUtils.ensureTrailingSeparator(pomDirectory);
final String moduleName = StringUtils.removePrefix(normalisedPomDirectory, normalisedRootPath);
return FileUtils.removeTrailingSeparator(moduleName);
}
private void resolvePoms(final Element pomRoot, final String pomPath, final Map<String, String> pomSet) {
pomSet.put(pomPath, pomSet.get(pomPath)); // ensures this key exists
final Element parentElement = XmlUtils.findFirstElement("/project/parent", pomRoot);
if (parentElement != null) {
resolveParentPom(pomPath, pomSet, parentElement);
}
resolveChildModulePoms(pomRoot, pomPath, pomSet);
}
private void resolveParentPom(final String pomPath, final Map<String, String> pomSet, final Element parentElement) {
final String relativePath = XmlUtils.getTextContent("/relativePath", parentElement, DEFAULT_RELATIVE_PATH);
final String parentPomPath = resolveRelativePath(pomPath, relativePath);
final boolean alreadyDiscovered = pomSet.containsKey(parentPomPath);
if (!alreadyDiscovered) {
pomSet.put(parentPomPath, pomSet.get(parentPomPath));
if (new File(parentPomPath).isFile()) {
final Document pomDocument = XmlUtils.readXml(fileManager.getInputStream(parentPomPath));
final Element root = pomDocument.getDocumentElement();
resolvePoms(root, parentPomPath, pomSet);
}
}
}
private void resolveChildModulePoms(final Element pomRoot, final String pomPath, final Map<String, String> pomSet) {
for (final Element module : XmlUtils.findElements("/project/modules/module", pomRoot)) {
final String moduleName = module.getTextContent();
if (StringUtils.hasText(moduleName)) {
final String modulePath = resolveRelativePath(pomPath, moduleName);
final boolean alreadyDiscovered = pomSet.containsKey(modulePath);
pomSet.put(modulePath, moduleName);
if (!alreadyDiscovered) {
final Document pomDocument = XmlUtils.readXml(fileManager.getInputStream(modulePath));
final Element root = pomDocument.getDocumentElement();
resolvePoms(root, modulePath, pomSet);
}
}
}
}
private String resolveRelativePath(String relativeTo, final String relativePath) {
if (relativeTo.endsWith(File.separator)) {
relativeTo = relativeTo.substring(0, relativeTo.length() - 1);
}
while (new File(relativeTo).isFile()) {
relativeTo = relativeTo.substring(0, relativeTo.lastIndexOf(File.separator));
}
final String[] relativePathSegments = relativePath.split(FileUtils.getFileSeparatorAsRegex());
int backCount = 0;
for (final String relativePathSegment : relativePathSegments) {
if (relativePathSegment.equals("..")) {
backCount++;
} else {
break;
}
}
final StringBuilder sb = new StringBuilder();
for (int i = backCount; i < relativePathSegments.length; i++) {
sb.append(relativePathSegments[i]);
- sb.append("/");
+ sb.append(File.separatorChar);
}
while (backCount > 0) {
relativeTo = relativeTo.substring(0, relativeTo.lastIndexOf(File.separatorChar));
backCount--;
}
String path = relativeTo + File.separator + sb.toString();
if (new File(path).isDirectory()) {
path = path + DEFAULT_POM_NAME;
}
if (path.endsWith(File.separator)) {
path = path.substring(0, path.length() - 1);
}
return path;
}
private void sortPomMap() {
final List<String> sortedPomPaths = new ArrayList<String>(pomMap.keySet());
Collections.sort(sortedPomPaths, new PomComparator(pomMap));
final Map<String, Pom> sortedPomMap = new LinkedHashMap<String, Pom>();
for (final String pomPath : sortedPomPaths) {
sortedPomMap.put(pomPath, pomMap.get(pomPath));
}
pomMap.clear();
pomMap.putAll(sortedPomMap);
}
private void updateProjectMetadataForModules(final Iterable<Pom> newPoms) {
for (final Pom pom : newPoms) {
final String projectMetadataId = ProjectMetadata.getProjectIdentifier(pom.getModuleName());
metadataService.evictAndGet(projectMetadataId);
metadataDependencyRegistry.notifyDownstream(projectMetadataId);
}
}
public Collection<Pom> getPoms() {
updatePomCache();
return new ArrayList<Pom>(pomMap.values());
}
/**
* For test cases to set up the state of this service
*
* @param pom the POM to add (required)
*/
void addPom(final Pom pom) {
pomMap.put(pom.getPath(), pom);
}
private static class PomComparator implements Comparator<String> {
// Fields
private final Map<String, Pom> pomMap;
/**
* Constructor
*
* @param pomMap
*/
private PomComparator(final Map<String, Pom> pomMap) {
this.pomMap = pomMap;
}
public int compare(final String s1, final String s2) {
final String p1 = pomMap.get(s1).getRoot() + File.separator;
final String p2 = pomMap.get(s2).getRoot() + File.separator;
if (p1.startsWith(p2)) {
return -1;
} else if (p2.startsWith(p1)) {
return 1;
}
return 0;
}
}
}
| true | true | private String resolveRelativePath(String relativeTo, final String relativePath) {
if (relativeTo.endsWith(File.separator)) {
relativeTo = relativeTo.substring(0, relativeTo.length() - 1);
}
while (new File(relativeTo).isFile()) {
relativeTo = relativeTo.substring(0, relativeTo.lastIndexOf(File.separator));
}
final String[] relativePathSegments = relativePath.split(FileUtils.getFileSeparatorAsRegex());
int backCount = 0;
for (final String relativePathSegment : relativePathSegments) {
if (relativePathSegment.equals("..")) {
backCount++;
} else {
break;
}
}
final StringBuilder sb = new StringBuilder();
for (int i = backCount; i < relativePathSegments.length; i++) {
sb.append(relativePathSegments[i]);
sb.append("/");
}
while (backCount > 0) {
relativeTo = relativeTo.substring(0, relativeTo.lastIndexOf(File.separatorChar));
backCount--;
}
String path = relativeTo + File.separator + sb.toString();
if (new File(path).isDirectory()) {
path = path + DEFAULT_POM_NAME;
}
if (path.endsWith(File.separator)) {
path = path.substring(0, path.length() - 1);
}
return path;
}
| private String resolveRelativePath(String relativeTo, final String relativePath) {
if (relativeTo.endsWith(File.separator)) {
relativeTo = relativeTo.substring(0, relativeTo.length() - 1);
}
while (new File(relativeTo).isFile()) {
relativeTo = relativeTo.substring(0, relativeTo.lastIndexOf(File.separator));
}
final String[] relativePathSegments = relativePath.split(FileUtils.getFileSeparatorAsRegex());
int backCount = 0;
for (final String relativePathSegment : relativePathSegments) {
if (relativePathSegment.equals("..")) {
backCount++;
} else {
break;
}
}
final StringBuilder sb = new StringBuilder();
for (int i = backCount; i < relativePathSegments.length; i++) {
sb.append(relativePathSegments[i]);
sb.append(File.separatorChar);
}
while (backCount > 0) {
relativeTo = relativeTo.substring(0, relativeTo.lastIndexOf(File.separatorChar));
backCount--;
}
String path = relativeTo + File.separator + sb.toString();
if (new File(path).isDirectory()) {
path = path + DEFAULT_POM_NAME;
}
if (path.endsWith(File.separator)) {
path = path.substring(0, path.length() - 1);
}
return path;
}
|
diff --git a/kafka-eight/src/main/java/io/druid/firehose/kafka/KafkaEightDruidModule.java b/kafka-eight/src/main/java/io/druid/firehose/kafka/KafkaEightDruidModule.java
index b8ccc93365..658b64bf82 100644
--- a/kafka-eight/src/main/java/io/druid/firehose/kafka/KafkaEightDruidModule.java
+++ b/kafka-eight/src/main/java/io/druid/firehose/kafka/KafkaEightDruidModule.java
@@ -1,51 +1,51 @@
/*
* Druid - a distributed column store.
* Copyright (C) 2012, 2013 Metamarkets Group Inc.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package io.druid.firehose.kafka;
import com.fasterxml.jackson.databind.Module;
import com.fasterxml.jackson.databind.jsontype.NamedType;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.google.inject.Binder;
import io.druid.initialization.DruidModule;
import java.util.Arrays;
import java.util.List;
/**
*/
public class KafkaEightDruidModule implements DruidModule
{
@Override
public List<? extends Module> getJacksonModules()
{
return Arrays.<Module>asList(
new SimpleModule("KafkaEightFirehoseModule")
.registerSubtypes(
- new NamedType(KafkaEightDruidModule.class, "kafka-0.8")
+ new NamedType(KafkaEightFirehoseFactory.class, "kafka-0.8")
)
);
}
@Override
public void configure(Binder binder)
{
}
}
| true | true | public List<? extends Module> getJacksonModules()
{
return Arrays.<Module>asList(
new SimpleModule("KafkaEightFirehoseModule")
.registerSubtypes(
new NamedType(KafkaEightDruidModule.class, "kafka-0.8")
)
);
}
| public List<? extends Module> getJacksonModules()
{
return Arrays.<Module>asList(
new SimpleModule("KafkaEightFirehoseModule")
.registerSubtypes(
new NamedType(KafkaEightFirehoseFactory.class, "kafka-0.8")
)
);
}
|
diff --git a/tests/frontend/org/voltdb/regressionsuites/MultiConfigSuiteBuilder.java b/tests/frontend/org/voltdb/regressionsuites/MultiConfigSuiteBuilder.java
index b30d18c6e..cc3414143 100644
--- a/tests/frontend/org/voltdb/regressionsuites/MultiConfigSuiteBuilder.java
+++ b/tests/frontend/org/voltdb/regressionsuites/MultiConfigSuiteBuilder.java
@@ -1,161 +1,163 @@
/* This file is part of VoltDB.
* Copyright (C) 2008-2012 VoltDB Inc.
*
* 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 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.voltdb.regressionsuites;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* A subclass of TestSuite that multiplexes test methods across
* all volt configurations given to it. For example, if there are
* 7 test methods and 2 volt configurations, this TestSuite will
* contain 14 tests and will munge names to descibe each test
* individually. This class is typically used as a helper in a
* TestCase's suite() method.
*
*/
public class MultiConfigSuiteBuilder extends TestSuite {
/** The class that contains the JUnit test methods to run */
Class<? extends TestCase> m_testClass = null;
/**
* Get the JUnit test methods for a given class. These methods have no
* parameters, return void and start with "test".
*
* @param testCls The class that contains the JUnit test methods to run.
* @return A list of the names of each JUnit test method.
*/
static List<String> getTestMethodNames(Class<? extends TestCase> testCls) {
ArrayList<String> retval = new ArrayList<String>();
for (Method m : testCls.getMethods()) {
if (m.getReturnType() != void.class)
continue;
if (m.getParameterTypes().length > 0)
continue;
if (m.getName().startsWith("test") == false)
continue;
retval.add(m.getName());
}
return retval;
}
/**
* Initialize by passing in a class that contains JUnit test methods to run.
*
* @param testClass The class that contains the JUnit test methods to run.
*/
public MultiConfigSuiteBuilder(Class<? extends TestCase> testClass) {
m_testClass = testClass;
}
/**
* Add a sever configuration to the set of configurations we want these
* tests to run on.
*
* @param config A Server Configuration to run this set of tests on.
*/
public boolean addServerConfig(VoltServerConfig config) {
final String enabled_configs = System.getenv().get("VOLT_REGRESSIONS");
System.out.println("VOLT REGRESSIONS ENABLED: " + enabled_configs);
if (!(enabled_configs == null || enabled_configs.contentEquals("all")))
{
if ((config instanceof LocalCluster) &&
!(enabled_configs.contains("cluster")))
{
return true;
}
- if ((config instanceof LocalSingleProcessServer) &&
- !(enabled_configs.contains("local")))
+ if (config instanceof LocalSingleProcessServer)
{
- return true;
- }
- if (config.isHSQL() && !(enabled_configs.contains("hsql")))
- {
- return true;
+ if (config.isHSQL()) {
+ if (!enabled_configs.contains("hsql")) {
+ return true;
+ }
+ }
+ else if (!enabled_configs.contains("local")) {
+ return true;
+ }
}
}
final String buildType = System.getenv().get("BUILD");
if (buildType != null) {
if (buildType.startsWith("memcheck")) {
if (config instanceof LocalCluster) {
return true;
}
if (config.isHSQL()) {
return true;
}
}
}
// get the constructor of the test class
Constructor<?> cons = null;
try {
cons = m_testClass.getConstructor(String.class);
} catch (Exception e) {
e.printStackTrace();
return false;
}
// get the set of test methods
List<String> methods = getTestMethodNames(m_testClass);
// add a test case instance for each method for the specified
// server config
for (String mname : methods) {
RegressionSuite rs = null;
try {
rs = (RegressionSuite) cons.newInstance(mname);
} catch (Exception e) {
e.printStackTrace();
return false;
}
rs.setConfig(config);
super.addTest(rs);
}
return true;
}
@Override
public void addTest(Test test) {
// don't let users do this
throw new RuntimeException("Unsupported Usage");
}
@Override
public void addTestSuite(Class<? extends TestCase> testClass) {
// don't let users do this
throw new RuntimeException("Unsupported Usage");
}
}
| false | true | public boolean addServerConfig(VoltServerConfig config) {
final String enabled_configs = System.getenv().get("VOLT_REGRESSIONS");
System.out.println("VOLT REGRESSIONS ENABLED: " + enabled_configs);
if (!(enabled_configs == null || enabled_configs.contentEquals("all")))
{
if ((config instanceof LocalCluster) &&
!(enabled_configs.contains("cluster")))
{
return true;
}
if ((config instanceof LocalSingleProcessServer) &&
!(enabled_configs.contains("local")))
{
return true;
}
if (config.isHSQL() && !(enabled_configs.contains("hsql")))
{
return true;
}
}
final String buildType = System.getenv().get("BUILD");
if (buildType != null) {
if (buildType.startsWith("memcheck")) {
if (config instanceof LocalCluster) {
return true;
}
if (config.isHSQL()) {
return true;
}
}
}
// get the constructor of the test class
Constructor<?> cons = null;
try {
cons = m_testClass.getConstructor(String.class);
} catch (Exception e) {
e.printStackTrace();
return false;
}
// get the set of test methods
List<String> methods = getTestMethodNames(m_testClass);
// add a test case instance for each method for the specified
// server config
for (String mname : methods) {
RegressionSuite rs = null;
try {
rs = (RegressionSuite) cons.newInstance(mname);
} catch (Exception e) {
e.printStackTrace();
return false;
}
rs.setConfig(config);
super.addTest(rs);
}
return true;
}
| public boolean addServerConfig(VoltServerConfig config) {
final String enabled_configs = System.getenv().get("VOLT_REGRESSIONS");
System.out.println("VOLT REGRESSIONS ENABLED: " + enabled_configs);
if (!(enabled_configs == null || enabled_configs.contentEquals("all")))
{
if ((config instanceof LocalCluster) &&
!(enabled_configs.contains("cluster")))
{
return true;
}
if (config instanceof LocalSingleProcessServer)
{
if (config.isHSQL()) {
if (!enabled_configs.contains("hsql")) {
return true;
}
}
else if (!enabled_configs.contains("local")) {
return true;
}
}
}
final String buildType = System.getenv().get("BUILD");
if (buildType != null) {
if (buildType.startsWith("memcheck")) {
if (config instanceof LocalCluster) {
return true;
}
if (config.isHSQL()) {
return true;
}
}
}
// get the constructor of the test class
Constructor<?> cons = null;
try {
cons = m_testClass.getConstructor(String.class);
} catch (Exception e) {
e.printStackTrace();
return false;
}
// get the set of test methods
List<String> methods = getTestMethodNames(m_testClass);
// add a test case instance for each method for the specified
// server config
for (String mname : methods) {
RegressionSuite rs = null;
try {
rs = (RegressionSuite) cons.newInstance(mname);
} catch (Exception e) {
e.printStackTrace();
return false;
}
rs.setConfig(config);
super.addTest(rs);
}
return true;
}
|
diff --git a/src/main/java/org/apache/giraph/graph/Vertex.java b/src/main/java/org/apache/giraph/graph/Vertex.java
index 2c9fc88..8f9d056 100644
--- a/src/main/java/org/apache/giraph/graph/Vertex.java
+++ b/src/main/java/org/apache/giraph/graph/Vertex.java
@@ -1,199 +1,199 @@
/*
* 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.giraph.graph;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableComparable;
import org.apache.log4j.Logger;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
/**
* User applications should all subclass {@link Vertex}. Package access
* should prevent users from accessing internal methods.
*
* @param <I> Vertex index value
* @param <V> Vertex value
* @param <E> Edge value
* @param <M> Message value
*/
@SuppressWarnings("rawtypes")
public abstract class Vertex<I extends WritableComparable, V extends Writable,
E extends Writable, M extends Writable>
extends MutableVertex<I, V, E, M> {
/** Class logger */
private static final Logger LOG = Logger.getLogger(Vertex.class);
/** Vertex id */
private I vertexId = null;
/** Vertex value */
private V vertexValue = null;
/** Map of destination vertices and their edge values */
private final SortedMap<I, Edge<I, E>> destEdgeMap =
new TreeMap<I, Edge<I, E>>();
/** If true, do not do anymore computation on this vertex. */
boolean halt = false;
/** List of incoming messages from the previous superstep */
private final List<M> msgList = new ArrayList<M>();
@Override
public void preApplication()
throws InstantiationException, IllegalAccessException {
// Do nothing, might be overriden by the user
}
@Override
public void postApplication() {
// Do nothing, might be overriden by the user
}
@Override
public void preSuperstep() {
// Do nothing, might be overriden by the user
}
@Override
public void postSuperstep() {
// Do nothing, might be overriden by the user
}
@Override
public final boolean addEdge(Edge<I, E> edge) {
edge.setConf(getContext().getConfiguration());
if (destEdgeMap.put(edge.getDestVertexId(), edge) != null) {
if (LOG.isDebugEnabled()) {
LOG.debug("addEdge: Vertex=" + vertexId +
": already added an edge value for dest vertex id " +
edge.getDestVertexId());
}
return false;
} else {
return true;
}
}
@Override
public final void setVertexId(I vertexId) {
this.vertexId = vertexId;
}
@Override
public final I getVertexId() {
return vertexId;
}
@Override
public final V getVertexValue() {
return vertexValue;
}
@Override
public final void setVertexValue(V vertexValue) {
this.vertexValue = vertexValue;
}
@Override
public final SortedMap<I, Edge<I, E>> getOutEdgeMap() {
return destEdgeMap;
}
@Override
public final void sendMsgToAllEdges(M msg) {
if (msg == null) {
throw new IllegalArgumentException(
"sendMsgToAllEdges: Cannot send null message to all edges");
}
for (Edge<I, E> edge : destEdgeMap.values()) {
sendMsg(edge.getDestVertexId(), msg);
}
}
@Override
public final void voteToHalt() {
halt = true;
}
@Override
public final boolean isHalted() {
return halt;
}
@Override
final public void readFields(DataInput in) throws IOException {
vertexId =
- BspUtils.createVertexIndex(getContext().getConfiguration());
+ BspUtils.<I>createVertexIndex(getContext().getConfiguration());
vertexId.readFields(in);
boolean hasVertexValue = in.readBoolean();
if (hasVertexValue) {
vertexValue =
- BspUtils.createVertexValue(getContext().getConfiguration());
+ BspUtils.<V>createVertexValue(getContext().getConfiguration());
vertexValue.readFields(in);
}
long edgeMapSize = in.readLong();
for (long i = 0; i < edgeMapSize; ++i) {
Edge<I, E> edge = new Edge<I, E>();
edge.setConf(getContext().getConfiguration());
edge.readFields(in);
addEdge(edge);
}
long msgListSize = in.readLong();
for (long i = 0; i < msgListSize; ++i) {
M msg =
- BspUtils.createMessageValue(getContext().getConfiguration());
+ BspUtils.<M>createMessageValue(getContext().getConfiguration());
msg.readFields(in);
msgList.add(msg);
}
halt = in.readBoolean();
}
@Override
final public void write(DataOutput out) throws IOException {
vertexId.write(out);
out.writeBoolean(vertexValue != null);
if (vertexValue != null) {
vertexValue.write(out);
}
out.writeLong(destEdgeMap.size());
for (Edge<I, E> edge : destEdgeMap.values()) {
edge.write(out);
}
out.writeLong(msgList.size());
for (M msg : msgList) {
msg.write(out);
}
out.writeBoolean(halt);
}
@Override
public List<M> getMsgList() {
return msgList;
}
@Override
public String toString() {
return "Vertex(id=" + getVertexId() + ",value=" + getVertexValue() +
",#edges=" + getOutEdgeMap().size() + ")";
}
}
| false | true | final public void readFields(DataInput in) throws IOException {
vertexId =
BspUtils.createVertexIndex(getContext().getConfiguration());
vertexId.readFields(in);
boolean hasVertexValue = in.readBoolean();
if (hasVertexValue) {
vertexValue =
BspUtils.createVertexValue(getContext().getConfiguration());
vertexValue.readFields(in);
}
long edgeMapSize = in.readLong();
for (long i = 0; i < edgeMapSize; ++i) {
Edge<I, E> edge = new Edge<I, E>();
edge.setConf(getContext().getConfiguration());
edge.readFields(in);
addEdge(edge);
}
long msgListSize = in.readLong();
for (long i = 0; i < msgListSize; ++i) {
M msg =
BspUtils.createMessageValue(getContext().getConfiguration());
msg.readFields(in);
msgList.add(msg);
}
halt = in.readBoolean();
}
| final public void readFields(DataInput in) throws IOException {
vertexId =
BspUtils.<I>createVertexIndex(getContext().getConfiguration());
vertexId.readFields(in);
boolean hasVertexValue = in.readBoolean();
if (hasVertexValue) {
vertexValue =
BspUtils.<V>createVertexValue(getContext().getConfiguration());
vertexValue.readFields(in);
}
long edgeMapSize = in.readLong();
for (long i = 0; i < edgeMapSize; ++i) {
Edge<I, E> edge = new Edge<I, E>();
edge.setConf(getContext().getConfiguration());
edge.readFields(in);
addEdge(edge);
}
long msgListSize = in.readLong();
for (long i = 0; i < msgListSize; ++i) {
M msg =
BspUtils.<M>createMessageValue(getContext().getConfiguration());
msg.readFields(in);
msgList.add(msg);
}
halt = in.readBoolean();
}
|
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestBackupNode.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestBackupNode.java
index fc56eb48c2..f01be4b99f 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestBackupNode.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestBackupNode.java
@@ -1,482 +1,483 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs.server.namenode;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Collections;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.impl.Log4JLogger;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.ha.HAServiceProtocol.HAServiceState;
import org.apache.hadoop.hdfs.DFSConfigKeys;
import org.apache.hadoop.hdfs.DFSTestUtil;
import org.apache.hadoop.hdfs.HAUtil;
import org.apache.hadoop.hdfs.HdfsConfiguration;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.hdfs.server.common.HdfsServerConstants.NamenodeRole;
import org.apache.hadoop.hdfs.server.common.HdfsServerConstants.StartupOption;
import org.apache.hadoop.hdfs.server.common.Storage.StorageDirectory;
import org.apache.hadoop.hdfs.server.namenode.FileJournalManager.EditLogFile;
import org.apache.hadoop.hdfs.server.protocol.NamenodeProtocols;
import org.apache.hadoop.net.NetUtils;
import org.apache.hadoop.test.GenericTestUtils;
import org.apache.log4j.Level;
import org.junit.Before;
import org.junit.Test;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
public class TestBackupNode {
public static final Log LOG = LogFactory.getLog(TestBackupNode.class);
static {
((Log4JLogger)Checkpointer.LOG).getLogger().setLevel(Level.ALL);
((Log4JLogger)BackupImage.LOG).getLogger().setLevel(Level.ALL);
}
static final String BASE_DIR = MiniDFSCluster.getBaseDirectory();
static final long seed = 0xDEADBEEFL;
static final int blockSize = 4096;
static final int fileSize = 8192;
@Before
public void setUp() throws Exception {
File baseDir = new File(BASE_DIR);
if(baseDir.exists())
if(!(FileUtil.fullyDelete(baseDir)))
throw new IOException("Cannot remove directory: " + baseDir);
File dirC = new File(getBackupNodeDir(StartupOption.CHECKPOINT, 1));
dirC.mkdirs();
File dirB = new File(getBackupNodeDir(StartupOption.BACKUP, 1));
dirB.mkdirs();
dirB = new File(getBackupNodeDir(StartupOption.BACKUP, 2));
dirB.mkdirs();
}
static String getBackupNodeDir(StartupOption t, int idx) {
return BASE_DIR + "name" + t.getName() + idx + "/";
}
BackupNode startBackupNode(Configuration conf,
StartupOption startupOpt,
int idx) throws IOException {
Configuration c = new HdfsConfiguration(conf);
String dirs = getBackupNodeDir(startupOpt, idx);
c.set(DFSConfigKeys.DFS_NAMENODE_NAME_DIR_KEY, dirs);
c.set(DFSConfigKeys.DFS_NAMENODE_EDITS_DIR_KEY,
"${" + DFSConfigKeys.DFS_NAMENODE_NAME_DIR_KEY + "}");
c.set(DFSConfigKeys.DFS_NAMENODE_BACKUP_ADDRESS_KEY,
"127.0.0.1:0");
c.set(DFSConfigKeys.DFS_NAMENODE_BACKUP_HTTP_ADDRESS_KEY,
"127.0.0.1:0");
BackupNode bn = (BackupNode)NameNode.createNameNode(
new String[]{startupOpt.getName()}, c);
assertTrue(bn.getRole() + " must be in SafeMode.", bn.isInSafeMode());
assertTrue(bn.getRole() + " must be in StandbyState",
bn.getNamesystem().getHAState()
.equalsIgnoreCase(HAServiceState.STANDBY.name()));
return bn;
}
void waitCheckpointDone(MiniDFSCluster cluster, long txid) {
long thisCheckpointTxId;
do {
try {
LOG.info("Waiting checkpoint to complete... " +
"checkpoint txid should increase above " + txid);
Thread.sleep(1000);
} catch (Exception e) {}
// The checkpoint is not done until the nn has received it from the bn
thisCheckpointTxId = cluster.getNameNode().getFSImage().getStorage()
.getMostRecentCheckpointTxId();
} while (thisCheckpointTxId < txid);
// Check that the checkpoint got uploaded to NN successfully
FSImageTestUtil.assertNNHasCheckpoints(cluster,
Collections.singletonList((int)thisCheckpointTxId));
}
@Test
public void testCheckpointNode() throws Exception {
testCheckpoint(StartupOption.CHECKPOINT);
}
/**
* Ensure that the backupnode will tail edits from the NN
* and keep in sync, even while the NN rolls, checkpoints
* occur, etc.
*/
@Test
public void testBackupNodeTailsEdits() throws Exception {
Configuration conf = new HdfsConfiguration();
HAUtil.setAllowStandbyReads(conf, true);
MiniDFSCluster cluster = null;
FileSystem fileSys = null;
BackupNode backup = null;
try {
cluster = new MiniDFSCluster.Builder(conf)
.numDataNodes(0).build();
fileSys = cluster.getFileSystem();
backup = startBackupNode(conf, StartupOption.BACKUP, 1);
BackupImage bnImage = (BackupImage) backup.getFSImage();
testBNInSync(cluster, backup, 1);
// Force a roll -- BN should roll with NN.
NameNode nn = cluster.getNameNode();
NamenodeProtocols nnRpc = nn.getRpcServer();
nnRpc.rollEditLog();
assertEquals(bnImage.getEditLog().getCurSegmentTxId(),
nn.getFSImage().getEditLog().getCurSegmentTxId());
// BN should stay in sync after roll
testBNInSync(cluster, backup, 2);
long nnImageBefore =
nn.getFSImage().getStorage().getMostRecentCheckpointTxId();
// BN checkpoint
backup.doCheckpoint();
// NN should have received a new image
long nnImageAfter =
nn.getFSImage().getStorage().getMostRecentCheckpointTxId();
assertTrue("nn should have received new checkpoint. before: " +
nnImageBefore + " after: " + nnImageAfter,
nnImageAfter > nnImageBefore);
// BN should stay in sync after checkpoint
testBNInSync(cluster, backup, 3);
// Stop BN
StorageDirectory sd = bnImage.getStorage().getStorageDir(0);
backup.stop();
backup = null;
// When shutting down the BN, it shouldn't finalize logs that are
// still open on the NN
EditLogFile editsLog = FSImageTestUtil.findLatestEditsLog(sd);
assertEquals(editsLog.getFirstTxId(),
nn.getFSImage().getEditLog().getCurSegmentTxId());
assertTrue("Should not have finalized " + editsLog,
editsLog.isInProgress());
// do some edits
assertTrue(fileSys.mkdirs(new Path("/edit-while-bn-down")));
// start a new backup node
backup = startBackupNode(conf, StartupOption.BACKUP, 1);
testBNInSync(cluster, backup, 4);
assertNotNull(backup.getNamesystem().getFileInfo("/edit-while-bn-down", false));
// Trigger an unclean shutdown of the backup node. Backup node will not
// unregister from the active when this is done simulating a node crash.
backup.stop(false);
// do some edits on the active. This should go through without failing.
// This will verify that active is still up and can add entries to
// master editlog.
assertTrue(fileSys.mkdirs(new Path("/edit-while-bn-down-2")));
} finally {
LOG.info("Shutting down...");
if (backup != null) backup.stop();
if (fileSys != null) fileSys.close();
if (cluster != null) cluster.shutdown();
}
assertStorageDirsMatch(cluster.getNameNode(), backup);
}
private void testBNInSync(MiniDFSCluster cluster, final BackupNode backup,
int testIdx) throws Exception {
final NameNode nn = cluster.getNameNode();
final FileSystem fs = cluster.getFileSystem();
// Do a bunch of namespace operations, make sure they're replicated
// to the BN.
for (int i = 0; i < 10; i++) {
final String src = "/test_" + testIdx + "_" + i;
LOG.info("Creating " + src + " on NN");
Path p = new Path(src);
assertTrue(fs.mkdirs(p));
GenericTestUtils.waitFor(new Supplier<Boolean>() {
@Override
public Boolean get() {
LOG.info("Checking for " + src + " on BN");
try {
boolean hasFile = backup.getNamesystem().getFileInfo(src, false) != null;
boolean txnIdMatch =
backup.getRpcServer().getTransactionID() ==
nn.getRpcServer().getTransactionID();
return hasFile && txnIdMatch;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}, 30, 10000);
}
assertStorageDirsMatch(nn, backup);
}
private void assertStorageDirsMatch(final NameNode nn, final BackupNode backup)
throws Exception {
// Check that the stored files in the name dirs are identical
List<File> dirs = Lists.newArrayList(
FSImageTestUtil.getCurrentDirs(nn.getFSImage().getStorage(),
null));
dirs.addAll(FSImageTestUtil.getCurrentDirs(backup.getFSImage().getStorage(),
null));
FSImageTestUtil.assertParallelFilesAreIdentical(dirs, ImmutableSet.of("VERSION"));
}
@Test
public void testBackupNode() throws Exception {
testCheckpoint(StartupOption.BACKUP);
}
void testCheckpoint(StartupOption op) throws Exception {
Path file1 = new Path("/checkpoint.dat");
Path file2 = new Path("/checkpoint2.dat");
Path file3 = new Path("/backup.dat");
Configuration conf = new HdfsConfiguration();
HAUtil.setAllowStandbyReads(conf, true);
short replication = (short)conf.getInt("dfs.replication", 3);
int numDatanodes = Math.max(3, replication);
+ conf.set(DFSConfigKeys.DFS_NAMENODE_BACKUP_HTTP_ADDRESS_KEY, "localhost:0");
conf.set(DFSConfigKeys.DFS_BLOCKREPORT_INITIAL_DELAY_KEY, "0");
conf.setInt(DFSConfigKeys.DFS_DATANODE_SCAN_PERIOD_HOURS_KEY, -1); // disable block scanner
conf.setInt(DFSConfigKeys.DFS_NAMENODE_CHECKPOINT_TXNS_KEY, 1);
MiniDFSCluster cluster = null;
FileSystem fileSys = null;
BackupNode backup = null;
try {
cluster = new MiniDFSCluster.Builder(conf)
.numDataNodes(0).build();
fileSys = cluster.getFileSystem();
//
// verify that 'format' really blew away all pre-existing files
//
assertTrue(!fileSys.exists(file1));
assertTrue(!fileSys.exists(file2));
//
// Create file1
//
assertTrue(fileSys.mkdirs(file1));
//
// Take a checkpoint
//
long txid = cluster.getNameNodeRpc().getTransactionID();
backup = startBackupNode(conf, op, 1);
waitCheckpointDone(cluster, txid);
} catch(IOException e) {
LOG.error("Error in TestBackupNode:", e);
assertTrue(e.getLocalizedMessage(), false);
} finally {
if(backup != null) backup.stop();
if(fileSys != null) fileSys.close();
if(cluster != null) cluster.shutdown();
}
File nnCurDir = new File(BASE_DIR, "name1/current/");
File bnCurDir = new File(getBackupNodeDir(op, 1), "/current/");
FSImageTestUtil.assertParallelFilesAreIdentical(
ImmutableList.of(bnCurDir, nnCurDir),
ImmutableSet.<String>of("VERSION"));
try {
//
// Restart cluster and verify that file1 still exist.
//
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(numDatanodes)
.format(false).build();
fileSys = cluster.getFileSystem();
// check that file1 still exists
assertTrue(fileSys.exists(file1));
fileSys.delete(file1, true);
// create new file file2
fileSys.mkdirs(file2);
//
// Take a checkpoint
//
long txid = cluster.getNameNodeRpc().getTransactionID();
backup = startBackupNode(conf, op, 1);
waitCheckpointDone(cluster, txid);
for (int i = 0; i < 10; i++) {
fileSys.mkdirs(new Path("file_" + i));
}
txid = cluster.getNameNodeRpc().getTransactionID();
backup.doCheckpoint();
waitCheckpointDone(cluster, txid);
txid = cluster.getNameNodeRpc().getTransactionID();
backup.doCheckpoint();
waitCheckpointDone(cluster, txid);
// Try BackupNode operations
InetSocketAddress add = backup.getNameNodeAddress();
// Write to BN
FileSystem bnFS = FileSystem.get(new Path("hdfs://"
+ NetUtils.getHostPortString(add)).toUri(), conf);
boolean canWrite = true;
try {
DFSTestUtil.createFile(bnFS, file3, fileSize, fileSize, blockSize,
replication, seed);
} catch (IOException eio) {
LOG.info("Write to " + backup.getRole() + " failed as expected: ", eio);
canWrite = false;
}
assertFalse("Write to BackupNode must be prohibited.", canWrite);
// Reads are allowed for BackupNode, but not for CheckpointNode
boolean canRead = true;
try {
bnFS.exists(file2);
} catch (IOException eio) {
LOG.info("Read from " + backup.getRole() + " failed: ", eio);
canRead = false;
}
assertEquals("Reads to BackupNode are allowed, but not CheckpointNode.",
canRead, backup.isRole(NamenodeRole.BACKUP));
DFSTestUtil.createFile(fileSys, file3, fileSize, fileSize, blockSize,
replication, seed);
TestCheckpoint.checkFile(fileSys, file3, replication);
// should also be on BN right away
assertTrue("file3 does not exist on BackupNode",
op != StartupOption.BACKUP ||
backup.getNamesystem().getFileInfo(
file3.toUri().getPath(), false) != null);
} catch(IOException e) {
LOG.error("Error in TestBackupNode:", e);
throw new AssertionError(e);
} finally {
if(backup != null) backup.stop();
if(fileSys != null) fileSys.close();
if(cluster != null) cluster.shutdown();
}
FSImageTestUtil.assertParallelFilesAreIdentical(
ImmutableList.of(bnCurDir, nnCurDir),
ImmutableSet.<String>of("VERSION"));
try {
//
// Restart cluster and verify that file2 exists and
// file1 does not exist.
//
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(0).format(false).build();
fileSys = cluster.getFileSystem();
assertTrue(!fileSys.exists(file1));
// verify that file2 exists
assertTrue(fileSys.exists(file2));
} catch(IOException e) {
LOG.error("Error in TestBackupNode: ", e);
assertTrue(e.getLocalizedMessage(), false);
} finally {
fileSys.close();
cluster.shutdown();
}
}
/**
* Verify that a file can be read both from NameNode and BackupNode.
*/
@Test
public void testCanReadData() throws IOException {
Path file1 = new Path("/fileToRead.dat");
Configuration conf = new HdfsConfiguration();
MiniDFSCluster cluster = null;
FileSystem fileSys = null;
BackupNode backup = null;
try {
// Start NameNode and BackupNode
cluster = new MiniDFSCluster.Builder(conf)
.numDataNodes(0).format(true).build();
fileSys = cluster.getFileSystem();
long txid = cluster.getNameNodeRpc().getTransactionID();
backup = startBackupNode(conf, StartupOption.BACKUP, 1);
waitCheckpointDone(cluster, txid);
// Setup dual NameNode configuration for DataNodes
String rpcAddrKeyPreffix =
DFSConfigKeys.DFS_NAMENODE_RPC_ADDRESS_KEY + ".bnCluster";
String nnAddr = cluster.getNameNode().getNameNodeAddressHostPortString();
conf.get(DFSConfigKeys.DFS_NAMENODE_RPC_ADDRESS_KEY);
String bnAddr = backup.getNameNodeAddressHostPortString();
conf.set(DFSConfigKeys.DFS_NAMESERVICES, "bnCluster");
conf.set(DFSConfigKeys.DFS_NAMESERVICE_ID, "bnCluster");
conf.set(DFSConfigKeys.DFS_HA_NAMENODES_KEY_PREFIX + ".bnCluster",
"nnActive, nnBackup");
conf.set(rpcAddrKeyPreffix + ".nnActive", nnAddr);
conf.set(rpcAddrKeyPreffix + ".nnBackup", bnAddr);
cluster.startDataNodes(conf, 3, true, StartupOption.REGULAR, null);
DFSTestUtil.createFile(
fileSys, file1, fileSize, fileSize, blockSize, (short)3, seed);
// Read the same file from file systems pointing to NN and BN
FileSystem bnFS = FileSystem.get(
new Path("hdfs://" + bnAddr).toUri(), conf);
String nnData = DFSTestUtil.readFile(fileSys, file1);
String bnData = DFSTestUtil.readFile(bnFS, file1);
assertEquals("Data read from BackupNode and NameNode is not the same.",
nnData, bnData);
} catch(IOException e) {
LOG.error("Error in TestBackupNode: ", e);
assertTrue(e.getLocalizedMessage(), false);
} finally {
if(fileSys != null) fileSys.close();
if(backup != null) backup.stop();
if(cluster != null) cluster.shutdown();
}
}
}
| true | true | void testCheckpoint(StartupOption op) throws Exception {
Path file1 = new Path("/checkpoint.dat");
Path file2 = new Path("/checkpoint2.dat");
Path file3 = new Path("/backup.dat");
Configuration conf = new HdfsConfiguration();
HAUtil.setAllowStandbyReads(conf, true);
short replication = (short)conf.getInt("dfs.replication", 3);
int numDatanodes = Math.max(3, replication);
conf.set(DFSConfigKeys.DFS_BLOCKREPORT_INITIAL_DELAY_KEY, "0");
conf.setInt(DFSConfigKeys.DFS_DATANODE_SCAN_PERIOD_HOURS_KEY, -1); // disable block scanner
conf.setInt(DFSConfigKeys.DFS_NAMENODE_CHECKPOINT_TXNS_KEY, 1);
MiniDFSCluster cluster = null;
FileSystem fileSys = null;
BackupNode backup = null;
try {
cluster = new MiniDFSCluster.Builder(conf)
.numDataNodes(0).build();
fileSys = cluster.getFileSystem();
//
// verify that 'format' really blew away all pre-existing files
//
assertTrue(!fileSys.exists(file1));
assertTrue(!fileSys.exists(file2));
//
// Create file1
//
assertTrue(fileSys.mkdirs(file1));
//
// Take a checkpoint
//
long txid = cluster.getNameNodeRpc().getTransactionID();
backup = startBackupNode(conf, op, 1);
waitCheckpointDone(cluster, txid);
} catch(IOException e) {
LOG.error("Error in TestBackupNode:", e);
assertTrue(e.getLocalizedMessage(), false);
} finally {
if(backup != null) backup.stop();
if(fileSys != null) fileSys.close();
if(cluster != null) cluster.shutdown();
}
File nnCurDir = new File(BASE_DIR, "name1/current/");
File bnCurDir = new File(getBackupNodeDir(op, 1), "/current/");
FSImageTestUtil.assertParallelFilesAreIdentical(
ImmutableList.of(bnCurDir, nnCurDir),
ImmutableSet.<String>of("VERSION"));
try {
//
// Restart cluster and verify that file1 still exist.
//
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(numDatanodes)
.format(false).build();
fileSys = cluster.getFileSystem();
// check that file1 still exists
assertTrue(fileSys.exists(file1));
fileSys.delete(file1, true);
// create new file file2
fileSys.mkdirs(file2);
//
// Take a checkpoint
//
long txid = cluster.getNameNodeRpc().getTransactionID();
backup = startBackupNode(conf, op, 1);
waitCheckpointDone(cluster, txid);
for (int i = 0; i < 10; i++) {
fileSys.mkdirs(new Path("file_" + i));
}
txid = cluster.getNameNodeRpc().getTransactionID();
backup.doCheckpoint();
waitCheckpointDone(cluster, txid);
txid = cluster.getNameNodeRpc().getTransactionID();
backup.doCheckpoint();
waitCheckpointDone(cluster, txid);
// Try BackupNode operations
InetSocketAddress add = backup.getNameNodeAddress();
// Write to BN
FileSystem bnFS = FileSystem.get(new Path("hdfs://"
+ NetUtils.getHostPortString(add)).toUri(), conf);
boolean canWrite = true;
try {
DFSTestUtil.createFile(bnFS, file3, fileSize, fileSize, blockSize,
replication, seed);
} catch (IOException eio) {
LOG.info("Write to " + backup.getRole() + " failed as expected: ", eio);
canWrite = false;
}
assertFalse("Write to BackupNode must be prohibited.", canWrite);
// Reads are allowed for BackupNode, but not for CheckpointNode
boolean canRead = true;
try {
bnFS.exists(file2);
} catch (IOException eio) {
LOG.info("Read from " + backup.getRole() + " failed: ", eio);
canRead = false;
}
assertEquals("Reads to BackupNode are allowed, but not CheckpointNode.",
canRead, backup.isRole(NamenodeRole.BACKUP));
DFSTestUtil.createFile(fileSys, file3, fileSize, fileSize, blockSize,
replication, seed);
TestCheckpoint.checkFile(fileSys, file3, replication);
// should also be on BN right away
assertTrue("file3 does not exist on BackupNode",
op != StartupOption.BACKUP ||
backup.getNamesystem().getFileInfo(
file3.toUri().getPath(), false) != null);
} catch(IOException e) {
LOG.error("Error in TestBackupNode:", e);
throw new AssertionError(e);
} finally {
if(backup != null) backup.stop();
if(fileSys != null) fileSys.close();
if(cluster != null) cluster.shutdown();
}
FSImageTestUtil.assertParallelFilesAreIdentical(
ImmutableList.of(bnCurDir, nnCurDir),
ImmutableSet.<String>of("VERSION"));
try {
//
// Restart cluster and verify that file2 exists and
// file1 does not exist.
//
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(0).format(false).build();
fileSys = cluster.getFileSystem();
assertTrue(!fileSys.exists(file1));
// verify that file2 exists
assertTrue(fileSys.exists(file2));
} catch(IOException e) {
LOG.error("Error in TestBackupNode: ", e);
assertTrue(e.getLocalizedMessage(), false);
} finally {
fileSys.close();
cluster.shutdown();
}
}
| void testCheckpoint(StartupOption op) throws Exception {
Path file1 = new Path("/checkpoint.dat");
Path file2 = new Path("/checkpoint2.dat");
Path file3 = new Path("/backup.dat");
Configuration conf = new HdfsConfiguration();
HAUtil.setAllowStandbyReads(conf, true);
short replication = (short)conf.getInt("dfs.replication", 3);
int numDatanodes = Math.max(3, replication);
conf.set(DFSConfigKeys.DFS_NAMENODE_BACKUP_HTTP_ADDRESS_KEY, "localhost:0");
conf.set(DFSConfigKeys.DFS_BLOCKREPORT_INITIAL_DELAY_KEY, "0");
conf.setInt(DFSConfigKeys.DFS_DATANODE_SCAN_PERIOD_HOURS_KEY, -1); // disable block scanner
conf.setInt(DFSConfigKeys.DFS_NAMENODE_CHECKPOINT_TXNS_KEY, 1);
MiniDFSCluster cluster = null;
FileSystem fileSys = null;
BackupNode backup = null;
try {
cluster = new MiniDFSCluster.Builder(conf)
.numDataNodes(0).build();
fileSys = cluster.getFileSystem();
//
// verify that 'format' really blew away all pre-existing files
//
assertTrue(!fileSys.exists(file1));
assertTrue(!fileSys.exists(file2));
//
// Create file1
//
assertTrue(fileSys.mkdirs(file1));
//
// Take a checkpoint
//
long txid = cluster.getNameNodeRpc().getTransactionID();
backup = startBackupNode(conf, op, 1);
waitCheckpointDone(cluster, txid);
} catch(IOException e) {
LOG.error("Error in TestBackupNode:", e);
assertTrue(e.getLocalizedMessage(), false);
} finally {
if(backup != null) backup.stop();
if(fileSys != null) fileSys.close();
if(cluster != null) cluster.shutdown();
}
File nnCurDir = new File(BASE_DIR, "name1/current/");
File bnCurDir = new File(getBackupNodeDir(op, 1), "/current/");
FSImageTestUtil.assertParallelFilesAreIdentical(
ImmutableList.of(bnCurDir, nnCurDir),
ImmutableSet.<String>of("VERSION"));
try {
//
// Restart cluster and verify that file1 still exist.
//
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(numDatanodes)
.format(false).build();
fileSys = cluster.getFileSystem();
// check that file1 still exists
assertTrue(fileSys.exists(file1));
fileSys.delete(file1, true);
// create new file file2
fileSys.mkdirs(file2);
//
// Take a checkpoint
//
long txid = cluster.getNameNodeRpc().getTransactionID();
backup = startBackupNode(conf, op, 1);
waitCheckpointDone(cluster, txid);
for (int i = 0; i < 10; i++) {
fileSys.mkdirs(new Path("file_" + i));
}
txid = cluster.getNameNodeRpc().getTransactionID();
backup.doCheckpoint();
waitCheckpointDone(cluster, txid);
txid = cluster.getNameNodeRpc().getTransactionID();
backup.doCheckpoint();
waitCheckpointDone(cluster, txid);
// Try BackupNode operations
InetSocketAddress add = backup.getNameNodeAddress();
// Write to BN
FileSystem bnFS = FileSystem.get(new Path("hdfs://"
+ NetUtils.getHostPortString(add)).toUri(), conf);
boolean canWrite = true;
try {
DFSTestUtil.createFile(bnFS, file3, fileSize, fileSize, blockSize,
replication, seed);
} catch (IOException eio) {
LOG.info("Write to " + backup.getRole() + " failed as expected: ", eio);
canWrite = false;
}
assertFalse("Write to BackupNode must be prohibited.", canWrite);
// Reads are allowed for BackupNode, but not for CheckpointNode
boolean canRead = true;
try {
bnFS.exists(file2);
} catch (IOException eio) {
LOG.info("Read from " + backup.getRole() + " failed: ", eio);
canRead = false;
}
assertEquals("Reads to BackupNode are allowed, but not CheckpointNode.",
canRead, backup.isRole(NamenodeRole.BACKUP));
DFSTestUtil.createFile(fileSys, file3, fileSize, fileSize, blockSize,
replication, seed);
TestCheckpoint.checkFile(fileSys, file3, replication);
// should also be on BN right away
assertTrue("file3 does not exist on BackupNode",
op != StartupOption.BACKUP ||
backup.getNamesystem().getFileInfo(
file3.toUri().getPath(), false) != null);
} catch(IOException e) {
LOG.error("Error in TestBackupNode:", e);
throw new AssertionError(e);
} finally {
if(backup != null) backup.stop();
if(fileSys != null) fileSys.close();
if(cluster != null) cluster.shutdown();
}
FSImageTestUtil.assertParallelFilesAreIdentical(
ImmutableList.of(bnCurDir, nnCurDir),
ImmutableSet.<String>of("VERSION"));
try {
//
// Restart cluster and verify that file2 exists and
// file1 does not exist.
//
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(0).format(false).build();
fileSys = cluster.getFileSystem();
assertTrue(!fileSys.exists(file1));
// verify that file2 exists
assertTrue(fileSys.exists(file2));
} catch(IOException e) {
LOG.error("Error in TestBackupNode: ", e);
assertTrue(e.getLocalizedMessage(), false);
} finally {
fileSys.close();
cluster.shutdown();
}
}
|
diff --git a/gui/src/main/java/org/jboss/as/console/client/shared/subsys/jca/JcaPresenter.java b/gui/src/main/java/org/jboss/as/console/client/shared/subsys/jca/JcaPresenter.java
index b0660f63..c17cb6f8 100644
--- a/gui/src/main/java/org/jboss/as/console/client/shared/subsys/jca/JcaPresenter.java
+++ b/gui/src/main/java/org/jboss/as/console/client/shared/subsys/jca/JcaPresenter.java
@@ -1,692 +1,693 @@
package org.jboss.as.console.client.shared.subsys.jca;
import com.google.gwt.event.shared.EventBus;
import com.google.inject.Inject;
import com.gwtplatform.mvp.client.Presenter;
import com.gwtplatform.mvp.client.View;
import com.gwtplatform.mvp.client.annotations.NameToken;
import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit;
import com.gwtplatform.mvp.client.proxy.Place;
import com.gwtplatform.mvp.client.proxy.PlaceManager;
import com.gwtplatform.mvp.client.proxy.PlaceRequest;
import com.gwtplatform.mvp.client.proxy.Proxy;
import org.jboss.as.console.client.Console;
import org.jboss.as.console.client.core.NameTokens;
import org.jboss.as.console.client.domain.model.SimpleCallback;
import org.jboss.as.console.client.shared.BeanFactory;
import org.jboss.as.console.client.shared.dispatch.DispatchAsync;
import org.jboss.as.console.client.shared.dispatch.impl.DMRAction;
import org.jboss.as.console.client.shared.dispatch.impl.DMRResponse;
import org.jboss.as.console.client.shared.properties.CreatePropertyCmd;
import org.jboss.as.console.client.shared.properties.DeletePropertyCmd;
import org.jboss.as.console.client.shared.properties.NewPropertyWizard;
import org.jboss.as.console.client.shared.properties.PropertyManagement;
import org.jboss.as.console.client.shared.properties.PropertyRecord;
import org.jboss.as.console.client.shared.subsys.Baseadress;
import org.jboss.as.console.client.shared.subsys.RevealStrategy;
import org.jboss.as.console.client.shared.subsys.jca.model.JcaArchiveValidation;
import org.jboss.as.console.client.shared.subsys.jca.model.JcaBootstrapContext;
import org.jboss.as.console.client.shared.subsys.jca.model.JcaConnectionManager;
import org.jboss.as.console.client.shared.subsys.jca.model.JcaWorkmanager;
import org.jboss.as.console.client.shared.subsys.jca.model.WorkmanagerPool;
import org.jboss.as.console.client.shared.viewframework.builder.ModalWindowLayout;
import org.jboss.as.console.client.widgets.forms.ApplicationMetaData;
import org.jboss.as.console.client.widgets.forms.BeanMetaData;
import org.jboss.as.console.client.widgets.forms.EntityAdapter;
import org.jboss.ballroom.client.widgets.window.DefaultWindow;
import org.jboss.dmr.client.ModelNode;
import org.jboss.dmr.client.Property;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.jboss.dmr.client.ModelDescriptionConstants.*;
/**
* @author Heiko Braun
* @date 11/29/11
*/
public class JcaPresenter extends Presenter<JcaPresenter.MyView, JcaPresenter.MyProxy>
implements PropertyManagement {
private final PlaceManager placeManager;
private RevealStrategy revealStrategy;
private ApplicationMetaData metaData;
private DispatchAsync dispatcher;
private BeanMetaData beanMetaData;
private BeanFactory factory;
private EntityAdapter<JcaBootstrapContext> boostrapAdapter;
private EntityAdapter<JcaBeanValidation> beanAdapter;
private EntityAdapter<JcaArchiveValidation> archiveAdapter;
private EntityAdapter<JcaConnectionManager> ccmAdapter;
private EntityAdapter<JcaWorkmanager> managerAdapter;
private LoadWorkmanagerCmd loadWorkManager;
private DefaultWindow window;
private DefaultWindow propertyWindow;
private List<JcaWorkmanager> managers;
private EntityAdapter<WorkmanagerPool> poolAdapter;
private String selectedWorkmanager;
@ProxyCodeSplit
@NameToken(NameTokens.JcaPresenter)
public interface MyProxy extends Proxy<JcaPresenter>, Place {
}
public interface MyView extends View {
void setPresenter(JcaPresenter presenter);
void setWorkManagers(List<JcaWorkmanager> managers);
void setBeanSettings(JcaBeanValidation jcaBeanValidation);
void setArchiveSettings(JcaArchiveValidation jcaArchiveValidation);
void setCCMSettings(JcaConnectionManager jcaConnectionManager);
void setBootstrapContexts(List<JcaBootstrapContext> contexts);
void setSelectedWorkmanager(String selectedWorkmanager);
}
@Inject
public JcaPresenter(
EventBus eventBus, MyView view, MyProxy proxy,
PlaceManager placeManager,
DispatchAsync dispatcher,
RevealStrategy revealStrategy,
ApplicationMetaData metaData, BeanFactory factory) {
super(eventBus, view, proxy);
this.placeManager = placeManager;
this.revealStrategy = revealStrategy;
this.metaData = metaData;
this.dispatcher = dispatcher;
this.beanMetaData = metaData.getBeanMetaData(JcaWorkmanager.class);
this.boostrapAdapter = new EntityAdapter<JcaBootstrapContext>(JcaBootstrapContext.class, metaData);
this.managerAdapter= new EntityAdapter<JcaWorkmanager>(JcaWorkmanager.class, metaData);
this.beanAdapter = new EntityAdapter<JcaBeanValidation>(JcaBeanValidation.class, metaData);
this.archiveAdapter = new EntityAdapter<JcaArchiveValidation>(JcaArchiveValidation.class, metaData);
this.ccmAdapter = new EntityAdapter<JcaConnectionManager>(JcaConnectionManager.class, metaData);
this.poolAdapter = new EntityAdapter<WorkmanagerPool>(WorkmanagerPool.class, metaData);
this.factory = factory;
this.loadWorkManager = new LoadWorkmanagerCmd(dispatcher, metaData);
}
@Override
protected void onBind() {
super.onBind();
getView().setPresenter(this);
}
@Override
protected void onReset() {
super.onReset();
loadJcaSubsystem();
loadWorkManager(true);
}
@Override
public void prepareFromRequest(PlaceRequest request) {
super.prepareFromRequest(request);
this.selectedWorkmanager = request.getParameter("name", null);
}
private void loadJcaSubsystem() {
ModelNode operation = new ModelNode();
operation.get(OP).set(COMPOSITE);
operation.get(ADDRESS).setEmptyList();
ModelNode archive = new ModelNode();
archive.get(ADDRESS).set(Baseadress.get());
archive.get(ADDRESS).add("subsystem", "jca");
archive.get(ADDRESS).add("archive-validation", "archive-validation");
archive.get(OP).set(READ_RESOURCE_OPERATION);
ModelNode bean = new ModelNode();
bean.get(ADDRESS).set(Baseadress.get());
bean.get(ADDRESS).add("subsystem", "jca");
bean.get(ADDRESS).add("bean-validation", "bean-validation");
bean.get(OP).set(READ_RESOURCE_OPERATION);
ModelNode ccm = new ModelNode();
ccm.get(ADDRESS).set(Baseadress.get());
ccm.get(ADDRESS).add("subsystem", "jca");
ccm.get(ADDRESS).add("cached-connection-manager", "cached-connection-manager");
ccm.get(OP).set(READ_RESOURCE_OPERATION);
List<ModelNode> steps = new ArrayList<ModelNode>(3);
steps.add(archive);
steps.add(bean);
steps.add(ccm);
operation.get(STEPS).set(steps);
dispatcher.execute(new DMRAction(operation), new SimpleCallback<DMRResponse>() {
@Override
public void onSuccess(DMRResponse result) {
ModelNode response = result.get();
List<Property> steps = response.get(RESULT).asPropertyList();
JcaArchiveValidation jcaArchiveValidation = archiveAdapter.fromDMR(
steps.get(0).getValue().get(RESULT).asObject()
);
JcaBeanValidation jcaBeanValidation = beanAdapter.fromDMR(
steps.get(1).getValue().get(RESULT).asObject()
);
JcaConnectionManager jcaConnectionManager = ccmAdapter.fromDMR(
steps.get(2).getValue().get(RESULT).asObject()
);
getView().setArchiveSettings(jcaArchiveValidation);
getView().setBeanSettings(jcaBeanValidation);
getView().setCCMSettings(jcaConnectionManager);
}
});
}
private void loadWorkManager() {
loadWorkManager(false);
}
private void loadWorkManager(final boolean retainSelection) {
loadWorkManager.execute(new SimpleCallback<List<JcaWorkmanager>>() {
@Override
public void onSuccess(List<JcaWorkmanager> result) {
JcaPresenter.this.managers = result;
getView().setWorkManagers(result);
// TODO: should only be invoked when called from onReset()
if(retainSelection)
getView().setSelectedWorkmanager(selectedWorkmanager);
else
getView().setSelectedWorkmanager(null);
loadBootstrapContexts();
}
});
}
private void loadBootstrapContexts() {
ModelNode operation = new ModelNode();
operation.get(OP).set(READ_CHILDREN_RESOURCES_OPERATION);
operation.get(ADDRESS).set(Baseadress.get());
operation.get(ADDRESS).add("subsystem", "jca");
operation.get(CHILD_TYPE).set("bootstrap-context");
operation.get(RECURSIVE).set(true);
dispatcher.execute(new DMRAction(operation), new SimpleCallback<DMRResponse>() {
@Override
public void onSuccess(DMRResponse result) {
ModelNode response = result.get();
List<Property> children = response.get(RESULT).asPropertyList();
List<JcaBootstrapContext> contexts = new ArrayList<JcaBootstrapContext>(children.size());
for(Property child : children)
{
ModelNode value = child.getValue();
JcaBootstrapContext entity = boostrapAdapter.fromDMR(value);
contexts.add(entity);
}
getView().setBootstrapContexts(contexts);
}
});
}
@Override
protected void revealInParent() {
revealStrategy.revealInParent(this);
}
public PlaceManager getPlaceManager() {
return placeManager;
}
public void onSaveArchiveSettings(Map<String, Object> changeset) {
ModelNode address = new ModelNode();
address.get(ADDRESS).set(Baseadress.get());
address.get(ADDRESS).add("subsystem", "jca");
address.get(ADDRESS).add("archive-validation", "archive-validation");
ModelNode operation = archiveAdapter.fromChangeset(changeset, address);
dispatcher.execute(new DMRAction(operation), new SimpleCallback<DMRResponse>() {
@Override
public void onSuccess(DMRResponse result) {
ModelNode response = result.get();
if(response.isFailure())
Console.error("Failed to update JCA settings", response.getFailureDescription());
else
Console.info("Success: Update JCA settings");
loadJcaSubsystem();
}
});
}
public void onSaveBeanSettings(Map<String, Object> changeset) {
ModelNode address = new ModelNode();
address.get(ADDRESS).set(Baseadress.get());
address.get(ADDRESS).add("subsystem", "jca");
address.get(ADDRESS).add("bean-validation", "bean-validation");
ModelNode operation = beanAdapter.fromChangeset(changeset, address);
dispatcher.execute(new DMRAction(operation), new SimpleCallback<DMRResponse>() {
@Override
public void onSuccess(DMRResponse result) {
ModelNode response = result.get();
if(response.isFailure())
Console.error("Failed to update JCA settings", response.getFailureDescription());
else
Console.info("Success: Update JCA settings");
loadJcaSubsystem();
}
});
}
public void onSaveCCMSettings(Map<String, Object> changeset) {
ModelNode address = new ModelNode();
address.get(ADDRESS).set(Baseadress.get());
address.get(ADDRESS).add("subsystem", "jca");
address.get(ADDRESS).add("cached-connection-manager", "cached-connection-manager");
ModelNode operation = ccmAdapter.fromChangeset(changeset, address);
dispatcher.execute(new DMRAction(operation), new SimpleCallback<DMRResponse>() {
@Override
public void onSuccess(DMRResponse result) {
ModelNode response = result.get();
if(response.isFailure())
Console.error("Failed to update JCA settings", response.getFailureDescription());
else
Console.info("Success: Update JCA settings");
loadJcaSubsystem();
}
});
}
public void onSaveBootstrapContext(final JcaBootstrapContext entity, Map<String, Object> changeset) {
ModelNode address = new ModelNode();
address.get(ADDRESS).set(Baseadress.get());
address.get(ADDRESS).add("subsystem", "jca");
address.get(ADDRESS).add("bootstrap-context", entity.getName());
ModelNode operation = boostrapAdapter.fromChangeset(changeset, address);
dispatcher.execute(new DMRAction(operation), new SimpleCallback<DMRResponse>() {
@Override
public void onSuccess(DMRResponse result) {
ModelNode response = result.get();
if(response.isFailure())
Console.error("Failed to update JCA settings", response.getFailureDescription());
else
Console.info("Success: Update JCA settings");
loadWorkManager();
}
});
}
public void onDeleteBootstrapContext(final JcaBootstrapContext entity) {
if(entity.getName().equals("default"))
{
Console.error(Console.CONSTANTS.subsys_jca_error_context_removal(), Console.CONSTANTS.subsys_jca_error_context_removal_desc());
return;
}
ModelNode operation = new ModelNode();
operation.get(ADDRESS).set(Baseadress.get());
operation.get(ADDRESS).add("subsystem", "jca");
operation.get(ADDRESS).add("bootstrap-context", entity.getName());
operation.get(OP).set(REMOVE);
dispatcher.execute(new DMRAction(operation), new SimpleCallback<DMRResponse>() {
@Override
public void onSuccess(DMRResponse result) {
ModelNode response = result.get();
if(response.isFailure())
Console.error("Failed to update JCA settings", response.getFailureDescription());
else
Console.info("Success: Update JCA settings");
loadWorkManager();
}
});
}
public void launchNewContextDialogue() {
window = new ModalWindowLayout()
.setTitle(Console.MESSAGES.createTitle("Bootstrap Context"))
.setWidget(new NewContextWizard(this, managers).asWidget())
.build();
}
public void createNewContext(final JcaBootstrapContext entity) {
closeDialoge();
ModelNode operation = boostrapAdapter.fromEntity(entity);
operation.get(ADDRESS).set(Baseadress.get());
operation.get(ADDRESS).add("subsystem", "jca");
operation.get(ADDRESS).add("bootstrap-context", entity.getName());
operation.get(OP).set(ADD);
dispatcher.execute(new DMRAction(operation), new SimpleCallback<DMRResponse>() {
@Override
public void onSuccess(DMRResponse result) {
ModelNode response = result.get();
if(response.isFailure())
Console.error(Console.MESSAGES.addingFailed("Bootstrap Context"), response.getFailureDescription());
else
Console.info(Console.MESSAGES.added("Bootstrap Context"));
loadWorkManager();
}
});
}
public void closeDialoge() {
window.hide();
}
public void launchNewManagerDialogue() {
window = new ModalWindowLayout()
.setTitle(Console.MESSAGES.createTitle("Work Manager"))
.setWidget(new NewManagerWizard(this).asWidget())
.build();
}
public void onDeleteManager(final JcaWorkmanager entity) {
if(entity.getName().equals("default"))
{
Console.error(Console.CONSTANTS.subsys_jca_error_default_workmanager_deletion());
return;
}
ModelNode operation = new ModelNode();
operation.get(ADDRESS).set(Baseadress.get());
operation.get(ADDRESS).add("subsystem", "jca");
operation.get(ADDRESS).add("workmanager", entity.getName());
operation.get(OP).set(REMOVE);
dispatcher.execute(new DMRAction(operation), new SimpleCallback<DMRResponse>() {
@Override
public void onSuccess(DMRResponse result) {
ModelNode response = result.get();
if(response.isFailure())
Console.error(Console.MESSAGES.deletionFailed("Work Manager"), response.getFailureDescription());
else
Console.info(Console.MESSAGES.deleted("Work Manager "+entity.getName() ));
loadWorkManager();
}
});
}
public void createNewManager(final JcaWorkmanager entity) {
closeDialoge();
if(null==entity.getShortRunning() || entity.getShortRunning().isEmpty())
{
// provide a default short running thread pool config (mandatory)
WorkmanagerPool pool = factory.WorkmanagerPool().as();
pool.setShortRunning(true);
- pool.setName("short-running-pool_" + entity.getName());
+ //pool.setName("short-running-pool_" + entity.getName());
+ pool.setName(entity.getName());
pool.setMaxThreads(10);
pool.setQueueLength(10);
List<WorkmanagerPool> managers = new ArrayList<WorkmanagerPool>(1);
managers.add(pool);
entity.setShortRunning(managers);
}
ModelNode operation = new ModelNode();
operation.get(ADDRESS).setEmptyList();
operation.get(OP).set(COMPOSITE);
ModelNode workmanagerOp = managerAdapter.fromEntity(entity);
workmanagerOp.get(ADDRESS).set(Baseadress.get());
workmanagerOp.get(ADDRESS).add("subsystem", "jca");
workmanagerOp.get(ADDRESS).add("workmanager", entity.getName());
workmanagerOp.get(OP).set(ADD);
WorkmanagerPool pool = entity.getShortRunning().get(0);
ModelNode poolOp = poolAdapter.fromEntity(pool);
poolOp.get(ADDRESS).set(Baseadress.get());
poolOp.get(ADDRESS).add("subsystem", "jca");
poolOp.get(ADDRESS).add("workmanager", entity.getName());
poolOp.get(OP).set(ADD);
if(pool.isShortRunning())
poolOp.get(ADDRESS).add("short-running-threads", pool.getName());
else
poolOp.get(ADDRESS).add("long-running-threads", pool.getName());
List<ModelNode> steps = new ArrayList<ModelNode>(2);
steps.add(workmanagerOp);
steps.add(poolOp);
operation.get(STEPS).set(steps);
dispatcher.execute(new DMRAction(operation), new SimpleCallback<DMRResponse>() {
@Override
public void onSuccess(DMRResponse result) {
ModelNode response = result.get();
if(response.isFailure())
{
Console.error(Console.MESSAGES.addingFailed("Work Manager"), response.getFailureDescription());
}
else
Console.info(Console.MESSAGES.added("Work Manager "+entity.getName()));
loadWorkManager();
}
});
}
// work manager
public void closePropertyDialoge() {
propertyWindow.hide();
}
public void launchNewPropertyDialoge(String reference) {
propertyWindow = new DefaultWindow(Console.MESSAGES.createTitle("Pool Property"));
propertyWindow.setWidth(320);
propertyWindow.setHeight(240);
propertyWindow.trapWidget(
new NewPropertyWizard(this, reference).asWidget()
);
propertyWindow.setGlassEnabled(true);
propertyWindow.center();
}
public void onCreateProperty(final String poolName, final PropertyRecord prop)
{
if(propertyWindow!=null && propertyWindow.isShowing())
{
propertyWindow.hide();
}
String[] tokens = poolName.split("/");
ModelNode address = new ModelNode();
address.set(Baseadress.get());
address.add("subsystem", "jca");
address.add("workmanager", tokens[0]);
address.add(tokens[1], tokens[2]);
address.add("properties", prop.getKey());
CreatePropertyCmd cmd = new CreatePropertyCmd(dispatcher, factory, address);
cmd.execute(prop, new SimpleCallback<Boolean>() {
@Override
public void onSuccess(Boolean result) {
loadWorkManager();
}
});
}
public void onDeleteProperty(final String poolName, final PropertyRecord prop)
{
String[] tokens = poolName.split("/");
ModelNode address = new ModelNode();
address.set(Baseadress.get());
address.add("subsystem", "jca");
address.add("workmanager", tokens[0]);
address.add(tokens[1], tokens[2]);
address.add("properties", prop.getKey());
DeletePropertyCmd cmd = new DeletePropertyCmd(dispatcher,factory,address);
cmd.execute(prop, new SimpleCallback<Boolean>() {
@Override
public void onSuccess(Boolean result) {
loadWorkManager();
}
});
}
@Override
public void onChangeProperty(String groupName, PropertyRecord prop) {
// do nothing
}
public void onSavePoolConfig(
String managerName,
final WorkmanagerPool entity,
Map<String, Object> changeset)
{
ModelNode address = new ModelNode();
address.get(ADDRESS).set(Baseadress.get());
address.get(ADDRESS).add("subsystem", "jca");
address.get(ADDRESS).add("workmanager", managerName);
if(entity.isShortRunning())
address.get(ADDRESS).add("short-running-threads", entity.getName());
else
address.get(ADDRESS).add("long-running-threads", entity.getName());
ModelNode operation = poolAdapter.fromChangeset(changeset, address);
dispatcher.execute(new DMRAction(operation), new SimpleCallback<DMRResponse>() {
@Override
public void onSuccess(DMRResponse result) {
ModelNode response = result.get();
if(response.isFailure())
Console.error(Console.MESSAGES.modificationFailed("Pool Config"), response.getFailureDescription());
else
Console.info(Console.MESSAGES.modified("Pool Config"));
loadWorkManager(true);
}
});
}
public void onRemovePoolConfig(
String managerName, WorkmanagerPool entity) {
ModelNode operation = new ModelNode();
operation.get(ADDRESS).set(Baseadress.get());
operation.get(ADDRESS).add("subsystem", "jca");
operation.get(ADDRESS).add("workmanager", managerName);
if(entity.isShortRunning())
operation.get(ADDRESS).add("short-running-threads", entity.getName());
else
operation.get(ADDRESS).add("long-running-threads", entity.getName());
operation.get(OP).set(REMOVE);
dispatcher.execute(new DMRAction(operation), new SimpleCallback<DMRResponse>() {
@Override
public void onSuccess(DMRResponse result) {
ModelNode response = result.get();
if(response.isFailure())
Console.error(Console.MESSAGES.deletionFailed("Pool Config"), response.getFailureDescription());
else
Console.info(Console.MESSAGES.deleted("Pool Config"));
loadWorkManager(true);
}
});
}
public void launchNewPoolDialoge(JcaWorkmanager entity) {
boolean hasShortRunning = entity.getShortRunning().size()>0;
boolean hasLongRunning = entity.getLongRunning().size()>0;
if(hasShortRunning && hasLongRunning)
{
Console.error(Console.CONSTANTS.subsys_jca_error_pool_exist(),
Console.CONSTANTS.subsys_jca_error_pool_exist_desc());
return;
}
window = new ModalWindowLayout()
.setTitle(Console.MESSAGES.createTitle("Pool Config"))
.setWidget(new NewPoolWizard(this, entity.getName()).asWidget())
.build();
}
public void createNewPool(String workManagerName, WorkmanagerPool pool) {
closeDialoge();
ModelNode operation = poolAdapter.fromEntity(pool);
operation.get(ADDRESS).set(Baseadress.get());
operation.get(ADDRESS).add("subsystem", "jca");
operation.get(ADDRESS).add("workmanager", workManagerName);
operation.get(OP).set(ADD);
if(pool.isShortRunning())
operation.get(ADDRESS).add("short-running-threads", pool.getName());
else
operation.get(ADDRESS).add("long-running-threads", pool.getName());
dispatcher.execute(new DMRAction(operation), new SimpleCallback<DMRResponse>() {
@Override
public void onSuccess(DMRResponse result) {
ModelNode response = result.get();
if(response.isFailure())
Console.error(Console.MESSAGES.addingFailed("Pool Config"), response.getFailureDescription());
else
Console.info(Console.MESSAGES.added("Pool Config"));
loadWorkManager(true);
}
});
}
}
| true | true | public void createNewManager(final JcaWorkmanager entity) {
closeDialoge();
if(null==entity.getShortRunning() || entity.getShortRunning().isEmpty())
{
// provide a default short running thread pool config (mandatory)
WorkmanagerPool pool = factory.WorkmanagerPool().as();
pool.setShortRunning(true);
pool.setName("short-running-pool_" + entity.getName());
pool.setMaxThreads(10);
pool.setQueueLength(10);
List<WorkmanagerPool> managers = new ArrayList<WorkmanagerPool>(1);
managers.add(pool);
entity.setShortRunning(managers);
}
ModelNode operation = new ModelNode();
operation.get(ADDRESS).setEmptyList();
operation.get(OP).set(COMPOSITE);
ModelNode workmanagerOp = managerAdapter.fromEntity(entity);
workmanagerOp.get(ADDRESS).set(Baseadress.get());
workmanagerOp.get(ADDRESS).add("subsystem", "jca");
workmanagerOp.get(ADDRESS).add("workmanager", entity.getName());
workmanagerOp.get(OP).set(ADD);
WorkmanagerPool pool = entity.getShortRunning().get(0);
ModelNode poolOp = poolAdapter.fromEntity(pool);
poolOp.get(ADDRESS).set(Baseadress.get());
poolOp.get(ADDRESS).add("subsystem", "jca");
poolOp.get(ADDRESS).add("workmanager", entity.getName());
poolOp.get(OP).set(ADD);
if(pool.isShortRunning())
poolOp.get(ADDRESS).add("short-running-threads", pool.getName());
else
poolOp.get(ADDRESS).add("long-running-threads", pool.getName());
List<ModelNode> steps = new ArrayList<ModelNode>(2);
steps.add(workmanagerOp);
steps.add(poolOp);
operation.get(STEPS).set(steps);
dispatcher.execute(new DMRAction(operation), new SimpleCallback<DMRResponse>() {
@Override
public void onSuccess(DMRResponse result) {
ModelNode response = result.get();
if(response.isFailure())
{
Console.error(Console.MESSAGES.addingFailed("Work Manager"), response.getFailureDescription());
}
else
Console.info(Console.MESSAGES.added("Work Manager "+entity.getName()));
loadWorkManager();
}
});
}
| public void createNewManager(final JcaWorkmanager entity) {
closeDialoge();
if(null==entity.getShortRunning() || entity.getShortRunning().isEmpty())
{
// provide a default short running thread pool config (mandatory)
WorkmanagerPool pool = factory.WorkmanagerPool().as();
pool.setShortRunning(true);
//pool.setName("short-running-pool_" + entity.getName());
pool.setName(entity.getName());
pool.setMaxThreads(10);
pool.setQueueLength(10);
List<WorkmanagerPool> managers = new ArrayList<WorkmanagerPool>(1);
managers.add(pool);
entity.setShortRunning(managers);
}
ModelNode operation = new ModelNode();
operation.get(ADDRESS).setEmptyList();
operation.get(OP).set(COMPOSITE);
ModelNode workmanagerOp = managerAdapter.fromEntity(entity);
workmanagerOp.get(ADDRESS).set(Baseadress.get());
workmanagerOp.get(ADDRESS).add("subsystem", "jca");
workmanagerOp.get(ADDRESS).add("workmanager", entity.getName());
workmanagerOp.get(OP).set(ADD);
WorkmanagerPool pool = entity.getShortRunning().get(0);
ModelNode poolOp = poolAdapter.fromEntity(pool);
poolOp.get(ADDRESS).set(Baseadress.get());
poolOp.get(ADDRESS).add("subsystem", "jca");
poolOp.get(ADDRESS).add("workmanager", entity.getName());
poolOp.get(OP).set(ADD);
if(pool.isShortRunning())
poolOp.get(ADDRESS).add("short-running-threads", pool.getName());
else
poolOp.get(ADDRESS).add("long-running-threads", pool.getName());
List<ModelNode> steps = new ArrayList<ModelNode>(2);
steps.add(workmanagerOp);
steps.add(poolOp);
operation.get(STEPS).set(steps);
dispatcher.execute(new DMRAction(operation), new SimpleCallback<DMRResponse>() {
@Override
public void onSuccess(DMRResponse result) {
ModelNode response = result.get();
if(response.isFailure())
{
Console.error(Console.MESSAGES.addingFailed("Work Manager"), response.getFailureDescription());
}
else
Console.info(Console.MESSAGES.added("Work Manager "+entity.getName()));
loadWorkManager();
}
});
}
|
diff --git a/src/com/fsck/k9/activity/setup/AccountSettings.java b/src/com/fsck/k9/activity/setup/AccountSettings.java
index 7ea0df0..44e36cf 100644
--- a/src/com/fsck/k9/activity/setup/AccountSettings.java
+++ b/src/com/fsck/k9/activity/setup/AccountSettings.java
@@ -1,954 +1,954 @@
package com.fsck.k9.activity.setup;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Vibrator;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.RingtonePreference;
import android.util.Log;
import android.view.KeyEvent;
import java.util.Map;
import java.util.LinkedList;
import java.util.List;
import com.fsck.k9.Account;
import com.fsck.k9.Account.FolderMode;
import com.fsck.k9.K9;
import com.fsck.k9.Preferences;
import com.fsck.k9.R;
import com.fsck.k9.mail.Folder;
import com.fsck.k9.activity.ChooseFolder;
import com.fsck.k9.activity.ChooseIdentity;
import com.fsck.k9.activity.ColorPickerDialog;
import com.fsck.k9.activity.K9PreferenceActivity;
import com.fsck.k9.activity.ManageIdentities;
import com.fsck.k9.controller.MessagingController;
import com.fsck.k9.crypto.Apg;
import com.fsck.k9.mail.Store;
import com.fsck.k9.service.MailService;
import com.fsck.k9.mail.store.LocalStore;
import com.fsck.k9.mail.store.StorageManager;
import com.fsck.k9.mail.store.LocalStore.LocalFolder;
import com.fsck.k9.mail.store.StorageManager.StorageProvider;
public class AccountSettings extends K9PreferenceActivity
{
private static final String EXTRA_ACCOUNT = "account";
private static final int SELECT_AUTO_EXPAND_FOLDER = 1;
private static final int ACTIVITY_MANAGE_IDENTITIES = 2;
private static final String PREFERENCE_DESCRIPTION = "account_description";
private static final String PREFERENCE_COMPOSITION = "composition";
private static final String PREFERENCE_MANAGE_IDENTITIES = "manage_identities";
private static final String PREFERENCE_FREQUENCY = "account_check_frequency";
private static final String PREFERENCE_DISPLAY_COUNT = "account_display_count";
private static final String PREFERENCE_DEFAULT = "account_default";
private static final String PREFERENCE_HIDE_BUTTONS = "hide_buttons_enum";
private static final String PREFERENCE_HIDE_MOVE_BUTTONS = "hide_move_buttons_enum";
private static final String PREFERENCE_SHOW_PICTURES = "show_pictures_enum";
private static final String PREFERENCE_ENABLE_MOVE_BUTTONS = "enable_move_buttons";
private static final String PREFERENCE_NOTIFY = "account_notify";
private static final String PREFERENCE_NOTIFY_SELF = "account_notify_self";
private static final String PREFERENCE_NOTIFY_SYNC = "account_notify_sync";
private static final String PREFERENCE_VIBRATE = "account_vibrate";
private static final String PREFERENCE_VIBRATE_PATTERN = "account_vibrate_pattern";
private static final String PREFERENCE_VIBRATE_TIMES = "account_vibrate_times";
private static final String PREFERENCE_RINGTONE = "account_ringtone";
private static final String PREFERENCE_NOTIFICATION_LED = "account_led";
private static final String PREFERENCE_INCOMING = "incoming";
private static final String PREFERENCE_OUTGOING = "outgoing";
private static final String PREFERENCE_DISPLAY_MODE = "folder_display_mode";
private static final String PREFERENCE_SYNC_MODE = "folder_sync_mode";
private static final String PREFERENCE_PUSH_MODE = "folder_push_mode";
private static final String PREFERENCE_PUSH_POLL_ON_CONNECT = "push_poll_on_connect";
private static final String PREFERENCE_MAX_PUSH_FOLDERS = "max_push_folders";
private static final String PREFERENCE_IDLE_REFRESH_PERIOD = "idle_refresh_period";
private static final String PREFERENCE_TARGET_MODE = "folder_target_mode";
private static final String PREFERENCE_DELETE_POLICY = "delete_policy";
private static final String PREFERENCE_EXPUNGE_POLICY = "expunge_policy";
private static final String PREFERENCE_AUTO_EXPAND_FOLDER = "account_setup_auto_expand_folder";
private static final String PREFERENCE_SEARCHABLE_FOLDERS = "searchable_folders";
private static final String PREFERENCE_CHIP_COLOR = "chip_color";
private static final String PREFERENCE_LED_COLOR = "led_color";
private static final String PREFERENCE_NOTIFICATION_OPENS_UNREAD = "notification_opens_unread";
private static final String PREFERENCE_MESSAGE_AGE = "account_message_age";
private static final String PREFERENCE_MESSAGE_SIZE = "account_autodownload_size";
private static final String PREFERENCE_SAVE_ALL_HEADERS = "account_save_all_headers";
private static final String PREFERENCE_QUOTE_PREFIX = "account_quote_prefix";
private static final String PREFERENCE_REPLY_AFTER_QUOTE = "reply_after_quote";
private static final String PREFERENCE_SYNC_REMOTE_DELETIONS = "account_sync_remote_deletetions";
private static final String PREFERENCE_CRYPTO_APP = "crypto_app";
private static final String PREFERENCE_CRYPTO_AUTO_SIGNATURE = "crypto_auto_signature";
private static final String PREFERENCE_LOCAL_STORAGE_PROVIDER = "local_storage_provider";
private static final String PREFERENCE_ARCHIVE_FOLDER = "archive_folder";
private static final String PREFERENCE_DRAFTS_FOLDER = "drafts_folder";
private static final String PREFERENCE_OUTBOX_FOLDER = "outbox_folder";
private static final String PREFERENCE_SENT_FOLDER = "sent_folder";
private static final String PREFERENCE_SPAM_FOLDER = "spam_folder";
private static final String PREFERENCE_TRASH_FOLDER = "trash_folder";
private Account mAccount;
private boolean mIsPushCapable = false;
private boolean mIsExpungeCapable = false;
private EditTextPreference mAccountDescription;
private ListPreference mCheckFrequency;
private ListPreference mDisplayCount;
private ListPreference mMessageAge;
private ListPreference mMessageSize;
private CheckBoxPreference mAccountDefault;
private CheckBoxPreference mAccountNotify;
private CheckBoxPreference mAccountNotifySelf;
private ListPreference mAccountHideButtons;
private ListPreference mAccountHideMoveButtons;
private ListPreference mAccountShowPictures;
private CheckBoxPreference mAccountEnableMoveButtons;
private CheckBoxPreference mAccountNotifySync;
private CheckBoxPreference mAccountVibrate;
private CheckBoxPreference mAccountLed;
private ListPreference mAccountVibratePattern;
private ListPreference mAccountVibrateTimes;
private RingtonePreference mAccountRingtone;
private ListPreference mDisplayMode;
private ListPreference mSyncMode;
private ListPreference mPushMode;
private ListPreference mTargetMode;
private ListPreference mDeletePolicy;
private ListPreference mExpungePolicy;
private ListPreference mSearchableFolders;
private ListPreference mAutoExpandFolder;
private Preference mChipColor;
private Preference mLedColor;
private boolean mIncomingChanged = false;
private CheckBoxPreference mNotificationOpensUnread;
private EditTextPreference mAccountQuotePrefix;
private CheckBoxPreference mReplyAfterQuote;
private CheckBoxPreference mSyncRemoteDeletions;
private CheckBoxPreference mSaveAllHeaders;
private CheckBoxPreference mPushPollOnConnect;
private ListPreference mIdleRefreshPeriod;
private ListPreference mMaxPushFolders;
private ListPreference mCryptoApp;
private CheckBoxPreference mCryptoAutoSignature;
private ListPreference mLocalStorageProvider;
private ListPreference mArchiveFolder;
private ListPreference mDraftsFolder;
private ListPreference mOutboxFolder;
private ListPreference mSentFolder;
private ListPreference mSpamFolder;
private ListPreference mTrashFolder;
public static void actionSettings(Context context, Account account)
{
Intent i = new Intent(context, AccountSettings.class);
i.putExtra(EXTRA_ACCOUNT, account.getUuid());
context.startActivity(i);
}
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
String accountUuid = getIntent().getStringExtra(EXTRA_ACCOUNT);
mAccount = Preferences.getPreferences(this).getAccount(accountUuid);
try
{
final Store store = mAccount.getRemoteStore();
mIsPushCapable = store.isPushCapable();
mIsExpungeCapable = store.isExpungeCapable();
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Could not get remote store", e);
}
addPreferencesFromResource(R.xml.account_settings_preferences);
mAccountDescription = (EditTextPreference) findPreference(PREFERENCE_DESCRIPTION);
mAccountDescription.setSummary(mAccount.getDescription());
mAccountDescription.setText(mAccount.getDescription());
mAccountDescription.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
mAccountDescription.setSummary(summary);
mAccountDescription.setText(summary);
return false;
}
});
mAccountQuotePrefix = (EditTextPreference) findPreference(PREFERENCE_QUOTE_PREFIX);
mAccountQuotePrefix.setSummary(mAccount.getQuotePrefix());
mAccountQuotePrefix.setText(mAccount.getQuotePrefix());
mAccountQuotePrefix.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
@Override
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String value = newValue.toString();
mAccountQuotePrefix.setSummary(value);
mAccountQuotePrefix.setText(value);
return false;
}
});
mReplyAfterQuote = (CheckBoxPreference) findPreference(PREFERENCE_REPLY_AFTER_QUOTE);
mReplyAfterQuote.setChecked(mAccount.isReplyAfterQuote());
mCheckFrequency = (ListPreference) findPreference(PREFERENCE_FREQUENCY);
mCheckFrequency.setValue(String.valueOf(mAccount.getAutomaticCheckIntervalMinutes()));
mCheckFrequency.setSummary(mCheckFrequency.getEntry());
mCheckFrequency.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mCheckFrequency.findIndexOfValue(summary);
mCheckFrequency.setSummary(mCheckFrequency.getEntries()[index]);
mCheckFrequency.setValue(summary);
return false;
}
});
mDisplayMode = (ListPreference) findPreference(PREFERENCE_DISPLAY_MODE);
mDisplayMode.setValue(mAccount.getFolderDisplayMode().name());
mDisplayMode.setSummary(mDisplayMode.getEntry());
mDisplayMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mDisplayMode.findIndexOfValue(summary);
mDisplayMode.setSummary(mDisplayMode.getEntries()[index]);
mDisplayMode.setValue(summary);
return false;
}
});
mSyncMode = (ListPreference) findPreference(PREFERENCE_SYNC_MODE);
mSyncMode.setValue(mAccount.getFolderSyncMode().name());
mSyncMode.setSummary(mSyncMode.getEntry());
mSyncMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mSyncMode.findIndexOfValue(summary);
mSyncMode.setSummary(mSyncMode.getEntries()[index]);
mSyncMode.setValue(summary);
return false;
}
});
mPushMode = (ListPreference) findPreference(PREFERENCE_PUSH_MODE);
mPushMode.setEnabled(mIsPushCapable);
mPushMode.setValue(mAccount.getFolderPushMode().name());
mPushMode.setSummary(mPushMode.getEntry());
mPushMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mPushMode.findIndexOfValue(summary);
mPushMode.setSummary(mPushMode.getEntries()[index]);
mPushMode.setValue(summary);
return false;
}
});
mTargetMode = (ListPreference) findPreference(PREFERENCE_TARGET_MODE);
mTargetMode.setValue(mAccount.getFolderTargetMode().name());
mTargetMode.setSummary(mTargetMode.getEntry());
mTargetMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mTargetMode.findIndexOfValue(summary);
mTargetMode.setSummary(mTargetMode.getEntries()[index]);
mTargetMode.setValue(summary);
return false;
}
});
mDeletePolicy = (ListPreference) findPreference(PREFERENCE_DELETE_POLICY);
mDeletePolicy.setValue("" + mAccount.getDeletePolicy());
mDeletePolicy.setSummary(mDeletePolicy.getEntry());
mDeletePolicy.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mDeletePolicy.findIndexOfValue(summary);
mDeletePolicy.setSummary(mDeletePolicy.getEntries()[index]);
mDeletePolicy.setValue(summary);
return false;
}
});
mExpungePolicy = (ListPreference) findPreference(PREFERENCE_EXPUNGE_POLICY);
mExpungePolicy.setEnabled(mIsExpungeCapable);
mExpungePolicy.setValue(mAccount.getExpungePolicy());
mExpungePolicy.setSummary(mExpungePolicy.getEntry());
mExpungePolicy.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mExpungePolicy.findIndexOfValue(summary);
mExpungePolicy.setSummary(mExpungePolicy.getEntries()[index]);
mExpungePolicy.setValue(summary);
return false;
}
});
mSyncRemoteDeletions = (CheckBoxPreference) findPreference(PREFERENCE_SYNC_REMOTE_DELETIONS);
mSyncRemoteDeletions.setChecked(mAccount.syncRemoteDeletions());
mSaveAllHeaders = (CheckBoxPreference) findPreference(PREFERENCE_SAVE_ALL_HEADERS);
mSaveAllHeaders.setChecked(mAccount.saveAllHeaders());
mSearchableFolders = (ListPreference) findPreference(PREFERENCE_SEARCHABLE_FOLDERS);
mSearchableFolders.setValue(mAccount.getSearchableFolders().name());
mSearchableFolders.setSummary(mSearchableFolders.getEntry());
mSearchableFolders.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mSearchableFolders.findIndexOfValue(summary);
mSearchableFolders.setSummary(mSearchableFolders.getEntries()[index]);
mSearchableFolders.setValue(summary);
return false;
}
});
mDisplayCount = (ListPreference) findPreference(PREFERENCE_DISPLAY_COUNT);
mDisplayCount.setValue(String.valueOf(mAccount.getDisplayCount()));
mDisplayCount.setSummary(mDisplayCount.getEntry());
mDisplayCount.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mDisplayCount.findIndexOfValue(summary);
mDisplayCount.setSummary(mDisplayCount.getEntries()[index]);
mDisplayCount.setValue(summary);
return false;
}
});
mMessageAge = (ListPreference) findPreference(PREFERENCE_MESSAGE_AGE);
mMessageAge.setValue(String.valueOf(mAccount.getMaximumPolledMessageAge()));
mMessageAge.setSummary(mMessageAge.getEntry());
mMessageAge.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mMessageAge.findIndexOfValue(summary);
mMessageAge.setSummary(mMessageAge.getEntries()[index]);
mMessageAge.setValue(summary);
return false;
}
});
mMessageSize = (ListPreference) findPreference(PREFERENCE_MESSAGE_SIZE);
mMessageSize.setValue(String.valueOf(mAccount.getMaximumAutoDownloadMessageSize()));
mMessageSize.setSummary(mMessageSize.getEntry());
mMessageSize.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mMessageSize.findIndexOfValue(summary);
mMessageSize.setSummary(mMessageSize.getEntries()[index]);
mMessageSize.setValue(summary);
return false;
}
});
mAccountDefault = (CheckBoxPreference) findPreference(PREFERENCE_DEFAULT);
mAccountDefault.setChecked(
mAccount.equals(Preferences.getPreferences(this).getDefaultAccount()));
mAccountHideButtons = (ListPreference) findPreference(PREFERENCE_HIDE_BUTTONS);
mAccountHideButtons.setValue("" + mAccount.getHideMessageViewButtons());
mAccountHideButtons.setSummary(mAccountHideButtons.getEntry());
mAccountHideButtons.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mAccountHideButtons.findIndexOfValue(summary);
mAccountHideButtons.setSummary(mAccountHideButtons.getEntries()[index]);
mAccountHideButtons.setValue(summary);
return false;
}
});
mAccountEnableMoveButtons = (CheckBoxPreference) findPreference(PREFERENCE_ENABLE_MOVE_BUTTONS);
mAccountEnableMoveButtons.setChecked(mAccount.getEnableMoveButtons());
mAccountHideMoveButtons = (ListPreference) findPreference(PREFERENCE_HIDE_MOVE_BUTTONS);
mAccountHideMoveButtons.setValue("" + mAccount.getHideMessageViewMoveButtons());
mAccountHideMoveButtons.setSummary(mAccountHideMoveButtons.getEntry());
mAccountHideMoveButtons.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mAccountHideMoveButtons.findIndexOfValue(summary);
mAccountHideMoveButtons.setSummary(mAccountHideMoveButtons.getEntries()[index]);
mAccountHideMoveButtons.setValue(summary);
return false;
}
});
mAccountShowPictures = (ListPreference) findPreference(PREFERENCE_SHOW_PICTURES);
mAccountShowPictures.setValue("" + mAccount.getShowPictures());
mAccountShowPictures.setSummary(mAccountShowPictures.getEntry());
mAccountShowPictures.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mAccountShowPictures.findIndexOfValue(summary);
mAccountShowPictures.setSummary(mAccountShowPictures.getEntries()[index]);
mAccountShowPictures.setValue(summary);
return false;
}
});
mLocalStorageProvider = (ListPreference) findPreference(PREFERENCE_LOCAL_STORAGE_PROVIDER);
{
final Map<String, String> providers;
providers = StorageManager.getInstance(K9.app).getAvailableProviders();
int i = 0;
final String[] providerLabels = new String[providers.size()];
final String[] providerIds = new String[providers.size()];
for (final Map.Entry<String, String> entry : providers.entrySet())
{
providerIds[i] = entry.getKey();
providerLabels[i] = entry.getValue();
i++;
}
mLocalStorageProvider.setEntryValues(providerIds);
mLocalStorageProvider.setEntries(providerLabels);
mLocalStorageProvider.setValue(mAccount.getLocalStorageProviderId());
mLocalStorageProvider.setSummary(providers.get((Object)mAccount.getLocalStorageProviderId()));
mLocalStorageProvider.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
mLocalStorageProvider.setSummary(providers.get(newValue));
return true;
}
});
}
// IMAP-specific preferences
mPushPollOnConnect = (CheckBoxPreference) findPreference(PREFERENCE_PUSH_POLL_ON_CONNECT);
mIdleRefreshPeriod = (ListPreference) findPreference(PREFERENCE_IDLE_REFRESH_PERIOD);
mMaxPushFolders = (ListPreference) findPreference(PREFERENCE_MAX_PUSH_FOLDERS);
if (mIsPushCapable)
{
mPushPollOnConnect.setChecked(mAccount.isPushPollOnConnect());
mIdleRefreshPeriod.setValue(String.valueOf(mAccount.getIdleRefreshMinutes()));
mIdleRefreshPeriod.setSummary(mIdleRefreshPeriod.getEntry());
mIdleRefreshPeriod.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mIdleRefreshPeriod.findIndexOfValue(summary);
mIdleRefreshPeriod.setSummary(mIdleRefreshPeriod.getEntries()[index]);
mIdleRefreshPeriod.setValue(summary);
return false;
}
});
mMaxPushFolders.setValue(String.valueOf(mAccount.getMaxPushFolders()));
mMaxPushFolders.setSummary(mMaxPushFolders.getEntry());
mMaxPushFolders.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mMaxPushFolders.findIndexOfValue(summary);
mMaxPushFolders.setSummary(mMaxPushFolders.getEntries()[index]);
mMaxPushFolders.setValue(summary);
return false;
}
});
}
else
{
mPushPollOnConnect.setEnabled(false);
mMaxPushFolders.setEnabled(false);
mIdleRefreshPeriod.setEnabled(false);
}
mAccountNotify = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFY);
mAccountNotify.setChecked(mAccount.isNotifyNewMail());
mAccountNotifySelf = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFY_SELF);
mAccountNotifySelf.setChecked(mAccount.isNotifySelfNewMail());
mAccountNotifySync = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFY_SYNC);
mAccountNotifySync.setChecked(mAccount.isShowOngoing());
mAccountRingtone = (RingtonePreference) findPreference(PREFERENCE_RINGTONE);
// XXX: The following two lines act as a workaround for the RingtonePreference
// which does not let us set/get the value programmatically
SharedPreferences prefs = mAccountRingtone.getPreferenceManager().getSharedPreferences();
String currentRingtone = (!mAccount.getNotificationSetting().shouldRing() ? null : mAccount.getNotificationSetting().getRingtone());
prefs.edit().putString(PREFERENCE_RINGTONE, currentRingtone).commit();
mAccountVibrate = (CheckBoxPreference) findPreference(PREFERENCE_VIBRATE);
mAccountVibrate.setChecked(mAccount.getNotificationSetting().isVibrate());
mAccountVibratePattern = (ListPreference) findPreference(PREFERENCE_VIBRATE_PATTERN);
mAccountVibratePattern.setValue(String.valueOf(mAccount.getNotificationSetting().getVibratePattern()));
mAccountVibratePattern.setSummary(mAccountVibratePattern.getEntry());
mAccountVibratePattern.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mAccountVibratePattern.findIndexOfValue(summary);
mAccountVibratePattern.setSummary(mAccountVibratePattern.getEntries()[index]);
mAccountVibratePattern.setValue(summary);
doVibrateTest(preference);
return false;
}
});
mAccountVibrateTimes = (ListPreference) findPreference(PREFERENCE_VIBRATE_TIMES);
mAccountVibrateTimes.setValue(String.valueOf(mAccount.getNotificationSetting().getVibrateTimes()));
mAccountVibrateTimes.setSummary(String.valueOf(mAccount.getNotificationSetting().getVibrateTimes()));
mAccountVibrateTimes.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
@Override
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String value = newValue.toString();
mAccountVibrateTimes.setSummary(value);
mAccountVibrateTimes.setValue(value);
doVibrateTest(preference);
return false;
}
});
mAccountLed = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFICATION_LED);
mAccountLed.setChecked(mAccount.getNotificationSetting().isLed());
mNotificationOpensUnread = (CheckBoxPreference)findPreference(PREFERENCE_NOTIFICATION_OPENS_UNREAD);
mNotificationOpensUnread.setChecked(mAccount.goToUnreadMessageSearch());
List<? extends Folder> folders = new LinkedList<LocalFolder>();;
try
{
folders = mAccount.getLocalStore().getPersonalNamespaces(false);
}
catch (Exception e)
{
/// this can't be checked in
}
final String[] allFolderValues = new String[folders.size()+2];
final String[] allFolderLabels = new String[folders.size()+2];
- allFolderValues[0] = "";
+ allFolderValues[0] = K9.FOLDER_NONE;
allFolderLabels[0] = K9.FOLDER_NONE;
// There's a non-zero chance that "outbox" won't actually exist, so we force it into the list
allFolderValues[1] = mAccount.getOutboxFolderName();
allFolderLabels[1] = mAccount.getOutboxFolderName();
int i =2;
for (Folder folder : folders)
{
allFolderLabels[i] = folder.getName();
allFolderValues[i] = folder.getName();
i++;
}
mAutoExpandFolder = (ListPreference)findPreference(PREFERENCE_AUTO_EXPAND_FOLDER);
initListPreference(mAutoExpandFolder, mAccount.getAutoExpandFolderName(), allFolderLabels,allFolderValues);
mArchiveFolder = (ListPreference)findPreference(PREFERENCE_ARCHIVE_FOLDER);
initListPreference(mArchiveFolder, mAccount.getArchiveFolderName(), allFolderLabels,allFolderValues);
mDraftsFolder = (ListPreference)findPreference(PREFERENCE_DRAFTS_FOLDER);
initListPreference(mDraftsFolder, mAccount.getDraftsFolderName(), allFolderLabels,allFolderValues);
mOutboxFolder = (ListPreference)findPreference(PREFERENCE_OUTBOX_FOLDER);
initListPreference(mOutboxFolder, mAccount.getOutboxFolderName(), allFolderLabels,allFolderValues);
mSentFolder = (ListPreference)findPreference(PREFERENCE_SENT_FOLDER);
initListPreference(mSentFolder, mAccount.getSentFolderName(), allFolderLabels,allFolderValues);
mSpamFolder = (ListPreference)findPreference(PREFERENCE_SPAM_FOLDER);
initListPreference(mSpamFolder, mAccount.getSpamFolderName(), allFolderLabels,allFolderValues);
mTrashFolder = (ListPreference)findPreference(PREFERENCE_TRASH_FOLDER);
initListPreference(mTrashFolder, mAccount.getTrashFolderName(), allFolderLabels,allFolderValues);
mChipColor = (Preference)findPreference(PREFERENCE_CHIP_COLOR);
mChipColor.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener()
{
public boolean onPreferenceClick(Preference preference)
{
onChooseChipColor();
return false;
}
});
mLedColor = (Preference)findPreference(PREFERENCE_LED_COLOR);
mLedColor.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener()
{
public boolean onPreferenceClick(Preference preference)
{
onChooseLedColor();
return false;
}
});
findPreference(PREFERENCE_COMPOSITION).setOnPreferenceClickListener(
new Preference.OnPreferenceClickListener()
{
public boolean onPreferenceClick(Preference preference)
{
onCompositionSettings();
return true;
}
});
findPreference(PREFERENCE_MANAGE_IDENTITIES).setOnPreferenceClickListener(
new Preference.OnPreferenceClickListener()
{
public boolean onPreferenceClick(Preference preference)
{
onManageIdentities();
return true;
}
});
findPreference(PREFERENCE_INCOMING).setOnPreferenceClickListener(
new Preference.OnPreferenceClickListener()
{
public boolean onPreferenceClick(Preference preference)
{
mIncomingChanged = true;
onIncomingSettings();
return true;
}
});
findPreference(PREFERENCE_OUTGOING).setOnPreferenceClickListener(
new Preference.OnPreferenceClickListener()
{
public boolean onPreferenceClick(Preference preference)
{
onOutgoingSettings();
return true;
}
});
mCryptoApp = (ListPreference) findPreference(PREFERENCE_CRYPTO_APP);
CharSequence cryptoAppEntries[] = mCryptoApp.getEntries();
if (!new Apg().isAvailable(this))
{
int apgIndex = mCryptoApp.findIndexOfValue(Apg.NAME);
if (apgIndex >= 0)
{
cryptoAppEntries[apgIndex] = "APG (" + getResources().getString(R.string.account_settings_crypto_app_not_available) + ")";
mCryptoApp.setEntries(cryptoAppEntries);
}
}
mCryptoApp.setValue(String.valueOf(mAccount.getCryptoApp()));
mCryptoApp.setSummary(mCryptoApp.getEntry());
mCryptoApp.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
String value = newValue.toString();
int index = mCryptoApp.findIndexOfValue(value);
mCryptoApp.setSummary(mCryptoApp.getEntries()[index]);
mCryptoApp.setValue(value);
handleCryptoAppDependencies();
if (Apg.NAME.equals(value))
{
Apg.createInstance(null).test(AccountSettings.this);
}
return false;
}
});
mCryptoAutoSignature = (CheckBoxPreference) findPreference(PREFERENCE_CRYPTO_AUTO_SIGNATURE);
mCryptoAutoSignature.setChecked(mAccount.getCryptoAutoSignature());
handleCryptoAppDependencies();
}
private void handleCryptoAppDependencies()
{
if ("".equals(mCryptoApp.getValue()))
{
mCryptoAutoSignature.setEnabled(false);
}
else
{
mCryptoAutoSignature.setEnabled(true);
}
}
@Override
public void onResume()
{
super.onResume();
}
private void saveSettings()
{
if (mAccountDefault.isChecked())
{
Preferences.getPreferences(this).setDefaultAccount(mAccount);
}
mAccount.setDescription(mAccountDescription.getText());
mAccount.setNotifyNewMail(mAccountNotify.isChecked());
mAccount.setNotifySelfNewMail(mAccountNotifySelf.isChecked());
mAccount.setShowOngoing(mAccountNotifySync.isChecked());
mAccount.setDisplayCount(Integer.parseInt(mDisplayCount.getValue()));
mAccount.setMaximumPolledMessageAge(Integer.parseInt(mMessageAge.getValue()));
mAccount.setMaximumAutoDownloadMessageSize(Integer.parseInt(mMessageSize.getValue()));
mAccount.getNotificationSetting().setVibrate(mAccountVibrate.isChecked());
mAccount.getNotificationSetting().setVibratePattern(Integer.parseInt(mAccountVibratePattern.getValue()));
mAccount.getNotificationSetting().setVibrateTimes(Integer.parseInt(mAccountVibrateTimes.getValue()));
mAccount.getNotificationSetting().setLed(mAccountLed.isChecked());
mAccount.setGoToUnreadMessageSearch(mNotificationOpensUnread.isChecked());
mAccount.setFolderTargetMode(Account.FolderMode.valueOf(mTargetMode.getValue()));
mAccount.setDeletePolicy(Integer.parseInt(mDeletePolicy.getValue()));
mAccount.setExpungePolicy(mExpungePolicy.getValue());
mAccount.setSyncRemoteDeletions(mSyncRemoteDeletions.isChecked());
mAccount.setSaveAllHeaders(mSaveAllHeaders.isChecked());
mAccount.setSearchableFolders(Account.Searchable.valueOf(mSearchableFolders.getValue()));
mAccount.setQuotePrefix(mAccountQuotePrefix.getText());
mAccount.setReplyAfterQuote(mReplyAfterQuote.isChecked());
mAccount.setCryptoApp(mCryptoApp.getValue());
mAccount.setCryptoAutoSignature(mCryptoAutoSignature.isChecked());
mAccount.setLocalStorageProviderId(mLocalStorageProvider.getValue());
mAccount.setAutoExpandFolderName(reverseTranslateFolder(mAutoExpandFolder.getValue().toString()));
mAccount.setArchiveFolderName(mArchiveFolder.getValue().toString());
mAccount.setDraftsFolderName(mDraftsFolder.getValue().toString());
mAccount.setOutboxFolderName(mOutboxFolder.getValue().toString());
mAccount.setSentFolderName(mSentFolder.getValue().toString());
mAccount.setSpamFolderName(mSpamFolder.getValue().toString());
mAccount.setTrashFolderName(mTrashFolder.getValue().toString());
if (mIsPushCapable)
{
mAccount.setPushPollOnConnect(mPushPollOnConnect.isChecked());
mAccount.setIdleRefreshMinutes(Integer.parseInt(mIdleRefreshPeriod.getValue()));
mAccount.setMaxPushFolders(Integer.parseInt(mMaxPushFolders.getValue()));
}
boolean needsRefresh = mAccount.setAutomaticCheckIntervalMinutes(Integer.parseInt(mCheckFrequency.getValue()));
needsRefresh |= mAccount.setFolderSyncMode(Account.FolderMode.valueOf(mSyncMode.getValue()));
boolean needsPushRestart = mAccount.setFolderPushMode(Account.FolderMode.valueOf(mPushMode.getValue()));
boolean displayModeChanged = mAccount.setFolderDisplayMode(Account.FolderMode.valueOf(mDisplayMode.getValue()));
if (mAccount.getFolderPushMode() != FolderMode.NONE)
{
needsPushRestart |= displayModeChanged;
needsPushRestart |= mIncomingChanged;
}
SharedPreferences prefs = mAccountRingtone.getPreferenceManager().getSharedPreferences();
String newRingtone = prefs.getString(PREFERENCE_RINGTONE, null);
if (newRingtone != null)
{
mAccount.getNotificationSetting().setRing(true);
mAccount.getNotificationSetting().setRingtone(newRingtone);
}
else
{
if (mAccount.getNotificationSetting().shouldRing())
{
mAccount.getNotificationSetting().setRingtone(null);
}
}
mAccount.setHideMessageViewButtons(Account.HideButtons.valueOf(mAccountHideButtons.getValue()));
mAccount.setHideMessageViewMoveButtons(Account.HideButtons.valueOf(mAccountHideMoveButtons.getValue()));
mAccount.setShowPictures(Account.ShowPictures.valueOf(mAccountShowPictures.getValue()));
mAccount.setEnableMoveButtons(mAccountEnableMoveButtons.isChecked());
mAccount.save(Preferences.getPreferences(this));
if (needsRefresh && needsPushRestart)
{
MailService.actionReset(this, null);
}
else if (needsRefresh)
{
MailService.actionReschedulePoll(this, null);
}
else if (needsPushRestart)
{
MailService.actionRestartPushers(this, null);
}
// TODO: refresh folder list here
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK)
{
switch (requestCode)
{
case SELECT_AUTO_EXPAND_FOLDER:
mAutoExpandFolder.setSummary(translateFolder(data.getStringExtra(ChooseFolder.EXTRA_NEW_FOLDER)));
break;
}
}
super.onActivityResult(requestCode, resultCode, data);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK)
{
saveSettings();
}
return super.onKeyDown(keyCode, event);
}
private void onCompositionSettings()
{
AccountSetupComposition.actionEditCompositionSettings(this, mAccount);
}
private void onManageIdentities()
{
Intent intent = new Intent(this, ManageIdentities.class);
intent.putExtra(ChooseIdentity.EXTRA_ACCOUNT, mAccount.getUuid());
startActivityForResult(intent, ACTIVITY_MANAGE_IDENTITIES);
}
private void onIncomingSettings()
{
AccountSetupIncoming.actionEditIncomingSettings(this, mAccount);
}
private void onOutgoingSettings()
{
AccountSetupOutgoing.actionEditOutgoingSettings(this, mAccount);
}
public void onChooseChipColor()
{
new ColorPickerDialog(this, new ColorPickerDialog.OnColorChangedListener()
{
public void colorChanged(int color)
{
mAccount.setChipColor(color);
}
},
mAccount.getChipColor()).show();
}
public void onChooseLedColor()
{
new ColorPickerDialog(this, new ColorPickerDialog.OnColorChangedListener()
{
public void colorChanged(int color)
{
mAccount.getNotificationSetting().setLedColor(color);
}
},
mAccount.getNotificationSetting().getLedColor()).show();
}
public void onChooseAutoExpandFolder()
{
Intent selectIntent = new Intent(this, ChooseFolder.class);
selectIntent.putExtra(ChooseFolder.EXTRA_ACCOUNT, mAccount.getUuid());
selectIntent.putExtra(ChooseFolder.EXTRA_CUR_FOLDER, mAutoExpandFolder.getSummary());
selectIntent.putExtra(ChooseFolder.EXTRA_SHOW_CURRENT, "yes");
selectIntent.putExtra(ChooseFolder.EXTRA_SHOW_FOLDER_NONE, "yes");
selectIntent.putExtra(ChooseFolder.EXTRA_SHOW_DISPLAYABLE_ONLY, "yes");
startActivityForResult(selectIntent, SELECT_AUTO_EXPAND_FOLDER);
}
private String translateFolder(String in)
{
if (K9.INBOX.equalsIgnoreCase(in))
{
return getString(R.string.special_mailbox_name_inbox);
}
else
{
return in;
}
}
private String reverseTranslateFolder(String in)
{
if (getString(R.string.special_mailbox_name_inbox).equals(in))
{
return K9.INBOX;
}
else
{
return in;
}
}
private void doVibrateTest(Preference preference)
{
// Do the vibration to show the user what it's like.
Vibrator vibrate = (Vibrator)preference.getContext().getSystemService(Context.VIBRATOR_SERVICE);
long[] pattern = MessagingController.getVibratePattern(
Integer.parseInt(mAccountVibratePattern.getValue()),
Integer.parseInt(mAccountVibrateTimes.getValue()));
vibrate.vibrate(pattern, -1);
}
}
| true | true | public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
String accountUuid = getIntent().getStringExtra(EXTRA_ACCOUNT);
mAccount = Preferences.getPreferences(this).getAccount(accountUuid);
try
{
final Store store = mAccount.getRemoteStore();
mIsPushCapable = store.isPushCapable();
mIsExpungeCapable = store.isExpungeCapable();
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Could not get remote store", e);
}
addPreferencesFromResource(R.xml.account_settings_preferences);
mAccountDescription = (EditTextPreference) findPreference(PREFERENCE_DESCRIPTION);
mAccountDescription.setSummary(mAccount.getDescription());
mAccountDescription.setText(mAccount.getDescription());
mAccountDescription.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
mAccountDescription.setSummary(summary);
mAccountDescription.setText(summary);
return false;
}
});
mAccountQuotePrefix = (EditTextPreference) findPreference(PREFERENCE_QUOTE_PREFIX);
mAccountQuotePrefix.setSummary(mAccount.getQuotePrefix());
mAccountQuotePrefix.setText(mAccount.getQuotePrefix());
mAccountQuotePrefix.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
@Override
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String value = newValue.toString();
mAccountQuotePrefix.setSummary(value);
mAccountQuotePrefix.setText(value);
return false;
}
});
mReplyAfterQuote = (CheckBoxPreference) findPreference(PREFERENCE_REPLY_AFTER_QUOTE);
mReplyAfterQuote.setChecked(mAccount.isReplyAfterQuote());
mCheckFrequency = (ListPreference) findPreference(PREFERENCE_FREQUENCY);
mCheckFrequency.setValue(String.valueOf(mAccount.getAutomaticCheckIntervalMinutes()));
mCheckFrequency.setSummary(mCheckFrequency.getEntry());
mCheckFrequency.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mCheckFrequency.findIndexOfValue(summary);
mCheckFrequency.setSummary(mCheckFrequency.getEntries()[index]);
mCheckFrequency.setValue(summary);
return false;
}
});
mDisplayMode = (ListPreference) findPreference(PREFERENCE_DISPLAY_MODE);
mDisplayMode.setValue(mAccount.getFolderDisplayMode().name());
mDisplayMode.setSummary(mDisplayMode.getEntry());
mDisplayMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mDisplayMode.findIndexOfValue(summary);
mDisplayMode.setSummary(mDisplayMode.getEntries()[index]);
mDisplayMode.setValue(summary);
return false;
}
});
mSyncMode = (ListPreference) findPreference(PREFERENCE_SYNC_MODE);
mSyncMode.setValue(mAccount.getFolderSyncMode().name());
mSyncMode.setSummary(mSyncMode.getEntry());
mSyncMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mSyncMode.findIndexOfValue(summary);
mSyncMode.setSummary(mSyncMode.getEntries()[index]);
mSyncMode.setValue(summary);
return false;
}
});
mPushMode = (ListPreference) findPreference(PREFERENCE_PUSH_MODE);
mPushMode.setEnabled(mIsPushCapable);
mPushMode.setValue(mAccount.getFolderPushMode().name());
mPushMode.setSummary(mPushMode.getEntry());
mPushMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mPushMode.findIndexOfValue(summary);
mPushMode.setSummary(mPushMode.getEntries()[index]);
mPushMode.setValue(summary);
return false;
}
});
mTargetMode = (ListPreference) findPreference(PREFERENCE_TARGET_MODE);
mTargetMode.setValue(mAccount.getFolderTargetMode().name());
mTargetMode.setSummary(mTargetMode.getEntry());
mTargetMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mTargetMode.findIndexOfValue(summary);
mTargetMode.setSummary(mTargetMode.getEntries()[index]);
mTargetMode.setValue(summary);
return false;
}
});
mDeletePolicy = (ListPreference) findPreference(PREFERENCE_DELETE_POLICY);
mDeletePolicy.setValue("" + mAccount.getDeletePolicy());
mDeletePolicy.setSummary(mDeletePolicy.getEntry());
mDeletePolicy.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mDeletePolicy.findIndexOfValue(summary);
mDeletePolicy.setSummary(mDeletePolicy.getEntries()[index]);
mDeletePolicy.setValue(summary);
return false;
}
});
mExpungePolicy = (ListPreference) findPreference(PREFERENCE_EXPUNGE_POLICY);
mExpungePolicy.setEnabled(mIsExpungeCapable);
mExpungePolicy.setValue(mAccount.getExpungePolicy());
mExpungePolicy.setSummary(mExpungePolicy.getEntry());
mExpungePolicy.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mExpungePolicy.findIndexOfValue(summary);
mExpungePolicy.setSummary(mExpungePolicy.getEntries()[index]);
mExpungePolicy.setValue(summary);
return false;
}
});
mSyncRemoteDeletions = (CheckBoxPreference) findPreference(PREFERENCE_SYNC_REMOTE_DELETIONS);
mSyncRemoteDeletions.setChecked(mAccount.syncRemoteDeletions());
mSaveAllHeaders = (CheckBoxPreference) findPreference(PREFERENCE_SAVE_ALL_HEADERS);
mSaveAllHeaders.setChecked(mAccount.saveAllHeaders());
mSearchableFolders = (ListPreference) findPreference(PREFERENCE_SEARCHABLE_FOLDERS);
mSearchableFolders.setValue(mAccount.getSearchableFolders().name());
mSearchableFolders.setSummary(mSearchableFolders.getEntry());
mSearchableFolders.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mSearchableFolders.findIndexOfValue(summary);
mSearchableFolders.setSummary(mSearchableFolders.getEntries()[index]);
mSearchableFolders.setValue(summary);
return false;
}
});
mDisplayCount = (ListPreference) findPreference(PREFERENCE_DISPLAY_COUNT);
mDisplayCount.setValue(String.valueOf(mAccount.getDisplayCount()));
mDisplayCount.setSummary(mDisplayCount.getEntry());
mDisplayCount.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mDisplayCount.findIndexOfValue(summary);
mDisplayCount.setSummary(mDisplayCount.getEntries()[index]);
mDisplayCount.setValue(summary);
return false;
}
});
mMessageAge = (ListPreference) findPreference(PREFERENCE_MESSAGE_AGE);
mMessageAge.setValue(String.valueOf(mAccount.getMaximumPolledMessageAge()));
mMessageAge.setSummary(mMessageAge.getEntry());
mMessageAge.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mMessageAge.findIndexOfValue(summary);
mMessageAge.setSummary(mMessageAge.getEntries()[index]);
mMessageAge.setValue(summary);
return false;
}
});
mMessageSize = (ListPreference) findPreference(PREFERENCE_MESSAGE_SIZE);
mMessageSize.setValue(String.valueOf(mAccount.getMaximumAutoDownloadMessageSize()));
mMessageSize.setSummary(mMessageSize.getEntry());
mMessageSize.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mMessageSize.findIndexOfValue(summary);
mMessageSize.setSummary(mMessageSize.getEntries()[index]);
mMessageSize.setValue(summary);
return false;
}
});
mAccountDefault = (CheckBoxPreference) findPreference(PREFERENCE_DEFAULT);
mAccountDefault.setChecked(
mAccount.equals(Preferences.getPreferences(this).getDefaultAccount()));
mAccountHideButtons = (ListPreference) findPreference(PREFERENCE_HIDE_BUTTONS);
mAccountHideButtons.setValue("" + mAccount.getHideMessageViewButtons());
mAccountHideButtons.setSummary(mAccountHideButtons.getEntry());
mAccountHideButtons.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mAccountHideButtons.findIndexOfValue(summary);
mAccountHideButtons.setSummary(mAccountHideButtons.getEntries()[index]);
mAccountHideButtons.setValue(summary);
return false;
}
});
mAccountEnableMoveButtons = (CheckBoxPreference) findPreference(PREFERENCE_ENABLE_MOVE_BUTTONS);
mAccountEnableMoveButtons.setChecked(mAccount.getEnableMoveButtons());
mAccountHideMoveButtons = (ListPreference) findPreference(PREFERENCE_HIDE_MOVE_BUTTONS);
mAccountHideMoveButtons.setValue("" + mAccount.getHideMessageViewMoveButtons());
mAccountHideMoveButtons.setSummary(mAccountHideMoveButtons.getEntry());
mAccountHideMoveButtons.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mAccountHideMoveButtons.findIndexOfValue(summary);
mAccountHideMoveButtons.setSummary(mAccountHideMoveButtons.getEntries()[index]);
mAccountHideMoveButtons.setValue(summary);
return false;
}
});
mAccountShowPictures = (ListPreference) findPreference(PREFERENCE_SHOW_PICTURES);
mAccountShowPictures.setValue("" + mAccount.getShowPictures());
mAccountShowPictures.setSummary(mAccountShowPictures.getEntry());
mAccountShowPictures.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mAccountShowPictures.findIndexOfValue(summary);
mAccountShowPictures.setSummary(mAccountShowPictures.getEntries()[index]);
mAccountShowPictures.setValue(summary);
return false;
}
});
mLocalStorageProvider = (ListPreference) findPreference(PREFERENCE_LOCAL_STORAGE_PROVIDER);
{
final Map<String, String> providers;
providers = StorageManager.getInstance(K9.app).getAvailableProviders();
int i = 0;
final String[] providerLabels = new String[providers.size()];
final String[] providerIds = new String[providers.size()];
for (final Map.Entry<String, String> entry : providers.entrySet())
{
providerIds[i] = entry.getKey();
providerLabels[i] = entry.getValue();
i++;
}
mLocalStorageProvider.setEntryValues(providerIds);
mLocalStorageProvider.setEntries(providerLabels);
mLocalStorageProvider.setValue(mAccount.getLocalStorageProviderId());
mLocalStorageProvider.setSummary(providers.get((Object)mAccount.getLocalStorageProviderId()));
mLocalStorageProvider.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
mLocalStorageProvider.setSummary(providers.get(newValue));
return true;
}
});
}
// IMAP-specific preferences
mPushPollOnConnect = (CheckBoxPreference) findPreference(PREFERENCE_PUSH_POLL_ON_CONNECT);
mIdleRefreshPeriod = (ListPreference) findPreference(PREFERENCE_IDLE_REFRESH_PERIOD);
mMaxPushFolders = (ListPreference) findPreference(PREFERENCE_MAX_PUSH_FOLDERS);
if (mIsPushCapable)
{
mPushPollOnConnect.setChecked(mAccount.isPushPollOnConnect());
mIdleRefreshPeriod.setValue(String.valueOf(mAccount.getIdleRefreshMinutes()));
mIdleRefreshPeriod.setSummary(mIdleRefreshPeriod.getEntry());
mIdleRefreshPeriod.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mIdleRefreshPeriod.findIndexOfValue(summary);
mIdleRefreshPeriod.setSummary(mIdleRefreshPeriod.getEntries()[index]);
mIdleRefreshPeriod.setValue(summary);
return false;
}
});
mMaxPushFolders.setValue(String.valueOf(mAccount.getMaxPushFolders()));
mMaxPushFolders.setSummary(mMaxPushFolders.getEntry());
mMaxPushFolders.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mMaxPushFolders.findIndexOfValue(summary);
mMaxPushFolders.setSummary(mMaxPushFolders.getEntries()[index]);
mMaxPushFolders.setValue(summary);
return false;
}
});
}
else
{
mPushPollOnConnect.setEnabled(false);
mMaxPushFolders.setEnabled(false);
mIdleRefreshPeriod.setEnabled(false);
}
mAccountNotify = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFY);
mAccountNotify.setChecked(mAccount.isNotifyNewMail());
mAccountNotifySelf = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFY_SELF);
mAccountNotifySelf.setChecked(mAccount.isNotifySelfNewMail());
mAccountNotifySync = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFY_SYNC);
mAccountNotifySync.setChecked(mAccount.isShowOngoing());
mAccountRingtone = (RingtonePreference) findPreference(PREFERENCE_RINGTONE);
// XXX: The following two lines act as a workaround for the RingtonePreference
// which does not let us set/get the value programmatically
SharedPreferences prefs = mAccountRingtone.getPreferenceManager().getSharedPreferences();
String currentRingtone = (!mAccount.getNotificationSetting().shouldRing() ? null : mAccount.getNotificationSetting().getRingtone());
prefs.edit().putString(PREFERENCE_RINGTONE, currentRingtone).commit();
mAccountVibrate = (CheckBoxPreference) findPreference(PREFERENCE_VIBRATE);
mAccountVibrate.setChecked(mAccount.getNotificationSetting().isVibrate());
mAccountVibratePattern = (ListPreference) findPreference(PREFERENCE_VIBRATE_PATTERN);
mAccountVibratePattern.setValue(String.valueOf(mAccount.getNotificationSetting().getVibratePattern()));
mAccountVibratePattern.setSummary(mAccountVibratePattern.getEntry());
mAccountVibratePattern.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mAccountVibratePattern.findIndexOfValue(summary);
mAccountVibratePattern.setSummary(mAccountVibratePattern.getEntries()[index]);
mAccountVibratePattern.setValue(summary);
doVibrateTest(preference);
return false;
}
});
mAccountVibrateTimes = (ListPreference) findPreference(PREFERENCE_VIBRATE_TIMES);
mAccountVibrateTimes.setValue(String.valueOf(mAccount.getNotificationSetting().getVibrateTimes()));
mAccountVibrateTimes.setSummary(String.valueOf(mAccount.getNotificationSetting().getVibrateTimes()));
mAccountVibrateTimes.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
@Override
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String value = newValue.toString();
mAccountVibrateTimes.setSummary(value);
mAccountVibrateTimes.setValue(value);
doVibrateTest(preference);
return false;
}
});
mAccountLed = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFICATION_LED);
mAccountLed.setChecked(mAccount.getNotificationSetting().isLed());
mNotificationOpensUnread = (CheckBoxPreference)findPreference(PREFERENCE_NOTIFICATION_OPENS_UNREAD);
mNotificationOpensUnread.setChecked(mAccount.goToUnreadMessageSearch());
List<? extends Folder> folders = new LinkedList<LocalFolder>();;
try
{
folders = mAccount.getLocalStore().getPersonalNamespaces(false);
}
catch (Exception e)
{
/// this can't be checked in
}
final String[] allFolderValues = new String[folders.size()+2];
final String[] allFolderLabels = new String[folders.size()+2];
allFolderValues[0] = "";
allFolderLabels[0] = K9.FOLDER_NONE;
// There's a non-zero chance that "outbox" won't actually exist, so we force it into the list
allFolderValues[1] = mAccount.getOutboxFolderName();
allFolderLabels[1] = mAccount.getOutboxFolderName();
int i =2;
for (Folder folder : folders)
{
allFolderLabels[i] = folder.getName();
allFolderValues[i] = folder.getName();
i++;
}
mAutoExpandFolder = (ListPreference)findPreference(PREFERENCE_AUTO_EXPAND_FOLDER);
initListPreference(mAutoExpandFolder, mAccount.getAutoExpandFolderName(), allFolderLabels,allFolderValues);
mArchiveFolder = (ListPreference)findPreference(PREFERENCE_ARCHIVE_FOLDER);
initListPreference(mArchiveFolder, mAccount.getArchiveFolderName(), allFolderLabels,allFolderValues);
mDraftsFolder = (ListPreference)findPreference(PREFERENCE_DRAFTS_FOLDER);
initListPreference(mDraftsFolder, mAccount.getDraftsFolderName(), allFolderLabels,allFolderValues);
mOutboxFolder = (ListPreference)findPreference(PREFERENCE_OUTBOX_FOLDER);
initListPreference(mOutboxFolder, mAccount.getOutboxFolderName(), allFolderLabels,allFolderValues);
mSentFolder = (ListPreference)findPreference(PREFERENCE_SENT_FOLDER);
initListPreference(mSentFolder, mAccount.getSentFolderName(), allFolderLabels,allFolderValues);
mSpamFolder = (ListPreference)findPreference(PREFERENCE_SPAM_FOLDER);
initListPreference(mSpamFolder, mAccount.getSpamFolderName(), allFolderLabels,allFolderValues);
mTrashFolder = (ListPreference)findPreference(PREFERENCE_TRASH_FOLDER);
initListPreference(mTrashFolder, mAccount.getTrashFolderName(), allFolderLabels,allFolderValues);
mChipColor = (Preference)findPreference(PREFERENCE_CHIP_COLOR);
mChipColor.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener()
{
public boolean onPreferenceClick(Preference preference)
{
onChooseChipColor();
return false;
}
});
mLedColor = (Preference)findPreference(PREFERENCE_LED_COLOR);
mLedColor.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener()
{
public boolean onPreferenceClick(Preference preference)
{
onChooseLedColor();
return false;
}
});
findPreference(PREFERENCE_COMPOSITION).setOnPreferenceClickListener(
new Preference.OnPreferenceClickListener()
{
public boolean onPreferenceClick(Preference preference)
{
onCompositionSettings();
return true;
}
});
findPreference(PREFERENCE_MANAGE_IDENTITIES).setOnPreferenceClickListener(
new Preference.OnPreferenceClickListener()
{
public boolean onPreferenceClick(Preference preference)
{
onManageIdentities();
return true;
}
});
findPreference(PREFERENCE_INCOMING).setOnPreferenceClickListener(
new Preference.OnPreferenceClickListener()
{
public boolean onPreferenceClick(Preference preference)
{
mIncomingChanged = true;
onIncomingSettings();
return true;
}
});
findPreference(PREFERENCE_OUTGOING).setOnPreferenceClickListener(
new Preference.OnPreferenceClickListener()
{
public boolean onPreferenceClick(Preference preference)
{
onOutgoingSettings();
return true;
}
});
mCryptoApp = (ListPreference) findPreference(PREFERENCE_CRYPTO_APP);
CharSequence cryptoAppEntries[] = mCryptoApp.getEntries();
if (!new Apg().isAvailable(this))
{
int apgIndex = mCryptoApp.findIndexOfValue(Apg.NAME);
if (apgIndex >= 0)
{
cryptoAppEntries[apgIndex] = "APG (" + getResources().getString(R.string.account_settings_crypto_app_not_available) + ")";
mCryptoApp.setEntries(cryptoAppEntries);
}
}
mCryptoApp.setValue(String.valueOf(mAccount.getCryptoApp()));
mCryptoApp.setSummary(mCryptoApp.getEntry());
mCryptoApp.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
String value = newValue.toString();
int index = mCryptoApp.findIndexOfValue(value);
mCryptoApp.setSummary(mCryptoApp.getEntries()[index]);
mCryptoApp.setValue(value);
handleCryptoAppDependencies();
if (Apg.NAME.equals(value))
{
Apg.createInstance(null).test(AccountSettings.this);
}
return false;
}
});
mCryptoAutoSignature = (CheckBoxPreference) findPreference(PREFERENCE_CRYPTO_AUTO_SIGNATURE);
mCryptoAutoSignature.setChecked(mAccount.getCryptoAutoSignature());
handleCryptoAppDependencies();
}
| public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
String accountUuid = getIntent().getStringExtra(EXTRA_ACCOUNT);
mAccount = Preferences.getPreferences(this).getAccount(accountUuid);
try
{
final Store store = mAccount.getRemoteStore();
mIsPushCapable = store.isPushCapable();
mIsExpungeCapable = store.isExpungeCapable();
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Could not get remote store", e);
}
addPreferencesFromResource(R.xml.account_settings_preferences);
mAccountDescription = (EditTextPreference) findPreference(PREFERENCE_DESCRIPTION);
mAccountDescription.setSummary(mAccount.getDescription());
mAccountDescription.setText(mAccount.getDescription());
mAccountDescription.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
mAccountDescription.setSummary(summary);
mAccountDescription.setText(summary);
return false;
}
});
mAccountQuotePrefix = (EditTextPreference) findPreference(PREFERENCE_QUOTE_PREFIX);
mAccountQuotePrefix.setSummary(mAccount.getQuotePrefix());
mAccountQuotePrefix.setText(mAccount.getQuotePrefix());
mAccountQuotePrefix.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
@Override
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String value = newValue.toString();
mAccountQuotePrefix.setSummary(value);
mAccountQuotePrefix.setText(value);
return false;
}
});
mReplyAfterQuote = (CheckBoxPreference) findPreference(PREFERENCE_REPLY_AFTER_QUOTE);
mReplyAfterQuote.setChecked(mAccount.isReplyAfterQuote());
mCheckFrequency = (ListPreference) findPreference(PREFERENCE_FREQUENCY);
mCheckFrequency.setValue(String.valueOf(mAccount.getAutomaticCheckIntervalMinutes()));
mCheckFrequency.setSummary(mCheckFrequency.getEntry());
mCheckFrequency.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mCheckFrequency.findIndexOfValue(summary);
mCheckFrequency.setSummary(mCheckFrequency.getEntries()[index]);
mCheckFrequency.setValue(summary);
return false;
}
});
mDisplayMode = (ListPreference) findPreference(PREFERENCE_DISPLAY_MODE);
mDisplayMode.setValue(mAccount.getFolderDisplayMode().name());
mDisplayMode.setSummary(mDisplayMode.getEntry());
mDisplayMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mDisplayMode.findIndexOfValue(summary);
mDisplayMode.setSummary(mDisplayMode.getEntries()[index]);
mDisplayMode.setValue(summary);
return false;
}
});
mSyncMode = (ListPreference) findPreference(PREFERENCE_SYNC_MODE);
mSyncMode.setValue(mAccount.getFolderSyncMode().name());
mSyncMode.setSummary(mSyncMode.getEntry());
mSyncMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mSyncMode.findIndexOfValue(summary);
mSyncMode.setSummary(mSyncMode.getEntries()[index]);
mSyncMode.setValue(summary);
return false;
}
});
mPushMode = (ListPreference) findPreference(PREFERENCE_PUSH_MODE);
mPushMode.setEnabled(mIsPushCapable);
mPushMode.setValue(mAccount.getFolderPushMode().name());
mPushMode.setSummary(mPushMode.getEntry());
mPushMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mPushMode.findIndexOfValue(summary);
mPushMode.setSummary(mPushMode.getEntries()[index]);
mPushMode.setValue(summary);
return false;
}
});
mTargetMode = (ListPreference) findPreference(PREFERENCE_TARGET_MODE);
mTargetMode.setValue(mAccount.getFolderTargetMode().name());
mTargetMode.setSummary(mTargetMode.getEntry());
mTargetMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mTargetMode.findIndexOfValue(summary);
mTargetMode.setSummary(mTargetMode.getEntries()[index]);
mTargetMode.setValue(summary);
return false;
}
});
mDeletePolicy = (ListPreference) findPreference(PREFERENCE_DELETE_POLICY);
mDeletePolicy.setValue("" + mAccount.getDeletePolicy());
mDeletePolicy.setSummary(mDeletePolicy.getEntry());
mDeletePolicy.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mDeletePolicy.findIndexOfValue(summary);
mDeletePolicy.setSummary(mDeletePolicy.getEntries()[index]);
mDeletePolicy.setValue(summary);
return false;
}
});
mExpungePolicy = (ListPreference) findPreference(PREFERENCE_EXPUNGE_POLICY);
mExpungePolicy.setEnabled(mIsExpungeCapable);
mExpungePolicy.setValue(mAccount.getExpungePolicy());
mExpungePolicy.setSummary(mExpungePolicy.getEntry());
mExpungePolicy.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mExpungePolicy.findIndexOfValue(summary);
mExpungePolicy.setSummary(mExpungePolicy.getEntries()[index]);
mExpungePolicy.setValue(summary);
return false;
}
});
mSyncRemoteDeletions = (CheckBoxPreference) findPreference(PREFERENCE_SYNC_REMOTE_DELETIONS);
mSyncRemoteDeletions.setChecked(mAccount.syncRemoteDeletions());
mSaveAllHeaders = (CheckBoxPreference) findPreference(PREFERENCE_SAVE_ALL_HEADERS);
mSaveAllHeaders.setChecked(mAccount.saveAllHeaders());
mSearchableFolders = (ListPreference) findPreference(PREFERENCE_SEARCHABLE_FOLDERS);
mSearchableFolders.setValue(mAccount.getSearchableFolders().name());
mSearchableFolders.setSummary(mSearchableFolders.getEntry());
mSearchableFolders.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mSearchableFolders.findIndexOfValue(summary);
mSearchableFolders.setSummary(mSearchableFolders.getEntries()[index]);
mSearchableFolders.setValue(summary);
return false;
}
});
mDisplayCount = (ListPreference) findPreference(PREFERENCE_DISPLAY_COUNT);
mDisplayCount.setValue(String.valueOf(mAccount.getDisplayCount()));
mDisplayCount.setSummary(mDisplayCount.getEntry());
mDisplayCount.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mDisplayCount.findIndexOfValue(summary);
mDisplayCount.setSummary(mDisplayCount.getEntries()[index]);
mDisplayCount.setValue(summary);
return false;
}
});
mMessageAge = (ListPreference) findPreference(PREFERENCE_MESSAGE_AGE);
mMessageAge.setValue(String.valueOf(mAccount.getMaximumPolledMessageAge()));
mMessageAge.setSummary(mMessageAge.getEntry());
mMessageAge.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mMessageAge.findIndexOfValue(summary);
mMessageAge.setSummary(mMessageAge.getEntries()[index]);
mMessageAge.setValue(summary);
return false;
}
});
mMessageSize = (ListPreference) findPreference(PREFERENCE_MESSAGE_SIZE);
mMessageSize.setValue(String.valueOf(mAccount.getMaximumAutoDownloadMessageSize()));
mMessageSize.setSummary(mMessageSize.getEntry());
mMessageSize.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mMessageSize.findIndexOfValue(summary);
mMessageSize.setSummary(mMessageSize.getEntries()[index]);
mMessageSize.setValue(summary);
return false;
}
});
mAccountDefault = (CheckBoxPreference) findPreference(PREFERENCE_DEFAULT);
mAccountDefault.setChecked(
mAccount.equals(Preferences.getPreferences(this).getDefaultAccount()));
mAccountHideButtons = (ListPreference) findPreference(PREFERENCE_HIDE_BUTTONS);
mAccountHideButtons.setValue("" + mAccount.getHideMessageViewButtons());
mAccountHideButtons.setSummary(mAccountHideButtons.getEntry());
mAccountHideButtons.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mAccountHideButtons.findIndexOfValue(summary);
mAccountHideButtons.setSummary(mAccountHideButtons.getEntries()[index]);
mAccountHideButtons.setValue(summary);
return false;
}
});
mAccountEnableMoveButtons = (CheckBoxPreference) findPreference(PREFERENCE_ENABLE_MOVE_BUTTONS);
mAccountEnableMoveButtons.setChecked(mAccount.getEnableMoveButtons());
mAccountHideMoveButtons = (ListPreference) findPreference(PREFERENCE_HIDE_MOVE_BUTTONS);
mAccountHideMoveButtons.setValue("" + mAccount.getHideMessageViewMoveButtons());
mAccountHideMoveButtons.setSummary(mAccountHideMoveButtons.getEntry());
mAccountHideMoveButtons.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mAccountHideMoveButtons.findIndexOfValue(summary);
mAccountHideMoveButtons.setSummary(mAccountHideMoveButtons.getEntries()[index]);
mAccountHideMoveButtons.setValue(summary);
return false;
}
});
mAccountShowPictures = (ListPreference) findPreference(PREFERENCE_SHOW_PICTURES);
mAccountShowPictures.setValue("" + mAccount.getShowPictures());
mAccountShowPictures.setSummary(mAccountShowPictures.getEntry());
mAccountShowPictures.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mAccountShowPictures.findIndexOfValue(summary);
mAccountShowPictures.setSummary(mAccountShowPictures.getEntries()[index]);
mAccountShowPictures.setValue(summary);
return false;
}
});
mLocalStorageProvider = (ListPreference) findPreference(PREFERENCE_LOCAL_STORAGE_PROVIDER);
{
final Map<String, String> providers;
providers = StorageManager.getInstance(K9.app).getAvailableProviders();
int i = 0;
final String[] providerLabels = new String[providers.size()];
final String[] providerIds = new String[providers.size()];
for (final Map.Entry<String, String> entry : providers.entrySet())
{
providerIds[i] = entry.getKey();
providerLabels[i] = entry.getValue();
i++;
}
mLocalStorageProvider.setEntryValues(providerIds);
mLocalStorageProvider.setEntries(providerLabels);
mLocalStorageProvider.setValue(mAccount.getLocalStorageProviderId());
mLocalStorageProvider.setSummary(providers.get((Object)mAccount.getLocalStorageProviderId()));
mLocalStorageProvider.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
mLocalStorageProvider.setSummary(providers.get(newValue));
return true;
}
});
}
// IMAP-specific preferences
mPushPollOnConnect = (CheckBoxPreference) findPreference(PREFERENCE_PUSH_POLL_ON_CONNECT);
mIdleRefreshPeriod = (ListPreference) findPreference(PREFERENCE_IDLE_REFRESH_PERIOD);
mMaxPushFolders = (ListPreference) findPreference(PREFERENCE_MAX_PUSH_FOLDERS);
if (mIsPushCapable)
{
mPushPollOnConnect.setChecked(mAccount.isPushPollOnConnect());
mIdleRefreshPeriod.setValue(String.valueOf(mAccount.getIdleRefreshMinutes()));
mIdleRefreshPeriod.setSummary(mIdleRefreshPeriod.getEntry());
mIdleRefreshPeriod.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mIdleRefreshPeriod.findIndexOfValue(summary);
mIdleRefreshPeriod.setSummary(mIdleRefreshPeriod.getEntries()[index]);
mIdleRefreshPeriod.setValue(summary);
return false;
}
});
mMaxPushFolders.setValue(String.valueOf(mAccount.getMaxPushFolders()));
mMaxPushFolders.setSummary(mMaxPushFolders.getEntry());
mMaxPushFolders.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mMaxPushFolders.findIndexOfValue(summary);
mMaxPushFolders.setSummary(mMaxPushFolders.getEntries()[index]);
mMaxPushFolders.setValue(summary);
return false;
}
});
}
else
{
mPushPollOnConnect.setEnabled(false);
mMaxPushFolders.setEnabled(false);
mIdleRefreshPeriod.setEnabled(false);
}
mAccountNotify = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFY);
mAccountNotify.setChecked(mAccount.isNotifyNewMail());
mAccountNotifySelf = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFY_SELF);
mAccountNotifySelf.setChecked(mAccount.isNotifySelfNewMail());
mAccountNotifySync = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFY_SYNC);
mAccountNotifySync.setChecked(mAccount.isShowOngoing());
mAccountRingtone = (RingtonePreference) findPreference(PREFERENCE_RINGTONE);
// XXX: The following two lines act as a workaround for the RingtonePreference
// which does not let us set/get the value programmatically
SharedPreferences prefs = mAccountRingtone.getPreferenceManager().getSharedPreferences();
String currentRingtone = (!mAccount.getNotificationSetting().shouldRing() ? null : mAccount.getNotificationSetting().getRingtone());
prefs.edit().putString(PREFERENCE_RINGTONE, currentRingtone).commit();
mAccountVibrate = (CheckBoxPreference) findPreference(PREFERENCE_VIBRATE);
mAccountVibrate.setChecked(mAccount.getNotificationSetting().isVibrate());
mAccountVibratePattern = (ListPreference) findPreference(PREFERENCE_VIBRATE_PATTERN);
mAccountVibratePattern.setValue(String.valueOf(mAccount.getNotificationSetting().getVibratePattern()));
mAccountVibratePattern.setSummary(mAccountVibratePattern.getEntry());
mAccountVibratePattern.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String summary = newValue.toString();
int index = mAccountVibratePattern.findIndexOfValue(summary);
mAccountVibratePattern.setSummary(mAccountVibratePattern.getEntries()[index]);
mAccountVibratePattern.setValue(summary);
doVibrateTest(preference);
return false;
}
});
mAccountVibrateTimes = (ListPreference) findPreference(PREFERENCE_VIBRATE_TIMES);
mAccountVibrateTimes.setValue(String.valueOf(mAccount.getNotificationSetting().getVibrateTimes()));
mAccountVibrateTimes.setSummary(String.valueOf(mAccount.getNotificationSetting().getVibrateTimes()));
mAccountVibrateTimes.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
@Override
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String value = newValue.toString();
mAccountVibrateTimes.setSummary(value);
mAccountVibrateTimes.setValue(value);
doVibrateTest(preference);
return false;
}
});
mAccountLed = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFICATION_LED);
mAccountLed.setChecked(mAccount.getNotificationSetting().isLed());
mNotificationOpensUnread = (CheckBoxPreference)findPreference(PREFERENCE_NOTIFICATION_OPENS_UNREAD);
mNotificationOpensUnread.setChecked(mAccount.goToUnreadMessageSearch());
List<? extends Folder> folders = new LinkedList<LocalFolder>();;
try
{
folders = mAccount.getLocalStore().getPersonalNamespaces(false);
}
catch (Exception e)
{
/// this can't be checked in
}
final String[] allFolderValues = new String[folders.size()+2];
final String[] allFolderLabels = new String[folders.size()+2];
allFolderValues[0] = K9.FOLDER_NONE;
allFolderLabels[0] = K9.FOLDER_NONE;
// There's a non-zero chance that "outbox" won't actually exist, so we force it into the list
allFolderValues[1] = mAccount.getOutboxFolderName();
allFolderLabels[1] = mAccount.getOutboxFolderName();
int i =2;
for (Folder folder : folders)
{
allFolderLabels[i] = folder.getName();
allFolderValues[i] = folder.getName();
i++;
}
mAutoExpandFolder = (ListPreference)findPreference(PREFERENCE_AUTO_EXPAND_FOLDER);
initListPreference(mAutoExpandFolder, mAccount.getAutoExpandFolderName(), allFolderLabels,allFolderValues);
mArchiveFolder = (ListPreference)findPreference(PREFERENCE_ARCHIVE_FOLDER);
initListPreference(mArchiveFolder, mAccount.getArchiveFolderName(), allFolderLabels,allFolderValues);
mDraftsFolder = (ListPreference)findPreference(PREFERENCE_DRAFTS_FOLDER);
initListPreference(mDraftsFolder, mAccount.getDraftsFolderName(), allFolderLabels,allFolderValues);
mOutboxFolder = (ListPreference)findPreference(PREFERENCE_OUTBOX_FOLDER);
initListPreference(mOutboxFolder, mAccount.getOutboxFolderName(), allFolderLabels,allFolderValues);
mSentFolder = (ListPreference)findPreference(PREFERENCE_SENT_FOLDER);
initListPreference(mSentFolder, mAccount.getSentFolderName(), allFolderLabels,allFolderValues);
mSpamFolder = (ListPreference)findPreference(PREFERENCE_SPAM_FOLDER);
initListPreference(mSpamFolder, mAccount.getSpamFolderName(), allFolderLabels,allFolderValues);
mTrashFolder = (ListPreference)findPreference(PREFERENCE_TRASH_FOLDER);
initListPreference(mTrashFolder, mAccount.getTrashFolderName(), allFolderLabels,allFolderValues);
mChipColor = (Preference)findPreference(PREFERENCE_CHIP_COLOR);
mChipColor.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener()
{
public boolean onPreferenceClick(Preference preference)
{
onChooseChipColor();
return false;
}
});
mLedColor = (Preference)findPreference(PREFERENCE_LED_COLOR);
mLedColor.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener()
{
public boolean onPreferenceClick(Preference preference)
{
onChooseLedColor();
return false;
}
});
findPreference(PREFERENCE_COMPOSITION).setOnPreferenceClickListener(
new Preference.OnPreferenceClickListener()
{
public boolean onPreferenceClick(Preference preference)
{
onCompositionSettings();
return true;
}
});
findPreference(PREFERENCE_MANAGE_IDENTITIES).setOnPreferenceClickListener(
new Preference.OnPreferenceClickListener()
{
public boolean onPreferenceClick(Preference preference)
{
onManageIdentities();
return true;
}
});
findPreference(PREFERENCE_INCOMING).setOnPreferenceClickListener(
new Preference.OnPreferenceClickListener()
{
public boolean onPreferenceClick(Preference preference)
{
mIncomingChanged = true;
onIncomingSettings();
return true;
}
});
findPreference(PREFERENCE_OUTGOING).setOnPreferenceClickListener(
new Preference.OnPreferenceClickListener()
{
public boolean onPreferenceClick(Preference preference)
{
onOutgoingSettings();
return true;
}
});
mCryptoApp = (ListPreference) findPreference(PREFERENCE_CRYPTO_APP);
CharSequence cryptoAppEntries[] = mCryptoApp.getEntries();
if (!new Apg().isAvailable(this))
{
int apgIndex = mCryptoApp.findIndexOfValue(Apg.NAME);
if (apgIndex >= 0)
{
cryptoAppEntries[apgIndex] = "APG (" + getResources().getString(R.string.account_settings_crypto_app_not_available) + ")";
mCryptoApp.setEntries(cryptoAppEntries);
}
}
mCryptoApp.setValue(String.valueOf(mAccount.getCryptoApp()));
mCryptoApp.setSummary(mCryptoApp.getEntry());
mCryptoApp.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference, Object newValue)
{
String value = newValue.toString();
int index = mCryptoApp.findIndexOfValue(value);
mCryptoApp.setSummary(mCryptoApp.getEntries()[index]);
mCryptoApp.setValue(value);
handleCryptoAppDependencies();
if (Apg.NAME.equals(value))
{
Apg.createInstance(null).test(AccountSettings.this);
}
return false;
}
});
mCryptoAutoSignature = (CheckBoxPreference) findPreference(PREFERENCE_CRYPTO_AUTO_SIGNATURE);
mCryptoAutoSignature.setChecked(mAccount.getCryptoAutoSignature());
handleCryptoAppDependencies();
}
|
diff --git a/nuget-tests/src/jetbrains/buildServer/nuget/tests/server/feed/server/NuGetServerStatusHolderTest.java b/nuget-tests/src/jetbrains/buildServer/nuget/tests/server/feed/server/NuGetServerStatusHolderTest.java
index a1ab08ac..72820008 100644
--- a/nuget-tests/src/jetbrains/buildServer/nuget/tests/server/feed/server/NuGetServerStatusHolderTest.java
+++ b/nuget-tests/src/jetbrains/buildServer/nuget/tests/server/feed/server/NuGetServerStatusHolderTest.java
@@ -1,122 +1,123 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.nuget.tests.server.feed.server;
import jetbrains.buildServer.BaseTestCase;
import jetbrains.buildServer.nuget.server.feed.server.NuGetServerRunnerSettings;
import jetbrains.buildServer.nuget.server.feed.server.NuGetServerStatus;
import jetbrains.buildServer.nuget.server.feed.server.process.NuGetServerStatusHolderImpl;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.api.Invocation;
import org.jmock.lib.action.CustomAction;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/**
* @author Eugene Petrenko ([email protected])
* Date: 01.11.11 17:44
*/
public class NuGetServerStatusHolderTest extends BaseTestCase {
private Mockery m;
private NuGetServerRunnerSettings mySettings;
private NuGetServerStatusHolderImpl myHolder;
private boolean myIsEnabled;
@BeforeMethod
@Override
protected void setUp() throws Exception {
m = new Mockery();
myIsEnabled = false;
mySettings = m.mock(NuGetServerRunnerSettings.class);
m.checking(new Expectations(){{
allowing(mySettings).isNuGetFeedEnabled(); will(new CustomAction("return myIsEnabled") {
public Object invoke(Invocation invocation) throws Throwable {
return myIsEnabled;
}
});
+ allowing(mySettings).getLogFilePath(); will(returnValue(createTempFile("aaa")));
}});
myHolder = new NuGetServerStatusHolderImpl(mySettings);
}
@Test
public void test_remember_failed_ping_status_on_stop() {
myHolder.startingServer();
myHolder.pingFailed();
myHolder.stoppingServer();
final NuGetServerStatus status = myHolder.getStatus();
Assert.assertFalse(status.isRunning());
Assert.assertFalse(status.getServerAccessible());
}
@Test
public void test_remember_succeeded_ping_status_on_stop() {
myHolder.startingServer();
myHolder.pingSucceeded();
myHolder.stoppingServer();
final NuGetServerStatus status = myHolder.getStatus();
Assert.assertFalse(status.isRunning());
Assert.assertTrue(status.getServerAccessible());
}
@Test
public void test_remember_failed_ping_status_on_restart() {
myHolder.startingServer();
myHolder.pingFailed();
myHolder.stoppingServer();
myHolder.startingServer();
final NuGetServerStatus status = myHolder.getStatus();
Assert.assertTrue(status.isRunning());
Assert.assertFalse(status.getServerAccessible());
}
@Test
public void test_remember_succeeded_ping_status_on_restart() {
myHolder.startingServer();
myHolder.pingSucceeded();
myHolder.stoppingServer();
myHolder.startingServer();
final NuGetServerStatus status = myHolder.getStatus();
Assert.assertTrue(status.isRunning());
Assert.assertTrue(status.getServerAccessible());
}
@Test
public void test_default_disabled() {
final NuGetServerStatus status = myHolder.getStatus();
Assert.assertFalse(status.isRunning());
Assert.assertFalse(status.isScheduledToStart());
Assert.assertNull(status.getServerAccessible());
}
@Test
public void test_default_enabled() {
myIsEnabled = true;
final NuGetServerStatus status = myHolder.getStatus();
Assert.assertFalse(status.isRunning());
Assert.assertTrue(status.isScheduledToStart());
Assert.assertNull(status.getServerAccessible());
}
}
| true | true | protected void setUp() throws Exception {
m = new Mockery();
myIsEnabled = false;
mySettings = m.mock(NuGetServerRunnerSettings.class);
m.checking(new Expectations(){{
allowing(mySettings).isNuGetFeedEnabled(); will(new CustomAction("return myIsEnabled") {
public Object invoke(Invocation invocation) throws Throwable {
return myIsEnabled;
}
});
}});
myHolder = new NuGetServerStatusHolderImpl(mySettings);
}
| protected void setUp() throws Exception {
m = new Mockery();
myIsEnabled = false;
mySettings = m.mock(NuGetServerRunnerSettings.class);
m.checking(new Expectations(){{
allowing(mySettings).isNuGetFeedEnabled(); will(new CustomAction("return myIsEnabled") {
public Object invoke(Invocation invocation) throws Throwable {
return myIsEnabled;
}
});
allowing(mySettings).getLogFilePath(); will(returnValue(createTempFile("aaa")));
}});
myHolder = new NuGetServerStatusHolderImpl(mySettings);
}
|
diff --git a/src/main/java/edu/wm/werewolf/service/GameService.java b/src/main/java/edu/wm/werewolf/service/GameService.java
index 287e0f3..9cf6ce7 100644
--- a/src/main/java/edu/wm/werewolf/service/GameService.java
+++ b/src/main/java/edu/wm/werewolf/service/GameService.java
@@ -1,159 +1,158 @@
package edu.wm.werewolf.service;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import org.springframework.beans.factory.annotation.Autowired;
import edu.wm.werewolf.dao.IGameDAO;
import edu.wm.werewolf.dao.IKillsDAO;
import edu.wm.werewolf.dao.IPlayerDAO;
import edu.wm.werewolf.dao.IUserDAO;
import edu.wm.werewolf.domain.GPSLocation;
import edu.wm.werewolf.domain.Game;
import edu.wm.werewolf.domain.Kill;
import edu.wm.werewolf.domain.Player;
import edu.wm.werewolf.domain.User;
import edu.wm.werewolf.exceptions.NoPlayerFoundException;
public class GameService {
@Autowired private IPlayerDAO playerDAO;
@Autowired private IUserDAO userDAO;
@Autowired private IKillsDAO killsDAO;
@Autowired private IGameDAO gameDAO;
public List<Player> getAllAlive()
{
if(!gameDAO.getIsRunning()) {
return null;
}
return playerDAO.getAllAlive();
}
public List<Player> getAllPlayersNear(Player player)
{
if(!gameDAO.getIsRunning()) {
return null;
}
return playerDAO.getAllNear(player);
}
public void updatePosition(String userName, GPSLocation location)
{
if(gameDAO.getIsRunning()) {
User user = userDAO.getUserbyID(userName);
playerDAO.setPlayerLocation(user.getId(), location);
}
}
public boolean canKill(Player killer, Player victim) {
if(!gameDAO.getIsRunning()) {
return false;
}
System.out.println("Is night: " + gameDAO.isNight());
if (killer.isWerewolf() && !victim.isWerewolf() && !victim.isDead() && gameDAO.isNight())
{
return true;
}
else
{
return false;
}
}
public void setKill (Kill kill)
{
if(gameDAO.getIsRunning()) {
killsDAO.setKill(kill);
try {
playerDAO.setDead(playerDAO.getPlayerByID(kill.getVictimID()));
} catch (NoPlayerFoundException e) {
e.printStackTrace();
}
}
}
public boolean isAdmin(String id)
{
User user = userDAO.getUserbyID(id);
return user.isAdmin();
}
public void newGame(int dayNightFreq)
{
killsDAO.reset();
playerDAO.reset();
gameDAO.reset();
Game game = new Game(dayNightFreq);
gameDAO.createGame(game);
- List <Player> players = new ArrayList<>();
//List <MyUser> users = userDAO.getAllUsers();
List <User> users = userDAO.getAllUsers();
//for(MyUser u: users)
for (User u: users)
{
Player p = new Player();
p.setUserId(u.getId());
playerDAO.createPlayer(p);
- players.add(p);
}
- Collections.shuffle(players, new Random(System.currentTimeMillis()));
- int werewolfindex = (int) (players.size() * .3f);
+ List <Player> allPlayers = playerDAO.getAllAlive();
+ Collections.shuffle(allPlayers, new Random(System.currentTimeMillis()));
+ int werewolfindex = (int) (allPlayers.size() * .3f);
if (werewolfindex == 0) {
werewolfindex = 1;
}
- for (Player gamePlayer : players)
+ for (Player gamePlayer : allPlayers)
{
if (werewolfindex>0) {
gamePlayer.setWerewolf(true);
werewolfindex--;
}
else {
gamePlayer.setWerewolf(false);
}
}
}
public void vote(Player player, Player votee) {
if(gameDAO.getIsRunning()) {
playerDAO.vote(player, votee);
}
}
public void checkGame()
{
if (gameDAO == null) {}
else if (!gameDAO.getIsRunning()) {}
else if ((playerDAO.getAllWerewolves().size() == 0) ||
(playerDAO.getAllWerewolves().size() > playerDAO.getAllTownspeople().size()))
{
gameDAO.endGame();
}
//TODO add another else if that checks if its time to vote
//& also if it's time to collect votes.
// must vote off person who is voted most
}
public void addPlayer(Player player)
{
playerDAO.createPlayer(player);
}
public void addUser (String id, String firstName, String lastName, String username,
String hashedPassword, String imageURL, Boolean isAdmin)
{
User user = new User(id, firstName, lastName, username, hashedPassword, imageURL, isAdmin);
userDAO.createUser(user);
}
}
| false | true | public void newGame(int dayNightFreq)
{
killsDAO.reset();
playerDAO.reset();
gameDAO.reset();
Game game = new Game(dayNightFreq);
gameDAO.createGame(game);
List <Player> players = new ArrayList<>();
//List <MyUser> users = userDAO.getAllUsers();
List <User> users = userDAO.getAllUsers();
//for(MyUser u: users)
for (User u: users)
{
Player p = new Player();
p.setUserId(u.getId());
playerDAO.createPlayer(p);
players.add(p);
}
Collections.shuffle(players, new Random(System.currentTimeMillis()));
int werewolfindex = (int) (players.size() * .3f);
if (werewolfindex == 0) {
werewolfindex = 1;
}
for (Player gamePlayer : players)
{
if (werewolfindex>0) {
gamePlayer.setWerewolf(true);
werewolfindex--;
}
else {
gamePlayer.setWerewolf(false);
}
}
}
| public void newGame(int dayNightFreq)
{
killsDAO.reset();
playerDAO.reset();
gameDAO.reset();
Game game = new Game(dayNightFreq);
gameDAO.createGame(game);
//List <MyUser> users = userDAO.getAllUsers();
List <User> users = userDAO.getAllUsers();
//for(MyUser u: users)
for (User u: users)
{
Player p = new Player();
p.setUserId(u.getId());
playerDAO.createPlayer(p);
}
List <Player> allPlayers = playerDAO.getAllAlive();
Collections.shuffle(allPlayers, new Random(System.currentTimeMillis()));
int werewolfindex = (int) (allPlayers.size() * .3f);
if (werewolfindex == 0) {
werewolfindex = 1;
}
for (Player gamePlayer : allPlayers)
{
if (werewolfindex>0) {
gamePlayer.setWerewolf(true);
werewolfindex--;
}
else {
gamePlayer.setWerewolf(false);
}
}
}
|
diff --git a/framework/src/java/org/apache/tapestry/components/IfBean.java b/framework/src/java/org/apache/tapestry/components/IfBean.java
index 691f79931..eb46c6913 100644
--- a/framework/src/java/org/apache/tapestry/components/IfBean.java
+++ b/framework/src/java/org/apache/tapestry/components/IfBean.java
@@ -1,202 +1,202 @@
// Copyright 2004, 2005 The Apache Software Foundation
//
// 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.apache.tapestry.components;
import org.apache.hivemind.ApplicationRuntimeException;
import org.apache.hivemind.HiveMind;
import org.apache.tapestry.IActionListener;
import org.apache.tapestry.IBinding;
import org.apache.tapestry.IForm;
import org.apache.tapestry.IMarkupWriter;
import org.apache.tapestry.IRequestCycle;
import org.apache.tapestry.Tapestry;
import org.apache.tapestry.TapestryUtils;
import org.apache.tapestry.form.AbstractFormComponent;
import org.apache.tapestry.services.DataSqueezer;
/**
* @author mb
*/
public abstract class IfBean extends AbstractFormComponent
{
public final static String IF_VALUE_ATTRIBUTE = "org.mb.tapestry.base.IfValue";
public abstract IBinding getConditionValueBinding();
public abstract boolean getCondition();
public abstract boolean getVolatile();
public abstract String getElement();
public abstract IActionListener getListener();
private boolean _rendering = false;
private boolean _conditionValue;
protected void renderComponent(IMarkupWriter writer, IRequestCycle cycle)
{
boolean cycleRewinding = cycle.isRewinding();
// form may be null if component is not located in a form
IForm form = (IForm) cycle.getAttribute(TapestryUtils.FORM_ATTRIBUTE);
// If the cycle is rewinding, but not this particular form,
// then do nothing (don't even render the body).
- if (cycleRewinding && form != null && !cycleRewinding)
+ if (cycleRewinding && form != null && !form.isRewinding())
return;
// get the condition. work with a hidden field if necessary
_conditionValue = evaluateCondition(cycle, form, cycleRewinding);
_rendering = true;
try
{
// call listener
IActionListener listener = getListener();
if (listener != null)
listener.actionTriggered(this, cycle);
// now render if condition is true
if (_conditionValue)
{
String element = getElement();
boolean render = !cycleRewinding && HiveMind.isNonBlank(element);
if (render)
{
writer.begin(element);
renderInformalParameters(writer, cycle);
}
renderBody(writer, cycle);
if (render)
writer.end(element);
}
}
finally
{
_rendering = false;
}
cycle.setAttribute(IF_VALUE_ATTRIBUTE, new Boolean(_conditionValue));
}
protected boolean evaluateCondition(IRequestCycle cycle, IForm form, boolean cycleRewinding)
{
boolean condition;
if (form == null || getVolatile())
{
condition = getCondition();
}
else
{
// we are in a form and we care -- load/store the condition in a hidden field
String name = form.getElementId(this);
if (!cycleRewinding)
{
condition = getCondition();
writeValue(form, name, condition);
}
else
{
condition = readValue(cycle, name);
}
}
// write condition value if parameter is bound
IBinding conditionValueBinding = getConditionValueBinding();
if (conditionValueBinding != null)
conditionValueBinding.setObject(new Boolean(condition));
return condition;
}
private void writeValue(IForm form, String name, boolean value)
{
String externalValue;
Object booleanValue = new Boolean(value);
try
{
externalValue = getDataSqueezer().squeeze(booleanValue);
}
catch (Exception ex)
{
throw new ApplicationRuntimeException(Tapestry.format(
"If.unable-to-convert-value",
booleanValue), this, null, ex);
}
form.addHiddenValue(name, externalValue);
}
private boolean readValue(IRequestCycle cycle, String name)
{
String submittedValue = cycle.getParameter(name);
try
{
Object valueObject = getDataSqueezer().unsqueeze(submittedValue);
if (!(valueObject instanceof Boolean))
throw new ApplicationRuntimeException(Tapestry.format(
"If.invalid-condition-type",
submittedValue));
return ((Boolean) valueObject).booleanValue();
}
catch (Exception ex)
{
throw new ApplicationRuntimeException(Tapestry.format(
"If.unable-to-convert-string",
submittedValue), this, null, ex);
}
}
public abstract DataSqueezer getDataSqueezer();
public boolean isDisabled()
{
return false;
}
/**
* Returns the value of the condition
*
* @return the condition value
*/
public boolean getConditionValue()
{
if (!_rendering)
throw Tapestry.createRenderOnlyPropertyException(this, "conditionValue");
return _conditionValue;
}
// Do nothing in those methods, but make the JVM happy
protected void renderFormComponent(IMarkupWriter writer, IRequestCycle cycle)
{
}
protected void rewindFormComponent(IMarkupWriter writer, IRequestCycle cycle)
{
}
}
| true | true | protected void renderComponent(IMarkupWriter writer, IRequestCycle cycle)
{
boolean cycleRewinding = cycle.isRewinding();
// form may be null if component is not located in a form
IForm form = (IForm) cycle.getAttribute(TapestryUtils.FORM_ATTRIBUTE);
// If the cycle is rewinding, but not this particular form,
// then do nothing (don't even render the body).
if (cycleRewinding && form != null && !cycleRewinding)
return;
// get the condition. work with a hidden field if necessary
_conditionValue = evaluateCondition(cycle, form, cycleRewinding);
_rendering = true;
try
{
// call listener
IActionListener listener = getListener();
if (listener != null)
listener.actionTriggered(this, cycle);
// now render if condition is true
if (_conditionValue)
{
String element = getElement();
boolean render = !cycleRewinding && HiveMind.isNonBlank(element);
if (render)
{
writer.begin(element);
renderInformalParameters(writer, cycle);
}
renderBody(writer, cycle);
if (render)
writer.end(element);
}
}
finally
{
_rendering = false;
}
cycle.setAttribute(IF_VALUE_ATTRIBUTE, new Boolean(_conditionValue));
}
| protected void renderComponent(IMarkupWriter writer, IRequestCycle cycle)
{
boolean cycleRewinding = cycle.isRewinding();
// form may be null if component is not located in a form
IForm form = (IForm) cycle.getAttribute(TapestryUtils.FORM_ATTRIBUTE);
// If the cycle is rewinding, but not this particular form,
// then do nothing (don't even render the body).
if (cycleRewinding && form != null && !form.isRewinding())
return;
// get the condition. work with a hidden field if necessary
_conditionValue = evaluateCondition(cycle, form, cycleRewinding);
_rendering = true;
try
{
// call listener
IActionListener listener = getListener();
if (listener != null)
listener.actionTriggered(this, cycle);
// now render if condition is true
if (_conditionValue)
{
String element = getElement();
boolean render = !cycleRewinding && HiveMind.isNonBlank(element);
if (render)
{
writer.begin(element);
renderInformalParameters(writer, cycle);
}
renderBody(writer, cycle);
if (render)
writer.end(element);
}
}
finally
{
_rendering = false;
}
cycle.setAttribute(IF_VALUE_ATTRIBUTE, new Boolean(_conditionValue));
}
|
diff --git a/src/main/java/hudson/plugins/perforce/PerforceSCM.java b/src/main/java/hudson/plugins/perforce/PerforceSCM.java
index ad77344..c6aa147 100644
--- a/src/main/java/hudson/plugins/perforce/PerforceSCM.java
+++ b/src/main/java/hudson/plugins/perforce/PerforceSCM.java
@@ -1,639 +1,639 @@
package hudson.plugins.perforce;
import static hudson.Util.fixNull;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.Actionable;
import hudson.model.BuildListener;
import hudson.model.TaskListener;
import hudson.scm.ChangeLogParser;
import hudson.scm.RepositoryBrowsers;
import hudson.scm.SCM;
import hudson.scm.SCMDescriptor;
import hudson.util.FormFieldValidator;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.List;
import javax.servlet.ServletException;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import com.tek42.perforce.Depot;
import com.tek42.perforce.PerforceException;
import com.tek42.perforce.model.Changelist;
import com.tek42.perforce.model.Workspace;
/**
* Extends {@link SCM} to provide integration with Perforce SCM repositories.
*
* @author Mike Wille
* @author Brian Westrich
*/
public class PerforceSCM extends SCM {
public static final PerforceSCM.PerforceSCMDescriptor DESCRIPTOR = new PerforceSCM.PerforceSCMDescriptor();
String p4User;
String p4Passwd;
String p4Port;
String p4Client;
String projectPath;
String p4Exe = "C:\\Program Files\\Perforce\\p4.exe";
String p4SysDrive = "C:";
String p4SysRoot = "C:\\WINDOWS";
Depot depot;
PerforceRepositoryBrowser browser;
/**
* This is being removed, including it as transient to fix exceptions on startup.
*/
transient int lastChange;
/**
* force sync is a one time trigger from the config area to force a sync with the depot.
* it is reset to false after the first checkout.
*/
boolean forceSync = false;
/**
* If true, we will manage the workspace view within the plugin. If false, we will leave the
* view alone.
*/
boolean updateView = true;
/**
* If > 0 then will override the changelist we sync to for the first build.
*/
int firstChange = -1;
public PerforceSCM(String p4User, String p4Pass, String p4Client, String p4Port, String projectPath,
String p4Exe, String p4SysRoot, String p4SysDrive, boolean forceSync,
boolean updateView, int firstChange, PerforceRepositoryBrowser browser) {
this.p4User = p4User;
this.p4Passwd = p4Pass;
this.p4Client = p4Client;
this.p4Port = p4Port;
this.projectPath = projectPath;
if(p4Exe != null)
this.p4Exe = p4Exe;
if(p4SysRoot != null)
this.p4SysRoot = p4SysRoot;
if(p4SysDrive != null)
this.p4SysDrive = p4SysDrive;
this.forceSync = forceSync;
this.browser = browser;
this.updateView = updateView;
this.firstChange = firstChange;
}
/**
* This only exists because we need to do initialization after we have been brought
* back to life. I'm not quite clear on stapler and how all that works.
* At any rate, it doesn't look like we have an init() method for setting up our Depot
* after all of the setters have been called. Someone correct me if I'm wrong...
*/
private Depot getDepot() {
if(depot == null) {
depot = new Depot();
depot.setUser(p4User);
depot.setPassword(p4Passwd);
depot.setPort(p4Port);
depot.setClient(p4Client);
depot.setExecutable(p4Exe);
depot.setSystemDrive(p4SysDrive);
depot.setSystemRoot(p4SysRoot);
}
return depot;
}
/**
* Perform some manipulation on the workspace URI to get a valid local path
* <p>
* Is there an issue doing this? What about remote workspaces? does that happen?
*
* @param path
* @return
* @throws IOException
* @throws InterruptedException
*/
private String getLocalPathName(FilePath path) throws IOException, InterruptedException {
String uriString = path.toURI().toString();
// Get rid of URI prefix
// NOTE: this won't handle remote files, is that a problem?
uriString = uriString.replaceAll("file:/", "");
// It seems there is a /./ to denote the root in the path on my test instance.
// I don't know if this is in production, or how it works on other platforms (non win32)
// but I am removing it here because perforce doesn't like it.
uriString = uriString.replaceAll("/./", "/");
// The URL is also escaped. We need to unescape it because %20 in path names isn't cool for perforce.
uriString = URLDecoder.decode(uriString, "UTF-8");
// Last but not least, we need to convert this to local path separators.
String sep = System.getProperty("file.separator");
if(sep.equals("\\")) {
// just replace with sep doesn't work because java's foobar regexp replaceAll
uriString = uriString.replaceAll("/", "\\\\");
} else {
// on unixen we need to prepend with /
uriString = "/" + uriString;
}
return uriString;
}
/* (non-Javadoc)
* @see hudson.scm.SCM#checkout(hudson.model.AbstractBuild, hudson.Launcher, hudson.FilePath, hudson.model.BuildListener, java.io.File)
*/
@Override
public boolean checkout(AbstractBuild build, Launcher launcher, FilePath workspace, BuildListener listener, File changelogFile) throws IOException, InterruptedException {
try {
listener.getLogger().println("Performing sync with Perforce for: " + projectPath);
// Check to make sure our client is mapped to the local hudson directory...
// The problem is that perforce assumes a local directory on your computer maps
// directly to the remote depot. Unfortunately, this doesn't work with they way
// Hudson sets up workspaces. Not to worry! What we do here is manipulate the
// perforce client spec before we do a checkout.
// An alternative would be to setup a single client for each build project. While,
// that is possible, I think its wasteful makes setup time for the user longer as
// they have to go and create a workspace in perforce for each new project.
// 1. Retrieve the client specified, throw an exception if we are configured wrong and the
// client spec doesn't exist.
Workspace p4workspace = getDepot().getWorkspaces().getWorkspace(p4Client);
assert p4workspace != null;
boolean creatingNewWorkspace = p4workspace.getAccess() == null
|| p4workspace.getAccess().length() == 0;
- // 2. Before we sync, we need to update the client spec. (we do this on every build)
+ // 2. Before we sync, we need to update the client spec (we do this on every build).
// Here we are getting the local file path to the workspace. We will use this as the "Root"
// config property of the client spec. This tells perforce where to store the files on our local disk
String localPath = getLocalPathName(workspace);
listener.getLogger().println("Changing P4 Client Root to: " + localPath);
p4workspace.setRoot(localPath);
// 3. Optionally regenerate the workspace view.
// We tell perforce to map the project contents directly (this drops off the project
// name from the workspace. So instead of:
// [Hudson]/[job]/workspace/[Project]/contents
// we get:
// [Hudson]/[job]/workspace/contents
if(updateView || creatingNewWorkspace) {
String view = projectPath + " //" + p4workspace.getName() + "/...";
listener.getLogger().println("Changing P4 Client View to: " + view);
p4workspace.clearViews();
p4workspace.addView(view);
}
// 3b. There is a slight chance of failure with sync'ing to head. I've experienced
// a problem where a sync does not happen and there is no error message. It is when
// the host value of the workspace does not match up with the host hudson is working on.
// Perforce reports an error like: "Client 'hudson' can only be used from host 'workstation'."
// but this does not show up in P4Java as an error. Until P4Java is fixed, the workaround is
// to clear the host value.
p4workspace.setHost("");
// 4. Go and save the client for use when sync'ing in a few...
depot.getWorkspaces().saveWorkspace(p4workspace);
// 5. Get the list of changes since the last time we looked...
int lastChange = getLastChange(build.getPreviousBuild());
listener.getLogger().println("Last sync'd change: " + lastChange);
List<Changelist> changes = depot.getChanges().getChangelistsFromNumbers(depot.getChanges().getChangeNumbersTo(projectPath, lastChange + 1));
if(changes.size() > 0) {
// save the last change we sync'd to for use when polling...
lastChange = changes.get(0).getChangeNumber();
PerforceChangeLogSet.saveToChangeLog(new FileOutputStream(changelogFile), changes);
} else if(!forceSync) {
listener.getLogger().println("No changes since last build.");
return createEmptyChangeLog(changelogFile, listener, "changelog");
}
// 7. Now we can actually do the sync process...
long startTime = System.currentTimeMillis();
listener.getLogger().println("Sync'ing workspace to depot.");
if(forceSync)
listener.getLogger().println("ForceSync flag is set, forcing: p4 sync " + projectPath);
depot.getWorkspaces().syncToHead(projectPath, forceSync);
// reset one time use variables...
forceSync = false;
firstChange = -1;
listener.getLogger().println("Sync complete, took " + (System.currentTimeMillis() - startTime) + " MS");
// Add tagging action...
build.addAction(new PerforceTagAction(build, depot, lastChange, projectPath));
// And I'm spent...
- build.getParent().save(); // The pertient things we want to save are the one time use variables...
+ build.getParent().save(); // The pertinent things we want to save are the one time use variables...
return true;
} catch(PerforceException e) {
listener.getLogger().print("Caught Exception communicating with perforce. " + e.getMessage());
e.printStackTrace();
throw new IOException("Unable to communicate with perforce. " + e.getMessage());
} finally {
//Utils.cleanUp();
}
}
@Override
public PerforceRepositoryBrowser getBrowser() {
return browser;
}
/* (non-Javadoc)
* @see hudson.scm.SCM#createChangeLogParser()
*/
@Override
public ChangeLogParser createChangeLogParser() {
return new PerforceChangeLogParser();
}
/* (non-Javadoc)
* @see hudson.scm.SCM#getDescriptor()
*/
@Override
public SCMDescriptor<?> getDescriptor() {
return DESCRIPTOR;
}
/* (non-Javadoc)
* @see hudson.scm.SCM#pollChanges(hudson.model.AbstractProject, hudson.Launcher, hudson.FilePath, hudson.model.TaskListener)
*/
@Override
public boolean pollChanges(AbstractProject project, Launcher launcher, FilePath workspace, TaskListener listener) throws IOException, InterruptedException {
try {
int lastChange = getLastChange(project.getLastBuild());
listener.getLogger().println("Looking for changes...");
List<Changelist> changes = getDepot().getChanges().getChangelists(projectPath, -1, 1);
listener.getLogger().println("Latest change in depot is: " + changes.get(0).getChangeNumber());
listener.getLogger().println(changes.get(0).toString());
listener.getLogger().println("Last sync'd change is : " + lastChange);
if(lastChange != changes.get(0).getChangeNumber()) {
listener.getLogger().println("New changes detected, triggering a build.");
return true;
}
listener.getLogger().println("We have nothing to do.");
return false;
} catch(PerforceException e) {
System.out.println("Problem: " + e.getMessage());
listener.getLogger().println("Caught Exception communicating with perforce." + e.getMessage());
e.printStackTrace();
throw new IOException("Unable to communicate with perforce. Check log file for: " + e.getMessage());
} finally {
//Utils.cleanUp();
}
//return false;
}
public int getLastChange(Actionable build) {
// If we are starting a new hudson project on existing work and want to skip the prior history...
if(firstChange > 0)
return firstChange;
// If anything is broken, we will default to 0.
if(build == null)
return 0;
PerforceTagAction action = build.getAction(PerforceTagAction.class);
// If anything is broken, we will default to 0.
if(action == null)
return 0;
return action.getChangeNumber();
}
public static final class PerforceSCMDescriptor extends SCMDescriptor<PerforceSCM> {
private PerforceSCMDescriptor() {
super(PerforceSCM.class, PerforceRepositoryBrowser.class);
load();
}
public String getDisplayName() {
return "Perforce";
}
public SCM newInstance(StaplerRequest req) throws FormException {
String value = req.getParameter("p4.forceSync");
boolean force = false;
if(value != null && !value.equals(""))
force = new Boolean(value);
value = req.getParameter("p4.updateView");
boolean update = false;
if(value != null && !value.equals(""))
update = new Boolean(value);
value = req.getParameter("p4.firstChange");
int firstChange = -1;
if(value != null && !value.equals(""))
firstChange = new Integer(value);
return new PerforceSCM(
req.getParameter("p4.user"),
req.getParameter("p4.passwd"),
req.getParameter("p4.client"),
req.getParameter("p4.port"),
req.getParameter("projectPath"),
req.getParameter("p4.exe"),
req.getParameter("p4.sysRoot"),
req.getParameter("p4.sysDrive"),
force,
update,
firstChange,
RepositoryBrowsers.createInstance(PerforceRepositoryBrowser.class, req, "p4.browser"));
}
public String isValidProjectPath(String path) {
if(!path.startsWith("//")) {
return "Path must start with '//' (Example: //depot/ProjectName/...)";
}
if(!path.endsWith("/...")) {
return "Path must end with Perforce wildcard: '/...' (Example: //depot/ProjectName/...)";
}
return null;
}
protected Depot getDepotFromRequest(StaplerRequest request) {
String port = fixNull(request.getParameter("port")).trim();
String exe = fixNull(request.getParameter("exe")).trim();
String user = fixNull(request.getParameter("user")).trim();
String pass = fixNull(request.getParameter("pass")).trim();
if(port.length()==0 || exe.length() == 0 || user.length() == 0 || pass.length() == 0) {// nothing entered yet
return null;
}
Depot depot = new Depot();
depot.setUser(user);
depot.setPassword(pass);
depot.setPort(port);
depot.setExecutable(exe);
return depot;
}
/**
* Checks if the perforce login credentials are good.
*/
public void doValidatePerforceLogin(StaplerRequest request, StaplerResponse rsp) throws IOException, ServletException {
new FormFieldValidator(request, rsp, false) {
protected void check() throws IOException, ServletException {
Depot depot = getDepotFromRequest(request);
if(depot != null) {
try {
depot.getStatus().isValid();
} catch(PerforceException e) {
error(e.getMessage());
}
}
ok();
return;
}
}.check();
}
/**
* Checks to see if the specified workspace is valid.
*/
public void doValidateWorkspace(StaplerRequest request, StaplerResponse rsp) throws IOException, ServletException {
new FormFieldValidator(request, rsp, false) {
protected void check() throws IOException, ServletException {
Depot depot = getDepotFromRequest(request);
String workspace = request.getParameter("workspace");
if(depot != null) {
try {
depot.getWorkspaces().getWorkspace(workspace);
} catch(PerforceException e) {
error(e.getMessage());
}
}
ok();
return;
}
}.check();
}
/**
* Checks if the value is a valid Perforce project path.
*/
public void doCheckProjectPath(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
new FormFieldValidator(req, rsp, false) {
protected void check() throws IOException, ServletException {
String path = fixNull(request.getParameter("value")).trim();
if(path.length() == 0) {// nothing entered yet
ok();
return;
}
// TODO: Check against depot if the path actually exists via: p4 fstat -m 1 [projectPath]
error(isValidProjectPath(path));
}
}.check();
}
/**
* Checks if the change list entered exists
*/
public void doCheckChangeList(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
new FormFieldValidator(req, rsp, false) {
protected void check() throws IOException, ServletException {
Depot depot = getDepotFromRequest(request);
String change = fixNull(request.getParameter("change")).trim();
if(change.length() == 0) {// nothing entered yet
ok();
return;
}
if(depot != null) {
try {
int number = new Integer(change);
Changelist changelist = depot.getChanges().getChangelist(number);
if(changelist.getChangeNumber() != number)
throw new PerforceException("broken");
} catch(Exception e) {
error("Changelist: " + change + " does not exist.");
}
}
ok();
return;
}
}.check();
}
}
/**
* @return the projectPath
*/
public String getProjectPath() {
return projectPath;
}
/**
* @param projectPath the projectPath to set
*/
public void setProjectPath(String projectPath) {
this.projectPath = projectPath;
}
/**
* @return the p4User
*/
public String getP4User() {
return p4User;
}
/**
* @param user the p4User to set
*/
public void setP4User(String user) {
p4User = user;
}
/**
* @return the p4Passwd
*/
public String getP4Passwd() {
return p4Passwd;
}
/**
* @param passwd the p4Passwd to set
*/
public void setP4Passwd(String passwd) {
p4Passwd = passwd;
}
/**
* @return the p4Port
*/
public String getP4Port() {
return p4Port;
}
/**
* @param port the p4Port to set
*/
public void setP4Port(String port) {
p4Port = port;
}
/**
* @return the p4Client
*/
public String getP4Client() {
return p4Client;
}
/**
* @param client the p4Client to set
*/
public void setP4Client(String client) {
p4Client = client;
}
/**
* @return the p4SysDrive
*/
public String getP4SysDrive() {
return p4SysDrive;
}
/**
* @param sysDrive the p4SysDrive to set
*/
public void setP4SysDrive(String sysDrive) {
p4SysDrive = sysDrive;
}
/**
* @return the p4SysRoot
*/
public String getP4SysRoot() {
return p4SysRoot;
}
/**
* @param sysRoot the p4SysRoot to set
*/
public void setP4SysRoot(String sysRoot) {
p4SysRoot = sysRoot;
}
/**
* @return the p4Exe
*/
public String getP4Exe() {
return p4Exe;
}
/**
* @param exe the p4Exe to set
*/
public void setP4Exe(String exe) {
p4Exe = exe;
}
/**
* @param update True to let the plugin manage the view, false to let the user manage it
*/
public void setUpdateView(boolean update) {
this.updateView = update;
}
/**
* @return True if the plugin manages the view, false if the user does.
*/
public boolean isUpdateView() {
return updateView;
}
/**
* @return True if we are performing a one-time force sync
*/
public boolean isForceSync() {
return forceSync;
}
/**
* @param force True to perform a one time force sync, false to perform normal sync
*/
public void setForceSync(boolean force) {
this.forceSync = force;
}
/**
* This is only for the config screen. Also, it returns a string and not an int.
* This is because we want to show an empty value in the config option if it is not being
* used. The default value of -1 is not exactly empty. So if we are set to default of
* -1, we return an empty string. Anything else and we return the actual change number.
*
* @return The one time use variable, firstChange.
*/
public String getFirstChange() {
if(firstChange < 0)
return "";
return new Integer(firstChange).toString();
}
}
| false | true | public boolean checkout(AbstractBuild build, Launcher launcher, FilePath workspace, BuildListener listener, File changelogFile) throws IOException, InterruptedException {
try {
listener.getLogger().println("Performing sync with Perforce for: " + projectPath);
// Check to make sure our client is mapped to the local hudson directory...
// The problem is that perforce assumes a local directory on your computer maps
// directly to the remote depot. Unfortunately, this doesn't work with they way
// Hudson sets up workspaces. Not to worry! What we do here is manipulate the
// perforce client spec before we do a checkout.
// An alternative would be to setup a single client for each build project. While,
// that is possible, I think its wasteful makes setup time for the user longer as
// they have to go and create a workspace in perforce for each new project.
// 1. Retrieve the client specified, throw an exception if we are configured wrong and the
// client spec doesn't exist.
Workspace p4workspace = getDepot().getWorkspaces().getWorkspace(p4Client);
assert p4workspace != null;
boolean creatingNewWorkspace = p4workspace.getAccess() == null
|| p4workspace.getAccess().length() == 0;
// 2. Before we sync, we need to update the client spec. (we do this on every build)
// Here we are getting the local file path to the workspace. We will use this as the "Root"
// config property of the client spec. This tells perforce where to store the files on our local disk
String localPath = getLocalPathName(workspace);
listener.getLogger().println("Changing P4 Client Root to: " + localPath);
p4workspace.setRoot(localPath);
// 3. Optionally regenerate the workspace view.
// We tell perforce to map the project contents directly (this drops off the project
// name from the workspace. So instead of:
// [Hudson]/[job]/workspace/[Project]/contents
// we get:
// [Hudson]/[job]/workspace/contents
if(updateView || creatingNewWorkspace) {
String view = projectPath + " //" + p4workspace.getName() + "/...";
listener.getLogger().println("Changing P4 Client View to: " + view);
p4workspace.clearViews();
p4workspace.addView(view);
}
// 3b. There is a slight chance of failure with sync'ing to head. I've experienced
// a problem where a sync does not happen and there is no error message. It is when
// the host value of the workspace does not match up with the host hudson is working on.
// Perforce reports an error like: "Client 'hudson' can only be used from host 'workstation'."
// but this does not show up in P4Java as an error. Until P4Java is fixed, the workaround is
// to clear the host value.
p4workspace.setHost("");
// 4. Go and save the client for use when sync'ing in a few...
depot.getWorkspaces().saveWorkspace(p4workspace);
// 5. Get the list of changes since the last time we looked...
int lastChange = getLastChange(build.getPreviousBuild());
listener.getLogger().println("Last sync'd change: " + lastChange);
List<Changelist> changes = depot.getChanges().getChangelistsFromNumbers(depot.getChanges().getChangeNumbersTo(projectPath, lastChange + 1));
if(changes.size() > 0) {
// save the last change we sync'd to for use when polling...
lastChange = changes.get(0).getChangeNumber();
PerforceChangeLogSet.saveToChangeLog(new FileOutputStream(changelogFile), changes);
} else if(!forceSync) {
listener.getLogger().println("No changes since last build.");
return createEmptyChangeLog(changelogFile, listener, "changelog");
}
// 7. Now we can actually do the sync process...
long startTime = System.currentTimeMillis();
listener.getLogger().println("Sync'ing workspace to depot.");
if(forceSync)
listener.getLogger().println("ForceSync flag is set, forcing: p4 sync " + projectPath);
depot.getWorkspaces().syncToHead(projectPath, forceSync);
// reset one time use variables...
forceSync = false;
firstChange = -1;
listener.getLogger().println("Sync complete, took " + (System.currentTimeMillis() - startTime) + " MS");
// Add tagging action...
build.addAction(new PerforceTagAction(build, depot, lastChange, projectPath));
// And I'm spent...
build.getParent().save(); // The pertient things we want to save are the one time use variables...
return true;
} catch(PerforceException e) {
listener.getLogger().print("Caught Exception communicating with perforce. " + e.getMessage());
e.printStackTrace();
throw new IOException("Unable to communicate with perforce. " + e.getMessage());
} finally {
//Utils.cleanUp();
}
}
| public boolean checkout(AbstractBuild build, Launcher launcher, FilePath workspace, BuildListener listener, File changelogFile) throws IOException, InterruptedException {
try {
listener.getLogger().println("Performing sync with Perforce for: " + projectPath);
// Check to make sure our client is mapped to the local hudson directory...
// The problem is that perforce assumes a local directory on your computer maps
// directly to the remote depot. Unfortunately, this doesn't work with they way
// Hudson sets up workspaces. Not to worry! What we do here is manipulate the
// perforce client spec before we do a checkout.
// An alternative would be to setup a single client for each build project. While,
// that is possible, I think its wasteful makes setup time for the user longer as
// they have to go and create a workspace in perforce for each new project.
// 1. Retrieve the client specified, throw an exception if we are configured wrong and the
// client spec doesn't exist.
Workspace p4workspace = getDepot().getWorkspaces().getWorkspace(p4Client);
assert p4workspace != null;
boolean creatingNewWorkspace = p4workspace.getAccess() == null
|| p4workspace.getAccess().length() == 0;
// 2. Before we sync, we need to update the client spec (we do this on every build).
// Here we are getting the local file path to the workspace. We will use this as the "Root"
// config property of the client spec. This tells perforce where to store the files on our local disk
String localPath = getLocalPathName(workspace);
listener.getLogger().println("Changing P4 Client Root to: " + localPath);
p4workspace.setRoot(localPath);
// 3. Optionally regenerate the workspace view.
// We tell perforce to map the project contents directly (this drops off the project
// name from the workspace. So instead of:
// [Hudson]/[job]/workspace/[Project]/contents
// we get:
// [Hudson]/[job]/workspace/contents
if(updateView || creatingNewWorkspace) {
String view = projectPath + " //" + p4workspace.getName() + "/...";
listener.getLogger().println("Changing P4 Client View to: " + view);
p4workspace.clearViews();
p4workspace.addView(view);
}
// 3b. There is a slight chance of failure with sync'ing to head. I've experienced
// a problem where a sync does not happen and there is no error message. It is when
// the host value of the workspace does not match up with the host hudson is working on.
// Perforce reports an error like: "Client 'hudson' can only be used from host 'workstation'."
// but this does not show up in P4Java as an error. Until P4Java is fixed, the workaround is
// to clear the host value.
p4workspace.setHost("");
// 4. Go and save the client for use when sync'ing in a few...
depot.getWorkspaces().saveWorkspace(p4workspace);
// 5. Get the list of changes since the last time we looked...
int lastChange = getLastChange(build.getPreviousBuild());
listener.getLogger().println("Last sync'd change: " + lastChange);
List<Changelist> changes = depot.getChanges().getChangelistsFromNumbers(depot.getChanges().getChangeNumbersTo(projectPath, lastChange + 1));
if(changes.size() > 0) {
// save the last change we sync'd to for use when polling...
lastChange = changes.get(0).getChangeNumber();
PerforceChangeLogSet.saveToChangeLog(new FileOutputStream(changelogFile), changes);
} else if(!forceSync) {
listener.getLogger().println("No changes since last build.");
return createEmptyChangeLog(changelogFile, listener, "changelog");
}
// 7. Now we can actually do the sync process...
long startTime = System.currentTimeMillis();
listener.getLogger().println("Sync'ing workspace to depot.");
if(forceSync)
listener.getLogger().println("ForceSync flag is set, forcing: p4 sync " + projectPath);
depot.getWorkspaces().syncToHead(projectPath, forceSync);
// reset one time use variables...
forceSync = false;
firstChange = -1;
listener.getLogger().println("Sync complete, took " + (System.currentTimeMillis() - startTime) + " MS");
// Add tagging action...
build.addAction(new PerforceTagAction(build, depot, lastChange, projectPath));
// And I'm spent...
build.getParent().save(); // The pertinent things we want to save are the one time use variables...
return true;
} catch(PerforceException e) {
listener.getLogger().print("Caught Exception communicating with perforce. " + e.getMessage());
e.printStackTrace();
throw new IOException("Unable to communicate with perforce. " + e.getMessage());
} finally {
//Utils.cleanUp();
}
}
|
diff --git a/src/core/model/src/main/java/it/geosolutions/geobatch/configuration/event/action/ActionConfiguration.java b/src/core/model/src/main/java/it/geosolutions/geobatch/configuration/event/action/ActionConfiguration.java
index 3c96c339..70f82dd9 100644
--- a/src/core/model/src/main/java/it/geosolutions/geobatch/configuration/event/action/ActionConfiguration.java
+++ b/src/core/model/src/main/java/it/geosolutions/geobatch/configuration/event/action/ActionConfiguration.java
@@ -1,85 +1,86 @@
/*
* GeoBatch - Open Source geospatial batch processing system
* http://geobatch.codehaus.org/
* Copyright (C) 2007-2008-2009 GeoSolutions S.A.S.
* http://www.geo-solutions.it
*
* GPLv3 + Classpath exception
*
* 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 it.geosolutions.geobatch.configuration.event.action;
import it.geosolutions.geobatch.catalog.Configuration;
import it.geosolutions.geobatch.catalog.impl.BaseConfiguration;
import it.geosolutions.geobatch.configuration.event.listener.ProgressListenerConfiguration;
import java.util.ArrayList;
import java.util.List;
public abstract class ActionConfiguration
extends BaseConfiguration
implements Configuration, Cloneable {
private List<String> listenerIds = null;
private List<ProgressListenerConfiguration> listenerConfigurations = new ArrayList<ProgressListenerConfiguration>();
public ActionConfiguration() {
super();
}
public ActionConfiguration(String id, String name, String description, boolean dirty) {
super(id, name, description, dirty);
}
public List<String> getListenerIds() {
return listenerIds;
}
protected void setListenerId(List<String> listenerIds) {
this.listenerIds = listenerIds;
}
public void addListenerConfiguration(ProgressListenerConfiguration plc) {
listenerConfigurations.add(plc);
}
public List<ProgressListenerConfiguration> getListenerConfigurations() {
return listenerConfigurations;
}
public void setListenerConfigurations(List<ProgressListenerConfiguration> listenerConfigurations) {
if(listenerConfigurations == null)
throw new NullPointerException("Can't set listenerConfig list to null");
this.listenerConfigurations = listenerConfigurations;
}
@Override
public ActionConfiguration clone() {
ActionConfiguration bc = (ActionConfiguration) super.clone();
- bc.listenerIds = new ArrayList<String>(listenerIds);
- for (String lid : listenerIds) {
- bc.listenerIds.add(lid);
- }
+ bc.listenerIds = listenerIds == null ?
+ new ArrayList<String>() :
+ new ArrayList<String>(listenerIds);
bc.listenerConfigurations = new ArrayList<ProgressListenerConfiguration>();
- for (ProgressListenerConfiguration plc : listenerConfigurations) {
- bc.listenerConfigurations.add(plc); // CHECKME: shall we clone the configs?
+ if(listenerConfigurations != null) {
+ for (ProgressListenerConfiguration plc : listenerConfigurations) {
+ bc.listenerConfigurations.add(plc); // CHECKME: shall we clone the configs?
+ }
}
return bc;
}
}
| false | true | public ActionConfiguration clone() {
ActionConfiguration bc = (ActionConfiguration) super.clone();
bc.listenerIds = new ArrayList<String>(listenerIds);
for (String lid : listenerIds) {
bc.listenerIds.add(lid);
}
bc.listenerConfigurations = new ArrayList<ProgressListenerConfiguration>();
for (ProgressListenerConfiguration plc : listenerConfigurations) {
bc.listenerConfigurations.add(plc); // CHECKME: shall we clone the configs?
}
return bc;
}
| public ActionConfiguration clone() {
ActionConfiguration bc = (ActionConfiguration) super.clone();
bc.listenerIds = listenerIds == null ?
new ArrayList<String>() :
new ArrayList<String>(listenerIds);
bc.listenerConfigurations = new ArrayList<ProgressListenerConfiguration>();
if(listenerConfigurations != null) {
for (ProgressListenerConfiguration plc : listenerConfigurations) {
bc.listenerConfigurations.add(plc); // CHECKME: shall we clone the configs?
}
}
return bc;
}
|
diff --git a/plugins/org.eclipse.graphiti.ui/src/org/eclipse/graphiti/ui/internal/editor/GFMarqueeToolEntry.java b/plugins/org.eclipse.graphiti.ui/src/org/eclipse/graphiti/ui/internal/editor/GFMarqueeToolEntry.java
index 7ed8946a..dd1dc1e1 100644
--- a/plugins/org.eclipse.graphiti.ui/src/org/eclipse/graphiti/ui/internal/editor/GFMarqueeToolEntry.java
+++ b/plugins/org.eclipse.graphiti.ui/src/org/eclipse/graphiti/ui/internal/editor/GFMarqueeToolEntry.java
@@ -1,90 +1,92 @@
/*******************************************************************************
* <copyright>
*
* Copyright (c) 2005, 2010 SAP AG.
* 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:
* SAP AG - initial API, implementation and documentation
* mwenz - Bug 327669 - removed dependencies to GEF internal stuff
*
* </copyright>
*
*******************************************************************************/
package org.eclipse.graphiti.ui.internal.editor;
import org.eclipse.gef.SharedImages;
import org.eclipse.gef.palette.ToolEntry;
import org.eclipse.gef.tools.MarqueeSelectionTool;
import org.eclipse.graphiti.ui.internal.Messages;
/**
* A palette ToolEntry for a {@link org.eclipse.gef.tools.MarqueeSelectionTool}.
*
* @author hudsonr
* @since 2.1
* @noinstantiate This class is not intended to be instantiated by clients.
* @noextend This class is not intended to be subclassed by clients.
*/
public class GFMarqueeToolEntry extends ToolEntry {
/**
* Creates a new MarqueeToolEntry that can select nodes.
*/
public GFMarqueeToolEntry() {
this(null, null);
}
/**
* Constructor for MarqueeToolEntry.
*
* @param label
* the label
*/
public GFMarqueeToolEntry(String label) {
this(label, null);
}
/**
* Constructor for MarqueeToolEntry.
*
* @param label
* the label; can be <code>null</code>
* @param description
* the description (can be <code>null</code>)
*/
public GFMarqueeToolEntry(String label, String description) {
super(label, description, SharedImages.DESC_MARQUEE_TOOL_16, SharedImages.DESC_MARQUEE_TOOL_24, GFMarqueeSelectionTool.class);
if (label == null || label.length() == 0)
setLabel(Messages.GFMarqueeToolEntry_Marquee);
setUserModificationPermission(PERMISSION_NO_MODIFICATION);
}
/**
* Gets the description.
*
* @return the description
*
* @see org.eclipse.gef.palette.PaletteEntry#getDescription()
*/
@Override
public String getDescription() {
String description = super.getDescription();
if (description != null)
return description;
Object value = getToolProperty(MarqueeSelectionTool.PROPERTY_MARQUEE_BEHAVIOR);
if (value instanceof Integer) {
int selectionType = ((Integer) value).intValue();
- if (selectionType == MarqueeSelectionTool.BEHAVIOR_NODES_CONTAINED_AND_RELATED_CONNECTIONS)
+ // TODO Replace after 0.8.0 (in 0.8.0 Indigo we need to be
+ // compatible with GEF 3.6 and 3.7)
+ if (selectionType == MarqueeSelectionTool.BEHAVIOR_NODES_AND_CONNECTIONS)
return Messages.GFMarqueeToolEntry_MarqueeBothNodesAndRelatedConnections;
if (selectionType == MarqueeSelectionTool.BEHAVIOR_CONNECTIONS_TOUCHED)
return Messages.GFMarqueeToolEntry_MarqueeSelectionTouched;
}
return Messages.GFMarqueeToolEntry_MarqueeNodesTouched;
}
}
| true | true | public String getDescription() {
String description = super.getDescription();
if (description != null)
return description;
Object value = getToolProperty(MarqueeSelectionTool.PROPERTY_MARQUEE_BEHAVIOR);
if (value instanceof Integer) {
int selectionType = ((Integer) value).intValue();
if (selectionType == MarqueeSelectionTool.BEHAVIOR_NODES_CONTAINED_AND_RELATED_CONNECTIONS)
return Messages.GFMarqueeToolEntry_MarqueeBothNodesAndRelatedConnections;
if (selectionType == MarqueeSelectionTool.BEHAVIOR_CONNECTIONS_TOUCHED)
return Messages.GFMarqueeToolEntry_MarqueeSelectionTouched;
}
return Messages.GFMarqueeToolEntry_MarqueeNodesTouched;
}
| public String getDescription() {
String description = super.getDescription();
if (description != null)
return description;
Object value = getToolProperty(MarqueeSelectionTool.PROPERTY_MARQUEE_BEHAVIOR);
if (value instanceof Integer) {
int selectionType = ((Integer) value).intValue();
// TODO Replace after 0.8.0 (in 0.8.0 Indigo we need to be
// compatible with GEF 3.6 and 3.7)
if (selectionType == MarqueeSelectionTool.BEHAVIOR_NODES_AND_CONNECTIONS)
return Messages.GFMarqueeToolEntry_MarqueeBothNodesAndRelatedConnections;
if (selectionType == MarqueeSelectionTool.BEHAVIOR_CONNECTIONS_TOUCHED)
return Messages.GFMarqueeToolEntry_MarqueeSelectionTouched;
}
return Messages.GFMarqueeToolEntry_MarqueeNodesTouched;
}
|
diff --git a/hokan_ng-core-engine/src/main/java/com/freakz/hokan_ng/core_engine/command/handlers/HoroCmd.java b/hokan_ng-core-engine/src/main/java/com/freakz/hokan_ng/core_engine/command/handlers/HoroCmd.java
index ba87ab4..6909aa9 100644
--- a/hokan_ng-core-engine/src/main/java/com/freakz/hokan_ng/core_engine/command/handlers/HoroCmd.java
+++ b/hokan_ng-core-engine/src/main/java/com/freakz/hokan_ng/core_engine/command/handlers/HoroCmd.java
@@ -1,60 +1,60 @@
package com.freakz.hokan_ng.core_engine.command.handlers;
import com.freakz.hokan_ng.common.exception.HokanException;
import com.freakz.hokan_ng.common.rest.EngineRequest;
import com.freakz.hokan_ng.common.rest.EngineResponse;
import com.freakz.hokan_ng.common.updaters.UpdaterData;
import com.freakz.hokan_ng.common.updaters.UpdaterManagerService;
import com.freakz.hokan_ng.common.updaters.horo.HoroHolder;
import com.freakz.hokan_ng.common.updaters.horo.HoroUpdater;
import com.martiansoftware.jsap.JSAPResult;
import com.martiansoftware.jsap.UnflaggedOption;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* User: petria
* Date: 11/21/13
* Time: 1:43 PM
*
* @author Petri Airio <[email protected]>
*/
@Component
public class HoroCmd extends Cmd {
@Autowired
private UpdaterManagerService updaterManagerService;
private final static String ARG_HORO = "horo";
public HoroCmd() {
super();
UnflaggedOption opt = new UnflaggedOption(ARG_HORO)
.setRequired(true)
.setGreedy(false);
registerParameter(opt);
}
@Override
public String getMatchPattern() {
return "!horo.*";
}
@Override
public void handleRequest(EngineRequest request, EngineResponse response, JSAPResult results) throws HokanException {
String horo = results.getString(ARG_HORO);
HoroUpdater horoUpdater = (HoroUpdater) updaterManagerService.getUpdater("horoUpdater");
UpdaterData updaterData = new UpdaterData();
horoUpdater.getData(updaterData, horo);
HoroHolder hh = (HoroHolder) updaterData.getData();
if (hh != null) {
response.setResponseMessage(hh.toString());
} else {
- response.setResponseMessage("Saat dildoo perään et pääse pylsimään!");
+ response.setResponseMessage("Saat dildoo perään ja et pääse pylsimään!");
}
}
}
| true | true | public void handleRequest(EngineRequest request, EngineResponse response, JSAPResult results) throws HokanException {
String horo = results.getString(ARG_HORO);
HoroUpdater horoUpdater = (HoroUpdater) updaterManagerService.getUpdater("horoUpdater");
UpdaterData updaterData = new UpdaterData();
horoUpdater.getData(updaterData, horo);
HoroHolder hh = (HoroHolder) updaterData.getData();
if (hh != null) {
response.setResponseMessage(hh.toString());
} else {
response.setResponseMessage("Saat dildoo perään et pääse pylsimään!");
}
}
| public void handleRequest(EngineRequest request, EngineResponse response, JSAPResult results) throws HokanException {
String horo = results.getString(ARG_HORO);
HoroUpdater horoUpdater = (HoroUpdater) updaterManagerService.getUpdater("horoUpdater");
UpdaterData updaterData = new UpdaterData();
horoUpdater.getData(updaterData, horo);
HoroHolder hh = (HoroHolder) updaterData.getData();
if (hh != null) {
response.setResponseMessage(hh.toString());
} else {
response.setResponseMessage("Saat dildoo perään ja et pääse pylsimään!");
}
}
|
diff --git a/src/main/java/se/nctrl/jenkins/plugin/CTSuiteLogParser.java b/src/main/java/se/nctrl/jenkins/plugin/CTSuiteLogParser.java
index 27f9119..68de2c7 100644
--- a/src/main/java/se/nctrl/jenkins/plugin/CTSuiteLogParser.java
+++ b/src/main/java/se/nctrl/jenkins/plugin/CTSuiteLogParser.java
@@ -1,351 +1,351 @@
package se.nctrl.jenkins.plugin;
import hudson.model.AbstractBuild;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
* @author karl
*/
public class CTSuiteLogParser extends CTLogParser {
private enum Fields {
CASES,
USER,
HOST,
HOSTS,
LAN,
EMULATOR_VSN,
EMULATOR,
OTP_RELEASE,
STARTED,
CASE,
LOGFILE,
ENDED,
RESULT,
ELAPSED,
GROUP_TIME,
FINISHED,
FAILED,
SUCCESSFUL,
USER_SKIPPED,
AUTO_SKIPPED,
GROUP_PROPS,
NODE_START,
NODE_STOP
}
private static Pattern field_pattern = Pattern.compile("^=(\\w+)\\s+(.+)$");
private static Pattern comment_pattern = Pattern.compile("^===.+$");
private static final Logger logger = Logger.getLogger(CTSuiteLogParser.class.getName());
private BufferedReader br;
private CTResult tr_root = null;
private CTResult tr_current_child = null;
private boolean parsing_child = false;
private String suite_path;
public CTSuiteLogParser(AbstractBuild build) {
super(build);
}
public CTResult parse(File f) throws FileNotFoundException, IOException {
this.tr_root = new CTResult(this.getBuild());
//this.suite_path = f.
FileInputStream fs = new FileInputStream(f);
this.br = new BufferedReader(new InputStreamReader(fs, "UTF-8"));
try {
while (true) {
String l = br.readLine();
if (l == null) {
break;
}
Matcher f_m = field_pattern.matcher(l);
if (f_m.matches()) {
String fieldname = f_m.group(1);
String value = f_m.group(2);
parseField(fieldname,value);
}
}
} finally {
br.close();
}
return tr_root;
}
private void parseField(String fieldname, String value) throws IOException
{
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
logger.log(Level.FINE, "parsed : field = {0}, value = {1}", new Object[]{fieldname, value});
Fields f = Fields.valueOf(fieldname.toUpperCase());
switch (f) {
case CASES:
int cases;
if (value.equals("unknown")) { // this is apparently possible
cases = 0;
logger.log(Level.WARNING, "Cases had value 'unknown'");
} else {
cases = Integer.parseInt(value);
}
logger.log(Level.FINE, "Set cases to {0}", cases);
this.tr_root.setCases(cases);
break;
case USER:
logger.log(Level.FINE, "Set user to {0}", value);
this.tr_root.setUser(value);
break;
case HOST:
logger.log(Level.FINE, "Set host to {0}", value);
this.tr_root.setHost(value);
break;
case HOSTS:
logger.log(Level.FINE, "Set hosts to {0}", value);
this.tr_root.setHosts(value);
break;
case LAN:
logger.log(Level.FINE, "Set lan to {0}", value);
this.tr_root.setLan(value);
break;
case EMULATOR_VSN:
logger.log(Level.FINE, "Set emulator_vsn to {0}", value);
this.tr_root.setEmulator_vsn(value);
break;
case EMULATOR:
logger.log(Level.FINE, "Set emulator to {0}", value);
this.tr_root.setEmulator(value);
break;
case OTP_RELEASE:
logger.log(Level.FINE, "Set otp_release to {0}", value);
this.tr_root.setOtp_release(value);
break;
case STARTED:
Date started_date;
try {
started_date = df.parse(value);
logger.log(Level.FINE, "Set date to {0}", started_date.toString());
} catch (ParseException ex) {
started_date = null;
logger.log(Level.SEVERE, "Error while parsing date.");
}
if (this.parsing_child && this.tr_current_child != null) {
this.tr_current_child.setStarted(started_date);
} else if (!this.parsing_child) {
this.tr_root.setStarted(started_date);
} else {
logger.log(Level.SEVERE, "Unexpected date-field.");
}
break;
case CASE:
if (this.parsing_child) {
this.tr_root.addChild(this.tr_current_child);
}
logger.log(Level.FINE, "Creating new child = {0}", value);
this.tr_current_child = new CTResult(this.getBuild());
this.tr_current_child.setCase_name(value);
this.parsing_child = true;
break;
case LOGFILE:
if (this.parsing_child && this.tr_current_child != null) {
logger.log(Level.FINE, "Set logfile to {0}", value);
this.tr_current_child.setLog_file(value);
} else if (!this.parsing_child) {
logger.log(Level.SEVERE, "Unexpected logfile-field.");
}
break;
case ENDED:
if (this.parsing_child && this.tr_current_child != null) {
Date ended_date;
try {
ended_date = df.parse(value);
logger.log(Level.FINE, "Set date to {0}", ended_date.toString());
} catch (ParseException ex) {
ended_date = null;
logger.log(Level.SEVERE, "Error while parsing date.");
}
this.tr_current_child.setEnded(ended_date);
} else if (!this.parsing_child) {
logger.log(Level.SEVERE, "Unexpected ended-field.");
}
break;
case RESULT:
int res = -1;
String value2 = this.readMultiLine();
String value3 = value + value2;
if (this.parsing_child && this.tr_current_child != null) {
if (value3 != null) {
if (value3.substring(0, 2).toUpperCase().equals("OK")) {
logger.log(Level.FINE, "Set result to OK");
res = 1;
} else if (value3.substring(0, 6).toUpperCase().equals("FAILED")) {
logger.log(Level.FINE, "Set result to FAILED");
res = 0;
} else if (value3.substring(0, 7).toUpperCase().equals("SKIPPED")) {
logger.log(Level.FINE, "Set result to SKIPPED");
res = 2;
} else {
logger.log(Level.SEVERE, "Unable to parse result-field (Invalid result)");
}
} else {
logger.log(Level.SEVERE, "Unable to parse result-field (Empty result)");
}
this.tr_current_child.setResult(res);
this.tr_current_child.setResult_msg(value3);
} else if (!this.parsing_child) {
logger.log(Level.SEVERE, "Unexpected result-field.");
}
break;
case ELAPSED:
if (this.parsing_child && this.tr_current_child != null) {
float elapsed = Float.parseFloat(value);
logger.log(Level.FINE, "Set elapsed to {0}", elapsed);
this.tr_root.setElapsed(elapsed);
} else if (!this.parsing_child) {
logger.log(Level.SEVERE, "Unexpected elapsed-field.");
}
break;
case GROUP_TIME:
logger.log(Level.FINE, "Set group time to {0}", value);
this.tr_root.setGroup_time(value);
break;
case FINISHED:
Date finished_date;
try {
finished_date = df.parse(value);
logger.log(Level.FINE, "Set finished date to {0}", finished_date.toString());
} catch (ParseException ex) {
finished_date = null;
logger.log(Level.SEVERE, "Error while parsing date.");
}
- this.tr_root.setEnded(finished_date);
+ this.tr_root.setFinished(finished_date);
break;
case SUCCESSFUL:
int successful = Integer.parseInt(value);
logger.log(Level.FINE, "Set successful to {0}", successful);
this.tr_root.setSuccessful(successful);
break;
case FAILED:
int failed = Integer.parseInt(value);
logger.log(Level.FINE, "Set failed to {0}", failed);
this.tr_root.setSuccessful(failed);
break;
case USER_SKIPPED:
int user_skipped = Integer.parseInt(value);
logger.log(Level.FINE, "Set user_skipped to {0}", user_skipped);
this.tr_root.setUser_skipped(user_skipped);
break;
case AUTO_SKIPPED:
int auto_skipped = Integer.parseInt(value);
logger.log(Level.FINE, "Set auto_skipped to {0}", auto_skipped);
this.tr_root.setAuto_skipped(auto_skipped);
break;
case GROUP_PROPS:
String gp_value2 = this.readMultiLine();
String gp_value3 = value + gp_value2;
this.tr_root.setGroup_props(gp_value3);
break;
case NODE_START:
logger.log(Level.FINE, "Set node start to {0}", value);
this.tr_root.setNode_start(value);
break;
case NODE_STOP:
logger.log(Level.FINE, "Set node stop to {0}", value);
this.tr_root.setNode_stop(value);
break;
default:
}
}
private String readMultiLine() throws IOException {
StringBuilder sb = new StringBuilder();
boolean done = false;
while (!done) {
br.mark(1024);
String l = br.readLine();
if (l != null)
{
Matcher f_m = field_pattern.matcher(l);
Matcher c_m = comment_pattern.matcher(l);
if (f_m.matches() || c_m.matches()) {
br.reset(); // we've read past the multiline value
done = true;
} else {
sb.append(l);
}
} else { done = true; }
}
return sb.toString();
}
}
| true | true | private void parseField(String fieldname, String value) throws IOException
{
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
logger.log(Level.FINE, "parsed : field = {0}, value = {1}", new Object[]{fieldname, value});
Fields f = Fields.valueOf(fieldname.toUpperCase());
switch (f) {
case CASES:
int cases;
if (value.equals("unknown")) { // this is apparently possible
cases = 0;
logger.log(Level.WARNING, "Cases had value 'unknown'");
} else {
cases = Integer.parseInt(value);
}
logger.log(Level.FINE, "Set cases to {0}", cases);
this.tr_root.setCases(cases);
break;
case USER:
logger.log(Level.FINE, "Set user to {0}", value);
this.tr_root.setUser(value);
break;
case HOST:
logger.log(Level.FINE, "Set host to {0}", value);
this.tr_root.setHost(value);
break;
case HOSTS:
logger.log(Level.FINE, "Set hosts to {0}", value);
this.tr_root.setHosts(value);
break;
case LAN:
logger.log(Level.FINE, "Set lan to {0}", value);
this.tr_root.setLan(value);
break;
case EMULATOR_VSN:
logger.log(Level.FINE, "Set emulator_vsn to {0}", value);
this.tr_root.setEmulator_vsn(value);
break;
case EMULATOR:
logger.log(Level.FINE, "Set emulator to {0}", value);
this.tr_root.setEmulator(value);
break;
case OTP_RELEASE:
logger.log(Level.FINE, "Set otp_release to {0}", value);
this.tr_root.setOtp_release(value);
break;
case STARTED:
Date started_date;
try {
started_date = df.parse(value);
logger.log(Level.FINE, "Set date to {0}", started_date.toString());
} catch (ParseException ex) {
started_date = null;
logger.log(Level.SEVERE, "Error while parsing date.");
}
if (this.parsing_child && this.tr_current_child != null) {
this.tr_current_child.setStarted(started_date);
} else if (!this.parsing_child) {
this.tr_root.setStarted(started_date);
} else {
logger.log(Level.SEVERE, "Unexpected date-field.");
}
break;
case CASE:
if (this.parsing_child) {
this.tr_root.addChild(this.tr_current_child);
}
logger.log(Level.FINE, "Creating new child = {0}", value);
this.tr_current_child = new CTResult(this.getBuild());
this.tr_current_child.setCase_name(value);
this.parsing_child = true;
break;
case LOGFILE:
if (this.parsing_child && this.tr_current_child != null) {
logger.log(Level.FINE, "Set logfile to {0}", value);
this.tr_current_child.setLog_file(value);
} else if (!this.parsing_child) {
logger.log(Level.SEVERE, "Unexpected logfile-field.");
}
break;
case ENDED:
if (this.parsing_child && this.tr_current_child != null) {
Date ended_date;
try {
ended_date = df.parse(value);
logger.log(Level.FINE, "Set date to {0}", ended_date.toString());
} catch (ParseException ex) {
ended_date = null;
logger.log(Level.SEVERE, "Error while parsing date.");
}
this.tr_current_child.setEnded(ended_date);
} else if (!this.parsing_child) {
logger.log(Level.SEVERE, "Unexpected ended-field.");
}
break;
case RESULT:
int res = -1;
String value2 = this.readMultiLine();
String value3 = value + value2;
if (this.parsing_child && this.tr_current_child != null) {
if (value3 != null) {
if (value3.substring(0, 2).toUpperCase().equals("OK")) {
logger.log(Level.FINE, "Set result to OK");
res = 1;
} else if (value3.substring(0, 6).toUpperCase().equals("FAILED")) {
logger.log(Level.FINE, "Set result to FAILED");
res = 0;
} else if (value3.substring(0, 7).toUpperCase().equals("SKIPPED")) {
logger.log(Level.FINE, "Set result to SKIPPED");
res = 2;
} else {
logger.log(Level.SEVERE, "Unable to parse result-field (Invalid result)");
}
} else {
logger.log(Level.SEVERE, "Unable to parse result-field (Empty result)");
}
this.tr_current_child.setResult(res);
this.tr_current_child.setResult_msg(value3);
} else if (!this.parsing_child) {
logger.log(Level.SEVERE, "Unexpected result-field.");
}
break;
case ELAPSED:
if (this.parsing_child && this.tr_current_child != null) {
float elapsed = Float.parseFloat(value);
logger.log(Level.FINE, "Set elapsed to {0}", elapsed);
this.tr_root.setElapsed(elapsed);
} else if (!this.parsing_child) {
logger.log(Level.SEVERE, "Unexpected elapsed-field.");
}
break;
case GROUP_TIME:
logger.log(Level.FINE, "Set group time to {0}", value);
this.tr_root.setGroup_time(value);
break;
case FINISHED:
Date finished_date;
try {
finished_date = df.parse(value);
logger.log(Level.FINE, "Set finished date to {0}", finished_date.toString());
} catch (ParseException ex) {
finished_date = null;
logger.log(Level.SEVERE, "Error while parsing date.");
}
this.tr_root.setEnded(finished_date);
break;
case SUCCESSFUL:
int successful = Integer.parseInt(value);
logger.log(Level.FINE, "Set successful to {0}", successful);
this.tr_root.setSuccessful(successful);
break;
case FAILED:
int failed = Integer.parseInt(value);
logger.log(Level.FINE, "Set failed to {0}", failed);
this.tr_root.setSuccessful(failed);
break;
case USER_SKIPPED:
int user_skipped = Integer.parseInt(value);
logger.log(Level.FINE, "Set user_skipped to {0}", user_skipped);
this.tr_root.setUser_skipped(user_skipped);
break;
case AUTO_SKIPPED:
int auto_skipped = Integer.parseInt(value);
logger.log(Level.FINE, "Set auto_skipped to {0}", auto_skipped);
this.tr_root.setAuto_skipped(auto_skipped);
break;
case GROUP_PROPS:
String gp_value2 = this.readMultiLine();
String gp_value3 = value + gp_value2;
this.tr_root.setGroup_props(gp_value3);
break;
case NODE_START:
logger.log(Level.FINE, "Set node start to {0}", value);
this.tr_root.setNode_start(value);
break;
case NODE_STOP:
logger.log(Level.FINE, "Set node stop to {0}", value);
this.tr_root.setNode_stop(value);
break;
default:
}
}
| private void parseField(String fieldname, String value) throws IOException
{
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
logger.log(Level.FINE, "parsed : field = {0}, value = {1}", new Object[]{fieldname, value});
Fields f = Fields.valueOf(fieldname.toUpperCase());
switch (f) {
case CASES:
int cases;
if (value.equals("unknown")) { // this is apparently possible
cases = 0;
logger.log(Level.WARNING, "Cases had value 'unknown'");
} else {
cases = Integer.parseInt(value);
}
logger.log(Level.FINE, "Set cases to {0}", cases);
this.tr_root.setCases(cases);
break;
case USER:
logger.log(Level.FINE, "Set user to {0}", value);
this.tr_root.setUser(value);
break;
case HOST:
logger.log(Level.FINE, "Set host to {0}", value);
this.tr_root.setHost(value);
break;
case HOSTS:
logger.log(Level.FINE, "Set hosts to {0}", value);
this.tr_root.setHosts(value);
break;
case LAN:
logger.log(Level.FINE, "Set lan to {0}", value);
this.tr_root.setLan(value);
break;
case EMULATOR_VSN:
logger.log(Level.FINE, "Set emulator_vsn to {0}", value);
this.tr_root.setEmulator_vsn(value);
break;
case EMULATOR:
logger.log(Level.FINE, "Set emulator to {0}", value);
this.tr_root.setEmulator(value);
break;
case OTP_RELEASE:
logger.log(Level.FINE, "Set otp_release to {0}", value);
this.tr_root.setOtp_release(value);
break;
case STARTED:
Date started_date;
try {
started_date = df.parse(value);
logger.log(Level.FINE, "Set date to {0}", started_date.toString());
} catch (ParseException ex) {
started_date = null;
logger.log(Level.SEVERE, "Error while parsing date.");
}
if (this.parsing_child && this.tr_current_child != null) {
this.tr_current_child.setStarted(started_date);
} else if (!this.parsing_child) {
this.tr_root.setStarted(started_date);
} else {
logger.log(Level.SEVERE, "Unexpected date-field.");
}
break;
case CASE:
if (this.parsing_child) {
this.tr_root.addChild(this.tr_current_child);
}
logger.log(Level.FINE, "Creating new child = {0}", value);
this.tr_current_child = new CTResult(this.getBuild());
this.tr_current_child.setCase_name(value);
this.parsing_child = true;
break;
case LOGFILE:
if (this.parsing_child && this.tr_current_child != null) {
logger.log(Level.FINE, "Set logfile to {0}", value);
this.tr_current_child.setLog_file(value);
} else if (!this.parsing_child) {
logger.log(Level.SEVERE, "Unexpected logfile-field.");
}
break;
case ENDED:
if (this.parsing_child && this.tr_current_child != null) {
Date ended_date;
try {
ended_date = df.parse(value);
logger.log(Level.FINE, "Set date to {0}", ended_date.toString());
} catch (ParseException ex) {
ended_date = null;
logger.log(Level.SEVERE, "Error while parsing date.");
}
this.tr_current_child.setEnded(ended_date);
} else if (!this.parsing_child) {
logger.log(Level.SEVERE, "Unexpected ended-field.");
}
break;
case RESULT:
int res = -1;
String value2 = this.readMultiLine();
String value3 = value + value2;
if (this.parsing_child && this.tr_current_child != null) {
if (value3 != null) {
if (value3.substring(0, 2).toUpperCase().equals("OK")) {
logger.log(Level.FINE, "Set result to OK");
res = 1;
} else if (value3.substring(0, 6).toUpperCase().equals("FAILED")) {
logger.log(Level.FINE, "Set result to FAILED");
res = 0;
} else if (value3.substring(0, 7).toUpperCase().equals("SKIPPED")) {
logger.log(Level.FINE, "Set result to SKIPPED");
res = 2;
} else {
logger.log(Level.SEVERE, "Unable to parse result-field (Invalid result)");
}
} else {
logger.log(Level.SEVERE, "Unable to parse result-field (Empty result)");
}
this.tr_current_child.setResult(res);
this.tr_current_child.setResult_msg(value3);
} else if (!this.parsing_child) {
logger.log(Level.SEVERE, "Unexpected result-field.");
}
break;
case ELAPSED:
if (this.parsing_child && this.tr_current_child != null) {
float elapsed = Float.parseFloat(value);
logger.log(Level.FINE, "Set elapsed to {0}", elapsed);
this.tr_root.setElapsed(elapsed);
} else if (!this.parsing_child) {
logger.log(Level.SEVERE, "Unexpected elapsed-field.");
}
break;
case GROUP_TIME:
logger.log(Level.FINE, "Set group time to {0}", value);
this.tr_root.setGroup_time(value);
break;
case FINISHED:
Date finished_date;
try {
finished_date = df.parse(value);
logger.log(Level.FINE, "Set finished date to {0}", finished_date.toString());
} catch (ParseException ex) {
finished_date = null;
logger.log(Level.SEVERE, "Error while parsing date.");
}
this.tr_root.setFinished(finished_date);
break;
case SUCCESSFUL:
int successful = Integer.parseInt(value);
logger.log(Level.FINE, "Set successful to {0}", successful);
this.tr_root.setSuccessful(successful);
break;
case FAILED:
int failed = Integer.parseInt(value);
logger.log(Level.FINE, "Set failed to {0}", failed);
this.tr_root.setSuccessful(failed);
break;
case USER_SKIPPED:
int user_skipped = Integer.parseInt(value);
logger.log(Level.FINE, "Set user_skipped to {0}", user_skipped);
this.tr_root.setUser_skipped(user_skipped);
break;
case AUTO_SKIPPED:
int auto_skipped = Integer.parseInt(value);
logger.log(Level.FINE, "Set auto_skipped to {0}", auto_skipped);
this.tr_root.setAuto_skipped(auto_skipped);
break;
case GROUP_PROPS:
String gp_value2 = this.readMultiLine();
String gp_value3 = value + gp_value2;
this.tr_root.setGroup_props(gp_value3);
break;
case NODE_START:
logger.log(Level.FINE, "Set node start to {0}", value);
this.tr_root.setNode_start(value);
break;
case NODE_STOP:
logger.log(Level.FINE, "Set node stop to {0}", value);
this.tr_root.setNode_stop(value);
break;
default:
}
}
|
diff --git a/Character_Equipment_Impl/src/net/sf/anathema/character/equipment/impl/character/view/EquipmentObjectView.java b/Character_Equipment_Impl/src/net/sf/anathema/character/equipment/impl/character/view/EquipmentObjectView.java
index 01270a5ff7..965e466e56 100644
--- a/Character_Equipment_Impl/src/net/sf/anathema/character/equipment/impl/character/view/EquipmentObjectView.java
+++ b/Character_Equipment_Impl/src/net/sf/anathema/character/equipment/impl/character/view/EquipmentObjectView.java
@@ -1,93 +1,94 @@
package net.sf.anathema.character.equipment.impl.character.view;
import net.disy.commons.core.model.BooleanModel;
import net.disy.commons.swing.action.ActionWidgetFactory;
import net.disy.commons.swing.action.SmartToggleAction;
import net.disy.commons.swing.layout.grid.GridDialogLayout;
import net.sf.anathema.character.equipment.character.view.IEquipmentObjectView;
import net.sf.anathema.character.library.taskpane.ITaskPaneGroupView;
import net.sf.anathema.lib.gui.GuiUtilities;
import org.jdesktop.swingx.JXTaskPane;
import javax.swing.Action;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.util.HashMap;
import java.util.Map;
public class EquipmentObjectView implements IEquipmentObjectView, ITaskPaneGroupView {
private final JXTaskPane taskGroup = new JXTaskPane();
private final JLabel descriptionLabel = new JLabel();
private final Map<BooleanModel, JCheckBox> boxes = new HashMap<BooleanModel, JCheckBox>();
private final Map<BooleanModel, JPanel> boxPanels = new HashMap<BooleanModel, JPanel>();
public EquipmentObjectView() {
taskGroup.add(descriptionLabel);
}
public void setItemTitle(String title) {
taskGroup.setTitle(title);
}
public void setItemDescription(String text) {
descriptionLabel.setText(text);
GuiUtilities.revalidate(taskGroup);
}
public void clearContents() {
taskGroup.removeAll();
boxes.clear();
boxPanels.clear();
}
public BooleanModel addStats(String description) {
BooleanModel isSelectedModel = new BooleanModel();
JCheckBox box = ActionWidgetFactory.createCheckBox(new SmartToggleAction(isSelectedModel, description));
boxes.put(isSelectedModel, box);
GridDialogLayout layout = new GridDialogLayout(1, false);
+ layout.setVerticalSpacing(0);
JPanel panel = new JPanel(layout);
panel.add(box);
taskGroup.add(panel);
boxPanels.put(isSelectedModel, panel);
return isSelectedModel;
}
public BooleanModel addOptionFlag(BooleanModel base, String description) {
BooleanModel isSelectedModel = new BooleanModel();
JPanel basePanel = boxPanels.get(base);
if (basePanel != null)
{
JPanel optionPanel = new JPanel(new GridDialogLayout(2, false));
optionPanel.add(new JLabel(" ..."));
JCheckBox box = ActionWidgetFactory.createCheckBox(new SmartToggleAction(isSelectedModel, description));
boxes.put(isSelectedModel, box);
optionPanel.add(box);
basePanel.add(optionPanel);
}
return isSelectedModel;
}
public void updateStatText(BooleanModel model, String newText)
{
boxes.get(model).setText(newText);
}
public void setEnabled(BooleanModel model, boolean enabled)
{
boxes.get(model).setEnabled(enabled);
}
public JXTaskPane getTaskGroup() {
return taskGroup;
}
public void addAction(Action action) {
taskGroup.add(action);
}
}
| true | true | public BooleanModel addStats(String description) {
BooleanModel isSelectedModel = new BooleanModel();
JCheckBox box = ActionWidgetFactory.createCheckBox(new SmartToggleAction(isSelectedModel, description));
boxes.put(isSelectedModel, box);
GridDialogLayout layout = new GridDialogLayout(1, false);
JPanel panel = new JPanel(layout);
panel.add(box);
taskGroup.add(panel);
boxPanels.put(isSelectedModel, panel);
return isSelectedModel;
}
| public BooleanModel addStats(String description) {
BooleanModel isSelectedModel = new BooleanModel();
JCheckBox box = ActionWidgetFactory.createCheckBox(new SmartToggleAction(isSelectedModel, description));
boxes.put(isSelectedModel, box);
GridDialogLayout layout = new GridDialogLayout(1, false);
layout.setVerticalSpacing(0);
JPanel panel = new JPanel(layout);
panel.add(box);
taskGroup.add(panel);
boxPanels.put(isSelectedModel, panel);
return isSelectedModel;
}
|
diff --git a/src/org/plantuml/idea/plantuml/PlantUml.java b/src/org/plantuml/idea/plantuml/PlantUml.java
index 0271f9e..7d43c8a 100644
--- a/src/org/plantuml/idea/plantuml/PlantUml.java
+++ b/src/org/plantuml/idea/plantuml/PlantUml.java
@@ -1,122 +1,122 @@
package org.plantuml.idea.plantuml;
import net.sourceforge.plantuml.BlockUml;
import net.sourceforge.plantuml.FileFormat;
import net.sourceforge.plantuml.FileFormatOption;
import net.sourceforge.plantuml.SourceStringReader;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author Eugene Steinberg
*/
public class PlantUml {
public static final String TESTDOT = "@startuml\ntestdot\n@enduml";
public static final String UMLSTART = "@start";
public enum ImageFormat {
PNG {
@Override
FileFormat getFormat() {
return FileFormat.PNG;
}
},
SVG {
@Override
FileFormat getFormat() {
return FileFormat.SVG;
}
},
EPS {
@Override
FileFormat getFormat() {
return FileFormat.EPS;
}
};
abstract FileFormat getFormat();
}
public static PlantUmlResult render(String source) {
return render(source, ImageFormat.PNG);
}
/**
* Renders given source code into diagram
*
* @param source plantUml source code
* @param format desired image format
* @return rendering result
*/
public static PlantUmlResult render(String source, ImageFormat format) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
String desc = null;
String error = null;
try {
// image generation.
SourceStringReader reader = new SourceStringReader(source);
// Write the image to "os"
desc = reader.generateImage(os, new FileFormatOption(format.getFormat()));
- } catch (Exception e) {
+ } catch (Throwable e) {
error = e.getMessage();
}
return new PlantUmlResult(os.toByteArray(), desc, error);
}
/**
* Renders source code and saves diagram images to files according to provided naming scheme
* and image format.
*
* @param source source code to be rendered
* @param format image format
* @param fileName fileName to use with first file
* @param fileNameFormat file naming scheme for further files
* @throws IOException in case of rendering or saving fails
*/
public static void renderAndSave(String source, ImageFormat format, String fileName, String fileNameFormat)
throws IOException {
SourceStringReader reader = new SourceStringReader(source);
List<BlockUml> blocks = reader.getBlocks();
for (int i = 0; i < blocks.size(); i++) {
String fName = i == 0 ? fileName : String.format(fileNameFormat, i);
FileOutputStream outputStream = new FileOutputStream(fName);
reader.generateImage(outputStream, i, new FileFormatOption(format.getFormat()));
outputStream.close();
}
}
private static Pattern sourcePattern =
Pattern.compile("(?:(@start(?:uml|dot|jcckit|ditaa|salt)(?s).*?(?:@end(?:uml|dot|jcckit|ditaa|salt)|$))(?s).*?)+");
/**
* Extracts plantUML diagram source code from the given string starting from given offset
* <ul>
* <li>Relies on having @startuml and @enduml tags (puml tags) wrapping plantuml sourcePattern code</li>
* <li>If offset happens to be inside puml tags, returns corresponding sourcePattern code.</li>
* <li>If offset happens to be outside puml tags, returns empty string </li>
* </ul>
*
* @param text source code containing multiple plantuml sources
* @param offset offset in the text from which plantuml sourcePattern is extracted
* @return extracted plantUml code, including @startuml and @enduml tags or empty string if
* no valid sourcePattern code was found
*/
public static String extractSource(String text, int offset) {
if (!text.contains(UMLSTART)) return "";
Matcher matcher = sourcePattern.matcher(text);
while (matcher.find()) {
String group = matcher.group();
if (matcher.start() <= offset && offset <= matcher.end())
return group;
}
return "";
}
}
| true | true | public static PlantUmlResult render(String source, ImageFormat format) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
String desc = null;
String error = null;
try {
// image generation.
SourceStringReader reader = new SourceStringReader(source);
// Write the image to "os"
desc = reader.generateImage(os, new FileFormatOption(format.getFormat()));
} catch (Exception e) {
error = e.getMessage();
}
return new PlantUmlResult(os.toByteArray(), desc, error);
}
| public static PlantUmlResult render(String source, ImageFormat format) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
String desc = null;
String error = null;
try {
// image generation.
SourceStringReader reader = new SourceStringReader(source);
// Write the image to "os"
desc = reader.generateImage(os, new FileFormatOption(format.getFormat()));
} catch (Throwable e) {
error = e.getMessage();
}
return new PlantUmlResult(os.toByteArray(), desc, error);
}
|
diff --git a/src/AdditionalBuildcraftObjects/ItemABOPipe.java b/src/AdditionalBuildcraftObjects/ItemABOPipe.java
index 24ca7f6..f8ab719 100644
--- a/src/AdditionalBuildcraftObjects/ItemABOPipe.java
+++ b/src/AdditionalBuildcraftObjects/ItemABOPipe.java
@@ -1,94 +1,94 @@
/**
* Copyright (C) 2011 Flow86
*
* AdditionalBuildcraftObjects is open-source.
*
* It is distributed under the terms of my Open Source License.
* It grants rights to read, modify, compile or run the code.
* It does *NOT* grant the right to redistribute this software or its
* modifications in any form, binary or source, except if expressively
* granted by the copyright holder.
*/
package net.minecraft.src.AdditionalBuildcraftObjects;
import net.minecraft.src.Block;
import net.minecraft.src.EntityPlayer;
import net.minecraft.src.ItemStack;
import net.minecraft.src.World;
import net.minecraft.src.mod_AdditionalBuildcraftObjects;
import net.minecraft.src.buildcraft.transport.ItemPipe;
import net.minecraft.src.buildcraft.transport.Pipe;
public class ItemABOPipe extends ItemPipe {
Pipe dummyPipe;
protected ItemABOPipe(int i) {
super(i);
}
@Override
public boolean onItemUse(ItemStack itemstack, EntityPlayer entityplayer, World world, int i, int j, int k, int l) {
int blockID = mod_AdditionalBuildcraftObjects.blockABOPipe.blockID;
if (world.getBlockId(i, j, k) == Block.snow.blockID) {
l = 0;
} else {
if (l == 0) {
j--;
}
if (l == 1) {
j++;
}
if (l == 2) {
k--;
}
if (l == 3) {
k++;
}
if (l == 4) {
i--;
}
if (l == 5) {
i++;
}
}
if (itemstack.stackSize == 0) {
return false;
}
if (j == 127 && Block.blocksList[blockID].blockMaterial.isSolid()) {
return false;
}
if (world.canBlockBePlacedAt(blockID, i, j, k, false, l)) {
- BlockABOPipe.createPipe(i, j, k, shiftedIndex);
+ BlockABOPipe.createPipe(world, i, j, k, shiftedIndex);
if (world.setBlockAndMetadataWithNotify(i, j, k, blockID, 0)) {
Block.blocksList[blockID].onBlockPlaced(world, i, j, k, l);
Block.blocksList[blockID].onBlockPlacedBy(world, i, j, k, entityplayer);
// To move to a proxt
// world.playSoundEffect((float)i + 0.5F, (float)j + 0.5F,
// (float)k + 0.5F, block.stepSound.stepSoundDir2(),
// (block.stepSound.getVolume() + 1.0F) / 2.0F,
// block.stepSound.getPitch() * 0.8F);
itemstack.stackSize--;
}
return true;
} else {
return false;
}
}
@Override
public String getTextureFile() {
return mod_AdditionalBuildcraftObjects.customTexture;
}
@Override
public int getTextureIndex() {
if (dummyPipe == null) {
dummyPipe = BlockABOPipe.createPipe(shiftedIndex);
}
return dummyPipe.getBlockTexture();
}
}
| true | true | public boolean onItemUse(ItemStack itemstack, EntityPlayer entityplayer, World world, int i, int j, int k, int l) {
int blockID = mod_AdditionalBuildcraftObjects.blockABOPipe.blockID;
if (world.getBlockId(i, j, k) == Block.snow.blockID) {
l = 0;
} else {
if (l == 0) {
j--;
}
if (l == 1) {
j++;
}
if (l == 2) {
k--;
}
if (l == 3) {
k++;
}
if (l == 4) {
i--;
}
if (l == 5) {
i++;
}
}
if (itemstack.stackSize == 0) {
return false;
}
if (j == 127 && Block.blocksList[blockID].blockMaterial.isSolid()) {
return false;
}
if (world.canBlockBePlacedAt(blockID, i, j, k, false, l)) {
BlockABOPipe.createPipe(i, j, k, shiftedIndex);
if (world.setBlockAndMetadataWithNotify(i, j, k, blockID, 0)) {
Block.blocksList[blockID].onBlockPlaced(world, i, j, k, l);
Block.blocksList[blockID].onBlockPlacedBy(world, i, j, k, entityplayer);
// To move to a proxt
// world.playSoundEffect((float)i + 0.5F, (float)j + 0.5F,
// (float)k + 0.5F, block.stepSound.stepSoundDir2(),
// (block.stepSound.getVolume() + 1.0F) / 2.0F,
// block.stepSound.getPitch() * 0.8F);
itemstack.stackSize--;
}
return true;
} else {
return false;
}
}
| public boolean onItemUse(ItemStack itemstack, EntityPlayer entityplayer, World world, int i, int j, int k, int l) {
int blockID = mod_AdditionalBuildcraftObjects.blockABOPipe.blockID;
if (world.getBlockId(i, j, k) == Block.snow.blockID) {
l = 0;
} else {
if (l == 0) {
j--;
}
if (l == 1) {
j++;
}
if (l == 2) {
k--;
}
if (l == 3) {
k++;
}
if (l == 4) {
i--;
}
if (l == 5) {
i++;
}
}
if (itemstack.stackSize == 0) {
return false;
}
if (j == 127 && Block.blocksList[blockID].blockMaterial.isSolid()) {
return false;
}
if (world.canBlockBePlacedAt(blockID, i, j, k, false, l)) {
BlockABOPipe.createPipe(world, i, j, k, shiftedIndex);
if (world.setBlockAndMetadataWithNotify(i, j, k, blockID, 0)) {
Block.blocksList[blockID].onBlockPlaced(world, i, j, k, l);
Block.blocksList[blockID].onBlockPlacedBy(world, i, j, k, entityplayer);
// To move to a proxt
// world.playSoundEffect((float)i + 0.5F, (float)j + 0.5F,
// (float)k + 0.5F, block.stepSound.stepSoundDir2(),
// (block.stepSound.getVolume() + 1.0F) / 2.0F,
// block.stepSound.getPitch() * 0.8F);
itemstack.stackSize--;
}
return true;
} else {
return false;
}
}
|
diff --git a/org.eclipse.jubula.client.core/src/org/eclipse/jubula/client/core/Activator.java b/org.eclipse.jubula.client.core/src/org/eclipse/jubula/client/core/Activator.java
index 21efc8b53..391d10b19 100644
--- a/org.eclipse.jubula.client.core/src/org/eclipse/jubula/client/core/Activator.java
+++ b/org.eclipse.jubula.client.core/src/org/eclipse/jubula/client/core/Activator.java
@@ -1,87 +1,87 @@
/*******************************************************************************
* Copyright (c) 2004, 2010 BREDEX GmbH.
* 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:
* BREDEX GmbH - initial API and implementation and/or initial documentation
*******************************************************************************/
package org.eclipse.jubula.client.core;
import java.io.InputStream;
import org.eclipse.core.runtime.Plugin;
import org.osgi.framework.BundleContext;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.joran.spi.JoranException;
/**
* @author BREDEX GmbH
* @created Nov 29, 2010
*/
public class Activator extends Plugin {
/** The plug-in ID */
public static final String PLUGIN_ID = "org.eclipse.jubula.client.core"; //$NON-NLS-1$
/**
* <code>RESOURCES_DIR</code>
*/
public static final String RESOURCES_DIR = "resources/"; //$NON-NLS-1$
/** The shared instance */
private static Activator plugin;
/**
* Constructor
*/
public Activator() {
// empty
}
/**
* {@inheritDoc}
*/
public void start(BundleContext context) throws Exception {
super.start(context);
plugin = this;
- // initialize tie logging facility
+ // initialize the logging facility
LoggerContext lc = (LoggerContext)LoggerFactory.getILoggerFactory();
try {
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(lc);
// the context was probably already configured by default
// configuration
// rules
lc.reset();
InputStream is = context.getBundle().getResource("logback.xml") //$NON-NLS-1$
.openStream();
configurator.doConfigure(is);
} catch (JoranException je) {
// no logging if logger fails :-(
}
}
/**
* {@inheritDoc}
*/
public void stop(BundleContext context) throws Exception {
plugin = null;
super.stop(context);
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static Activator getDefault() {
return plugin;
}
}
| true | true | public void start(BundleContext context) throws Exception {
super.start(context);
plugin = this;
// initialize tie logging facility
LoggerContext lc = (LoggerContext)LoggerFactory.getILoggerFactory();
try {
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(lc);
// the context was probably already configured by default
// configuration
// rules
lc.reset();
InputStream is = context.getBundle().getResource("logback.xml") //$NON-NLS-1$
.openStream();
configurator.doConfigure(is);
} catch (JoranException je) {
// no logging if logger fails :-(
}
}
| public void start(BundleContext context) throws Exception {
super.start(context);
plugin = this;
// initialize the logging facility
LoggerContext lc = (LoggerContext)LoggerFactory.getILoggerFactory();
try {
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(lc);
// the context was probably already configured by default
// configuration
// rules
lc.reset();
InputStream is = context.getBundle().getResource("logback.xml") //$NON-NLS-1$
.openStream();
configurator.doConfigure(is);
} catch (JoranException je) {
// no logging if logger fails :-(
}
}
|
diff --git a/src/java/org/joshy/html/swing/DOMInspector.java b/src/java/org/joshy/html/swing/DOMInspector.java
index 150cb427..91bbf9f9 100755
--- a/src/java/org/joshy/html/swing/DOMInspector.java
+++ b/src/java/org/joshy/html/swing/DOMInspector.java
@@ -1,509 +1,509 @@
package org.joshy.html.swing;
import javax.swing.event.*;
import java.util.*;
import javax.swing.tree.*;
import javax.swing.*;
import java.awt.Graphics;
import java.awt.Dimension;
import java.awt.BorderLayout;
import org.w3c.dom.*;
import org.joshy.u;
import java.awt.Component;
import java.awt.Color;
import java.awt.Font;
import java.awt.Toolkit;
import javax.swing.table.*;
import org.w3c.dom.css.CSSPrimitiveValue;
import org.joshy.html.*;
import com.pdoubleya.xhtmlrenderer.css.*;
import com.pdoubleya.xhtmlrenderer.css.constants.*;
import com.pdoubleya.xhtmlrenderer.css.bridge.*;
public class DOMInspector extends JPanel {
// PW
XRStyleReference xrStyleReference;
Context context;
ElementPropertiesPanel elementPropPanel;
DOMSelectionListener nodeSelectionListener;
// PW
Document doc;
JTree tree;
JScrollPane scroll;
public void setForDocument(Document doc) {
setForDocument(doc, null, null);
}
public void setForDocument(Document doc, Context context, XRStyleReference xsr) {
this.doc = doc;
this.xrStyleReference = xsr;
this.context = context;
this.initForCurrentDocument();
}
public DOMInspector(Document doc) {
this(doc, null, null);
}
public DOMInspector(Document doc, Context context, XRStyleReference xsr) {
super();
this.setLayout(new java.awt.BorderLayout());
this.tree = new JTree();
this.scroll = new JScrollPane(tree);
if ( xsr == null ) {
add(scroll,"Center");
} else {
add(scroll,"West");
this.tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
}
this.add(new JButton("close"),"South");
this.setPreferredSize(new Dimension(300,300));
setForDocument(doc, context, xsr);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawLine(0,0,100,100);
}
private void initForCurrentDocument() {
// tree stuff
TreeModel model = new DOMTreeModel(doc);
tree.setModel(model);
if ( ! (tree.getCellRenderer() instanceof DOMTreeCellRenderer) )
tree.setCellRenderer(new DOMTreeCellRenderer());
if ( xrStyleReference != null ) {
if ( elementPropPanel != null ) this.remove(elementPropPanel);
elementPropPanel = new ElementPropertiesPanel(context, xrStyleReference);
add(elementPropPanel,"Center");
tree.removeTreeSelectionListener(nodeSelectionListener);
nodeSelectionListener = new DOMSelectionListener(tree, xrStyleReference, elementPropPanel);
tree.addTreeSelectionListener(nodeSelectionListener);
}
}
}
//-{{{ ElementPropertiesPanel
class ElementPropertiesPanel extends JPanel {
private Context _context;
private XRStyleReference _xsr;
private JTable _properties;
ElementPropertiesPanel(Context context, XRStyleReference xsr) {
super();
this._context = context;
this._xsr = xsr;
_properties = new PropertiesJTable();
JScrollPane spn = new JScrollPane( _properties );
this.setLayout( new BorderLayout() );
this.add( spn, BorderLayout.CENTER );
}
public void setForElement(Node node) {
try {
_properties.setModel(tableModel(node));
TableColumnModel model = _properties.getColumnModel();
if ( model.getColumnCount() > 0 )
model.getColumn(0).sizeWidthToFit();
} catch (Exception ex) {
ex.printStackTrace();
}
}
class PropertiesJTable extends JTable {
Font propLabelFont;
Font defaultFont;
PropertiesJTable() {
super();
this.setColumnSelectionAllowed(false);
this.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
propLabelFont = new Font("Courier New", Font.BOLD, 12);
defaultFont = new Font("Default", Font.PLAIN, 12);
}
public TableCellRenderer getCellRenderer(int row, int col) {
JLabel label = (JLabel)super.getCellRenderer(row, col);
label.setBackground(Color.white);
label.setFont(defaultFont);
if ( col == 0 ) {
// BUG: not working?
label.setFont(propLabelFont);
} else if ( col == 2 ) {
PropertiesTableModel pmodel = (PropertiesTableModel)this.getModel();
XRProperty prop = (XRProperty)pmodel._properties.get(row);
XRValue actual = prop.actualValue();
if ( actual.cssValue().getCssText().startsWith("rgb"))
label.setBackground(actual.asColor());
}
return (TableCellRenderer)label;
}
}
/**
* Description of the Method
*
* @return Returns
* @exception Exception Throws
*/
private TableModel tableModel(Node node)
throws Exception {
List props = new ArrayList();
XRElement xrElem = _xsr.getNodeXRElement(node);
if ( xrElem == null ) {
Toolkit.getDefaultToolkit().beep();
return new DefaultTableModel();
}
Iterator iter = xrElem.derivedStyle().listXRProperties();
while ( iter.hasNext()) {
XRProperty prop = (XRProperty)iter.next();
prop = xrElem.derivedStyle().propertyByName(_context, prop.propertyName());
props.add(prop);
}
return new PropertiesTableModel(props);
}
/**
* Description of the Class
*
* @author Patrick Wright
*/
class PropertiesTableModel extends AbstractTableModel {
/** Description of the Field */
String _colNames[] = {"Property Name", "Text", "Value", "Convert", "Important-Inherit"};
List _properties;
/**
* Constructor for the PropertiesTableModel object
*
* @param xrProperties PARAM
*/
PropertiesTableModel( List xrProperties ) {
_properties = xrProperties;
}
/**
* Gets the columnName attribute of the PropertiesTableModel object
*
* @param col PARAM
* @return The columnName value
*/
public String getColumnName( int col ) {
return _colNames[col];
}
/**
* Gets the columnCount attribute of the PropertiesTableModel object
*
* @return The columnCount value
*/
public int getColumnCount() {
return _colNames.length;
}
/**
* Gets the rowCount attribute of the PropertiesTableModel object
*
* @return The rowCount value
*/
public int getRowCount() {
return _properties.size();
}
/**
* Gets the valueAt attribute of the PropertiesTableModel object
*
* @param row PARAM
* @param col PARAM
* @return The valueAt value
*/
public Object getValueAt( int row, int col ) {
XRProperty prop = (XRProperty)_properties.get(row);
XRValue actual = prop.actualValue();
Object val = null;
switch( col ) {
case 0:
val = prop.propertyName();
break;
case 1:
val = actual.cssValue().getCssText();
break;
case 2:
if ( ValueConstants.isNumber(((CSSPrimitiveValue)actual.cssValue()).getPrimitiveType())) {
- val = Float.valueOf(actual.asFloat());
+ val = new Float(actual.asFloat());
} else {
val = ""; //actual.cssValue().getCssText();
}
break;
case 3:
val = (ValueConstants.isAbsoluteUnit(actual.cssValue())? "" : "RELATIVE");
break;
case 4:
val = (actual.isImportant() ? "!Imp" : "") +
" " +
(actual.forcedInherit() ? "Inherit" : "");
break;
}
return val;
}
/**
* Gets the cellEditable attribute of the PropertiesTableModel object
*
* @param row PARAM
* @param col PARAM
* @return The cellEditable value
*/
public boolean isCellEditable( int row, int col ) {
return false;
}
}
} //}}}
//-{{{ DOMSelectionListener
class DOMSelectionListener implements TreeSelectionListener {
private JTree _tree;
private XRStyleReference _xsr;
private ElementPropertiesPanel _elemPropPanel;
DOMSelectionListener(JTree tree, XRStyleReference xsr, ElementPropertiesPanel panel) {
_tree = tree;
_xsr = xsr;
_elemPropPanel = panel;
}
public void valueChanged(TreeSelectionEvent e) {
Node node = (Node)_tree.getLastSelectedPathComponent();
if (node == null) return;
_elemPropPanel.setForElement(node);
}
}//}}}
//-{{{
class DOMTreeModel implements TreeModel {
Document doc;
HashMap displayableNodes;
public DOMTreeModel(Document doc) {
this.displayableNodes = new HashMap();
this.doc = doc;
}
List listeners = new ArrayList();
//Adds a listener for the TreeModelEvent posted after the tree changes.
public void addTreeModelListener(TreeModelListener l) {
this.listeners.add(l);
}
// only adds displayable nodes--not stupid DOM text filler nodes
private List addDisplayable(Node parent) {
List children = (List)this.displayableNodes.get(parent);
if ( children == null ) {
children = new ArrayList();
this.displayableNodes.put(parent, children);
NodeList nl = parent.getChildNodes();
for ( int i=0, len=nl.getLength(); i < len; i++ ) {
Node child = nl.item(i);
if ( child.getNodeType() == Node.ELEMENT_NODE ||
child.getNodeType() == Node.COMMENT_NODE ||
( child.getNodeType() == Node.TEXT_NODE && (child.getNodeValue().trim().length() > 0))) {
children.add(child);
}
}
return children;
} else return new ArrayList();
}
//Returns the child of parent at index index in the parent's child array.
public Object getChild(Object parent, int index) {
Node node = (Node)parent;
List children = (List)this.displayableNodes.get(parent);
if ( children == null ) {
children = addDisplayable(node);
}
// CLEAN return node.getChildNodes().item(index);
return (Node)children.get(index);
}
//Returns the number of children of parent.
public int getChildCount(Object parent) {
Node node = (Node)parent;
List children = (List)this.displayableNodes.get(parent);
if ( children == null ) {
children = addDisplayable(node);
}
// CLEAN return node.getChildNodes().getLength();
return children.size();
}
//Returns the index of child in parent.
public int getIndexOfChild(Object parent, Object child) {
Node node = (Node)parent;
List children = (List)this.displayableNodes.get(parent);
if ( children == null ) {
children = addDisplayable(node);
}
if ( children.contains(child))
return children.indexOf(child);
else
return -1;
/* CLEAN
for(int i=0; i<node.getChildNodes().getLength(); i++) {
if(child == node.getChildNodes().item(i)) {
return i;
}
}
return -1;
*/
}
//Returns the root of the tree.
public Object getRoot() {
return doc;
}
//Returns true if node is a leaf.
public boolean isLeaf(Object nd) {
Node node = (Node)nd;
//u.p("checking leaf: " + node.getNodeName());
//u.p("is: " + node.hasChildNodes());
return !node.hasChildNodes();
}
//Removes a listener previously added with addTreeModelListener.
public void removeTreeModelListener(TreeModelListener l) {
this.listeners.remove(l);
}
//Messaged when the user has altered the value for the item identified by path to newValue.
public void valueForPathChanged(TreePath path, Object newValue) {
// no-op
}
}//}}}
//-{{{ DOMTreeCellRenderer
class DOMTreeCellRenderer extends DefaultTreeCellRenderer {
public Component getTreeCellRendererComponent(JTree tree, Object value,
boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
Node node = (Node)value;
if(node.getNodeType() == node.ELEMENT_NODE) {
String cls = "";
if ( node.hasAttributes()) {
Node cn = node.getAttributes().getNamedItem("class");
if ( cn != null ) {
cls = " class='" + cn.getNodeValue() +"'";
}
}
value = "<"+node.getNodeName()+ cls + ">";
}
if(node.getNodeType() == node.TEXT_NODE) {
if ( node.getNodeValue().trim().length() > 0 )
value = "\""+ node.getNodeValue() + "\"";
}
if(node.getNodeType() == node.COMMENT_NODE) {
value = "<!-- " + node.getNodeValue() + " -->";
}
return super.getTreeCellRendererComponent(tree,value,selected,expanded,leaf,row,hasFocus);
}
}//}}}
| true | true | public Object getValueAt( int row, int col ) {
XRProperty prop = (XRProperty)_properties.get(row);
XRValue actual = prop.actualValue();
Object val = null;
switch( col ) {
case 0:
val = prop.propertyName();
break;
case 1:
val = actual.cssValue().getCssText();
break;
case 2:
if ( ValueConstants.isNumber(((CSSPrimitiveValue)actual.cssValue()).getPrimitiveType())) {
val = Float.valueOf(actual.asFloat());
} else {
val = ""; //actual.cssValue().getCssText();
}
break;
case 3:
val = (ValueConstants.isAbsoluteUnit(actual.cssValue())? "" : "RELATIVE");
break;
case 4:
val = (actual.isImportant() ? "!Imp" : "") +
" " +
(actual.forcedInherit() ? "Inherit" : "");
break;
}
return val;
}
| public Object getValueAt( int row, int col ) {
XRProperty prop = (XRProperty)_properties.get(row);
XRValue actual = prop.actualValue();
Object val = null;
switch( col ) {
case 0:
val = prop.propertyName();
break;
case 1:
val = actual.cssValue().getCssText();
break;
case 2:
if ( ValueConstants.isNumber(((CSSPrimitiveValue)actual.cssValue()).getPrimitiveType())) {
val = new Float(actual.asFloat());
} else {
val = ""; //actual.cssValue().getCssText();
}
break;
case 3:
val = (ValueConstants.isAbsoluteUnit(actual.cssValue())? "" : "RELATIVE");
break;
case 4:
val = (actual.isImportant() ? "!Imp" : "") +
" " +
(actual.forcedInherit() ? "Inherit" : "");
break;
}
return val;
}
|
diff --git a/activemq-core/src/test/java/org/apache/activemq/transport/discovery/DiscoveryUriTest.java b/activemq-core/src/test/java/org/apache/activemq/transport/discovery/DiscoveryUriTest.java
index 9f65e08c4..fe1f9522d 100644
--- a/activemq-core/src/test/java/org/apache/activemq/transport/discovery/DiscoveryUriTest.java
+++ b/activemq-core/src/test/java/org/apache/activemq/transport/discovery/DiscoveryUriTest.java
@@ -1,54 +1,54 @@
/**
* 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.transport.discovery;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.EmbeddedBrokerTestSupport;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.TransportConnector;
import javax.jms.*;
import java.net.URI;
public class DiscoveryUriTest extends EmbeddedBrokerTestSupport {
@Override
protected BrokerService createBroker() throws Exception {
bindAddress = "tcp://localhost:0";
BrokerService answer = new BrokerService();
answer.setPersistent(isPersistent());
TransportConnector connector = new TransportConnector();
connector.setUri(new URI(bindAddress));
connector.setDiscoveryUri(new URI("multicast://default?group=test"));
answer.addConnector(connector);
return answer;
}
public void testConnect() throws Exception {
- ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("discovery:(multicast://default?group=test)?reconnectDelay=1000&maxReconnectAttempts=30&useExponentialBackOff=false");
+ ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("discovery:(multicast://default?group=test&reconnectDelay=1000&maxReconnectAttempts=30&useExponentialBackOff=false)");
Connection conn = factory.createConnection();
conn.start();
Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer producer = sess.createProducer(sess.createQueue("test"));
producer.send(sess.createTextMessage("test"));
MessageConsumer consumer = sess.createConsumer(sess.createQueue("test"));
Message msg = consumer.receive(1000);
assertNotNull(msg);
}
}
| true | true | public void testConnect() throws Exception {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("discovery:(multicast://default?group=test)?reconnectDelay=1000&maxReconnectAttempts=30&useExponentialBackOff=false");
Connection conn = factory.createConnection();
conn.start();
Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer producer = sess.createProducer(sess.createQueue("test"));
producer.send(sess.createTextMessage("test"));
MessageConsumer consumer = sess.createConsumer(sess.createQueue("test"));
Message msg = consumer.receive(1000);
assertNotNull(msg);
}
| public void testConnect() throws Exception {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("discovery:(multicast://default?group=test&reconnectDelay=1000&maxReconnectAttempts=30&useExponentialBackOff=false)");
Connection conn = factory.createConnection();
conn.start();
Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer producer = sess.createProducer(sess.createQueue("test"));
producer.send(sess.createTextMessage("test"));
MessageConsumer consumer = sess.createConsumer(sess.createQueue("test"));
Message msg = consumer.receive(1000);
assertNotNull(msg);
}
|
diff --git a/src/main/java/org/basex/query/func/FNQName.java b/src/main/java/org/basex/query/func/FNQName.java
index fa99e28d7..a0ba23865 100644
--- a/src/main/java/org/basex/query/func/FNQName.java
+++ b/src/main/java/org/basex/query/func/FNQName.java
@@ -1,164 +1,161 @@
package org.basex.query.func;
import static org.basex.query.QueryText.*;
import static org.basex.query.util.Err.*;
import static org.basex.util.Token.*;
import org.basex.query.QueryContext;
import org.basex.query.QueryException;
import org.basex.query.expr.Expr;
import org.basex.query.item.Item;
import org.basex.query.item.ANode;
import org.basex.query.item.NodeType;
import org.basex.query.item.QNm;
import org.basex.query.item.AtomType;
import org.basex.query.item.Str;
import org.basex.query.item.Uri;
import org.basex.query.iter.ItemCache;
import org.basex.query.iter.Iter;
import org.basex.query.util.Err;
import org.basex.util.Atts;
import org.basex.util.InputInfo;
import org.basex.util.XMLToken;
import org.basex.util.hash.TokenSet;
/**
* QName functions.
*
* @author BaseX Team 2005-11, BSD License
* @author Christian Gruen
*/
public final class FNQName extends FuncCall {
/**
* Constructor.
* @param ii input info
* @param f function definition
* @param e arguments
*/
public FNQName(final InputInfo ii, final Function f, final Expr... e) {
super(ii, f, e);
}
@Override
public Iter iter(final QueryContext ctx) throws QueryException {
switch(def) {
case INSCOPE: return inscope(ctx,
(ANode) checkType(expr[0].item(ctx, input), NodeType.ELM));
default: return super.iter(ctx);
}
}
@Override
public Item item(final QueryContext ctx, final InputInfo ii)
throws QueryException {
// functions have 1 or 2 arguments...
final Item it = expr[0].item(ctx, input);
final Item it2 = expr.length == 2 ? expr[1].item(ctx, input) : null;
switch(def) {
case RESQNAME:
return it == null ? null : resolve(ctx, it, checkEmpty(it2));
case QNAME:
- final byte[] uri = it == null ? EMPTY :
- checkType(it, AtomType.STR).atom(input);
- final Item it3 = it2 == null ? Str.ZERO :
- checkType(it2, AtomType.STR);
- final byte[] atm = it3.atom(input);
+ final byte[] uri = checkEStr(it);
+ final byte[] atm = checkEStr(it2);
final byte[] str = !contains(atm, ':') && eq(uri, XMLURI) ?
concat(XMLC, atm) : atm;
- if(!XMLToken.isQName(str)) Err.value(input, AtomType.QNM, it3);
+ if(!XMLToken.isQName(str)) Err.value(input, AtomType.QNM, atm);
QNm nm = new QNm(str, uri);
if(nm.ns() && uri.length == 0)
Err.value(input, AtomType.URI, nm.uri());
return nm;
case LOCNAMEQNAME:
if(it == null) return null;
nm = (QNm) checkType(it, AtomType.QNM);
return AtomType.NCN.e(Str.get(nm.ln()), ctx, input);
case PREQNAME:
if(it == null) return null;
nm = (QNm) checkType(it, AtomType.QNM);
return !nm.ns() ? null : AtomType.NCN.e(Str.get(nm.pref()), ctx, input);
case NSURIPRE:
// [LK] Namespaces: find out if inherit flag has a persistent effect
final byte[] pre = checkEStr(it);
final ANode an = (ANode) checkType(it2, NodeType.ELM);
final boolean copied = ctx.copiedNods.contains(an.data());
final Atts at = an.nsScope(!copied || ctx.nsInherit);
final int i = at != null ? at.get(pre) : -1;
return i != -1 ? Uri.uri(at.val[i]) : null;
case RESURI:
if(it == null) return null;
final Uri rel = Uri.uri(checkEStr(it));
if(!rel.valid()) URIINV.thrw(input, it);
final Uri base = it2 == null ? ctx.baseURI : Uri.uri(checkEStr(it2));
if(!base.valid()) URIINV.thrw(input, base);
return base.resolve(rel);
default:
return super.item(ctx, ii);
}
}
/**
* Resolves a QName.
* @param ctx query context
* @param q qname
* @param it item
* @return prefix sequence
* @throws QueryException query exception
*/
private Item resolve(final QueryContext ctx, final Item q, final Item it)
throws QueryException {
final byte[] name = trim(checkEStr(q));
if(!XMLToken.isQName(name)) Err.value(input, AtomType.QNM, q);
final QNm nm = new QNm(name);
final byte[] pref = nm.pref();
final byte[] uri = ((ANode) checkType(it, NodeType.ELM)).uri(pref, ctx);
if(uri == null) NSDECL.thrw(input, pref);
nm.uri(uri);
return nm;
}
/**
* Returns the in-scope prefixes for the specified node.
* @param ctx query context
* @param node node
* @return prefix sequence
*/
private Iter inscope(final QueryContext ctx, final ANode node) {
final TokenSet pref = new TokenSet(XML);
byte[] emp = null;
ANode n = node;
do {
final Atts at = n.ns();
if(at == null) break;
if(n != node || ctx.nsPreserve) {
for(int a = 0; a < at.size; ++a) {
final byte[] pre = at.key[a];
if(pre.length == 0) {
if(emp == null) emp = at.val[a];
} else pref.add(pre);
}
}
if(emp == null) {
final QNm nm = n.qname();
if(!nm.ns()) emp = nm.uri().atom();
}
n = n.parent();
} while(n != null && ctx.nsInherit);
if(emp == null) emp = ctx.nsElem;
if(emp.length != 0) pref.add(EMPTY);
final ItemCache ic = new ItemCache(pref.size());
for(final byte[] t : pref.keys()) ic.add(Str.get(t));
return ic;
}
@Override
public boolean uses(final Use u) {
return u == Use.CTX && def == Function.INSCOPE || super.uses(u);
}
}
| false | true | public Item item(final QueryContext ctx, final InputInfo ii)
throws QueryException {
// functions have 1 or 2 arguments...
final Item it = expr[0].item(ctx, input);
final Item it2 = expr.length == 2 ? expr[1].item(ctx, input) : null;
switch(def) {
case RESQNAME:
return it == null ? null : resolve(ctx, it, checkEmpty(it2));
case QNAME:
final byte[] uri = it == null ? EMPTY :
checkType(it, AtomType.STR).atom(input);
final Item it3 = it2 == null ? Str.ZERO :
checkType(it2, AtomType.STR);
final byte[] atm = it3.atom(input);
final byte[] str = !contains(atm, ':') && eq(uri, XMLURI) ?
concat(XMLC, atm) : atm;
if(!XMLToken.isQName(str)) Err.value(input, AtomType.QNM, it3);
QNm nm = new QNm(str, uri);
if(nm.ns() && uri.length == 0)
Err.value(input, AtomType.URI, nm.uri());
return nm;
case LOCNAMEQNAME:
if(it == null) return null;
nm = (QNm) checkType(it, AtomType.QNM);
return AtomType.NCN.e(Str.get(nm.ln()), ctx, input);
case PREQNAME:
if(it == null) return null;
nm = (QNm) checkType(it, AtomType.QNM);
return !nm.ns() ? null : AtomType.NCN.e(Str.get(nm.pref()), ctx, input);
case NSURIPRE:
// [LK] Namespaces: find out if inherit flag has a persistent effect
final byte[] pre = checkEStr(it);
final ANode an = (ANode) checkType(it2, NodeType.ELM);
final boolean copied = ctx.copiedNods.contains(an.data());
final Atts at = an.nsScope(!copied || ctx.nsInherit);
final int i = at != null ? at.get(pre) : -1;
return i != -1 ? Uri.uri(at.val[i]) : null;
case RESURI:
if(it == null) return null;
final Uri rel = Uri.uri(checkEStr(it));
if(!rel.valid()) URIINV.thrw(input, it);
final Uri base = it2 == null ? ctx.baseURI : Uri.uri(checkEStr(it2));
if(!base.valid()) URIINV.thrw(input, base);
return base.resolve(rel);
default:
return super.item(ctx, ii);
}
}
| public Item item(final QueryContext ctx, final InputInfo ii)
throws QueryException {
// functions have 1 or 2 arguments...
final Item it = expr[0].item(ctx, input);
final Item it2 = expr.length == 2 ? expr[1].item(ctx, input) : null;
switch(def) {
case RESQNAME:
return it == null ? null : resolve(ctx, it, checkEmpty(it2));
case QNAME:
final byte[] uri = checkEStr(it);
final byte[] atm = checkEStr(it2);
final byte[] str = !contains(atm, ':') && eq(uri, XMLURI) ?
concat(XMLC, atm) : atm;
if(!XMLToken.isQName(str)) Err.value(input, AtomType.QNM, atm);
QNm nm = new QNm(str, uri);
if(nm.ns() && uri.length == 0)
Err.value(input, AtomType.URI, nm.uri());
return nm;
case LOCNAMEQNAME:
if(it == null) return null;
nm = (QNm) checkType(it, AtomType.QNM);
return AtomType.NCN.e(Str.get(nm.ln()), ctx, input);
case PREQNAME:
if(it == null) return null;
nm = (QNm) checkType(it, AtomType.QNM);
return !nm.ns() ? null : AtomType.NCN.e(Str.get(nm.pref()), ctx, input);
case NSURIPRE:
// [LK] Namespaces: find out if inherit flag has a persistent effect
final byte[] pre = checkEStr(it);
final ANode an = (ANode) checkType(it2, NodeType.ELM);
final boolean copied = ctx.copiedNods.contains(an.data());
final Atts at = an.nsScope(!copied || ctx.nsInherit);
final int i = at != null ? at.get(pre) : -1;
return i != -1 ? Uri.uri(at.val[i]) : null;
case RESURI:
if(it == null) return null;
final Uri rel = Uri.uri(checkEStr(it));
if(!rel.valid()) URIINV.thrw(input, it);
final Uri base = it2 == null ? ctx.baseURI : Uri.uri(checkEStr(it2));
if(!base.valid()) URIINV.thrw(input, base);
return base.resolve(rel);
default:
return super.item(ctx, ii);
}
}
|
diff --git a/src/gui/REPLTextArea.java b/src/gui/REPLTextArea.java
index 289efc5..6dbef5c 100644
--- a/src/gui/REPLTextArea.java
+++ b/src/gui/REPLTextArea.java
@@ -1,152 +1,154 @@
package gui;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import javax.swing.AbstractAction;
import javax.swing.KeyStroke;
import javax.swing.text.BadLocationException;
/**
* Run commands.
*/
public class REPLTextArea extends SchemeTextArea {
private static final long serialVersionUID = 8753865168892947915L;
MainFrame Main;
// Store previously entered commands.
List<String> commandHistory;
int currentCommand = 0;
/**
* Create a new REPL area.
*/
public REPLTextArea(final MainFrame main) {
Main = main;
commandHistory = new ArrayList<String>();
setPreferredSize(new Dimension(100, 100));
// When the user hits the 'ENTER' key, check for a complete command.
code.getInputMap().put(
KeyStroke.getKeyStroke("ENTER"),
new AbstractAction() {
private static final long serialVersionUID = 723647997099071931L;
public void actionPerformed(ActionEvent e) {
if (Main.Running) return;
checkRun();
}
});
// On CTRL-ENTER (command-ENTER on a mac).
code.getInputMap().put(
KeyStroke.getKeyStroke(
KeyEvent.VK_ENTER,
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()
),
new AbstractAction() {
private static final long serialVersionUID = 723647997099071931L;
public void actionPerformed(ActionEvent e) {
if (Main.Running) return;
if (getText().trim().isEmpty()) return;
commandHistory.add(getText());
currentCommand = commandHistory.size();
main.doCommand(getText());
setText("");
}
});
// When the user hits the up arrow, it they are on the first line, reload the previous command.
code.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent arg0) {
if (arg0.getKeyCode() == KeyEvent.VK_UP) {
- if (getText().lastIndexOf("\n", code.getCaretPosition()) == -1) {
+ if (getText().lastIndexOf("\n", code.getCaretPosition() - 1) == -1) {
if (currentCommand == commandHistory.size())
if (!getText().isEmpty())
commandHistory.add(getText());
if (currentCommand == 0)
return;
currentCommand--;
setText(commandHistory.get(currentCommand));
+ code.setCaretPosition(0);
}
}
if (arg0.getKeyCode() == KeyEvent.VK_DOWN) {
if (getText().indexOf("\n", code.getCaretPosition()) == -1) {
if (currentCommand == commandHistory.size()) {
return;
} else if (currentCommand == commandHistory.size() - 1) {
setText(commandHistory.remove(commandHistory.size() - 1));
} else {
currentCommand++;
setText(commandHistory.get(currentCommand));
+ code.setCaretPosition(getText().length());
}
}
}
}
@Override
public void keyReleased(KeyEvent arg0) {}
@Override
public void keyTyped(KeyEvent arg0) {
}
});
}
/**
* Check if the command should run, run it if it should.
*
* To run:
* - Last line
* - Brackets are matched
*/
protected void checkRun() {
// The cursor should be on the last line.
if (getText().substring(code.getCaretPosition()).trim().isEmpty()) {
// Check to see that we have a matched pair of brackets.
Stack<Character> brackets = new Stack<Character>();
for (char c : getText().toCharArray()) {
if (c == '(') brackets.push(')');
else if (c == '[') brackets.push(']');
else if (c == ')' || c == ']')
if (!brackets.empty() && brackets.peek() == c)
brackets.pop();
else
return;
}
// This means we matched them all.
if (brackets.empty()) {
commandHistory.add(getText());
currentCommand = commandHistory.size();
Main.doCommand(getText());
setText("");
return;
}
}
// Either we didn't match the brackets or we aren't on the last line. Insert the return normally.
try {
code.getDocument().insertString(code.getCaretPosition(), SchemeTextArea.NL, null);
} catch (BadLocationException ble) {
System.err.println("badwolf");
}
tab();
}
}
| false | true | public REPLTextArea(final MainFrame main) {
Main = main;
commandHistory = new ArrayList<String>();
setPreferredSize(new Dimension(100, 100));
// When the user hits the 'ENTER' key, check for a complete command.
code.getInputMap().put(
KeyStroke.getKeyStroke("ENTER"),
new AbstractAction() {
private static final long serialVersionUID = 723647997099071931L;
public void actionPerformed(ActionEvent e) {
if (Main.Running) return;
checkRun();
}
});
// On CTRL-ENTER (command-ENTER on a mac).
code.getInputMap().put(
KeyStroke.getKeyStroke(
KeyEvent.VK_ENTER,
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()
),
new AbstractAction() {
private static final long serialVersionUID = 723647997099071931L;
public void actionPerformed(ActionEvent e) {
if (Main.Running) return;
if (getText().trim().isEmpty()) return;
commandHistory.add(getText());
currentCommand = commandHistory.size();
main.doCommand(getText());
setText("");
}
});
// When the user hits the up arrow, it they are on the first line, reload the previous command.
code.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent arg0) {
if (arg0.getKeyCode() == KeyEvent.VK_UP) {
if (getText().lastIndexOf("\n", code.getCaretPosition()) == -1) {
if (currentCommand == commandHistory.size())
if (!getText().isEmpty())
commandHistory.add(getText());
if (currentCommand == 0)
return;
currentCommand--;
setText(commandHistory.get(currentCommand));
}
}
if (arg0.getKeyCode() == KeyEvent.VK_DOWN) {
if (getText().indexOf("\n", code.getCaretPosition()) == -1) {
if (currentCommand == commandHistory.size()) {
return;
} else if (currentCommand == commandHistory.size() - 1) {
setText(commandHistory.remove(commandHistory.size() - 1));
} else {
currentCommand++;
setText(commandHistory.get(currentCommand));
}
}
}
}
@Override
public void keyReleased(KeyEvent arg0) {}
@Override
public void keyTyped(KeyEvent arg0) {
}
});
}
| public REPLTextArea(final MainFrame main) {
Main = main;
commandHistory = new ArrayList<String>();
setPreferredSize(new Dimension(100, 100));
// When the user hits the 'ENTER' key, check for a complete command.
code.getInputMap().put(
KeyStroke.getKeyStroke("ENTER"),
new AbstractAction() {
private static final long serialVersionUID = 723647997099071931L;
public void actionPerformed(ActionEvent e) {
if (Main.Running) return;
checkRun();
}
});
// On CTRL-ENTER (command-ENTER on a mac).
code.getInputMap().put(
KeyStroke.getKeyStroke(
KeyEvent.VK_ENTER,
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()
),
new AbstractAction() {
private static final long serialVersionUID = 723647997099071931L;
public void actionPerformed(ActionEvent e) {
if (Main.Running) return;
if (getText().trim().isEmpty()) return;
commandHistory.add(getText());
currentCommand = commandHistory.size();
main.doCommand(getText());
setText("");
}
});
// When the user hits the up arrow, it they are on the first line, reload the previous command.
code.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent arg0) {
if (arg0.getKeyCode() == KeyEvent.VK_UP) {
if (getText().lastIndexOf("\n", code.getCaretPosition() - 1) == -1) {
if (currentCommand == commandHistory.size())
if (!getText().isEmpty())
commandHistory.add(getText());
if (currentCommand == 0)
return;
currentCommand--;
setText(commandHistory.get(currentCommand));
code.setCaretPosition(0);
}
}
if (arg0.getKeyCode() == KeyEvent.VK_DOWN) {
if (getText().indexOf("\n", code.getCaretPosition()) == -1) {
if (currentCommand == commandHistory.size()) {
return;
} else if (currentCommand == commandHistory.size() - 1) {
setText(commandHistory.remove(commandHistory.size() - 1));
} else {
currentCommand++;
setText(commandHistory.get(currentCommand));
code.setCaretPosition(getText().length());
}
}
}
}
@Override
public void keyReleased(KeyEvent arg0) {}
@Override
public void keyTyped(KeyEvent arg0) {
}
});
}
|
diff --git a/src/core/java/org/wyona/yanel/core/source/SourceResolver.java b/src/core/java/org/wyona/yanel/core/source/SourceResolver.java
index 3e3aa7c4e..562a551ba 100644
--- a/src/core/java/org/wyona/yanel/core/source/SourceResolver.java
+++ b/src/core/java/org/wyona/yanel/core/source/SourceResolver.java
@@ -1,106 +1,109 @@
package org.wyona.yanel.core.source;
import java.util.HashMap;
import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import javax.xml.transform.URIResolver;
import org.apache.log4j.Category;
import org.wyona.yanel.core.Resource;
import org.wyona.commons.io.PathUtil;
/**
* Resolves a URI to a Source.
* This class just checks the scheme and delegates to the scheme-specific resolver.
*
* TODO: allow to configure schemes in a config file
*/
public class SourceResolver implements URIResolver {
private static Category log = Category.getInstance(SourceResolver.class);
private HashMap resolvers;
private Resource resource;
public SourceResolver(Resource resource) {
this.resource = resource;
this.resolvers = new HashMap();
}
/**
*
*/
public Source resolve(String uri, String base) throws SourceException {
if (log.isDebugEnabled()) {
log.debug("URI to be resolved: " + uri);
log.debug("Base: "+ base);
}
- int colonIndex = uri.indexOf(":/");
+ // NOTE: One cannot use ":/" in order to find the protocol/scheme, because one can also specifiy the realm id and repository id, for example: yanelrepo:REALM_ID:REPO_ID:/foo/bar.gif
+ int colonIndex = uri.indexOf(":");
+ //int colonIndex = uri.indexOf(":/");
String uriScheme = "";
if (colonIndex <= 0) {//Check for scheme in URI, if true, then URI has no scheme
//log.error("DEBUG: URI has no scheme: " + uri);
if (base != null) {
- int colBaseIndex = base.indexOf(":/");
+ int colBaseIndex = base.indexOf(":");
+ //int colBaseIndex = base.indexOf(":/");
if(colBaseIndex <=0 ){//Check for scheme in Base
throw new SourceException("invalid url syntax (missing scheme): " + uri);//no scheme found in uri and base
}else{//base contains scheme. Use base scheme for uri scheme
uriScheme = base.substring(0, colBaseIndex);
uri = PathUtil.concat(base,uri);
//log.error("DEBUG: Use scheme of base: " + uriScheme + ", " + uri);
}
} else {
log.error("Neither scheme for URI nor base specified for URI: " + uri);
throw new SourceException("invalid url syntax (missing scheme): " + uri);//no scheme found in uri and base
}
} else {//uri contains scheme
uriScheme = uri.substring(0, colonIndex);
//log.error("DEBUG: URI has scheme: " + uriScheme + ", " + uri);
}
URIResolver resolver = getResolver(uriScheme);
if (resolver != null) {
try {
// TODO: What shall be used as base?!
Source s = resolver.resolve(uri, base);
s.setSystemId(uri);
return s;
} catch (TransformerException e) {
throw new SourceException(e.getMessage(), e);
}
} else {
throw new SourceException("No resolver could be loaded for scheme: " + uriScheme);
}
}
/**
*
*/
private URIResolver getResolver(String scheme) {
URIResolver resolver = null;
if (this.resolvers.containsKey(scheme)) {
resolver = (URIResolver)this.resolvers.get(scheme);
} else {
if (scheme.equals("yanelresource")) {
resolver = new ResourceResolver(this.resource);
this.resolvers.put(scheme, resolver);
} else if (scheme.equals("yanelrepo")) {
resolver = new YanelRepositoryResolver(this.resource);
this.resolvers.put(scheme, resolver);
//resolver = new RepositoryResolver(this.resource);
} else if (scheme.equals("http")) {
resolver = new HttpResolver(this.resource);
this.resolvers.put(scheme, resolver);
} else if (scheme.equals("rthtdocs")) {
resolver = new RTHtdocsResolver(this.resource);
this.resolvers.put(scheme, resolver);
} else if (scheme.equals("rtyanelhtdocs")) {
resolver = new RTYanelHtdocsResolver(this.resource);
this.resolvers.put(scheme, resolver);
}
}
return resolver;
}
}
| false | true | public Source resolve(String uri, String base) throws SourceException {
if (log.isDebugEnabled()) {
log.debug("URI to be resolved: " + uri);
log.debug("Base: "+ base);
}
int colonIndex = uri.indexOf(":/");
String uriScheme = "";
if (colonIndex <= 0) {//Check for scheme in URI, if true, then URI has no scheme
//log.error("DEBUG: URI has no scheme: " + uri);
if (base != null) {
int colBaseIndex = base.indexOf(":/");
if(colBaseIndex <=0 ){//Check for scheme in Base
throw new SourceException("invalid url syntax (missing scheme): " + uri);//no scheme found in uri and base
}else{//base contains scheme. Use base scheme for uri scheme
uriScheme = base.substring(0, colBaseIndex);
uri = PathUtil.concat(base,uri);
//log.error("DEBUG: Use scheme of base: " + uriScheme + ", " + uri);
}
} else {
log.error("Neither scheme for URI nor base specified for URI: " + uri);
throw new SourceException("invalid url syntax (missing scheme): " + uri);//no scheme found in uri and base
}
} else {//uri contains scheme
uriScheme = uri.substring(0, colonIndex);
//log.error("DEBUG: URI has scheme: " + uriScheme + ", " + uri);
}
URIResolver resolver = getResolver(uriScheme);
if (resolver != null) {
try {
// TODO: What shall be used as base?!
Source s = resolver.resolve(uri, base);
s.setSystemId(uri);
return s;
} catch (TransformerException e) {
throw new SourceException(e.getMessage(), e);
}
} else {
throw new SourceException("No resolver could be loaded for scheme: " + uriScheme);
}
}
| public Source resolve(String uri, String base) throws SourceException {
if (log.isDebugEnabled()) {
log.debug("URI to be resolved: " + uri);
log.debug("Base: "+ base);
}
// NOTE: One cannot use ":/" in order to find the protocol/scheme, because one can also specifiy the realm id and repository id, for example: yanelrepo:REALM_ID:REPO_ID:/foo/bar.gif
int colonIndex = uri.indexOf(":");
//int colonIndex = uri.indexOf(":/");
String uriScheme = "";
if (colonIndex <= 0) {//Check for scheme in URI, if true, then URI has no scheme
//log.error("DEBUG: URI has no scheme: " + uri);
if (base != null) {
int colBaseIndex = base.indexOf(":");
//int colBaseIndex = base.indexOf(":/");
if(colBaseIndex <=0 ){//Check for scheme in Base
throw new SourceException("invalid url syntax (missing scheme): " + uri);//no scheme found in uri and base
}else{//base contains scheme. Use base scheme for uri scheme
uriScheme = base.substring(0, colBaseIndex);
uri = PathUtil.concat(base,uri);
//log.error("DEBUG: Use scheme of base: " + uriScheme + ", " + uri);
}
} else {
log.error("Neither scheme for URI nor base specified for URI: " + uri);
throw new SourceException("invalid url syntax (missing scheme): " + uri);//no scheme found in uri and base
}
} else {//uri contains scheme
uriScheme = uri.substring(0, colonIndex);
//log.error("DEBUG: URI has scheme: " + uriScheme + ", " + uri);
}
URIResolver resolver = getResolver(uriScheme);
if (resolver != null) {
try {
// TODO: What shall be used as base?!
Source s = resolver.resolve(uri, base);
s.setSystemId(uri);
return s;
} catch (TransformerException e) {
throw new SourceException(e.getMessage(), e);
}
} else {
throw new SourceException("No resolver could be loaded for scheme: " + uriScheme);
}
}
|
diff --git a/org.eclipse.egit.core/src/org/eclipse/egit/core/ContainerTreeIterator.java b/org.eclipse.egit.core/src/org/eclipse/egit/core/ContainerTreeIterator.java
index b7ded696..abb3f04a 100644
--- a/org.eclipse.egit.core/src/org/eclipse/egit/core/ContainerTreeIterator.java
+++ b/org.eclipse.egit.core/src/org/eclipse/egit/core/ContainerTreeIterator.java
@@ -1,262 +1,263 @@
/*******************************************************************************
* Copyright (C) 2008, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package org.eclipse.egit.core;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.egit.core.project.RepositoryMapping;
import org.eclipse.jgit.errors.IncorrectObjectTypeException;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.FileMode;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.ObjectReader;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.treewalk.AbstractTreeIterator;
import org.eclipse.jgit.treewalk.WorkingTreeIterator;
import org.eclipse.jgit.treewalk.WorkingTreeOptions;
import org.eclipse.jgit.util.FS;
import org.eclipse.team.core.Team;
/**
* Adapts an Eclipse {@link IContainer} for use in a <code>TreeWalk</code>.
* <p>
* This iterator converts an Eclipse IContainer object into something that a
* TreeWalk instance can iterate over in parallel with any other Git tree data
* structure, such as another working directory tree from outside of the
* workspace or a stored tree from a Repository object database.
* <p>
* Modification times provided by this iterator are obtained from the cache
* Eclipse uses to track external resource modification. This can be faster, but
* requires the user refresh their workspace when external modifications take
* place. This is not really a concern as it is common practice to need to do a
* workspace refresh after externally modifying a file.
*
* @see org.eclipse.jgit.treewalk.TreeWalk
*/
public class ContainerTreeIterator extends WorkingTreeIterator {
private static String computePrefix(final IContainer base) {
final RepositoryMapping rm = RepositoryMapping.getMapping(base);
if (rm == null)
throw new IllegalArgumentException(
"Not in a Git project: " + base); //$NON-NLS-1$
return rm.getRepoRelativePath(base);
}
private final IContainer node;
/**
* Construct a new iterator from a container in the workspace.
* <p>
* The iterator will support traversal over the named container, but only if
* it is contained within a project which has the Git repository provider
* connected and this resource is mapped into a Git repository. During the
* iteration the paths will be automatically generated to match the proper
* repository paths for this container's children.
*
* @param repository
* repository the given base is mapped to
* @param base
* the part of the workspace the iterator will walk over.
*/
public ContainerTreeIterator(final Repository repository, final IContainer base) {
super(computePrefix(base), repository.getConfig().get(WorkingTreeOptions.KEY));
node = base;
init(entries());
}
/**
* Construct a new iterator from the workspace root.
* <p>
* The iterator will support traversal over workspace projects that have
* a Git repository provider connected and is mapped into a Git repository.
* During the iteration the paths will be automatically generated to match
* the proper repository paths for this container's children.
*
* @param repository
* repository the given base is mapped to
* @param root
* the workspace root to walk over.
*/
public ContainerTreeIterator(final Repository repository, final IWorkspaceRoot root) {
super("", repository.getConfig().get(WorkingTreeOptions.KEY)); //$NON-NLS-1$
node = root;
init(entries());
}
/**
* Construct a new iterator from a container in the workspace, with a given
* parent iterator.
* <p>
* The iterator will support traversal over the named container, but only if
* it is contained within a project which has the Git repository provider
* connected and this resource is mapped into a Git repository. During the
* iteration the paths will be automatically generated to match the proper
* repository paths for this container's children.
*
* @param p
* the parent iterator we were created from.
* @param base
* the part of the workspace the iterator will walk over.
*/
public ContainerTreeIterator(final WorkingTreeIterator p,
final IContainer base) {
super(p);
node = base;
init(entries());
}
@Override
public AbstractTreeIterator createSubtreeIterator(ObjectReader reader)
throws IncorrectObjectTypeException, IOException {
if (FileMode.TREE.equals(mode))
return new ContainerTreeIterator(this,
(IContainer) ((ResourceEntry) current()).rsrc);
else
throw new IncorrectObjectTypeException(ObjectId.zeroId(),
Constants.TYPE_TREE);
}
/**
* Get the ResourceEntry for the current entry.
*
* @return the current entry
*/
public ResourceEntry getResourceEntry() {
return (ResourceEntry) current();
}
private Entry[] entries() {
final IResource[] all;
try {
all = node.members(IContainer.INCLUDE_HIDDEN);
} catch (CoreException err) {
return EOF;
}
final Entry[] r = new Entry[all.length];
for (int i = 0; i < r.length; i++)
r[i] = new ResourceEntry(all[i]);
return r;
}
@Override
public boolean isEntryIgnored() throws IOException {
return super.isEntryIgnored() ||
isEntryIgnoredByTeamProvider(getResourceEntry().getResource());
}
private boolean isEntryIgnoredByTeamProvider(IResource resource) {
if (resource instanceof IWorkspaceRoot)
return false;
if (Team.isIgnoredHint(resource))
return true;
return isEntryIgnoredByTeamProvider(resource.getParent());
}
/**
* Wrapper for a resource in the Eclipse workspace
*/
static public class ResourceEntry extends Entry {
final IResource rsrc;
private final FileMode mode;
private long length = -1;
ResourceEntry(final IResource f) {
rsrc = f;
switch (f.getType()) {
case IResource.FILE:
- if (FS.DETECTED.canExecute(asFile()))
+ if (FS.DETECTED.supportsExecute()
+ && FS.DETECTED.canExecute(asFile()))
mode = FileMode.EXECUTABLE_FILE;
else
mode = FileMode.REGULAR_FILE;
break;
case IResource.PROJECT:
case IResource.FOLDER: {
final IContainer c = (IContainer) f;
if (c.findMember(Constants.DOT_GIT) != null)
mode = FileMode.GITLINK;
else
mode = FileMode.TREE;
break;
}
default:
mode = FileMode.MISSING;
break;
}
}
@Override
public FileMode getMode() {
return mode;
}
@Override
public String getName() {
if (rsrc.getType() == IResource.PROJECT)
return rsrc.getLocation().lastSegment();
else
return rsrc.getName();
}
@Override
public long getLength() {
if (length < 0) {
if (rsrc instanceof IFile)
length = asFile().length();
else
length = 0;
}
return length;
}
@Override
public long getLastModified() {
return rsrc.getLocalTimeStamp();
}
@Override
public InputStream openInputStream() throws IOException {
if (rsrc instanceof IFile) {
try {
return ((IFile) rsrc).getContents(true);
} catch (CoreException err) {
final IOException ioe = new IOException(err.getMessage());
ioe.initCause(err);
throw ioe;
}
}
throw new IOException("Not a regular file: " + rsrc); //$NON-NLS-1$
}
/**
* Get the underlying resource of this entry.
*
* @return the underlying resource
*/
public IResource getResource() {
return rsrc;
}
private File asFile() {
return ((IFile) rsrc).getLocation().toFile();
}
}
}
| true | true | ResourceEntry(final IResource f) {
rsrc = f;
switch (f.getType()) {
case IResource.FILE:
if (FS.DETECTED.canExecute(asFile()))
mode = FileMode.EXECUTABLE_FILE;
else
mode = FileMode.REGULAR_FILE;
break;
case IResource.PROJECT:
case IResource.FOLDER: {
final IContainer c = (IContainer) f;
if (c.findMember(Constants.DOT_GIT) != null)
mode = FileMode.GITLINK;
else
mode = FileMode.TREE;
break;
}
default:
mode = FileMode.MISSING;
break;
}
}
| ResourceEntry(final IResource f) {
rsrc = f;
switch (f.getType()) {
case IResource.FILE:
if (FS.DETECTED.supportsExecute()
&& FS.DETECTED.canExecute(asFile()))
mode = FileMode.EXECUTABLE_FILE;
else
mode = FileMode.REGULAR_FILE;
break;
case IResource.PROJECT:
case IResource.FOLDER: {
final IContainer c = (IContainer) f;
if (c.findMember(Constants.DOT_GIT) != null)
mode = FileMode.GITLINK;
else
mode = FileMode.TREE;
break;
}
default:
mode = FileMode.MISSING;
break;
}
}
|
diff --git a/flexodesktop/model/flexopamela/src/main/java/org/openflexo/model/factory/XMLDeserializer.java b/flexodesktop/model/flexopamela/src/main/java/org/openflexo/model/factory/XMLDeserializer.java
index 6537b633a..7bb5e650a 100644
--- a/flexodesktop/model/flexopamela/src/main/java/org/openflexo/model/factory/XMLDeserializer.java
+++ b/flexodesktop/model/flexopamela/src/main/java/org/openflexo/model/factory/XMLDeserializer.java
@@ -1,326 +1,327 @@
package org.openflexo.model.factory;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.filter.ElementFilter;
import org.jdom2.input.SAXBuilder;
import org.openflexo.model.ModelContext.ModelPropertyXMLTag;
import org.openflexo.model.ModelEntity;
import org.openflexo.model.ModelProperty;
import org.openflexo.model.StringEncoder;
import org.openflexo.model.exceptions.InvalidDataException;
import org.openflexo.model.exceptions.ModelDefinitionException;
import org.openflexo.model.exceptions.ModelExecutionException;
import org.openflexo.model.exceptions.RestrictiveDeserializationException;
class XMLDeserializer {
public static final String ID = "id";
public static final String ID_REF = "idref";
private ModelFactory modelFactory;
private Map<String, Element> index;
/**
* Stores already serialized objects where value is the serialized object and key is an object coding the unique identifier of the
* object
*/
private Map<Object, Object> alreadyDeserialized;
private List<ProxyMethodHandler<?>> deserializingHandlers;
private final DeserializationPolicy policy;
public XMLDeserializer(ModelFactory factory) {
this(factory, DeserializationPolicy.PERMISSIVE);
}
public XMLDeserializer(ModelFactory factory, DeserializationPolicy policy) {
this.modelFactory = factory;
this.policy = policy;
alreadyDeserialized = new HashMap<Object, Object>();
deserializingHandlers = new ArrayList<ProxyMethodHandler<?>>();
}
private StringEncoder getStringEncoder() {
return modelFactory.getStringEncoder();
}
public Object deserializeDocument(InputStream in) throws IOException, JDOMException, InvalidDataException, ModelDefinitionException {
alreadyDeserialized.clear();
Document dataDocument = parseXMLData(in);
Element rootElement = dataDocument.getRootElement();
return buildObjectFromNode(rootElement);
}
public Object deserializeDocument(String xml) throws IOException, JDOMException, InvalidDataException, ModelDefinitionException {
alreadyDeserialized.clear();
Document dataDocument = parseXMLData(xml);
Element rootElement = dataDocument.getRootElement();
return buildObjectFromNode(rootElement);
}
private Object buildObjectFromNode(Element node) throws InvalidDataException, ModelDefinitionException {
// System.out.println("What to do with "+node+" ?");
ModelEntity<?> modelEntity = modelFactory.getModelContext().getModelEntity(node.getName());
Object object = buildObjectFromNodeAndModelEntity(node, modelEntity);
for (ProxyMethodHandler<?> handler : deserializingHandlers) {
handler.setDeserializing(false);
}
return object;
}
private <I> Object buildObjectFromNodeAndModelEntity(Element node, ModelEntity<I> modelEntity) throws InvalidDataException,
ModelDefinitionException {
Object currentDeserializedReference = null;
Attribute idAttribute = node.getAttribute(ID);
Attribute idrefAttribute = node.getAttribute(ID_REF);
if (idrefAttribute != null) {
// This seems to be an already deserialized object
Object reference;
reference = idrefAttribute.getValue();
Object referenceObject = alreadyDeserialized.get(reference);
if (referenceObject == null) {
// Try to find this object elsewhere in the document
// NOTE: This should never occur, except if the file was
// manually edited, or
// if the file was generated BEFORE development of ordered
// properties feature
// TODO: Throw here an error in future release but for backward compatibility we leave it for now.
Element idRefElement = findElementWithId(idrefAttribute.getValue());
if (idRefElement != null) {
return buildObjectFromNodeAndModelEntity(idRefElement, modelEntity);
}
throw new InvalidDataException("No reference to object with identifier " + reference);
} else {
// No need to go further: i've got my object
// Debugging.debug ("Stopping decoding: object found as a
// reference "+reference+" "+referenceObject);
return referenceObject;
}
}
if (idAttribute != null) {
currentDeserializedReference = idAttribute.getValue();
Object referenceObject = alreadyDeserialized.get(currentDeserializedReference);
if (referenceObject != null) {
// No need to go further: i've got my object
return referenceObject;
}
}
// I need to rebuild it
I returned;
String text = node.getText();
if (text != null && getStringEncoder().isConvertable(modelEntity.getImplementedInterface())) {
// GPO: I am not sure this is still useful.
try {
returned = getStringEncoder().fromString(modelEntity.getImplementedInterface(), text);
} catch (InvalidDataException e) {
throw new ModelExecutionException(e);
}
} else {
returned = modelFactory._newInstance(modelEntity.getImplementedInterface(), policy == DeserializationPolicy.EXTENSIVE);
}
if (currentDeserializedReference != null) {
alreadyDeserialized.put(currentDeserializedReference, returned);
}
ProxyMethodHandler<I> handler = modelFactory.getHandler(returned);
deserializingHandlers.add(handler);
handler.setDeserializing(true);
for (Attribute attribute : node.getAttributes()) {
ModelProperty<? super I> property = modelEntity.getPropertyForXMLAttributeName(attribute.getName());
if (property == null) {
if (attribute.getNamespace().equals(PAMELAConstants.NAMESPACE)
&& (attribute.getName().equals(PAMELAConstants.CLASS_ATTRIBUTE) || attribute.getName().equals(
PAMELAConstants.MODEL_ENTITY_ATTRIBUTE))) {
continue;
}
if (attribute.getName().equals(ID) || attribute.getName().equals(ID_REF)) {
continue;
}
switch (policy) {
case PERMISSIVE:
continue;
case RESTRICTIVE:
throw new RestrictiveDeserializationException("No attribute found for the attribute named: " + attribute.getName());
case EXTENSIVE:
// TODO: handle extra values
- break;
+ // break;
+ continue; // As long as we don't handlethem, we continue to avoid NPE.
}
}
Object value = getStringEncoder().fromString(property.getType(), attribute.getValue());
if (value != null) {
handler.invokeSetterForDeserialization(property, value);
}
}
for (Element child : node.getChildren()) {
ModelPropertyXMLTag<I> modelPropertyXMLTag = modelFactory.getModelContext().getPropertyForXMLTag(modelEntity, child.getName());
ModelProperty<? super I> property = null;
ModelEntity<?> entity = null;
if (modelPropertyXMLTag != null) {
property = modelPropertyXMLTag.getProperty();
entity = modelPropertyXMLTag.getAccessedEntity();
} else if (policy == DeserializationPolicy.RESTRICTIVE) {
throw new RestrictiveDeserializationException("Element with name does not fit any properties within entity " + modelEntity);
}
Class<?> implementedInterface = null;
Class<?> implementingClass = null;
String entityName = child.getAttributeValue(PAMELAConstants.MODEL_ENTITY_ATTRIBUTE, PAMELAConstants.NAMESPACE);
String className = child.getAttributeValue(PAMELAConstants.CLASS_ATTRIBUTE, PAMELAConstants.NAMESPACE);
if (entityName != null) {
try {
implementedInterface = Class.forName(entityName);
} catch (ClassNotFoundException e) {
// TODO: log something here
}
switch (policy) {
case PERMISSIVE:
break;
case RESTRICTIVE:
break;
case EXTENSIVE:
if (entityName != null) {
entity = modelFactory.importClass(implementedInterface);
if (className != null) {
try {
implementingClass = Class.forName(className);
if (implementedInterface.isAssignableFrom(implementingClass)) {
modelFactory.setImplementingClassForInterface((Class) implementingClass, implementedInterface,
policy == DeserializationPolicy.EXTENSIVE);
} else {
throw new ModelExecutionException(className + " does not implement " + implementedInterface
+ " for node " + child.getName());
}
} catch (ClassNotFoundException e) {
// TODO: log something here
}
}
}
break;
}
if (implementedInterface != null) {
if (policy == DeserializationPolicy.EXTENSIVE) {
entity = modelFactory.getExtendedContext().getModelEntity(implementedInterface);
} else {
entity = modelFactory.getModelContext().getModelEntity(implementedInterface);
}
}
if (entity == null && policy == DeserializationPolicy.RESTRICTIVE) {
if (entityName != null) {
throw new RestrictiveDeserializationException("Entity " + entityName + " is not part of this model context");
} else {
throw new RestrictiveDeserializationException("No entity found for tag " + child.getName());
}
}
}
if (property != null) {
Object value = null;
if (entity != null && !getStringEncoder().isConvertable(property.getType())) {
value = buildObjectFromNodeAndModelEntity(child, entity);
} else if (getStringEncoder().isConvertable(property.getType())) {
value = getStringEncoder().fromString(property.getType(), child.getText());
} else {
// Should not happen
throw new ModelExecutionException("Found property " + property + " but was unable to deserialize the content of node "
+ child);
}
switch (property.getCardinality()) {
case SINGLE:
handler.invokeSetterForDeserialization(property, value);
break;
case LIST:
handler.invokeAdderForDeserialization(property, value);
break;
case MAP:
throw new UnsupportedOperationException("Cannot deserialize maps for now");
default:
break;
}
}
}
return returned;
}
private class MatchingElement {
private Element element;
private ModelEntity<?> modelEntity;
private MatchingElement(Element element, ModelEntity<?> modelEntity) {
super();
this.element = element;
this.modelEntity = modelEntity;
}
@Override
public String toString() {
return element.toString() + "/" + modelEntity;
}
}
protected Document parseXMLData(InputStream xmlStream) throws IOException, JDOMException {
SAXBuilder parser = new SAXBuilder();
Document reply = parser.build(xmlStream);
makeIndex(reply);
return reply;
}
protected Document parseXMLData(String xml) throws IOException, JDOMException {
SAXBuilder parser = new SAXBuilder();
Document reply = parser.build(new StringReader(xml));
makeIndex(reply);
return reply;
}
static private class ElementWithIDFilter extends ElementFilter {
public ElementWithIDFilter() {
super();
}
@Override
public Element filter(Object arg0) {
Element element = super.filter(arg0);
if (element != null && element.getAttributeValue("id") != null) {
return element;
}
return null;
}
}
public Document makeIndex(Document doc) {
index = new Hashtable<String, Element>();
Iterator<Element> it = doc.getDescendants(new ElementWithIDFilter());
Element e = null;
while (it.hasNext()) {
e = it.next();
index.put(e.getAttributeValue("id"), e);
}
return doc;
}
private Element findElementWithId(String id) {
return index.get(id);
}
}
| true | true | private <I> Object buildObjectFromNodeAndModelEntity(Element node, ModelEntity<I> modelEntity) throws InvalidDataException,
ModelDefinitionException {
Object currentDeserializedReference = null;
Attribute idAttribute = node.getAttribute(ID);
Attribute idrefAttribute = node.getAttribute(ID_REF);
if (idrefAttribute != null) {
// This seems to be an already deserialized object
Object reference;
reference = idrefAttribute.getValue();
Object referenceObject = alreadyDeserialized.get(reference);
if (referenceObject == null) {
// Try to find this object elsewhere in the document
// NOTE: This should never occur, except if the file was
// manually edited, or
// if the file was generated BEFORE development of ordered
// properties feature
// TODO: Throw here an error in future release but for backward compatibility we leave it for now.
Element idRefElement = findElementWithId(idrefAttribute.getValue());
if (idRefElement != null) {
return buildObjectFromNodeAndModelEntity(idRefElement, modelEntity);
}
throw new InvalidDataException("No reference to object with identifier " + reference);
} else {
// No need to go further: i've got my object
// Debugging.debug ("Stopping decoding: object found as a
// reference "+reference+" "+referenceObject);
return referenceObject;
}
}
if (idAttribute != null) {
currentDeserializedReference = idAttribute.getValue();
Object referenceObject = alreadyDeserialized.get(currentDeserializedReference);
if (referenceObject != null) {
// No need to go further: i've got my object
return referenceObject;
}
}
// I need to rebuild it
I returned;
String text = node.getText();
if (text != null && getStringEncoder().isConvertable(modelEntity.getImplementedInterface())) {
// GPO: I am not sure this is still useful.
try {
returned = getStringEncoder().fromString(modelEntity.getImplementedInterface(), text);
} catch (InvalidDataException e) {
throw new ModelExecutionException(e);
}
} else {
returned = modelFactory._newInstance(modelEntity.getImplementedInterface(), policy == DeserializationPolicy.EXTENSIVE);
}
if (currentDeserializedReference != null) {
alreadyDeserialized.put(currentDeserializedReference, returned);
}
ProxyMethodHandler<I> handler = modelFactory.getHandler(returned);
deserializingHandlers.add(handler);
handler.setDeserializing(true);
for (Attribute attribute : node.getAttributes()) {
ModelProperty<? super I> property = modelEntity.getPropertyForXMLAttributeName(attribute.getName());
if (property == null) {
if (attribute.getNamespace().equals(PAMELAConstants.NAMESPACE)
&& (attribute.getName().equals(PAMELAConstants.CLASS_ATTRIBUTE) || attribute.getName().equals(
PAMELAConstants.MODEL_ENTITY_ATTRIBUTE))) {
continue;
}
if (attribute.getName().equals(ID) || attribute.getName().equals(ID_REF)) {
continue;
}
switch (policy) {
case PERMISSIVE:
continue;
case RESTRICTIVE:
throw new RestrictiveDeserializationException("No attribute found for the attribute named: " + attribute.getName());
case EXTENSIVE:
// TODO: handle extra values
break;
}
}
Object value = getStringEncoder().fromString(property.getType(), attribute.getValue());
if (value != null) {
handler.invokeSetterForDeserialization(property, value);
}
}
for (Element child : node.getChildren()) {
ModelPropertyXMLTag<I> modelPropertyXMLTag = modelFactory.getModelContext().getPropertyForXMLTag(modelEntity, child.getName());
ModelProperty<? super I> property = null;
ModelEntity<?> entity = null;
if (modelPropertyXMLTag != null) {
property = modelPropertyXMLTag.getProperty();
entity = modelPropertyXMLTag.getAccessedEntity();
} else if (policy == DeserializationPolicy.RESTRICTIVE) {
throw new RestrictiveDeserializationException("Element with name does not fit any properties within entity " + modelEntity);
}
Class<?> implementedInterface = null;
Class<?> implementingClass = null;
String entityName = child.getAttributeValue(PAMELAConstants.MODEL_ENTITY_ATTRIBUTE, PAMELAConstants.NAMESPACE);
String className = child.getAttributeValue(PAMELAConstants.CLASS_ATTRIBUTE, PAMELAConstants.NAMESPACE);
if (entityName != null) {
try {
implementedInterface = Class.forName(entityName);
} catch (ClassNotFoundException e) {
// TODO: log something here
}
switch (policy) {
case PERMISSIVE:
break;
case RESTRICTIVE:
break;
case EXTENSIVE:
if (entityName != null) {
entity = modelFactory.importClass(implementedInterface);
if (className != null) {
try {
implementingClass = Class.forName(className);
if (implementedInterface.isAssignableFrom(implementingClass)) {
modelFactory.setImplementingClassForInterface((Class) implementingClass, implementedInterface,
policy == DeserializationPolicy.EXTENSIVE);
} else {
throw new ModelExecutionException(className + " does not implement " + implementedInterface
+ " for node " + child.getName());
}
} catch (ClassNotFoundException e) {
// TODO: log something here
}
}
}
break;
}
if (implementedInterface != null) {
if (policy == DeserializationPolicy.EXTENSIVE) {
entity = modelFactory.getExtendedContext().getModelEntity(implementedInterface);
} else {
entity = modelFactory.getModelContext().getModelEntity(implementedInterface);
}
}
if (entity == null && policy == DeserializationPolicy.RESTRICTIVE) {
if (entityName != null) {
throw new RestrictiveDeserializationException("Entity " + entityName + " is not part of this model context");
} else {
throw new RestrictiveDeserializationException("No entity found for tag " + child.getName());
}
}
}
if (property != null) {
Object value = null;
if (entity != null && !getStringEncoder().isConvertable(property.getType())) {
value = buildObjectFromNodeAndModelEntity(child, entity);
} else if (getStringEncoder().isConvertable(property.getType())) {
value = getStringEncoder().fromString(property.getType(), child.getText());
} else {
// Should not happen
throw new ModelExecutionException("Found property " + property + " but was unable to deserialize the content of node "
+ child);
}
switch (property.getCardinality()) {
case SINGLE:
handler.invokeSetterForDeserialization(property, value);
break;
case LIST:
handler.invokeAdderForDeserialization(property, value);
break;
case MAP:
throw new UnsupportedOperationException("Cannot deserialize maps for now");
default:
break;
}
}
}
return returned;
}
| private <I> Object buildObjectFromNodeAndModelEntity(Element node, ModelEntity<I> modelEntity) throws InvalidDataException,
ModelDefinitionException {
Object currentDeserializedReference = null;
Attribute idAttribute = node.getAttribute(ID);
Attribute idrefAttribute = node.getAttribute(ID_REF);
if (idrefAttribute != null) {
// This seems to be an already deserialized object
Object reference;
reference = idrefAttribute.getValue();
Object referenceObject = alreadyDeserialized.get(reference);
if (referenceObject == null) {
// Try to find this object elsewhere in the document
// NOTE: This should never occur, except if the file was
// manually edited, or
// if the file was generated BEFORE development of ordered
// properties feature
// TODO: Throw here an error in future release but for backward compatibility we leave it for now.
Element idRefElement = findElementWithId(idrefAttribute.getValue());
if (idRefElement != null) {
return buildObjectFromNodeAndModelEntity(idRefElement, modelEntity);
}
throw new InvalidDataException("No reference to object with identifier " + reference);
} else {
// No need to go further: i've got my object
// Debugging.debug ("Stopping decoding: object found as a
// reference "+reference+" "+referenceObject);
return referenceObject;
}
}
if (idAttribute != null) {
currentDeserializedReference = idAttribute.getValue();
Object referenceObject = alreadyDeserialized.get(currentDeserializedReference);
if (referenceObject != null) {
// No need to go further: i've got my object
return referenceObject;
}
}
// I need to rebuild it
I returned;
String text = node.getText();
if (text != null && getStringEncoder().isConvertable(modelEntity.getImplementedInterface())) {
// GPO: I am not sure this is still useful.
try {
returned = getStringEncoder().fromString(modelEntity.getImplementedInterface(), text);
} catch (InvalidDataException e) {
throw new ModelExecutionException(e);
}
} else {
returned = modelFactory._newInstance(modelEntity.getImplementedInterface(), policy == DeserializationPolicy.EXTENSIVE);
}
if (currentDeserializedReference != null) {
alreadyDeserialized.put(currentDeserializedReference, returned);
}
ProxyMethodHandler<I> handler = modelFactory.getHandler(returned);
deserializingHandlers.add(handler);
handler.setDeserializing(true);
for (Attribute attribute : node.getAttributes()) {
ModelProperty<? super I> property = modelEntity.getPropertyForXMLAttributeName(attribute.getName());
if (property == null) {
if (attribute.getNamespace().equals(PAMELAConstants.NAMESPACE)
&& (attribute.getName().equals(PAMELAConstants.CLASS_ATTRIBUTE) || attribute.getName().equals(
PAMELAConstants.MODEL_ENTITY_ATTRIBUTE))) {
continue;
}
if (attribute.getName().equals(ID) || attribute.getName().equals(ID_REF)) {
continue;
}
switch (policy) {
case PERMISSIVE:
continue;
case RESTRICTIVE:
throw new RestrictiveDeserializationException("No attribute found for the attribute named: " + attribute.getName());
case EXTENSIVE:
// TODO: handle extra values
// break;
continue; // As long as we don't handlethem, we continue to avoid NPE.
}
}
Object value = getStringEncoder().fromString(property.getType(), attribute.getValue());
if (value != null) {
handler.invokeSetterForDeserialization(property, value);
}
}
for (Element child : node.getChildren()) {
ModelPropertyXMLTag<I> modelPropertyXMLTag = modelFactory.getModelContext().getPropertyForXMLTag(modelEntity, child.getName());
ModelProperty<? super I> property = null;
ModelEntity<?> entity = null;
if (modelPropertyXMLTag != null) {
property = modelPropertyXMLTag.getProperty();
entity = modelPropertyXMLTag.getAccessedEntity();
} else if (policy == DeserializationPolicy.RESTRICTIVE) {
throw new RestrictiveDeserializationException("Element with name does not fit any properties within entity " + modelEntity);
}
Class<?> implementedInterface = null;
Class<?> implementingClass = null;
String entityName = child.getAttributeValue(PAMELAConstants.MODEL_ENTITY_ATTRIBUTE, PAMELAConstants.NAMESPACE);
String className = child.getAttributeValue(PAMELAConstants.CLASS_ATTRIBUTE, PAMELAConstants.NAMESPACE);
if (entityName != null) {
try {
implementedInterface = Class.forName(entityName);
} catch (ClassNotFoundException e) {
// TODO: log something here
}
switch (policy) {
case PERMISSIVE:
break;
case RESTRICTIVE:
break;
case EXTENSIVE:
if (entityName != null) {
entity = modelFactory.importClass(implementedInterface);
if (className != null) {
try {
implementingClass = Class.forName(className);
if (implementedInterface.isAssignableFrom(implementingClass)) {
modelFactory.setImplementingClassForInterface((Class) implementingClass, implementedInterface,
policy == DeserializationPolicy.EXTENSIVE);
} else {
throw new ModelExecutionException(className + " does not implement " + implementedInterface
+ " for node " + child.getName());
}
} catch (ClassNotFoundException e) {
// TODO: log something here
}
}
}
break;
}
if (implementedInterface != null) {
if (policy == DeserializationPolicy.EXTENSIVE) {
entity = modelFactory.getExtendedContext().getModelEntity(implementedInterface);
} else {
entity = modelFactory.getModelContext().getModelEntity(implementedInterface);
}
}
if (entity == null && policy == DeserializationPolicy.RESTRICTIVE) {
if (entityName != null) {
throw new RestrictiveDeserializationException("Entity " + entityName + " is not part of this model context");
} else {
throw new RestrictiveDeserializationException("No entity found for tag " + child.getName());
}
}
}
if (property != null) {
Object value = null;
if (entity != null && !getStringEncoder().isConvertable(property.getType())) {
value = buildObjectFromNodeAndModelEntity(child, entity);
} else if (getStringEncoder().isConvertable(property.getType())) {
value = getStringEncoder().fromString(property.getType(), child.getText());
} else {
// Should not happen
throw new ModelExecutionException("Found property " + property + " but was unable to deserialize the content of node "
+ child);
}
switch (property.getCardinality()) {
case SINGLE:
handler.invokeSetterForDeserialization(property, value);
break;
case LIST:
handler.invokeAdderForDeserialization(property, value);
break;
case MAP:
throw new UnsupportedOperationException("Cannot deserialize maps for now");
default:
break;
}
}
}
return returned;
}
|
diff --git a/src/main/java/com/eyeq/pivot4j/primefaces/ui/PrimeFacesPivotRenderer.java b/src/main/java/com/eyeq/pivot4j/primefaces/ui/PrimeFacesPivotRenderer.java
index f7cfe54..36f2854 100644
--- a/src/main/java/com/eyeq/pivot4j/primefaces/ui/PrimeFacesPivotRenderer.java
+++ b/src/main/java/com/eyeq/pivot4j/primefaces/ui/PrimeFacesPivotRenderer.java
@@ -1,425 +1,421 @@
package com.eyeq.pivot4j.primefaces.ui;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import javax.el.ExpressionFactory;
import javax.el.MethodExpression;
import javax.faces.application.Application;
import javax.faces.component.UIParameter;
import javax.faces.component.html.HtmlOutputText;
import javax.faces.component.html.HtmlPanelGroup;
import javax.faces.context.FacesContext;
import org.olap4j.Axis;
import org.olap4j.Cell;
import org.primefaces.component.column.Column;
import org.primefaces.component.commandbutton.CommandButton;
import org.primefaces.component.panelgrid.PanelGrid;
import org.primefaces.component.row.Row;
import org.primefaces.context.RequestContext;
import com.eyeq.pivot4j.PivotModel;
import com.eyeq.pivot4j.ui.AbstractPivotUIRenderer;
import com.eyeq.pivot4j.ui.CellType;
import com.eyeq.pivot4j.ui.PivotUIRenderer;
import com.eyeq.pivot4j.ui.RenderContext;
import com.eyeq.pivot4j.ui.aggregator.Aggregator;
import com.eyeq.pivot4j.ui.command.BasicDrillThroughCommand;
import com.eyeq.pivot4j.ui.command.CellCommand;
import com.eyeq.pivot4j.ui.command.CellParameters;
public class PrimeFacesPivotRenderer extends AbstractPivotUIRenderer {
private Map<String, String> iconMap;
private PanelGrid component;
private FacesContext facesContext;
private ExpressionFactory expressionFactory;
private HtmlPanelGroup header;
private Row row;
private Column column;
private int commandIndex = 0;
private ResourceBundle bundle;
/**
* @param facesContext
*/
public PrimeFacesPivotRenderer(FacesContext facesContext) {
this.facesContext = facesContext;
if (facesContext != null) {
Application application = facesContext.getApplication();
this.expressionFactory = application.getExpressionFactory();
}
}
/**
* @return the parent JSF component
*/
public PanelGrid getComponent() {
return component;
}
/**
* @param component
*/
public void setComponent(PanelGrid component) {
this.component = component;
}
/**
* @see com.eyeq.pivot4j.ui.AbstractPivotRenderer#initialize()
*/
@Override
public void initialize() {
super.initialize();
FacesContext context = FacesContext.getCurrentInstance();
this.bundle = context.getApplication()
.getResourceBundle(context, "msg");
// Map command mode names to jQuery's predefined icon names. It can be
// also done by CSS.
this.iconMap = new HashMap<String, String>();
iconMap.put("expandPosition-position", "ui-icon-plus");
iconMap.put("collapsePosition-position", "ui-icon-minus");
iconMap.put("expandMember-member", "ui-icon-plusthick");
iconMap.put("collapseMember-member", "ui-icon-minusthick");
iconMap.put("drillDown-replace", "ui-icon-arrowthick-1-e");
iconMap.put("drillUp-replace", "ui-icon-arrowthick-1-n");
iconMap.put("sort-basic-natural", "ui-icon-triangle-2-n-s");
iconMap.put("sort-basic-other-up", "ui-icon-triangle-1-n");
iconMap.put("sort-basic-other-down", "ui-icon-triangle-1-s");
iconMap.put("sort-basic-current-up", "ui-icon-circle-triangle-n");
iconMap.put("sort-basic-current-down", "ui-icon-circle-triangle-s");
iconMap.put("drillThrough", "ui-icon-search");
this.commandIndex = 0;
}
/**
* @return bundle
*/
protected ResourceBundle getBundle() {
return bundle;
}
/**
* @see com.eyeq.pivot4j.ui.AbstractPivotUIRenderer#registerCommands()
*/
@Override
protected void registerCommands() {
super.registerCommands();
addCommand(new DrillThroughCommandImpl(this));
}
/**
* @see com.eyeq.pivot4j.ui.AbstractPivotRenderer#getCellLabel(com.eyeq.pivot4j.ui.RenderContext)
*/
@Override
protected String getCellLabel(RenderContext context) {
String label = super.getCellLabel(context);
if (context.getCellType() == CellType.Aggregation) {
Aggregator aggregator = context.getAggregator();
if (aggregator != null && context.getMember() == null) {
String key = "label.aggregation.type." + aggregator.getName();
String value = bundle.getString(key);
if (value != null) {
label = value;
}
}
}
return label;
}
/**
* @see com.eyeq.pivot4j.ui.PivotLayoutCallback#startTable(com.eyeq.pivot4j.ui.RenderContext)
*/
@Override
public void startTable(RenderContext context) {
component.getChildren().clear();
}
/**
* @see com.eyeq.pivot4j.ui.PivotLayoutCallback#startHeader(com.eyeq.pivot4j.ui.RenderContext)
*/
@Override
public void startHeader(RenderContext context) {
this.header = new HtmlPanelGroup();
header.setId("pivot-header");
}
/**
* @see com.eyeq.pivot4j.ui.PivotLayoutCallback#endHeader(com.eyeq.pivot4j.ui.RenderContext)
*/
@Override
public void endHeader(RenderContext context) {
component.getFacets().put("header", header);
this.header = null;
}
/**
* @see com.eyeq.pivot4j.ui.PivotLayoutCallback#startBody(com.eyeq.pivot4j.ui.RenderContext)
*/
@Override
public void startBody(RenderContext context) {
}
/**
* @see com.eyeq.pivot4j.ui.PivotLayoutCallback#startRow(com.eyeq.pivot4j.ui.RenderContext)
*/
@Override
public void startRow(RenderContext context) {
this.row = new Row();
}
/**
* @see com.eyeq.pivot4j.ui.AbstractPivotRenderer#startCell(com.eyeq.pivot4j.ui.RenderContext,
* java.util.List)
*/
@Override
public void startCell(RenderContext context, List<CellCommand<?>> commands) {
this.column = new Column();
String id = "col-" + column.hashCode();
column.setId(id);
column.setColspan(context.getColSpan());
column.setRowspan(context.getRowSpan());
String styleClass;
switch (context.getCellType()) {
case Header:
case Title:
case None:
if (context.getAxis() == Axis.COLUMNS) {
styleClass = "col-hdr-cell";
} else {
if (context.getCellType() == CellType.Header) {
styleClass = "row-hdr-cell ui-widget-header";
} else {
styleClass = "ui-widget-header";
}
}
if (!getShowParentMembers() && context.getMember() != null) {
int padding = context.getMember().getDepth() * 10;
column.setStyle("padding-left: " + padding + "px");
}
break;
case Aggregation:
if (context.getAxis() == Axis.ROWS) {
styleClass = "ui-widget-header ";
} else {
styleClass = "";
}
- if (context.getMember() == null) {
- styleClass += "agg-title";
- } else {
- styleClass += "agg-hdr";
- }
+ styleClass += "agg-title";
if (!getShowParentMembers() && context.getMember() != null) {
int padding = context.getMember().getDepth() * 10;
column.setStyle("padding-left: " + padding + "px");
}
break;
case Value:
if (context.getAggregator() == null) {
// PrimeFaces' Row class doesn't have the styleClass property.
if (context.getRowIndex() % 2 == 0) {
styleClass = "value-cell cell-even";
} else {
styleClass = "value-cell cell-odd";
}
} else {
styleClass = "ui-widget-header agg-cell";
if (context.getAxis() == Axis.COLUMNS) {
styleClass += " col-agg-cell";
} else if (context.getAxis() == Axis.ROWS) {
styleClass += " row-agg-cell";
}
}
break;
default:
styleClass = null;
}
column.setStyleClass(styleClass);
if (expressionFactory != null) {
for (CellCommand<?> command : commands) {
CellParameters parameters = command.createParameters(context);
CommandButton button = new CommandButton();
// JSF requires an unique id for command components.
button.setId("btn-" + commandIndex++);
button.setTitle(command.getDescription());
String icon = null;
String mode = command.getMode(context);
if (mode == null) {
icon = iconMap.get(command.getName());
} else {
icon = iconMap.get(command.getName() + "-" + mode);
}
button.setIcon(icon);
MethodExpression expression = expressionFactory
.createMethodExpression(facesContext.getELContext(),
"#{pivotGridHandler.executeCommand}",
Void.class, new Class<?>[0]);
button.setActionExpression(expression);
button.setUpdate(":grid-form,:editor-form:mdx-editor,:editor-form:editor-toolbar,:source-tree-form,:target-tree-form");
UIParameter commandParam = new UIParameter();
commandParam.setName("command");
commandParam.setValue(command.getName());
button.getChildren().add(commandParam);
UIParameter axisParam = new UIParameter();
axisParam.setName("axis");
axisParam.setValue(parameters.getAxisOrdinal());
button.getChildren().add(axisParam);
UIParameter positionParam = new UIParameter();
positionParam.setName("position");
positionParam.setValue(parameters.getPositionOrdinal());
button.getChildren().add(positionParam);
UIParameter memberParam = new UIParameter();
memberParam.setName("member");
memberParam.setValue(parameters.getMemberOrdinal());
button.getChildren().add(memberParam);
UIParameter hierarchyParam = new UIParameter();
hierarchyParam.setName("hierarchy");
hierarchyParam.setValue(parameters.getHierarchyOrdinal());
button.getChildren().add(hierarchyParam);
UIParameter cellParam = new UIParameter();
hierarchyParam.setName("cell");
hierarchyParam.setValue(parameters.getCellOrdinal());
button.getChildren().add(cellParam);
column.getChildren().add(button);
}
}
}
/**
* @see com.eyeq.pivot4j.ui.AbstractPivotRenderer#cellContent(com.eyeq.pivot4j.ui.RenderContext,
* java.lang.String)
*/
@Override
public void cellContent(RenderContext context, String label) {
HtmlOutputText text = new HtmlOutputText();
String id = "txt-" + text.hashCode();
text.setId(id);
text.setValue(label);
column.getChildren().add(text);
}
/**
* @see com.eyeq.pivot4j.ui.PivotLayoutCallback#endCell(com.eyeq.pivot4j.ui.RenderContext)
*/
@Override
public void endCell(RenderContext context) {
row.getChildren().add(column);
this.column = null;
}
/**
* @see com.eyeq.pivot4j.ui.PivotLayoutCallback#endRow(com.eyeq.pivot4j.ui.RenderContext)
*/
@Override
public void endRow(RenderContext context) {
if (header == null) {
component.getChildren().add(row);
} else {
header.getChildren().add(row);
}
this.row = null;
}
/**
* @see com.eyeq.pivot4j.ui.PivotLayoutCallback#endBody(com.eyeq.pivot4j.ui.RenderContext)
*/
@Override
public void endBody(RenderContext context) {
}
/**
* @see com.eyeq.pivot4j.ui.PivotLayoutCallback#endTable(com.eyeq.pivot4j.ui.RenderContext)
*/
@Override
public void endTable(RenderContext context) {
this.commandIndex = 0;
}
/**
* Workaround to implement lazy rendering due to limitation in Olap4J's API
* :
*
* @see http://sourceforge.net/p/olap4j/bugs/15/
*/
class DrillThroughCommandImpl extends BasicDrillThroughCommand {
/**
* @param renderer
*/
public DrillThroughCommandImpl(PivotUIRenderer renderer) {
super(renderer);
}
/**
* @see com.eyeq.pivot4j.ui.command.BasicDrillThroughCommand#execute(com.eyeq.pivot4j.PivotModel,
* com.eyeq.pivot4j.ui.command.CellParameters)
*/
@Override
public ResultSet execute(PivotModel model, CellParameters parameters) {
Cell cell = model.getCellSet().getCell(parameters.getCellOrdinal());
DrillThroughDataModel data = facesContext.getApplication()
.evaluateExpressionGet(facesContext, "#{drillThroughData}",
DrillThroughDataModel.class);
data.initialize(cell);
data.setPageSize(15);
RequestContext context = RequestContext.getCurrentInstance();
context.execute("drillThrough();");
return null;
}
}
}
| true | true | public void startCell(RenderContext context, List<CellCommand<?>> commands) {
this.column = new Column();
String id = "col-" + column.hashCode();
column.setId(id);
column.setColspan(context.getColSpan());
column.setRowspan(context.getRowSpan());
String styleClass;
switch (context.getCellType()) {
case Header:
case Title:
case None:
if (context.getAxis() == Axis.COLUMNS) {
styleClass = "col-hdr-cell";
} else {
if (context.getCellType() == CellType.Header) {
styleClass = "row-hdr-cell ui-widget-header";
} else {
styleClass = "ui-widget-header";
}
}
if (!getShowParentMembers() && context.getMember() != null) {
int padding = context.getMember().getDepth() * 10;
column.setStyle("padding-left: " + padding + "px");
}
break;
case Aggregation:
if (context.getAxis() == Axis.ROWS) {
styleClass = "ui-widget-header ";
} else {
styleClass = "";
}
if (context.getMember() == null) {
styleClass += "agg-title";
} else {
styleClass += "agg-hdr";
}
if (!getShowParentMembers() && context.getMember() != null) {
int padding = context.getMember().getDepth() * 10;
column.setStyle("padding-left: " + padding + "px");
}
break;
case Value:
if (context.getAggregator() == null) {
// PrimeFaces' Row class doesn't have the styleClass property.
if (context.getRowIndex() % 2 == 0) {
styleClass = "value-cell cell-even";
} else {
styleClass = "value-cell cell-odd";
}
} else {
styleClass = "ui-widget-header agg-cell";
if (context.getAxis() == Axis.COLUMNS) {
styleClass += " col-agg-cell";
} else if (context.getAxis() == Axis.ROWS) {
styleClass += " row-agg-cell";
}
}
break;
default:
styleClass = null;
}
column.setStyleClass(styleClass);
if (expressionFactory != null) {
for (CellCommand<?> command : commands) {
CellParameters parameters = command.createParameters(context);
CommandButton button = new CommandButton();
// JSF requires an unique id for command components.
button.setId("btn-" + commandIndex++);
button.setTitle(command.getDescription());
String icon = null;
String mode = command.getMode(context);
if (mode == null) {
icon = iconMap.get(command.getName());
} else {
icon = iconMap.get(command.getName() + "-" + mode);
}
button.setIcon(icon);
MethodExpression expression = expressionFactory
.createMethodExpression(facesContext.getELContext(),
"#{pivotGridHandler.executeCommand}",
Void.class, new Class<?>[0]);
button.setActionExpression(expression);
button.setUpdate(":grid-form,:editor-form:mdx-editor,:editor-form:editor-toolbar,:source-tree-form,:target-tree-form");
UIParameter commandParam = new UIParameter();
commandParam.setName("command");
commandParam.setValue(command.getName());
button.getChildren().add(commandParam);
UIParameter axisParam = new UIParameter();
axisParam.setName("axis");
axisParam.setValue(parameters.getAxisOrdinal());
button.getChildren().add(axisParam);
UIParameter positionParam = new UIParameter();
positionParam.setName("position");
positionParam.setValue(parameters.getPositionOrdinal());
button.getChildren().add(positionParam);
UIParameter memberParam = new UIParameter();
memberParam.setName("member");
memberParam.setValue(parameters.getMemberOrdinal());
button.getChildren().add(memberParam);
UIParameter hierarchyParam = new UIParameter();
hierarchyParam.setName("hierarchy");
hierarchyParam.setValue(parameters.getHierarchyOrdinal());
button.getChildren().add(hierarchyParam);
UIParameter cellParam = new UIParameter();
hierarchyParam.setName("cell");
hierarchyParam.setValue(parameters.getCellOrdinal());
button.getChildren().add(cellParam);
column.getChildren().add(button);
}
}
}
| public void startCell(RenderContext context, List<CellCommand<?>> commands) {
this.column = new Column();
String id = "col-" + column.hashCode();
column.setId(id);
column.setColspan(context.getColSpan());
column.setRowspan(context.getRowSpan());
String styleClass;
switch (context.getCellType()) {
case Header:
case Title:
case None:
if (context.getAxis() == Axis.COLUMNS) {
styleClass = "col-hdr-cell";
} else {
if (context.getCellType() == CellType.Header) {
styleClass = "row-hdr-cell ui-widget-header";
} else {
styleClass = "ui-widget-header";
}
}
if (!getShowParentMembers() && context.getMember() != null) {
int padding = context.getMember().getDepth() * 10;
column.setStyle("padding-left: " + padding + "px");
}
break;
case Aggregation:
if (context.getAxis() == Axis.ROWS) {
styleClass = "ui-widget-header ";
} else {
styleClass = "";
}
styleClass += "agg-title";
if (!getShowParentMembers() && context.getMember() != null) {
int padding = context.getMember().getDepth() * 10;
column.setStyle("padding-left: " + padding + "px");
}
break;
case Value:
if (context.getAggregator() == null) {
// PrimeFaces' Row class doesn't have the styleClass property.
if (context.getRowIndex() % 2 == 0) {
styleClass = "value-cell cell-even";
} else {
styleClass = "value-cell cell-odd";
}
} else {
styleClass = "ui-widget-header agg-cell";
if (context.getAxis() == Axis.COLUMNS) {
styleClass += " col-agg-cell";
} else if (context.getAxis() == Axis.ROWS) {
styleClass += " row-agg-cell";
}
}
break;
default:
styleClass = null;
}
column.setStyleClass(styleClass);
if (expressionFactory != null) {
for (CellCommand<?> command : commands) {
CellParameters parameters = command.createParameters(context);
CommandButton button = new CommandButton();
// JSF requires an unique id for command components.
button.setId("btn-" + commandIndex++);
button.setTitle(command.getDescription());
String icon = null;
String mode = command.getMode(context);
if (mode == null) {
icon = iconMap.get(command.getName());
} else {
icon = iconMap.get(command.getName() + "-" + mode);
}
button.setIcon(icon);
MethodExpression expression = expressionFactory
.createMethodExpression(facesContext.getELContext(),
"#{pivotGridHandler.executeCommand}",
Void.class, new Class<?>[0]);
button.setActionExpression(expression);
button.setUpdate(":grid-form,:editor-form:mdx-editor,:editor-form:editor-toolbar,:source-tree-form,:target-tree-form");
UIParameter commandParam = new UIParameter();
commandParam.setName("command");
commandParam.setValue(command.getName());
button.getChildren().add(commandParam);
UIParameter axisParam = new UIParameter();
axisParam.setName("axis");
axisParam.setValue(parameters.getAxisOrdinal());
button.getChildren().add(axisParam);
UIParameter positionParam = new UIParameter();
positionParam.setName("position");
positionParam.setValue(parameters.getPositionOrdinal());
button.getChildren().add(positionParam);
UIParameter memberParam = new UIParameter();
memberParam.setName("member");
memberParam.setValue(parameters.getMemberOrdinal());
button.getChildren().add(memberParam);
UIParameter hierarchyParam = new UIParameter();
hierarchyParam.setName("hierarchy");
hierarchyParam.setValue(parameters.getHierarchyOrdinal());
button.getChildren().add(hierarchyParam);
UIParameter cellParam = new UIParameter();
hierarchyParam.setName("cell");
hierarchyParam.setValue(parameters.getCellOrdinal());
button.getChildren().add(cellParam);
column.getChildren().add(button);
}
}
}
|
diff --git a/core/src/org/tangram/view/velocity/IncludeDirective.java b/core/src/org/tangram/view/velocity/IncludeDirective.java
index c5ca115b..da064085 100644
--- a/core/src/org/tangram/view/velocity/IncludeDirective.java
+++ b/core/src/org/tangram/view/velocity/IncludeDirective.java
@@ -1,89 +1,86 @@
/**
*
* Copyright 2011 Martin Goellnitz
*
* 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 org.tangram.view.velocity;
import java.io.IOException;
import java.io.Writer;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.velocity.context.InternalContextAdapter;
import org.apache.velocity.runtime.RuntimeServices;
import org.apache.velocity.runtime.directive.Directive;
import org.apache.velocity.runtime.directive.DirectiveConstants;
import org.apache.velocity.runtime.parser.node.Node;
import org.tangram.view.Utils;
import org.tangram.view.jsp.IncludeTag;
public class IncludeDirective extends Directive {
// private static final Log log = LogFactory.getLog(IncludeDirective.class);
@Override
public String getName() {
return "include";
} // getName();
@Override
public int getType() {
return DirectiveConstants.LINE;
} // getType()
@Override
public void init(RuntimeServices rs, InternalContextAdapter context, Node node) {
super.init(rs, context, node);
context.put("null", null);
} // init()
@Override
public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException {
HttpServletRequest request = (HttpServletRequest)context.get("request");
HttpServletResponse response = (HttpServletResponse)context.get("response");
/* getting direct parameters */
Object bean = node.jjtGetChild(0).value(context);
String view = null;
if (node.jjtGetNumChildren()>1) {
view = (String)node.jjtGetChild(1).value(context);
} // if
// copy model from original context
Map<String, Object> model = Utils.getModelAndViewFactory(request).createModel(bean, request, response);
- // Map<String, Object> model = new HashMap<String, Object>();
Object[] keys = context.getKeys();
for (Object key : keys) {
String k = ""+key;
if ( !model.containsKey(k)) {
model.put(k, context.get(k));
} // if
} // for
model.remove("springMacroRequestContext");
- // model.remove(Constants.THIS);
- // model.put(Constants.THIS, bean);
IncludeTag.render(writer, model, view);
return false;
} // render()
} // IncludeDirective
| false | true | public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException {
HttpServletRequest request = (HttpServletRequest)context.get("request");
HttpServletResponse response = (HttpServletResponse)context.get("response");
/* getting direct parameters */
Object bean = node.jjtGetChild(0).value(context);
String view = null;
if (node.jjtGetNumChildren()>1) {
view = (String)node.jjtGetChild(1).value(context);
} // if
// copy model from original context
Map<String, Object> model = Utils.getModelAndViewFactory(request).createModel(bean, request, response);
// Map<String, Object> model = new HashMap<String, Object>();
Object[] keys = context.getKeys();
for (Object key : keys) {
String k = ""+key;
if ( !model.containsKey(k)) {
model.put(k, context.get(k));
} // if
} // for
model.remove("springMacroRequestContext");
// model.remove(Constants.THIS);
// model.put(Constants.THIS, bean);
IncludeTag.render(writer, model, view);
return false;
} // render()
| public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException {
HttpServletRequest request = (HttpServletRequest)context.get("request");
HttpServletResponse response = (HttpServletResponse)context.get("response");
/* getting direct parameters */
Object bean = node.jjtGetChild(0).value(context);
String view = null;
if (node.jjtGetNumChildren()>1) {
view = (String)node.jjtGetChild(1).value(context);
} // if
// copy model from original context
Map<String, Object> model = Utils.getModelAndViewFactory(request).createModel(bean, request, response);
Object[] keys = context.getKeys();
for (Object key : keys) {
String k = ""+key;
if ( !model.containsKey(k)) {
model.put(k, context.get(k));
} // if
} // for
model.remove("springMacroRequestContext");
IncludeTag.render(writer, model, view);
return false;
} // render()
|
diff --git a/src/minecraft/com/github/AbrarSyed/SecretRooms/SecretKey.java b/src/minecraft/com/github/AbrarSyed/SecretRooms/SecretKey.java
index d170c71..a8b99bf 100644
--- a/src/minecraft/com/github/AbrarSyed/SecretRooms/SecretKey.java
+++ b/src/minecraft/com/github/AbrarSyed/SecretRooms/SecretKey.java
@@ -1,83 +1,83 @@
package com.github.AbrarSyed.SecretRooms;
import java.util.EnumSet;
import org.lwjgl.input.Keyboard;
import com.github.AbrarSyed.SecretRooms.SecretRooms;
import net.minecraft.src.KeyBinding;
import net.minecraft.src.ModLoader;
import net.minecraft.src.Packet250CustomPayload;
import cpw.mods.fml.client.FMLClientHandler;
import cpw.mods.fml.client.registry.KeyBindingRegistry.KeyHandler;
import cpw.mods.fml.common.Side;
import cpw.mods.fml.common.TickType;
import cpw.mods.fml.common.asm.SideOnly;
@SideOnly(value=Side.CLIENT)
public class SecretKey extends KeyHandler {
public SecretKey(KeyBinding keyBinding, boolean repeating)
{
super(new KeyBinding[] {keyBinding}, new boolean[] {repeating});
}
@Override
public EnumSet<TickType> ticks()
{
return EnumSet.of(TickType.WORLDLOAD);
}
@Override
public String getLabel()
{
return null;
}
@Override
public void keyDown(EnumSet<TickType> types, KeyBinding kb, boolean tickEnd, boolean isRepeat)
{
// do nothing.
}
@Override
public void keyUp(EnumSet<TickType> types, KeyBinding kb, boolean tickEnd)
{
/*
// check if its in SMP
if (ModLoader.getMinecraftInstance().theWorld != null && ModLoader.getMinecraftInstance().theWorld.isRemote)
{
// create packet AND set channel
Packet250CustomPayload packet = new Packet250CustomPayload();
packet.channel = "SRM-KeyEvents";
// set byte[] data
packet.data = SecretRooms.intToByteArray(Keyboard.KEY_BACKSLASH);
// set length
packet.length = packet.data.length;
// send packet.
ModLoader.clientSendPacket(packet);
}
*/
SecretRooms.OneWayFaceTowards = !SecretRooms.OneWayFaceTowards;
if (!ModLoader.getMinecraftInstance().theWorld.isRemote)
{
if (SecretRooms.OneWayFaceTowards)
chat(PacketHandlerClient.getColorThing()+"e-- !!! OneWayBlock facing set to Towards !!! --");
else
- chat(PacketHandlerClient.getColorThing()+"�-- !!! OneWayBlock facing set to Away !!! --");
+ chat(PacketHandlerClient.getColorThing()+"e-- !!! OneWayBlock facing set to Away !!! --");
}
}
@SideOnly( value = Side.CLIENT)
public static void chat(String s)
{
FMLClientHandler.instance().getClient().thePlayer.addChatMessage(s);
}
}
| true | true | public void keyUp(EnumSet<TickType> types, KeyBinding kb, boolean tickEnd)
{
/*
// check if its in SMP
if (ModLoader.getMinecraftInstance().theWorld != null && ModLoader.getMinecraftInstance().theWorld.isRemote)
{
// create packet AND set channel
Packet250CustomPayload packet = new Packet250CustomPayload();
packet.channel = "SRM-KeyEvents";
// set byte[] data
packet.data = SecretRooms.intToByteArray(Keyboard.KEY_BACKSLASH);
// set length
packet.length = packet.data.length;
// send packet.
ModLoader.clientSendPacket(packet);
}
*/
SecretRooms.OneWayFaceTowards = !SecretRooms.OneWayFaceTowards;
if (!ModLoader.getMinecraftInstance().theWorld.isRemote)
{
if (SecretRooms.OneWayFaceTowards)
chat(PacketHandlerClient.getColorThing()+"e-- !!! OneWayBlock facing set to Towards !!! --");
else
chat(PacketHandlerClient.getColorThing()+"�-- !!! OneWayBlock facing set to Away !!! --");
}
}
| public void keyUp(EnumSet<TickType> types, KeyBinding kb, boolean tickEnd)
{
/*
// check if its in SMP
if (ModLoader.getMinecraftInstance().theWorld != null && ModLoader.getMinecraftInstance().theWorld.isRemote)
{
// create packet AND set channel
Packet250CustomPayload packet = new Packet250CustomPayload();
packet.channel = "SRM-KeyEvents";
// set byte[] data
packet.data = SecretRooms.intToByteArray(Keyboard.KEY_BACKSLASH);
// set length
packet.length = packet.data.length;
// send packet.
ModLoader.clientSendPacket(packet);
}
*/
SecretRooms.OneWayFaceTowards = !SecretRooms.OneWayFaceTowards;
if (!ModLoader.getMinecraftInstance().theWorld.isRemote)
{
if (SecretRooms.OneWayFaceTowards)
chat(PacketHandlerClient.getColorThing()+"e-- !!! OneWayBlock facing set to Towards !!! --");
else
chat(PacketHandlerClient.getColorThing()+"e-- !!! OneWayBlock facing set to Away !!! --");
}
}
|
diff --git a/modules/org.restlet.ext.odata/src/org/restlet/ext/odata/internal/edm/MetadataReader.java b/modules/org.restlet.ext.odata/src/org/restlet/ext/odata/internal/edm/MetadataReader.java
index 783d8c8dd..e65c47de9 100644
--- a/modules/org.restlet.ext.odata/src/org/restlet/ext/odata/internal/edm/MetadataReader.java
+++ b/modules/org.restlet.ext.odata/src/org/restlet/ext/odata/internal/edm/MetadataReader.java
@@ -1,726 +1,732 @@
/**
* Copyright 2005-2013 Restlet S.A.S.
*
* The contents of this file are subject to the terms of one of the following
* open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL
* 1.0 (the "Licenses"). You can select the license that you prefer but you may
* not use this file except in compliance with one of these Licenses.
*
* You can obtain a copy of the Apache 2.0 license at
* http://www.opensource.org/licenses/apache-2.0
*
* You can obtain a copy of the LGPL 3.0 license at
* http://www.opensource.org/licenses/lgpl-3.0
*
* You can obtain a copy of the LGPL 2.1 license at
* http://www.opensource.org/licenses/lgpl-2.1
*
* You can obtain a copy of the CDDL 1.0 license at
* http://www.opensource.org/licenses/cddl1
*
* You can obtain a copy of the EPL 1.0 license at
* http://www.opensource.org/licenses/eclipse-1.0
*
* See the Licenses for the specific language governing permissions and
* limitations under the Licenses.
*
* Alternatively, you can obtain a royalty free commercial license with less
* limitations, transferable or non-transferable, directly at
* http://www.restlet.com/products/restlet-framework
*
* Restlet is a registered trademark of Restlet S.A.S.
*/
package org.restlet.ext.odata.internal.edm;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.restlet.data.MediaType;
import org.restlet.data.Method;
import org.restlet.ext.odata.Service;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
* Used to parse a metadata descriptor of a given OData service and generate the
* associated object's tree.
*
* @author Thierry Boileau
*/
public class MetadataReader extends DefaultHandler {
/** The list of defined states of this parser. */
private enum State {
ASSOCIATION, ASSOCIATION_END, ASSOCIATION_SET, ASSOCIATION_SET_END, COMPLEX_TYPE, COMPLEX_TYPE_PROPERTY, DOCUMENTATION, ENTITY_CONTAINER, ENTITY_SET, ENTITY_TYPE, ENTITY_TYPE_KEY, ENTITY_TYPE_PROPERTY, FUNCTION, FUNCTION_IMPORT, NAVIGATION_PROPERTY, NONE, ON_DELETE, PARAMETER, REFERENTIAL_CONSTRAINT, SCHEMA, USING
}
/** List of possible values for the blob reference member. */
private final String[] blobEditRefValues = { "blobEditReference",
"blobEditReferenceValue" };
/** List of possible values for the blob reference member. */
private final String[] blobRefValues = { "blobReference",
"blobReferenceValue" };
/** The current association. */
private Association currentAssociation;
/** The current association set. */
private AssociationSet currentAssociationSet;
/** The current complex type. */
private ComplexType currentComplexType;
/** The current entity container. */
private EntityContainer currentEntityContainer;
/** The current entity type. */
private EntityType currentEntityType;
/** The current functionn import. */
private FunctionImport currentFunctionImport;
/** The metadata objet to update. */
private Metadata currentMetadata;
/** The current schema. */
private Schema currentSchema;
/** The registered collection of associations. */
private Map<String, NamedObject> registeredAssociations;
/** The registered collection of complex types. */
private Map<String, NamedObject> registeredComplexTypes;
/** The registered collection of entity containers. */
private Map<String, EntityContainer> registeredContainers;
/** The registered collection of entity sets. */
private Map<String, NamedObject> registeredEntitySets;
/** The registered collection of entity types. */
private Map<String, NamedObject> registeredEntityTypes;
/** The registered collection of namespaces. */
private List<Namespace> registeredNamespaces;
/** The current heap of states. */
private List<State> states;
/**
* Constructor.
*
* @param feed
* The feed object to update during the parsing.
*/
public MetadataReader(Metadata metadata) {
this.states = new ArrayList<State>();
pushState(State.NONE);
this.currentMetadata = metadata;
}
/**
* Pick up the first method name among a given list of proposed names.
* Returns null if the proposed values are already in the given entity type.
*
* @param type
* The entity type to check.
* @param values
* The list of proposed values.
* @return A method name.
*/
private String chooseAttributeName(EntityType type, String[] values) {
String result = null;
int index = 0;
// Check that one of the possible names is not already set.
for (int i = 0; i < type.getProperties().size()
&& (index < values.length); i++) {
Property property = type.getProperties().get(i);
if (values[index].equals(property.getName())) {
index++;
}
}
for (int i = 0; i < type.getAssociations().size()
&& (index < values.length); i++) {
NavigationProperty property = type.getAssociations().get(i);
if (values[index].equals(property.getName())) {
index++;
}
}
if (index != values.length) {
result = values[index];
}
return result;
}
/**
* Explores the given attributes in order to get a declared property
* mapping.
*
* @param type
* The type of the mapped property.
* @param property
* The property that declares the mapping (is null if the mapping
* is declared on the entity type tag).
* @param metadata
* The metadata instance to update.
* @param attributes
* The XML attributes to parse.
*/
private void discoverMapping(EntityType type, Property property,
Metadata metadata, Attributes attributes) {
String contentKind = null;
String nsPrefix = null;
String nsUri = null;
String propertyPath = null;
String valuePath = null;
boolean keepInContent = true;
contentKind = attributes.getValue(
Service.WCF_DATASERVICES_METADATA_NAMESPACE, "FC_ContentKind");
if (contentKind == null) {
contentKind = "text";
}
nsPrefix = attributes.getValue(
Service.WCF_DATASERVICES_METADATA_NAMESPACE, "FC_NsPrefix");
nsUri = attributes.getValue(
Service.WCF_DATASERVICES_METADATA_NAMESPACE, "FC_NsUri");
String str = attributes
.getValue(Service.WCF_DATASERVICES_METADATA_NAMESPACE,
"FC_KeepInContent");
if (str != null) {
keepInContent = Boolean.parseBoolean(str);
}
if (property == null) {
// mapping declared on the entity type, the "FC_SourcePath"
// attribute is mandatory.
propertyPath = attributes.getValue(
Service.WCF_DATASERVICES_METADATA_NAMESPACE,
"FC_SourcePath");
} else {
propertyPath = property.getName();
}
valuePath = attributes.getValue(
Service.WCF_DATASERVICES_METADATA_NAMESPACE, "FC_TargetPath");
if (propertyPath != null && valuePath != null && !keepInContent) {
// The mapping is really defined between a property and an XML
// element, and the value is only available in a customized part of
// the feed.
if ((nsUri == null && nsPrefix == null)
|| (nsUri != null && nsPrefix != null)) {
// The mapping is correctly declared (either in an ATOM or a
// customized XML element).
metadata.getMappings().add(
new Mapping(type, nsPrefix, nsUri, propertyPath,
valuePath, contentKind));
}
}
}
@Override
public void endDocument() throws SAXException {
// Update references.
for (Schema schema : currentMetadata.getSchemas()) {
// - associations.ends.type
for (Association association : schema.getAssociations()) {
// association type
for (AssociationEnd end : association.getEnds()) {
end.setType((EntityType) resolve(end.getType(),
registeredEntityTypes, schema));
}
}
for (EntityType entityType : schema.getEntityTypes()) {
// entityType.key
if (entityType.getKeys() != null) {
List<Property> props = entityType.getKeys();
entityType.setKeys(new ArrayList<Property>());
for (Property prop : props) {
for (Property property : entityType.getProperties()) {
if (property.equals(prop)) {
entityType.getKeys().add(property);
break;
}
}
}
}
// entityType.associations
for (NavigationProperty navigationProperty : entityType
.getAssociations()) {
navigationProperty.setRelationship((Association) resolve(
navigationProperty.getRelationship(),
registeredAssociations, schema));
if (navigationProperty.getRelationship() != null) {
// association's roles.
for (AssociationEnd end : navigationProperty
.getRelationship().getEnds()) {
if (end.getRole().equals(
navigationProperty.getFromRole().getRole())) {
navigationProperty.setFromRole(end);
} else if (end.getRole().equals(
navigationProperty.getToRole().getRole())) {
navigationProperty.setToRole(end);
}
}
} else {
navigationProperty.setFromRole(null);
navigationProperty.setToRole(null);
}
}
// entityType.baseType
entityType.setBaseType((EntityType) resolve(entityType
.getBaseType(), registeredEntityTypes, schema));
}
for (ComplexType complexType : schema.getComplexTypes()) {
// complexType.baseType
complexType.setBaseType((ComplexType) resolve(complexType
.getBaseType(), registeredComplexTypes, schema));
}
}
for (EntityContainer container : currentMetadata.getContainers()) {
// - entityContainer.extended
if (container.getExtended() != null) {
container.setExtended(registeredContainers.get(container
.getExtended().getName()));
}
for (AssociationSet associationSet : container.getAssociations()) {
// - associationSet.association
associationSet.setAssociation((Association) resolve(
associationSet.getAssociation(),
registeredAssociations, container.getSchema()));
// - associationSet.ends.entitySet
for (AssociationSetEnd end : associationSet.getEnds()) {
for (EntitySet entitySet : container.getEntities()) {
if (entitySet.equals(end.getType())) {
end.setType(entitySet);
break;
}
}
}
}
// - entityContainer.entitySet.entityType
for (EntitySet entitySet : container.getEntities()) {
entitySet.setType((EntityType) resolve(entitySet.getType(),
registeredEntityTypes, container.getSchema()));
}
// - entityContainer.functionImport.entitySet
for (FunctionImport functionImport : container.getFunctionImports()) {
functionImport.setEntitySet((EntitySet) resolve(functionImport
.getEntitySet(), registeredEntitySets, container
.getSchema()));
}
}
for (Schema schema : currentMetadata.getSchemas()) {
for (EntityType entityType : schema.getEntityTypes()) {
// entityType.complexTypes
for (ComplexProperty property : entityType
.getComplexProperties()) {
ComplexType type = (ComplexType) resolve(property
.getComplexType(), registeredComplexTypes, schema);
if (type != null) {
property.setComplexType(type);
}
}
}
for (ComplexType complexType : schema.getComplexTypes()) {
// entityType.complexTypes
for (ComplexProperty property : complexType
.getComplexProperties()) {
ComplexType type = (ComplexType) resolve(property
.getComplexType(), registeredComplexTypes, schema);
if (type != null) {
property.setComplexType(type);
}
}
}
}
}
@Override
public void endElement(String uri, String localName, String name)
throws SAXException {
if ("schema".equalsIgnoreCase(localName)) {
popState();
currentSchema = null;
} else if ("using".equalsIgnoreCase(localName)) {
popState();
} else if ("documentation".equalsIgnoreCase(localName)) {
popState();
} else if ("entityType".equalsIgnoreCase(localName)) {
if (currentEntityType.isBlob()) {
String memberName = chooseAttributeName(currentEntityType,
blobRefValues);
if (memberName == null) {
// Should not happen
currentEntityType.setBlob(false);
} else {
Property property = new Property(memberName);
currentEntityType.setBlobValueRefProperty(property);
}
// Sets the name of the property of the generated class that
// contains the reference of resource that is able to update the
// blob value.
memberName = chooseAttributeName(currentEntityType,
blobEditRefValues);
if (memberName == null) {
// Should not happen
currentEntityType.setBlob(false);
} else {
Property property = new Property(memberName);
currentEntityType.setBlobValueEditRefProperty(property);
}
}
popState();
currentEntityType = null;
} else if ("key".equalsIgnoreCase(localName)) {
popState();
} else if ("property".equalsIgnoreCase(localName)) {
popState();
} else if ("navigationProperty".equalsIgnoreCase(localName)) {
popState();
} else if ("complexType".equalsIgnoreCase(localName)) {
popState();
} else if ("association".equalsIgnoreCase(localName)) {
popState();
currentAssociation = null;
} else if ("end".equalsIgnoreCase(localName)) {
popState();
} else if ("onDelete".equalsIgnoreCase(localName)) {
popState();
} else if ("referentialConstraint".equalsIgnoreCase(localName)) {
popState();
} else if ("functionImport".equalsIgnoreCase(localName)) {
currentFunctionImport = null;
popState();
} else if ("function".equalsIgnoreCase(localName)) {
popState();
} else if ("entityContainer".equalsIgnoreCase(localName)) {
popState();
currentEntityContainer = null;
} else if ("entitySet".equalsIgnoreCase(localName)) {
popState();
} else if ("associationSet".equalsIgnoreCase(localName)) {
popState();
currentAssociationSet = null;
} else if ("parameter".equalsIgnoreCase(localName)) {
popState();
}
}
/**
* Returns the current state when processing the document.
*
* @return the current state when processing the document.
*/
private State getState() {
final State result = this.states.get(0);
return result;
}
/**
* Drops the current state from the stack and returns it. This state becomes
* the former current state.
*
* @return the former current state.
*/
private State popState() {
return this.states.remove(0);
}
/**
* Adds the given state.
*
* @param state
* The given state.
*/
private void pushState(State state) {
this.states.add(0, state);
}
/**
* Finds a namedObject inside a register.
*
* @param namedObject
* The namedObject to find.
* @param register
* The register.
* @param schema
* The schema of the named object.
* @return The namedObject if found inside the register, null otherwise.
*/
private NamedObject resolve(NamedObject namedObject,
Map<String, NamedObject> register, Schema currentSchema) {
NamedObject result = null;
if (namedObject != null && namedObject.getName() != null) {
String key = null;
int index = namedObject.getName().lastIndexOf(".");
if (index != -1) {
// Objects are named via the namespace alias or full name
String nsName = namedObject.getName().substring(0, index);
for (Namespace namespace : registeredNamespaces) {
if (nsName.equals(namespace.getAlias())
|| nsName.equals(namespace.getName())) {
key = namespace.getName()
+ namedObject.getName().substring(index);
break;
}
}
} else {
key = currentSchema.getNamespace().getName() + "."
+ namedObject.getName();
}
result = register.get(key);
}
return result;
}
@Override
public void startDocument() throws SAXException {
registeredComplexTypes = new HashMap<String, NamedObject>();
registeredEntityTypes = new HashMap<String, NamedObject>();
registeredAssociations = new HashMap<String, NamedObject>();
registeredEntitySets = new HashMap<String, NamedObject>();
registeredNamespaces = new ArrayList<Namespace>();
registeredContainers = new HashMap<String, EntityContainer>();
}
@Override
public void startElement(String uri, String localName, String name,
Attributes attrs) throws SAXException {
if ("schema".equalsIgnoreCase(localName)) {
pushState(State.SCHEMA);
currentSchema = new Schema();
this.currentMetadata.getSchemas().add(currentSchema);
Namespace namespace = new Namespace(attrs.getValue("Namespace"));
namespace.setAlias(attrs.getValue("Alias"));
this.currentSchema.setNamespace(namespace);
registeredNamespaces.add(namespace);
} else if ("using".equalsIgnoreCase(localName)) {
pushState(State.USING);
Namespace namespace = new Namespace(attrs.getValue("Namespace"));
namespace.setAlias(attrs.getValue("Alias"));
this.currentSchema.getReferencedNamespaces().add(namespace);
} else if ("documentation".equalsIgnoreCase(localName)) {
pushState(State.DOCUMENTATION);
} else if ("entityType".equalsIgnoreCase(localName)) {
pushState(State.ENTITY_TYPE);
currentEntityType = new EntityType(attrs.getValue("Name"));
currentEntityType.setSchema(this.currentSchema);
currentEntityType.setAbstractType(Boolean.parseBoolean(attrs
.getValue("Abstract")));
currentEntityType.setBlob(Boolean.parseBoolean(attrs.getValue(
Service.WCF_DATASERVICES_METADATA_NAMESPACE, "HasStream")));
String value = attrs.getValue("BaseType");
if (value != null) {
currentEntityType.setBaseType(new EntityType(value));
}
this.currentSchema.getEntityTypes().add(currentEntityType);
// Check the declaration of a property mapping.
discoverMapping(currentEntityType, null, currentMetadata, attrs);
// register the new type.
registeredEntityTypes.put(currentSchema.getNamespace().getName()
+ "." + currentEntityType.getName(), currentEntityType);
} else if ("key".equalsIgnoreCase(localName)) {
pushState(State.ENTITY_TYPE_KEY);
} else if ("propertyRef".equalsIgnoreCase(localName)) {
if (getState() == State.ENTITY_TYPE_KEY) {
if (currentEntityType.getKeys() == null) {
currentEntityType.setKeys(new ArrayList<Property>());
}
currentEntityType.getKeys().add(
new Property(attrs.getValue("Name")));
}
} else if ("property".equalsIgnoreCase(localName)) {
String type = attrs.getValue("Type");
Property property;
if (type.toLowerCase().startsWith("edm.")) {
property = new Property(attrs.getValue("Name"));
property.setType(new Type(attrs.getValue("Type")));
} else {
ComplexProperty p = new ComplexProperty(attrs.getValue("Name"));
p.setComplexType(new ComplexType(attrs.getValue("Type")));
property = p;
}
property.setDefaultValue(attrs.getValue("Default"));
- property.setNullable(Boolean.parseBoolean(attrs
- .getValue("Nullable")));
+ // If no value is specified, the nullable facet defaults to true
+ // http://www.odata.org/documentation/odata-v3-documentation/common-schema-definition-language-csdl/#531_The_edmNullable_Attribute
+ String nullable = attrs.getValue("Nullable");
+ if (nullable == null) {
+ property.setNullable(true);
+ } else {
+ property.setNullable(Boolean.parseBoolean(nullable));
+ }
// ConcurrencyMode
if ("fixed".equalsIgnoreCase(attrs.getValue("ConcurrencyMode"))) {
property.setConcurrent(true);
} else {
property.setConcurrent(false);
}
property.setGetterAccess(attrs.getValue("GetterAccess"));
property.setSetterAccess(attrs.getValue("SetterAccess"));
String str = attrs.getValue(
Service.WCF_DATASERVICES_METADATA_NAMESPACE, "MimeType");
if (str != null) {
property.setMediaType(MediaType.valueOf(str));
}
if (getState() == State.ENTITY_TYPE) {
pushState(State.ENTITY_TYPE_PROPERTY);
if (property instanceof ComplexProperty) {
this.currentEntityType.getComplexProperties().add(
(ComplexProperty) property);
} else {
this.currentEntityType.getProperties().add(property);
}
} else {
pushState(State.COMPLEX_TYPE_PROPERTY);
if (property instanceof ComplexProperty) {
this.currentComplexType.getComplexProperties().add(
(ComplexProperty) property);
} else {
this.currentComplexType.getProperties().add(property);
}
}
// Check the declaration of a property mapping.
discoverMapping(this.currentEntityType, property, currentMetadata,
attrs);
} else if ("navigationProperty".equalsIgnoreCase(localName)) {
pushState(State.NAVIGATION_PROPERTY);
NavigationProperty property = new NavigationProperty(attrs
.getValue("Name"));
property
.setFromRole(new AssociationEnd(attrs.getValue("FromRole")));
property.setRelationship(new Association(attrs
.getValue("Relationship")));
property.setToRole(new AssociationEnd(attrs.getValue("ToRole")));
currentEntityType.getAssociations().add(property);
} else if ("complexType".equalsIgnoreCase(localName)) {
pushState(State.COMPLEX_TYPE);
currentComplexType = new ComplexType(attrs.getValue("Name"));
currentComplexType.setSchema(this.currentSchema);
String value = attrs.getValue("BaseType");
if (value != null) {
currentComplexType.setBaseType(new ComplexType(value));
}
this.currentSchema.getComplexTypes().add(currentComplexType);
// register the new type.
registeredComplexTypes.put(currentSchema.getNamespace().getName()
+ "." + currentComplexType.getName(), currentComplexType);
} else if ("association".equalsIgnoreCase(localName)) {
pushState(State.ASSOCIATION);
currentAssociation = new Association(attrs.getValue("Name"));
currentSchema.getAssociations().add(currentAssociation);
registeredAssociations.put(currentSchema.getNamespace().getName()
+ "." + currentAssociation.getName(), currentAssociation);
} else if ("end".equalsIgnoreCase(localName)) {
if (getState() == State.ASSOCIATION) {
pushState(State.ASSOCIATION_END);
AssociationEnd end = new AssociationEnd(attrs.getValue("Role"));
end.setMultiplicity(attrs.getValue("Multiplicity"));
end.setType(new EntityType(attrs.getValue("Type")));
currentAssociation.getEnds().add(end);
} else {
pushState(State.ASSOCIATION_SET_END);
AssociationSetEnd end = new AssociationSetEnd(attrs
.getValue("Role"));
end.setType(new EntitySet(attrs.getValue("EntitySet")));
currentAssociationSet.getEnds().add(end);
}
} else if ("onDelete".equalsIgnoreCase(localName)) {
pushState(State.ON_DELETE);
} else if ("referentialConstraint".equalsIgnoreCase(localName)) {
pushState(State.REFERENTIAL_CONSTRAINT);
} else if ("functionImport".equalsIgnoreCase(localName)) {
currentFunctionImport = new FunctionImport(attrs.getValue("Name"));
currentFunctionImport.setReturnType(attrs.getValue("ReturnType"));
currentFunctionImport.setEntitySet(new EntitySet(attrs
.getValue("EntitySet")));
currentFunctionImport.setMethodAccess(attrs
.getValue("MethodAccess"));
currentFunctionImport.setMetadata(currentMetadata);
String str = attrs.getValue(
Service.WCF_DATASERVICES_METADATA_NAMESPACE, "HttpMethod");
if (str != null) {
currentFunctionImport.setMethod(Method.valueOf(str));
}
if (State.ENTITY_CONTAINER == getState()) {
currentEntityContainer.getFunctionImports().add(
currentFunctionImport);
}
pushState(State.FUNCTION_IMPORT);
} else if ("parameter".equalsIgnoreCase(localName)) {
if (State.FUNCTION_IMPORT == getState()) {
Parameter parameter = new Parameter(attrs.getValue("Name"));
parameter.setType(attrs.getValue("Type"));
parameter.setMode(attrs.getValue("Mode"));
String str = attrs.getValue("MaxLength");
if (str != null) {
parameter.setMaxLength(Integer.parseInt(str));
}
str = attrs.getValue("Precision");
if (str != null) {
parameter.setPrecision(Integer.parseInt(str));
}
str = attrs.getValue("Scale");
if (str != null) {
parameter.setScale(Integer.parseInt(str));
}
currentFunctionImport.getParameters().add(parameter);
}
pushState(State.PARAMETER);
} else if ("function".equalsIgnoreCase(localName)) {
pushState(State.FUNCTION);
} else if ("entityContainer".equalsIgnoreCase(localName)) {
pushState(State.ENTITY_CONTAINER);
currentEntityContainer = new EntityContainer(attrs.getValue("Name"));
currentEntityContainer.setDefaultEntityContainer(Boolean
.parseBoolean(attrs.getValue(
Service.WCF_DATASERVICES_METADATA_NAMESPACE,
"IsDefaultEntityContainer")));
String value = attrs.getValue("Extends");
if (value != null) {
currentEntityContainer.setExtended(new EntityContainer(value));
}
currentEntityContainer.setSchema(currentSchema);
currentMetadata.getContainers().add(currentEntityContainer);
registeredContainers.put(currentSchema.getNamespace().getName()
+ "." + currentEntityContainer.getName(),
currentEntityContainer);
} else if ("entitySet".equalsIgnoreCase(localName)) {
pushState(State.ENTITY_SET);
EntitySet entitySet = new EntitySet(attrs.getValue("Name"));
registeredEntitySets.put(currentSchema.getNamespace().getName()
+ "." + entitySet.getName(), entitySet);
entitySet.setType(new EntityType(attrs.getValue("EntityType")));
currentEntityContainer.getEntities().add(entitySet);
} else if ("associationSet".equalsIgnoreCase(localName)) {
pushState(State.ASSOCIATION_SET);
currentAssociationSet = new AssociationSet(attrs.getValue("Name"));
currentAssociationSet.setAssociation(new Association(attrs
.getValue("Association")));
currentEntityContainer.getAssociations().add(currentAssociationSet);
}
}
}
| true | true | public void startElement(String uri, String localName, String name,
Attributes attrs) throws SAXException {
if ("schema".equalsIgnoreCase(localName)) {
pushState(State.SCHEMA);
currentSchema = new Schema();
this.currentMetadata.getSchemas().add(currentSchema);
Namespace namespace = new Namespace(attrs.getValue("Namespace"));
namespace.setAlias(attrs.getValue("Alias"));
this.currentSchema.setNamespace(namespace);
registeredNamespaces.add(namespace);
} else if ("using".equalsIgnoreCase(localName)) {
pushState(State.USING);
Namespace namespace = new Namespace(attrs.getValue("Namespace"));
namespace.setAlias(attrs.getValue("Alias"));
this.currentSchema.getReferencedNamespaces().add(namespace);
} else if ("documentation".equalsIgnoreCase(localName)) {
pushState(State.DOCUMENTATION);
} else if ("entityType".equalsIgnoreCase(localName)) {
pushState(State.ENTITY_TYPE);
currentEntityType = new EntityType(attrs.getValue("Name"));
currentEntityType.setSchema(this.currentSchema);
currentEntityType.setAbstractType(Boolean.parseBoolean(attrs
.getValue("Abstract")));
currentEntityType.setBlob(Boolean.parseBoolean(attrs.getValue(
Service.WCF_DATASERVICES_METADATA_NAMESPACE, "HasStream")));
String value = attrs.getValue("BaseType");
if (value != null) {
currentEntityType.setBaseType(new EntityType(value));
}
this.currentSchema.getEntityTypes().add(currentEntityType);
// Check the declaration of a property mapping.
discoverMapping(currentEntityType, null, currentMetadata, attrs);
// register the new type.
registeredEntityTypes.put(currentSchema.getNamespace().getName()
+ "." + currentEntityType.getName(), currentEntityType);
} else if ("key".equalsIgnoreCase(localName)) {
pushState(State.ENTITY_TYPE_KEY);
} else if ("propertyRef".equalsIgnoreCase(localName)) {
if (getState() == State.ENTITY_TYPE_KEY) {
if (currentEntityType.getKeys() == null) {
currentEntityType.setKeys(new ArrayList<Property>());
}
currentEntityType.getKeys().add(
new Property(attrs.getValue("Name")));
}
} else if ("property".equalsIgnoreCase(localName)) {
String type = attrs.getValue("Type");
Property property;
if (type.toLowerCase().startsWith("edm.")) {
property = new Property(attrs.getValue("Name"));
property.setType(new Type(attrs.getValue("Type")));
} else {
ComplexProperty p = new ComplexProperty(attrs.getValue("Name"));
p.setComplexType(new ComplexType(attrs.getValue("Type")));
property = p;
}
property.setDefaultValue(attrs.getValue("Default"));
property.setNullable(Boolean.parseBoolean(attrs
.getValue("Nullable")));
// ConcurrencyMode
if ("fixed".equalsIgnoreCase(attrs.getValue("ConcurrencyMode"))) {
property.setConcurrent(true);
} else {
property.setConcurrent(false);
}
property.setGetterAccess(attrs.getValue("GetterAccess"));
property.setSetterAccess(attrs.getValue("SetterAccess"));
String str = attrs.getValue(
Service.WCF_DATASERVICES_METADATA_NAMESPACE, "MimeType");
if (str != null) {
property.setMediaType(MediaType.valueOf(str));
}
if (getState() == State.ENTITY_TYPE) {
pushState(State.ENTITY_TYPE_PROPERTY);
if (property instanceof ComplexProperty) {
this.currentEntityType.getComplexProperties().add(
(ComplexProperty) property);
} else {
this.currentEntityType.getProperties().add(property);
}
} else {
pushState(State.COMPLEX_TYPE_PROPERTY);
if (property instanceof ComplexProperty) {
this.currentComplexType.getComplexProperties().add(
(ComplexProperty) property);
} else {
this.currentComplexType.getProperties().add(property);
}
}
// Check the declaration of a property mapping.
discoverMapping(this.currentEntityType, property, currentMetadata,
attrs);
} else if ("navigationProperty".equalsIgnoreCase(localName)) {
pushState(State.NAVIGATION_PROPERTY);
NavigationProperty property = new NavigationProperty(attrs
.getValue("Name"));
property
.setFromRole(new AssociationEnd(attrs.getValue("FromRole")));
property.setRelationship(new Association(attrs
.getValue("Relationship")));
property.setToRole(new AssociationEnd(attrs.getValue("ToRole")));
currentEntityType.getAssociations().add(property);
} else if ("complexType".equalsIgnoreCase(localName)) {
pushState(State.COMPLEX_TYPE);
currentComplexType = new ComplexType(attrs.getValue("Name"));
currentComplexType.setSchema(this.currentSchema);
String value = attrs.getValue("BaseType");
if (value != null) {
currentComplexType.setBaseType(new ComplexType(value));
}
this.currentSchema.getComplexTypes().add(currentComplexType);
// register the new type.
registeredComplexTypes.put(currentSchema.getNamespace().getName()
+ "." + currentComplexType.getName(), currentComplexType);
} else if ("association".equalsIgnoreCase(localName)) {
pushState(State.ASSOCIATION);
currentAssociation = new Association(attrs.getValue("Name"));
currentSchema.getAssociations().add(currentAssociation);
registeredAssociations.put(currentSchema.getNamespace().getName()
+ "." + currentAssociation.getName(), currentAssociation);
} else if ("end".equalsIgnoreCase(localName)) {
if (getState() == State.ASSOCIATION) {
pushState(State.ASSOCIATION_END);
AssociationEnd end = new AssociationEnd(attrs.getValue("Role"));
end.setMultiplicity(attrs.getValue("Multiplicity"));
end.setType(new EntityType(attrs.getValue("Type")));
currentAssociation.getEnds().add(end);
} else {
pushState(State.ASSOCIATION_SET_END);
AssociationSetEnd end = new AssociationSetEnd(attrs
.getValue("Role"));
end.setType(new EntitySet(attrs.getValue("EntitySet")));
currentAssociationSet.getEnds().add(end);
}
} else if ("onDelete".equalsIgnoreCase(localName)) {
pushState(State.ON_DELETE);
} else if ("referentialConstraint".equalsIgnoreCase(localName)) {
pushState(State.REFERENTIAL_CONSTRAINT);
} else if ("functionImport".equalsIgnoreCase(localName)) {
currentFunctionImport = new FunctionImport(attrs.getValue("Name"));
currentFunctionImport.setReturnType(attrs.getValue("ReturnType"));
currentFunctionImport.setEntitySet(new EntitySet(attrs
.getValue("EntitySet")));
currentFunctionImport.setMethodAccess(attrs
.getValue("MethodAccess"));
currentFunctionImport.setMetadata(currentMetadata);
String str = attrs.getValue(
Service.WCF_DATASERVICES_METADATA_NAMESPACE, "HttpMethod");
if (str != null) {
currentFunctionImport.setMethod(Method.valueOf(str));
}
if (State.ENTITY_CONTAINER == getState()) {
currentEntityContainer.getFunctionImports().add(
currentFunctionImport);
}
pushState(State.FUNCTION_IMPORT);
} else if ("parameter".equalsIgnoreCase(localName)) {
if (State.FUNCTION_IMPORT == getState()) {
Parameter parameter = new Parameter(attrs.getValue("Name"));
parameter.setType(attrs.getValue("Type"));
parameter.setMode(attrs.getValue("Mode"));
String str = attrs.getValue("MaxLength");
if (str != null) {
parameter.setMaxLength(Integer.parseInt(str));
}
str = attrs.getValue("Precision");
if (str != null) {
parameter.setPrecision(Integer.parseInt(str));
}
str = attrs.getValue("Scale");
if (str != null) {
parameter.setScale(Integer.parseInt(str));
}
currentFunctionImport.getParameters().add(parameter);
}
pushState(State.PARAMETER);
} else if ("function".equalsIgnoreCase(localName)) {
pushState(State.FUNCTION);
} else if ("entityContainer".equalsIgnoreCase(localName)) {
pushState(State.ENTITY_CONTAINER);
currentEntityContainer = new EntityContainer(attrs.getValue("Name"));
currentEntityContainer.setDefaultEntityContainer(Boolean
.parseBoolean(attrs.getValue(
Service.WCF_DATASERVICES_METADATA_NAMESPACE,
"IsDefaultEntityContainer")));
String value = attrs.getValue("Extends");
if (value != null) {
currentEntityContainer.setExtended(new EntityContainer(value));
}
currentEntityContainer.setSchema(currentSchema);
currentMetadata.getContainers().add(currentEntityContainer);
registeredContainers.put(currentSchema.getNamespace().getName()
+ "." + currentEntityContainer.getName(),
currentEntityContainer);
} else if ("entitySet".equalsIgnoreCase(localName)) {
pushState(State.ENTITY_SET);
EntitySet entitySet = new EntitySet(attrs.getValue("Name"));
registeredEntitySets.put(currentSchema.getNamespace().getName()
+ "." + entitySet.getName(), entitySet);
entitySet.setType(new EntityType(attrs.getValue("EntityType")));
currentEntityContainer.getEntities().add(entitySet);
} else if ("associationSet".equalsIgnoreCase(localName)) {
pushState(State.ASSOCIATION_SET);
currentAssociationSet = new AssociationSet(attrs.getValue("Name"));
currentAssociationSet.setAssociation(new Association(attrs
.getValue("Association")));
currentEntityContainer.getAssociations().add(currentAssociationSet);
}
}
| public void startElement(String uri, String localName, String name,
Attributes attrs) throws SAXException {
if ("schema".equalsIgnoreCase(localName)) {
pushState(State.SCHEMA);
currentSchema = new Schema();
this.currentMetadata.getSchemas().add(currentSchema);
Namespace namespace = new Namespace(attrs.getValue("Namespace"));
namespace.setAlias(attrs.getValue("Alias"));
this.currentSchema.setNamespace(namespace);
registeredNamespaces.add(namespace);
} else if ("using".equalsIgnoreCase(localName)) {
pushState(State.USING);
Namespace namespace = new Namespace(attrs.getValue("Namespace"));
namespace.setAlias(attrs.getValue("Alias"));
this.currentSchema.getReferencedNamespaces().add(namespace);
} else if ("documentation".equalsIgnoreCase(localName)) {
pushState(State.DOCUMENTATION);
} else if ("entityType".equalsIgnoreCase(localName)) {
pushState(State.ENTITY_TYPE);
currentEntityType = new EntityType(attrs.getValue("Name"));
currentEntityType.setSchema(this.currentSchema);
currentEntityType.setAbstractType(Boolean.parseBoolean(attrs
.getValue("Abstract")));
currentEntityType.setBlob(Boolean.parseBoolean(attrs.getValue(
Service.WCF_DATASERVICES_METADATA_NAMESPACE, "HasStream")));
String value = attrs.getValue("BaseType");
if (value != null) {
currentEntityType.setBaseType(new EntityType(value));
}
this.currentSchema.getEntityTypes().add(currentEntityType);
// Check the declaration of a property mapping.
discoverMapping(currentEntityType, null, currentMetadata, attrs);
// register the new type.
registeredEntityTypes.put(currentSchema.getNamespace().getName()
+ "." + currentEntityType.getName(), currentEntityType);
} else if ("key".equalsIgnoreCase(localName)) {
pushState(State.ENTITY_TYPE_KEY);
} else if ("propertyRef".equalsIgnoreCase(localName)) {
if (getState() == State.ENTITY_TYPE_KEY) {
if (currentEntityType.getKeys() == null) {
currentEntityType.setKeys(new ArrayList<Property>());
}
currentEntityType.getKeys().add(
new Property(attrs.getValue("Name")));
}
} else if ("property".equalsIgnoreCase(localName)) {
String type = attrs.getValue("Type");
Property property;
if (type.toLowerCase().startsWith("edm.")) {
property = new Property(attrs.getValue("Name"));
property.setType(new Type(attrs.getValue("Type")));
} else {
ComplexProperty p = new ComplexProperty(attrs.getValue("Name"));
p.setComplexType(new ComplexType(attrs.getValue("Type")));
property = p;
}
property.setDefaultValue(attrs.getValue("Default"));
// If no value is specified, the nullable facet defaults to true
// http://www.odata.org/documentation/odata-v3-documentation/common-schema-definition-language-csdl/#531_The_edmNullable_Attribute
String nullable = attrs.getValue("Nullable");
if (nullable == null) {
property.setNullable(true);
} else {
property.setNullable(Boolean.parseBoolean(nullable));
}
// ConcurrencyMode
if ("fixed".equalsIgnoreCase(attrs.getValue("ConcurrencyMode"))) {
property.setConcurrent(true);
} else {
property.setConcurrent(false);
}
property.setGetterAccess(attrs.getValue("GetterAccess"));
property.setSetterAccess(attrs.getValue("SetterAccess"));
String str = attrs.getValue(
Service.WCF_DATASERVICES_METADATA_NAMESPACE, "MimeType");
if (str != null) {
property.setMediaType(MediaType.valueOf(str));
}
if (getState() == State.ENTITY_TYPE) {
pushState(State.ENTITY_TYPE_PROPERTY);
if (property instanceof ComplexProperty) {
this.currentEntityType.getComplexProperties().add(
(ComplexProperty) property);
} else {
this.currentEntityType.getProperties().add(property);
}
} else {
pushState(State.COMPLEX_TYPE_PROPERTY);
if (property instanceof ComplexProperty) {
this.currentComplexType.getComplexProperties().add(
(ComplexProperty) property);
} else {
this.currentComplexType.getProperties().add(property);
}
}
// Check the declaration of a property mapping.
discoverMapping(this.currentEntityType, property, currentMetadata,
attrs);
} else if ("navigationProperty".equalsIgnoreCase(localName)) {
pushState(State.NAVIGATION_PROPERTY);
NavigationProperty property = new NavigationProperty(attrs
.getValue("Name"));
property
.setFromRole(new AssociationEnd(attrs.getValue("FromRole")));
property.setRelationship(new Association(attrs
.getValue("Relationship")));
property.setToRole(new AssociationEnd(attrs.getValue("ToRole")));
currentEntityType.getAssociations().add(property);
} else if ("complexType".equalsIgnoreCase(localName)) {
pushState(State.COMPLEX_TYPE);
currentComplexType = new ComplexType(attrs.getValue("Name"));
currentComplexType.setSchema(this.currentSchema);
String value = attrs.getValue("BaseType");
if (value != null) {
currentComplexType.setBaseType(new ComplexType(value));
}
this.currentSchema.getComplexTypes().add(currentComplexType);
// register the new type.
registeredComplexTypes.put(currentSchema.getNamespace().getName()
+ "." + currentComplexType.getName(), currentComplexType);
} else if ("association".equalsIgnoreCase(localName)) {
pushState(State.ASSOCIATION);
currentAssociation = new Association(attrs.getValue("Name"));
currentSchema.getAssociations().add(currentAssociation);
registeredAssociations.put(currentSchema.getNamespace().getName()
+ "." + currentAssociation.getName(), currentAssociation);
} else if ("end".equalsIgnoreCase(localName)) {
if (getState() == State.ASSOCIATION) {
pushState(State.ASSOCIATION_END);
AssociationEnd end = new AssociationEnd(attrs.getValue("Role"));
end.setMultiplicity(attrs.getValue("Multiplicity"));
end.setType(new EntityType(attrs.getValue("Type")));
currentAssociation.getEnds().add(end);
} else {
pushState(State.ASSOCIATION_SET_END);
AssociationSetEnd end = new AssociationSetEnd(attrs
.getValue("Role"));
end.setType(new EntitySet(attrs.getValue("EntitySet")));
currentAssociationSet.getEnds().add(end);
}
} else if ("onDelete".equalsIgnoreCase(localName)) {
pushState(State.ON_DELETE);
} else if ("referentialConstraint".equalsIgnoreCase(localName)) {
pushState(State.REFERENTIAL_CONSTRAINT);
} else if ("functionImport".equalsIgnoreCase(localName)) {
currentFunctionImport = new FunctionImport(attrs.getValue("Name"));
currentFunctionImport.setReturnType(attrs.getValue("ReturnType"));
currentFunctionImport.setEntitySet(new EntitySet(attrs
.getValue("EntitySet")));
currentFunctionImport.setMethodAccess(attrs
.getValue("MethodAccess"));
currentFunctionImport.setMetadata(currentMetadata);
String str = attrs.getValue(
Service.WCF_DATASERVICES_METADATA_NAMESPACE, "HttpMethod");
if (str != null) {
currentFunctionImport.setMethod(Method.valueOf(str));
}
if (State.ENTITY_CONTAINER == getState()) {
currentEntityContainer.getFunctionImports().add(
currentFunctionImport);
}
pushState(State.FUNCTION_IMPORT);
} else if ("parameter".equalsIgnoreCase(localName)) {
if (State.FUNCTION_IMPORT == getState()) {
Parameter parameter = new Parameter(attrs.getValue("Name"));
parameter.setType(attrs.getValue("Type"));
parameter.setMode(attrs.getValue("Mode"));
String str = attrs.getValue("MaxLength");
if (str != null) {
parameter.setMaxLength(Integer.parseInt(str));
}
str = attrs.getValue("Precision");
if (str != null) {
parameter.setPrecision(Integer.parseInt(str));
}
str = attrs.getValue("Scale");
if (str != null) {
parameter.setScale(Integer.parseInt(str));
}
currentFunctionImport.getParameters().add(parameter);
}
pushState(State.PARAMETER);
} else if ("function".equalsIgnoreCase(localName)) {
pushState(State.FUNCTION);
} else if ("entityContainer".equalsIgnoreCase(localName)) {
pushState(State.ENTITY_CONTAINER);
currentEntityContainer = new EntityContainer(attrs.getValue("Name"));
currentEntityContainer.setDefaultEntityContainer(Boolean
.parseBoolean(attrs.getValue(
Service.WCF_DATASERVICES_METADATA_NAMESPACE,
"IsDefaultEntityContainer")));
String value = attrs.getValue("Extends");
if (value != null) {
currentEntityContainer.setExtended(new EntityContainer(value));
}
currentEntityContainer.setSchema(currentSchema);
currentMetadata.getContainers().add(currentEntityContainer);
registeredContainers.put(currentSchema.getNamespace().getName()
+ "." + currentEntityContainer.getName(),
currentEntityContainer);
} else if ("entitySet".equalsIgnoreCase(localName)) {
pushState(State.ENTITY_SET);
EntitySet entitySet = new EntitySet(attrs.getValue("Name"));
registeredEntitySets.put(currentSchema.getNamespace().getName()
+ "." + entitySet.getName(), entitySet);
entitySet.setType(new EntityType(attrs.getValue("EntityType")));
currentEntityContainer.getEntities().add(entitySet);
} else if ("associationSet".equalsIgnoreCase(localName)) {
pushState(State.ASSOCIATION_SET);
currentAssociationSet = new AssociationSet(attrs.getValue("Name"));
currentAssociationSet.setAssociation(new Association(attrs
.getValue("Association")));
currentEntityContainer.getAssociations().add(currentAssociationSet);
}
}
|
diff --git a/src/jp/tnasu/f1tvnews/controller/RssController.java b/src/jp/tnasu/f1tvnews/controller/RssController.java
index 5284bef..68bdb8e 100644
--- a/src/jp/tnasu/f1tvnews/controller/RssController.java
+++ b/src/jp/tnasu/f1tvnews/controller/RssController.java
@@ -1,259 +1,262 @@
package jp.tnasu.f1tvnews.controller;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map.Entry;
import java.util.TimeZone;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import jp.tnasu.f1tvnews.client.F1bsfujiClient;
import jp.tnasu.f1tvnews.client.google.calendar.GoogleCalendarClient;
import jp.tnasu.f1tvnews.client.google.oauth2.GoogleClient;
import jp.tnasu.f1tvnews.dao.HtmlDocumentDao;
import jp.tnasu.f1tvnews.dao.google.calendar.GoogleCalendarDtoMapDao;
import jp.tnasu.f1tvnews.handler.ErrorHandler;
import jp.tnasu.f1tvnews.handler.RssHandler;
import jp.tnasu.f1tvnews.model.HtmlContent;
import jp.tnasu.f1tvnews.model.HtmlDocument;
import jp.tnasu.f1tvnews.model.google.calendar.Event;
import jp.tnasu.f1tvnews.model.google.calendar.GoogleCalendarDto;
import jp.tnasu.f1tvnews.model.google.calendar.GoogleCalendarDtoMap;
import jp.tnasu.f1tvnews.model.google.oauth2.Google;
import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.util.StringUtil;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Text;
public class RssController extends Controller {
static final Logger LOGGER = Logger.getLogger(RssController.class.getName());
HtmlDocumentDao htmlDocumentDao = new HtmlDocumentDao();
F1bsfujiClient f1bsfujiClient = new F1bsfujiClient();
GoogleCalendarDtoMapDao googleCalendarDtoMapDao = new GoogleCalendarDtoMapDao();
GoogleClient googleClinet = new GoogleClient();
GoogleCalendarClient googleCalendarClient = new GoogleCalendarClient();
@Override
public Navigation run() throws Exception {
TimeZone.setDefault(TimeZone.getTimeZone("Asia/Tokyo"));
Key key = htmlDocumentDao.getKey();
HtmlDocument htmlDocument = htmlDocumentDao.get(key);
long lastModified = 0L;
long nextModify = 1L;
if (htmlDocument.getHtmlContentList().size() != 0) {
HtmlContent latest = htmlDocument.getHtmlContentList().get(0);
lastModified = latest.getLastModified();
nextModify = latest.getNextModify();
}
LOGGER.severe("" + new Date(lastModified));
LOGGER.severe("" + new Date(nextModify));
String force = request.getParameter("force");
if (!StringUtil.isEmpty(force)) {
lastModified = 0L;
}
if (!StringUtil.isEmpty(force) || (lastModified < nextModify && nextModify < new Date().getTime())) {
HtmlContent htmlContent = new HtmlContent();
fillHtml(lastModified, htmlContent);
LOGGER.severe(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS").format(new Date(htmlContent.getLastModified())));
if (lastModified != htmlContent.getLastModified()) {
fillData(htmlContent);
fillNextModify(htmlContent);
fillDocument(htmlDocument, htmlContent);
htmlDocument.getHtmlContentList().add(0, htmlContent);
htmlDocumentDao.put(htmlDocument);
registGoogleCalendar(htmlDocument);
}
}
RssHandler.writeRss(response, htmlDocument);
return null;
}
private HtmlContent fillHtml(long lastModified, HtmlContent htmlContent) throws MalformedURLException, ProtocolException, IOException {
HttpURLConnection con = null;
try {
con = f1bsfujiClient.getConnection(lastModified);
htmlContent.setLastModified(con.getLastModified());
if (con.getResponseCode() == 200) {
htmlContent.setHtml(new Text(f1bsfujiClient.getContent(con)));
}
return htmlContent;
} finally {
if (con != null) {
con.disconnect();
}
}
}
private HtmlContent fillData(HtmlContent htmlContent) {
String html = htmlContent.getHtml().getValue();
int beginIndex = html.indexOf("<div id=\"containerInner\" class=\"clearfix\">");
if (beginIndex != -1) {
html = html.substring(beginIndex);
}
int endIndex = html.indexOf("<div id=\"rightArea\">");
if (endIndex != -1) {
html = html.substring(0, endIndex);
}
// LOGGER.severe(html);
htmlContent.setData(new Text(html));
htmlContent.setTitle(getString(html, "<div class=\"title\">", "</div>") + getString(html, "<div class=\"subtitle\">", "</div>"));
htmlContent.setDescription(getString(html, "<div class=\"midokoroIn\">", "</div>").replaceAll("<.+?>", " "));
htmlContent.setShowtime(getString(html, "<div class=\"midokoroIn\"> <p>", "</p>").replaceAll("<.+?>", " "));
if (htmlContent.getShowtime().indexOf(regexQualify) == -1 || htmlContent.getShowtime().indexOf(regexRace) == -1) {
htmlContent.setShowtime(getString(html, "<div class=\"free\">", "</div>").replaceAll("<br />", " ").replaceAll("<p>", " ").replace("</p>", " "));
}
fillAnyTime(htmlContent, html);
return htmlContent;
}
static final String regexQualify = "【予選】";
static final String regexRace = "【決勝】";
static final String regex = "([0-9]?[0-9]月[0-9]?[0-9]日)\\([月火水木金土日]{1}\\)[ ]?([0-9]?[0-9]:[0-9][0-9])~([0-9]?[0-9]:[0-9]?[0-9])";
private HtmlContent fillAnyTime(HtmlContent htmlContent, String html) {
try {
fillAnyTime(htmlContent, html, regex, regexQualify);
fillAnyTime(htmlContent, html, regex, regexRace);
} catch (ParseException e) {
LOGGER.severe(e.getLocalizedMessage());
}
return htmlContent;
}
private void fillAnyTime(HtmlContent htmlContent, String html, String regex, String prefix) throws ParseException {
Pattern pattern = Pattern.compile("(" + prefix + regex + ")");
Matcher matcher = pattern.matcher(html);
if (matcher.find()) {
String date = matcher.group(2);
String startTime = matcher.group(3);
String endTime = matcher.group(4);
SimpleDateFormat sdf = new SimpleDateFormat("MM月dd日HH:mm");
Date s = sdf.parse(date + startTime);
Date e = sdf.parse(date + endTime);
Calendar nowCal = Calendar.getInstance();
Calendar startCal = Calendar.getInstance();
Calendar endCal = Calendar.getInstance();
nowCal.setTime(new Date());
startCal.setTime(s);
startCal.set(Calendar.YEAR, nowCal.get(Calendar.YEAR));
endCal.setTime(e);
endCal.set(Calendar.YEAR, nowCal.get(Calendar.YEAR));
LOGGER.severe(new Date(startCal.getTimeInMillis()).toString());
LOGGER.severe(new Date(endCal.getTimeInMillis()).toString());
if (regexQualify.equals(prefix)) {
htmlContent.setQualifyStartTime(startCal.getTime());
htmlContent.setQualifyEndTime(endCal.getTime());
} else if (regexRace.equals(prefix)) {
htmlContent.setRaceStartTime(startCal.getTime());
htmlContent.setRaceEndTime(endCal.getTime());
}
}
}
private HtmlContent fillNextModify(HtmlContent htmlContent) {
if (htmlContent.getRaceEndTime() == null) {
return htmlContent;
}
Calendar next = Calendar.getInstance();
next.setTime(htmlContent.getRaceEndTime());
next.set(Calendar.HOUR, 9);
next.set(Calendar.MINUTE, 0);
if (next.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
next.add(Calendar.DATE, 1);
}
LOGGER.severe(new Date(next.getTimeInMillis()).toString());
htmlContent.setNextModify(next.getTimeInMillis());
return htmlContent;
}
private HtmlDocument fillDocument(HtmlDocument htmlDocument, HtmlContent htmlContent) {
String html = htmlContent.getHtml().getValue();
String description = getString(html, "<meta name=\"description\" content=\"", "\" />");
String title = getString(html, "<title>", "</title>");
htmlDocument.setTitle(title);
htmlDocument.setLink(F1bsfujiClient.ENDPOINT);
htmlDocument.setDescription(description);
htmlDocument.setLanguage("ja-JP");
htmlDocument.setCopyright("http://www.bsfuji.tv/top/index/copyright.html");
htmlDocument.setPublishedDate(new Date(htmlContent.getLastModified()));
return htmlDocument;
}
private String getString(String html, String prefix, String suffix) {
int beginIndex = html.indexOf(prefix);
if (beginIndex != -1) {
html = html.substring(beginIndex + prefix.length());
}
int endIndex = html.indexOf(suffix);
if (endIndex != -1) {
html = html.substring(0, endIndex);
}
// LOGGER.severe(html);
return html;
}
private void registGoogleCalendar(HtmlDocument htmlDocument) {
if (googleClinet.isInitialize()) {
return;
}
try {
HtmlContent htmlContent = htmlDocument.getHtmlContentList().get(0);
Key key = googleCalendarDtoMapDao.getKey();
GoogleCalendarDtoMap googleCalendarDtoMap = googleCalendarDtoMapDao.get(key);
for (Entry<String, GoogleCalendarDto> entry : googleCalendarDtoMap.getGoogleCalendarMap().entrySet()) {
Google google = entry.getValue().getGoogle();
LOGGER.severe("" + google.getClientId());
LOGGER.severe("" + google.getAccessToken());
LOGGER.severe("" + google.getRefreshToken());
+ if (entry.getValue().getCalendarList() == null) {
+ continue;
+ }
Event eventQualify = googleCalendarClient.getEvent(htmlContent.getTitle(), htmlContent.getQualifyStartTime(), htmlContent.getQualifyEndTime());
Event eventRace = googleCalendarClient.getEvent(htmlContent.getTitle(), htmlContent.getRaceStartTime(), htmlContent.getRaceEndTime());
for (Event event : new Event[] { eventQualify, eventRace }) {
LOGGER.severe("" + event.getSummary());
LOGGER.severe("" + event.getStart().getModel().getDateTime());
entry.getValue().getGoogle().getRefreshToken();
String[] calendarIds = entry.getValue().getCalendarList();
for (String calendarId : calendarIds) {
LOGGER.severe(calendarId);
HttpURLConnection http = googleCalendarClient.getEventInsert(google, event, calendarId);
String content = googleCalendarClient.getContent(http);
LOGGER.severe(content);
if (http.getResponseCode() != 200) {
// FIXME no test
// jp.tnasu.f1tvnews.model.google.calendar.Error error = ErrorMeta.get().jsonToModel(content);
// System.out.println(error.getCode());
// System.out.println(error.getMessage());
// if (error.getErrors() != null) {
// ErrorDetail[] errors = ErrorDetailMeta.get().jsonToModels(error.getErrors());
// for (ErrorDetail e : errors) {
// System.out.println(e.getDomain());
// System.out.println(e.getReason());
// System.out.println(e.getMessage());
// System.out.println(e.getLocationType());
// System.out.println(e.getLocation());
// }
// }
}
}
}
}
} catch (Exception e) {
ErrorHandler.writeErrorLogger(e, LOGGER);
}
}
}
| true | true | private void registGoogleCalendar(HtmlDocument htmlDocument) {
if (googleClinet.isInitialize()) {
return;
}
try {
HtmlContent htmlContent = htmlDocument.getHtmlContentList().get(0);
Key key = googleCalendarDtoMapDao.getKey();
GoogleCalendarDtoMap googleCalendarDtoMap = googleCalendarDtoMapDao.get(key);
for (Entry<String, GoogleCalendarDto> entry : googleCalendarDtoMap.getGoogleCalendarMap().entrySet()) {
Google google = entry.getValue().getGoogle();
LOGGER.severe("" + google.getClientId());
LOGGER.severe("" + google.getAccessToken());
LOGGER.severe("" + google.getRefreshToken());
Event eventQualify = googleCalendarClient.getEvent(htmlContent.getTitle(), htmlContent.getQualifyStartTime(), htmlContent.getQualifyEndTime());
Event eventRace = googleCalendarClient.getEvent(htmlContent.getTitle(), htmlContent.getRaceStartTime(), htmlContent.getRaceEndTime());
for (Event event : new Event[] { eventQualify, eventRace }) {
LOGGER.severe("" + event.getSummary());
LOGGER.severe("" + event.getStart().getModel().getDateTime());
entry.getValue().getGoogle().getRefreshToken();
String[] calendarIds = entry.getValue().getCalendarList();
for (String calendarId : calendarIds) {
LOGGER.severe(calendarId);
HttpURLConnection http = googleCalendarClient.getEventInsert(google, event, calendarId);
String content = googleCalendarClient.getContent(http);
LOGGER.severe(content);
if (http.getResponseCode() != 200) {
// FIXME no test
// jp.tnasu.f1tvnews.model.google.calendar.Error error = ErrorMeta.get().jsonToModel(content);
// System.out.println(error.getCode());
// System.out.println(error.getMessage());
// if (error.getErrors() != null) {
// ErrorDetail[] errors = ErrorDetailMeta.get().jsonToModels(error.getErrors());
// for (ErrorDetail e : errors) {
// System.out.println(e.getDomain());
// System.out.println(e.getReason());
// System.out.println(e.getMessage());
// System.out.println(e.getLocationType());
// System.out.println(e.getLocation());
// }
// }
}
}
}
}
} catch (Exception e) {
ErrorHandler.writeErrorLogger(e, LOGGER);
}
}
| private void registGoogleCalendar(HtmlDocument htmlDocument) {
if (googleClinet.isInitialize()) {
return;
}
try {
HtmlContent htmlContent = htmlDocument.getHtmlContentList().get(0);
Key key = googleCalendarDtoMapDao.getKey();
GoogleCalendarDtoMap googleCalendarDtoMap = googleCalendarDtoMapDao.get(key);
for (Entry<String, GoogleCalendarDto> entry : googleCalendarDtoMap.getGoogleCalendarMap().entrySet()) {
Google google = entry.getValue().getGoogle();
LOGGER.severe("" + google.getClientId());
LOGGER.severe("" + google.getAccessToken());
LOGGER.severe("" + google.getRefreshToken());
if (entry.getValue().getCalendarList() == null) {
continue;
}
Event eventQualify = googleCalendarClient.getEvent(htmlContent.getTitle(), htmlContent.getQualifyStartTime(), htmlContent.getQualifyEndTime());
Event eventRace = googleCalendarClient.getEvent(htmlContent.getTitle(), htmlContent.getRaceStartTime(), htmlContent.getRaceEndTime());
for (Event event : new Event[] { eventQualify, eventRace }) {
LOGGER.severe("" + event.getSummary());
LOGGER.severe("" + event.getStart().getModel().getDateTime());
entry.getValue().getGoogle().getRefreshToken();
String[] calendarIds = entry.getValue().getCalendarList();
for (String calendarId : calendarIds) {
LOGGER.severe(calendarId);
HttpURLConnection http = googleCalendarClient.getEventInsert(google, event, calendarId);
String content = googleCalendarClient.getContent(http);
LOGGER.severe(content);
if (http.getResponseCode() != 200) {
// FIXME no test
// jp.tnasu.f1tvnews.model.google.calendar.Error error = ErrorMeta.get().jsonToModel(content);
// System.out.println(error.getCode());
// System.out.println(error.getMessage());
// if (error.getErrors() != null) {
// ErrorDetail[] errors = ErrorDetailMeta.get().jsonToModels(error.getErrors());
// for (ErrorDetail e : errors) {
// System.out.println(e.getDomain());
// System.out.println(e.getReason());
// System.out.println(e.getMessage());
// System.out.println(e.getLocationType());
// System.out.println(e.getLocation());
// }
// }
}
}
}
}
} catch (Exception e) {
ErrorHandler.writeErrorLogger(e, LOGGER);
}
}
|
diff --git a/src/org/usfirst/frc1923/AscentRobot.java b/src/org/usfirst/frc1923/AscentRobot.java
index cde7b36..e32e7c7 100644
--- a/src/org/usfirst/frc1923/AscentRobot.java
+++ b/src/org/usfirst/frc1923/AscentRobot.java
@@ -1,183 +1,187 @@
package org.usfirst.frc1923;
import org.usfirst.frc1923.event.DriveGearDownEvent;
import org.usfirst.frc1923.event.DriveGearUpEvent;
import org.usfirst.frc1923.event.RingLightActivateEvent;
import org.usfirst.frc1923.event.RingLightDeactivateEvent;
import org.usfirst.frc1923.event.ShooterActuatorEvent;
import org.usfirst.frc1923.event.ShooterGearDownEvent;
import org.usfirst.frc1923.event.ShooterGearUpEvent;
import org.usfirst.frc1923.event.ShooterStartEvent;
import org.usfirst.frc1923.event.ShooterStopEvent;
import org.usfirst.frc1923.utils.DefaultConfiguration;
import org.usfirst.frc1923.utils.XboxController;
import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.Relay;
/**
* The core <code>IterativeRobot</code> for the Ultimate Ascent robot.
*
* @author Aaron Weiss
* @version 2.1
* @since 2/9/13
*/
public class AscentRobot extends IterativeRobot {
private boolean[] justPressed = new boolean[14];
private boolean[] triggers = new boolean[2];
/**
* Initializes the robot.
*/
public void robotInit() {
// Components.networkTable.putBoolean("~S A V E~", true);
}
/**
* Initializes the robot for teleop.
*/
public void teleopInit() {
Components.driveGearbox.setGear(0);
Components.shooterGearbox.setGear(0);
}
/**
* Provides tele-operated functionality.
*/
public void teleopPeriodic() {
{ // Driving Scope
if (Components.preferences.getBoolean("experimental_drive", DefaultConfiguration.EXPERIMENTAL_DRIVE)) {
double forwardMagnitude = -Components.leftDriveStick.getCoalescedY();
double curvature = Components.rightDriveStick.getCoalescedX();
double attachment = Components.rightDriveStick.getCoalescedZ();
if (Math.abs(attachment) > 0.1 && Components.preferences.getBoolean("experimental_drive_attachment", DefaultConfiguration.EXPERIMENTAL_DRIVE_ATTACHMENT)) {
Components.driveSystem.drive(-attachment, attachment, false);
- } else if (curvature < 0.1) { // Turning left
+ } else if (curvature < 0.1 && -forwardMagnitude > 0) { // Turning left and going forward
Components.driveSystem.drive(-(forwardMagnitude + curvature), -forwardMagnitude, false);
- } else if (curvature > 0.1) { // Turning right
+ } else if (curvature > 0.1 && -forwardMagnitude > 0) { // Turning right and going forward
Components.driveSystem.drive(-forwardMagnitude, -(forwardMagnitude - curvature), false);
+ } else if (curvature < 0.1) {
+ Components.driveSystem.drive((forwardMagnitude + curvature), forwardMagnitude, false);
+ } else if (curvature > 0.1) {
+ Components.driveSystem.drive(forwardMagnitude, (forwardMagnitude - curvature), false);
} else { // Going straight
Components.driveSystem.drive(forwardMagnitude, forwardMagnitude, true);
}
} else {
Components.driveSystem.drive(Components.leftDriveStick.getCoalescedY(), Components.rightDriveStick.getCoalescedY());
}
// Left Stick Trigger -- Driving gear down
if (Components.leftDriveStick.getTrigger() && !this.triggers[0]) {
Components.eventBus.push(new DriveGearDownEvent());
this.triggers[0] = true;
} else if (!Components.leftDriveStick.getTrigger()) {
this.triggers[0] = false;
}
// Right Stick Trigger -- Driving gear up
if (Components.rightDriveStick.getTrigger() && !this.triggers[1]) {
Components.eventBus.push(new DriveGearUpEvent());
this.triggers[1] = true;
} else if (!Components.rightDriveStick.getTrigger()) {
this.triggers[1] = false;
}
} // End Driving Scope
{ // Shooter Scope
XboxController xbc = Components.operatorController;
// Right Bumper (RB) -- Gear up
if (xbc.getButton(XboxController.Button.RB) && !justPressed[XboxController.Button.RB.value]) {
Components.eventBus.push(new ShooterGearUpEvent());
justPressed[XboxController.Button.RB.value] = true;
} else if (!xbc.getButton(XboxController.Button.RB)) {
justPressed[XboxController.Button.RB.value] = false;
}
// Left Bumper (LB) -- Gear down
if (xbc.getButton(XboxController.Button.LB) && !justPressed[XboxController.Button.LB.value]) {
Components.eventBus.push(new ShooterGearDownEvent());
justPressed[XboxController.Button.LB.value] = true;
} else if (!xbc.getButton(XboxController.Button.LB)) {
justPressed[XboxController.Button.LB.value] = false;
}
// A Button -- Fire shooter (1 disque)
if (xbc.getButton(XboxController.Button.A) && !justPressed[XboxController.Button.A.value]) {
Components.eventBus.push(new ShooterActuatorEvent());
justPressed[XboxController.Button.A.value] = true;
} else if (!xbc.getButton(XboxController.Button.A)) {
justPressed[XboxController.Button.A.value] = false;
}
// B Button -- Fire shooter (2 disques)
if (xbc.getButton(XboxController.Button.B) && !justPressed[XboxController.Button.B.value]) {
Components.eventBus.push(new ShooterActuatorEvent(2));
justPressed[XboxController.Button.B.value] = true;
} else if (!xbc.getButton(XboxController.Button.B)) {
justPressed[XboxController.Button.B.value] = false;
}
// Y Button -- Fire shooter (3 disques)
if (xbc.getButton(XboxController.Button.Y) && !justPressed[XboxController.Button.Y.value]) {
Components.eventBus.push(new ShooterActuatorEvent(3));
justPressed[XboxController.Button.Y.value] = true;
} else if (!xbc.getButton(XboxController.Button.Y)) {
justPressed[XboxController.Button.Y.value] = false;
}
// X Button -- Fire shooter (4 disques)
if (xbc.getButton(XboxController.Button.X) && !justPressed[XboxController.Button.X.value]) {
Components.eventBus.push(new ShooterActuatorEvent(4));
justPressed[XboxController.Button.X.value] = true;
} else if (!xbc.getButton(XboxController.Button.X)) {
justPressed[XboxController.Button.X.value] = false;
}
// Right Thumb Click -- Ring Light
if (xbc.getButton(XboxController.Button.RightClick) && !justPressed[XboxController.Button.RightClick.value]) {
Components.eventBus.push(new RingLightActivateEvent());
justPressed[XboxController.Button.RightClick.value] = true;
} else if (!xbc.getButton(XboxController.Button.RightClick)) {
Components.eventBus.push(new RingLightDeactivateEvent());
justPressed[XboxController.Button.RightClick.value] = false;
}
// Shooter state control options
if (!Components.preferences.getBoolean("shooter_always_on", DefaultConfiguration.SHOOTER_ALWAYS_ON)) {
// Back -- Stop shooter
if (xbc.getButton(XboxController.Button.Back) && !justPressed[XboxController.Button.Back.value]) {
Components.eventBus.push(new ShooterStopEvent());
justPressed[XboxController.Button.Back.value] = true;
} else if (!xbc.getButton(XboxController.Button.Back)) {
justPressed[XboxController.Button.Back.value] = false;
}
// Start -- Start shooter
if (xbc.getButton(XboxController.Button.Start) && !justPressed[XboxController.Button.Start.value]) {
Components.eventBus.push(new ShooterStartEvent());
justPressed[XboxController.Button.Start.value] = true;
} else if (!xbc.getButton(XboxController.Button.Start)) {
justPressed[XboxController.Button.Start.value] = false;
}
} else {
Components.shooterSystem.set(1);
}
} // End Shooter Scope
{ // Shooter Angle Scope
Components.shooterAngleSystem.set(Components.operatorController.getAxis(1, 2));
} // End Shooter Angle Scope
{ // Event Bus Scope
Components.eventBus.next();
} // End Event Bus Scope
{ // Compressor Support Scope
if (Components.preferences.getBoolean("compressor_on", DefaultConfiguration.COMPRESSOR_ON)) {
if (!Components.compressorSafety.get()) {
Components.compressor.set(Relay.Value.kOn);
} else {
Components.compressor.set(Relay.Value.kOff);
}
}
} // End Compressor Support Scope
}
}
| false | true | public void teleopPeriodic() {
{ // Driving Scope
if (Components.preferences.getBoolean("experimental_drive", DefaultConfiguration.EXPERIMENTAL_DRIVE)) {
double forwardMagnitude = -Components.leftDriveStick.getCoalescedY();
double curvature = Components.rightDriveStick.getCoalescedX();
double attachment = Components.rightDriveStick.getCoalescedZ();
if (Math.abs(attachment) > 0.1 && Components.preferences.getBoolean("experimental_drive_attachment", DefaultConfiguration.EXPERIMENTAL_DRIVE_ATTACHMENT)) {
Components.driveSystem.drive(-attachment, attachment, false);
} else if (curvature < 0.1) { // Turning left
Components.driveSystem.drive(-(forwardMagnitude + curvature), -forwardMagnitude, false);
} else if (curvature > 0.1) { // Turning right
Components.driveSystem.drive(-forwardMagnitude, -(forwardMagnitude - curvature), false);
} else { // Going straight
Components.driveSystem.drive(forwardMagnitude, forwardMagnitude, true);
}
} else {
Components.driveSystem.drive(Components.leftDriveStick.getCoalescedY(), Components.rightDriveStick.getCoalescedY());
}
// Left Stick Trigger -- Driving gear down
if (Components.leftDriveStick.getTrigger() && !this.triggers[0]) {
Components.eventBus.push(new DriveGearDownEvent());
this.triggers[0] = true;
} else if (!Components.leftDriveStick.getTrigger()) {
this.triggers[0] = false;
}
// Right Stick Trigger -- Driving gear up
if (Components.rightDriveStick.getTrigger() && !this.triggers[1]) {
Components.eventBus.push(new DriveGearUpEvent());
this.triggers[1] = true;
} else if (!Components.rightDriveStick.getTrigger()) {
this.triggers[1] = false;
}
} // End Driving Scope
{ // Shooter Scope
XboxController xbc = Components.operatorController;
// Right Bumper (RB) -- Gear up
if (xbc.getButton(XboxController.Button.RB) && !justPressed[XboxController.Button.RB.value]) {
Components.eventBus.push(new ShooterGearUpEvent());
justPressed[XboxController.Button.RB.value] = true;
} else if (!xbc.getButton(XboxController.Button.RB)) {
justPressed[XboxController.Button.RB.value] = false;
}
// Left Bumper (LB) -- Gear down
if (xbc.getButton(XboxController.Button.LB) && !justPressed[XboxController.Button.LB.value]) {
Components.eventBus.push(new ShooterGearDownEvent());
justPressed[XboxController.Button.LB.value] = true;
} else if (!xbc.getButton(XboxController.Button.LB)) {
justPressed[XboxController.Button.LB.value] = false;
}
// A Button -- Fire shooter (1 disque)
if (xbc.getButton(XboxController.Button.A) && !justPressed[XboxController.Button.A.value]) {
Components.eventBus.push(new ShooterActuatorEvent());
justPressed[XboxController.Button.A.value] = true;
} else if (!xbc.getButton(XboxController.Button.A)) {
justPressed[XboxController.Button.A.value] = false;
}
// B Button -- Fire shooter (2 disques)
if (xbc.getButton(XboxController.Button.B) && !justPressed[XboxController.Button.B.value]) {
Components.eventBus.push(new ShooterActuatorEvent(2));
justPressed[XboxController.Button.B.value] = true;
} else if (!xbc.getButton(XboxController.Button.B)) {
justPressed[XboxController.Button.B.value] = false;
}
// Y Button -- Fire shooter (3 disques)
if (xbc.getButton(XboxController.Button.Y) && !justPressed[XboxController.Button.Y.value]) {
Components.eventBus.push(new ShooterActuatorEvent(3));
justPressed[XboxController.Button.Y.value] = true;
} else if (!xbc.getButton(XboxController.Button.Y)) {
justPressed[XboxController.Button.Y.value] = false;
}
// X Button -- Fire shooter (4 disques)
if (xbc.getButton(XboxController.Button.X) && !justPressed[XboxController.Button.X.value]) {
Components.eventBus.push(new ShooterActuatorEvent(4));
justPressed[XboxController.Button.X.value] = true;
} else if (!xbc.getButton(XboxController.Button.X)) {
justPressed[XboxController.Button.X.value] = false;
}
// Right Thumb Click -- Ring Light
if (xbc.getButton(XboxController.Button.RightClick) && !justPressed[XboxController.Button.RightClick.value]) {
Components.eventBus.push(new RingLightActivateEvent());
justPressed[XboxController.Button.RightClick.value] = true;
} else if (!xbc.getButton(XboxController.Button.RightClick)) {
Components.eventBus.push(new RingLightDeactivateEvent());
justPressed[XboxController.Button.RightClick.value] = false;
}
// Shooter state control options
if (!Components.preferences.getBoolean("shooter_always_on", DefaultConfiguration.SHOOTER_ALWAYS_ON)) {
// Back -- Stop shooter
if (xbc.getButton(XboxController.Button.Back) && !justPressed[XboxController.Button.Back.value]) {
Components.eventBus.push(new ShooterStopEvent());
justPressed[XboxController.Button.Back.value] = true;
} else if (!xbc.getButton(XboxController.Button.Back)) {
justPressed[XboxController.Button.Back.value] = false;
}
// Start -- Start shooter
if (xbc.getButton(XboxController.Button.Start) && !justPressed[XboxController.Button.Start.value]) {
Components.eventBus.push(new ShooterStartEvent());
justPressed[XboxController.Button.Start.value] = true;
} else if (!xbc.getButton(XboxController.Button.Start)) {
justPressed[XboxController.Button.Start.value] = false;
}
} else {
Components.shooterSystem.set(1);
}
} // End Shooter Scope
{ // Shooter Angle Scope
Components.shooterAngleSystem.set(Components.operatorController.getAxis(1, 2));
} // End Shooter Angle Scope
{ // Event Bus Scope
Components.eventBus.next();
} // End Event Bus Scope
{ // Compressor Support Scope
if (Components.preferences.getBoolean("compressor_on", DefaultConfiguration.COMPRESSOR_ON)) {
if (!Components.compressorSafety.get()) {
Components.compressor.set(Relay.Value.kOn);
} else {
Components.compressor.set(Relay.Value.kOff);
}
}
} // End Compressor Support Scope
}
| public void teleopPeriodic() {
{ // Driving Scope
if (Components.preferences.getBoolean("experimental_drive", DefaultConfiguration.EXPERIMENTAL_DRIVE)) {
double forwardMagnitude = -Components.leftDriveStick.getCoalescedY();
double curvature = Components.rightDriveStick.getCoalescedX();
double attachment = Components.rightDriveStick.getCoalescedZ();
if (Math.abs(attachment) > 0.1 && Components.preferences.getBoolean("experimental_drive_attachment", DefaultConfiguration.EXPERIMENTAL_DRIVE_ATTACHMENT)) {
Components.driveSystem.drive(-attachment, attachment, false);
} else if (curvature < 0.1 && -forwardMagnitude > 0) { // Turning left and going forward
Components.driveSystem.drive(-(forwardMagnitude + curvature), -forwardMagnitude, false);
} else if (curvature > 0.1 && -forwardMagnitude > 0) { // Turning right and going forward
Components.driveSystem.drive(-forwardMagnitude, -(forwardMagnitude - curvature), false);
} else if (curvature < 0.1) {
Components.driveSystem.drive((forwardMagnitude + curvature), forwardMagnitude, false);
} else if (curvature > 0.1) {
Components.driveSystem.drive(forwardMagnitude, (forwardMagnitude - curvature), false);
} else { // Going straight
Components.driveSystem.drive(forwardMagnitude, forwardMagnitude, true);
}
} else {
Components.driveSystem.drive(Components.leftDriveStick.getCoalescedY(), Components.rightDriveStick.getCoalescedY());
}
// Left Stick Trigger -- Driving gear down
if (Components.leftDriveStick.getTrigger() && !this.triggers[0]) {
Components.eventBus.push(new DriveGearDownEvent());
this.triggers[0] = true;
} else if (!Components.leftDriveStick.getTrigger()) {
this.triggers[0] = false;
}
// Right Stick Trigger -- Driving gear up
if (Components.rightDriveStick.getTrigger() && !this.triggers[1]) {
Components.eventBus.push(new DriveGearUpEvent());
this.triggers[1] = true;
} else if (!Components.rightDriveStick.getTrigger()) {
this.triggers[1] = false;
}
} // End Driving Scope
{ // Shooter Scope
XboxController xbc = Components.operatorController;
// Right Bumper (RB) -- Gear up
if (xbc.getButton(XboxController.Button.RB) && !justPressed[XboxController.Button.RB.value]) {
Components.eventBus.push(new ShooterGearUpEvent());
justPressed[XboxController.Button.RB.value] = true;
} else if (!xbc.getButton(XboxController.Button.RB)) {
justPressed[XboxController.Button.RB.value] = false;
}
// Left Bumper (LB) -- Gear down
if (xbc.getButton(XboxController.Button.LB) && !justPressed[XboxController.Button.LB.value]) {
Components.eventBus.push(new ShooterGearDownEvent());
justPressed[XboxController.Button.LB.value] = true;
} else if (!xbc.getButton(XboxController.Button.LB)) {
justPressed[XboxController.Button.LB.value] = false;
}
// A Button -- Fire shooter (1 disque)
if (xbc.getButton(XboxController.Button.A) && !justPressed[XboxController.Button.A.value]) {
Components.eventBus.push(new ShooterActuatorEvent());
justPressed[XboxController.Button.A.value] = true;
} else if (!xbc.getButton(XboxController.Button.A)) {
justPressed[XboxController.Button.A.value] = false;
}
// B Button -- Fire shooter (2 disques)
if (xbc.getButton(XboxController.Button.B) && !justPressed[XboxController.Button.B.value]) {
Components.eventBus.push(new ShooterActuatorEvent(2));
justPressed[XboxController.Button.B.value] = true;
} else if (!xbc.getButton(XboxController.Button.B)) {
justPressed[XboxController.Button.B.value] = false;
}
// Y Button -- Fire shooter (3 disques)
if (xbc.getButton(XboxController.Button.Y) && !justPressed[XboxController.Button.Y.value]) {
Components.eventBus.push(new ShooterActuatorEvent(3));
justPressed[XboxController.Button.Y.value] = true;
} else if (!xbc.getButton(XboxController.Button.Y)) {
justPressed[XboxController.Button.Y.value] = false;
}
// X Button -- Fire shooter (4 disques)
if (xbc.getButton(XboxController.Button.X) && !justPressed[XboxController.Button.X.value]) {
Components.eventBus.push(new ShooterActuatorEvent(4));
justPressed[XboxController.Button.X.value] = true;
} else if (!xbc.getButton(XboxController.Button.X)) {
justPressed[XboxController.Button.X.value] = false;
}
// Right Thumb Click -- Ring Light
if (xbc.getButton(XboxController.Button.RightClick) && !justPressed[XboxController.Button.RightClick.value]) {
Components.eventBus.push(new RingLightActivateEvent());
justPressed[XboxController.Button.RightClick.value] = true;
} else if (!xbc.getButton(XboxController.Button.RightClick)) {
Components.eventBus.push(new RingLightDeactivateEvent());
justPressed[XboxController.Button.RightClick.value] = false;
}
// Shooter state control options
if (!Components.preferences.getBoolean("shooter_always_on", DefaultConfiguration.SHOOTER_ALWAYS_ON)) {
// Back -- Stop shooter
if (xbc.getButton(XboxController.Button.Back) && !justPressed[XboxController.Button.Back.value]) {
Components.eventBus.push(new ShooterStopEvent());
justPressed[XboxController.Button.Back.value] = true;
} else if (!xbc.getButton(XboxController.Button.Back)) {
justPressed[XboxController.Button.Back.value] = false;
}
// Start -- Start shooter
if (xbc.getButton(XboxController.Button.Start) && !justPressed[XboxController.Button.Start.value]) {
Components.eventBus.push(new ShooterStartEvent());
justPressed[XboxController.Button.Start.value] = true;
} else if (!xbc.getButton(XboxController.Button.Start)) {
justPressed[XboxController.Button.Start.value] = false;
}
} else {
Components.shooterSystem.set(1);
}
} // End Shooter Scope
{ // Shooter Angle Scope
Components.shooterAngleSystem.set(Components.operatorController.getAxis(1, 2));
} // End Shooter Angle Scope
{ // Event Bus Scope
Components.eventBus.next();
} // End Event Bus Scope
{ // Compressor Support Scope
if (Components.preferences.getBoolean("compressor_on", DefaultConfiguration.COMPRESSOR_ON)) {
if (!Components.compressorSafety.get()) {
Components.compressor.set(Relay.Value.kOn);
} else {
Components.compressor.set(Relay.Value.kOff);
}
}
} // End Compressor Support Scope
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.