answer
stringlengths 17
10.2M
|
|---|
package edu.mit.csail.uid;
import java.awt.*;
import java.util.*;
import javax.swing.text.*;
import javax.swing.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.event.*;
import javax.swing.SizeRequirements;
public class SikuliViewFactory implements ViewFactory {
/**
* @see javax.swing.text.ViewFactory#create(javax.swing.text.Element)
*/
public View create(Element elem) {
String kind = elem.getName();
Debug.log(8, "create: " + kind );
if (kind != null)
{
if (kind.equals(AbstractDocument.ContentElementName))
{
return new HighlightLabelView(elem);
//return new LabelView(elem);
}
else if (kind.equals(AbstractDocument.ParagraphElementName))
{
//return new MyParagraphView(elem);
//return new ParagraphView(elem);
return new LineBoxView(elem, View.X_AXIS);
}
else if (kind.equals(AbstractDocument.SectionElementName))
{
//return new CenteredBoxView(elem, View.Y_AXIS);
return new SectionBoxView(elem, View.Y_AXIS);
}
else if (kind.equals(StyleConstants.ComponentElementName))
{
return new ComponentView(elem);
}
else if (kind.equals(StyleConstants.IconElementName))
{
return new IconView(elem);
}
}
// default to text display
return new LabelView(elem);
//return new SikuliView(element);
}
}
class MyParagraphView extends ParagraphView
{
protected View createRow(){
Element elem = getElement();
Debug.log(1, "createRow: " + elem);
View row = new LineBoxView(elem, View.X_AXIS);
return row;
}
public MyParagraphView(Element elem){
super(elem);
}
}
class LineBoxView extends BoxView
{
public LineBoxView(Element elem, int axis)
{
super(elem,axis);
}
// for Utilities.getRowStart
public Shape modelToView(int pos, Shape a, Position.Bias b) throws BadLocationException {
Rectangle r = a.getBounds();
View v = getViewAtPosition(pos, r);
if ((v != null) && (!v.getElement().isLeaf())) {
// Don't adjust the height if the view represents a branch.
return super.modelToView(pos, a, b);
}
r = a.getBounds();
int height = r.height;
int y = r.y;
Shape loc = super.modelToView(pos, a, b);
r = loc.getBounds();
r.height = height;
r.y = y;
return r;
}
protected void layoutMinorAxis(int targetSpan, int axis, int[] offsets, int[] spans)
{
super.layoutMinorAxis(targetSpan,axis,offsets,spans);
int maxH = 0;
int offset = 0;
for (int i = 0; i < spans.length; i++)
if( spans[i] > maxH )
maxH = spans[i];
for (int i = 0; i < offsets.length; i++)
offsets[i] = (maxH - spans[i])/2;
}
}
class SectionBoxView extends BoxView
{
public SectionBoxView(Element elem, int axis)
{
super(elem,axis);
}
protected void layoutMajorAxis(int targetSpan, int axis, int[] offsets, int[] spans)
{
super.layoutMajorAxis(targetSpan,axis,offsets,spans);
int count = getViewCount();
if( count == 0 )
return;
int offset = 0;
offsets[0] = 0;
spans[0] = (int)getView(0).getMinimumSpan(View.Y_AXIS);
for(int i=1;i<count;i++){
View view = getView(i);
spans[i] = (int)view.getMinimumSpan(View.Y_AXIS);
offset += spans[i-1];
offsets[i] = offset;
}
}
protected void layoutMinorAxis(int targetSpan, int axis, int[] offsets, int[] spans)
{
super.layoutMinorAxis(targetSpan,axis,offsets,spans);
int count = getViewCount();
for(int i=0;i<count;i++){
offsets[i] = 0;
}
}
}
class HighlightLabelView extends LabelView {
static FontMetrics _fMetrics = null;
final String tabStr = " "; // default tab size: 4
private static Map<Pattern, Color> patternColors;
private static Font fontParenthesis;
private static String[] keywords = {
"and", "del", "for", "is", "raise",
"assert", "elif", "from", "lambda", "return",
"break", "else", "global", "not", "try",
"class", "except", "if", "or", "while",
"continue", "exec", "import", "pass", "yield",
"def", "finally", "in", "print", "with"
};
private static String[] keywordsSikuliClass = {
"Region", "Screen", "Match", "Pattern",
"Location", "VDict", "Env", "Key", "Button", "Finder"
};
private static String[] keywordsSikuli = {
"find", "wait", "findAll", "waitVanish", "exists",
"click", "doubleClick", "rightClick", "hover",
"type", "paste",
"dragDrop", "drag", "dropAt",
"mouseMove", "mouseDown", "mouseUp",
"keyDown", "keyUp",
"onAppear", "onVanish", "onChange", "observe", "stopObserver",
"popup", "capture", "input", "sleep",
"switchApp", "openApp", "closeApp",
"assertExist", "assertNotExist",
"selectRegion",
"getOS", "getMouseLocation", "exit",
"right", "left", "above", "below", "nearby", "inside",
"getScreen", "getCenter",
"setX", "setY", "setW", "setH", "setRect", "setROI",
"getX", "getY", "getW", "getH", "getRect", "getROI",
"getNumberScreens", "getBounds",
"similar", "targetOffset", "getLastMatch", "getLastMatches",
"getTargetOffset", "getFilename",
"setAutoWaitTimeout", "setBundlePath", "setShowActions",
"setThrowException",
"hasNext", "next", "destroy", "exact", "offset",
"getOSVersion", "getScore", "getTarget",
"getBundlePath", "getAutoWaitTimeout", "getThrowException",
"getClipboard"
};
private static String[] constantsSikuli = {
"FOREVER",
"KEY_SHIFT", "KEY_CTRL", "KEY_META", "KEY_ALT", "KEY_CMD", "KEY_WIN",
"ENTER", "BACKSPACE", "TAB", "ESC", "UP", "RIGHT", "DOWN", "LEFT",
"PAGE_UP", "PAGE_DOWN", "DELETE", "END", "HOME", "INSERT", "F1",
"F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12",
"F13", "F14", "F15", "SHIFT", "CTRL", "ALT", "META", "CMD", "WIN"
"SCREEN", "MIDDLE"
};
static {
Debug.log(4, "init patternColors");
fontParenthesis = new Font("Osaka-Mono", Font.PLAIN, 30);
// NOTE: the order is important!
patternColors = new HashMap<Pattern, Color>();
patternColors.put(Pattern.compile("(#:.*$)"), new Color(220,220,220));
patternColors.put(Pattern.compile("(#.*$)"), new Color(138,140,193));
patternColors.put(Pattern.compile("(\"[^\"]*\"?)"), new Color(128,0,0));
patternColors.put(Pattern.compile("\\b([0-9]+)\\b"), new Color(128,64,0));
for(int i=0;i<keywords.length;i++)
patternColors.put(Pattern.compile("\\b("+keywords[i]+")\\b"),
Color.blue);
for(int i=0;i<keywordsSikuli.length;i++){
patternColors.put(Pattern.compile("\\b("+keywordsSikuli[i]+")\\b"),
new Color(63,127,127));
}
for(int i=0;i<keywordsSikuliClass.length;i++){
patternColors.put(Pattern.compile(
"\\b("+keywordsSikuliClass[i]+")\\b"),
new Color(215,41,56));
}
for(int i=0;i<constantsSikuli.length;i++){
patternColors.put(Pattern.compile(
"\\b("+constantsSikuli[i]+")\\b"),
new Color(128,64,0));
}
//patternColors.put(Pattern.compile("(\t)"), Color.white);
/*
patternColors.put(Pattern.compile("(\\()$"), Color.black);
patternColors.put(Pattern.compile("^(\\))"), Color.black);
*/
}
public HighlightLabelView(Element elm){
super(elm);
}
private int countTab(String str){
int pos = -1;
int count = 0;
while((pos=str.indexOf('\t', pos+1))!=-1){
count++;
}
return count;
}
private int tabbedWidth(){
if(_fMetrics==null)
return -1;
String str = getText(getStartOffset(), getEndOffset()).toString();
int tab = countTab(str);
int tabWidth = _fMetrics.stringWidth(tabStr.substring(1));
return _fMetrics.stringWidth(str) + tabWidth*tab;
}
public float getMinimumSpan(int axis) {
float f = super.getMinimumSpan(axis);
if(axis == View.X_AXIS && _fMetrics!=null){
f = tabbedWidth();
}
return f;
}
public float getMaximumSpan(int axis) {
float f = super.getMaximumSpan(axis);
if(axis == View.X_AXIS && _fMetrics!=null ){
f = tabbedWidth();
}
return f;
}
public float getPreferredSpan(int axis) {
float f = super.getPreferredSpan(axis);
if(axis == View.X_AXIS && _fMetrics!=null){
f = tabbedWidth();
}
return f;
}
public int viewToModel(float fx, float fy, Shape a, Position.Bias[] bias) {
bias[0] = Position.Bias.Forward;
Debug.log(9, "viewToModel: " + fx + " " + fy);
String str = getText(getStartOffset(), getEndOffset()).toString();
int left = getStartOffset(), right = getEndOffset();
int pos = 0;
while(left<right){
Debug.log(9, "viewToModel: " + left + " " + right + " " + pos);
pos = (left+right)/2;
try{
Shape s = modelToView(pos, a, bias[0]);
float sx = s.getBounds().x;
if( sx > fx )
right = pos;
else if( sx < fx )
left = pos+1;
else
break;
}
catch(BadLocationException ble){
break;
}
}
pos = left-1>=getStartOffset()? left-1 : getStartOffset();
try{
Debug.log(9, "viewToModel: try " + pos);
Shape s1 = modelToView(pos, a, bias[0]);
Shape s2 = modelToView(pos+1, a, bias[0]);
if( Math.abs(s1.getBounds().x-fx) <= Math.abs(s2.getBounds().x-fx) )
return pos;
else
return pos+1;
}
catch(BadLocationException ble){}
return pos;
}
public Shape modelToView(int pos, Shape a, Position.Bias b)
throws BadLocationException {
if(_fMetrics==null)
return super.modelToView(pos, a, b);
int start = getStartOffset(), end = getEndOffset();
Debug.log(9,"[modelToView] start: " + start +
" end: " + end + " pos:" + pos);
String strHead = getText(start, pos).toString();
String strTail = getText(pos, end).toString();
Debug.log(9, "[modelToView] [" + strHead + "]-pos-[" + strTail+"]");
int tabHead = countTab(strHead), tabTail = countTab(strTail);
Debug.log(9, "[modelToView] " + tabHead + " " + tabTail);
Shape s = super.modelToView(pos, a, b);
Rectangle ret = s.getBounds();
Debug.log(9, "[modelToView] super.bounds: " + ret);
int tabWidth = _fMetrics.stringWidth(tabStr.substring(1));
if(pos!=end)
ret.x += tabHead*tabWidth;
//ret.width += tabTail*tabWidth;
Debug.log(9, "[modelToView] new bounds: " + ret);
return ret;
}
public void paint(Graphics g, Shape shape){
Graphics2D g2d = (Graphics2D)g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
//super.paint(g, shape); // for drawing selection
String text = getText(getStartOffset(), getEndOffset()).toString();
//System.out.println("draw " + text);
SortedMap<Integer, Integer> posMap = new TreeMap<Integer, Integer>();
SortedMap<Integer, Color> colorMap = new TreeMap<Integer, Color>();
buildColorMaps(text, posMap, colorMap);
if(_fMetrics == null)
_fMetrics = g2d.getFontMetrics();
Rectangle alloc = (shape instanceof Rectangle)?
(Rectangle)shape : shape.getBounds();
int sx = alloc.x;
int sy = alloc.y + alloc.height - _fMetrics.getDescent();
int i = 0;
for (Map.Entry<Integer, Integer> entry : posMap.entrySet()) {
int start = entry.getKey();
int end = entry.getValue();
if (i <= start) {
g2d.setColor(Color.black);
String str = text.substring(i, start);
sx = drawString(g2d, str, sx, sy);
}
else
break;
g2d.setColor(colorMap.get(start));
i = end;
String str = text.substring(start, i);
/*
if( str.equals("(") || str.equals(")") )
sx = drawParenthesis(g2d, str, sx, sy);
else
*/
sx = drawString(g2d, str, sx, sy);
}
// Paint possible remaining text black
if (i < text.length()) {
g2d.setColor(Color.black);
String str = text.substring(i, text.length());
sx = drawString(g2d, str, sx, sy);
}
}
int drawTab(Graphics2D g2d, int x, int y){
drawString(g2d, tabStr, x, y);
return x + _fMetrics.stringWidth(tabStr);
}
int drawString(Graphics2D g2d, String str, int x, int y){
if(str.length()==0)
return x;
int tabPos = str.indexOf('\t');
if( tabPos != -1){
x = drawString(g2d, str.substring(0, tabPos), x, y);
x = drawTab(g2d, x, y);
x = drawString(g2d, str.substring(tabPos+1), x, y);
}
else{
g2d.drawString(str, x, y);
x += _fMetrics.stringWidth(str);
}
return x;
}
int drawParenthesis(Graphics2D g2d, String str, int x, int y){
Font origFont = g2d.getFont();
g2d.setFont(fontParenthesis);
g2d.drawString(str, x, y);
x += g2d.getFontMetrics().stringWidth(str);
g2d.setFont(origFont);
return x;
}
void buildColorMaps(String text, Map<Integer, Integer> posMap,
Map<Integer,Color> colorMap){
// Match all regexes on this snippet, store positions
for (Map.Entry<Pattern, Color> entry : patternColors.entrySet()) {
Matcher matcher = entry.getKey().matcher(text);
while(matcher.find()) {
posMap.put(matcher.start(1), matcher.end());
colorMap.put(matcher.start(1), entry.getValue());
}
}
}
}
|
package org.jboss.jca.sjc.deployers.ra;
import org.jboss.jca.sjc.annotationscanner.Annotation;
import org.jboss.jca.sjc.deployers.DeployException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.resource.spi.Activation;
import javax.resource.spi.AdministeredObject;
import javax.resource.spi.AuthenticationMechanism;
import javax.resource.spi.ConfigProperty;
import javax.resource.spi.ConnectionDefinition;
import javax.resource.spi.ConnectionDefinitions;
import javax.resource.spi.Connector;
import javax.resource.spi.SecurityPermission;
import javax.resource.spi.TransactionSupport;
import javax.resource.spi.work.WorkContext;
import org.jboss.logging.Logger;
import org.jboss.metadata.rar.spec.ConnectorMetaData;
import org.jboss.metadata.rar.spec.JCA16DTDMetaData;
import org.jboss.metadata.rar.spec.JCA16DefaultNSMetaData;
import org.jboss.metadata.rar.spec.JCA16MetaData;
import org.jboss.metadata.rar.spec.LicenseMetaData;
import org.jboss.metadata.rar.spec.ResourceAdapterMetaData;
import org.jboss.metadata.rar.spec.SecurityPermissionMetaData;
/**
* The annotation processor for JCA 1.6
* @author <a href="mailto:jesper.pedersen@jboss.org">Jesper Pedersen</a>
*/
public class Annotations
{
private static Logger log = Logger.getLogger(Annotations.class);
private static boolean trace = log.isTraceEnabled();
/**
* Constructor
*/
private Annotations()
{
}
/**
* Process annotations
* @param md The metadata
* @param annotations The annotations
* @return The updated metadata
* @exception Exception Thrown if an error occurs
*/
public static ConnectorMetaData process(ConnectorMetaData md, Map<Class, List<Annotation>> annotations)
throws Exception
{
if (md == null)
{
JCA16MetaData jmd = new JCA16MetaData();
jmd.setMetadataComplete(false);
md = jmd;
}
// @Connector
md = processConnector(md, annotations);
// @ConnectionDefinitions
md = processConnectionDefinitions(md, annotations);
// @ConnectionDefinition (outside of @ConnectionDefinitions)
md = processConnectionDefinition(md, annotations);
// @ConfigProperty
md = processConfigProperty(md, annotations);
// @AuthenticationMechanism
md = processAuthenticationMechanism(md, annotations);
// @AdministeredObject
md = processAdministeredObject(md, annotations);
// @Activation
md = processActivation(md, annotations);
return md;
}
/**
* Process: @Connector
* @param md The metadata
* @param annotations The annotations
* @return The updated metadata
* @exception Exception Thrown if an error occurs
*/
private static ConnectorMetaData processConnector(ConnectorMetaData md, Map<Class, List<Annotation>> annotations)
throws Exception
{
List<Annotation> values = annotations.get(Connector.class);
if (values != null)
{
if (values.size() == 1)
{
Annotation annotation = values.get(0);
Connector c = (Connector)annotation.getAnnotation();
if (trace)
log.trace("Processing: " + c);
md = attachConnector(md, c);
}
else
throw new DeployException("More than one @Connector defined");
}
return md;
}
/**
* Attach @Connector
* @param md The metadata
* @param c The connector
* @return The updated metadata
* @exception Exception Thrown if an error occurs
*/
private static ConnectorMetaData attachConnector(ConnectorMetaData md, Connector c)
throws Exception
{
// AuthenticationMechanism
AuthenticationMechanism[] authMechanisms = c.authMechanisms();
if (authMechanisms != null)
{
for (AuthenticationMechanism authMechanism : authMechanisms)
{
attachAuthenticationMechanism(md, authMechanism);
}
}
// Description
String[] description = c.description();
if (description != null)
{
// TODO
}
// Display name
String[] displayName = c.displayName();
if (displayName != null)
{
// TODO
}
// EIS type
String eisType = c.eisType();
if (eisType != null)
{
if (md.getEISType() == null)
md.setEISType(eisType);
}
// Large icon
String[] largeIcon = c.largeIcon();
if (largeIcon != null)
{
// TODO
}
String[] licenseDescription = c.licenseDescription();
if (licenseDescription != null)
{
if (md.getLicense() == null)
md.setLicense(new LicenseMetaData());
// TODO
}
boolean licenseRequired = c.licenseRequired();
if (md.getLicense() == null)
md.setLicense(new LicenseMetaData());
md.getLicense().setRequired(licenseRequired);
// Reauthentication support
boolean reauthenticationSupport = c.reauthenticationSupport();
// TODO
// RequiredWorkContext
Class<? extends WorkContext>[] requiredWorkContexts = c.requiredWorkContexts();
if (requiredWorkContexts != null)
{
for (Class<? extends WorkContext> requiredWorkContext : requiredWorkContexts)
{
if (md instanceof JCA16MetaData)
{
JCA16MetaData jmd = (JCA16MetaData)md;
if (jmd.getRequiredWorkContexts() == null)
jmd.setRequiredWorkContexts(new ArrayList<String>());
if (!jmd.getRequiredWorkContexts().contains(requiredWorkContext.getName()))
{
if (trace)
log.trace("RequiredWorkContext=" + requiredWorkContext.getName());
jmd.getRequiredWorkContexts().add(requiredWorkContext.getName());
}
}
else if (md instanceof JCA16DefaultNSMetaData)
{
JCA16DefaultNSMetaData jmd = (JCA16DefaultNSMetaData)md;
if (jmd.getRequiredWorkContexts() == null)
jmd.setRequiredWorkContexts(new ArrayList<String>());
if (!jmd.getRequiredWorkContexts().contains(requiredWorkContext.getName()))
{
if (trace)
log.trace("RequiredWorkContext=" + requiredWorkContext.getName());
jmd.getRequiredWorkContexts().add(requiredWorkContext.getName());
}
}
else if (md instanceof JCA16DTDMetaData)
{
JCA16DTDMetaData jmd = (JCA16DTDMetaData)md;
if (jmd.getRequiredWorkContexts() == null)
jmd.setRequiredWorkContexts(new ArrayList<String>());
if (!jmd.getRequiredWorkContexts().contains(requiredWorkContext.getName()))
{
if (trace)
log.trace("RequiredWorkContext=" + requiredWorkContext.getName());
jmd.getRequiredWorkContexts().add(requiredWorkContext.getName());
}
}
}
}
SecurityPermission[] securityPermissions = c.securityPermissions();
if (securityPermissions != null)
{
if (md.getRa() == null)
md.setRa(new ResourceAdapterMetaData());
if (md.getRa().getSecurityPermissions() == null)
md.getRa().setSecurityPermissions(new ArrayList<SecurityPermissionMetaData>());
for (SecurityPermission securityPermission : securityPermissions)
{
// TODO
}
}
// Small icon
String[] smallIcon = c.smallIcon();
if (smallIcon != null)
{
// TODO
}
// Spec version
String specVersion = c.specVersion();
md.setVersion("1.6");
// Transaction support
TransactionSupport.TransactionSupportLevel transactionSupport = c.transactionSupport();
// TODO
// Vendor name
String vendorName = c.vendorName();
if (vendorName != null)
{
if (md.getVendorName() == null)
md.setVendorName(vendorName);
}
// Version
String version = c.version();
if (version != null)
{
if (md.getRAVersion() == null)
md.setRAVersion(version);
}
return md;
}
/**
* Process: @ConnectionDefinitions
* @param md The metadata
* @param annotations The annotations
* @return The updated metadata
* @exception Exception Thrown if an error occurs
*/
private static ConnectorMetaData processConnectionDefinitions(ConnectorMetaData md,
Map<Class, List<Annotation>> annotations)
throws Exception
{
List<Annotation> values = annotations.get(ConnectionDefinitions.class);
if (values != null)
{
if (values.size() == 1)
{
Annotation annotation = values.get(0);
ConnectionDefinitions c = (ConnectionDefinitions)annotation.getAnnotation();
if (trace)
log.trace("Processing: " + c);
md = attachConnectionDefinitions(md , c);
}
else
throw new DeployException("More than one @ConnectionDefinitions defined");
}
return md;
}
/**
* Attach @ConnectionDefinitions
* @param md The metadata
* @param cds The connection definitions
* @return The updated metadata
* @exception Exception Thrown if an error occurs
*/
private static ConnectorMetaData attachConnectionDefinitions(ConnectorMetaData md,
ConnectionDefinitions cds)
throws Exception
{
return md;
}
/**
* Process: @ConnectionDefinition
* @param md The metadata
* @param annotations The annotations
* @return The updated metadata
* @exception Exception Thrown if an error occurs
*/
private static ConnectorMetaData processConnectionDefinition(ConnectorMetaData md,
Map<Class, List<Annotation>> annotations)
throws Exception
{
List<Annotation> values = annotations.get(ConnectionDefinition.class);
if (values != null)
{
for (Annotation annotation : values)
{
ConnectionDefinition c = (ConnectionDefinition)annotation.getAnnotation();
if (trace)
log.trace("Processing: " + c);
md = attachConnectionDefinition(md, c);
}
}
return md;
}
/**
* Attach @ConnectionDefinition
* @param md The metadata
* @param cd The connection definition
* @return The updated metadata
* @exception Exception Thrown if an error occurs
*/
private static ConnectorMetaData attachConnectionDefinition(ConnectorMetaData md,
ConnectionDefinition cd)
throws Exception
{
return md;
}
/**
* Process: @ConfigProperty
* @param md The metadata
* @param annotations The annotations
* @return The updated metadata
* @exception Exception Thrown if an error occurs
*/
private static ConnectorMetaData processConfigProperty(ConnectorMetaData md,
Map<Class, List<Annotation>> annotations)
throws Exception
{
List<Annotation> values = annotations.get(ConfigProperty.class);
if (values != null)
{
for (Annotation annotation : values)
{
ConfigProperty c = (ConfigProperty)annotation.getAnnotation();
if (trace)
log.trace("Processing: " + c);
md = attachConfigProperty(md, c);
}
}
return md;
}
/**
* Attach @ConfigProperty
* @param md The metadata
* @param configProperty The config property
* @return The updated metadata
* @exception Exception Thrown if an error occurs
*/
private static ConnectorMetaData attachConfigProperty(ConnectorMetaData md,
ConfigProperty configProperty)
throws Exception
{
return md;
}
/**
* Process: @AuthenticationMechanism
* @param md The metadata
* @param annotations The annotations
* @return The updated metadata
* @exception Exception Thrown if an error occurs
*/
private static ConnectorMetaData processAuthenticationMechanism(ConnectorMetaData md,
Map<Class, List<Annotation>> annotations)
throws Exception
{
List<Annotation> values = annotations.get(AuthenticationMechanism.class);
if (values != null)
{
for (Annotation annotation : values)
{
AuthenticationMechanism a = (AuthenticationMechanism)annotation.getAnnotation();
if (trace)
log.trace("Processing: " + a);
md = attachAuthenticationMechanism(md, a);
}
}
return md;
}
/**
* Attach @AuthenticationMechanism
* @param md The metadata
* @param authenticationmechanism The authentication mechanism
* @return The updated metadata
* @exception Exception Thrown if an error occurs
*/
private static ConnectorMetaData attachAuthenticationMechanism(ConnectorMetaData md,
AuthenticationMechanism authenticationmechanism)
throws Exception
{
return md;
}
/**
* Process: @AdministeredObject
* @param md The metadata
* @param annotations The annotations
* @return The updated metadata
* @exception Exception Thrown if an error occurs
*/
private static ConnectorMetaData processAdministeredObject(ConnectorMetaData md,
Map<Class, List<Annotation>> annotations)
throws Exception
{
List<Annotation> values = annotations.get(AdministeredObject.class);
if (values != null)
{
for (Annotation annotation : values)
{
AdministeredObject a = (AdministeredObject)annotation.getAnnotation();
if (trace)
log.trace("Processing: " + a);
md = attachAdministeredObject(md, a);
}
}
return md;
}
/**
* Attach @AdministeredObject
* @param md The metadata
* @param a The administered object
* @return The updated metadata
* @exception Exception Thrown if an error occurs
*/
private static ConnectorMetaData attachAdministeredObject(ConnectorMetaData md, AdministeredObject a)
throws Exception
{
return md;
}
/**
* Process: @Activation
* @param md The metadata
* @param annotations The annotations
* @return The updated metadata
* @exception Exception Thrown if an error occurs
*/
private static ConnectorMetaData processActivation(ConnectorMetaData md,
Map<Class, List<Annotation>> annotations)
throws Exception
{
List<Annotation> values = annotations.get(Activation.class);
if (values != null)
{
for (Annotation annotation : values)
{
Activation a = (Activation)annotation.getAnnotation();
if (trace)
log.trace("Processing: " + a);
md = attachActivation(md, a);
}
}
return md;
}
/**
* Attach @Activation
* @param md The metadata
* @param activation The activation
* @return The updated metadata
* @exception Exception Thrown if an error occurs
*/
private static ConnectorMetaData attachActivation(ConnectorMetaData md, Activation activation)
throws Exception
{
return md;
}
}
|
package javarepl.web;
import com.googlecode.utterlyidle.RequestBuilder;
import com.googlecode.utterlyidle.Response;
import com.googlecode.utterlyidle.Status;
import com.googlecode.utterlyidle.handlers.ClientHttpHandler;
import javarepl.Main;
import java.io.File;
import java.util.UUID;
import static com.googlecode.totallylazy.Sequences.sequence;
import static com.googlecode.utterlyidle.Responses.response;
import static com.googlecode.utterlyidle.Status.GATEWAY_TIMEOUT;
import static com.googlecode.utterlyidle.Status.INTERNAL_SERVER_ERROR;
import static java.io.File.pathSeparator;
import static java.lang.Thread.sleep;
import static java.net.URLDecoder.decode;
import static javarepl.Utils.randomServerPort;
import static javarepl.console.TimingOutConsole.EXPRESSION_TIMEOUT;
import static javarepl.console.TimingOutConsole.INACTIVITY_TIMEOUT;
public class WebConsoleClientHandler {
private final String id;
private int port;
private Process process;
public WebConsoleClientHandler() {
this.id = UUID.randomUUID().toString();
}
public String id() {
return id;
}
public int port() {
return port;
}
private void createProcess() {
if (process == null) {
try {
File path = new File(decode(Main.class.getProtectionDomain().getCodeSource().getLocation().getPath(), "ISO-8859-1"));
String classpath = sequence(System.getProperty("java.class.path")).add(path.toURI().toURL().toString()).toString(pathSeparator);
port = randomServerPort();
ProcessBuilder builder = new ProcessBuilder("java", "-Xmx96M", "-cp", classpath, Main.class.getCanonicalName(),
"--sandboxed", "--ignoreConsole", "--port=" + port, "--expressionTimeout=15", "--inactivityTimeout=300");
builder.redirectErrorStream(true);
process = builder.start();
sleep(1000);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
public void shutdown() {
if (process != null) {
process.destroy();
process = null;
}
}
public Response execute(String expression) {
createProcess();
try {
return reportProcessErrors(new ClientHttpHandler().handle(RequestBuilder.post("http://localhost:" + port + "/" + "execute").form("expression", expression).build()));
} catch (Exception e) {
return response(INTERNAL_SERVER_ERROR);
}
}
private Response reportProcessErrors(Response response) {
if (response.status() != Status.OK) {
try {
switch (process.exitValue()) {
case EXPRESSION_TIMEOUT:
return response(GATEWAY_TIMEOUT);
case INACTIVITY_TIMEOUT:
return response(GATEWAY_TIMEOUT);
}
} catch (Exception e) {
}
}
return response;
}
}
|
package org.slc.sli.client;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.slc.sli.entity.GenericEntity;
import org.slc.sli.entity.util.GenericEntityEnhancer;
import org.slc.sli.util.Constants;
import org.slc.sli.util.SecurityUtil;
/**
*
* API Client class used by the Dashboard to make calls to the API service.
* TODO: Refactor public methods to private and mock with PowerMockito in unit tests
*
* @author svankina
*
*/
public class LiveAPIClient implements APIClient {
private static final Logger LOGGER = LoggerFactory.getLogger(LiveAPIClient.class);
// base urls
private static final String SECTIONS_URL = "/v1/sections/";
private static final String STUDENTS_URL = "/v1/students/";
private static final String TEACHERS_URL = "/v1/teachers/";
private static final String HOME_URL = "/v1/home/";
private static final String ASSMT_URL = "/v1/assessments/";
private static final String SESSION_URL = "/v1/sessions/";
private static final String STUDENT_ASSMT_ASSOC_URL = "/v1/studentAssessmentAssociations/";
private static final String STUDENT_SECTION_GRADEBOOK = "/v1/studentSectionGradebookEntries";
// resources to append to base urls
private static final String ATTENDANCES = "/attendances";
private static final String STUDENT_SECTION_ASSOC = "/studentSectionAssociations";
private static final String TEACHER_SECTION_ASSOC = "/teacherSectionAssociations";
private static final String STUDENT_ASSMT_ASSOC = "/studentAssessmentAssociations";
private static final String STUDENT_WITH_GRADE = "/studentWithGrade";
private static final String SECTIONS = "/sections";
private static final String STUDENTS = "/students";
private static final String STUDENT_TRANSCRIPT_ASSOC = "/studentTranscriptAssociations";
// link names
private static final String ED_ORG_LINK = "getEducationOrganization";
private static final String COURSE_LINK = "getCourse";
private static final String SCHOOL_LINK = "getSchool";
private static final String STUDENT_SCHOOL_ASSOCIATIONS_LINK = "getStudentSchoolAssociations";
@Autowired
@Value("${api.server.url}")
private String apiUrl;
private String portalHeaderUrl;
private String portalFooterUrl;
public void setPortalHeaderUrl(String portalHeaderUrl) {
this.portalHeaderUrl = portalHeaderUrl;
}
public void setPortalFooterUrl(String portalFooterUrl) {
this.portalFooterUrl = portalFooterUrl;
}
private RESTClient restClient;
private Gson gson;
// For now, the live client will use the mock client for api calls not yet implemented
private MockAPIClient mockClient;
public LiveAPIClient() {
mockClient = new MockAPIClient();
gson = new Gson();
}
/**
* Get a list of schools for the user
*/
@Override
public List<GenericEntity> getSchools(String token, List<String> schoolIds) {
String teacherId = getId(token);
List<GenericEntity> sections = getSectionsForTeacher(teacherId, token);
List<GenericEntity> schools = getSchoolsForSection(sections, token);
return schools;
}
/**
* Get a list of student objects, given the student ids
*/
@Override
public List<GenericEntity> getStudents(final String token, Collection<String> ids) {
if (ids == null || ids.size() == 0) {
return null;
}
List<GenericEntity> students = new ArrayList<GenericEntity>();
for (String id : ids) {
GenericEntity student = getStudent(token, id);
if (student != null) {
students.add(student);
}
}
return students;
}
/**
* Get a list of student assessment results, given a student id
*/
@Override
public List<GenericEntity> getStudentAssessments(final String token, String studentId) {
// make a call to student-assessments, with the student id
List<GenericEntity> responses = createEntitiesFromAPI(getApiUrl() + STUDENTS_URL + studentId
+ STUDENT_ASSMT_ASSOC, token, true);
// for each link in the returned list, make the student-assessment call for the result data
List<GenericEntity> studentAssmts = new ArrayList<GenericEntity>();
if (responses != null) {
for (GenericEntity studentAssmt : responses) {
studentAssmts.add(studentAssmt);
}
}
return studentAssmts;
}
/**
* Get custom data
*/
@Override
public List<GenericEntity> getCustomData(final String token, String key) {
return mockClient.getCustomData(getUsername(), key);
}
/**
* Get assessment info, given a list of assessment ids
*/
@Override
public List<GenericEntity> getAssessments(final String token, List<String> assessmentIds) {
List<GenericEntity> assmts = new ArrayList<GenericEntity>();
for (String assmtId : assessmentIds) {
assmts.add(getAssessment(assmtId, token));
}
return assmts;
}
/**
* Get program participation, given a list of student ids
*/
@Override
public List<GenericEntity> getPrograms(final String token, List<String> studentIds) {
return mockClient.getPrograms(getUsername(), studentIds);
}
@Override
public GenericEntity getParentEducationalOrganization(final String token, GenericEntity edOrg) {
List<String> hrefs = extractLinksFromEntity(edOrg, ED_ORG_LINK);
for (String href : hrefs) {
// API provides *both* parent and children edOrgs in the "educationOrganization" link.
// So this hack needs be made because api doesn't distinguish between
// parent or children edOrgs. DE105 has been logged to resolve it.
// TODO: Remove the if statement once DE105 is resolved.
if (href.contains("?" + Constants.ATTR_PARENT_EDORG + "=")) {
// Links to children edOrgs are queries; ignore them.
continue;
}
GenericEntity responses = createEntityFromAPI(href, token, false);
return responses; // there should only be one parent.
}
// if we reached here the edOrg or school doesn't have a parent
return null;
}
/**
* Get a list of student ids belonging to a section
*/
private List<String> getStudentIdsForSection(String id, String token) {
List<GenericEntity> responses = createEntitiesFromAPI(getApiUrl() + SECTIONS_URL + id
+ STUDENT_SECTION_ASSOC, token, true);
List<String> studentIds = new ArrayList<String>();
if (responses != null) {
for (GenericEntity response : responses) {
studentIds.add(response.getString(Constants.ATTR_STUDENT_ID));
}
}
return studentIds;
}
/**
* Get one student
*/
@Override
public GenericEntity getStudent(String token, String id) {
return createEntityFromAPI(getApiUrl() + STUDENTS_URL + id + STUDENT_WITH_GRADE, token, false);
}
@Override
public List<GenericEntity> getStudents(String token, String sectionId, List<String> studentIds) {
return createEntitiesFromAPI(getApiUrl() + SECTIONS_URL + sectionId
+ STUDENT_SECTION_ASSOC + STUDENTS + "?optionalFields=assessments,attendances.1", token, false);
}
@Override
public List<GenericEntity> getStudentsWithGradebookEntries(final String token, final String sectionId) {
return createEntitiesFromAPI(getApiUrl() + SECTIONS_URL + sectionId + STUDENT_SECTION_ASSOC
+ STUDENTS + "?optionalFields=gradebook", token, false);
}
/**
* Get one section
*/
public GenericEntity getSection(String id, String token) {
if (id == null) {
return null;
}
GenericEntity section = createEntityFromAPI(getApiUrl() + SECTIONS_URL + id, token, false);
if (section == null) {
return null;
}
// if no section name, fill in with section code
if (section.get(Constants.ATTR_SECTION_NAME) == null) {
section.put(Constants.ATTR_SECTION_NAME, section.get(Constants.ATTR_UNIQUE_SECTION_CODE));
}
return section;
}
@Override
public GenericEntity getSession(String token, String id) {
GenericEntity session = null;
try {
session = createEntityFromAPI(getApiUrl() + SESSION_URL + id, token, false);
LOGGER.debug("Session: {}", session);
} catch (Exception e) {
LOGGER.warn("Error occured while getting session", e);
session = new GenericEntity();
}
return session;
}
/**
* Get one student-assessment association
*/
private GenericEntity getStudentAssessment(String id, String token) {
return createEntityFromAPI(getApiUrl() + STUDENT_ASSMT_ASSOC_URL + id, token, true);
}
/**
* Get one assessment
*/
private GenericEntity getAssessment(String id, String token) {
return createEntityFromAPI(getApiUrl() + ASSMT_URL + id, token, true);
}
/**
* Get the user's unique identifier
*
* @param token
* @return
*/
public String getId(String token) {
// Make a call to the /home uri and retrieve id from there
String returnValue = "";
GenericEntity response = createEntityFromAPI(getApiUrl() + HOME_URL, token, true);
for (Map link : (List<Map>) (response.get(Constants.ATTR_LINKS))) {
if (link.get(Constants.ATTR_REL).equals(Constants.ATTR_SELF)) {
returnValue = parseId(link);
}
}
return returnValue;
}
/**
* Given a link in the API response, extract the entity's unique id
*
* @param link
* @return
*/
private String parseId(Map link) {
String returnValue;
int index = ((String) (link.get(Constants.ATTR_HREF))).lastIndexOf("/");
returnValue = ((String) (link.get(Constants.ATTR_HREF))).substring(index + 1);
return returnValue;
}
/**
* Get a list of sections, given a teacher id
*/
public List<GenericEntity> getSectionsForTeacher(String id, String token) {
List<GenericEntity> sections = createEntitiesFromAPI(getApiUrl() + TEACHERS_URL + id
+ TEACHER_SECTION_ASSOC + SECTIONS, token, false);
if (sections != null) {
for (GenericEntity section : sections) {
// if no section name, fill in with section code
if (section.get(Constants.ATTR_SECTION_NAME) == null) {
section.put(Constants.ATTR_SECTION_NAME, section.get(Constants.ATTR_UNIQUE_SECTION_CODE));
}
// TODO: remove this when old LOS is retired
// get student ids in section
section.put(Constants.ATTR_STUDENT_UIDS, getStudentIdsForSection(section.getId(), token));
}
}
return sections;
}
/**
* Get a list of schools, given a list of sections
*
* @param sections
* @param token
* @return
*/
public List<GenericEntity> getSchoolsForSection(List<GenericEntity> sections, String token) {
// collect associated course first.
HashMap<String, GenericEntity> courseMap = new HashMap<String, GenericEntity>();
HashMap<String, String> sectionIDToCourseIDMap = new HashMap<String, String>();
getCourseSectionsMappings(sections, token, courseMap, sectionIDToCourseIDMap);
// now collect associated schools.
HashMap<String, GenericEntity> schoolMap = new HashMap<String, GenericEntity>();
HashMap<String, String> sectionIDToSchoolIDMap = new HashMap<String, String>();
getSchoolSectionsMappings(sections, token, schoolMap, sectionIDToSchoolIDMap);
// Now associate course and school.
// There is no direct course-school association in ed-fi, so in dashboard
// the "course-school" association is defined as follows:
// course C is associated with school S if there exists a section X s.t. C is associated
// with X and S is associated with X.
HashMap<String, HashSet<String>> schoolIDToCourseIDMap = new HashMap<String, HashSet<String>>();
for (int i = 0; i < sections.size(); i++) {
GenericEntity section = sections.get(i);
if (sectionIDToSchoolIDMap.containsKey(section.get(Constants.ATTR_ID))
&& sectionIDToCourseIDMap.containsKey(section.get(Constants.ATTR_ID))) {
String schoolId = sectionIDToSchoolIDMap.get(section.get(Constants.ATTR_ID));
String courseId = sectionIDToCourseIDMap.get(section.get(Constants.ATTR_ID));
if (!schoolIDToCourseIDMap.containsKey(schoolId)) {
schoolIDToCourseIDMap.put(schoolId, new HashSet<String>());
}
schoolIDToCourseIDMap.get(schoolId).add(courseId);
}
}
// now create the generic entity
for (String schoolId : schoolIDToCourseIDMap.keySet()) {
for (String courseId : schoolIDToCourseIDMap.get(schoolId)) {
GenericEntity s = schoolMap.get(schoolId);
GenericEntity c = courseMap.get(courseId);
s.appendToList(Constants.ATTR_COURSES, c);
}
}
return new ArrayList<GenericEntity>(schoolMap.values());
}
/**
* Get the associations between courses and sections
*/
private void getCourseSectionsMappings(List<GenericEntity> sections, String token,
Map<String, GenericEntity> courseMap, Map<String, String> sectionIDToCourseIDMap) {
for (int i = 0; i < sections.size(); i++) {
GenericEntity section = sections.get(i);
// Get course using courseId reference in section
List<String> hrefs = extractLinksFromEntity(section, COURSE_LINK);
if (hrefs.size() == 0) {
continue;
} // this section has no course attached to it.
// Add course to courseMap, if it doesn't exist already
if (!courseMap.containsKey(section.getString(Constants.ATTR_COURSE_ID))) {
GenericEntity course = this.createEntityFromAPI(hrefs.get(0), token, false);
courseMap.put(section.getString(Constants.ATTR_COURSE_ID), course);
}
// Grab the most up to date course from the map
// Add the section to it's section list, and update sectionIdToCourseIdMap
GenericEntity course = courseMap.get(section.get(Constants.ATTR_COURSE_ID));
course.appendToList(Constants.ATTR_SECTIONS, section);
sectionIDToCourseIDMap.put(section.getString(Constants.ATTR_ID), course.getString(Constants.ATTR_ID));
}
}
/**
* Get the associations between schools and sections
*/
private void getSchoolSectionsMappings(List<GenericEntity> sections, String token,
Map<String, GenericEntity> schoolMap, Map<String, String> sectionIDToSchoolIDMap) {
for (int i = 0; i < sections.size(); i++) {
GenericEntity section = sections.get(i);
// Get school link
List<String> hrefs = extractLinksFromEntity(section, SCHOOL_LINK);
if (hrefs.size() == 0) {
continue;
} // this section has no course attached to it.
// Add school to map, if it doesn't exist already
if (!schoolMap.containsKey(section.get(Constants.ATTR_SCHOOL_ID))) {
GenericEntity school = this.createEntityFromAPI(hrefs.get(0), token, false);
schoolMap.put((String) section.get(Constants.ATTR_SCHOOL_ID), school);
}
// update the sectionID to schoolID mapping
sectionIDToSchoolIDMap.put(section.getString(Constants.ATTR_ID),
section.getString(Constants.ATTR_SCHOOL_ID));
}
}
@Override
public List<GenericEntity> getSessionsByYear(String token, String schoolYear) {
String url = getApiUrl() + SESSION_URL + "?schoolYear=" + schoolYear;
try {
return createEntitiesFromAPI(url, token, false);
} catch (Exception e) {
LOGGER.error(e.toString());
return new ArrayList<GenericEntity>();
}
}
/**
* Returns the homeroom section for the student
*
* @param studentId
* @param token
* @return
*/
@Override
public GenericEntity getHomeRoomForStudent(String studentId, String token) {
String url = getApiUrl() + STUDENTS_URL + studentId + STUDENT_SECTION_ASSOC;
List<GenericEntity> sectionStudentAssociations = createEntitiesFromAPI(url, token, true);
// If only one section association exists for the student, return the section as home room
if (sectionStudentAssociations.size() == 1) {
String sectionId = sectionStudentAssociations.get(0).getString(Constants.ATTR_SECTION_ID);
return getSection(sectionId, token);
}
// If multiple section associations exist for the student, return the section with
// homeroomIndicator set to true
for (GenericEntity secStudentAssociation : sectionStudentAssociations) {
if ((secStudentAssociation.get(Constants.ATTR_HOMEROOM_INDICATOR) != null)
&& ((Boolean) secStudentAssociation.get(Constants.ATTR_HOMEROOM_INDICATOR))) {
String sectionId = secStudentAssociation.getString(Constants.ATTR_SECTION_ID);
return getSection(sectionId, token);
}
}
return null;
}
/**
* Returns the primary staff associated with the section.
*
* @param sectionId
* @param token
* @return
*/
@Override
public GenericEntity getTeacherForSection(String sectionId, String token) {
String url = getApiUrl() + SECTIONS_URL + sectionId + TEACHER_SECTION_ASSOC;
List<GenericEntity> teacherSectionAssociations = createEntitiesFromAPI(url, token, true);
if (teacherSectionAssociations != null) {
for (GenericEntity teacherSectionAssociation : teacherSectionAssociations) {
if (teacherSectionAssociation.getString(Constants.ATTR_CLASSROOM_POSITION).equals(
Constants.TEACHER_OF_RECORD)) {
String teacherUrl = getApiUrl() + TEACHERS_URL
+ teacherSectionAssociation.getString(Constants.ATTR_TEACHER_ID);
GenericEntity teacher = createEntityFromAPI(teacherUrl, token, true);
return teacher;
}
}
}
return null;
}
/**
* Simple method to return a list of attendance data.
*
* @return A list of attendance events for a student.
*/
@Override
public List<GenericEntity> getStudentAttendance(final String token, String studentId, String start, String end) {
LOGGER.info("Getting attendance for ID: {}", studentId);
String url = STUDENTS_URL + studentId + ATTENDANCES;
if (start != null && start.length() > 0) {
url += "?eventDate>=" + start;
url += "&eventDate<=" + end;
}
try {
long startTime = System.nanoTime();
List<GenericEntity> attendances = createEntitiesFromAPI(getApiUrl() + url, token, false);
LOGGER.warn("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ API CALL for attendance: {}",
(System.nanoTime() - startTime) * 1.0e-9);
LOGGER.debug(attendances.toString());
return attendances;
} catch (Exception e) {
LOGGER.error("Couldn't retrieve attendance for:" + studentId, e);
return new ArrayList<GenericEntity>();
}
}
private String getUsername() {
return SecurityUtil.getPrincipal().getUsername().replace(" ", "");
}
/**
* Creates a generic entity from an API call
*
* @param url
* @param token
* @param fullEntities
* TODO
* @return the entity
*/
public GenericEntity createEntityFromAPI(String url, String token, boolean fullEntities) {
LOGGER.info("Querying API: {}", url);
String response = restClient.makeJsonRequestWHeaders(url, token, fullEntities);
if (response == null) {
return null;
}
GenericEntity e = gson.fromJson(response, GenericEntity.class);
return e;
}
/**
* Retrieves an entity list from the specified API url
* and instantiates from its JSON representation
*
* @param url
* - the API url to retrieve the entity list JSON string representation
* @param token
* - the principle authentication token
* @param fullEntities
* TODO
*
* @return entityList
* - the generic entity list
*/
public List<GenericEntity> createEntitiesFromAPI(String url, String token, boolean fullEntities) {
List<GenericEntity> entityList = new ArrayList<GenericEntity>();
// Parse JSON
LOGGER.info("Querying API for list: {}", url);
String response = restClient.makeJsonRequestWHeaders(url, token, fullEntities);
if (response == null) {
return null;
}
List<Map> maps = gson.fromJson(response, new ArrayList<Map>().getClass());
if (maps != null) {
for (Map<String, Object> map : maps) {
entityList.add(new GenericEntity(map));
}
}
return entityList;
}
/**
* Returns a list of courses for a given student and query params
* i.e students/{studentId}/studentCourseAssociations/courses?subejctArea="math"&includeFields=
* courseId,courseTitle
*
* @param token
* Securiy token
* @param sectionId
* The student Id
* @param params
* Query params
* @return
*/
@Override
public List<GenericEntity> getCourses(final String token, final String sectionId, Map<String, String> params) {
// get the entities
return createEntitiesFromAPI(getApiUrl() + SECTIONS_URL + sectionId + STUDENT_SECTION_ASSOC
+ STUDENTS + "?optionalFields=transcript", token, false);
}
/**
* Returns a list of student course associations for a
* given student and query params
* i.e students/{studentId}/studentCourseAssociations?courseId={courseId}&includeFields=
* finalLettergrade,studentId
*
* @param token
* Securiy token
* @param studentId
* The student Id
* @param params
* Query params
* @return
*/
@Override
public List<GenericEntity> getStudentTranscriptAssociations(final String token, final String studentId,
Map<String, String> params) {
// get the entities
List<GenericEntity> entities = createEntitiesFromAPI(
buildStudentURI(studentId, STUDENT_TRANSCRIPT_ASSOC, params), token, false);
return entities;
}
/**
* Returns an entity for the given type, id and params
*
* @param token
* Security token
* @param type
* Type of the entity
* @param id
* The id of the entity
* @param params
* param map
* @return
*/
@Override
public GenericEntity getEntity(final String token, final String type, final String id, Map<String, String> params) {
StringBuilder url = new StringBuilder();
// build the url
url.append(getApiUrl());
url.append("/v1/");
url.append(type);
url.append("/");
url.append(id);
// add the query string
if (!params.isEmpty()) {
url.append("?");
url.append(buildQueryString(params));
}
return createEntityFromAPI(url.toString(), token, false);
}
/**
* Returns a list of sections for the given student and params
*
* @param token
* @param studentId
* @param params
* @return
*/
@Override
public List<GenericEntity> getSections(final String token, final String studentId, Map<String, String> params) {
// get the entities
List<GenericEntity> entities = createEntitiesFromAPI(
buildStudentURI(studentId, STUDENT_SECTION_ASSOC + SECTIONS, params), token, false);
return entities;
}
/*
* Retrieves and returns student school associations for a given student.
*/
@Override
public List<GenericEntity> getStudentEnrollment(final String token, GenericEntity student) {
List<String> urls = extractLinksFromEntity(student, STUDENT_SCHOOL_ASSOCIATIONS_LINK);
if (urls == null || urls.isEmpty()) {
return new LinkedList<GenericEntity>();
}
//Retrieve the student school associations from the furst link with STUDENT_SCHOOL_ASSOCIATIONS_LINK
String url = urls.get(0);
List<GenericEntity> studentSchoolAssociations = createEntitiesFromAPI(url, token, false);
for (GenericEntity studentSchoolAssociation : studentSchoolAssociations) {
studentSchoolAssociation = GenericEntityEnhancer.enhanceStudentSchoolAssociation(studentSchoolAssociation);
String schoolUrl = extractLinksFromEntity(studentSchoolAssociation, SCHOOL_LINK).get(0);
//Retrieve the school for the corresponding student school association
GenericEntity school = createEntityFromAPI(schoolUrl, token, false);
studentSchoolAssociation.put(Constants.ATTR_SCHOOL, school);
}
return studentSchoolAssociations;
}
/**
* Returns a list of student grade book entries for a given student and params
*
* @param token
* Security token
* @param studentId
* The student Id
* @param params
* param map
* @return
*/
@Override
public List<GenericEntity> getStudentSectionGradebookEntries(final String token, final String studentId,
Map<String, String> params) {
StringBuilder url = new StringBuilder();
// add the studentId to the param list
params.put(Constants.ATTR_STUDENT_ID, studentId);
// build the url
url.append(getApiUrl());
url.append(STUDENT_SECTION_GRADEBOOK);
// add the query string
if (!params.isEmpty()) {
url.append("?");
url.append(buildQueryString(params));
}
// get the entities
List<GenericEntity> entities = createEntitiesFromAPI(url.toString(), token, false);
return entities;
}
/**
* Builds a student based URI using the given studentId,path and param map
*
* @param studentId
* The studentId
* @param path
* The URI path
* @param params
* The param map
* @return
*/
protected String buildStudentURI(final String studentId, String path, Map<String, String> params) {
StringBuilder url = new StringBuilder();
// build the url
url.append(getApiUrl());
url.append(STUDENTS_URL);
url.append(studentId);
url.append(path);
// add the query string
if (!params.isEmpty()) {
url.append("?");
url.append(buildQueryString(params));
}
return url.toString();
}
/**
* Builds a query string from the given param map
*
* @param params
* The param map
* @return
*/
protected String buildQueryString(Map<String, String> params) {
StringBuilder query = new StringBuilder();
String separator = "";
for (Map.Entry<String, String> e : params.entrySet()) {
query.append(separator);
separator = "&";
query.append(e.getKey());
query.append("=");
query.append(e.getValue());
}
return query.toString();
}
/**
* Extract the link with the given relationship from an entity
*/
private static List<String> extractLinksFromEntity(GenericEntity e, String rel) {
List<String> retVal = new ArrayList<String>();
if (e == null || !e.containsKey(Constants.ATTR_LINKS)) {
return retVal;
}
for (Map link : (List<Map>) (e.get(Constants.ATTR_LINKS))) {
if (link.get(Constants.ATTR_REL).equals(rel)) {
String href = (String) link.get(Constants.ATTR_HREF);
retVal.add(href);
}
}
return retVal;
}
/**
* Getter and Setter used by Spring to instantiate the live/test api class
*
* @return
*/
public RESTClient getRestClient() {
return restClient;
}
public void setRestClient(RESTClient restClient) {
this.restClient = restClient;
}
public String getApiUrl() {
return apiUrl + Constants.API_PREFIX;
}
public void setApiUrl(String apiUrl) {
this.apiUrl = apiUrl;
}
/*
*
* TODO: HARDCODED Token, because lycans server is bad. Change to incoming token
*/
@Override
public String getHeader(String token) {
return restClient.getJsonRequest(portalHeaderUrl + "e88cb6d1-771d-46ac-a207-2e58d7f12196");
}
/*
*
* TODO: HARDCODED Token, because lycans server is bad. Change to incoming token
*/
@Override
public String getFooter(String token) {
return restClient.getJsonRequest(portalFooterUrl + "e88cb6d1-771d-46ac-a207-2e58d7f12196");
}
}
|
package io.spine.tools.protoc;
import com.google.common.truth.Correspondence;
import io.spine.base.EntityColumn;
import io.spine.tools.column.ProjectView;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Method;
import static com.google.common.truth.Truth.assertThat;
import static io.spine.testing.Tests.assertHasPrivateParameterlessCtor;
@SuppressWarnings("DuplicateStringLiteralInspection") // Random duplication.
@DisplayName("`ProtocPlugin`, when generating entity columns, should")
class ColumnsTest {
@Test
@DisplayName("generate a nested `Columns` class with a private c-tor")
void havePrivateCtor() {
assertHasPrivateParameterlessCtor(ProjectView.Columns.class);
}
@Test
@DisplayName("generate a method which returns an `EntityColumn` for each message column")
void generateColumnMethods() {
checkColumn(ProjectView.Columns.projectName(), "project_name");
checkColumn(ProjectView.Columns.status(), "status");
}
@Test
@DisplayName("ignore nested columns")
void ignoreNestedColumns() {
assertDoesNotContainMethod(ProjectView.Columns.class, "assignee");
assertDoesNotContainMethod(ProjectView.Columns.class, "name");
}
private static void checkColumn(EntityColumn column, String expectedName) {
assertThat(column.name()).isEqualTo(expectedName);
}
private static void assertDoesNotContainMethod(Class<?> type, String methodNames) {
Method[] methods = type.getDeclaredMethods();
assertThat(methods).asList()
.comparingElementsUsing(nameCorrespondence())
.doesNotContain(methodNames);
}
private static Correspondence<Method, String> nameCorrespondence() {
return Correspondence.from(ColumnsTest::hasName, "has a name");
}
private static boolean hasName(Method method, String name) {
return name.equals(method.getName());
}
}
|
package com.intellij.openapi.application.impl;
import com.intellij.CommonBundle;
import com.intellij.Patches;
import com.intellij.ide.HackyRepaintManager;
import com.intellij.ide.IdeEventQueue;
import com.intellij.ide.impl.ProjectUtil;
import com.intellij.ide.plugins.IdeaPluginDescriptor;
import com.intellij.ide.plugins.PluginManager;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.*;
import com.intellij.openapi.application.ex.ApplicationEx;
import com.intellij.openapi.application.ex.ApplicationManagerEx;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.components.StateStorage;
import com.intellij.openapi.components.impl.ApplicationPathMacroManager;
import com.intellij.openapi.components.impl.ComponentManagerImpl;
import com.intellij.openapi.components.impl.stores.IApplicationStore;
import com.intellij.openapi.components.impl.stores.IComponentStore;
import com.intellij.openapi.components.impl.stores.StoresFactory;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.extensions.PluginId;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.util.ProgressWindow;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.project.ex.ProjectEx;
import com.intellij.openapi.project.ex.ProjectManagerEx;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.*;
import com.intellij.psi.PsiLock;
import com.intellij.psi.impl.source.PostprocessReformattingAspect;
import com.intellij.util.ConcurrencyUtil;
import com.intellij.util.ReflectionCache;
import com.intellij.util.concurrency.ReentrantWriterPreferenceReadWriteLock;
import com.intellij.util.containers.Stack;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.picocontainer.MutablePicoContainer;
import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.*;
@SuppressWarnings({"AssignmentToStaticFieldFromInstanceMethod"})
public class ApplicationImpl extends ComponentManagerImpl implements ApplicationEx {
private static final Logger LOG = Logger.getInstance("#com.intellij.application.impl.ApplicationImpl");
private ModalityState MODALITY_STATE_NONE = ModalityState.NON_MODAL;
private final ModalityInvokator myInvokator = new ModalityInvokatorImpl();
private final List<ApplicationListener> myListeners = new CopyOnWriteArrayList<ApplicationListener>();
private boolean myTestModeFlag = false;
private boolean myHeadlessMode = false;
private final String myComponentsDescriptor;
private boolean myIsInternal = false;
@NonNls private static final String APPLICATION_LAYER = "application-components";
private final String myName;
private final ReentrantWriterPreferenceReadWriteLock myActionsLock = new ReentrantWriterPreferenceReadWriteLock();
private final Stack<Runnable> myWriteActionsStack = new Stack<Runnable>();
private volatile Thread myExceptionalThreadWithReadAccess = null;
private volatile Runnable myExceptionalThreadWithReadAccessRunnable;
private int myInEditorPaintCounter = 0;
private long myStartTime = 0;
private boolean myDoNotSave = false;
private volatile boolean myIsWaitingForWriteAction = false;
private volatile boolean myDisposeInProgress = false;
private final ExecutorService ourThreadExecutorsService = new ThreadPoolExecutor(
3,
Integer.MAX_VALUE,
30 * 60L,
TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(),
new ThreadFactory() {
public Thread newThread(Runnable r) {
return new Thread(r, "ApplicationImpl pooled thread")
{
public void interrupt() {
if (LOG.isDebugEnabled()) {
LOG.debug("Interrupted worker, will remove from pool");
}
super.interrupt();
}
public void run() {
try {
super.run();
} catch(Throwable t) {
if (LOG.isDebugEnabled()) {
LOG.debug("Worker exits due to exception", t);
}
}
}
};
}
}
);
protected void boostrapPicoContainer() {
super.boostrapPicoContainer();
getPicoContainer().registerComponentImplementation(IComponentStore.class, StoresFactory.getApplicationStoreClass());
getPicoContainer().registerComponentImplementation(ApplicationPathMacroManager.class);
}
@Override
@NotNull
public synchronized IApplicationStore getStateStore() {
return (IApplicationStore)super.getStateStore();
}
public ApplicationImpl(String componentsDescriptor, boolean isInternal, boolean isUnitTestMode, boolean isHeadless, String appName) {
super(null);
if (isInternal || isUnitTestMode) {
Disposer.setDebugMode(true);
}
myStartTime = System.currentTimeMillis();
myName = appName;
ApplicationManagerEx.setApplication(this);
PluginsFacade.INSTANCE = new PluginsFacade() {
public IdeaPluginDescriptor getPlugin(PluginId id) {
return PluginManager.getPlugin(id);
}
public IdeaPluginDescriptor[] getPlugins() {
return PluginManager.getPlugins();
}
};
if (!isUnitTestMode && !isHeadless) {
Toolkit.getDefaultToolkit().getSystemEventQueue().push(IdeEventQueue.getInstance());
if (Patches.SUN_BUG_ID_6209673) {
RepaintManager.setCurrentManager(new HackyRepaintManager());
}
IconLoader.activate();
}
myComponentsDescriptor = componentsDescriptor;
myIsInternal = isInternal;
myTestModeFlag = isUnitTestMode;
myHeadlessMode = isHeadless;
loadApplicationComponents();
if (!isHeadless) {
registerShutdownHook();
}
if (!isUnitTestMode && !isHeadless) {
Disposer.register(this, new Disposable() {
public void dispose() {
}
}, "ui");
}
}
private void registerShutdownHook() {
ShutDownTracker.getInstance(); // Necessary to avoid creating an instance while already shutting down.
ShutDownTracker.getInstance().registerShutdownThread(new Thread(new Runnable() {
public void run() {
if (isDisposed() || isDisposeInProgress()) return;
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
ApplicationManagerEx.setApplication(ApplicationImpl.this);
saveAll();
disposeSelf();
}
});
}
catch (InterruptedException e) {
LOG.error(e);
}
catch (InvocationTargetException e) {
LOG.error(e);
}
}
}));
}
private void disposeSelf() {
Disposer.dispose(this);
Disposer.assertIsEmpty();
}
public String getComponentsDescriptor() {
return myComponentsDescriptor;
}
public String getName() {
return myName;
}
public boolean holdsReadLock() {
return myActionsLock.isReadLockAcquired(Thread.currentThread());
}
@Override
protected void handleInitComponentError(final Throwable ex, final boolean fatal, final String componentClassName) {
if (PluginManager.isPluginClass(componentClassName)) {
LOG.error(ex);
PluginId pluginId = PluginManager.getPluginByClassName(componentClassName);
@NonNls final String errorMessage = "Plugin " + pluginId.getIdString() + " failed to initialize:\n" + ex.getMessage() +
"\nPlease remove the plugin and restart " + ApplicationNamesInfo.getInstance().getFullProductName() + ".";
if (!myHeadlessMode) {
JOptionPane.showMessageDialog(null, errorMessage);
}
else {
//noinspection UseOfSystemOutOrSystemErr
System.out.println(errorMessage);
}
System.exit(1);
}
else if (fatal) {
LOG.error(ex);
@NonNls final String errorMessage = "Fatal error initializing class " + componentClassName + ":\n" +
ex.toString() +
"\nComplete error stacktrace was written to idea.log";
if (!myHeadlessMode) {
JOptionPane.showMessageDialog(null, errorMessage);
}
else {
//noinspection UseOfSystemOutOrSystemErr
System.out.println(errorMessage);
}
}
super.handleInitComponentError(ex, fatal, componentClassName);
}
private void loadApplicationComponents() {
loadComponentsConfiguration(APPLICATION_LAYER, true);
final IdeaPluginDescriptor[] plugins = PluginManager.getPlugins();
for (IdeaPluginDescriptor plugin : plugins) {
if (PluginManager.shouldSkipPlugin(plugin)) continue;
loadComponentsConfiguration(plugin.getAppComponents(), plugin, true);
}
}
protected MutablePicoContainer createPicoContainer() {
return Extensions.getRootArea().getPicoContainer();
}
public boolean isInternal() {
return myIsInternal;
}
public boolean isUnitTestMode() {
return myTestModeFlag;
}
public boolean isHeadlessEnvironment() {
return myHeadlessMode;
}
public IdeaPluginDescriptor getPlugin(PluginId id) {
return PluginsFacade.INSTANCE.getPlugin(id);
}
public IdeaPluginDescriptor[] getPlugins() {
return PluginsFacade.INSTANCE.getPlugins();
}
public Future<?> executeOnPooledThread(final Runnable action) {
return ourThreadExecutorsService.submit(new Runnable() {
public void run() {
try {
action.run();
}
catch (Throwable t) {
LOG.error(t);
}
finally {
Thread.interrupted(); // reset interrupted status
}
}
});
}
private static Thread ourDispatchThread = null;
public boolean isDispatchThread() {
return EventQueue.isDispatchThread();
}
@NotNull
public ModalityInvokator getInvokator() {
return myInvokator;
}
public void invokeLater(final Runnable runnable) {
myInvokator.invokeLater(runnable);
}
public void invokeLater(final Runnable runnable, @NotNull final Condition expired) {
myInvokator.invokeLater(runnable, expired);
}
public void invokeLater(final Runnable runnable, @NotNull final ModalityState state) {
myInvokator.invokeLater(runnable, state);
}
public void invokeLater(final Runnable runnable, @NotNull final ModalityState state, @NotNull final Condition expired) {
myInvokator.invokeLater(runnable, state, expired);
}
public void load(String path) throws IOException, InvalidDataException {
getStateStore().setConfigPath(path);
try {
getStateStore().load();
}
catch (StateStorage.StateStorageException e) {
throw new IOException(e.getMessage());
}
}
public void dispose() {
myDisposeInProgress = true;
Project[] openProjects = ProjectManagerEx.getInstanceEx().getOpenProjects();
final boolean[] canClose = new boolean[]{true};
for (final Project project : openProjects) {
CommandProcessor commandProcessor = CommandProcessor.getInstance();
commandProcessor.executeCommand(project, new Runnable() {
public void run() {
FileDocumentManager.getInstance().saveAllDocuments();
canClose[0] = ProjectUtil.closeProject(project);
}
}, ApplicationBundle.message("command.exit"), null);
if (!canClose[0]) break;
}
if (canClose[0]) {
fireApplicationExiting();
disposeComponents();
}
ourThreadExecutorsService.shutdownNow();
super.dispose();
}
public boolean runProcessWithProgressSynchronously(final Runnable process, String progressTitle, boolean canBeCanceled, Project project) {
assertIsDispatchThread();
if (myExceptionalThreadWithReadAccess != null ||
myExceptionalThreadWithReadAccessRunnable != null ||
ApplicationManager.getApplication().isUnitTestMode() ||
ApplicationManager.getApplication().isHeadlessEnvironment()) {
process.run();
return true;
}
final ProgressWindow progress = new ProgressWindow(canBeCanceled, project);
progress.setTitle(progressTitle);
try {
myExceptionalThreadWithReadAccessRunnable = process;
final boolean[] threadStarted = new boolean[]{false};
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (myExceptionalThreadWithReadAccessRunnable != process) {
LOG.error("myExceptionalThreadWithReadAccessRunnable != process, process = " + myExceptionalThreadWithReadAccessRunnable);
}
executeOnPooledThread(new Runnable() {
public void run() {
if (myExceptionalThreadWithReadAccessRunnable != process) {
LOG.error("myExceptionalThreadWithReadAccessRunnable != process, process = " + myExceptionalThreadWithReadAccessRunnable);
}
myExceptionalThreadWithReadAccess = Thread.currentThread();
boolean old = setExceptionalThreadWithReadAccessFlag(true);
LOG.assertTrue(isReadAccessAllowed());
try {
ProgressManager.getInstance().runProcess(process, progress);
}
catch (ProcessCanceledException e) {
// ok to ignore.
}
finally {
setExceptionalThreadWithReadAccessFlag(old);
}
}
});
threadStarted[0] = true;
}
});
progress.startBlocking();
LOG.assertTrue(threadStarted[0]);
LOG.assertTrue(!progress.isRunning());
}
finally {
myExceptionalThreadWithReadAccess = null;
myExceptionalThreadWithReadAccessRunnable = null;
}
return !progress.isCanceled();
}
public <T> List<Future<T>> invokeAllUnderReadAction(@NotNull Collection<Callable<T>> tasks, final ExecutorService executorService) throws
Throwable {
final List<Callable<T>> newCallables = new ArrayList<Callable<T>>(tasks.size());
for (final Callable<T> task : tasks) {
Callable<T> newCallable = new Callable<T>() {
public T call() throws Exception {
boolean old = setExceptionalThreadWithReadAccessFlag(true);
try {
LOG.assertTrue(isReadAccessAllowed());
return task.call();
}
finally {
setExceptionalThreadWithReadAccessFlag(old);
}
}
};
newCallables.add(newCallable);
}
final Ref<Throwable> exception = new Ref<Throwable>();
List<Future<T>> result = runReadAction(new Computable<List<Future<T>>>() {
public List<Future<T>> compute() {
try {
return ConcurrencyUtil.invokeAll(newCallables, executorService);
}
catch (Throwable throwable) {
exception.set(throwable);
return null;
}
}
});
if (exception.get() != null) throw exception.get();
return result;
}
public void invokeAndWait(Runnable runnable, @NotNull ModalityState modalityState) {
if (isDispatchThread()) {
LOG.error("invokeAndWait should not be called from event queue thread");
runnable.run();
return;
}
Thread currentThread = Thread.currentThread();
if (myExceptionalThreadWithReadAccess == currentThread) { //OK if we're in exceptional thread.
LaterInvocator.invokeAndWait(runnable, modalityState);
return;
}
if (myActionsLock.isReadLockAcquired(currentThread)) {
final Throwable stack = new Throwable();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
LOG.error("Calling invokeAndWait from read-action leads to possible deadlock.", stack);
}
});
if (myIsWaitingForWriteAction) return; // The deadlock indeed. Do not perform request or we'll stall here immediately.
}
LaterInvocator.invokeAndWait(runnable, modalityState);
}
public ModalityState getCurrentModalityState() {
Object[] entities = LaterInvocator.getCurrentModalEntities();
return entities.length > 0 ? new ModalityStateEx(entities) : getNoneModalityState();
}
public ModalityState getModalityStateForComponent(Component c) {
Window window = c instanceof Window ? (Window)c : SwingUtilities.windowForComponent(c);
if (window == null) return getNoneModalityState();
return LaterInvocator.modalityStateForWindow(window);
}
public ModalityState getDefaultModalityState() {
if (EventQueue.isDispatchThread()) {
return getCurrentModalityState();
}
else {
ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator();
if (progress != null) {
return progress.getModalityState();
}
else {
return getNoneModalityState();
}
}
}
public ModalityState getNoneModalityState() {
return MODALITY_STATE_NONE;
}
public long getStartTime() {
return myStartTime;
}
public long getIdleTime() {
return IdeEventQueue.getInstance().getIdleTime();
}
public void exit() {
exit(false);
}
public void exit(final boolean force) {
Runnable runnable = new Runnable() {
public void run() {
if (!force) {
if (!showConfirmation()) {
saveAll();
return;
}
}
saveAll();
if (!canExit()) return;
disposeSelf();
System.exit(0);
}
};
if (!isDispatchThread()) {
invokeLater(runnable, ModalityState.NON_MODAL);
}
else {
runnable.run();
}
}
private static boolean showConfirmation() {
final ConfirmExitDialog confirmExitDialog = new ConfirmExitDialog();
if (confirmExitDialog.isToBeShown()) {
confirmExitDialog.show();
if (!confirmExitDialog.isOK()) {
return false;
}
}
return true;
}
private boolean canExit() {
for (ApplicationListener applicationListener : myListeners) {
if (!applicationListener.canExitApplication()) {
return false;
}
}
ProjectManagerEx projectManager = (ProjectManagerEx)ProjectManager.getInstance();
Project[] projects = projectManager.getOpenProjects();
for (Project project : projects) {
if (!projectManager.canClose(project)) {
return false;
}
}
return true;
}
public void runReadAction(final Runnable action) {
/** if we are inside read action, do not try to acquire read lock again since it will deadlock if there is a pending writeAction
* see {@link com.intellij.util.concurrency.ReentrantWriterPreferenceReadWriteLock#allowReader()} */
boolean mustAcquire = !isReadAccessAllowed();
if (mustAcquire) {
LOG.assertTrue(!Thread.holdsLock(PsiLock.LOCK), "Thread must not hold PsiLock while performing readAction");
try {
myActionsLock.readLock().acquire();
}
catch (InterruptedException e) {
throw new RuntimeInterruptedException(e);
}
}
try {
action.run();
}
finally {
if (mustAcquire) {
myActionsLock.readLock().release();
}
}
}
private static final ThreadLocal<Boolean> exceptionalThreadWithReadAccessFlag = new ThreadLocal<Boolean>();
private static boolean isExceptionalThreadWithReadAccess() {
Boolean flag = exceptionalThreadWithReadAccessFlag.get();
return flag != null && flag.booleanValue();
}
public static boolean setExceptionalThreadWithReadAccessFlag(boolean flag) {
boolean old = isExceptionalThreadWithReadAccess();
if (flag) {
exceptionalThreadWithReadAccessFlag.set(true);
}
else {
exceptionalThreadWithReadAccessFlag.remove();
}
return old;
}
public <T> T runReadAction(final Computable<T> computation) {
final Ref<T> ref = Ref.create(null);
runReadAction(new Runnable() {
public void run() {
ref.set(computation.compute());
}
});
return ref.get();
}
public void runWriteAction(final Runnable action) {
assertCanRunWriteAction();
fireBeforeWriteActionStart(action);
LOG.assertTrue(myActionsLock.isWriteLockAcquired(Thread.currentThread()) || !Thread.holdsLock(PsiLock.LOCK), "Thread must not hold PsiLock while performing writeAction");
myIsWaitingForWriteAction = true;
try {
myActionsLock.writeLock().acquire();
}
catch (InterruptedException e) {
throw new RuntimeInterruptedException(e);
}
finally {
myIsWaitingForWriteAction = false;
}
fireWriteActionStarted(action);
try {
synchronized (myWriteActionsStack) {
myWriteActionsStack.push(action);
}
final Project project = CommandProcessor.getInstance().getCurrentCommandProject();
if(project != null/* && !(action instanceof PsiExternalChangeAction)*/) {
// run postprocess formatting inside commands only
PostprocessReformattingAspect.getInstance(project).postponeFormattingInside(new Computable<Object>() {
public Object compute() {
action.run();
return null;
}
});
}
else action.run();
}
finally {
synchronized (myWriteActionsStack) {
myWriteActionsStack.pop();
}
fireWriteActionFinished(action);
myActionsLock.writeLock().release();
}
}
public <T> T runWriteAction(final Computable<T> computation) {
final Ref<T> ref = Ref.create(null);
runWriteAction(new Runnable() {
public void run() {
ref.set(computation.compute());
}
});
return ref.get();
}
public Object getCurrentWriteAction(Class actionClass) {
synchronized (myWriteActionsStack) {
for (int i = myWriteActionsStack.size() - 1; i >= 0; i
Runnable action = myWriteActionsStack.get(i);
if (actionClass == null || ReflectionCache.isAssignable(actionClass, action.getClass())) return action;
}
}
return null;
}
public void assertReadAccessAllowed() {
if (myTestModeFlag || myHeadlessMode) return;
if (!isReadAccessAllowed()) {
LOG.error(
"Read access is allowed from event dispatch thread or inside read-action only (see com.intellij.openapi.application.Application.runReadAction())",
"Current thread: " + describe(Thread.currentThread()), "Our dispatch thread:" + describe(ourDispatchThread),
"SystemEventQueueThread: " + describe(getEventQueueThread()));
}
}
@NonNls
private static String describe(Thread o) {
if (o == null) return "null";
return o.toString() + " " + System.identityHashCode(o);
}
@Nullable
private static Thread getEventQueueThread() {
EventQueue eventQueue = Toolkit.getDefaultToolkit().getSystemEventQueue();
try {
Method method = EventQueue.class.getDeclaredMethod("getDispatchThread");
method.setAccessible(true);
return (Thread)method.invoke(eventQueue);
}
catch (Exception e1) {
}
return null;
}
public boolean isReadAccessAllowed() {
Thread currentThread = Thread.currentThread();
if (ourDispatchThread == currentThread) {
//TODO!
/*
IdeEventQueue eventQueue = IdeEventQueue.getInstance(); //TODO: cache?
if (!eventQueue.isInInputEvent() && !LaterInvocator.isInMyRunnable() && !myInEditorPaint) {
LOG.error("Read access from event dispatch thread is allowed only inside input event processing or LaterInvocator.invokeLater");
}
*/
return true;
}
if (isExceptionalThreadWithReadAccess()) return true;
if (myActionsLock.isReadLockAcquired(currentThread)) return true;
if (myActionsLock.isWriteLockAcquired(currentThread)) return true;
return isDispatchThread();
}
public void assertReadAccessToDocumentsAllowed() {
/* TODO
Thread currentThread = Thread.currentThread();
if (ourDispatchThread != currentThread) {
if (myExceptionalThreadWithReadAccess == currentThread) return;
if (myActionsLock.isReadLockAcquired(currentThread)) return;
if (myActionsLock.isWriteLockAcquired(currentThread)) return;
if (isDispatchThread(currentThread)) return;
LOG.error(
"Read access is allowed from event dispatch thread or inside read-action only (see com.intellij.openapi.application.Application.runReadAction())");
}
*/
}
private void assertCanRunWriteAction() {
assertIsDispatchThread("Write access is allowed from event dispatch thread only");
}
public void assertIsDispatchThread() {
assertIsDispatchThread("Access is allowed from event dispatch thread only.");
}
private void assertIsDispatchThread(String message) {
if (myTestModeFlag || myHeadlessMode) return;
final Thread currentThread = Thread.currentThread();
if (ourDispatchThread == currentThread) return;
if (EventQueue.isDispatchThread()) {
ourDispatchThread = currentThread;
}
if (ourDispatchThread == currentThread) return;
LOG.error(message,
"Current thread: " + describe(Thread.currentThread()),
"Our dispatch thread:" + describe(ourDispatchThread),
"SystemEventQueueThread: " + describe(getEventQueueThread()));
}
public void assertWriteAccessAllowed() {
LOG.assertTrue(isWriteAccessAllowed(),
"Write access is allowed inside write-action only (see com.intellij.openapi.application.Application.runWriteAction())");
}
public boolean isWriteAccessAllowed() {
return myActionsLock.isWriteLockAcquired(Thread.currentThread());
}
public void editorPaintStart() {
myInEditorPaintCounter++;
}
public void editorPaintFinish() {
myInEditorPaintCounter
LOG.assertTrue(myInEditorPaintCounter >= 0);
}
public void addApplicationListener(ApplicationListener l) {
myListeners.add(l);
}
public void removeApplicationListener(ApplicationListener l) {
myListeners.remove(l);
}
private void fireApplicationExiting() {
for (ApplicationListener applicationListener : myListeners) {
applicationListener.applicationExiting();
}
}
private void fireBeforeWriteActionStart(Runnable action) {
for (ApplicationListener listener : myListeners) {
listener.beforeWriteActionStart(action);
}
}
private void fireWriteActionStarted(Runnable action) {
for (ApplicationListener listener : myListeners) {
listener.writeActionStarted(action);
}
}
private void fireWriteActionFinished(Runnable action) {
for (ApplicationListener listener : myListeners) {
listener.writeActionFinished(action);
}
}
public void saveSettings() {
if (myDoNotSave) return;
try {
doSave();
}
catch (final Throwable ex) {
LOG.info("Saving application settings failed", ex);
invokeLater(new Runnable() {
public void run() {
Messages.showMessageDialog(ApplicationBundle.message("application.save.settings.error", ex.getLocalizedMessage()),
CommonBundle.getErrorTitle(), Messages.getErrorIcon());
}
});
}
}
public void saveAll() {
if (myDoNotSave || isUnitTestMode() || isHeadlessEnvironment()) return;
FileDocumentManager.getInstance().saveAllDocuments();
Project[] openProjects = ProjectManager.getInstance().getOpenProjects();
for (Project openProject : openProjects) {
ProjectEx project = (ProjectEx)openProject;
project.save();
}
saveSettings();
}
public void doNotSave() {
myDoNotSave = true;
}
public boolean isDoNotSave() {
return myDoNotSave;
}
public <T> T[] getExtensions(final ExtensionPointName<T> extensionPointName) {
return Extensions.getRootArea().getExtensionPoint(extensionPointName).getExtensions();
}
public boolean isDisposeInProgress() {
return myDisposeInProgress;
}
}
|
package com.intellij.psi.impl.source.javadoc;
import com.intellij.codeInsight.daemon.JavaErrorMessages;
import com.intellij.psi.*;
import com.intellij.psi.javadoc.JavadocTagInfo;
import com.intellij.psi.javadoc.PsiDocTagValue;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.ArrayUtil;
import org.jetbrains.annotations.NonNls;
/**
* @author mike
*/
class ExceptionTagInfo implements JavadocTagInfo {
private String myName;
public ExceptionTagInfo(@NonNls String name) {
myName = name;
}
public String checkTagValue(PsiDocTagValue value) {
if (value == null) return JavaErrorMessages.message("javadoc.exception.tag.exception.class.expected");
final PsiElement firstChild = value.getFirstChild();
if (firstChild == null) return JavaErrorMessages.message("javadoc.exception.tag.exception.class.expected");
final PsiElement psiElement = firstChild.getFirstChild();
if (!(psiElement instanceof PsiJavaCodeReferenceElement)) {
return JavaErrorMessages.message("javadoc.exception.tag.wrong.tag.value");
}
final PsiJavaCodeReferenceElement ref = ((PsiJavaCodeReferenceElement)psiElement);
final PsiElement element = ref.resolve();
if (!(element instanceof PsiClass)) return null;
final PsiClass exceptionClass = (PsiClass)element;
final PsiClass throwable = value.getManager().findClass("java.lang.Throwable", value.getResolveScope());
if (throwable != null) {
if (!exceptionClass.equals(throwable) && !exceptionClass.isInheritor(throwable, true)) {
return JavaErrorMessages.message("javadoc.exception.tag.class.is.not.throwable", exceptionClass.getQualifiedName());
}
}
final PsiClass runtimeException = value.getManager().findClass("java.lang.RuntimeException", value.getResolveScope());
if (runtimeException != null &&
(exceptionClass.isInheritor(runtimeException, true) || exceptionClass.equals(runtimeException))) {
return null;
}
final PsiClass errorException = value.getManager().findClass("java.lang.Error", value.getResolveScope());
if (errorException != null &&
(exceptionClass.isInheritor(errorException, true) || exceptionClass.equals(errorException))) {
return null;
}
PsiMethod method = PsiTreeUtil.getParentOfType(value, PsiMethod.class);
if (method == null) {
return null;
}
final PsiClassType[] references = method.getThrowsList().getReferencedTypes();
for (PsiClassType reference : references) {
final PsiClass psiClass = reference.resolve();
if (psiClass == null) continue;
if (exceptionClass.isInheritor(psiClass, true) || exceptionClass.equals(psiClass)) return null;
}
return JavaErrorMessages.message("javadoc.exception.tag.exception.is.not.thrown", exceptionClass.getName(), method.getName());
}
public String getName() {
return myName;
}
public Object[] getPossibleValues(PsiElement context, PsiElement place, String prefix) {
return ArrayUtil.EMPTY_OBJECT_ARRAY;
}
public PsiReference getReference(PsiDocTagValue value) {
return null;
}
public boolean isValidInContext(PsiElement element) {
if (!(element instanceof PsiMethod)) return false;
return true;
}
public boolean isInline() {
return false;
}
}
|
package org.pml.debrief.KMLTransfer;
import java.awt.geom.Point2D;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Vector;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import MWC.GenericData.HiResDate;
import MWC.GenericData.TimePeriod;
import MWC.GenericData.WorldArea;
import MWC.GenericData.WorldLocation;
public class KMLTX_Presenter
{
private final static String filePath = "/Users/ianmayo/Downloads/portland2";
private static final String DATABASE_ROOT = "jdbc:postgresql://127.0.0.1/ais";
private static Connection _conn;
private static PreparedStatement sql;
private static WorldArea limits;
private static HashMap<Integer, Vector<NumberedTimePeriod>> map;
/**
* @param args
*/
public static void main(String[] args)
{
map = new HashMap<Integer, Vector<NumberedTimePeriod>>();
try
{
WorldLocation tl = new WorldLocation(50.863, -2.5, 0d);
WorldLocation br = new WorldLocation(50.45, -0.4, 0d);
limits = new WorldArea(tl, br);
// check we have data
File sourceP = new File(filePath);
if (!sourceP.exists())
{
throw new RuntimeException("data directory not found");
}
// check we have a database
connectToDatabase();
// sort out a helper to read the XML
MyHandler handler = new MyHandler()
{
public void writeThis(String name2, Date date2, Point2D coords2,
Integer index2, Double course2, Double speed2)
{
try
{
writeThisToDb(name2, date2, coords2, index2, course2, speed2);
}
catch (SQLException e)
{
e.printStackTrace();
System.exit(1);
}
}
};
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
// XMLReader parser = XMLReaderFactory
// .createXMLReader("org.apache.xerces.parsers.SAXParser");
// parser.setContentHandler(saxer);
// see about format
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// String str =
// "insert into tracks (latval, longval) values (32.3, 22.4);";
// Statement st = _conn.createStatement();
// st.execute(str);
// System.exit(0);
String query = "insert into tracks3 (dateval, nameval, latval, longval,"
+ " courseval, speedval, mmsi, dataset) VALUES (?, ?, ?, ?, ?, ?, ?, ?);";
System.out.println("query will be:" + query);
sql = _conn.prepareStatement(query);
String query2 = "insert into datasets (ivalue, starttime, endtime, mmsi,"
+ " length) VALUES (?, ?, ?, ?, ?);";
System.out.println("query2 will be:" + query2);
PreparedStatement dataquery = _conn.prepareStatement(query2);
// start looping through files
File[] fList = sourceP.listFiles();
int len = fList.length;
for (int i = 0; i < len; i++)
{
File thisF = fList[i];
// check it's not the duff file
if(thisF.getName().equals(".DS_Store"))
continue;
// unzip it to get the KML
ZipFile zip = new ZipFile(thisF);
ZipEntry contents = zip.entries().nextElement();
InputStream is = zip.getInputStream(contents);
// sort out the filename snap_2011-04-11_08/32/00
String[] legs = thisF.getName().split("_");
String timeStr = legs[2].substring(0, 8);
Date theDate = df.parse(legs[1] + " " + timeStr);
handler.setDate(theDate);
files++;
System.err.println("==" + i + " of " + fList.length + " at:"
+ new Date());
// right, go for it
processThisFile(is, parser, handler);
}
System.out.println("output " + places + " for " + files + " files");
// now output the datasets
outputDatesets(map, dataquery);
}
catch (RuntimeException re)
{
re.printStackTrace();
}
catch (ZipException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (SAXException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ParseException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ParserConfigurationException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
// close the databse
if (_conn != null)
{
try
{
System.out.println("closing database");
_conn.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
}
private static void outputDatesets(
HashMap<Integer, Vector<NumberedTimePeriod>> map2,
PreparedStatement dataquery) throws SQLException
{
Iterator<Integer> iter = map2.keySet().iterator();
while (iter.hasNext())
{
Integer integer = (Integer) iter.next();
Vector<NumberedTimePeriod> periods = map2.get(integer);
Iterator<NumberedTimePeriod> pIter = periods.iterator();
while (pIter.hasNext())
{
KMLTX_Presenter.NumberedTimePeriod thisP = (KMLTX_Presenter.NumberedTimePeriod) pIter
.next();
dataquery.setInt(1, thisP.getIndex());
dataquery.setTimestamp(2, new Timestamp(thisP.getStartDTG().getDate().getTime()));
dataquery.setTimestamp(3, new Timestamp(thisP.getEndDTG().getDate().getTime()));
dataquery.setInt(4, integer);
dataquery.setInt(5, thisP.getNumPoints());
dataquery.executeUpdate();
}
}
}
protected static void writeThisToDb(String name2, Date date2,
Point2D coords2, Integer index2, Double course2, Double speed2)
throws SQLException
{
// are we in zone?
WorldLocation loc = new WorldLocation(coords2.getY(), coords2.getX(), 0d);
if (!limits.contains(loc))
return;
// find out if this is a new or old data track
int thisDataIndex = getIndexFor(name2, index2, date2);
// String query =
// "insert into AIS_tracks (daveVal, name, latVal, longVal, courseVal, speedVal) VALUES (";
sql.setTimestamp(1, new java.sql.Timestamp(date2.getTime()));
sql.setString(2, name2);
sql.setDouble(3, coords2.getY());
sql.setDouble(4, coords2.getX());
sql.setDouble(5, course2);
sql.setDouble(6, speed2);
sql.setInt(7, index2);
sql.setInt(8, thisDataIndex);
sql.executeUpdate();
places++;
}
private static class NumberedTimePeriod extends TimePeriod.BaseTimePeriod
{
private static final long serialVersionUID = 1L;
static int ctr = 1;
private int _myIndex;
private int _numPoints = 0;
public NumberedTimePeriod(HiResDate startD, HiResDate endD)
{
super(startD, endD);
_myIndex = ctr++;
}
public void increment()
{
_numPoints ++;
}
public int getNumPoints()
{
return _numPoints;
}
public int getIndex()
{
return _myIndex;
}
}
private static int getIndexFor(String name2, Integer mmsi, Date date2)
{
Vector<NumberedTimePeriod> periods = map.get(mmsi);
if (periods == null)
{
periods = new Vector<NumberedTimePeriod>();
map.put(mmsi, periods);
}
NumberedTimePeriod timeP = null;
if (periods.size() > 0)
{
timeP = periods.lastElement();
Date lastTime = timeP.getEndDTG().getDate();
// is it too far back?
long delta = lastTime.getTime() - date2.getTime();
if (delta < 1000 * 60 * 15)
{
// cool, in period. extend it
timeP.setEndDTG(new HiResDate(date2));
}
else
{
// naah, too late. put it in another time period
timeP = null;
}
}
if (timeP == null)
{
// ok, create a new period for this time
timeP = new NumberedTimePeriod(new HiResDate(date2), new HiResDate(date2));
periods.add(timeP);
}
// increment his counter
timeP.increment();
return timeP.getIndex();
}
private static void connectToDatabase()
{
// driver first
try
{
Class.forName("org.postgresql.Driver");
}
catch (ClassNotFoundException e)
{
throw new RuntimeException("Failed to load database driver");
}
try
{
String url = DATABASE_ROOT;
final String password = System.getenv("pg_pwd");
if (password == null)
throw new RuntimeException("database password missing");
_conn = DriverManager.getConnection(url, "postgres", password);
// also tell the connection about our new custom data types
((org.postgresql.PGConnection) _conn).addDataType("geometry",
org.postgis.PGgeometry.class);
((org.postgresql.PGConnection) _conn).addDataType("box3d",
org.postgis.PGbox3d.class);
}
catch (SQLException e)
{
throw new RuntimeException("failed to create connection");
}
}
public static int places = 0;
public static int files = 0;
protected static abstract class MyHandler extends DefaultHandler
{
private String name;
private Point2D coords;
private Double course;
private Double speed;
private Integer mmsi;
private Date date;
@Override
public void endElement(String arg0, String arg1, String arg2)
throws SAXException
{
super.endElement(arg0, arg1, arg2);
// ok, check our datai
if (name != null)
{
if (coords != null)
{
if (course != null)
{
if (mmsi != null)
{
writeThis(name, date, coords, mmsi, course, speed);
name = null;
coords = null;
course = null;
speed = null;
mmsi = null;
}
}
}
}
}
abstract public void writeThis(String name2, Date date2, Point2D coords2,
Integer index2, Double course2, Double speed2);
public void setDate(Date finalDate)
{
date = finalDate;
}
@Override
public void characters(final char[] ch, final int start, final int length)
throws SAXException
{
String data = "";
if (isName)
{
String name = new String(ch, start, length);
if (name.length() > 0)
{
if (name.equals("MarineTraffic"))
{
// just ignore it
}
else
{
this.name = name;
}
}
}
else if (isCoords)
{
try
{
data = new String(ch, start, length);
String[] split = data.split(",");
double longVal = Double.valueOf(split[0]);
double latVal = Double.valueOf(split[1]);
coords = new Point2D.Double(longVal, latVal);
}
catch (NumberFormatException e)
{
System.out.println("number format prob reading pos for " + name);
}
catch (java.lang.ArrayIndexOutOfBoundsException aw)
{
System.out.println("array index prob reading pos for " + name
+ " from " + data);
}
}
else if (isDesc)
{
String details = "";
try
{
details = new String(ch, start, length);
// start off with course & speed
int startStr = details.indexOf(" ") + 6;
int endStr = details.indexOf("°");
if (endStr == -1)
return;
String subStr = details.substring(startStr, endStr);
String[] components = subStr.split(" ");
course = Double.valueOf(components[3]);
speed = Double.valueOf(components[0]);
// now the mmsi
startStr = details.indexOf("mmsi=");
if (startStr == -1)
return;
endStr = details.indexOf("\"", startStr);
subStr = details.substring(startStr + "mmsi=".length(), endStr);
mmsi = Integer.valueOf(subStr);
}
catch (java.lang.StringIndexOutOfBoundsException aw)
{
System.out.println("prob reading desc for " + name);
}
}
}
boolean isName = false;
boolean isCoords = false;
boolean isDesc = false;
boolean foundPlacemark = false;
@Override
public void startElement(String nsURI, String strippedName, String tagName,
Attributes attributes) throws SAXException
{
isName = isCoords = isDesc = false;
if (tagName.equals("Placemark"))
{
foundPlacemark = true;
return;
}
if (foundPlacemark)
{
if (tagName.equals("name"))
{
isName = true;
// ok - go for new placemark
places++;
}
else if (tagName.equals("coordinates"))
{
isCoords = true;
}
else if (tagName.equals("description"))
{
isDesc = true;
}
}
}
}
private static void processThisFile(InputStream is, SAXParser parser,
DefaultHandler handler) throws ZipException, IOException, SAXException
{
parser.parse(is, handler);
// process the KML
// loop through the observations
// create position for this obs
// extract the other fields
// add this record
}
}
|
package io.vertx.it.plugin;
import io.vertx.it.plugin.win.WindowsDestroyer;
import org.apache.commons.exec.OS;
import org.apache.commons.exec.ProcessDestroyer;
import java.util.ArrayList;
import java.util.List;
class Destroyer implements ProcessDestroyer {
public static final Destroyer INSTANCE = new Destroyer();
private List<Process> processes = new ArrayList<>();
private Destroyer() {
// Avoid direct instantiation.
}
public synchronized void killThemAll() {
if (processes.size() <= 0) {
return;
}
System.out.println(processes.size() + " processes need to be destroyed");
List<Process> copy = new ArrayList<>(processes);
for (Process p : copy) {
if (OS.isFamilyWindows()) {
// Well windows...
// Destroying the process won't kill children process,
// so we need another dirty way
killWindowsProcessAndChildren(p);
} else {
p.destroyForcibly();
}
processes.remove(p);
System.out.println("Process destroyed");
}
}
private void killWindowsProcessAndChildren(Process p) {
WindowsDestroyer.destroy(p);
}
/**
* Returns <code>true</code> if the specified
* {@link Process} was
* successfully added to the list of processes to be destroy.
*
* @param process the process to add
* @return <code>true</code> if the specified
* {@link Process} was
* successfully added
*/
@Override
public synchronized boolean add(Process process) {
return processes.add(process);
}
/**
* Returns <code>true</code> if the specified
* {@link Process} was
* successfully removed from the list of processes to be destroy.
*
* @param process the process to remove
* @return <code>true</code> if the specified
* {@link Process} was
* successfully removed
*/
@Override
public synchronized boolean remove(Process process) {
return processes.remove(process);
}
/**
* Returns the number of registered processes.
*
* @return the number of register process
*/
@Override
public synchronized int size() {
return processes.size();
}
}
|
package org.archive.wayback.requestparser;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.archive.wayback.core.WaybackRequest;
import org.archive.wayback.util.Timestamp;
import org.archive.wayback.util.url.UrlOperations;
import org.archive.wayback.webapp.AccessPoint;
/**
* RequestParser which attempts to extract data from an HTML form, that is, from
* HTTP GET request arguments
*
* @author brad
* @version $Date$, $Revision$
*/
public class FormRequestParser extends WrappedRequestParser {
/**
* @param wrapped the BaseRequestParser being wrapped
*/
public FormRequestParser(BaseRequestParser wrapped) {
super(wrapped);
}
/**
* CGI argument name for Submit button...
*/
private final static String SUBMIT_BUTTON = "Submit";
/*
* Stuff whatever GET/POST arguments are sent up into the returned
* WaybackRequest object, except the Submit button argument.
*/
public WaybackRequest parse(HttpServletRequest httpRequest,
AccessPoint accessPoint) {
WaybackRequest wbRequest = null;
@SuppressWarnings("unchecked")
Map<String,String[]> queryMap = httpRequest.getParameterMap();
if(queryMap.size() > 0) {
wbRequest = new WaybackRequest();
String base = accessPoint.translateRequestPath(httpRequest);
if(base.startsWith(REPLAY_BASE)) {
wbRequest.setReplayRequest();
} else if(base.startsWith(QUERY_BASE)) {
wbRequest.setCaptureQueryRequest();
} else if(base.startsWith(XQUERY_BASE)){
wbRequest.setCaptureQueryRequest();
wbRequest.setXMLMode(true);
} else {
return null;
}
wbRequest.setResultsPerPage(getMaxRecords());
Set<String> keys = queryMap.keySet();
Iterator<String> itr = keys.iterator();
while(itr.hasNext()) {
String key = itr.next();
if(key.equals(SUBMIT_BUTTON)) {
continue;
}
// just jam everything else in:
String val = AccessPoint.getMapParam(queryMap,key);
if(key.equals(WaybackRequest.REQUEST_URL)) {
String scheme = UrlOperations.urlToScheme(val);
if(scheme == null) {
val = UrlOperations.HTTP_SCHEME + val;
}
}
wbRequest.put(key,val);
}
String partialTS = wbRequest.getReplayTimestamp();
if(partialTS != null) {
if(wbRequest.getStartTimestamp()== null) {
String startTS = Timestamp.parseBefore(partialTS).getDateStr();
wbRequest.setStartTimestamp(startTS);
}
if(wbRequest.getEndTimestamp() == null) {
String endTS = Timestamp.parseAfter(partialTS).getDateStr();
wbRequest.setEndTimestamp(endTS);
}
} else {
if(wbRequest.getStartTimestamp()== null) {
wbRequest.setStartTimestamp(getEarliestTimestamp());
}
if(wbRequest.getEndTimestamp() == null) {
wbRequest.setEndTimestamp(getLatestTimestamp());
}
}
}
return wbRequest;
}
}
|
package org.decimal4j.jmh;
import java.io.BufferedReader;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Collection;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.results.RunResult;
import org.openjdk.jmh.results.format.ResultFormat;
import org.openjdk.jmh.results.format.ResultFormatFactory;
import org.openjdk.jmh.results.format.ResultFormatType;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import org.openjdk.jmh.runner.options.TimeValue;
public class JmhRunner {
private final Class<?> benchmarkClass;
public JmhRunner(Class<?> benchmarkClass) {
if (benchmarkClass == null) {
throw new NullPointerException("benchmarkClass cannot be null");
}
this.benchmarkClass = benchmarkClass;
}
public void run() throws RunnerException, IOException, InterruptedException {
final File jmhJar = findJmhJar();
final Process process = Runtime.getRuntime().exec("java -cp " + jmhJar.getAbsolutePath() + " " + JmhRunner.class.getName() + " " + benchmarkClass.getName());
final Reader r1 = new Reader(process.getInputStream());
final Reader r2 = new Reader(process.getErrorStream());
r1.start();
r2.start();
if (0 != process.waitFor()) {
System.err.println("FAILED");
}
r1.await();
r2.await();
}
private final File findJmhJar() {
final File libDir = new File("./build/libs");
final File[] files = libDir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith("-jmh.jar");
}
});
if (files != null && files.length == 1) {
return files[0];
}
throw new IllegalStateException("no jmh jar file found in '" + libDir.getAbsolutePath() + "', hint: run 'gradle jmhJar' first");
}
private static class Reader extends Thread {
private final AtomicBoolean isReading = new AtomicBoolean(false);
private final BufferedReader reader;
public Reader(final InputStream inputStream) {
this.reader = new BufferedReader(new InputStreamReader(inputStream));
}
@Override
public void run() {
try {
String line = reader.readLine();
while (line != null && !isInterrupted()) {
isReading.set(true);
System.out.println(line);
line = reader.readLine();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void await() throws InterruptedException {
while (isReading.get()) {
isReading.set(false);
Thread.sleep(1000);
}
interrupt();
}
}
private static String askRunAll() throws IOException {
System.out.print("Do you want to run all jmh benchmarks? (can take approx. 3h!)[y/n]");
final char ch = (char)System.in.read();
System.out.println();
if (Character.toLowerCase(ch) == 'y') {
return ".*";
}
System.out.println("aborted.");
System.exit(1);
return null;//should not get here
}
public static void main(String[] args) throws RunnerException, IOException {
final String include;
if (args.length == 0) {
include = askRunAll();
} else {
include = args[0];
}
final Options opt = new OptionsBuilder()
.include(include)
.mode(Mode.Throughput)
.measurementIterations(3)
.measurementBatchSize(1)
.measurementTime(TimeValue.milliseconds(1000))
.forks(1)
.timeUnit(TimeUnit.MICROSECONDS)
.warmupIterations(3)
.warmupTime(TimeValue.milliseconds(1000))
.build();
final Collection<RunResult> runResult = new Runner(opt).run();
System.out.flush();
final ResultFormat resultFormat = ResultFormatFactory.getInstance(ResultFormatType.CSV, System.out);
resultFormat.writeOut(runResult);
System.out.flush();
}
}
|
package kodkod.engine.ltl2fol;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import kodkod.ast.BinaryTempFormula;
import kodkod.ast.ConstantFormula;
import kodkod.ast.Expression;
import kodkod.ast.Formula;
import kodkod.ast.Node;
import kodkod.ast.Relation;
import kodkod.ast.RelationPredicate;
import kodkod.ast.TempExpression;
import kodkod.ast.UnaryTempFormula;
import kodkod.ast.VarRelation;
import kodkod.ast.Variable;
import kodkod.ast.operator.TemporalOperator;
import kodkod.ast.visitor.AbstractDetector;
import kodkod.ast.visitor.AbstractReplacer;
/**
* @author Eduardo Pessoa, Nuno Macedo
*
*/
public class AddTimeToFormula extends AbstractReplacer {
private int needToDeclarePostR;
private int numberMaxOfnestedPlicas;
private int numberMaxPlicasInit;;
private Relation next;
private Relation Time;
private Relation init;
private Relation end;
private Formula infinite;
private Map<String,Relation> relations;
/**
* The relations resulting from the extension of the variable relations.
* @return
*/
public Map<String,Relation> getExtendedVarRelations() {
return relations;
}
public AddTimeToFormula(Relation time, Relation next, Relation init, Relation end, Formula infinite) {
super(new HashSet<Node>());
this.relations = new HashMap<String,Relation>();
this.Time = time;
this.next = next;
this.init = init;
this.end = end;
this.infinite = infinite;
this.initializePostVariables();
pushVariable();
}
public Formula convert(Formula f){
Formula result = f.accept(this);
if (needToDeclarePostR > 0)
return forceNextExists(init, needToDeclarePostR).and(result);
else
return result;
}
@Override
public Expression visit(Relation relation) {
if (isTemporal(relation))
return this.getRelation((VarRelation) relation).join(this.getVariable());
else return relation;
}
@Override
public Formula visit(RelationPredicate relationPredicate) {
if (isTemporal(relationPredicate))
return relationPredicate.toConstraints().accept(this);
else return relationPredicate;
}
@Override
public Formula visit(UnaryTempFormula unaryTempFormula) {
int temp = this.needToDeclarePostR;
int tempI = this.numberMaxOfnestedPlicas;
this.initializePostVariables();
this.pushOperator(unaryTempFormula.op());
this.pushVariable();
Formula e = unaryTempFormula.formula().accept(this);
Formula rt = this.getQuantifier(this.getOperator(), e, needToDeclarePostR);
this.numberMaxOfnestedPlicas = tempI;
this.needToDeclarePostR = temp;
this.popOperator();
this.popVariable();
return rt;
}
@Override
public Formula visit(BinaryTempFormula binaryTempFormula) {
this.pushOperator(binaryTempFormula.op());
this.pushVariable();
int temp, tempI, quantificationPostRight, quantificationPostLeft, quantificationPostLeftf;
temp = this.needToDeclarePostR;
tempI = this.numberMaxOfnestedPlicas;
this.initializePostVariables();
Formula rt, left, right;
switch(binaryTempFormula.op()) {
case UNTIL:
right = binaryTempFormula.right().accept(this);
quantificationPostRight = this.needToDeclarePostR;
this.pushVariable();
this.initializePostVariables();
left = binaryTempFormula.left().accept(this);
quantificationPostLeftf = this.needToDeclarePostR;
rt = this.getQuantifierUntil(left, right, quantificationPostLeftf, quantificationPostRight);
this.popVariable();
break;
case RELEASE:
Formula rightAlways = binaryTempFormula.right().accept(this);
this.pushVariable();
this.initializePostVariables();
left = binaryTempFormula.left().accept(this);
quantificationPostLeft = this.needToDeclarePostR;
this.initializePostVariables();
this.pushVariable();
right = binaryTempFormula.right().accept(this);
quantificationPostRight = this.needToDeclarePostR;
rt = this.getQuantifierRelease(rightAlways, left, right, quantificationPostLeft, quantificationPostRight);
this.popVariable();
this.popVariable();
break;
default: throw new UnsupportedOperationException("Unsupported binary temporal operator:"+binaryTempFormula.op());
}
this.numberMaxOfnestedPlicas = tempI;
this.needToDeclarePostR = temp;
this.popVariable();
this.popOperator();
return rt;
}
@Override
public Expression visit(TempExpression tempExpression) {
this.pushOperator(TemporalOperator.POST);
this.pushVariable();
//condition to verify the number max of nested plicas!!
if(tempExpression.expression() instanceof TempExpression){
numberMaxOfnestedPlicas++;
}else{
if (numberMaxOfnestedPlicas>this.needToDeclarePostR){
this.needToDeclarePostR = numberMaxOfnestedPlicas;
numberMaxOfnestedPlicas=1;
}
}
//if the context is not a temporal operator.
if (this.getVariableLastQuantification() == init) {
if (numberMaxOfnestedPlicas>this.numberMaxPlicasInit){
this.numberMaxPlicasInit = numberMaxOfnestedPlicas;
}
}
Expression localExpression2 = tempExpression.expression().accept(this);
this.popOperator();
this.popVariable();
return localExpression2;
}
public Formula getQuantifierUntil(Formula left, Formula right, int quantificationLeft, int quantificationRight) {
Variable r = getVariableUntil(true);
Variable l = getVariableUntil(false);
Formula nfleft;
if (quantificationLeft>0) {
nfleft = (forceNextExists(l, quantificationLeft).and(left)).forAll(l.oneOf(getVariableLastQuantificationUntil(false).join(next.reflexiveClosure()).intersection(next.closure().join(r))));
} else {
nfleft = left.forAll(l.oneOf(getVariableLastQuantificationUntil(false).join(next.reflexiveClosure()).intersection(next.closure().join(r))));
}
if (quantificationRight>0) {
return (forceNextExists(r, quantificationRight).and(right)).and(nfleft).forSome(r.oneOf(getVariableLastQuantificationUntil(false).join(next.reflexiveClosure())));
} else {
return right.and(nfleft).forSome(r.oneOf(getVariableLastQuantificationUntil(false).join(next.reflexiveClosure())));
}
}
public Formula getQuantifierRelease(Formula always, Formula left, Formula right, int leftFormula, int rightFormula) {
Variable r = getVariableRelease(true, false);
Variable l = getVariableRelease(false, false);
Variable v = getVariableRelease(false, true);
Formula alw;
Formula nfleft;
Formula nfright;
alw = infinite.and(always.forAll(v.oneOf(getVariableLastQuantificationRelease(false, true).join(next.reflexiveClosure()))));
if (rightFormula>0) {
nfleft = (forceNextExists(l, rightFormula).and(right)).forAll(l.oneOf(getVariableLastQuantificationRelease(false, true).join(next.reflexiveClosure()).intersection(next.reflexiveClosure().join(r))));
} else {
nfleft = right.forAll(l.oneOf(getVariableLastQuantificationRelease(false, true).join(next.reflexiveClosure()).intersection(next.reflexiveClosure().join(r))));
}
if (leftFormula >0) {
nfright = (forceNextExists(r, leftFormula).and(left)).and(nfleft).forSome(r.oneOf(getVariableLastQuantificationRelease(false, true).join(next.reflexiveClosure())));
} else {
nfright = left.and(nfleft).forSome(r.oneOf(getVariableLastQuantificationRelease(false, true).join(next.reflexiveClosure())));
}
return alw.or(nfright);
}
public Formula getQuantifier(TemporalOperator op, Formula e, int posts) {
Variable v;
Expression quantification = this.getVariableLastQuantification();
switch(op) {
case ALWAYS:
v = (Variable) getVariable();
return infinite.and(e.forAll(v.oneOf(quantification.join(next.reflexiveClosure()))));
case EVENTUALLY:
v = (Variable) getVariable();
if (posts>0) {
return forceNextExists(v, posts).and(e).forSome(v.oneOf(quantification.join(next.reflexiveClosure())));
} else {
return e.forSome(v.oneOf(quantification.join(next.reflexiveClosure())));
}
case HISTORICALLY:
v = (Variable) getVariable();
if (posts>0) {
return forceNextExists(v, posts).and(e).forAll(v.oneOf(quantification.join(next.transpose().reflexiveClosure())));
} else {
return e.forAll(v.oneOf(quantification.join(next.transpose().reflexiveClosure())));
}
case ONCE:
v = (Variable) this.getVariable();
if (posts>0) {
return forceNextExists(v, posts).and(e).forSome(v.oneOf(quantification.join(next.transpose().reflexiveClosure())));
} else {
return e.forSome(v.oneOf(quantification.join(next.transpose().reflexiveClosure())));
}
case NEXT:
case PREVIOUS:
Expression v1 = this.getVariable();
if (posts>0) {
return forceNextExists(v1, posts).and(v1.some().and(e));
} else {
return v1.some().and(e);
}
default:
return e;
}
}
public Formula forceNextExists(Expression exp , int x){
Expression e = exp.join(next);
for (int i = 1;i < x;i++) {
e = e.join(next);
}
return e.some();
}
//Initialize the original values of the variable needToDeclarePostR and numberMaxOfnestedPlicas
public void initializePostVariables(){
this.needToDeclarePostR = 0;
this.numberMaxOfnestedPlicas = 1;
}
/*Operators Context*/
private List<TemporalOperator> operators = new ArrayList<TemporalOperator>();
private int totalOperators = -1;
public void pushOperator(TemporalOperator op) {
this.totalOperators++;
this.operators.add(op);
}
public TemporalOperator getOperator() {
return this.operators.get(this.totalOperators);
}
public boolean thereAreOperator() {
if (this.operators.size() == 0) return false;
return true;
}
public void popOperator() {
this.operators.remove(this.totalOperators);
this.totalOperators
}
/*VarRelations*/
/**
* Returns the static relation corresponding to the extension of a variable relation.
* Creates it first time.
* @param name
* @param v
* @return
*/
private Relation getRelation(VarRelation v) {
Relation e = this.relations.get(v.name());
if (e == null) {
Relation varRelation = Relation.nary(v.name(), v.arity() + 1);
this.relations.put(v.name(),varRelation);
return varRelation;
} else {
return e;
}
}
/*Variables*/
private List<Expression> variables = new ArrayList<Expression>();
private int totalVar = 0;
private int totalVariablesIt = 0;
private void resetVariables() {
this.variables = new ArrayList<Expression>();
this.totalVar = 0;
}
private void pushVariable() {
if (!this.thereAreVariables()) {
this.totalVar++;
this.variables.add(init);
return;
}
if (this.getOperator() == TemporalOperator.NEXT || this.getOperator() == TemporalOperator.POST) {
this.variables.add(getVariable().join(next));
} else {
if (this.getOperator() == TemporalOperator.PREVIOUS) {
this.variables.add(getVariable().join(next.transpose()));
} else {
Variable v = Variable.unary("t" + this.totalVariablesIt);
variables.add(v);
this.totalVariablesIt++;
}
}
this.totalVar++;
}
private void popVariable() {
this.variables.remove(this.totalVar - 1);
if (this.totalVar > 0) this.totalVar
}
private boolean thereAreVariables() {
if (this.variables.size() == 0) return false;
return true;
}
private Expression getVariable() {
return this.variables.get(this.totalVar - 1);
}
private Expression getVariableLastQuantification() {
return this.variables.get(this.totalVar - 2);
}
private Expression getVariableLastQuantificationUntil(boolean sideIsRight) {
if (!sideIsRight) {
return this.variables.get(this.totalVar - 3);
} else {
return this.variables.get(this.totalVar - 2);
}
}
private Variable getVariableUntil(boolean sideIsRight) {
if (!sideIsRight) {
return (Variable) this.variables.get(this.totalVar - 1);
} else {
return (Variable) this.variables.get(this.totalVar - 2);
}
}
private Expression getVariableLastQuantificationRelease(boolean sideIsRight, boolean isAlways) {
if (isAlways) {
return this.variables.get(this.totalVar - 4);
} else {
if (!sideIsRight) {
return this.variables.get(this.totalVar - 3);
} else {
return this.variables.get(this.totalVar - 2);
}
}
}
private Variable getVariableRelease(boolean sideIsRight, boolean isAlways) {
if (isAlways) {
return (Variable) this.variables.get(this.totalVar - 3);
} else {
if (!sideIsRight) {
return (Variable) this.variables.get(this.totalVar - 1);
} else {
return (Variable) this.variables.get(this.totalVar - 2);
}
}
}
private final boolean isTemporal(Node n) {
AbstractDetector det = new AbstractDetector(new HashSet<Node>()) {
public Boolean visit(UnaryTempFormula tempFormula) {
return cache(tempFormula, true);
}
public Boolean visit(BinaryTempFormula tempFormula) {
return cache(tempFormula, true);
}
public Boolean visit(TempExpression tempExpr) {
return cache(tempExpr, true);
}
public Boolean visit(Relation relation) {
return cache(relation, relation instanceof VarRelation);
}
};
return (boolean) n.accept(det);
}
}
|
package no.bagit;
import gov.loc.repository.bagit.Bag;
import gov.loc.repository.bagit.BagFactory;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
public class BagIt {
// our BagFactory
BagFactory bagFactory = new BagFactory();
// our constructors
/*
creates a BagIt from an existing directory
*/
BagIt(String filePath) {
Bag theBag = bagFactory.createBag(new File(filePath));
}
/*
adds a file to our BagIt
*/
public void addFile(String directory, InputStream inputStream) {
}
/*
get the licence for the item
*/
/*
returns the list of primary files in sequence
data/final/[final version files] ordered by tagfiles/final.sequence.txt
*/
public InputStream getPrimary() {
InputStream primary = new InputStream() {
@Override
public int read() throws IOException {
return 0; //To change body of implemented methods use File | Settings | File Templates.
}
};
return primary;
}
/*
returns the list of secondary files in sequence
data/supporting/[supporting files] ordered by tagfiles/supporting.sequence.txt
*/
public InputStream getSecondary() {
InputStream secondary = new InputStream() {
@Override
public int read() throws IOException {
return 0; //To change body of implemented methods use File | Settings | File Templates.
}
};
return secondary;
}
/*
verifies the bag against it's manifest
*/
/*
Looks for access set for filename in
tagfiles/supporting.access.txt
will be open or closed
*/
public String getSupportingAccess(String filename) {
return "open";
}
/*
returns the metadata file
data/metadata/metadata.xml
*/
} // end public class BagIt
|
package com.xamoom.android.xamoomsdk.xamoomsdk;
import com.xamoom.android.xamoomsdk.CallHandler;
import com.xamoom.android.xamoomsdk.EnduserApi;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import at.rags.morpheus.Morpheus;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNotNull;
import static org.mockito.Mockito.mock;
@RunWith(MockitoJUnitRunner.class)
public class CallHandlerTest {
private Morpheus mMockMorpheus;
private CallHandler mCallHandler;
@Before
public void setup() {
mMockMorpheus = mock(Morpheus.class);
mCallHandler = new CallHandler(mMockMorpheus);
}
@Test
public void testConstructor() {
CallHandler callHandler = new CallHandler(mMockMorpheus);
assertNotNull(callHandler);
}
@Test(expected = NullPointerException.class)
public void testEnqueCallWithNull() {
mCallHandler.enqueCall(null, null);
}
@Test(expected = NullPointerException.class)
public void testEnqueListCallWithNull() {
mCallHandler.enqueListCall(null, null);
}
}
|
package com.xpn.xwiki.plugin.feed;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jmock.Mock;
import org.jmock.core.Invocation;
import org.jmock.core.stub.CustomStub;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndEntryImpl;
import com.xpn.xwiki.XWiki;
import com.xpn.xwiki.XWikiConfig;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.api.Document;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.objects.classes.BaseClass;
import com.xpn.xwiki.store.XWikiHibernateStore;
import com.xpn.xwiki.store.XWikiHibernateVersioningStore;
import com.xpn.xwiki.store.XWikiStoreInterface;
import com.xpn.xwiki.store.XWikiVersioningStoreInterface;
import com.xpn.xwiki.test.AbstractBridgedXWikiComponentTestCase;
import com.xpn.xwiki.user.api.XWikiRightService;
import com.xpn.xwiki.user.impl.xwiki.XWikiRightServiceImpl;
import com.xpn.xwiki.web.XWikiServletURLFactory;
/**
* Unit tests for {@link SyndEntryDocumentSource}.
*/
public class SyndEntryDocumentSourceTest extends AbstractBridgedXWikiComponentTestCase
{
public static final String INCONSISTENCY = "Inconsistency!";
public static final String POLYMORPHISM_INCONSISTENCY = "Polymorphism inconsistency!";
public static final String ACCESS_RIGHTS_VIOLATED = "Access rights are violated!";
public static final String PARAMETERS_IGNORED = "Parameters are ignored!";
public static final String SVG_MIME_TYPE = "image/svg+xml";
public static final String PNG_MIME_TYPE = "image/png";
public static final String ARTICLE_CLASS_NAME = "XWiki.ArticleClass";
protected SyndEntryDocumentSource source;
protected XWikiDocument doc;
protected void setUp() throws Exception
{
super.setUp();
mockUp();
getContext().setUser("Condor");
doc = new XWikiDocument("MilkyWay", "Fidis");
doc.setCreator("Condor");
doc.setAuthor("Albatross");
doc.setTitle("Fidis from MilkyWay");
doc.setContent("blah blah blah..");
doc.setSyntaxId("xwiki/1.0");
initArticleClass();
doc.createNewObject(ARTICLE_CLASS_NAME, getContext());
doc.setStringValue(ARTICLE_CLASS_NAME, "title", "Old story");
doc.setStringValue(ARTICLE_CLASS_NAME, "content", "Once upon a <i>time</i> there was..");
List categories = new ArrayList();
categories.add("News");
categories.add("Information");
doc.setStringListValue(ARTICLE_CLASS_NAME, "category", categories);
getContext().getWiki().saveDocument(doc, getContext());
getContext().setDoc(doc);
// Ensure that no Velocity Templates are going to be used when executing Velocity since otherwise
// the Velocity init would fail (since by default the macros.vm templates wouldn't be found as we're
// not providing it in our unit test resources).
getContext().getWiki().getConfig().setProperty("xwiki.render.velocity.macrolist", "");
source = new SyndEntryDocumentSource();
}
private void mockUp() throws Exception
{
final Map docs = new HashMap();
final XWikiContext context = getContext();
final XWiki xwiki = new XWiki(new XWikiConfig(), context);
context.setURLFactory(new XWikiServletURLFactory(new URL("http:
final Mock mockXWikiStore =
mock(XWikiHibernateStore.class, new Class[] {XWiki.class, XWikiContext.class},
new Object[] {xwiki, context});
mockXWikiStore.stubs().method("loadXWikiDoc").will(
new CustomStub("Implements XWikiStoreInterface.loadXWikiDoc")
{
public Object invoke(Invocation invocation) throws Throwable
{
XWikiDocument shallowDoc = (XWikiDocument) invocation.parameterValues.get(0);
if (docs.containsKey(shallowDoc.getName())) {
return (XWikiDocument) docs.get(shallowDoc.getName());
} else {
return shallowDoc;
}
}
});
mockXWikiStore.stubs().method("saveXWikiDoc").will(
new CustomStub("Implements XWikiStoreInterface.saveXWikiDoc")
{
public Object invoke(Invocation invocation) throws Throwable
{
XWikiDocument document = (XWikiDocument) invocation.parameterValues.get(0);
document.setNew(false);
document.setStore((XWikiStoreInterface) mockXWikiStore.proxy());
docs.put(document.getName(), document);
return null;
}
});
mockXWikiStore.stubs().method("getTranslationList").will(returnValue(Collections.EMPTY_LIST));
final Mock mockXWikiVersioningStore =
mock(XWikiHibernateVersioningStore.class, new Class[] {XWiki.class, XWikiContext.class}, new Object[] {
xwiki, context});
mockXWikiVersioningStore.stubs().method("getXWikiDocumentArchive").will(returnValue(null));
mockXWikiVersioningStore.stubs().method("resetRCSArchive").will(returnValue(null));
xwiki.setStore((XWikiStoreInterface) mockXWikiStore.proxy());
xwiki.setVersioningStore((XWikiVersioningStoreInterface) mockXWikiVersioningStore.proxy());
final Mock mockXWikiRightsService = mock(XWikiRightServiceImpl.class, new Class[] {}, new Object[] {});
mockXWikiRightsService.stubs().method("hasAccessLevel").will(
new CustomStub("Implements XWikiRightService.hasAccessLevel")
{
public Object invoke(Invocation invocation) throws Throwable
{
// String right = (String) invocation.parameterValues.get(0);
String user = (String) invocation.parameterValues.get(1);
// String doc = (String) invocation.parameterValues.get(2);
// we give access to all the users with an even name length
return new Boolean(user.length() % 2 == 0);
}
});
xwiki.setRightService((XWikiRightService) mockXWikiRightsService.proxy());
}
protected BaseClass initArticleClass() throws XWikiException
{
XWikiDocument doc = getContext().getWiki().getDocument(ARTICLE_CLASS_NAME, getContext());
boolean needsUpdate = doc.isNew();
BaseClass bclass = doc.getxWikiClass();
bclass.setName(ARTICLE_CLASS_NAME);
needsUpdate |= bclass.addTextField("title", "Title", 64);
needsUpdate |= bclass.addTextAreaField("content", "Content", 45, 4);
needsUpdate |= bclass.addTextField("category", "Category", 64);
if (needsUpdate) {
getContext().getWiki().saveDocument(doc, getContext());
}
return bclass;
}
protected SyndEntryImpl source(Object obj)
{
return source(obj, Collections.EMPTY_MAP);
}
protected SyndEntryImpl source(Object obj, Map params)
{
SyndEntryImpl entry = new SyndEntryImpl();
try {
source.source(entry, obj, params, getContext());
} catch (Exception e) {
}
return entry;
}
/**
* Computes the sum of lengths of all the text nodes from the given XML fragment.
*
* @param xmlFragment the XML fragment to be parsed
* @return the number of characters in all the text nodes within the given XML fragment
*/
protected int getXMLContentLength(String xmlFragment)
{
return SyndEntryDocumentSource.innerTextLength(SyndEntryDocumentSource.tidy(xmlFragment,
SyndEntryDocumentSource.TIDY_HTML_CONFIG));
}
/**
* Tests if two successive calls of the source method with the same argument have the same result.
*/
public void testSourceConsistency()
{
assertEquals(INCONSISTENCY, source(doc), source(doc));
}
/**
* Tests if different calls of the source method have the same result when the argument passed points to the same
* document, irrespective of its type: {@link XWikiDocument}, {@link Document}, and {@link String}.
*/
public void testSourcePolymorphism()
{
SyndEntryImpl fromXDoc = source(doc);
SyndEntryImpl fromDoc = source(doc.newDocument(getContext()));
SyndEntryImpl fromFullName = source(doc.getFullName());
assertEquals(POLYMORPHISM_INCONSISTENCY, fromXDoc, fromDoc);
assertEquals(POLYMORPHISM_INCONSISTENCY, fromXDoc, fromFullName);
assertEquals(POLYMORPHISM_INCONSISTENCY, fromDoc, fromFullName);
}
/**
* Tests if the source method obeys the access rights.
*
* @throws XWikiException
*/
public void testSourceAccessRights() throws XWikiException
{
// odd user name length implies no access rights
getContext().setUser("XWiki.Albatross");
try {
source.source(new SyndEntryImpl(), doc, Collections.EMPTY_MAP, getContext());
fail(ACCESS_RIGHTS_VIOLATED);
} catch (XWikiException expected) {
// we should get an exception
assertEquals(XWikiException.ERROR_XWIKI_ACCESS_DENIED, expected.getCode());
}
// even user name length implies all access rights
getContext().setUser("Condor");
source.source(new SyndEntryImpl(), doc, Collections.EMPTY_MAP, getContext());
// we shouldn't get an exception
}
/**
* Tests if {@link SyndEntryDocumentSource#CONTENT_TYPE} parameter is used correctly.
*/
public void testSourceContentType()
{
Map instanceParams = new HashMap();
instanceParams.put(SyndEntryDocumentSource.CONTENT_TYPE, SVG_MIME_TYPE);
source.setParams(instanceParams);
assertEquals(PARAMETERS_IGNORED, SVG_MIME_TYPE, source(doc).getDescription().getType());
Map methodParams = new HashMap();
methodParams.put(SyndEntryDocumentSource.CONTENT_TYPE, PNG_MIME_TYPE);
SyndEntry entry = source(doc, methodParams);
assertEquals(PARAMETERS_IGNORED, PNG_MIME_TYPE, entry.getDescription().getType());
}
/**
* Tests if {@link SyndEntryDocumentSource#CONTENT_LENGTH} parameter is used correctly when the
* {@link SyndEntryDocumentSource#CONTENT_TYPE} is <i>text/plain</i>.
*/
public void testArticleSourcePlainContentLength()
{
int maxLength = 15;
Map params = new HashMap();
params.put(SyndEntryDocumentSource.CONTENT_TYPE, "text/plain");
params.put(SyndEntryDocumentSource.CONTENT_LENGTH, new Integer(maxLength));
params.put(SyndEntryDocumentSource.FIELD_DESCRIPTION, ARTICLE_CLASS_NAME + "_content");
source.setParams(params);
doc.setStringValue(ARTICLE_CLASS_NAME, "content", "Somewhere in la Mancha, in a place..");
assertTrue(doc.display("content", getContext()).length() > maxLength);
int descriptionLength = source(doc).getDescription().getValue().length();
assertTrue(PARAMETERS_IGNORED, descriptionLength <= maxLength);
}
/**
* Tests if {@link SyndEntryDocumentSource#CONTENT_LENGTH} parameter is used correctly when the
* {@link SyndEntryDocumentSource#CONTENT_TYPE} is <i>text/html</i>.
*/
public void testArticleSourceHTMLContentLength()
{
int maxLength = 16;
Map params = new HashMap();
params.put(SyndEntryDocumentSource.CONTENT_TYPE, "text/html");
params.put(SyndEntryDocumentSource.CONTENT_LENGTH, new Integer(maxLength));
params.put(SyndEntryDocumentSource.FIELD_DESCRIPTION, ARTICLE_CLASS_NAME + "_content");
doc.setStringValue(ARTICLE_CLASS_NAME, "content",
"Somewhere \n\tin <i>la</i> <a href=\"http:
assertTrue(getXMLContentLength(doc.display("content", getContext())) > maxLength);
String description = source(doc, params).getDescription().getValue();
int descriptionLength = getXMLContentLength(description);
assertTrue(PARAMETERS_IGNORED, descriptionLength <= maxLength);
}
public void testArticleSourceXMLContentLength()
{
int maxLength = 17;
Map params = new HashMap();
params.put(SyndEntryDocumentSource.CONTENT_TYPE, "text/xml");
params.put(SyndEntryDocumentSource.CONTENT_LENGTH, new Integer(maxLength));
params.put(SyndEntryDocumentSource.FIELD_DESCRIPTION, ARTICLE_CLASS_NAME + "_content");
doc.setStringValue(ARTICLE_CLASS_NAME, "content",
"<text>Somewhere \n\tin la <region> Mancha</region>, in a place..</text>");
assertTrue(getXMLContentLength(doc.display("content", getContext())) > maxLength);
String description = source(doc, params).getDescription().getValue();
int descriptionLength = getXMLContentLength(description);
assertTrue(PARAMETERS_IGNORED, descriptionLength <= maxLength);
}
}
|
package net.yasme.android.controller;
import android.app.ActivityManager;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import net.yasme.android.R;
import net.yasme.android.storage.DatabaseManager;
import net.yasme.android.ui.AbstractYasmeActivity;
import net.yasme.android.ui.activities.ChatActivity;
import java.util.List;
public class NewMessageNotificationManager {
private int numberOfMessages;
private Context mContext;
private NotificationManager mNotificationManager;
private NotificationCompat.Builder mBuilder;
// mId allows you to update the notification later on.
private int mId;
public NewMessageNotificationManager() {
mContext = DatabaseManager.INSTANCE.getContext();
numberOfMessages = 0;
mNotificationManager = (NotificationManager) mContext
.getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(mContext)
.setContentTitle("Yasme")
.setContentText(mContext.getString(R.string.notification_message))
.setSmallIcon(R.drawable.ic_notify_y)
.setPriority(1)
/*.setDefaults(Notification.DEFAULT_VIBRATE)
.setDefaults(Notification.DEFAULT_SOUND)*/
.setAutoCancel(true)
.setLargeIcon(getIcon(mContext));
mId = 1;
}
private boolean isForeground(){
//get Context
Context mContext = DatabaseManager.INSTANCE.getContext();
// Get the Activity Manager
ActivityManager manager = (ActivityManager) mContext.
getSystemService(mContext.ACTIVITY_SERVICE);
// Get a list of running tasks, we are only interested in the last one,
// the top most so we give a 1 as parameter so we only get the topmost.
List<ActivityManager.RunningTaskInfo> task = manager.getRunningTasks(1);
// Get the info we need for comparison.
ComponentName componentInfo = task.get(0).topActivity;
// Check if it matches our package name.
if(componentInfo.getPackageName().equals(mContext.getPackageName())) return true;
// If not then our app is not on the foreground.
return false;
}
public void mNotify(final int numberOfNewMessages, final long newestMessageId) {
if(isForeground()) {
Log.i(this.getClass().getSimpleName(), "App in foreground");
return;
}
mNotificationManager.cancel(mId);
numberOfMessages = numberOfNewMessages;
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(mContext, ChatActivity.class);
resultIntent.putExtra(AbstractYasmeActivity.CHAT_ID, newestMessageId);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent resultPendingIntent = PendingIntent.getActivity(mContext, 0,
resultIntent, 0);
mBuilder.setContentIntent(resultPendingIntent);
mBuilder.setContentInfo("" + numberOfMessages);
mNotificationManager.notify(mId, mBuilder.build());
}
private Bitmap getIcon(Context mContext) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = false;
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
String imageType = options.outMimeType;
return BitmapFactory.decodeResource(mContext.getResources(), R.raw.logo, options);
}
}
|
package io.yope.payment.rest.helpers;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.MessageFormat;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import io.yope.payment.blockchain.BlockChainService;
import io.yope.payment.blockchain.BlockchainException;
import io.yope.payment.domain.QRImage;
import io.yope.payment.domain.Transaction;
import io.yope.payment.domain.Transaction.Direction;
import io.yope.payment.domain.Transaction.Status;
import io.yope.payment.domain.Transaction.Type;
import io.yope.payment.domain.Wallet;
import io.yope.payment.exceptions.IllegalTransactionStateException;
import io.yope.payment.exceptions.InsufficientFundsException;
import io.yope.payment.exceptions.ObjectNotFoundException;
import io.yope.payment.rest.BadRequestException;
import io.yope.payment.services.TransactionService;
import io.yope.payment.services.WalletService;
import lombok.extern.slf4j.Slf4j;
/**
* @author massi
*
*/
@Slf4j
@Service
public class TransactionHelper {
static final BigDecimal BLOCKCHAIN_FEES = new BigDecimal("0.1");
private static final int SCALE = 5;
@Autowired
private AccountHelper accountHelper;
@Autowired
private WalletHelper walletHelper;
@Autowired
private TransactionService transactionService;
@Autowired
private WalletService walletService;
@Autowired
private BlockChainService blockChainService;
@Autowired
private QRHelper qrHelper;
public Transaction create(final Transaction transaction, final Long accountId) throws ObjectNotFoundException, BadRequestException, BlockchainException, InsufficientFundsException, IllegalTransactionStateException {
final Transaction.Type type = getType(transaction, accountId);
switch (type) {
case DEPOSIT:
return doDeposit(transaction.toBuilder().type(Type.DEPOSIT).build(), accountId);
case TRANSFER:
return doTransfer(transaction.toBuilder().type(Type.TRANSFER).build(), accountId);
case WITHDRAW:
return doWithdraw(transaction.toBuilder().type(Type.WITHDRAW).build(), accountId);
default:
break;
}
throw new BadRequestException("Transaction type not recognized "+transaction.getType(), "type");
}
private Type getType(final Transaction transaction, final Long accountId) throws BadRequestException {
final Wallet source = getWallet(transaction.getSource(), accountId);
final Wallet destination = getWallet(transaction.getDestination(), accountId);
if ((source != null && Wallet.Type.INTERNAL.equals(source.getType())) &&
(destination != null && Wallet.Type.INTERNAL.equals(destination.getType()))) {
return Transaction.Type.TRANSFER;
}
if ((source == null || (source != null && Wallet.Type.EXTERNAL.equals(source.getType()))) &&
(destination != null && Wallet.Type.INTERNAL.equals(destination.getType()))) {
return Transaction.Type.DEPOSIT;
}
if ((source != null && Wallet.Type.INTERNAL.equals(source.getType())) &&
(destination == null || (destination != null && Wallet.Type.EXTERNAL.equals(destination.getType())))) {
return Transaction.Type.WITHDRAW;
}
throw new BadRequestException("Transaction not allowed", null);
}
/**
* Transfers funds between 2 internal wallets belonging to the same seller.
* @param transaction the transaction details
* @param accountId the id of the seller
* @return the pending transaction
* @throws ObjectNotFoundException if the seller is not found
* @throws BadRequestException if the wallets are not found
* @throws InsufficientFundsException
*/
public Transaction doTransfer(final Transaction transaction, final Long accountId) throws ObjectNotFoundException, BadRequestException, InsufficientFundsException {
final Wallet source = walletHelper.getByName(accountId, transaction.getSource().getName());
if (source == null) {
throw new ObjectNotFoundException(MessageFormat.format("Source Wallet {0} Not Found", transaction.getSource()));
}
if (source.getAvailableBalance().compareTo(transaction.getAmount()) < 0) {
throw new InsufficientFundsException("not enough funds in the wallet with name "+source.getName());
}
final Wallet destination = walletHelper.getByName(accountId, transaction.getDestination().getName());
if (destination == null) {
throw new ObjectNotFoundException(MessageFormat.format("Destination Wallet {0} Not Found", transaction.getDestination()));
}
final BigDecimal correctedAmount = transaction.getAmount().setScale(SCALE, RoundingMode.FLOOR);
walletService.update(source.getId(), source.toBuilder()
.balance(source.getBalance().subtract(correctedAmount))
.availableBalance(source.getAvailableBalance().subtract(correctedAmount))
.build());
walletService.update(destination.getId(), destination.toBuilder()
.balance(destination.getBalance().add(correctedAmount))
.availableBalance(destination.getAvailableBalance().add(correctedAmount))
.build());
final Transaction.Builder pendingTransactionBuilder = transaction.toBuilder()
.amount(correctedAmount)
.balance(correctedAmount).blockchainFees(BigDecimal.ZERO).fees(BigDecimal.ZERO)
.source(source).destination(destination).status(Status.COMPLETED);
return transactionService.create(pendingTransactionBuilder.build());
}
/**
* Transfers funds between an external wallet and an internal wallet belonging to the same seller.
* @param transaction the transaction details
* @param accountId the id of the seller
* @return the pending transaction
* @throws ObjectNotFoundException if the seller is not found
* @throws BadRequestException if the internal wallet is not found
*/
public Transaction doDeposit(final Transaction transaction, final Long accountId) throws ObjectNotFoundException, BadRequestException, BlockchainException {
final Wallet source = getWalletForDeposit(transaction, accountId);
final Wallet destination = walletHelper.getByName(accountId, transaction.getDestination().getName());
if (destination == null) {
throw new ObjectNotFoundException(MessageFormat.format("Destination Wallet {0} Not Found", transaction.getDestination()));
}
final Transaction.Builder pendingTransactionBuilder = transaction.toBuilder().fees(BigDecimal.ZERO).source(source).destination(destination).status(Status.PENDING);
final BigDecimal correctedAmount = transaction.getAmount().setScale(SCALE, RoundingMode.FLOOR);
final QRImage qr = qrHelper.getQRImage(correctedAmount.add(BLOCKCHAIN_FEES));
pendingTransactionBuilder.QR(qr.getImageUrl()).receiverHash(qr.getHash());
return transactionService.create(pendingTransactionBuilder.amount(correctedAmount).build());
}
private Wallet getWalletForDeposit(final Transaction transaction, final Long accountId) throws ObjectNotFoundException, BadRequestException {
Wallet wallet = getWallet(transaction.getSource(), accountId);
if (wallet == null) {
wallet = accountHelper.saveWallet(
transaction.getSource().toBuilder().type(Wallet.Type.TRANSIT)
.availableBalance(transaction.getAmount())
.balance(transaction.getAmount()).build());
}
return wallet;
}
public Transaction doWithdraw(final Transaction transaction, final Long accountId) throws BlockchainException, ObjectNotFoundException, BadRequestException, InsufficientFundsException, IllegalTransactionStateException {
final BigDecimal correctedAmount = transaction.getAmount().setScale(SCALE, RoundingMode.FLOOR);
final Wallet source = walletHelper.getByName(accountId, transaction.getSource().getName());
if (source == null) {
throw new ObjectNotFoundException(MessageFormat.format("Source Wallet {0} Not Found", transaction.getSource()));
}
if (source.getAvailableBalance().compareTo(correctedAmount) < 0) {
throw new InsufficientFundsException(MessageFormat.format("Insufficient Funds Exception in Wallet {0}", transaction.getSource()));
}
final Wallet destination = getWalletForWithdraw(transaction, accountId);
final Transaction.Builder pendingTransactionBuilder = transaction.toBuilder()
.amount(correctedAmount)
.fees(BigDecimal.ZERO)
.source(source)
.destination(destination).status(Status.PENDING);
final Transaction pendingTransaction = transactionService.create(pendingTransactionBuilder.build());
try {
final String transactionHash = blockChainService.send(pendingTransaction);
transactionService.save(pendingTransaction.getId(), pendingTransactionBuilder.transactionHash(transactionHash).status(Status.ACCEPTED).build());
} catch (final Exception e) {
log.error("Transaction "+pendingTransaction.getId(), e);
transactionService.transition(pendingTransaction.getId(), Transaction.Status.FAILED);
throw e;
}
return pendingTransaction;
}
private Wallet getWalletForWithdraw(final Transaction transaction, final Long accountId) throws ObjectNotFoundException, BadRequestException {
final Wallet destination = transaction.getDestination();
if (StringUtils.isBlank(destination.getWalletHash())) {
final Wallet wallet = walletHelper.getByName(accountId, transaction.getDestination().getName());
if (wallet == null) {
throw new IllegalArgumentException(MessageFormat.format("Destination Wallet {0} Not Found", transaction.getDestination()));
}
if (wallet.getWalletHash() == null) {
throw new IllegalArgumentException(MessageFormat.format("Destination Wallet {0} Has no Hash", transaction.getDestination()));
}
return wallet;
}
Wallet wallet = walletHelper.getByWalletHash(destination.getWalletHash());
if (wallet != null) {
return wallet;
}
wallet = walletHelper.getByName(accountId, transaction.getDestination().getName());
if (wallet != null) {
return accountHelper.saveWallet(wallet.toBuilder().walletHash(destination.getWalletHash()).build());
}
return accountHelper.createWallet(accountId, destination);
}
private Wallet getWallet(final Wallet source, final Long sellerId) {
if (StringUtils.isNotBlank(source.getWalletHash())) {
return walletHelper.getByWalletHash(source.getWalletHash());
}
return walletHelper.getByName(sellerId, source.getName());
}
public List<Transaction> getTransactionsForWallet(final Long walletId, final String reference, final Direction direction, final Status status, final Type type) throws ObjectNotFoundException {
return transactionService.getForWallet(walletId, reference, direction, status, type);
}
public List<Transaction> getTransactionsForAccount(final Long accountId, final String reference, final Direction direction, final Status status, final Type type) throws ObjectNotFoundException {
return transactionService.getForAccount(accountId, reference, direction, status, type);
}
public Transaction getTransactionById(final Long transactionId) {
return transactionService.get(transactionId);
}
public Transaction doTransition(final Long transactionId, final Status status) throws ObjectNotFoundException, InsufficientFundsException, IllegalTransactionStateException {
return transactionService.transition(transactionId, status);
}
public Transaction getTransactionByHash(final String hash) {
return transactionService.getByTransactionHash(hash);
}
public Transaction getTransactionBySenderHash(final String hash) {
return transactionService.getBySenderHash(hash);
}
public Transaction getTransactionByReceiverHash(final String hash) {
return transactionService.getByReceiverHash(hash);
}
}
|
package myClient;
import java.io.IOException;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Scanner;
import javax.sound.sampled.LineEvent;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import dataModels.Book;
import serviceLayer.BookStoreServices;
/**
*
* @author Mr Bahram
*
*/
public class ClintForBookStore {
private final static int GET_LIST_OF_THE_BOOK=1;
private final static int SEARCH_A_BOOK=2;
private final static int ADD_A_NEW_BOOK=3;
private final static int ADD_TO_MY_BASKET=4;
private final static int GET_MY_BASKET=5;
private final static int REMOVE_FROM_MY_BASKET=6;
private final static int EXIT=7;
static String id="";
static String serverAddress="";
static Scanner line=new Scanner(System.in);
private static BookStoreServices services=new BookStoreServices();
/**
* Main function
* @param args
*/
public static void main(String[] args) {
ClintForBookStore bookastore=new ClintForBookStore();
System.out.println("Welcome commane Line for book story");
bookastore.connectToServer();
System.out.println("Client successfully connected to "+serverAddress);
int number=bookastore.bookStoryMenu();
while(number!=EXIT){// 7: Exit
if(number==GET_LIST_OF_THE_BOOK){// 1 :Get list of THE books
ArrayList<Book> result ;
try {
result = services.getAllBooks(serverAddress);
if(result.size()==0){
System.err.println("there is no book");
}else{
bookastore.printBookArray(result,false);
}
} catch (Exception e) {
line.nextLine();
bookastore.reConnect();
}
}else if(number==SEARCH_A_BOOK){// 2: Search a book
System.err.println("Enter Search Item in Title or Author");
line.nextLine();
String searchItem=line.nextLine();
ArrayList<Book> result;
try {
result = services.search(serverAddress,searchItem);
if(result.size()==0){
System.err.println("there is no result for "+searchItem);
}else
bookastore.printBookArray(result,false);
} catch (Exception e) {
bookastore.reConnect();
}
}else if(number==ADD_A_NEW_BOOK){// 3: Add a new book
Book book=new Book();
System.out.println("Please Enter ISBN of your book");
line.nextLine();
book.setISBN(line.nextLine());
System.out.println("Please Enter Title of your book");
book.setTitle(line.nextLine());
System.out.println("Please Enter Author of your book");
book.setAuthor(line.nextLine());
System.out.println("Please Enter Price of your book");
double price=bookastore.getValidDoubleNumber();
book.setPrice(price);
System.out.println("Please Enter quantity of your book");
int quantity=bookastore.getValidIntNumber();
book.setQuantity(quantity);
Book result;
try {
result = services.addNewItem(serverAddress,book);
if(result!=null)
System.out.println("Added "+ result+" , Quantity='"+book.getQuantity()+"'");
} catch (IOException e) {
line.nextLine();
bookastore.reConnect();
}
}else if(number==ADD_TO_MY_BASKET){// 4: Add to Basket
Book book=new Book();
System.err.println("Please Enter ISBN of your book to add in your basket");
line.nextLine();
book.setISBN(line.nextLine());
String result;
try {
result = services.addToBasket(serverAddress,id,book);
if(result!=null)
if(result.contentEquals("0"))
System.out.println("added the book in your basket");
else if(result.contentEquals("1"))
System.err.println("the book is not in stock sorry!!! ");
else
System.err.println("the book does not exist");
} catch (IOException e) {
bookastore.reConnect();
}
}else if(number==GET_MY_BASKET){// 5: Get Basket
ArrayList<Book> result;
try {
result = services.getMyBasket(serverAddress, "basket/"+id);
if(result.size()==0){
System.err.println("there is no item in your basket");
}else
bookastore.printBookArray(result,true);
} catch (Exception e) {
line.nextLine();
bookastore.reConnect();
}
}else if(number==REMOVE_FROM_MY_BASKET){// 6: Remove from Basket
Book book=new Book();
System.err.println("Please Enter ISBN of your book to remove from your basket");
line.nextLine();
book.setISBN(line.nextLine());
String result;
try {
result = services.deleteFromBasket(serverAddress,id,book);
if(result!=null)
if(result.contentEquals("0"))
System.out.println("removed the book in your basket");
else if(result.contentEquals("1"))
System.err.println("the book is not in stock sorry!!! ");
else
System.err.println("the book does not exist");
} catch (IOException e) {
bookastore.reConnect();
}
}else{// Exit
line.close();
System.exit(0);
}
// Show menu again
number=bookastore.bookStoryMenu();
}
}
/**
* Make connection to server
*/
private void connectToServer(){
do{
System.out.println("please enter Spring server IP and port. Exm: localhost:8080 or 83.10.20.111:5070 ");
String lineValue=line.nextLine();
System.out.println("Please wait...");
if(lineValue.equals("Exit")){
System.out.println("See you later!!!\ngoodbye");
System.exit(0);
}else serverAddress=lineValue;
id=services.getId(serverAddress,"id");
if(id.equals("Server Error")){
String errorMessage="Spring server address is not reachable please check the address and try again by\n"
+ "- Type a new Server Addres and Port or\n- type 'Exit' for quit";
System.err.println(errorMessage+"\n");
}
}while(id.equals("Server Error"));
}
/**
* calls when there is a fail in the connection
*/
private void reConnect(){
do{
String errorMessage="\nServer is Down or Maybe there is connection problem try again by\n"
+ "- Press Enter for re-connect\n- Type a new Server Addres and Port or\n- type 'Exit' for quit";
System.err.println(errorMessage+"\n");
String lineValue=line.nextLine();
System.out.println("Please wait...");
if(lineValue.equals("Exit")){
System.out.println("See you later!!!\ngoodbye");
System.exit(0);
}else if(lineValue.isEmpty())
System.out.println("Re-conecting please wait...");
else {
serverAddress=lineValue;
System.out.println("Trying to connect "+serverAddress+" please wait...");
}
id=services.getId(serverAddress,"id");
}while(id.equals("Server Error"));
}
/**
* shows option menu
* @return
*/
private int bookStoryMenu(){
int number=0;
boolean hasErrorInEnteredMenuNumber=false;
do{
System.out.println("\nOption menu\nPlease choose a number:\n"
+ "1: Get list of THE books\n"
+ "2: Search a book\n"
+ "3: Add a new book\n"
+ "4: Add to my Basket\n"
+ "5: Get my Basket\n"
+ "6: Remove from my Basket\n"
+ "7: Exit");
try{
number=line.nextInt();
hasErrorInEnteredMenuNumber=false;
if(number<=0||number>7){
System.err.println("Error please enter a number between 1...7");
hasErrorInEnteredMenuNumber=true;
}
}catch(InputMismatchException error){
hasErrorInEnteredMenuNumber=true;
System.err.println("Error please enter a number!!!");
line.nextLine();
}
}while(hasErrorInEnteredMenuNumber);
return number;
}
/**
* force the user to enter a valid double number
* @return
*/
private double getValidDoubleNumber(){
double price=0;
boolean isError=false;
do{
try{
price=line.nextDouble();
isError=false;
}catch(InputMismatchException error){
System.err.println("Error please enter a number!!!");
isError=true;
line.nextLine();
}
}while(isError);
return price;
}
/**
* force the user to enter a valid integer number
* @return
*/
private int getValidIntNumber(){
int quantity=0;
boolean isError=false;
do{
try{
quantity=line.nextInt();
isError=false;
}catch(InputMismatchException error){
System.err.println("Error please enter a number!!!");
isError=true;
line.nextLine();
}
}while(isError);
return quantity;
}
/**
* Prints list of books on the screen
* @param books
* @param isQuantity
*/
private void printBookArray(ArrayList<Book> books,boolean isQuantity){
int counter=1;
for (Book book : books) {
if(isQuantity)
System.out.println(counter+" "+ book+" , Quantity='"+book.getQuantity()+"'");
else
System.out.println(counter+" "+ book);
counter++;
}
}
}
|
package net.geforcemods.securitycraft.network;
import net.geforcemods.securitycraft.api.CustomizableSCTE;
import net.geforcemods.securitycraft.api.TileEntitySCTE;
import net.geforcemods.securitycraft.blocks.BlockAlarm;
import net.geforcemods.securitycraft.blocks.BlockCageTrap;
import net.geforcemods.securitycraft.blocks.BlockFakeLava;
import net.geforcemods.securitycraft.blocks.BlockFakeLavaBase;
import net.geforcemods.securitycraft.blocks.BlockFakeWater;
import net.geforcemods.securitycraft.blocks.BlockFakeWaterBase;
import net.geforcemods.securitycraft.blocks.BlockFrame;
import net.geforcemods.securitycraft.blocks.BlockInventoryScanner;
import net.geforcemods.securitycraft.blocks.BlockInventoryScannerField;
import net.geforcemods.securitycraft.blocks.BlockIronFence;
import net.geforcemods.securitycraft.blocks.BlockIronTrapDoor;
import net.geforcemods.securitycraft.blocks.BlockKeycardReader;
import net.geforcemods.securitycraft.blocks.BlockKeypad;
import net.geforcemods.securitycraft.blocks.BlockKeypadChest;
import net.geforcemods.securitycraft.blocks.BlockKeypadFurnace;
import net.geforcemods.securitycraft.blocks.BlockLaserBlock;
import net.geforcemods.securitycraft.blocks.BlockLaserField;
import net.geforcemods.securitycraft.blocks.BlockLogger;
import net.geforcemods.securitycraft.blocks.BlockOwnable;
import net.geforcemods.securitycraft.blocks.BlockPanicButton;
import net.geforcemods.securitycraft.blocks.BlockPortableRadar;
import net.geforcemods.securitycraft.blocks.BlockProtecto;
import net.geforcemods.securitycraft.blocks.BlockReinforcedDoor;
import net.geforcemods.securitycraft.blocks.BlockReinforcedFenceGate;
import net.geforcemods.securitycraft.blocks.BlockReinforcedGlass;
import net.geforcemods.securitycraft.blocks.BlockReinforcedIronBars;
import net.geforcemods.securitycraft.blocks.BlockReinforcedSandstone;
import net.geforcemods.securitycraft.blocks.BlockReinforcedSlabs;
import net.geforcemods.securitycraft.blocks.BlockReinforcedStainedGlass;
import net.geforcemods.securitycraft.blocks.BlockReinforcedStairs;
import net.geforcemods.securitycraft.blocks.BlockReinforcedWood;
import net.geforcemods.securitycraft.blocks.BlockReinforcedWoodSlabs;
import net.geforcemods.securitycraft.blocks.BlockRetinalScanner;
import net.geforcemods.securitycraft.blocks.BlockScannerDoor;
import net.geforcemods.securitycraft.blocks.BlockSecurityCamera;
import net.geforcemods.securitycraft.blocks.mines.BlockBouncingBetty;
import net.geforcemods.securitycraft.blocks.mines.BlockClaymore;
import net.geforcemods.securitycraft.blocks.mines.BlockFullMineBase;
import net.geforcemods.securitycraft.blocks.mines.BlockFurnaceMine;
import net.geforcemods.securitycraft.blocks.mines.BlockIMS;
import net.geforcemods.securitycraft.blocks.mines.BlockMine;
import net.geforcemods.securitycraft.blocks.mines.BlockTrackMine;
import net.geforcemods.securitycraft.entity.EntityBouncingBetty;
import net.geforcemods.securitycraft.entity.EntityIMSBomb;
import net.geforcemods.securitycraft.entity.EntitySecurityCamera;
import net.geforcemods.securitycraft.entity.EntityTaserBullet;
import net.geforcemods.securitycraft.gui.GuiHandler;
import net.geforcemods.securitycraft.items.ItemAdminTool;
import net.geforcemods.securitycraft.items.ItemBlockReinforcedPlanks;
import net.geforcemods.securitycraft.items.ItemBlockReinforcedSandstone;
import net.geforcemods.securitycraft.items.ItemBlockReinforcedSlabs;
import net.geforcemods.securitycraft.items.ItemBlockReinforcedStainedGlass;
import net.geforcemods.securitycraft.items.ItemBlockReinforcedWoodSlabs;
import net.geforcemods.securitycraft.items.ItemBriefcase;
import net.geforcemods.securitycraft.items.ItemCameraMonitor;
import net.geforcemods.securitycraft.items.ItemCodebreaker;
import net.geforcemods.securitycraft.items.ItemKeyPanel;
import net.geforcemods.securitycraft.items.ItemKeycardBase;
import net.geforcemods.securitycraft.items.ItemMineRemoteAccessTool;
import net.geforcemods.securitycraft.items.ItemModifiedBucket;
import net.geforcemods.securitycraft.items.ItemModule;
import net.geforcemods.securitycraft.items.ItemReinforcedDoor;
import net.geforcemods.securitycraft.items.ItemSCManual;
import net.geforcemods.securitycraft.items.ItemScannerDoor;
import net.geforcemods.securitycraft.items.ItemTaser;
import net.geforcemods.securitycraft.items.ItemUniversalBlockModifier;
import net.geforcemods.securitycraft.items.ItemUniversalBlockReinforcer;
import net.geforcemods.securitycraft.items.ItemUniversalBlockRemover;
import net.geforcemods.securitycraft.items.ItemUniversalKeyChanger;
import net.geforcemods.securitycraft.items.ItemUniversalOwnerChanger;
import net.geforcemods.securitycraft.main.mod_SecurityCraft;
import net.geforcemods.securitycraft.misc.EnumCustomModules;
import net.geforcemods.securitycraft.misc.SCManualPage;
import net.geforcemods.securitycraft.misc.SCSounds;
import net.geforcemods.securitycraft.network.packets.PacketCPlaySoundAtPos;
import net.geforcemods.securitycraft.network.packets.PacketCRequestTEOwnableUpdate;
import net.geforcemods.securitycraft.network.packets.PacketCSetPlayerPositionAndRotation;
import net.geforcemods.securitycraft.network.packets.PacketCUpdateNBTTag;
import net.geforcemods.securitycraft.network.packets.PacketGivePotionEffect;
import net.geforcemods.securitycraft.network.packets.PacketSAddModules;
import net.geforcemods.securitycraft.network.packets.PacketSCheckPassword;
import net.geforcemods.securitycraft.network.packets.PacketSMountCamera;
import net.geforcemods.securitycraft.network.packets.PacketSOpenGui;
import net.geforcemods.securitycraft.network.packets.PacketSSetCameraRotation;
import net.geforcemods.securitycraft.network.packets.PacketSSetOwner;
import net.geforcemods.securitycraft.network.packets.PacketSSetPassword;
import net.geforcemods.securitycraft.network.packets.PacketSSyncTENBTTag;
import net.geforcemods.securitycraft.network.packets.PacketSToggleOption;
import net.geforcemods.securitycraft.network.packets.PacketSUpdateNBTTag;
import net.geforcemods.securitycraft.network.packets.PacketSUpdateTEOwnable;
import net.geforcemods.securitycraft.network.packets.PacketSetBlock;
import net.geforcemods.securitycraft.network.packets.PacketSetExplosiveState;
import net.geforcemods.securitycraft.network.packets.PacketSetISType;
import net.geforcemods.securitycraft.network.packets.PacketSetKeycardLevel;
import net.geforcemods.securitycraft.network.packets.PacketUpdateLogger;
import net.geforcemods.securitycraft.tileentity.TileEntityAlarm;
import net.geforcemods.securitycraft.tileentity.TileEntityCageTrap;
import net.geforcemods.securitycraft.tileentity.TileEntityClaymore;
import net.geforcemods.securitycraft.tileentity.TileEntityIMS;
import net.geforcemods.securitycraft.tileentity.TileEntityInventoryScanner;
import net.geforcemods.securitycraft.tileentity.TileEntityKeycardReader;
import net.geforcemods.securitycraft.tileentity.TileEntityKeypad;
import net.geforcemods.securitycraft.tileentity.TileEntityKeypadChest;
import net.geforcemods.securitycraft.tileentity.TileEntityKeypadFurnace;
import net.geforcemods.securitycraft.tileentity.TileEntityLaserBlock;
import net.geforcemods.securitycraft.tileentity.TileEntityLogger;
import net.geforcemods.securitycraft.tileentity.TileEntityOwnable;
import net.geforcemods.securitycraft.tileentity.TileEntityPortableRadar;
import net.geforcemods.securitycraft.tileentity.TileEntityProtecto;
import net.geforcemods.securitycraft.tileentity.TileEntityRetinalScanner;
import net.geforcemods.securitycraft.tileentity.TileEntityScannerDoor;
import net.geforcemods.securitycraft.tileentity.TileEntitySecurityCamera;
import net.geforcemods.securitycraft.util.ClientUtils;
import net.geforcemods.securitycraft.util.ItemUtils;
import net.minecraft.block.Block;
import net.minecraft.block.BlockStaticLiquid;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumBlockRenderType;
import net.minecraft.util.NonNullList;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.SoundEvent;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.config.Property;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper;
import net.minecraftforge.fml.common.registry.EntityRegistry;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
public class ConfigurationHandler{
private int[] harmingPotions = {8268, 8236, 16460, 16428};
private int[] healingPotions = {8261, 8229, 16453, 16421};
/**
* Registers a block and its ItemBlock and adds the help info for the block to the SecurityCraft manual item
* @param block The block to register
*/
private void registerBlock(Block block)
{
registerBlock(block, new ItemBlock(block), true);
}
/**
* Registers a block and its ItemBlock
* @param block The Block to register
* @param initPage Wether a SecurityCraft Manual page should be added for the block
*/
private void registerBlock(Block block, boolean initPage)
{
registerBlock(block, new ItemBlock(block), initPage);
}
/**
* Registers a block with a custom ItemBlock
* @param block The Block to register
* @param itemBlock The ItemBlock to register
* @param initPage Wether a SecurityCraft Manual page should be added for the block
*/
private void registerBlock(Block block, ItemBlock itemBlock, boolean initPage){
GameRegistry.register(block);
GameRegistry.register(itemBlock.setRegistryName(block.getRegistryName().toString()));
if(initPage)
mod_SecurityCraft.instance.manualPages.add(new SCManualPage(Item.getItemFromBlock(block), ClientUtils.localize("help." + block.getUnlocalizedName().substring(5) + ".info")));
}
/**
* Registers the given block with GameRegistry.registerBlock(), and adds the help info for the block to the SecurityCraft manual item.
* Also overrides the default recipe that would've been drawn in the manual with a new recipe.
*
*/
private void registerBlockWithCustomRecipe(Block block, ItemStack... customRecipe){
GameRegistry.register(block);
GameRegistry.register(new ItemBlock(block).setRegistryName(block.getRegistryName().toString()));
NonNullList<ItemStack> recipeItems = NonNullList.<ItemStack>withSize(customRecipe.length, ItemStack.EMPTY);
for(int i = 0; i < recipeItems.size(); i++)
{
recipeItems.set(i, customRecipe[i]);
}
mod_SecurityCraft.instance.manualPages.add(new SCManualPage(Item.getItemFromBlock(block), ClientUtils.localize("help." + block.getUnlocalizedName().substring(5) + ".info"), recipeItems));
}
/**
* Registers the given item with GameRegistry.registerItem(), and adds the help info for the item to the SecurityCraft manual item.
*/
private void registerItem(Item item){
GameRegistry.register(item);
mod_SecurityCraft.instance.manualPages.add(new SCManualPage(item, ClientUtils.localize("help." + item.getUnlocalizedName().substring(5) + ".info")));
}
public void setupOtherRegistries(){
EnumCustomModules.refresh();
}
public void setupEntityRegistry() {
EntityRegistry.registerModEntity(new ResourceLocation("securitycraft", "bouncingbetty"), EntityBouncingBetty.class, "BBetty", 0, mod_SecurityCraft.instance, 128, 1, true);
EntityRegistry.registerModEntity(new ResourceLocation("securitycraft", "taserbullet"), EntityTaserBullet.class, "TazerBullet", 2, mod_SecurityCraft.instance, 256, 1, true);
EntityRegistry.registerModEntity(new ResourceLocation("securitycraft", "imsbomb"), EntityIMSBomb.class, "IMSBomb", 3, mod_SecurityCraft.instance, 256, 1, true);
EntityRegistry.registerModEntity(new ResourceLocation("securitycraft", "securitycamera"), EntitySecurityCamera.class, "SecurityCamera", 4, mod_SecurityCraft.instance, 256, 20, false);
}
public void setupHandlers(FMLPreInitializationEvent event) {
MinecraftForge.EVENT_BUS.register(mod_SecurityCraft.eventHandler);
}
public void setupPackets(SimpleNetworkWrapper network) {
network.registerMessage(PacketSetBlock.Handler.class, PacketSetBlock.class, 1, Side.SERVER);
network.registerMessage(PacketSetISType.Handler.class, PacketSetISType.class, 2, Side.SERVER);
network.registerMessage(PacketSetKeycardLevel.Handler.class, PacketSetKeycardLevel.class, 3, Side.SERVER);
network.registerMessage(PacketUpdateLogger.Handler.class, PacketUpdateLogger.class, 4, Side.CLIENT);
network.registerMessage(PacketCUpdateNBTTag.Handler.class, PacketCUpdateNBTTag.class, 5, Side.CLIENT);
network.registerMessage(PacketSUpdateNBTTag.Handler.class, PacketSUpdateNBTTag.class, 6, Side.SERVER);
network.registerMessage(PacketCPlaySoundAtPos.Handler.class, PacketCPlaySoundAtPos.class, 7, Side.CLIENT);
network.registerMessage(PacketSetExplosiveState.Handler.class, PacketSetExplosiveState.class, 8, Side.SERVER);
network.registerMessage(PacketGivePotionEffect.Handler.class, PacketGivePotionEffect.class, 9, Side.SERVER);
network.registerMessage(PacketSSetOwner.Handler.class, PacketSSetOwner.class, 10, Side.SERVER);
network.registerMessage(PacketSAddModules.Handler.class, PacketSAddModules.class, 11, Side.SERVER);
network.registerMessage(PacketSSetPassword.Handler.class, PacketSSetPassword.class, 12, Side.SERVER);
network.registerMessage(PacketSCheckPassword.Handler.class, PacketSCheckPassword.class, 13, Side.SERVER);
network.registerMessage(PacketSSyncTENBTTag.Handler.class, PacketSSyncTENBTTag.class, 14, Side.SERVER);
network.registerMessage(PacketSMountCamera.Handler.class, PacketSMountCamera.class, 15, Side.SERVER);
network.registerMessage(PacketSSetCameraRotation.Handler.class, PacketSSetCameraRotation.class, 16, Side.SERVER);
network.registerMessage(PacketCSetPlayerPositionAndRotation.Handler.class, PacketCSetPlayerPositionAndRotation.class, 17, Side.CLIENT);
network.registerMessage(PacketSOpenGui.Handler.class, PacketSOpenGui.class, 18, Side.SERVER);
network.registerMessage(PacketSToggleOption.Handler.class, PacketSToggleOption.class, 19, Side.SERVER);
network.registerMessage(PacketCRequestTEOwnableUpdate.Handler.class, PacketCRequestTEOwnableUpdate.class, 20, Side.SERVER);
network.registerMessage(PacketSUpdateTEOwnable.Handler.class, PacketSUpdateTEOwnable.class, 21, Side.CLIENT);
}
@SideOnly(Side.CLIENT)
public void setupTextureRegistry() {
//Blocks
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.keypad), 0, new ModelResourceLocation("securitycraft:keypad", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.frame), 0, new ModelResourceLocation("securitycraft:keypad_frame", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.reinforcedStone), 0, new ModelResourceLocation("securitycraft:reinforced_stone", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.laserBlock), 0, new ModelResourceLocation("securitycraft:laser_block", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.laser), 0, new ModelResourceLocation("securitycraft:laser", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.keypadChest), 0, new ModelResourceLocation("securitycraft:keypad_chest", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.reinforcedDoor), 0, new ModelResourceLocation("securitycraft:reinforced_iron_door", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.ironTrapdoor), 0, new ModelResourceLocation("securitycraft:reinforced_iron_trapdoor", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.keycardReader), 0, new ModelResourceLocation("securitycraft:keycard_reader", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.inventoryScanner), 0, new ModelResourceLocation("securitycraft:inventory_scanner", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.cageTrap), 0, new ModelResourceLocation("securitycraft:cage_trap", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.inventoryScannerField), 0, new ModelResourceLocation("securitycraft:inventory_scanner_field", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.retinalScanner), 0, new ModelResourceLocation("securitycraft:retinal_scanner", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.unbreakableIronBars), 0, new ModelResourceLocation("securitycraft:reinforced_iron_bars", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.portableRadar), 0, new ModelResourceLocation("securitycraft:portable_radar", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.alarm), 0, new ModelResourceLocation("securitycraft:alarm", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.alarmLit), 0, new ModelResourceLocation("securitycraft:alarm_lit", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.usernameLogger), 0, new ModelResourceLocation("securitycraft:username_logger", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.reinforcedFencegate), 0, new ModelResourceLocation("securitycraft:reinforced_fence_gate", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.ironFence), 0, new ModelResourceLocation("securitycraft:electrified_iron_fence", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.reinforcedWoodPlanks), 0, new ModelResourceLocation("securitycraft:reinforced_planks_oak", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.reinforcedWoodPlanks), 1, new ModelResourceLocation("securitycraft:reinforced_planks_spruce", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.reinforcedWoodPlanks), 2, new ModelResourceLocation("securitycraft:reinforced_planks_birch", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.reinforcedWoodPlanks), 3, new ModelResourceLocation("securitycraft:reinforced_planks_jungle", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.reinforcedWoodPlanks), 4, new ModelResourceLocation("securitycraft:reinforced_planks_acacia", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.reinforcedWoodPlanks), 5, new ModelResourceLocation("securitycraft:reinforced_planks_darkoak", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.reinforcedStairsStone), 0, new ModelResourceLocation("securitycraft:reinforced_stairs_stone", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.reinforcedStairsCobblestone), 0, new ModelResourceLocation("securitycraft:reinforced_stairs_cobblestone", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.reinforcedStairsOak), 0, new ModelResourceLocation("securitycraft:reinforced_stairs_oak", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.reinforcedStairsSpruce), 0, new ModelResourceLocation("securitycraft:reinforced_stairs_spruce", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.reinforcedStairsBirch), 0, new ModelResourceLocation("securitycraft:reinforced_stairs_birch", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.reinforcedStairsJungle), 0, new ModelResourceLocation("securitycraft:reinforced_stairs_jungle", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.reinforcedStairsAcacia), 0, new ModelResourceLocation("securitycraft:reinforced_stairs_acacia", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.reinforcedStairsDarkoak), 0, new ModelResourceLocation("securitycraft:reinforced_stairs_darkoak", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.reinforcedGlass), 0, new ModelResourceLocation("securitycraft:reinforced_glass_block", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.reinforcedStainedGlass), 0, new ModelResourceLocation("securitycraft:reinforced_stained_glass_white", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.reinforcedStainedGlass), 1, new ModelResourceLocation("securitycraft:reinforced_stained_glass_orange", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.reinforcedStainedGlass), 2, new ModelResourceLocation("securitycraft:reinforced_stained_glass_magenta", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.reinforcedStainedGlass), 3, new ModelResourceLocation("securitycraft:reinforced_stained_glass_light_blue", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.reinforcedStainedGlass), 4, new ModelResourceLocation("securitycraft:reinforced_stained_glass_yellow", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.reinforcedStainedGlass), 5, new ModelResourceLocation("securitycraft:reinforced_stained_glass_lime", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.reinforcedStainedGlass), 6, new ModelResourceLocation("securitycraft:reinforced_stained_glass_pink", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.reinforcedStainedGlass), 7, new ModelResourceLocation("securitycraft:reinforced_stained_glass_gray", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.reinforcedStainedGlass), 8, new ModelResourceLocation("securitycraft:reinforced_stained_glass_silver", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.reinforcedStainedGlass), 9, new ModelResourceLocation("securitycraft:reinforced_stained_glass_cyan", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.reinforcedStainedGlass), 10, new ModelResourceLocation("securitycraft:reinforced_stained_glass_purple", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.reinforcedStainedGlass), 11, new ModelResourceLocation("securitycraft:reinforced_stained_glass_blue", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.reinforcedStainedGlass), 12, new ModelResourceLocation("securitycraft:reinforced_stained_glass_brown", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.reinforcedStainedGlass), 13, new ModelResourceLocation("securitycraft:reinforced_stained_glass_green", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.reinforcedStainedGlass), 14, new ModelResourceLocation("securitycraft:reinforced_stained_glass_red", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.reinforcedStainedGlass), 15, new ModelResourceLocation("securitycraft:reinforced_stained_glass_black", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.keypadChest), 0, new ModelResourceLocation("securitycraft:keypad_chest", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.keypadFurnace), 0, new ModelResourceLocation("securitycraft:keypad_furnace", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.panicButton), 0, new ModelResourceLocation("securitycraft:panic_button", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.securityCamera), 0, new ModelResourceLocation("securitycraft:security_camera", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.reinforcedDirt), 0, new ModelResourceLocation("securitycraft:reinforced_dirt", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.reinforcedCobblestone), 0, new ModelResourceLocation("securitycraft:reinforced_cobblestone", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.reinforcedSandstone), 0, new ModelResourceLocation("securitycraft:reinforced_sandstone_normal", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.reinforcedSandstone), 1, new ModelResourceLocation("securitycraft:reinforced_sandstone_chiseled", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.reinforcedSandstone), 2, new ModelResourceLocation("securitycraft:reinforced_sandstone_smooth", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.reinforcedWoodSlabs), 0, new ModelResourceLocation("securitycraft:reinforced_wood_slabs_oak", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.reinforcedWoodSlabs), 1, new ModelResourceLocation("securitycraft:reinforced_wood_slabs_spruce", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.reinforcedWoodSlabs), 2, new ModelResourceLocation("securitycraft:reinforced_wood_slabs_birch", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.reinforcedWoodSlabs), 3, new ModelResourceLocation("securitycraft:reinforced_wood_slabs_jungle", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.reinforcedWoodSlabs), 4, new ModelResourceLocation("securitycraft:reinforced_wood_slabs_acacia", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.reinforcedWoodSlabs), 5, new ModelResourceLocation("securitycraft:reinforced_wood_slabs_darkoak", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.reinforcedStairsCobblestone), 0, new ModelResourceLocation("securitycraft:reinforced_stairs_cobblestone", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.reinforcedStairsSandstone), 0, new ModelResourceLocation("securitycraft:reinforced_stairs_sandstone", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.reinforcedStoneSlabs), 0, new ModelResourceLocation("securitycraft:reinforced_stone_slabs_stone", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.reinforcedStoneSlabs), 1, new ModelResourceLocation("securitycraft:reinforced_stone_slabs_cobblestone", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.reinforcedStoneSlabs), 2, new ModelResourceLocation("securitycraft:reinforced_stone_slabs_sandstone", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.protecto), 0, new ModelResourceLocation("securitycraft:protecto", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.scannerDoor), 0, new ModelResourceLocation("securitycraft:scanner_door", "inventory"));
//Items
ModelLoader.setCustomModelResourceLocation(mod_SecurityCraft.codebreaker, 0, new ModelResourceLocation("securitycraft:codebreaker", "inventory"));
ModelLoader.setCustomModelResourceLocation(mod_SecurityCraft.remoteAccessMine, 0, new ModelResourceLocation("securitycraft:remote_access_mine", "inventory"));
ModelLoader.setCustomModelResourceLocation(mod_SecurityCraft.reinforcedDoorItem, 0, new ModelResourceLocation("securitycraft:door_indestructible_iron_item", "inventory"));
ModelLoader.setCustomModelResourceLocation(mod_SecurityCraft.fWaterBucket, 0, new ModelResourceLocation("securitycraft:bucket_f_water", "inventory"));
ModelLoader.setCustomModelResourceLocation(mod_SecurityCraft.fLavaBucket, 0, new ModelResourceLocation("securitycraft:bucket_f_lava", "inventory"));
ModelLoader.setCustomModelResourceLocation(mod_SecurityCraft.keycardLV1, 0, new ModelResourceLocation("securitycraft:keycard_lv1", "inventory"));
ModelLoader.setCustomModelResourceLocation(mod_SecurityCraft.keycardLV2, 0, new ModelResourceLocation("securitycraft:keycard_lv2", "inventory"));
ModelLoader.setCustomModelResourceLocation(mod_SecurityCraft.keycardLV3, 0, new ModelResourceLocation("securitycraft:keycard_lv3", "inventory"));
ModelLoader.setCustomModelResourceLocation(mod_SecurityCraft.keycardLV4, 0, new ModelResourceLocation("securitycraft:keycard_lv4", "inventory"));
ModelLoader.setCustomModelResourceLocation(mod_SecurityCraft.keycardLV5, 0, new ModelResourceLocation("securitycraft:keycard_lv5", "inventory"));
ModelLoader.setCustomModelResourceLocation(mod_SecurityCraft.limitedUseKeycard, 0, new ModelResourceLocation("securitycraft:limited_use_keycard", "inventory"));
ModelLoader.setCustomModelResourceLocation(mod_SecurityCraft.universalBlockRemover, 0, new ModelResourceLocation("securitycraft:universal_block_remover", "inventory"));
ModelLoader.setCustomModelResourceLocation(mod_SecurityCraft.universalBlockModifier, 0, new ModelResourceLocation("securitycraft:universal_block_modifier", "inventory"));
ModelLoader.setCustomModelResourceLocation(mod_SecurityCraft.whitelistModule, 0, new ModelResourceLocation("securitycraft:whitelist_module", "inventory"));
ModelLoader.setCustomModelResourceLocation(mod_SecurityCraft.blacklistModule, 0, new ModelResourceLocation("securitycraft:blacklist_module", "inventory"));
ModelLoader.setCustomModelResourceLocation(mod_SecurityCraft.redstoneModule, 0, new ModelResourceLocation("securitycraft:redstone_module", "inventory"));
ModelLoader.setCustomModelResourceLocation(mod_SecurityCraft.harmingModule, 0, new ModelResourceLocation("securitycraft:harming_module", "inventory"));
ModelLoader.setCustomModelResourceLocation(mod_SecurityCraft.storageModule, 0, new ModelResourceLocation("securitycraft:storage_module", "inventory"));
ModelLoader.setCustomModelResourceLocation(mod_SecurityCraft.smartModule, 0, new ModelResourceLocation("securitycraft:smart_module", "inventory"));
ModelLoader.setCustomModelResourceLocation(mod_SecurityCraft.disguiseModule, 0, new ModelResourceLocation("securitycraft:disguise_module", "inventory"));
ModelLoader.setCustomModelResourceLocation(mod_SecurityCraft.wireCutters, 0, new ModelResourceLocation("securitycraft:wire_cutters", "inventory"));
ModelLoader.setCustomModelResourceLocation(mod_SecurityCraft.keyPanel, 0, new ModelResourceLocation("securitycraft:keypad_item", "inventory"));
ModelLoader.setCustomModelResourceLocation(mod_SecurityCraft.adminTool, 0, new ModelResourceLocation("securitycraft:admin_tool", "inventory"));
ModelLoader.setCustomModelResourceLocation(mod_SecurityCraft.cameraMonitor, 0, new ModelResourceLocation("securitycraft:camera_monitor", "inventory"));
ModelLoader.setCustomModelResourceLocation(mod_SecurityCraft.scManual, 0, new ModelResourceLocation("securitycraft:sc_manual", "inventory"));
ModelLoader.setCustomModelResourceLocation(mod_SecurityCraft.taser, 0, new ModelResourceLocation("securitycraft:taser", "inventory"));
ModelLoader.setCustomModelResourceLocation(mod_SecurityCraft.universalOwnerChanger, 0, new ModelResourceLocation("securitycraft:universal_owner_changer", "inventory"));
ModelLoader.setCustomModelResourceLocation(mod_SecurityCraft.universalBlockReinforcerLvL1, 0, new ModelResourceLocation("securitycraft:universal_block_reinforcer_lvl1", "inventory"));
ModelLoader.setCustomModelResourceLocation(mod_SecurityCraft.universalBlockReinforcerLvL2, 0, new ModelResourceLocation("securitycraft:universal_block_reinforcer_lvl2", "inventory"));
ModelLoader.setCustomModelResourceLocation(mod_SecurityCraft.universalBlockReinforcerLvL3, 0, new ModelResourceLocation("securitycraft:universal_block_reinforcer_lvl3", "inventory"));
ModelLoader.setCustomModelResourceLocation(mod_SecurityCraft.briefcase, 0, new ModelResourceLocation("securitycraft:briefcase", "inventory"));
ModelLoader.setCustomModelResourceLocation(mod_SecurityCraft.universalKeyChanger, 0, new ModelResourceLocation("securitycraft:universal_key_changer", "inventory"));
ModelLoader.setCustomModelResourceLocation(mod_SecurityCraft.scannerDoorItem, 0, new ModelResourceLocation("securitycraft:scanner_door_item", "inventory"));
//Mines
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.mine), 0, new ModelResourceLocation("securitycraft:mine", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.dirtMine), 0, new ModelResourceLocation("securitycraft:dirt_mine", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.stoneMine), 0, new ModelResourceLocation("securitycraft:stone_mine", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.cobblestoneMine), 0, new ModelResourceLocation("securitycraft:cobblestone_mine", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.sandMine), 0, new ModelResourceLocation("securitycraft:sand_mine", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.diamondOreMine), 0, new ModelResourceLocation("securitycraft:diamond_mine", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.furnaceMine), 0, new ModelResourceLocation("securitycraft:furnace_mine", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.trackMine), 0, new ModelResourceLocation("securitycraft:track_mine", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.bouncingBetty), 0, new ModelResourceLocation("securitycraft:bouncing_betty", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.claymore), 0, new ModelResourceLocation("securitycraft:claymore", "inventory"));
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(mod_SecurityCraft.ims), 0, new ModelResourceLocation("securitycraft:ims", "inventory"));
}
}
|
package nars.config;
import java.util.concurrent.atomic.AtomicInteger;
import nars.language.Interval.AtomicDuration;
import com.google.common.util.concurrent.AtomicDouble;
import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import nars.control.DerivationContext.DerivationFilter;
/**
* NAR Parameters which can be changed during runtime.
*/
public class RuntimeParameters implements Serializable {
public RuntimeParameters() { }
/** Silent threshold for task reporting, in [0, 100].
* Noise level = 100 - silence level; noise 0 = always silent, noise 100 = never silent
*/
public final AtomicInteger noiseLevel = new AtomicInteger(100);
/**
Cycles per duration.
Past/future tense usage convention;
How far away "past" and "future" is from "now", in cycles.
The range of "now" is [-DURATION/2, +DURATION/2]; */
public final AtomicDuration duration = new AtomicDuration(Parameters.DURATION);
/** Concept decay rate in ConceptBag, in [1, 99]. originally: CONCEPT_FORGETTING_CYCLE
* How many cycles it takes an item to decay completely to a threshold value (ex: 0.1).
* Lower means faster rate of decay.
*/
public final AtomicDouble conceptForgetDurations = new AtomicDouble(2.0);
/** TermLink decay rate in TermLinkBag, in [1, 99]. originally: TERM_LINK_FORGETTING_CYCLE */
public final AtomicDouble termLinkForgetDurations = new AtomicDouble(10.0);
/** TaskLink decay rate in TaskLinkBag, in [1, 99]. originally: TASK_LINK_FORGETTING_CYCLE */
public final AtomicDouble taskLinkForgetDurations = new AtomicDouble(4.0);
/** Sequence bag forget durations **/
public final AtomicDouble sequenceForgetDurations = new AtomicDouble(4.0);
/** novel task bag forget duration **/
public final AtomicDouble novelTaskForgetDurations = new AtomicDouble(2.0);
/** Minimum expectation for a desire value.
* the range of "now" is [-DURATION, DURATION]; */
public final AtomicDouble decisionThreshold = new AtomicDouble(0.51);
// //let NARS use NARS+ ideas (counting etc.)
// public final AtomicBoolean experimentalNarsPlus = new AtomicBoolean();
// //let NARS use NAL9 operators to perceive its own mental actions
// public final AtomicBoolean internalExperience = new AtomicBoolean();
//these two are AND-coupled:
//when a concept is important and exceeds a syntactic complexity, let NARS name it:
//public final AtomicInteger abbreviationMinComplexity = new AtomicInteger();
//public final AtomicDouble abbreviationMinQuality = new AtomicDouble();
public List<DerivationFilter> defaultDerivationFilters = new ArrayList();
public final List<DerivationFilter> getDerivationFilters() {
return defaultDerivationFilters;
}
}
|
package ca.josephroque.bowlingcompanion;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import ca.josephroque.bowlingcompanion.adapter.StatsAdapter;
import ca.josephroque.bowlingcompanion.data.ConvertValue;
import ca.josephroque.bowlingcompanion.database.Contract.*;
import ca.josephroque.bowlingcompanion.database.DatabaseHelper;
import ca.josephroque.bowlingcompanion.theme.ChangeableTheme;
import ca.josephroque.bowlingcompanion.theme.Theme;
public class StatsActivity extends ActionBarActivity
implements ChangeableTheme
{
/** Tag to identify class when outputting to console */
private static final String TAG = "StatsActivity";
/** Represent names of general stats related to the middle pin */
private static final String[] STATS_MIDDLE_GENERAL =
{"Middle Hit", "Strikes", "Spare Conversions"};
/** Represent names of specific stats related to middle pin*/
private static final String[] STATS_MIDDLE_DETAILED =
{"Head Pins", "Head Pins Spared",
"Lefts", "Lefts Spared", "Rights", "Rights Spared",
"Aces", "Aces Spared",
"Chop Offs", "Chop Offs Spared", "Left Chop Offs", "Left Chop Offs Spared", "Right Chop Offs", "Right Chop Offs Spared",
"Splits", "Splits Spared", "Left Splits", "Left Splits Spared", "Right Splits", "Right Splits Spared"};
/** Represent names of stats related to fouls */
private static final String[] STATS_FOULS =
{"Fouls"};
/** Represent names of stats related to pins left standing at the end of each frame */
private static final String[] STATS_PINS_TOTAL =
{"Pins Left"};
/** Represent names of stats related to average pins left standing per game */
private static final String[] STATS_PINS_AVERAGE =
{"Average Pins Left"};
/** Represent games of general stats about a bowler, league. or event */
private static final String[] STATS_GENERAL =
{"Average", "High Single", "High Series", "Total Pinfall", "# of Games"};
/** Indicates all the stats related to the specified bowler should be loaded */
private static final byte LOADING_BOWLER_STATS = 0;
/** Indicates all the stats related to the specified league should be loaded */
private static final byte LOADING_LEAGUE_STATS = 1;
/** Indicates all the stats related to the specified series should be loaded */
private static final byte LOADING_SERIES_STATS = 2;
/** Indicates only the stats related to the specified game should be loaded */
private static final byte LOADING_GAME_STATS = 3;
/** Displays the stat names and values in a list to the user */
private RecyclerView mStatsRecycler;
/** Organizes stat data into a list to be displayed by mStatsRecycler */
private StatsAdapter mStatsAdapter;
/** List of names of stats that will be displayed to the user */
private List<String> mListStatNames;
/** List of values of stats corresponding to those named in mListStatNames */
private List<String> mListStatValues;
/** Name of the bowler whose stats are being displayed */
private String mBowlerName;
/** Name of the league whose stats are being displayed */
private String mLeagueName;
private String mSeriesDate;
/** Id of the bowler whose stats will be loaded and displayed */
private long mBowlerId = -1;
/** Id of the league whose stats will be loaded and displayed */
private long mLeagueId = -1;
private long mSeriesId = -1;
/** Id of the game whose stats will be loaded and displayed */
private long mGameId = -1;
/** Number of the game in the series being loaded */
private byte mGameNumber = -1;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stats);
//Enables backtracking to activity which created this stats activity, since it's not always the same
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mListStatNames = new ArrayList<>();
mListStatValues = new ArrayList<>();
mStatsRecycler = (RecyclerView)findViewById(R.id.recyclerView_stats);
mStatsRecycler.setHasFixedSize(true);
mStatsRecycler.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
mStatsRecycler.setLayoutManager(layoutManager);
mStatsAdapter = new StatsAdapter(this, mListStatNames, mListStatValues);
mStatsRecycler.setAdapter(mStatsAdapter);
if (savedInstanceState != null)
{
mBowlerId = savedInstanceState.getLong(Constants.EXTRA_ID_BOWLER);
mLeagueId = savedInstanceState.getLong(Constants.EXTRA_ID_LEAGUE);
mSeriesId = savedInstanceState.getLong(Constants.EXTRA_ID_SERIES);
mGameId = savedInstanceState.getLong(Constants.EXTRA_ID_GAME);
mBowlerName = savedInstanceState.getString(Constants.EXTRA_NAME_BOWLER);
mLeagueName = savedInstanceState.getString(Constants.EXTRA_NAME_LEAGUE);
mSeriesDate = savedInstanceState.getString(Constants.EXTRA_NAME_SERIES);
mGameNumber = savedInstanceState.getByte(Constants.EXTRA_GAME_NUMBER);
}
updateTheme();
}
@Override
protected void onResume()
{
super.onResume();
if (mBowlerId == -1)
{
mBowlerId = getIntent().getLongExtra(Constants.EXTRA_ID_BOWLER, -1);
mLeagueId = getIntent().getLongExtra(Constants.EXTRA_ID_LEAGUE, -1);
mSeriesId = getIntent().getLongExtra(Constants.EXTRA_ID_SERIES, -1);
mGameId = getIntent().getLongExtra(Constants.EXTRA_ID_GAME, -1);
mBowlerName = getIntent().getStringExtra(Constants.EXTRA_NAME_BOWLER);
mLeagueName = getIntent().getStringExtra(Constants.EXTRA_NAME_LEAGUE);
mSeriesDate = getIntent().getStringExtra(Constants.EXTRA_NAME_SERIES);
mGameNumber = getIntent().getByteExtra(Constants.EXTRA_GAME_NUMBER, (byte)-1);
}
try
{
mSeriesDate = ConvertValue.formattedDateToPrettyCompact(mSeriesDate.substring(0,10));
}
catch (IllegalArgumentException ex)
{
//Does nothing, date is already formatted
}
mListStatNames.clear();
mListStatValues.clear();
byte statsToLoad;
int titleToSet;
if (mGameId == -1)
{
if (mSeriesId == -1)
{
if (mLeagueId == -1)
{
titleToSet = R.string.title_activity_stats_bowler;
statsToLoad = LOADING_BOWLER_STATS;
}
else
{
titleToSet = R.string.title_activity_stats_league;
statsToLoad = LOADING_LEAGUE_STATS;
}
}
else
{
titleToSet = R.string.title_activity_stats_series;
statsToLoad = LOADING_SERIES_STATS;
}
}
else
{
titleToSet = R.string.title_activity_stats_game;
statsToLoad = LOADING_GAME_STATS;
}
if(Theme.getStatsActivityThemeInvalidated())
{
updateTheme();
}
setTitle(titleToSet);
new LoadStatsTask().execute(statsToLoad);
}
@Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putString(Constants.EXTRA_NAME_BOWLER, mBowlerName);
outState.putString(Constants.EXTRA_NAME_LEAGUE, mLeagueName);
outState.putString(Constants.EXTRA_NAME_SERIES, mSeriesDate);
outState.putLong(Constants.EXTRA_ID_BOWLER, mBowlerId);
outState.putLong(Constants.EXTRA_ID_LEAGUE, mLeagueId);
outState.putLong(Constants.EXTRA_ID_SERIES, mSeriesId);
outState.putLong(Constants.EXTRA_ID_GAME, mGameId);
outState.putByte(Constants.EXTRA_GAME_NUMBER, mGameNumber);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_stats, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch(item.getItemId())
{
case android.R.id.home:
this.finish();
return true;
case R.id.action_settings:
showSettingsMenu();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Creates a new settings activity and displays it to the user
*/
private void showSettingsMenu()
{
Intent settingsIntent = new Intent(this, SettingsActivity.class);
settingsIntent.putExtra(Constants.EXTRA_SETTINGS_SOURCE, TAG);
startActivity(settingsIntent);
}
/**
* Checks which situation has occurred by the state of the pins in ball
*
* @param ball result of the pins after a ball was thrown
* @param statValues stat values to update
* @param offset indicates a spare was thrown and the spare count should be increased for a stat
*/
private void increaseFirstBallStat(int ball, int[] statValues, int offset)
{
if (offset > 1 || offset < 0)
throw new IllegalArgumentException("Offset must be either 0 or 1: " + offset);
switch(ball)
{
case Constants.BALL_VALUE_STRIKE:
if (offset == 0)
{
statValues[Constants.STAT_STRIKES]++;
}
break;
case Constants.BALL_VALUE_LEFT:statValues[Constants.STAT_LEFTS + offset]++; break;
case Constants.BALL_VALUE_RIGHT:statValues[Constants.STAT_RIGHTS + offset]++; break;
case Constants.BALL_VALUE_LEFT_CHOP:
statValues[Constants.STAT_LEFT_CHOP_OFFS + offset]++;
statValues[Constants.STAT_CHOP_OFFS + offset]++;
break;
case Constants.BALL_VALUE_RIGHT_CHOP:
statValues[Constants.STAT_RIGHT_CHOP_OFFS + offset]++;
statValues[Constants.STAT_CHOP_OFFS + offset]++;
break;
case Constants.BALL_VALUE_ACE:statValues[Constants.STAT_ACES + offset]++; break;
case Constants.BALL_VALUE_LEFT_SPLIT:
statValues[Constants.STAT_LEFT_SPLITS + offset]++;
statValues[Constants.STAT_SPLITS + offset]++;
break;
case Constants.BALL_VALUE_RIGHT_SPLIT:
statValues[Constants.STAT_RIGHT_SPLITS + offset]++;
statValues[Constants.STAT_SPLITS + offset]++;
break;
case Constants.BALL_VALUE_HEAD_PIN:statValues[Constants.STAT_HEAD_PINS + offset]++;
}
}
/**
* Counts the total value of pins which were left at the end of a frame on the third ball
*
* @param thirdBall state of the pins after the third ball
* @return total value of pins left standing
*/
private int countPinsLeftStanding(boolean[] thirdBall)
{
int pinsLeftStanding = 0;
for (int i = 0; i < thirdBall.length; i++)
{
if (!thirdBall[i])
{
switch(i)
{
case 0:case 4:pinsLeftStanding += 2; break;
case 1:case 3:pinsLeftStanding += 3; break;
case 2:pinsLeftStanding += 5; break;
}
}
}
return pinsLeftStanding;
}
/**
* Returns the indicated state of the pins after a ball was thrown
*
* @param firstBall the ball thrown
* @return the state of the pins after a ball was thrown
*/
private int getFirstBallValue(boolean[] firstBall)
{
if (!firstBall[2])
{
return -1;
}
int numberOfPinsKnockedDown = 0;
for (boolean knockedDown: firstBall)
{
if (knockedDown)
numberOfPinsKnockedDown++;
}
if (numberOfPinsKnockedDown == 5)
return Constants.BALL_VALUE_STRIKE;
else if (numberOfPinsKnockedDown == 4)
{
if (!firstBall[0])
return Constants.BALL_VALUE_LEFT;
else if (!firstBall[4])
return Constants.BALL_VALUE_RIGHT;
}
else if (numberOfPinsKnockedDown == 3)
{
if (!firstBall[3] && !firstBall[4])
return Constants.BALL_VALUE_LEFT_CHOP;
else if (!firstBall[0] && !firstBall[1])
return Constants.BALL_VALUE_RIGHT_CHOP;
else if (!firstBall[0] && !firstBall[4])
return Constants.BALL_VALUE_ACE;
}
else if (numberOfPinsKnockedDown == 2)
{
if (firstBall[1])
return Constants.BALL_VALUE_LEFT_SPLIT;
else if (firstBall[3])
return Constants.BALL_VALUE_RIGHT_SPLIT;
}
else
return Constants.BALL_VALUE_HEAD_PIN;
return -2;
}
/**
* Sets the strings in the list mListStatValues
*
* @param statValues raw value of stat
* @param totalShotsAtMiddle total "first ball" opportunities for a game, league or bowler
* @param spareChances total chances a bowler had to spare a ball
* @param statOffset position in mListStatValues to start altering
*/
private void setGeneralAndDetailedStatValues(final int[] statValues, final int totalShotsAtMiddle, final int spareChances, final int statOffset)
{
int currentStatPosition = statOffset;
final DecimalFormat decimalFormat = new DecimalFormat("
if (statValues[Constants.STAT_MIDDLE_HIT] > 0)
{
mListStatValues.set(currentStatPosition,
decimalFormat.format(statValues[Constants.STAT_MIDDLE_HIT] / (double)totalShotsAtMiddle * 100)
+ "% [" + statValues[Constants.STAT_MIDDLE_HIT] + "/" + totalShotsAtMiddle + "]");
}
currentStatPosition++;
if (statValues[Constants.STAT_STRIKES] > 0)
{
mListStatValues.set(currentStatPosition,
decimalFormat.format(statValues[Constants.STAT_STRIKES] / (double) totalShotsAtMiddle * 100)
+ "% [" + statValues[Constants.STAT_STRIKES] + "/" + totalShotsAtMiddle + "]");
}
currentStatPosition++;
if (statValues[Constants.STAT_SPARE_CONVERSIONS] > 0)
{
mListStatValues.set(currentStatPosition,
decimalFormat.format(statValues[Constants.STAT_SPARE_CONVERSIONS] / (double) spareChances * 100)
+ "% [" + statValues[Constants.STAT_SPARE_CONVERSIONS] + "/" + spareChances + "]");
}
currentStatPosition++;
for (int i = Constants.STAT_HEAD_PINS; i < Constants.STAT_RIGHT_SPLITS_SPARED; i += 2, currentStatPosition += 2)
{
if (statValues[i] > 0)
{
mListStatValues.set(currentStatPosition,
decimalFormat.format(statValues[i] / (double) totalShotsAtMiddle * 100)
+ "% [" + statValues[i] + "/" + totalShotsAtMiddle + "]");
}
if (statValues[i + 1] > 0)
{
mListStatValues.set(currentStatPosition + 1,
decimalFormat.format(statValues[i + 1] / (double)statValues[i] * 100)
+ "% [" + statValues[i + 1] + "/" + statValues[i] + "]");
}
}
final int statValuesListSize = mListStatValues.size();
for (int i = Constants.STAT_FOULS; i <= Constants.STAT_NUMBER_OF_GAMES && statValuesListSize > currentStatPosition; i++, currentStatPosition++)
{
mListStatValues.set(currentStatPosition, String.valueOf(statValues[i]));
}
}
/**
* Adds header stat names and placeholder values to certain positions
* in mListStatNames and mListStatValues
*
* @param bowlerLeagueOrGame indicates whether a bowler, league or game's stats are being loaded
* @param NUMBER_OF_GENERAL_DETAILS number of general details at the start of the lists
*/
private void setStatHeaders(byte bowlerLeagueOrGame, final byte NUMBER_OF_GENERAL_DETAILS)
{
int nextHeaderPosition = 0;
mListStatNames.add(nextHeaderPosition, "-General");
mListStatValues.add(nextHeaderPosition, "-");
nextHeaderPosition += NUMBER_OF_GENERAL_DETAILS + STATS_MIDDLE_GENERAL.length + 1;
mListStatNames.add(nextHeaderPosition, "-First Ball");
mListStatValues.add(nextHeaderPosition, "-");
nextHeaderPosition += STATS_MIDDLE_DETAILED.length + 1;
mListStatNames.add(nextHeaderPosition, "-Fouls");
mListStatValues.add(nextHeaderPosition, "-");
nextHeaderPosition += STATS_FOULS.length + 1;
mListStatNames.add(nextHeaderPosition, "-Pins Left on Deck");
mListStatValues.add(nextHeaderPosition, "-");
if (bowlerLeagueOrGame < LOADING_GAME_STATS)
{
nextHeaderPosition += STATS_PINS_TOTAL.length + STATS_PINS_AVERAGE.length + 1;
mListStatNames.add(nextHeaderPosition, "-Overall");
mListStatValues.add(nextHeaderPosition, "-");
}
}
/**
* Returns a cursor from database to load either bowler or league stats
*
* @param shouldGetLeagueStats if true, league stats will be loaded. Bowler stats will be loaded otherwise
* @return a cursor with rows relevant to mBowlerId or mLeagueId
*/
private Cursor getBowlerOrLeagueCursor(boolean shouldGetLeagueStats)
{
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean isEventIncluded = preferences.getBoolean(Constants.KEY_PREF_INCLUDE_EVENTS, true);
boolean isOpenIncluded = preferences.getBoolean(Constants.KEY_PREF_INCLUDE_OPEN, true);
SQLiteDatabase database = DatabaseHelper.getInstance(this).getReadableDatabase();
String rawStatsQuery = "SELECT "
+ GameEntry.COLUMN_NAME_GAME_FINAL_SCORE + ", "
+ GameEntry.COLUMN_NAME_GAME_NUMBER + ", "
+ FrameEntry.COLUMN_NAME_FRAME_NUMBER + ", "
+ FrameEntry.COLUMN_NAME_FRAME_ACCESSED + ", "
+ FrameEntry.COLUMN_NAME_FOULS + ", "
+ FrameEntry.COLUMN_NAME_BALL[0] + ", "
+ FrameEntry.COLUMN_NAME_BALL[1] + ", "
+ FrameEntry.COLUMN_NAME_BALL[2]
+ " FROM " + LeagueEntry.TABLE_NAME + " AS league"
+ " LEFT JOIN " + GameEntry.TABLE_NAME + " AS game"
+ " ON league." + LeagueEntry._ID + "=" + GameEntry.COLUMN_NAME_LEAGUE_ID
+ " LEFT JOIN " + FrameEntry.TABLE_NAME + " AS frame"
+ " ON game." + GameEntry._ID + "=" + FrameEntry.COLUMN_NAME_GAME_ID
+ ((shouldGetLeagueStats)
? " WHERE game." + GameEntry.COLUMN_NAME_LEAGUE_ID + "=?"
: " WHERE game." + GameEntry.COLUMN_NAME_BOWLER_ID + "=?")
+ ((!isEventIncluded)
? " AND league." + LeagueEntry.COLUMN_NAME_IS_EVENT + "=?"
: " AND 0=?"
+ ((!isOpenIncluded)
? " AND league." + LeagueEntry.COLUMN_NAME_LEAGUE_NAME + "!=?"
: " AND Open=?"))
+ " ORDER BY game." + GameEntry._ID + ", frame." + FrameEntry.COLUMN_NAME_FRAME_NUMBER;
String[] rawStatsArgs = {
((shouldGetLeagueStats)
? String.valueOf(mLeagueId)
: String.valueOf(mBowlerId)),
String.valueOf(0),
String.valueOf("Open")};
return database.rawQuery(rawStatsQuery, rawStatsArgs);
}
/**
* Returns a cursor from database to load series stats
*
* @return a cursor with rows relevant to mSeriesId
*/
private Cursor getSeriesCursor()
{
SQLiteDatabase database = DatabaseHelper.getInstance(this).getReadableDatabase();
String rawStatsQuery = "SELECT "
+ GameEntry.COLUMN_NAME_GAME_FINAL_SCORE + ", "
+ GameEntry.COLUMN_NAME_GAME_NUMBER + ", "
+ FrameEntry.COLUMN_NAME_FRAME_NUMBER + ", "
+ FrameEntry.COLUMN_NAME_FRAME_ACCESSED + ", "
+ FrameEntry.COLUMN_NAME_FOULS + ", "
+ FrameEntry.COLUMN_NAME_BALL[0] + ", "
+ FrameEntry.COLUMN_NAME_BALL[1] + ", "
+ FrameEntry.COLUMN_NAME_BALL[2]
+ " FROM " + GameEntry.TABLE_NAME + " AS game"
+ " LEFT JOIN " + FrameEntry.TABLE_NAME + " AS frame"
+ " ON game." + GameEntry._ID + "=" + FrameEntry.COLUMN_NAME_GAME_ID
+ " WHERE game." + GameEntry.COLUMN_NAME_SERIES_ID + "=?"
+ " ORDER BY game." + GameEntry._ID + ", frame." + FrameEntry.COLUMN_NAME_FRAME_NUMBER;
String[] rawStatsArgs = {String.valueOf(mSeriesId)};
return database.rawQuery(rawStatsQuery, rawStatsArgs);
}
/**
* Returns a cursor from the database to load game stats
*
* @return a cursor with rows relevant to mGameId
*/
private Cursor getGameCursor()
{
SQLiteDatabase database = DatabaseHelper.getInstance(this).getReadableDatabase();
String rawStatsQuery = "SELECT "
+ "game." + GameEntry.COLUMN_NAME_GAME_FINAL_SCORE + ", "
+ FrameEntry.COLUMN_NAME_FRAME_NUMBER + ", "
+ FrameEntry.COLUMN_NAME_FRAME_ACCESSED + ", "
+ FrameEntry.COLUMN_NAME_FOULS + ", "
+ FrameEntry.COLUMN_NAME_BALL[0] + ", "
+ FrameEntry.COLUMN_NAME_BALL[1] + ", "
+ FrameEntry.COLUMN_NAME_BALL[2]
+ " FROM " + GameEntry.TABLE_NAME + " AS game"
+ " JOIN " + FrameEntry.TABLE_NAME
+ " ON game." + GameEntry._ID + "=" + FrameEntry.COLUMN_NAME_GAME_ID
+ " WHERE " + FrameEntry.COLUMN_NAME_GAME_ID + "=?"
+ " ORDER BY " + FrameEntry.COLUMN_NAME_FRAME_NUMBER;
String[] rawStatsArgs = {String.valueOf(mGameId)};
return database.rawQuery(rawStatsQuery, rawStatsArgs);
}
/**
* Loads the data on a game, league or bowler and adds it to mStatsAdapter
*/
private class LoadStatsTask extends AsyncTask<Byte, Void, Void>
{
@Override
protected Void doInBackground(Byte... bowlerLeagueOrGameParam)
{
final byte bowlerLeagueOrGame = bowlerLeagueOrGameParam[0];
final byte NUMBER_OF_GENERAL_DETAILS;
Cursor cursor;
int[] statValues;
mListStatNames.add("Bowler");
mListStatValues.add(mBowlerName);
//Adds only names to list which are relevant to the data being loaded
mListStatNames.addAll(Arrays.asList(STATS_MIDDLE_GENERAL));
mListStatNames.addAll(Arrays.asList(STATS_MIDDLE_DETAILED));
mListStatNames.addAll(Arrays.asList(STATS_FOULS));
mListStatNames.addAll(Arrays.asList(STATS_PINS_TOTAL));
switch(bowlerLeagueOrGame)
{
case LOADING_BOWLER_STATS:
NUMBER_OF_GENERAL_DETAILS = 1;
mListStatNames.addAll(Arrays.asList(STATS_PINS_AVERAGE));
mListStatNames.addAll(Arrays.asList(STATS_GENERAL));
statValues = new int[STATS_MIDDLE_GENERAL.length + STATS_MIDDLE_DETAILED.length
+ STATS_FOULS.length + STATS_PINS_TOTAL.length + STATS_PINS_AVERAGE.length
+ STATS_GENERAL.length];
cursor = getBowlerOrLeagueCursor(false);
break;
case LOADING_LEAGUE_STATS:
NUMBER_OF_GENERAL_DETAILS = 2;
mListStatNames.add(1, "League/Event");
mListStatValues.add(1, mLeagueName);
mListStatNames.addAll(Arrays.asList(STATS_PINS_AVERAGE));
mListStatNames.addAll(Arrays.asList(STATS_GENERAL));
statValues = new int[STATS_MIDDLE_GENERAL.length + STATS_MIDDLE_DETAILED.length
+ STATS_FOULS.length + STATS_PINS_TOTAL.length + STATS_PINS_AVERAGE.length
+ STATS_GENERAL.length];
cursor = getBowlerOrLeagueCursor(true);
break;
case LOADING_SERIES_STATS:
NUMBER_OF_GENERAL_DETAILS = 3;
mListStatNames.add(1, "League/Event");
mListStatValues.add(1, mLeagueName);
mListStatNames.add(2, "Date");
mListStatValues.add(2, mSeriesDate);
mListStatNames.addAll(Arrays.asList(STATS_PINS_AVERAGE));
mListStatNames.addAll(Arrays.asList(STATS_GENERAL));
mListStatNames.set(NUMBER_OF_GENERAL_DETAILS + Constants.STAT_HIGH_SERIES, "Series Total");
statValues = new int[STATS_MIDDLE_GENERAL.length + STATS_MIDDLE_DETAILED.length
+ STATS_FOULS.length + STATS_PINS_TOTAL.length + STATS_PINS_AVERAGE.length
+ STATS_GENERAL.length];
cursor = getSeriesCursor();
break;
case LOADING_GAME_STATS:
NUMBER_OF_GENERAL_DETAILS = 4;
mListStatNames.add(1, "League/Event");
mListStatValues.add(1, mLeagueName);
mListStatNames.add(2, "Date");
mListStatValues.add(2, mSeriesDate);
mListStatNames.add(3, "Game
mListStatValues.add(3, String.valueOf(mGameNumber));
statValues = new int[STATS_MIDDLE_GENERAL.length + STATS_MIDDLE_DETAILED.length
+ STATS_FOULS.length + STATS_PINS_TOTAL.length];
cursor = getGameCursor();
break;
default:
throw new IllegalArgumentException("bowlerLeagueOrGame must be between 0 and 2 (inclusive");
}
int i = mListStatValues.size();
while (i < mListStatNames.size())
{
mListStatValues.add("
i++;
}
/*
* Passes through rows in the database and updates stats which are affected as each
* frame is analyzed
*/
int totalShotsAtMiddle = 0;
int spareChances = 0;
int seriesTotal = 0;
if (cursor.moveToFirst())
{
while(!cursor.isAfterLast())
{
boolean frameAccessed = (cursor.getInt(cursor.getColumnIndex(FrameEntry.COLUMN_NAME_FRAME_ACCESSED)) == 1);
if (bowlerLeagueOrGame == LOADING_GAME_STATS && !frameAccessed)
break;
byte frameNumber = (byte)cursor.getInt(cursor.getColumnIndex(FrameEntry.COLUMN_NAME_FRAME_NUMBER));
String frameFouls = cursor.getString(cursor.getColumnIndex(FrameEntry.COLUMN_NAME_FOULS));
String[] ballStrings = {cursor.getString(cursor.getColumnIndex(FrameEntry.COLUMN_NAME_BALL[0])),
cursor.getString(cursor.getColumnIndex(FrameEntry.COLUMN_NAME_BALL[1])),
cursor.getString(cursor.getColumnIndex(FrameEntry.COLUMN_NAME_BALL[2]))};
boolean[][] pinState = new boolean[3][5];
for (i = 0; i < 5; i++)
{
pinState[0][i] = ballStrings[0].charAt(i) == '1';
pinState[1][i] = ballStrings[1].charAt(i) == '1';
pinState[2][i] = ballStrings[2].charAt(i) == '1';
}
for (i = 1; i <= 3; i++)
{
if (frameFouls.contains(String.valueOf(i)))
statValues[Constants.STAT_FOULS]++;
}
if (bowlerLeagueOrGame != LOADING_GAME_STATS || frameAccessed)
{
if (frameNumber == Constants.NUMBER_OF_FRAMES)
{
totalShotsAtMiddle++;
int ballValue = getFirstBallValue(pinState[0]);
if (ballValue != -1)
statValues[Constants.STAT_MIDDLE_HIT]++;
increaseFirstBallStat(ballValue, statValues, 0);
if (ballValue < 5 && ballValue != Constants.BALL_VALUE_STRIKE)
spareChances++;
if (ballValue != 0)
{
if (Arrays.equals(pinState[1], Constants.FRAME_PINS_DOWN))
{
statValues[Constants.STAT_SPARE_CONVERSIONS]++;
increaseFirstBallStat(ballValue, statValues, 1);
if (ballValue >= 5)
spareChances++;
}
else
{
statValues[Constants.STAT_PINS_LEFT_ON_DECK] += countPinsLeftStanding(pinState[2]);
}
}
else
{
totalShotsAtMiddle++;
ballValue = getFirstBallValue(pinState[1]);
if (ballValue != -1)
statValues[Constants.STAT_MIDDLE_HIT]++;
increaseFirstBallStat(ballValue, statValues, 0);
if (ballValue != 0)
{
if (Arrays.equals(pinState[2], Constants.FRAME_PINS_DOWN))
{
statValues[Constants.STAT_SPARE_CONVERSIONS]++;
increaseFirstBallStat(ballValue, statValues, 1);
if (ballValue >= 5)
spareChances++;
}
else
{
statValues[Constants.STAT_PINS_LEFT_ON_DECK] += countPinsLeftStanding(pinState[2]);
}
}
else
{
totalShotsAtMiddle++;
ballValue = getFirstBallValue(pinState[2]);
if (ballValue != -1)
statValues[Constants.STAT_MIDDLE_HIT]++;
increaseFirstBallStat(ballValue, statValues, 0);
if (ballValue != 0)
{
statValues[Constants.STAT_PINS_LEFT_ON_DECK] += countPinsLeftStanding(pinState[2]);
}
}
}
}
else
{
totalShotsAtMiddle++;
int ballValue = getFirstBallValue(pinState[0]);
if (ballValue != -1)
statValues[Constants.STAT_MIDDLE_HIT]++;
increaseFirstBallStat(ballValue, statValues, 0);
if (ballValue < 5 && ballValue != Constants.BALL_VALUE_STRIKE)
spareChances++;
if (ballValue != 0)
{
if (Arrays.equals(pinState[1], Constants.FRAME_PINS_DOWN))
{
statValues[Constants.STAT_SPARE_CONVERSIONS]++;
increaseFirstBallStat(ballValue, statValues, 1);
if (ballValue >= 5)
spareChances++;
}
else
{
statValues[Constants.STAT_PINS_LEFT_ON_DECK] += countPinsLeftStanding(pinState[2]);
}
}
}
}
if (bowlerLeagueOrGame != LOADING_GAME_STATS && frameNumber == 1)
{
short gameScore = cursor.getShort(cursor.getColumnIndex(GameEntry.COLUMN_NAME_GAME_FINAL_SCORE));
byte gameNumber = (byte)cursor.getInt(cursor.getColumnIndex(GameEntry.COLUMN_NAME_GAME_NUMBER));
if (statValues[Constants.STAT_HIGH_SINGLE] < gameScore)
statValues[Constants.STAT_HIGH_SINGLE] = gameScore;
statValues[Constants.STAT_TOTAL_PINFALL] += gameScore;
statValues[Constants.STAT_NUMBER_OF_GAMES]++;
if (gameNumber == 1)
{
if (statValues[Constants.STAT_HIGH_SERIES] < seriesTotal)
statValues[Constants.STAT_HIGH_SERIES] = seriesTotal;
seriesTotal = gameScore;
}
else
{
seriesTotal += gameScore;
}
}
cursor.moveToNext();
}
}
if (bowlerLeagueOrGame != LOADING_GAME_STATS)
{
if (statValues[Constants.STAT_HIGH_SERIES] < seriesTotal)
{
statValues[Constants.STAT_HIGH_SERIES] = seriesTotal;
}
if (statValues[Constants.STAT_NUMBER_OF_GAMES] > 0)
{
statValues[Constants.STAT_AVERAGE] =
statValues[Constants.STAT_TOTAL_PINFALL] / statValues[Constants.STAT_NUMBER_OF_GAMES];
statValues[Constants.STAT_AVERAGE_PINS_LEFT_ON_DECK] =
statValues[Constants.STAT_PINS_LEFT_ON_DECK] / statValues[Constants.STAT_NUMBER_OF_GAMES];
}
}
setGeneralAndDetailedStatValues(statValues, totalShotsAtMiddle, spareChances, NUMBER_OF_GENERAL_DETAILS);
setStatHeaders(bowlerLeagueOrGame, NUMBER_OF_GENERAL_DETAILS);
return null;
}
@Override
protected void onPostExecute(Void param)
{
mStatsAdapter.notifyDataSetChanged();
}
}
@Override
public void updateTheme()
{
getSupportActionBar()
.setBackgroundDrawable(new ColorDrawable(Theme.getActionBarThemeColor()));
mStatsAdapter.updateTheme();
Theme.validateStatsActivityTheme();
}
}
|
package com.hubspot.blazar.github;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Optional;
import com.google.common.base.Throwables;
import com.hubspot.blazar.base.GitInfo;
import com.hubspot.blazar.config.BlazarConfiguration;
import com.hubspot.blazar.config.GitHubConfiguration;
import com.hubspot.blazar.guice.BlazarServiceModule;
import com.hubspot.horizon.HttpClient;
import com.hubspot.horizon.HttpConfig;
import com.hubspot.horizon.HttpRequest;
import com.hubspot.horizon.HttpRequest.Method;
import com.hubspot.horizon.ning.NingHttpClient;
import io.dropwizard.cli.ConfiguredCommand;
import io.dropwizard.jackson.Jackson;
import io.dropwizard.setup.Bootstrap;
import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser;
import org.kohsuke.github.GHOrganization;
import org.kohsuke.github.GHRepository;
import org.kohsuke.github.GitHub;
import java.io.IOException;
import java.util.Map.Entry;
public class BackfillGitHubDataCommand extends ConfiguredCommand<BlazarConfiguration> {
private final HttpClient httpClient;
public BackfillGitHubDataCommand() {
super("backfill", "Reprocess all repo and branch data");
ObjectMapper mapper = Jackson.newObjectMapper().setSerializationInclusion(Include.NON_NULL);
this.httpClient = new NingHttpClient(HttpConfig.newBuilder().setObjectMapper(mapper).build());
}
@Override
public void configure(Subparser subparser) {
super.configure(subparser);
subparser.addArgument("url").nargs("?").help("url to process each repo");
}
@Override
protected void run(Bootstrap<BlazarConfiguration> bootstrap,
Namespace namespace,
BlazarConfiguration configuration) throws Exception {
try {
for (Entry<String, GitHubConfiguration> entry : configuration.getGitHubConfiguration().entrySet()) {
String host = entry.getKey();
GitHubConfiguration gitHubConfig = entry.getValue();
GitHub gitHub = BlazarServiceModule.toGitHub(host, gitHubConfig);
for (String organization : gitHubConfig.getOrganizations()) {
System.out.println("Processing " + host + "/" + organization);
processOrganization(namespace.getString("url"), host, gitHub.getOrganization(organization));
System.out.println("Processed " + host + "/" + organization);
}
}
} finally {
httpClient.close();
}
}
private void processOrganization(String url, String host, GHOrganization organization) throws IOException {
for (GHRepository repository : organization.listRepositories()) {
GitInfo gitInfo = new GitInfo(Optional.<Long>absent(),
host,
repository.getOwnerName(),
repository.getName(),
repository.getId(),
"master",
true);
try {
System.out.println("Processing " + host + "/" + repository.getOwnerName() + "/" + repository.getName());
httpClient.execute(HttpRequest.newBuilder().setMethod(Method.PUT).setUrl(url).setBody(gitInfo).build());
System.out.println("Processed " + host + "/" + repository.getOwnerName() + "/" + repository.getName());
} catch (Throwable t) {
System.out.println(Throwables.getStackTraceAsString(t));
}
}
}
}
|
package com.braintreepayments.api.models;
import android.os.Parcel;
import android.os.Parcelable;
import com.google.android.gms.identity.intents.model.UserAddress;
import com.google.android.gms.wallet.PaymentData;
import org.json.JSONException;
import org.json.JSONObject;
import static com.braintreepayments.api.models.BinData.BIN_DATA_KEY;
/**
* {@link PaymentMethodNonce} representing a Google Payments card.
* @see PaymentMethodNonce
*/
public class GooglePaymentCardNonce extends PaymentMethodNonce implements Parcelable {
private static final String API_RESOURCE_KEY = "androidPayCards";
private static final String CARD_DETAILS_KEY = "details";
private static final String CARD_TYPE_KEY = "cardType";
private static final String LAST_TWO_KEY = "lastTwo";
private String mCardType;
private String mLastTwo;
private String mEmail;
private UserAddress mBillingAddress;
private UserAddress mShippingAddress;
private BinData mBinData;
/**
* Convert {@link PaymentData} to a {@link GooglePaymentCardNonce}.
*
* @param paymentData the {@link PaymentData} from a Google Payments response.
* @return {@link GooglePaymentCardNonce}.
* @throws JSONException when parsing the response fails.
*/
public static GooglePaymentCardNonce fromPaymentData(PaymentData paymentData) throws JSONException {
GooglePaymentCardNonce googlePaymentCardNonce = GooglePaymentCardNonce
.fromJson(paymentData.getPaymentMethodToken().getToken());
googlePaymentCardNonce.mDescription = paymentData.getCardInfo().getCardDescription();
googlePaymentCardNonce.mEmail = paymentData.getEmail();
googlePaymentCardNonce.mBillingAddress = paymentData.getCardInfo().getBillingAddress();
googlePaymentCardNonce.mShippingAddress = paymentData.getShippingAddress();
return googlePaymentCardNonce;
}
/**
* Convert an API response to a {@link GooglePaymentCardNonce}.
*
* @param json Raw JSON response from Braintree of a {@link GooglePaymentCardNonce}.
* @return {@link GooglePaymentCardNonce}.
* @throws JSONException when parsing the response fails.
*/
public static GooglePaymentCardNonce fromJson(String json) throws JSONException {
GooglePaymentCardNonce googlePaymentCardNonce = new GooglePaymentCardNonce();
googlePaymentCardNonce.fromJson(GooglePaymentCardNonce.getJsonObjectForType(API_RESOURCE_KEY, json));
return googlePaymentCardNonce;
}
protected void fromJson(JSONObject json) throws JSONException {
super.fromJson(json);
mDescription = getTypeLabel();
mBinData = BinData.fromJson(json.optJSONObject(BIN_DATA_KEY));
JSONObject details = json.getJSONObject(CARD_DETAILS_KEY);
mLastTwo = details.getString(LAST_TWO_KEY);
mCardType = details.getString(CARD_TYPE_KEY);
}
/**
* @return Type of this card (e.g. Visa, MasterCard, American Express)
*/
public String getCardType() {
return mCardType;
}
/**
* @return Last two digits of the user's underlying card, intended for display purposes.
*/
public String getLastTwo() {
return mLastTwo;
}
/**
* @return The user's email address associated the Google Payments account.
*/
public String getEmail() {
return mEmail;
}
/**
* @return The user's billing address.
*/
public UserAddress getBillingAddress() {
return mBillingAddress;
}
/**
* @return The user's shipping address.
*/
public UserAddress getShippingAddress() {
return mShippingAddress;
}
/**
* @return The BIN data for the card number associated with {@link GooglePaymentCardNonce}
*/
public BinData getBinData() {
return mBinData;
}
@Override
public String getTypeLabel() {
return "Google Payments";
}
public GooglePaymentCardNonce() {}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeString(mCardType);
dest.writeString(mLastTwo);
dest.writeString(mEmail);
dest.writeParcelable(mBillingAddress, flags);
dest.writeParcelable(mShippingAddress, flags);
dest.writeParcelable(mBinData, flags);
}
private GooglePaymentCardNonce(Parcel in) {
super(in);
mCardType = in.readString();
mLastTwo = in.readString();
mEmail = in.readString();
mBillingAddress = in.readParcelable(UserAddress.class.getClassLoader());
mShippingAddress = in.readParcelable(UserAddress.class.getClassLoader());
mBinData = in.readParcelable(BinData.class.getClassLoader());
}
public static final Creator<GooglePaymentCardNonce> CREATOR = new Creator<GooglePaymentCardNonce>() {
public GooglePaymentCardNonce createFromParcel(Parcel source) {
return new GooglePaymentCardNonce(source);
}
public GooglePaymentCardNonce[] newArray(int size) {
return new GooglePaymentCardNonce[size];
}
};
}
|
package ca.ualberta.cs.cmput301t02project.activity;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import ca.ualberta.cs.cmput301t02project.R;
import ca.ualberta.cs.cmput301t02project.model.User;
/**
* Allows a user to log in to the app with a selected username.
* If their username already exists, the previous data associated with that user is restored.
* If their username does not already exist, it is created.
*/
public class LoginActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
}
/**
* Reads and relays user's username input.
* <p>
* Called when login_button on the screen is pressed.
* Takes a view as a parameter because of conventions for onClick in the the layout.
* <p>
* @param v The current view. Variable is not used anywhere
*/
public void submitName(View v) {
// Read user input -SB
EditText enteredName = (EditText) findViewById(R.id.login_username);
// Test if the input is allowed -SB
login(enteredName.getText().toString());
}
/**
* Sets the current user's username.
* <p>
* Sets the current username in User.
* The current username is posted along with any comments the user makes.
* The user's information including old posted comments and favorite comments can be restored after the user is set.
* If an invalid username was entered, a message is printed to the screen.
* <p>
* @param username The user's username input
*/
private void login(String username) {
// Message on screen -SB
TextView message = (TextView) findViewById(R.id.login_message);
// If valid username set it -SB
if (checkIfValid(username)) {
// Reset message -SB
message.setText("Login Page");
// If user doesn't exist, create a user with that name -SB
User.login(username, getApplicationContext());
// Go to the main menu once user is set -SB
startActivity(new Intent(LoginActivity.this, MainMenuActivity.class));
}
// If invalid username is provided ask user to try again -SB
else {
message.setText("Please enter a valid username");
}
}
/**
* Checks if the username is valid.
* <p>
* If a invalid username is entered, false is returned.
* Otherwise true is returned.
* Example of an invalid username submission: "".
* Example of a valid username submission: "Bob".
* @param username The username entered by the user
* @return Returns false for invalid username, else true
*/
private boolean checkIfValid(String username) {
return !username.equals("");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.help_page:
goToHelpPage();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Redirects to the default help page
*/
public void goToHelpPage(){
// redirect to help page for logging in -SB
Intent viewIntent = new Intent("android.intent.action.VIEW",Uri.parse(
"https://rawgithub.com/CMPUT301W14T02/Comput301Project/master/Help%20Pages/login.html"));
startActivity(viewIntent);
}
}
|
package arekkuusu.solar.common;
import arekkuusu.solar.common.entity.ModEntities;
import arekkuusu.solar.common.handler.gen.ModGen;
import arekkuusu.solar.common.lib.LibMod;
import arekkuusu.solar.common.network.PacketHandler;
import arekkuusu.solar.common.proxy.IProxy;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.SidedProxy;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import static net.minecraftforge.fml.common.Mod.EventHandler;
import static net.minecraftforge.fml.common.Mod.Instance;
@Mod(modid = LibMod.MOD_ID, name = LibMod.MOD_NAME, version = LibMod.MOD_VERSION, acceptedMinecraftVersions = "[1.12.2]")
public class Solar {
@SidedProxy(clientSide = LibMod.CLIENT_PROXY, serverSide = LibMod.SERVER_PROXY)
public static IProxy PROXY;
@Instance
public static Solar INSTANCE;
//Logger used to log stuff in the loggerino
public static Logger LOG = LogManager.getLogger(LibMod.MOD_NAME);
@EventHandler
public void preInit(FMLPreInitializationEvent event) {
PROXY.preInit(event);
PacketHandler.init();
ModEntities.init();
ModGen.init();
}
@EventHandler
public void init(FMLInitializationEvent event) {
PROXY.init(event);
}
}
|
package beaform.gui.search;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import java.util.concurrent.Future;
import javax.swing.BoxLayout;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import beaform.DbTaskHandler;
import beaform.SearchFormulaTask;
import beaform.SearchFormulasByTagTask;
import beaform.VariousTaskHandler;
import beaform.entities.Formula;
import beaform.gui.FormulaTree;
/**
* A search GUI.
*
* @author Steven Post
*
*/
public class SearchGui extends JPanel {
/** A serial. */
private static final long serialVersionUID = 2557014310487638917L;
/** A logger */
private static final Logger LOG = LoggerFactory.getLogger(SearchGui.class);
/** The field to type in the search */
private final JTextField txtSearch = new JTextField();
/** The model for the combo box. */
private final DefaultComboBoxModel<SearchType> comboBoxModel = new DefaultComboBoxModel<SearchType>(SearchType.values());
/** The index of the formula tree on the target panel */
private static final int FORMULA_TREE_LOC = 3;
/**
* Constructor.
*/
public SearchGui() {
super(new BorderLayout());
final JPanel searchPanel = createSearchPanel();
this.add(searchPanel, BorderLayout.PAGE_START);
}
private JPanel createSearchPanel() {
final Dimension textFieldSize = new Dimension(100, 30);
final Dimension textFieldMaxSize = new Dimension(300, 30);
final JPanel searchPanel = new JPanel();
searchPanel.setLayout(new BoxLayout(searchPanel, BoxLayout.LINE_AXIS));
final JTextField search = this.txtSearch;
search.setMinimumSize(textFieldSize);
search.setPreferredSize(textFieldSize);
search.setMaximumSize(textFieldMaxSize);
searchPanel.add(search);
final JComboBox<SearchType> cmbType = new JComboBox<SearchType>(this.comboBoxModel);
cmbType.setMinimumSize(textFieldSize);
cmbType.setMaximumSize(textFieldMaxSize);
cmbType.setPreferredSize(textFieldSize);
cmbType.setEditable(false);
cmbType.setSelectedIndex(0);
searchPanel.add(cmbType);
final JButton btnSearch = new JButton("Search");
searchPanel.add(btnSearch);
btnSearch.addActionListener(new ActionListener() {
/**
* Invoked when the action occurs.
*/
@Override
public void actionPerformed(final ActionEvent event) {
search();
}
});
return searchPanel;
}
/**
* Kickoff the search.
*/
public void search() {
final SearchType searchType = (SearchType) this.comboBoxModel.getSelectedItem();
switch (searchType) {
case FORMULA:
{
final String searchText = this.txtSearch.getText();
final SearchFormulaTask task = new SearchFormulaTask(searchText);
final Future<Formula> searchresult = DbTaskHandler.addTask(task);
VariousTaskHandler.addTask(new RenderFormulaSearchResult(searchresult, this));
break;
}
case TAG:
{
final String searchText = this.txtSearch.getText();
final SearchFormulasByTagTask task = new SearchFormulasByTagTask(searchText);
final Future<List<Formula>> searchresult = DbTaskHandler.addTask(task);
VariousTaskHandler.addTask(new RenderFormulaSearchByTagResult(searchresult, this));
break;
}
default:
if (LOG.isErrorEnabled()) {
LOG.error(searchType + " is an unknown search");
}
break;
}
}
/**
* Set the search results in a view.
*
* @param formulaTree the search results
*/
public void setSearchResults(final FormulaTree formulaTree) {
if (this.getComponentCount() > FORMULA_TREE_LOC) {
this.remove(FORMULA_TREE_LOC);
}
this.add(formulaTree, BorderLayout.CENTER);
this.revalidate();
}
}
|
package com.elmakers.mine.bukkit.utility;
import java.util.UUID;
import org.apache.commons.lang.WordUtils;
import org.bukkit.Bukkit;
import org.bukkit.DyeColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.block.Skull;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.FallingBlock;
import org.bukkit.entity.Player;
import org.bukkit.event.enchantment.PrepareItemEnchantEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.BannerMeta;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.SkullMeta;
import org.bukkit.map.MapView;
import org.bukkit.plugin.Plugin;
/**
* Makes deprecation warnings useful again by suppressing all bukkit 'magic
* number' deprecations.
*
*/
@SuppressWarnings("deprecation")
public class DeprecatedUtils {
public static void updateInventory(Player player) {
// @deprecated This method should not be relied upon as it is a
// temporary work-around for a larger, more complicated issue.
player.updateInventory();
}
public static void setTypeAndData(Block block, Material material, byte data, boolean applyPhysics) {
// @deprecated Magic value
if (NMSUtils.class_Block_setTypeIdAndDataMethod != null) {
try {
NMSUtils.class_Block_setTypeIdAndDataMethod.invoke(block, material.getId(), data, applyPhysics);
} catch (Exception ex) {
block.setType(material, applyPhysics);
ex.printStackTrace();
}
} else {
block.setType(material, applyPhysics);
}
}
public static byte getData(Block block) {
// @deprecated Magic value
return block.getData();
}
public static byte getWoolData(DyeColor color) {
// @deprecated Magic value
return color.getWoolData();
}
public static int getId(Material material) {
// @deprecated Magic value
return material.getId();
}
public static byte getBlockData(FallingBlock falling) {
// @deprecated Magic value
return falling.getBlockData();
}
public static int getTypeId(Block block) {
// @deprecated Magic value
return block.getType().getId();
}
public static MapView getMap(short id) {
// @deprecated Magic value
return Bukkit.getMap(id);
}
public static String getName(EntityType entityType) {
// @deprecated Magic value
String name = entityType.getName();
return WordUtils.capitalize(name);
}
public static String getDisplayName(Entity entity) {
if (entity instanceof Player) {
return ((Player)entity).getDisplayName();
}
String customName = entity.getCustomName();
if (customName != null && !customName.isEmpty()) {
return customName;
}
return getName(entity.getType());
}
public static Player getPlayer(String name) {
// @deprecated Use {@link #getPlayer(UUID)} as player names are no
// longer guaranteed to be unique
return Bukkit.getPlayer(name);
}
public static Player getPlayerExact(String name) {
return Bukkit.getPlayerExact(name);
}
public static void setData(Block block, byte data) {
// @deprecated Magic value
block.setData(data);
}
public static FallingBlock spawnFallingBlock(Location location,
Material material, byte data) {
// @deprecated Magic value
return location.getWorld().spawnFallingBlock(location, material, data);
}
public static byte getRawData(BlockState state) {
// @deprecated Magic value
return state.getRawData();
}
public static DyeColor getBaseColor(BannerMeta banner) {
return banner.getBaseColor();
}
public static void setBaseColor(BannerMeta banner, DyeColor color) {
banner.setBaseColor(color);
}
public static void setSkullOwner(final ItemStack itemStack, String ownerName) {
SkinUtils.fetchProfile(ownerName, new SkinUtils.ProfileCallback() {
@Override
public void result(SkinUtils.ProfileResponse response) {
if (response != null) {
Object gameProfile = response.getGameProfile();
ItemMeta meta = itemStack.getItemMeta();
if (meta instanceof SkullMeta) {
InventoryUtils.setSkullProfile(meta, gameProfile);
itemStack.setItemMeta(meta);
}
}
}
});
}
public static void setSkullOwner(final ItemStack itemStack, UUID ownerUUID) {
SkinUtils.fetchProfile(ownerUUID, new SkinUtils.ProfileCallback() {
@Override
public void result(SkinUtils.ProfileResponse response) {
if (response != null) {
Object gameProfile = response.getGameProfile();
ItemMeta meta = itemStack.getItemMeta();
if (meta instanceof SkullMeta) {
InventoryUtils.setSkullProfile(meta, gameProfile);
itemStack.setItemMeta(meta);
}
}
}
});
}
public static void setOwner(final Skull skull, UUID uuid) {
SkinUtils.fetchProfile(uuid, new SkinUtils.ProfileCallback() {
@Override
public void result(SkinUtils.ProfileResponse response) {
if (response != null) {
Object gameProfile = response.getGameProfile();
InventoryUtils.setSkullProfile(skull, gameProfile);
}
skull.update(true, false);
}
});
}
public static void setOwner(final Skull skull, String ownerName) {
SkinUtils.fetchProfile(ownerName, new SkinUtils.ProfileCallback() {
@Override
public void result(SkinUtils.ProfileResponse response) {
if (response != null) {
Object gameProfile = response.getGameProfile();
InventoryUtils.setSkullProfile(skull, gameProfile);
}
skull.update(true, false);
}
});
}
public static void showPlayer(Plugin plugin, Player toPlayer, Player showPlayer) {
// TODO: Use Plugin
toPlayer.showPlayer(showPlayer);
}
public static void hidePlayer(Plugin plugin, Player fromPlayer, Player hidePlayer) {
// TODO: Use Plugin
fromPlayer.hidePlayer(hidePlayer);
}
public static int[] getExpLevelCostsOffered(PrepareItemEnchantEvent event) {
// TODO: Use getOffers
return event.getExpLevelCostsOffered();
}
public static Entity getPassenger(Entity mount) {
// TODO: Use getPassengers, refactor to search through list
return mount.getPassenger();
}
public static void setPassenger(Entity mount, Entity passenger) {
// TODO: Use addPassenger
mount.setPassenger(passenger);
}
public static org.bukkit.UnsafeValues getUnsafe() {
return Bukkit.getUnsafe();
}
}
|
package browserview;
import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef.HWND;
import com.sun.jna.platform.win32.WinUser;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeOptions;
import ui.UI;
import util.GitHubURL;
import util.PlatformSpecific;
import util.events.testevents.JumpToCommentEvent;
import util.events.testevents.SendKeysToBrowserEvent;
import java.io.*;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
/**
* An abstraction for the functions of the Selenium web driver.
* It depends minimally on UI for width adjustments.
*/
public class BrowserComponent {
private static final Logger logger = LogManager.getLogger(BrowserComponent.class.getName());
private static final boolean USE_MOBILE_USER_AGENT = false;
private static boolean isTestChromeDriver;
// Chrome, Android 4.2.2, Samsung Galaxy S4
private static final String MOBILE_USER_AGENT = "Mozilla/5.0 (Linux; Android 4.2.2; GT-I9505 Build/JDQ39)" +
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.59 Mobile Safari/537.36";
private static final String CHROME_DRIVER_LOCATION = "browserview/";
private static final String CHROME_DRIVER_BINARY_NAME = determineChromeDriverBinaryName();
private String pageContentOnLoad = "";
private static final int SWP_NOSIZE = 0x0001;
private static final int SWP_NOMOVE = 0x0002;
private static final int SWP_NOACTIVATE = 0x0010;
private static HWND browserWindowHandle;
private static User32 user32;
private final UI ui;
private ChromeDriverEx driver = null;
// We want browser commands to be run on a separate thread, but not to
// interfere with each other. This executor is limited to a single instance,
// so it ensures that browser commands are queued and executed in sequence.
// The alternatives would be to:
// - allow race conditions
// - interrupt the blocking WebDriver::get method
// The first is not desirable and the second does not seem to be possible
// at the moment.
private Executor executor;
public BrowserComponent(UI ui, boolean isTestChromeDriver) {
this.ui = ui;
executor = Executors.newSingleThreadExecutor();
BrowserComponent.isTestChromeDriver = isTestChromeDriver;
setupJNA();
setupChromeDriverExecutable();
}
/**
* Called on application startup. Blocks until the driver is created.
* Guaranteed to only happen once.
*/
public void initialise() {
assert driver == null;
executor.execute(() -> {
driver = createChromeDriver();
logger.info("Successfully initialised browser component and ChromeDriver");
});
login();
}
/**
* Called when application quits. Guaranteed to only happen once.
*/
public void onAppQuit() {
quit();
removeChromeDriverIfNecessary();
}
/**
* Quits the browser component.
*/
private void quit() {
logger.info("Quitting browser component");
// The application may quit before the browser is initialised.
// In that case, do nothing.
if (driver != null) {
try {
driver.quit();
} catch (WebDriverException e) {
// Chrome was closed; do nothing
}
}
}
/**
* Creates, initialises, and returns a ChromeDriver.
* @return
*/
private ChromeDriverEx createChromeDriver() {
ChromeOptions options = new ChromeOptions();
if (USE_MOBILE_USER_AGENT) {
options.addArguments(String.format("user-agent=\"%s\"", MOBILE_USER_AGENT));
}
ChromeDriverEx driver = new ChromeDriverEx(options, isTestChromeDriver);
WebDriver.Options manage = driver.manage();
if (!isTestChromeDriver) {
manage.window().setPosition(new Point((int) ui.getCollapsedX(), 0));
manage.window().setSize(new Dimension((int) ui.getAvailableDimensions().getWidth(),
(int) ui.getAvailableDimensions().getHeight()));
initialiseJNA();
}
return driver;
}
private void removeChromeDriverIfNecessary() {
if (ui.getCommandLineArgs().containsKey(UI.ARG_UPDATED_TO)) {
new File(CHROME_DRIVER_BINARY_NAME).delete();
}
}
/**
* Executes Javascript in the currently-active driver window.
* Run on the UI thread (will block until execution is complete,
* i.e. change implementation if long-running scripts must be run).
* @param script
*/
private void executeJavaScript(String script) {
driver.executeScript(script);
logger.info("Executed JavaScript " + script.substring(0, Math.min(script.length(), 10)));
}
/**
* Navigates to the New Label page on GitHub.
* Run on a separate thread.
*/
public void newLabel() {
logger.info("Navigating to New Label page");
runBrowserOperation(() -> driver.get(GitHubURL.getPathForNewLabel(ui.logic.getDefaultRepo()), false));
bringToTop();
}
/**
* Navigates to the New Milestone page on GitHub.
* Run on a separate thread.
*/
public void newMilestone() {
logger.info("Navigating to New Milestone page");
runBrowserOperation(() -> driver.get(GitHubURL.getPathForNewMilestone(ui.logic.getDefaultRepo()), false));
bringToTop();
}
/**
* Navigates to the New Issue page on GitHub.
* Run on a separate thread.
*/
public void newIssue() {
logger.info("Navigating to New Issue page");
runBrowserOperation(() -> driver.get(GitHubURL.getPathForNewIssue(ui.logic.getDefaultRepo()), false));
bringToTop();
}
/**
* Navigates to the HubTurbo documentation page.
* Run on a separate thread.
*/
public void showDocs() {
logger.info("Showing documentation page");
runBrowserOperation(() -> driver.get(GitHubURL.DOCS_PAGE, false));
}
/**
* Navigates to the GitHub changelog page.
* Run on a separate thread.
*/
// public void showChangelog(String version) {
// logger.info("Showing changelog for version " + version);
// runBrowserOperation(() -> driver.get(GitHubURL.getChangelogForVersion(version)));
/**
* Navigates to the GitHub page for the given issue in the currently-active
* driver window.
* Run on a separate thread.
*/
public void showIssue(String repoId, int id, boolean isPullRequest, boolean isForceRefresh) {
if (isPullRequest) {
logger.info("Showing pull request
runBrowserOperation(() -> driver.get(GitHubURL.getPathForPullRequest(repoId, id), isForceRefresh));
} else {
logger.info("Showing issue
runBrowserOperation(() -> driver.get(GitHubURL.getPathForIssue(repoId, id), isForceRefresh));
}
}
public void jumpToComment(){
if (isTestChromeDriver) {
UI.events.triggerEvent(new JumpToCommentEvent());
}
try {
WebElement comment = driver.findElementById("new_comment_field");
comment.click();
bringToTop();
} catch (Exception e) {
logger.warn("Unable to reach jump to comments. ");
}
}
private boolean isBrowserActive(){
if (driver == null) return false;
try {
// Throws an exception if unable to switch to original HT tab
// which then triggers a browser reset when called from runBrowserOperation
WebDriver.TargetLocator switchTo = driver.switchTo();
String windowHandle = driver.getWindowHandle();
if (!isTestChromeDriver) switchTo.window(windowHandle);
// When the HT tab is closed (but the window is still alive),
// a lot of the operations on the driver (such as getCurrentURL)
// will hang (without throwing an exception, the thread will just freeze the UI forever),
// so we cannot use getCurrentURL/getTitle to check if the original HT tab
// is still open. The above line does not hang the driver but still throws
// an exception, thus letting us detect that the HT tab is not active any more.
return true;
} catch (WebDriverException e) {
logger.warn("Unable to reach bview. ");
return false;
}
}
// A helper function for reseting browser.
private void resetBrowser(){
logger.info("Relaunching chrome.");
quit(); // if the driver hangs
driver = createChromeDriver();
login();
}
/**
* A helper function for running browser operations.
* Takes care of running it on a separate thread, and normalises error-handling across
* all types of code.
*/
private void runBrowserOperation (Runnable operation) {
executor.execute(() -> {
if (isBrowserActive()) {
try {
operation.run();
pageContentOnLoad = getCurrentPageSource();
} catch (WebDriverException e) {
switch (BrowserComponentError.fromErrorMessage(e.getMessage())) {
case NoSuchWindow:
resetBrowser();
runBrowserOperation(operation); // Recurse and repeat
break;
case NoSuchElement:
logger.info("Warning: no such element! " + e.getMessage());
break;
default:
break;
}
}
} else {
logger.info("Chrome window not responding.");
resetBrowser();
runBrowserOperation(operation);
}
});
}
/**
* Logs in the currently-active driver window using the credentials
* supplied by the user on login to the app.
* Run on a separate thread.
*/
public void login() {
logger.info("Logging in on GitHub...");
focus(ui.getMainWindowHandle());
runBrowserOperation(() -> {
driver.get(GitHubURL.LOGIN_PAGE, false);
try {
WebElement searchBox = driver.findElement(By.name("login"));
searchBox.sendKeys(ui.logic.loginController.credentials.username);
searchBox = driver.findElement(By.name("password"));
searchBox.sendKeys(ui.logic.loginController.credentials.password);
searchBox.submit();
} catch (Exception e) {
// Already logged in; do nothing
logger.info("Unable to login, may already be logged in. ");
}
});
}
/**
* One-time JNA setup.
*/
private static void setupJNA() {
if (PlatformSpecific.isOnWindows()) user32 = User32.INSTANCE;
}
/**
* JNA initialisation. Should happen whenever the Chrome window is recreated.
*/
private void initialiseJNA() {
if (PlatformSpecific.isOnWindows()) {
browserWindowHandle = user32.FindWindow(null, "data:, - Google Chrome");
}
}
private static String determineChromeDriverBinaryName() {
return PlatformSpecific.isOnMac() ? "chromedriver"
: PlatformSpecific.isOnWindows() ? "chromedriver.exe"
: "chromedriver_linux";
}
/**
* Ensures that the chromedriver executable is in the project root before
* initialisation. Since executables are packaged for all platforms, this also
* picks the right version to use.
*/
private static void setupChromeDriverExecutable() {
File f = new File(CHROME_DRIVER_BINARY_NAME);
if (!f.exists()) {
InputStream in = BrowserComponent.class.getClassLoader()
.getResourceAsStream(CHROME_DRIVER_LOCATION + CHROME_DRIVER_BINARY_NAME);
assert in != null : "Could not find " + CHROME_DRIVER_BINARY_NAME + " at "
+ CHROME_DRIVER_LOCATION + "; this path must be updated if the executables are moved";
OutputStream out;
try {
out = new FileOutputStream(CHROME_DRIVER_BINARY_NAME);
IOUtils.copy(in, out);
out.close();
f.setExecutable(true);
} catch (IOException e) {
logger.error("Could not load Chrome driver binary! " + e.getLocalizedMessage(), e);
}
logger.info("Could not find " + CHROME_DRIVER_BINARY_NAME + "; extracted it from jar");
} else {
logger.info("Located " + CHROME_DRIVER_BINARY_NAME);
}
System.setProperty("webdriver.chrome.driver", CHROME_DRIVER_BINARY_NAME);
}
private void bringToTop(){
if (PlatformSpecific.isOnWindows()) {
user32.ShowWindow(browserWindowHandle, WinUser.SW_RESTORE);
user32.SetForegroundWindow(browserWindowHandle);
}
}
public void focus(HWND mainWindowHandle){
if (PlatformSpecific.isOnWindows()) {
// SWP_NOMOVE and SWP_NOSIZE prevents the 0,0,0,0 parameters from taking effect.
user32.SetWindowPos(browserWindowHandle, mainWindowHandle, 0, 0, 0, 0,
SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
}
}
private String getCurrentPageSource() {
return StringEscapeUtils.escapeHtml4(
(String) driver.executeScript("return document.documentElement.outerHTML"));
}
public boolean hasBviewChanged() {
if (isTestChromeDriver) return true;
if (isBrowserActive()) {
if (getCurrentPageSource().equals(pageContentOnLoad)) return false;
pageContentOnLoad = getCurrentPageSource();
return true;
}
return false;
}
public void scrollToTop() {
String script = "window.scrollTo(0, 0)";
executeJavaScript(script);
}
public void scrollToBottom() {
String script = "window.scrollTo(0, document.body.scrollHeight)";
executeJavaScript(script);
}
public void scrollPage(boolean isDownScroll) {
String script;
if (isDownScroll)
script = "window.scrollBy(0,100)";
else
script = "window.scrollBy(0, -100)";
executeJavaScript(script);
}
private void sendKeysToBrowser(String keyCode) {
if (isTestChromeDriver) {
UI.events.triggerEvent(new SendKeysToBrowserEvent(keyCode));
}
WebElement body;
try {
body = driver.findElementByTagName("body");
body.sendKeys(keyCode);
} catch (Exception e) {
logger.error("No such element");
}
}
public void manageAssignees(String keyCode) {
sendKeysToBrowser(keyCode.toLowerCase());
bringToTop();
}
public void manageMilestones(String keyCode) {
sendKeysToBrowser(keyCode.toLowerCase());
bringToTop();
}
public void showIssues() {
logger.info("Navigating to Issues page");
runBrowserOperation(() -> driver.get(GitHubURL.getPathForAllIssues(ui.logic.getDefaultRepo()), false));
}
public void showPullRequests() {
logger.info("Navigating to Pull requests page");
runBrowserOperation(() -> driver.get(GitHubURL.getPathForPullRequests(ui.logic.getDefaultRepo()), false));
}
public void showKeyboardShortcuts() {
logger.info("Navigating to Keyboard Shortcuts");
runBrowserOperation(() -> driver.get(GitHubURL.KEYBOARD_SHORTCUTS_PAGE, false));
}
public void showMilestones() {
logger.info("Navigating to Milestones page");
runBrowserOperation(() -> driver.get(GitHubURL.getPathForMilestones(ui.logic.getDefaultRepo()), false));
}
public void showContributors() {
logger.info("Navigating to Contributors page");
runBrowserOperation(() -> driver.get(GitHubURL.getPathForContributors(ui.logic.getDefaultRepo()), false));
}
public boolean isCurrentUrlIssue() {
return driver != null && GitHubURL.isUrlIssue(driver.getCurrentUrl());
}
public String getCurrentUrl() {
return driver.getCurrentUrl();
}
}
|
package de.uka.ipd.sdq.beagle.core.measurement;
/**
* ATTENTION: Test coverage check turned off. Remove this comments block when implementing
* this class!
*
* <p>COVERAGE:OFF
*/
import de.uka.ipd.sdq.beagle.core.AnalysisController;
import de.uka.ipd.sdq.beagle.core.Blackboard;
import de.uka.ipd.sdq.beagle.core.measurement.order.MeasurementOrder;
import java.util.Set;
/**
* Controls which measurement tool is working.
*
* <p>There is always at most one measurement tool working.
*
* @author Roman Langrehr
* @see AnalysisController
*/
public class MeasurementController {
/**
* All {@link MeasurementTool}s this {@link MeasurementController} knows.
*/
private Set<MeasurementTool> measurementTools;
/**
* Constructs a new {@link MeasurementController}.
*
* @param measurementTools The {@link MeasurementTool}s to use.
*/
public MeasurementController(final Set<MeasurementTool> measurementTools) {
this.measurementTools = measurementTools;
}
/**
* Determines whether a {@link MeasurementTool} can contribute to the
* {@link Blackboard}.
*
* @param blackboard The blackboard.
* @return Whether a {@link MeasurementTool} can measure something which is marked as
* 'to be measured'. When {@code true} is returned, this is no guarantee that
* at least one new measurement result will be added.
*/
public boolean canMeasure(final ReadOnlyMeasurementControllerBlackboardView blackboard) {
for (MeasurementTool measurementTool : this.measurementTools) {
if (measurementTool.canMeasure(blackboard)) {
return true;
}
}
return false;
}
public void measure(final MeasurementControllerBlackboardView blackboard) {
for (MeasurementTool measurementTool : this.measurementTools) {
final MeasurementOrder measurementOrder = new MeasurementOrder();
measurementTool.measure(measurementOrder);
}
}
}
|
package ch.tkuhn.memetools;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.apache.commons.lang3.tuple.Pair;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParameterException;
public class SortTable {
@Parameter(description = "input-file", required = true)
private List<String> parameters = new ArrayList<String>();
private File inputFile;
@Parameter(names = "-o", description = "Output file")
private File outputFile;
@Parameter(names = "-r", description = "Sort in reversed order")
private boolean reversed = false;
@Parameter(names = "-c", description = "Index or name of column to sort")
private String colIndexOrName = "0";
@Parameter(names = "-u", description = "Upper threshold value")
private Double uThreshold;
@Parameter(names = "-l", description = "Lower threshold value")
private Double lThreshold;
public static final void main(String[] args) {
SortTable obj = new SortTable();
JCommander jc = new JCommander(obj);
try {
jc.parse(args);
} catch (ParameterException ex) {
jc.usage();
System.exit(1);
}
if (obj.parameters.size() != 1) {
System.err.println("ERROR: Exactly one main argument is needed");
jc.usage();
System.exit(1);
}
obj.inputFile = new File(obj.parameters.get(0));
try {
obj.run();
} catch (IOException ex) {
ex.printStackTrace();
}
}
private List<String> content;
private List<Pair<Integer,Double>> sortList;
public SortTable() {
}
public void run() throws IOException {
init();
BufferedReader reader = new BufferedReader(new FileReader(inputFile), 64*1024);
String headerLine = reader.readLine();
List<String> header = MemeUtils.readCsvLine(headerLine);
int col;
if (colIndexOrName.matches("[0-9]+")) {
col = Integer.parseInt(colIndexOrName);
} else {
col = header.indexOf(colIndexOrName);
}
content.add(headerLine);
String line;
while ((line = reader.readLine()) != null) {
List<String> entries = MemeUtils.readCsvLine(line);
double value = Double.parseDouble(entries.get(col));
if (uThreshold != null && value > uThreshold) continue;
if (lThreshold != null && value < lThreshold) continue;
sortList.add(Pair.of(content.size(), value));
content.add(line);
}
reader.close();
Collections.sort(sortList, new Comparator<Pair<Integer,Double>>() {
@Override
public int compare(Pair<Integer,Double> o1, Pair<Integer,Double> o2) {
if (reversed) {
return (int) (o2.getRight() - o1.getRight());
} else {
return (int) (o1.getRight() - o2.getRight());
}
}
});
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile), 64*1024);
writer.write(content.get(0) + "\n");
for (Pair<Integer,Double> p : sortList) {
writer.write(content.get(p.getLeft()) + "\n");
}
writer.close();
}
private void init() {
if (outputFile == null) {
outputFile = new File(inputFile.getPath().replaceAll("\\..*$", "") + "-sorted.csv");
}
content = new ArrayList<String>();
sortList = new ArrayList<Pair<Integer,Double>>();
}
}
|
package com.abnormalentropy;
import com.abnormalentropy.exceptions.EmptyListException;
import com.abnormalentropy.exceptions.NoSingleElementException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.function.*;
public class LinqList<T> extends ArrayList<T>
{
private static final Logger LOGGER = LoggerFactory.getLogger(LinqList.class);
LinqList()
{
super();
}
LinqList(Collection<T> collection)
{
super(collection);
}
LinqList(int capacity)
{
super(capacity);
}
LinqList<T> where(Function<T, Boolean> function)
{
LinqList<T> linqList = new LinqList<T>();
this.forEach(x -> {
if (function.apply(x))
linqList.add(x);
});
return linqList;
}
Boolean any(Function<T, Boolean> function)
{
for (T x : this)
if (function.apply(x))
return true;
return false;
}
Boolean all(Function<T, Boolean> function)
{
for (T x : this)
if (!function.apply(x))
return false;
return true;
}
Boolean contains(T elem, Comparator<T> comparator)
{
for (T x : this)
if (comparator.compare(x, elem) == 0)
return true;
return false;
}
LinqList<T> intersect(LinqList<T> list)
{
LinqList<T> intersection = new LinqList<T>();
LinqList<T> shortList = (list.size() < this.size()) ? list : this;
LinqList<T> longList = (shortList == list) ? this : list;
shortList.forEach(x -> {
if (longList.contains(x))
intersection.add(x);
});
return intersection;
}
LinqList<T> intersect(LinqList<T> list, Comparator<T> comparator)
{
LinqList<T> intersection = new LinqList<T>();
LinqList<T> shortList = (list.size() < this.size()) ? list : this;
LinqList<T> longList = (shortList == list) ? this : list;
shortList.forEach(x -> {
if (longList.contains(x, comparator))
intersection.add(x);
});
return intersection;
}
T first() throws EmptyListException
{
if (this.isEmpty())
throw new EmptyListException();
return this.get(0);
}
T first(Function<T, Boolean> function) throws EmptyListException
{
return this.where(function).first();
}
T firstOrDefault()
{
return this.isEmpty() ? null : this.get(0);
}
T firstOrDefault(Function<T, Boolean> function)
{
return this.where(function).firstOrDefault();
}
T last() throws EmptyListException
{
if (this.isEmpty())
throw new EmptyListException();
return this.get(this.size()-1);
}
T last(Function<T, Boolean> function) throws EmptyListException
{
return this.where(function).last();
}
T lastOrDefault()
{
return this.isEmpty() ? null : this.get(this.size()-1);
}
T lastOrDefault(Function<T, Boolean> function)
{
return this.where(function).lastOrDefault();
}
List<T> toList()
{
return new ArrayList<T>(this);
}
<K> HashMap<K, T> toHashMap(Function<T, K> function)
{
HashMap<K, T> hashMap = new HashMap<K, T>();
this.forEach(x -> hashMap.put(function.apply(x), x));
return hashMap;
}
LinqList<T> union(List<T> list)
{
LinqList<T> union = new LinqList<T>(this);
for (T x : list)
if (!union.contains(x))
union.add(x);
return union;
}
LinqList<T> union(List<T> list, Comparator<T> comparator)
{
LinqList<T> union = new LinqList<T>(this);
for (T x : list)
if (!union.contains(x, comparator))
union.add(x);
return union;
}
<U, R> LinqList<R> zip(List<U> list, BiFunction<T, U, R> function)
{
LinqList<R> linqList = new LinqList<R>();
int end = Math.min(this.size(), list.size());
for (int k = 0; k < end; k++)
linqList.add(function.apply(this.get(k), list.get(k)));
return linqList;
}
LinqList<T> take(int size)
{
return new LinqList<T>(this.subList(0, size));
}
LinqList<T> skip(int from)
{
return new LinqList<T>(this.subList(from, this.size()));
}
T single() throws NoSingleElementException
{
if (this.size() > 1)
throw new NoSingleElementException();
return this.get(0);
}
T single(Function<T, Boolean> function) throws NoSingleElementException
{
return this.where(function).single();
}
T singleOrDefault()
{
return (this.size() > 1) ? null : this.get(0);
}
T singleOrDefault(Function<T, Boolean> function)
{
return this.where(function).singleOrDefault();
}
}
|
package de.comeight.crystallogy.entity.ai;
import java.util.List;
import de.comeight.crystallogy.util.EnumCustomAis;
import de.comeight.crystallogy.util.Utilities;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
public class EntityAiPickupItems extends EntityAiMoveToPos{
private BlockPos itemsTargetPos;
private BlockPos areaRefPos;
private BlockPos area;
private EntityItem currentTarget;
private boolean deliveringItems;
private int waitCounter;
private final int MAX_ITEM_STACK_SIZE = 64;
private boolean maxStackSizeReached;
public EntityAiPickupItems(EntityLiving aiOwner, BlockPos itemsTargetPos, BlockPos areaStartPos, BlockPos area) {
super(aiOwner, new Vec3d(itemsTargetPos.add(0.5, 0.5, 0.5)), 1.0);
this.itemsTargetPos = itemsTargetPos;
this.areaRefPos = areaStartPos;
this.area = area;
this.currentTarget = null;
this.deliveringItems = false;
this.waitCounter = 0;
this.forceMoveTo = true;
this.maxStackSizeReached = false;
}
public EntityAiPickupItems(EntityLiving aiOwner) {
super(aiOwner);
this.currentTarget = null;
this.waitCounter = 0;
}
public EntityAiPickupItems() {
}
@Override
public int getAiID() {
return EnumCustomAis.PICKUP_ITEMS.ID;
}
private EntityItem getNextTarget(){
return (EntityItem) world.findNearestEntityWithinAABB(EntityItem.class, getAreaBoundingBox(), aiOwner);
}
private EntityItem getNearestEqualStack(ItemStack stack){
for (EntityItem entityitem : world.getEntitiesWithinAABB(EntityItem.class, getAreaBoundingBox()))
{
ItemStack iStack = entityitem.getEntityItem();
if(ItemStack.areItemsEqual(stack, iStack) && ItemStack.areItemStackTagsEqual(stack, iStack)){
return entityitem;
}
}
return null;
}
private boolean isDone(){
return !deliveringItems && currentTarget == null && getNextTarget() == null;
}
private AxisAlignedBB getAreaBoundingBox(){
int xMin = areaRefPos.getX();
int yMin = areaRefPos.getY() - 1;
int zMin = areaRefPos.getZ();
int xMax = areaRefPos.getX() + area.getX() + 1;
int yMax = areaRefPos.getY() + area.getY() + 1;
int zMax = areaRefPos.getZ() + area.getZ() + 1;
if(area.getX() < 0){
xMin += area.getX();
xMax = areaRefPos.getX() + 1;
}
if(area.getY() < 0){
yMin += area.getY() - 1;
yMax = areaRefPos.getY() + 1;
}
if(area.getZ() < 0){
zMin += area.getZ();
zMax = areaRefPos.getZ() + 1;
}
return new AxisAlignedBB(xMin, yMin, zMin, xMax, yMax, zMax);
}
@Override
public void writeToNBT(NBTTagCompound compound) {
super.writeToNBT(compound);
Utilities.saveBlockPosToNBT(compound, itemsTargetPos, "itemsTargetPos");
Utilities.saveBlockPosToNBT(compound, areaRefPos, "areaRefPos");
Utilities.saveBlockPosToNBT(compound, area, "area");
compound.setBoolean("deliveringItems", deliveringItems);
compound.setBoolean("maxStackSizeReached", maxStackSizeReached);
}
@Override
public void readFromNBT(NBTTagCompound compound) {
super.readFromNBT(compound);
itemsTargetPos = Utilities.readBlockPosFromNBT(compound, "itemsTargetPos");
areaRefPos = Utilities.readBlockPosFromNBT(compound, "areaRefPos");
area = Utilities.readBlockPosFromNBT(compound, "area");
deliveringItems = compound.getBoolean("deliveringItems");
maxStackSizeReached = compound.getBoolean("maxStackSizeReached");
}
@Override
public boolean continueExecuting() {
return !(isDone() && aiOwner.getDistanceSqToCenter(itemsTargetPos) < 2.5);
}
@Override
public boolean shouldExecute() {
return super.shouldExecute() || !isDone() || aiOwner.getDistanceSqToCenter(itemsTargetPos) > 2;
}
@Override
protected boolean shouldRecalcPath() {
if(super.shouldRecalcPath() || (aiOwnerPathfinder.noPath() && !isDone())){
return true;
}
return false;
}
@Override
public void updateTask() {
super.updateTask();
if(currentTarget == null){ // Searching for a stack:
if(deliveringItems){ // Next stack:
if(isNearItemsTargetPos()){ // Reached target position for delivering
dropItem();
return;
}
else if(!maxStackSizeReached){
currentTarget = getNearestEqualStack(getItemStackOnCompound());
if(currentTarget == null || currentTarget.getDistanceSqToEntity(aiOwner) > aiOwner.getDistanceSqToCenter(itemsTargetPos)){
currentTarget = null;
return;
}
}
}
else{ //First stack:
currentTarget = getNextTarget();
}
if(currentTarget != null){
setTargetPos(currentTarget.getPositionVector());
}
}
else{ // Pick up stack:
if(currentTarget.getPositionVector().squareDistanceTo(getTargetPos()) > 0.25){
setTargetPos(currentTarget.getPositionVector());
return;
}
if(isNearTargetPosition()){
pickUpItem(getRemoveItemStackOnNBT());
setTargetPos(new Vec3d(itemsTargetPos).addVector(0.5, 0.5, 0.5));
}
}
}
private boolean isNearItemsTargetPos(){
return aiOwner.getDistanceSqToCenter(itemsTargetPos) <= 2;
}
private void dropItem(){
if(tryInsertingInInventorry()){
deliveringItems = false;
maxStackSizeReached = false;
}
}
private void pickUpItem(ItemStack storedStack){
ItemStack targetStack = currentTarget.getEntityItem();
if(storedStack == null){
setItemStackOnNBT(targetStack);
}
else{
int stackLimit = 0;
if(MAX_ITEM_STACK_SIZE > targetStack.getMaxStackSize()){
stackLimit = targetStack.getMaxStackSize();
}
else{
stackLimit = MAX_ITEM_STACK_SIZE;
}
int e = (storedStack.stackSize + targetStack.stackSize) - stackLimit;
if(e >= 0){
maxStackSizeReached = true;
targetStack.stackSize = e;
storedStack.stackSize = stackLimit;
world.spawnEntityInWorld(new EntityItem(world, currentTarget.posX, currentTarget.posY, currentTarget.posZ, targetStack));
setItemStackOnNBT(storedStack);
}
else{
storedStack.stackSize = storedStack.stackSize + targetStack.stackSize;
setItemStackOnNBT(storedStack);
}
}
world.removeEntity(currentTarget);
currentTarget = null;
deliveringItems = true;
}
private void setItemStackOnNBT(ItemStack stack){
NBTTagCompound compound = getCompound(aiOwner);
NBTTagCompound itemsCompound = new NBTTagCompound();
stack.writeToNBT(itemsCompound);
compound.setTag("itemsCompound", itemsCompound);
setCompound(aiOwner, compound);
}
private ItemStack getRemoveItemStackOnNBT(){
NBTTagCompound compound = getCompound(aiOwner);
NBTTagCompound itemsCompound = (NBTTagCompound) compound.getTag("itemsCompound");
if(itemsCompound == null){
return null;
}
ItemStack stack = ItemStack.loadItemStackFromNBT(itemsCompound);
compound.setTag("itemsCompound", new NBTTagCompound());
setCompound(aiOwner, compound);
return stack;
}
private ItemStack getItemStackOnCompound(){
NBTTagCompound compound = getCompound(aiOwner);
NBTTagCompound itemsCompound = (NBTTagCompound) compound.getTag("itemsCompound");
if(itemsCompound == null){
return null;
}
return ItemStack.loadItemStackFromNBT(itemsCompound);
}
private boolean tryInsertingInInventorry(){
TileEntity tE = world.getTileEntity(itemsTargetPos);
if(tE != null && tE instanceof IInventory){
IInventory iTE = (IInventory)tE;
ItemStack stack = getRemoveItemStackOnNBT();
if(stack == null){
return true;
}
int stackLimit = 0;
if(iTE.getInventoryStackLimit() < stack.getMaxStackSize()){
stackLimit = iTE.getInventoryStackLimit();
}
else{
stackLimit = stack.getMaxStackSize();
}
for(int i = 0; i < iTE.getSizeInventory();i++){
ItemStack iStack = iTE.getStackInSlot(i);
if(iStack == null){
iTE.setInventorySlotContents(i, stack);
return true;
}
if(ItemStack.areItemsEqual(iStack, stack) && ItemStack.areItemStackTagsEqual(iStack, stack) && iStack.stackSize < stackLimit){
int e = (iStack.stackSize + stack.stackSize) - stackLimit;
if(e > 0){
iStack.stackSize = stackLimit;
iTE.setInventorySlotContents(i, iStack);
stack.stackSize -= e;
}
else{
iStack.stackSize += stack.stackSize;
iTE.setInventorySlotContents(i, iStack);
return true;
}
}
}
setItemStackOnNBT(stack);
}
return false;
}
public static void addAdvancedTooltip(ItemStack stack, EntityPlayer playerIn, List<String> tooltip){
NBTTagCompound compound = stack.getTagCompound();
BlockPos p1 = Utilities.readBlockPosFromNBT(compound, "areaMin");
BlockPos p2 = Utilities.readBlockPosFromNBT(compound, "areaMax");
BlockPos p3 = Utilities.readBlockPosFromNBT(compound, "itemsTargetPos");
tooltip.add("5Area:");
if(p1 == null || p2 == null){
tooltip.add("-");
}
else{
tooltip.add("X: 6" + p1.getX() + " - " + p2.getX());
tooltip.add("Y: 6" + p1.getY() + " - " + p2.getY());
tooltip.add("Z: 6" + p1.getZ() + " - " + p2.getZ());
}
tooltip.add("");
if(p3 == null){
tooltip.add("5Items target Position: 6-");
}
else{
tooltip.add("5Items target Position: 6X=" + p3.getX() + " Y=" + p3.getY() + " Z=" + p3.getZ());
}
}
}
|
package com.abnormalentropy;
import com.abnormalentropy.exceptions.EmptyListException;
import com.abnormalentropy.exceptions.NoSingleElementException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.function.*;
public class LinqList<T> extends ArrayList<T>
{
private static final Logger LOGGER = LoggerFactory.getLogger(LinqList.class);
LinqList()
{
super();
}
LinqList(Collection<T> collection)
{
super(collection);
}
LinqList(int capacity)
{
super(capacity);
}
LinqList<T> where(Function<T, Boolean> function)
{
LinqList<T> linqList = new LinqList<T>();
this.forEach(x -> {
if (function.apply(x))
linqList.add(x);
});
return linqList;
}
Boolean any(Function<T, Boolean> function)
{
for (T x : this)
if (function.apply(x))
return true;
return false;
}
Boolean all(Function<T, Boolean> function)
{
for (T x : this)
if (!function.apply(x))
return false;
return true;
}
Boolean contains(T elem, Comparator<T> comparator)
{
for (T x : this)
if (comparator.compare(x, elem) == 0)
return true;
return false;
}
LinqList<T> intersect(LinqList<T> list)
{
LinqList<T> intersection = new LinqList<T>();
LinqList<T> shortList = (list.size() < this.size()) ? list : this;
LinqList<T> longList = (shortList == list) ? this : list;
shortList.forEach(x -> {
if (longList.contains(x))
intersection.add(x);
});
return intersection;
}
LinqList<T> intersect(LinqList<T> list, Comparator<T> comparator)
{
LinqList<T> intersection = new LinqList<T>();
LinqList<T> shortList = (list.size() < this.size()) ? list : this;
LinqList<T> longList = (shortList == list) ? this : list;
shortList.forEach(x -> {
if (longList.contains(x, comparator))
intersection.add(x);
});
return intersection;
}
T first() throws EmptyListException
{
if (this.isEmpty())
throw new EmptyListException();
return this.get(0);
}
T first(Function<T, Boolean> function) throws EmptyListException
{
return this.where(function).first();
}
T firstOrDefault()
{
return this.isEmpty() ? null : this.get(0);
}
T firstOrDefault(Function<T, Boolean> function)
{
return this.where(function).firstOrDefault();
}
T last() throws EmptyListException
{
if (this.isEmpty())
throw new EmptyListException();
return this.get(this.size()-1);
}
T last(Function<T, Boolean> function) throws EmptyListException
{
return this.where(function).last();
}
T lastOrDefault()
{
return this.isEmpty() ? null : this.get(this.size()-1);
}
T lastOrDefault(Function<T, Boolean> function)
{
return this.where(function).lastOrDefault();
}
List<T> toList()
{
return new ArrayList<T>(this);
}
<K> HashMap<K, T> toHashMap(Function<T, K> function)
{
HashMap<K, T> hashMap = new HashMap<K, T>();
this.forEach(x -> hashMap.put(function.apply(x), x));
return hashMap;
}
LinqList<T> union(List<T> list)
{
LinqList<T> union = new LinqList<T>(this);
for (T x : list)
if (!union.contains(x))
union.add(x);
return union;
}
LinqList<T> union(List<T> list, Comparator<T> comparator)
{
LinqList<T> union = new LinqList<T>(this);
for (T x : list)
if (!union.contains(x, comparator))
union.add(x);
return union;
}
<U, R> LinqList<R> zip(List<U> list, BiFunction<T, U, R> function)
{
LinqList<R> linqList = new LinqList<R>();
int end = Math.min(this.size(), list.size());
for (int k = 0; k < end; k++)
linqList.add(function.apply(this.get(k), list.get(k)));
return linqList;
}
LinqList<T> take(int size)
{
return new LinqList<T>(this.subList(0, size));
}
LinqList<T> skip(int from)
{
return new LinqList<T>(this.subList(from, this.size()));
}
T single() throws NoSingleElementException
{
if (this.size() > 1)
throw new NoSingleElementException();
return this.get(0);
}
T single(Function<T, Boolean> function) throws NoSingleElementException
{
return this.where(function).single();
}
T singleOrDefault()
{
return (this.size() > 1) ? null : this.get(0);
}
T singleOrDefault(Function<T, Boolean> function)
{
return this.where(function).singleOrDefault();
}
LinqList<T> concat(LinqList<T> list)
{
LinqList<T> returnList = new LinqList<T>(list);
list.forEach(x -> returnList.add(x));
return returnList;
}
int count(Function<T, Boolean> function)
{
return this.where(function).size();
}
}
|
package com.microlands.android.draganddraw;
import android.content.Context;
import android.graphics.PointF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
public class BoxDrawingView extends View {
private static final String TAG = "BoxDrawingView";
public BoxDrawingView(Context context) {
this(context, null);
}
public BoxDrawingView(Context context, AttributeSet attributes) {
super(context, attributes);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
PointF current = new PointF(event.getX(), event.getY());
String action = "";
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
action = "ACTION_DOWN";
break;
case MotionEvent.ACTION_MOVE:
action = "ACTION_MOVE";
break;
case MotionEvent.ACTION_UP:
action = "ACTION_UP";
break;
case MotionEvent.ACTION_CANCEL:
action = "ACTION_CANCEL";
break;
}
Log.i(TAG, action + " at x = " + current.x + " , y = " + current.y);
return true;
}
}
|
package com.example.admin.goparty.views.activity;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.AppCompatButton;
import android.widget.Toast;
import com.example.admin.goparty.R;
import com.example.admin.goparty.models.Party;
import com.example.admin.goparty.presenters.PartyPresenter;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMapOptions;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
@Bind(R.id.btn_add_location)
AppCompatButton btnAddLocation;
private GoogleMap mMap;
LatLng tappedPoint;
PartyPresenter partyPresenter = new PartyPresenter();
Party party;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps2);
ButterKnife.bind(this);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
Intent intent = getIntent();
String title = intent.getExtras().getString("title");
Integer duration = intent.getExtras().getInt("duration");
party = new Party();
party.setTitle(title);
party.setDuration(duration);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat
// int[] grantResults)
// for ActivityCompat
return;
}
mMap.setMyLocationEnabled(true);
GoogleMapOptions options = new GoogleMapOptions();
options.mapType(GoogleMap.MAP_TYPE_SATELLITE)
.compassEnabled(true)
.rotateGesturesEnabled(true)
.tiltGesturesEnabled(true)
.ambientEnabled(true);
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng point) {
tappedPoint = point;
mMap.clear();
mMap.addMarker(new MarkerOptions().position(point));
}
});
}
@OnClick(R.id.btn_add_location)
public void onClick() {
if(tappedPoint != null){
party.setLatitude(tappedPoint.latitude);
party.setLongitude(tappedPoint.longitude);
partyPresenter.addParty(this, party);
CharSequence text = "Party Successfully added";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(this, text, duration);
toast.show();
Intent intent = new Intent(this, PartyActivity.class);
startActivity(intent);
}
else{
CharSequence text = "Tap on the map to add location";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(this, text, duration);
toast.show();
}
}
}
|
package com.github.to2mbn.to2nbt;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONObject;
abstract public class NBT implements Cloneable {
protected static NBT createNewByType(byte id) {
switch (id) {
case NBTByte.ID:
return new NBTByte();
case NBTShort.ID:
return new NBTShort();
case NBTInt.ID:
return new NBTInt();
case NBTLong.ID:
return new NBTLong();
case NBTFloat.ID:
return new NBTFloat();
case NBTDouble.ID:
return new NBTDouble();
case NBTByteArray.ID:
return new NBTByteArray();
case NBTString.ID:
return new NBTString();
case NBTList.ID:
return new NBTList();
case NBTCompound.ID:
return new NBTCompound();
case NBTIntArray.ID:
return new NBTIntArray();
default:
return null;
}
}
@Override
abstract public NBT clone();
abstract protected byte getId();
abstract protected void write(DataOutput out) throws IOException;
abstract protected void read(DataInput in) throws IOException;
abstract public Object unwrap();
@Override
public String toString() {
Object unwrapped = unwrap();
if (unwrapped instanceof Map) {
return new JSONObject((Map<?, ?>) unwrapped).toString();
} else if (unwrapped instanceof Collection) {
return new JSONArray((List<?>) unwrapped).toString();
} else if (unwrapped.getClass().isArray()) {
return new JSONArray((List<?>) unwrapped).toString();
} else {
return new JSONObject(unwrapped).toString();
}
}
@Override
public boolean equals(Object another) {
if (!(another instanceof NBT)) {
return false;
}
return getId() == ((NBT) another).getId();
}
@Override
public int hashCode() {
return getId();
}
}
|
package com.jaamsim.input;
import java.awt.FileDialog;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import com.jaamsim.ui.ExceptionBox;
import com.jaamsim.ui.FrameBox;
import com.jaamsim.ui.LogBox;
import com.sandwell.JavaSimulation.Entity;
import com.sandwell.JavaSimulation.ErrorException;
import com.sandwell.JavaSimulation.FileEntity;
import com.sandwell.JavaSimulation.Group;
import com.sandwell.JavaSimulation.Input;
import com.sandwell.JavaSimulation.Input.ParseContext;
import com.sandwell.JavaSimulation.InputErrorException;
import com.sandwell.JavaSimulation.ObjectType;
import com.sandwell.JavaSimulation.Palette;
import com.sandwell.JavaSimulation.Simulation;
import com.sandwell.JavaSimulation.StringVector;
import com.sandwell.JavaSimulation.Util;
import com.sandwell.JavaSimulation3D.GUIFrame;
public class InputAgent {
private static final String recordEditsMarker = "RecordEdits";
private static int numErrors = 0;
private static int numWarnings = 0;
private static FileEntity logFile;
private static double lastTimeForTrace;
private static File configFile; // present configuration file
private static boolean batchRun;
private static boolean sessionEdited; // TRUE if any inputs have been changed after loading a configuration file
private static boolean recordEditsFound; // TRUE if the "RecordEdits" marker is found in the configuration file
private static boolean recordEdits; // TRUE if input changes are to be marked as edited.
private static final String INP_ERR_DEFINEUSED = "The name: %s has already been used and is a %s";
private static File reportDir;
static {
recordEditsFound = false;
sessionEdited = false;
batchRun = false;
configFile = null;
reportDir = null;
lastTimeForTrace = -1.0d;
}
public static void clear() {
logFile = null;
numErrors = 0;
numWarnings = 0;
recordEditsFound = false;
sessionEdited = false;
configFile = null;
reportDir = null;
lastTimeForTrace = -1.0d;
}
private static String getReportDirectory() {
if (reportDir != null)
return reportDir.getPath() + File.separator;
if (configFile != null)
return configFile.getParentFile().getPath() + File.separator;
return null;
}
public static String getReportFileName(String name) {
return getReportDirectory() + name;
}
public static void setReportDirectory(String dir) {
String reportDirectory = Util.getAbsoluteFilePath(dir);
if (!reportDirectory.substring(reportDirectory.length() - 1).equals("\\"))
reportDirectory = reportDirectory + "\\";
// Create the report directory if it does not already exist
// This code should probably be added to FileEntity someday to
// create necessary folders on demand.
reportDir = new File(reportDirectory);
}
public static void prepareReportDirectory() {
if (reportDir != null) reportDir.mkdirs();
}
/**
* Sets the present configuration file.
*
* @param file - the present configuration file.
*/
public static void setConfigFile(File file) {
configFile = file;
}
/**
* Returns the present configuration file.
* <p>
* Null is returned if no configuration file has been loaded or saved yet.
* <p>
* @return the present configuration file.
*/
public static File getConfigFile() {
return configFile;
}
/**
* Returns the name of the simulation run.
* <p>
* For example, if the configuration file name is "case1.cfg", then the
* run name is "case1".
* <p>
* @return the name of simulation run.
*/
public static String getRunName() {
if( InputAgent.getConfigFile() == null )
return "";
String name = InputAgent.getConfigFile().getName();
int index = name.indexOf( "." );
if( index == -1 )
return name;
return name.substring( 0, index );
}
/**
* Specifies whether a RecordEdits marker was found in the present configuration file.
*
* @param bool - TRUE if a RecordEdits marker was found.
*/
public static void setRecordEditsFound(boolean bool) {
recordEditsFound = bool;
}
/**
* Indicates whether a RecordEdits marker was found in the present configuration file.
*
* @return - TRUE if a RecordEdits marker was found.
*/
public static boolean getRecordEditsFound() {
return recordEditsFound;
}
/**
* Returns the "RecordEdits" mode for the InputAgent.
* <p>
* When RecordEdits is TRUE, any model inputs that are changed and any objects that
* are defined are marked as "edited". When FALSE, model inputs and object
* definitions are marked as "unedited".
* <p>
* RecordEdits mode is used to determine the way JaamSim saves a configuration file
* through the graphical user interface. Object definitions and model inputs
* that are marked as unedited will be copied exactly as they appear in the original
* configuration file that was first loaded. Object definitions and model inputs
* that are marked as edited will be generated automatically by the program.
*
* @return the RecordEdits mode for the InputAgent.
*/
public static boolean recordEdits() {
return recordEdits;
}
/**
* Sets the "RecordEdits" mode for the InputAgent.
* <p>
* When RecordEdits is TRUE, any model inputs that are changed and any objects that
* are defined are marked as "edited". When FALSE, model inputs and object
* definitions are marked as "unedited".
* <p>
* RecordEdits mode is used to determine the way JaamSim saves a configuration file
* through the graphical user interface. Object definitions and model inputs
* that are marked as unedited will be copied exactly as they appear in the original
* configuration file that was first loaded. Object definitions and model inputs
* that are marked as edited will be generated automatically by the program.
*
* @param b - boolean value for the RecordEdits mode
*/
public static void setRecordEdits(boolean b) {
recordEdits = b;
}
public static boolean isSessionEdited() {
return sessionEdited;
}
public static void setBatch(boolean batch) {
batchRun = batch;
}
public static boolean getBatch() {
return batchRun;
}
/**
* returns true if the first and last tokens are matched braces
**/
public static boolean enclosedByBraces(ArrayList<String> tokens) {
if(tokens.size() < 2 || tokens.indexOf("{") < 0) // no braces
return false;
int level =1;
int i = 1;
for(String each: tokens.subList(1, tokens.size())) {
if(each.equals("{")) {
level++;
}
if(each.equals("}")) {
level
// Matching close brace found
if(level == 0)
break;
}
i++;
}
if(level == 0 && i == tokens.size()-1) {
return true;
}
return false;
}
private static int getBraceDepth(ArrayList<String> tokens, int startingBraceDepth, int startingIndex) {
int braceDepth = startingBraceDepth;
for (int i = startingIndex; i < tokens.size(); i++) {
String token = tokens.get(i);
if (token.equals("{"))
braceDepth++;
if (token.equals("}"))
braceDepth
if (braceDepth < 0) {
InputAgent.logBadInput(tokens, "Extra closing braces found");
tokens.clear();
}
if (braceDepth > 2) {
InputAgent.logBadInput(tokens, "Maximum brace depth (2) exceeded");
tokens.clear();
}
}
return braceDepth;
}
private static URI resRoot;
private static URI resPath;
private static final String res = "/resources/";
static {
try {
// locate the resource folder, and create
resRoot = InputAgent.class.getResource(res).toURI();
}
catch (URISyntaxException e) {}
resPath = URI.create(resRoot.toString());
}
private static void rethrowWrapped(Exception ex) {
StringBuilder causedStack = new StringBuilder();
for (StackTraceElement elm : ex.getStackTrace())
causedStack.append(elm.toString()).append("\n");
throw new InputErrorException("Caught exception: %s", ex.getMessage() + "\n" + causedStack.toString());
}
public static final void readResource(String res) {
if (res == null)
return;
try {
readStream(resRoot.toString(), resPath, res);
GUIFrame.instance().setProgressText(null);
}
catch (URISyntaxException ex) {
rethrowWrapped(ex);
}
}
public static final boolean readStream(String root, URI path, String file) throws URISyntaxException {
String shortName = file.substring(file.lastIndexOf('/') + 1, file.length());
GUIFrame.instance().setProgressText(shortName);
URI resolved = getFileURI(path, file, root);
String resolvedPath = resolved.getSchemeSpecificPart();
String currentDir = resolvedPath.substring(0, resolvedPath.lastIndexOf('/') + 1);
String oldRoot = FileEntity.getRootDirectory();
FileEntity.setRootDirectory(currentDir);
URL url = null;
try {
url = resolved.normalize().toURL();
}
catch (MalformedURLException e) {
rethrowWrapped(e);
}
if (url == null) {
InputAgent.logWarning("Unable to resolve path %s%s - %s", root, path.toString(), file);
return false;
}
BufferedReader buf = null;
try {
InputStream in = url.openStream();
buf = new BufferedReader(new InputStreamReader(in));
} catch (IOException e) {
InputAgent.logWarning("Could not read from %s", url.toString());
return false;
}
try {
ArrayList<String> record = new ArrayList<String>();
int braceDepth = 0;
Input.ParseContext pc = new Input.ParseContext();
pc.jail = root;
pc.context = resolved;
while (true) {
String line = buf.readLine();
// end of file, stop reading
if (line == null)
break;
int previousRecordSize = record.size();
Parser.tokenize(record, line, true);
braceDepth = InputAgent.getBraceDepth(record, braceDepth, previousRecordSize);
if( braceDepth != 0 )
continue;
if (record.size() == 0)
continue;
InputAgent.echoInputRecord(record);
if ("DEFINE".equalsIgnoreCase(record.get(0))) {
InputAgent.processDefineRecord(record);
record.clear();
continue;
}
if ("INCLUDE".equalsIgnoreCase(record.get(0))) {
try {
InputAgent.processIncludeRecord(pc, record);
}
catch (URISyntaxException ex) {
rethrowWrapped(ex);
}
record.clear();
continue;
}
if ("RECORDEDITS".equalsIgnoreCase(record.get(0))) {
InputAgent.setRecordEditsFound(true);
InputAgent.setRecordEdits(true);
record.clear();
continue;
}
// Otherwise assume it is a Keyword record
InputAgent.processKeywordRecord(record, pc);
record.clear();
}
// Leftover Input at end of file
if (record.size() > 0)
InputAgent.logBadInput(record, "Leftover input at end of file");
buf.close();
}
catch (IOException e) {
// Make best effort to ensure it closes
try { buf.close(); } catch (IOException e2) {}
}
FileEntity.setRootDirectory(oldRoot);
return true;
}
private static void processIncludeRecord(ParseContext pc, ArrayList<String> record) throws URISyntaxException {
if (record.size() != 2) {
InputAgent.logError("Bad Include record, should be: Include <File>");
return;
}
InputAgent.readStream(pc.jail, pc.context, record.get(1).replaceAll("\\\\", "/"));
}
private static void processDefineRecord(ArrayList<String> record) {
if (record.size() < 5 ||
!record.get(2).equals("{") ||
!record.get(record.size() - 1).equals("}")) {
InputAgent.logError("Bad Define record, should be: Define <Type> { <names>... }");
return;
}
Class<? extends Entity> proto = null;
try {
if( record.get( 1 ).equalsIgnoreCase( "Palette" ) ) {
proto = Palette.class;
}
else if( record.get( 1 ).equalsIgnoreCase( "ObjectType" ) ) {
proto = ObjectType.class;
}
else {
proto = Input.parseEntityType(record.get(1));
}
}
catch (InputErrorException e) {
InputAgent.logError("%s", e.getMessage());
return;
}
// Loop over all the new Entity names
for (int i = 3; i < record.size() - 1; i++) {
InputAgent.defineEntity(proto, record.get(i), InputAgent.recordEdits());
}
}
/**
* Like defineEntity(), but will generate a unique name if a name collision exists
* @param proto
* @param key
* @param addedEntity
* @return
*/
public static <T extends Entity> T defineEntityWithUniqueName(Class<T> proto, String key, boolean addedEntity) {
// Has the provided name been used already?
if (Entity.getNamedEntity(key) == null) {
return defineEntity(proto, key, addedEntity);
}
// Try the provided name plus "-1", "-2", etc. until an unused name is found
int entityNum = 1;
while(true) {
String name = String.format("%s-%d", key, entityNum);
if (Entity.getNamedEntity(name) == null) {
return defineEntity(proto, name, addedEntity);
}
entityNum++;
}
}
/**
* if addedEntity is true then this is an entity defined
* by user interaction or after added record flag is found;
* otherwise, it is from an input file define statement
* before the model is configured
* @param proto
* @param key
* @param addedEntity
*/
public static <T extends Entity> T defineEntity(Class<T> proto, String key, boolean addedEntity) {
Entity existingEnt = Input.tryParseEntity(key, Entity.class);
if (existingEnt != null) {
InputAgent.logError(INP_ERR_DEFINEUSED, key, existingEnt.getClass().getSimpleName());
return null;
}
T ent = null;
try {
ent = proto.newInstance();
if (addedEntity) {
ent.setFlag(Entity.FLAG_ADDED);
sessionEdited = true;
}
}
catch (InstantiationException e) {}
catch (IllegalAccessException e) {}
finally {
if (ent == null) {
InputAgent.logError("Could not create new Entity: %s", key);
return null;
}
}
ent.setInputName(key);
return ent;
}
public static void processKeywordRecord(ArrayList<String> record, Input.ParseContext context) {
Entity ent = Input.tryParseEntity(record.get(0), Entity.class);
if (ent == null) {
InputAgent.logError("Could not find Entity: %s", record.get(0));
return;
}
// Validate the tokens have the Entity Keyword { Args... } Keyword { Args... }
ArrayList<KeywordIndex> words = InputAgent.getKeywords(record, context);
for (KeywordIndex keyword : words) {
try {
InputAgent.processKeyword(ent, keyword);
}
catch (Throwable e) {
InputAgent.logInpError("Entity: %s, Keyword: %s - %s", ent.getInputName(), keyword.keyword, e.getMessage());
}
}
}
public static class KeywordIndex {
public final ArrayList<String> input;
public final String keyword;
public final int start;
public final int end;
public final ParseContext context;
public KeywordIndex(ArrayList<String> inp, int s, int e, ParseContext ctxt) {
input = inp;
keyword = input.get(s);
start = s;
end = e;
context = ctxt;
}
}
private static ArrayList<KeywordIndex> getKeywords(ArrayList<String> input, ParseContext context) {
ArrayList<KeywordIndex> ret = new ArrayList<KeywordIndex>();
int braceDepth = 0;
int index = 1;
for (int i = 1; i < input.size(); i++) {
String tok = input.get(i);
if ("{".equals(tok)) {
braceDepth++;
continue;
}
if ("}".equals(tok)) {
braceDepth
if (braceDepth == 0) {
ret.add(new KeywordIndex(input, index, i, context));
index = i + 1;
continue;
}
}
}
// Look for a leftover keyword at the end of line
KeywordIndex last = ret.get(ret.size() - 1);
if (last.end != input.size() - 1) {
ret.add(new KeywordIndex(input, last.end + 1, input.size() - 1, context));
}
for (KeywordIndex kw : ret) {
if (!"{".equals(input.get(kw.start + 1)) ||
!"}".equals(input.get(kw.end))) {
throw new InputErrorException("Keyword %s not valid, should be <keyword> { <args> }", kw.keyword);
}
}
return ret;
}
public static void doError(Throwable e) {
if (!batchRun)
return;
LogBox.logLine("An error occurred in the simulation environment. Please check inputs for an error:");
LogBox.logLine(e.toString());
GUIFrame.shutdown(1);
}
// Load the run file
public static void loadConfigurationFile( File file) throws URISyntaxException {
String inputTraceFileName = InputAgent.getRunName() + ".log";
// Initializing the tracing for the model
try {
System.out.println( "Creating trace file" );
URI confURI = file.toURI();
URI logURI = confURI.resolve(new URI(null, inputTraceFileName, null)); // The new URI here effectively escapes the file name
// Set and open the input trace file name
logFile = new FileEntity( logURI.getPath(), FileEntity.FILE_WRITE, false );
}
catch( Exception e ) {
InputAgent.logWarning("Could not create trace file");
}
URI dirURI = file.getParentFile().toURI();
InputAgent.readStream("", dirURI, file.getName());
FileEntity.setRootDirectory(dirURI.getPath());
GUIFrame.instance().setProgressText(null);
GUIFrame.instance().setProgress(0);
// At this point configuration file is loaded
// The session is not considered to be edited after loading a configuration file
sessionEdited = false;
// Save and close the input trace file
if (logFile != null) {
if (InputAgent.numWarnings == 0 && InputAgent.numErrors == 0) {
logFile.close();
logFile.delete();
logFile = new FileEntity( inputTraceFileName, FileEntity.FILE_WRITE, false );
}
}
// Check for found errors
if( InputAgent.numErrors > 0 )
throw new InputErrorException("%d input errors and %d warnings found, check %s", InputAgent.numErrors, InputAgent.numWarnings, inputTraceFileName);
if (Simulation.getPrintInputReport())
InputAgent.printInputFileKeywords();
}
public static final void apply(Entity ent, KeywordIndex kw) {
Input<?> in = ent.getInput(kw.keyword);
if (in == null) {
InputAgent.logWarning("Keyword %s could not be found for Entity %s.", kw.keyword, ent.getInputName());
return;
}
InputAgent.apply(ent, in, kw);
FrameBox.valueUpdate();
}
public static final void apply(Entity ent, Input<?> in, KeywordIndex kw) {
StringVector data = new StringVector(kw.end - kw.start);
for (int i = kw.start + 2; i < kw.end; i++) {
data.add(kw.input.get(i));
}
in.parse(data, kw.context);
// Only mark the keyword edited if we have finished initial configuration
if ( InputAgent.recordEdits() )
in.setEdited(true);
ent.updateForInput(in);
if(ent.testFlag(Entity.FLAG_GENERATED))
return;
StringBuilder out = new StringBuilder(data.size() * 6);
for (int i = 0; i < data.size(); i++) {
String dat = data.get(i);
if (Parser.needsQuoting(dat) && !dat.equals("{") && !dat.equals("}"))
out.append("'").append(dat).append("'");
else
out.append(dat);
if( i < data.size() - 1 )
out.append(" ");
}
if(in.isEdited()) {
ent.setFlag(Entity.FLAG_EDITED);
sessionEdited = true;
}
in.setValueString(out.toString());
}
private static void processKeyword(Entity entity, KeywordIndex key) {
if (entity.testFlag(Entity.FLAG_LOCKED))
throw new InputErrorException("Entity: %s is locked and cannot be modified", entity.getName());
Input<?> input = entity.getInput( key.keyword );
if (input != null) {
InputAgent.apply(entity, input, key);
FrameBox.valueUpdate();
return;
}
if (!(entity instanceof Group))
throw new InputErrorException("Not a valid keyword");
Group grp = (Group)entity;
grp.saveGroupKeyword(key);
// Store the keyword data for use in the edit table
for( int i = 0; i < grp.getList().size(); i++ ) {
Entity ent = grp.getList().get( i );
InputAgent.apply(ent, key);
}
}
private static class ConfigFileFilter implements FilenameFilter {
@Override
public boolean accept(File inFile, String fileName) {
return fileName.endsWith("[cC][fF][gG]");
}
}
public static void load(GUIFrame gui) {
LogBox.logLine("Loading...");
FileDialog chooser = new FileDialog(gui, "Load Configuration File", FileDialog.LOAD);
chooser.setFilenameFilter(new ConfigFileFilter());
chooser.setFile("*.cfg");
chooser.setVisible(true); // display the dialog, waits for selection
String file = chooser.getFile();
if (file == null)
return;
String absFile = chooser.getDirectory() + file;
absFile = absFile.trim();
File temp = new File(absFile);
InputAgent.setLoadFile(gui, temp);
}
public static void save(GUIFrame gui) {
LogBox.logLine("Saving...");
if( InputAgent.getConfigFile() != null ) {
setSaveFile(gui, InputAgent.getConfigFile().getPath() );
}
else {
saveAs( gui );
}
}
public static void saveAs(GUIFrame gui) {
LogBox.logLine("Save As...");
FileDialog chooser = new FileDialog(gui, "Save Configuration File As", FileDialog.SAVE);
chooser.setFilenameFilter(new ConfigFileFilter());
chooser.setFile(InputAgent.getConfigFile().getPath());
// Display the dialog and wait for selection
chooser.setVisible(true);
String file = chooser.getFile();
if (file == null)
return;
String absFile = chooser.getDirectory() + file;
// Compensate for an error in FileDialog under Java 7:
// - If the new name is shorter than the old name, then the method getDirectory() returns the absolute path and
// the file name. The method getFile() returns a corrupted version of the old file name.
// - If the new name is the same length or longer than the new name then both methods work properly.
// Expected to be fixed in Java 8.
if( System.getProperty("java.version").startsWith("1.7.") ) {
String dir = chooser.getDirectory();
if( InputAgent.getConfigFile() != null && !dir.endsWith("\\") && !dir.endsWith("/") ) {
absFile = dir;
}
}
// Add the file extension ".cfg" if needed
absFile = absFile.trim();
if( ! absFile.substring(absFile.length()-4).equalsIgnoreCase(".cfg") )
absFile = absFile.concat(".cfg");
// Save the configuration file
setSaveFile(gui, absFile);
}
public static void configure(GUIFrame gui, File file) {
try {
gui.clear();
InputAgent.setConfigFile(file);
gui.updateForSimulationState(GUIFrame.SIM_STATE_UNCONFIGURED);
try {
InputAgent.loadConfigurationFile(file);
}
catch( InputErrorException iee ) {
if (!batchRun)
ExceptionBox.instance().setErrorBox(iee.getMessage());
else
LogBox.logLine( iee.getMessage() );
}
LogBox.logLine("Configuration File Loaded");
// show the present state in the user interface
gui.setTitle( Simulation.getModelName() + " - " + InputAgent.getRunName() );
gui.updateForSimulationState(GUIFrame.SIM_STATE_CONFIGURED);
gui.enableSave(InputAgent.getRecordEditsFound());
}
catch( Throwable t ) {
ExceptionBox.instance().setError(t);
}
}
/**
* Loads the configuration file.
* <p>
* @param gui - the Control Panel.
* @param file - the configuration file to be loaded.
*/
private static void setLoadFile(final GUIFrame gui, File file) {
final File chosenfile = file;
new Thread(new Runnable() {
@Override
public void run() {
InputAgent.setRecordEdits(false);
InputAgent.configure(gui, chosenfile);
InputAgent.setRecordEdits(true);
GUIFrame.displayWindows(true);
FrameBox.valueUpdate();
}
}).start();
}
/**
* Saves the configuration file.
* @param gui = Control Panel window for JaamSim
* @param fileName = absolute file path and file name for the file to be saved
*/
private static void setSaveFile(GUIFrame gui, String fileName) {
// Set root directory
File temp = new File(fileName);
FileEntity.setRootDirectory( temp.getParentFile() );
// Save the configuration file
InputAgent.printNewConfigurationFileWithName( fileName );
sessionEdited = false;
InputAgent.setConfigFile(temp);
// Set the title bar to match the new run name
gui.setTitle( Simulation.getModelName() + " - " + InputAgent.getRunName() );
}
/*
* write input file keywords and values
*
* input file format:
* Define Group { <Group names> }
* Define <Object> { <Object names> }
*
* <Object name> <Keyword> { < values > }
*
*/
public static void printInputFileKeywords() {
// Create report file for the inputs
String inputReportFileName = InputAgent.getReportFileName(InputAgent.getRunName() + ".inp");
FileEntity inputReportFile = new FileEntity( inputReportFileName, FileEntity.FILE_WRITE, false );
inputReportFile.flush();
// Loop through the entity classes printing Define statements
for (ObjectType type : ObjectType.getAll()) {
Class<? extends Entity> each = type.getJavaClass();
// Loop through the instances for this entity class
int count = 0;
for (Entity ent : Entity.getInstanceIterator(each)) {
boolean hasinput = false;
for (Input<?> in : ent.getEditableInputs()) {
// If the keyword has been used, then add a record to the report
if (in.getValueString().length() != 0) {
hasinput = true;
count++;
break;
}
}
if (hasinput) {
String entityName = ent.getInputName();
if ((count - 1) % 5 == 0) {
inputReportFile.putString("Define");
inputReportFile.putTab();
inputReportFile.putString(type.getInputName());
inputReportFile.putTab();
inputReportFile.putString("{ " + entityName);
inputReportFile.putTab();
}
else if ((count - 1) % 5 == 4) {
inputReportFile.putString(entityName + " }");
inputReportFile.newLine();
}
else {
inputReportFile.putString(entityName);
inputReportFile.putTab();
}
}
}
if (!Entity.getInstanceIterator(each).hasNext()) {
if (count % 5 != 0) {
inputReportFile.putString(" }");
inputReportFile.newLine();
}
inputReportFile.newLine();
}
}
for (ObjectType type : ObjectType.getAll()) {
Class<? extends Entity> each = type.getJavaClass();
// Get the list of instances for this entity class
// sort the list alphabetically
ArrayList<? extends Entity> cloneList = Entity.getInstancesOf(each);
// Print the entity class name to the report (in the form of a comment)
if (cloneList.size() > 0) {
inputReportFile.putString("\" " + each.getSimpleName() + " \"");
inputReportFile.newLine();
inputReportFile.newLine(); // blank line below the class name heading
}
Collections.sort(cloneList, new Comparator<Entity>() {
@Override
public int compare(Entity a, Entity b) {
return a.getInputName().compareTo(b.getInputName());
}
});
// Loop through the instances for this entity class
for (int j = 0; j < cloneList.size(); j++) {
// Make sure the clone is an instance of the class (and not an instance of a subclass)
if (cloneList.get(j).getClass() == each) {
Entity ent = cloneList.get(j);
String entityName = ent.getInputName();
boolean hasinput = false;
// Loop through the editable keywords for this instance
for (Input<?> in : ent.getEditableInputs()) {
// If the keyword has been used, then add a record to the report
if (in.getValueString().length() != 0) {
if (!in.getCategory().contains("Graphics")) {
hasinput = true;
inputReportFile.putTab();
inputReportFile.putString(entityName);
inputReportFile.putTab();
inputReportFile.putString(in.getKeyword());
inputReportFile.putTab();
if (in.getValueString().lastIndexOf("{") > 10) {
String[] item1Array;
item1Array = in.getValueString().trim().split(" }");
inputReportFile.putString("{ " + item1Array[0] + " }");
for (int l = 1; l < (item1Array.length); l++) {
inputReportFile.newLine();
inputReportFile.putTabs(5);
inputReportFile.putString(item1Array[l] + " } ");
}
inputReportFile.putString(" }");
}
else {
inputReportFile.putString("{ " + in.getValueString() + " }");
}
inputReportFile.newLine();
}
}
}
// Put a blank line after each instance
if (hasinput) {
inputReportFile.newLine();
}
}
}
}
// Close out the report
inputReportFile.flush();
inputReportFile.close();
}
public static void closeLogFile() {
if (logFile == null)
return;
logFile.flush();
logFile.close();
if (numErrors ==0 && numWarnings == 0) {
logFile.delete();
}
logFile = null;
}
private static final String errPrefix = "*** ERROR *** %s%n";
private static final String inpErrPrefix = "*** INPUT ERROR *** %s%n";
private static final String wrnPrefix = "***WARNING*** %s%n";
public static int numErrors() {
return numErrors;
}
public static int numWarnings() {
return numWarnings;
}
private static void echoInputRecord(ArrayList<String> tokens) {
if (logFile == null)
return;
StringBuilder line = new StringBuilder();
for (int i = 0; i < tokens.size(); i++) {
line.append(" ").append(tokens.get(i));
if (tokens.get(i).startsWith("\"")) {
logFile.write(line.toString());
logFile.newLine();
line.setLength(0);
}
}
// Leftover input
if (line.length() > 0) {
logFile.write(line.toString());
logFile.newLine();
}
logFile.flush();
}
private static void logBadInput(ArrayList<String> tokens, String msg) {
InputAgent.echoInputRecord(tokens);
InputAgent.logError("%s", msg);
}
public static void logMessage(String fmt, Object... args) {
String msg = String.format(fmt, args);
System.out.println(msg);
LogBox.logLine(msg);
if (logFile == null)
return;
logFile.write(msg);
logFile.newLine();
logFile.flush();
}
public static void trace(int indent, Entity ent, String meth, String... text) {
// Create an indent string to space the lines
StringBuilder ind = new StringBuilder("");
for (int i = 0; i < indent; i++)
ind.append(" ");
String spacer = ind.toString();
// Print a TIME header every time time has advanced
double traceTime = ent.getCurrentTime();
if (lastTimeForTrace != traceTime) {
System.out.format(" \nTIME = %.5f\n", traceTime);
lastTimeForTrace = traceTime;
}
// Output the traces line(s)
System.out.format("%s%s %s\n", spacer, ent.getName(), meth);
for (String line : text) {
System.out.format("%s%s\n", spacer, line);
}
System.out.flush();
}
public static void logWarning(String fmt, Object... args) {
numWarnings++;
String msg = String.format(fmt, args);
InputAgent.logMessage(wrnPrefix, msg);
}
public static void logError(String fmt, Object... args) {
numErrors++;
String msg = String.format(fmt, args);
InputAgent.logMessage(errPrefix, msg);
}
public static void logInpError(String fmt, Object... args) {
numErrors++;
String msg = String.format(fmt, args);
InputAgent.logMessage(inpErrPrefix, msg);
}
public static void processEntity_Keyword_Value(Entity ent, Input<?> in, String value){
ArrayList<String> tokens = new ArrayList<String>();
tokens.add(in.getKeyword());
tokens.add("{");
Parser.tokenize(tokens, value, true);
tokens.add("}");
KeywordIndex kw = new KeywordIndex(tokens, 0, tokens.size() - 1, null);
InputAgent.processKeyword(ent, kw);
}
public static void processEntity_Keyword_Value(Entity ent, String keyword, String value){
ArrayList<String> tokens = new ArrayList<String>();
tokens.add(keyword);
tokens.add("{");
Parser.tokenize(tokens, value, true);
tokens.add("}");
KeywordIndex kw = new KeywordIndex(tokens, 0, tokens.size() - 1, null);
InputAgent.processKeyword(ent, kw);
}
/**
* Prints the present state of the model to a new configuration file.
*
* @param fileName - the full path and file name for the new configuration file.
*/
public static void printNewConfigurationFileWithName( String fileName ) {
// Copy the original configuration file up to the "RecordEdits" marker (if present)
// Temporary storage for the copied lines is needed in case the original file is to be overwritten
ArrayList<String> preAddedRecordLines = new ArrayList<String>();
if( InputAgent.getConfigFile() != null ) {
try {
BufferedReader in = new BufferedReader( new FileReader(InputAgent.getConfigFile()) );
String line;
while ( ( line = in.readLine() ) != null ) {
preAddedRecordLines.add( line );
if ( line.startsWith( recordEditsMarker ) ) {
break;
}
}
in.close();
}
catch ( Exception e ) {
throw new ErrorException( e );
}
}
// Create the new configuration file and copy the saved lines
FileEntity file = new FileEntity( fileName, FileEntity.FILE_WRITE, false );
for( int i=0; i < preAddedRecordLines.size(); i++ ) {
file.format("%s%n", preAddedRecordLines.get( i ));
}
// If not already present, insert the "RecordEdits" marker at the end of the original configuration file
if( ! InputAgent.getRecordEditsFound() ) {
file.format("%n%s%n", recordEditsMarker);
InputAgent.setRecordEditsFound(true);
}
// Determine all the new classes that were created
ArrayList<Class<? extends Entity>> newClasses = new ArrayList<Class<? extends Entity>>();
for (int i = 0; i < Entity.getAll().size(); i++) {
Entity ent = Entity.getAll().get(i);
if (!ent.testFlag(Entity.FLAG_ADDED))
continue;
if (!newClasses.contains(ent.getClass()))
newClasses.add(ent.getClass());
}
// Add a blank line before the first object definition
if( !newClasses.isEmpty() )
file.format("%n");
// Identify the object types for which new instances were defined
for( Class<? extends Entity> newClass : newClasses ) {
for (ObjectType o : ObjectType.getAll()) {
if (o.getJavaClass() == newClass) {
// Print the first part of the "Define" statement for this object type
file.format("Define %s {", o.getInputName());
break;
}
}
// Print the new instances that were defined
for (int i = 0; i < Entity.getAll().size(); i++) {
Entity ent = Entity.getAll().get(i);
if (!ent.testFlag(Entity.FLAG_ADDED))
continue;
if (ent.getClass() == newClass)
file.format(" %s ", ent.getInputName());
}
// Close the define statement
file.format("}%n");
}
// Identify the entities whose inputs were edited
for (int i = 0; i < Entity.getAll().size(); i++) {
Entity ent = Entity.getAll().get(i);
if (ent.testFlag(Entity.FLAG_EDITED)) {
file.format("%n");
writeInputsOnFile_ForEntity( file, ent );
}
}
// Close the new configuration file
file.flush();
file.close();
}
/**
* Prints the configuration file entries for Entity ent to the FileEntity file.
*
* @param file - the target configuration file.
* @param ent - the entity whose configuration file entries are to be written.
*/
static void writeInputsOnFile_ForEntity( FileEntity file, Entity ent ) {
// Loop through the keywords for this entity
for( int j=0; j < ent.getEditableInputs().size(); j++ ) {
Input<?> in = ent.getEditableInputs().get( j );
if (!in.isEdited())
continue;
// Print the keywords and values
String value = in.getValueString();
ArrayList<String> tokens = new ArrayList<String>();
Parser.tokenize(tokens, value);
if (!InputAgent.enclosedByBraces(tokens))
file.format("%s %s { %s }%n", ent.getInputName(), in.getKeyword(), value);
else
file.format("%s %s %s%n", ent.getInputName(), in.getKeyword(), value);
}
}
/**
* Returns the relative file path for the specified URI.
* <p>
* The path can start from either the folder containing the present
* configuration file or from the resources folder.
* <p>
* @param uri - the URI to be relativized.
* @return the relative file path.
*/
static public String getRelativeFilePath(URI uri) {
// Relativize the file path against the resources folder
String resString = resRoot.toString();
String inputString = uri.toString();
if (inputString.startsWith(resString)) {
return String.format("'<res>/%s'", inputString.substring(resString.length()));
}
// Relativize the file path against the configuration file
try {
URI configDirURI = InputAgent.getConfigFile().getParentFile().toURI();
return String.format("'%s'", configDirURI.relativize(uri).getPath());
}
catch (Exception ex) {
return String.format("'%s'", uri.getPath());
}
}
/**
* Loads the default configuration file.
*/
public static void loadDefault() {
// Read the default configuration file
InputAgent.readResource("inputs/default.cfg");
// A RecordEdits marker in the default configuration must be ignored
InputAgent.setRecordEditsFound(false);
// Set the model state to unedited
sessionEdited = false;
}
/**
* Split an input (list of strings) down to a single level of nested braces, this may then be called again for
* further nesting.
* @param input
* @return
*/
public static ArrayList<ArrayList<String>> splitForNestedBraces(List<String> input) {
ArrayList<ArrayList<String>> inputs = new ArrayList<ArrayList<String>>();
int braceDepth = 0;
ArrayList<String> currentLine = null;
for (int i = 0; i < input.size(); i++) {
if (currentLine == null)
currentLine = new ArrayList<String>();
currentLine.add(input.get(i));
if (input.get(i).equals("{")) {
braceDepth++;
continue;
}
if (input.get(i).equals("}")) {
braceDepth
if (braceDepth == 0) {
inputs.add(currentLine);
currentLine = null;
continue;
}
}
}
return inputs;
}
/**
* Converts a file path String to a URI.
* <p>
* The specified file path can be either relative or absolute. In the case
* of a relative file path, a 'context' folder must be specified. A context
* of null indicates an absolute file path.
* <p>
* To avoid bad input accessing an inappropriate file, a 'jail' folder can
* be specified. The URI to be returned must include the jail folder for it
* to be valid.
* <p>
* @param context - full file path for the folder that is the reference for relative file paths.
* @param filePath - string to be resolved to a URI.
* @param jailPrefix - file path to a base folder from which a relative cannot escape.
* @return the URI corresponding to the context and filePath.
*/
public static URI getFileURI(URI context, String filePath, String jailPrefix) throws URISyntaxException {
// Replace all backslashes with slashes
String path = filePath.replaceAll("\\\\", "/");
int colon = path.indexOf(':');
int openBrace = path.indexOf('<');
int closeBrace = path.indexOf('>');
int firstSlash = path.indexOf('/');
// Add a leading slash if needed to convert from Windows format (e.g. from "C:" to "/C:")
if (colon == 1)
path = String.format("/%s", path);
// 1) File path starts with a tagged folder, using the syntax "<tagName>/"
URI ret = null;
if (openBrace == 0 && closeBrace != -1 && firstSlash == closeBrace + 1) {
String specPath = path.substring(openBrace + 1, closeBrace);
// Resources folder in the Jar file
if (specPath.equals("res")) {
ret = new URI(resRoot.getScheme(), resRoot.getSchemeSpecificPart() + path.substring(closeBrace+2), null).normalize();
}
}
// 2) Normal file path
else {
URI pathURI = new URI(null, path, null).normalize();
if (context != null) {
if (context.isOpaque()) {
// Things are going to get messy in here
URI schemeless = new URI(null, context.getSchemeSpecificPart(), null);
URI resolved = schemeless.resolve(pathURI).normalize();
// Note: we are using the one argument constructor here because the 'resolved' URI is already encoded
// and we do not want to double-encode (and schemes should never need encoding, I hope)
ret = new URI(context.getScheme() + ":" + resolved.toString());
} else {
ret = context.resolve(pathURI).normalize();
}
} else {
// We have no context, so append a 'file' scheme if necessary
if (pathURI.getScheme() == null) {
ret = new URI("file", pathURI.getPath(), null);
} else {
ret = pathURI;
}
}
}
// Check that the file path includes the jail folder
if (jailPrefix != null && ret.toString().indexOf(jailPrefix) != 0) {
LogBox.format("Failed jail test: %s in jail: %s context: %s\n", ret.toString(), jailPrefix, context.toString());
LogBox.getInstance().setVisible(true);
return null; // This resolved URI is not in our jail
}
return ret;
}
/**
* Determines whether or not a file exists.
* <p>
* @param filePath - URI for the file to be tested.
* @return true if the file exists, false if it does not.
*/
public static boolean fileExists(URI filePath) {
try {
InputStream in = filePath.toURL().openStream();
in.close();
return true;
}
catch (MalformedURLException ex) {
return false;
}
catch (IOException ex) {
return false;
}
}
}
|
package com.punchline.javalib.entities.systems.generic;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.InputMultiplexer;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector3;
import com.punchline.javalib.entities.Entity;
import com.punchline.javalib.entities.systems.InputSystem;
/**
* System for moving the camera based on keyboard input from the arrow keys.
* @author Nathaniel
* @created Jul 23, 2013
*/
public class CameraMovementSystem extends InputSystem {
private static final float CAMERA_SPEED = 200f;
private static final float MOVEMENT_BORDER = .125f;
private Camera camera;
private Rectangle bounds;
private boolean movingLeft = false;
private boolean movingRight = false;
private boolean movingUp = false;
private boolean movingDown = false;
/**
* Makes a CameraMovementSystem
* @param input the game's current InputMultiplexer.
* @param camera The camera that this system will control.
*/
public CameraMovementSystem(InputMultiplexer input, Camera camera, Rectangle bounds) {
super(input);
this.camera = camera;
this.bounds = bounds;
}
@Override
public boolean canProcess(Entity e) {
return false; //Doesn't actually process Entities
}
@Override
public void processEntities() {
super.processEntities();
Vector3 movement = new Vector3(0, 0, 0);
if (movingLeft) {
movement.x = - 1;
} else if (movingRight) {
movement.x = 1;
}
if (movingUp){
movement.y = 1;
} else if (movingDown) {
movement.y = -1;
}
movement.nor();
movement.mul(CAMERA_SPEED);
movement.mul(deltaSeconds());
camera.translate(movement);
float left = camera.position.x - camera.viewportWidth / 2;
float bottom = camera.position.y - camera.viewportHeight / 2;
float right = left + camera.viewportWidth;
float top = bottom + camera.viewportHeight;
if (left < bounds.x) {
camera.position.x = bounds.x + camera.viewportWidth / 2;
}
if (top > bounds.y + camera.viewportHeight) {
camera.position.y = bounds.y + camera.viewportHeight - camera.viewportHeight / 2;
}
if (right > bounds.x + bounds.width) {
camera.position.x = bounds.x + bounds.width - camera.viewportWidth / 2;
}
if (bottom < bounds.y) {
camera.position.y = bounds.y + camera.viewportHeight / 2;
}
}
@Override
public boolean keyDown(int keycode) {
if (keycode == Keys.LEFT) {
movingLeft = true;
return true;
} else if (keycode == Keys.RIGHT){
movingRight = true;
return true;
}
if (keycode == Keys.UP) {
movingUp = true;
return true;
} else if (keycode == Keys.DOWN) {
movingDown = true;
return true;
}
return false;
}
@Override
public boolean keyUp(int keycode) {
if (keycode == Keys.LEFT) {
movingLeft = false;
return true;
} else if (keycode == Keys.RIGHT){
movingRight = false;
return true;
}
if (keycode == Keys.UP) {
movingUp = false;
return true;
} else if (keycode == Keys.DOWN) {
movingDown = false;
return true;
}
return false;
}
@Override
public boolean mouseMoved(int screenX, int screenY) {
int windowWidth = Gdx.graphics.getWidth();
int windowHeight = Gdx.graphics.getHeight();
int leftThreshold = (int)(windowWidth * MOVEMENT_BORDER);
int downThreshold = (int)(windowHeight * MOVEMENT_BORDER);
int rightThreshold = windowWidth - leftThreshold;
int upThreshold = windowHeight - downThreshold;
if (screenX < leftThreshold) {
movingLeft = true;
} else if (screenX > rightThreshold) {
movingRight = true;
} else {
movingLeft = false;
movingRight = false;
}
if (screenY < downThreshold) {
movingDown = true;
} else if (screenY > upThreshold) {
movingUp = true;
} else {
movingDown = false;
movingUp = false;
}
return false;
}
}
|
package edu.umd.cs.findbugs;
import java.io.IOException;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.concurrent.atomic.AtomicReference;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.meta.When;
import org.apache.bcel.Constants;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.InvokeInstruction;
import org.apache.bcel.generic.MethodGen;
import org.apache.bcel.generic.Type;
import org.objectweb.asm.tree.ClassNode;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.ba.AnalysisContext;
import edu.umd.cs.findbugs.ba.CFGBuilderException;
import edu.umd.cs.findbugs.ba.ClassContext;
import edu.umd.cs.findbugs.ba.DataflowAnalysisException;
import edu.umd.cs.findbugs.ba.Hierarchy2;
import edu.umd.cs.findbugs.ba.JavaClassAndMethod;
import edu.umd.cs.findbugs.ba.Location;
import edu.umd.cs.findbugs.ba.OpcodeStackScanner;
import edu.umd.cs.findbugs.ba.XFactory;
import edu.umd.cs.findbugs.ba.XField;
import edu.umd.cs.findbugs.ba.XMethod;
import edu.umd.cs.findbugs.ba.bcp.FieldVariable;
import edu.umd.cs.findbugs.ba.vna.ValueNumberSourceInfo;
import edu.umd.cs.findbugs.classfile.CheckedAnalysisException;
import edu.umd.cs.findbugs.classfile.ClassDescriptor;
import edu.umd.cs.findbugs.classfile.FieldDescriptor;
import edu.umd.cs.findbugs.classfile.Global;
import edu.umd.cs.findbugs.classfile.IAnalysisCache;
import edu.umd.cs.findbugs.classfile.MethodDescriptor;
import edu.umd.cs.findbugs.cloud.Cloud;
import edu.umd.cs.findbugs.cloud.Cloud.UserDesignation;
import edu.umd.cs.findbugs.internalAnnotations.DottedClassName;
import edu.umd.cs.findbugs.internalAnnotations.SlashedClassName;
import edu.umd.cs.findbugs.util.ClassName;
import edu.umd.cs.findbugs.util.Util;
import edu.umd.cs.findbugs.visitclass.DismantleBytecode;
import edu.umd.cs.findbugs.visitclass.PreorderVisitor;
import edu.umd.cs.findbugs.xml.XMLAttributeList;
import edu.umd.cs.findbugs.xml.XMLOutput;
import edu.umd.cs.findbugs.xml.XMLWriteable;
/**
* An instance of a bug pattern. A BugInstance consists of several parts:
* <p/>
* <ul>
* <li>the type, which is a string indicating what kind of bug it is; used as a
* key for the FindBugsMessages resource bundle
* <li>the priority; how likely this instance is to actually be a bug
* <li>a list of <em>annotations</em>
* </ul>
* <p/>
* The annotations describe classes, methods, fields, source locations, and
* other relevant context information about the bug instance. Every BugInstance
* must have at least one ClassAnnotation, which describes the class in which
* the instance was found. This is the "primary class annotation".
* <p/>
* <p>
* BugInstance objects are built up by calling a string of <code>add</code>
* methods. (These methods all "return this", so they can be chained). Some of
* the add methods are specialized to get information automatically from a
* BetterVisitor or DismantleBytecode object.
*
* @author David Hovemeyer
* @see BugAnnotation
*/
public class BugInstance implements Comparable<BugInstance>, XMLWriteable, Serializable, Cloneable {
private static final long serialVersionUID = 1L;
private final String type;
private int priority;
private final ArrayList<BugAnnotation> annotationList;
private int cachedHashCode;
private @CheckForNull
BugDesignation userDesignation;
private BugProperty propertyListHead, propertyListTail;
private String oldInstanceHash;
private String instanceHash;
private int instanceOccurrenceNum;
private int instanceOccurrenceMax;
private DetectorFactory detectorFactory;
private final AtomicReference<XmlProps> xmlProps = new AtomicReference<XmlProps>();
/*
* The following fields are used for tracking Bug instances across multiple
* versions of software. They are meaningless in a BugCollection for just
* one version of software.
*/
private long firstVersion = 0;
private long lastVersion = -1;
private boolean introducedByChangeOfExistingClass;
private boolean removedByChangeOfPersistingClass;
/**
* This value is used to indicate that the cached hashcode is invalid, and
* should be recomputed.
*/
private static final int INVALID_HASH_CODE = 0;
/**
* This value is used to indicate whether BugInstances should be
* reprioritized very low, when the BugPattern is marked as experimental
*/
private static boolean adjustExperimental = false;
private static Set<String> missingBugTypes = Collections.synchronizedSet(new HashSet<String>());
public static DateFormat firstSeenXMLFormat() {
return DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.ENGLISH);
}
/**
* Constructor.
*
* @param type
* the bug type
* @param priority
* the bug priority
*/
public BugInstance(String type, int priority) {
this.type = type.intern();
this.priority = priority;
annotationList = new ArrayList<BugAnnotation>(4);
cachedHashCode = INVALID_HASH_CODE;
BugPattern p = DetectorFactoryCollection.instance().lookupBugPattern(type);
if (p == null) {
if (missingBugTypes.add(type)) {
String msg = "Can't find definition of bug type " + type;
AnalysisContext.logError(msg, new IllegalArgumentException(msg));
}
} else
this.priority += p.getPriorityAdjustment();
if (adjustExperimental && isExperimental())
this.priority = Priorities.EXP_PRIORITY;
boundPriority();
}
private void boundPriority() {
priority = boundedPriority(priority);
}
@Override
public Object clone() {
BugInstance dup;
try {
dup = (BugInstance) super.clone();
// Do deep copying of mutable objects
for (int i = 0; i < dup.annotationList.size(); ++i) {
dup.annotationList.set(i, (BugAnnotation) dup.annotationList.get(i).clone());
}
dup.propertyListHead = dup.propertyListTail = null;
for (Iterator<BugProperty> i = propertyIterator(); i.hasNext();) {
dup.addProperty((BugProperty) i.next().clone());
}
return dup;
} catch (CloneNotSupportedException e) {
throw new AssertionError(e);
}
}
/**
* Create a new BugInstance. This is the constructor that should be used by
* Detectors.
*
* @param detector
* the Detector that is reporting the BugInstance
* @param type
* the bug type
* @param priority
* the bug priority
*/
public BugInstance(Detector detector, String type, int priority) {
this(type, priority);
if (detector != null) {
// Adjust priority if required
String detectorName = detector.getClass().getName();
adjustForDetector(detectorName);
}
}
/**
* @param detectorName
*/
public void adjustForDetector(String detectorName) {
detectorFactory = DetectorFactoryCollection.instance().getFactoryByClassName(detectorName);
if (detectorFactory != null) {
this.priority += detectorFactory.getPriorityAdjustment();
boundPriority();
BugPattern bugPattern = getBugPattern();
if (SystemProperties.ASSERTIONS_ENABLED && !bugPattern.getCategory().equals("EXPERIMENTAL")
&& !detectorFactory.getReportedBugPatterns().contains(bugPattern))
AnalysisContext.logError(detectorFactory.getShortName() + " doesn't note that it reports "
+ bugPattern + " in category " + bugPattern.getCategory());
}
}
/**
* Create a new BugInstance. This is the constructor that should be used by
* Detectors.
*
* @param detector
* the Detector2 that is reporting the BugInstance
* @param type
* the bug type
* @param priority
* the bug priority
*/
public BugInstance(Detector2 detector, String type, int priority) {
this(type, priority);
if (detector != null) {
// Adjust priority if required
String detectorName = detector.getDetectorClassName();
adjustForDetector(detectorName);
}
}
public static void setAdjustExperimental(boolean adjust) {
adjustExperimental = adjust;
}
/**
* Get the bug pattern name (e.g., IL_INFINITE_RECURSIVE_LOOP)
*/
public String getType() {
return type;
}
/**
* Get the BugPattern.
*/
public @NonNull
BugPattern getBugPattern() {
BugPattern result = DetectorFactoryCollection.instance().lookupBugPattern(getType());
if (result != null)
return result;
AnalysisContext.logError("Unable to find description of bug pattern " + getType());
result = DetectorFactoryCollection.instance().lookupBugPattern("UNKNOWN");
if (result != null)
return result;
return BugPattern.REALLY_UNKNOWN;
}
/**
* Get the bug priority.
*/
public int getPriority() {
return priority;
}
public int getBugRank() {
return BugRanker.findRank(this);
}
public BugRankCategory getBugRankCategory() {
return BugRankCategory.getRank(getBugRank());
}
/**
* Get a string describing the bug priority and type. e.g.
* "High Priority Correctness"
*
* @return a string describing the bug priority and type
*/
public String getPriorityTypeString() {
String priorityString = getPriorityString();
BugPattern bugPattern = this.getBugPattern();
// then get the category and put everything together
String categoryString;
if (bugPattern == null)
categoryString = "Unknown category for " + getType();
else
categoryString = I18N.instance().getBugCategoryDescription(bugPattern.getCategory());
return priorityString + " Confidence " + categoryString;
// TODO: internationalize the word "Confidence"
}
public String getPriorityTypeAbbreviation() {
String priorityString = getPriorityAbbreviation();
return priorityString + " " + getCategoryAbbrev();
}
public String getCategoryAbbrev() {
BugPattern bugPattern = getBugPattern();
if (bugPattern == null)
return "?";
return bugPattern.getCategoryAbbrev();
}
public String getPriorityString() {
// first, get the priority
int value = this.getPriority();
String priorityString;
if (value == Priorities.HIGH_PRIORITY)
priorityString = edu.umd.cs.findbugs.L10N.getLocalString("sort.priority_high", "High");
else if (value == Priorities.NORMAL_PRIORITY)
priorityString = edu.umd.cs.findbugs.L10N.getLocalString("sort.priority_normal", "Medium");
else if (value == Priorities.LOW_PRIORITY)
priorityString = edu.umd.cs.findbugs.L10N.getLocalString("sort.priority_low", "Low");
else if (value == Priorities.EXP_PRIORITY)
priorityString = edu.umd.cs.findbugs.L10N.getLocalString("sort.priority_experimental", "Experimental");
else
priorityString = edu.umd.cs.findbugs.L10N.getLocalString("sort.priority_ignore", "Ignore"); // This
// probably
// shouldn't
// ever
// happen,
// but
// what
// the
// hell,
// let's
// complete
return priorityString;
}
public String getPriorityAbbreviation() {
return getPriorityString().substring(0, 1);
}
/**
* Set the bug priority.
*/
public void setPriority(int p) {
priority = boundedPriority(p);
}
private int boundedPriority(int p) {
return Math.max(Priorities.HIGH_PRIORITY, Math.min(Priorities.IGNORE_PRIORITY, p));
}
public void raisePriority() {
priority = boundedPriority(priority - 1);
}
public void lowerPriority() {
priority = boundedPriority(priority + 1);
}
public void lowerPriorityALot() {
priority = boundedPriority(priority + 2);
}
/**
* Is this bug instance the result of an experimental detector?
*/
public boolean isExperimental() {
BugPattern pattern = getBugPattern();
return (pattern != null) && pattern.isExperimental();
}
/**
* Get the primary class annotation, which indicates where the bug occurs.
*/
public ClassAnnotation getPrimaryClass() {
ClassAnnotation result = findPrimaryAnnotationOfType(ClassAnnotation.class);
if (result == null) {
System.out.println("huh");
result = findPrimaryAnnotationOfType(ClassAnnotation.class);
}
return result;
}
/**
* Get the primary method annotation, which indicates where the bug occurs.
*/
public MethodAnnotation getPrimaryMethod() {
return findPrimaryAnnotationOfType(MethodAnnotation.class);
}
/**
* Get the primary method annotation, which indicates where the bug occurs.
*/
public FieldAnnotation getPrimaryField() {
return findPrimaryAnnotationOfType(FieldAnnotation.class);
}
public BugInstance lowerPriorityIfDeprecated() {
MethodAnnotation m = getPrimaryMethod();
if (m != null && XFactory.createXMethod(m).isDeprecated())
lowerPriority();
FieldAnnotation f = getPrimaryField();
if (f != null && XFactory.createXField(f).isDeprecated())
lowerPriority();
return this;
}
/**
* Find the first BugAnnotation in the list of annotations that is the same
* type or a subtype as the given Class parameter.
*
* @param cls
* the Class parameter
* @return the first matching BugAnnotation of the given type, or null if
* there is no such BugAnnotation
*/
private <T extends BugAnnotation> T findPrimaryAnnotationOfType(Class<T> cls) {
T bestMatch = null;
for (Iterator<BugAnnotation> i = annotationIterator(); i.hasNext();) {
BugAnnotation annotation = i.next();
if (cls.isAssignableFrom(annotation.getClass())) {
if (annotation.getDescription().endsWith("DEFAULT"))
return cls.cast(annotation);
else
bestMatch = cls.cast(annotation);
}
}
return bestMatch;
}
public LocalVariableAnnotation getPrimaryLocalVariableAnnotation() {
for (BugAnnotation annotation : annotationList)
if (annotation instanceof LocalVariableAnnotation)
return (LocalVariableAnnotation) annotation;
return null;
}
/**
* Get the primary source line annotation. There is guaranteed to be one
* (unless some Detector constructed an invalid BugInstance).
*
* @return the source line annotation
*/
public SourceLineAnnotation getPrimarySourceLineAnnotation() {
// Highest priority: return the first top level source line annotation
for (BugAnnotation annotation : annotationList) {
if (annotation instanceof SourceLineAnnotation
&& annotation.getDescription().equals(SourceLineAnnotation.DEFAULT_ROLE)
&& !((SourceLineAnnotation) annotation).isUnknown())
return (SourceLineAnnotation) annotation;
}
for (BugAnnotation annotation : annotationList) {
if (annotation instanceof SourceLineAnnotation && !((SourceLineAnnotation) annotation).isUnknown())
return (SourceLineAnnotation) annotation;
}
// Next: Try primary method, primary field, primary class
SourceLineAnnotation srcLine;
if ((srcLine = inspectPackageMemberSourceLines(getPrimaryMethod())) != null)
return srcLine;
if ((srcLine = inspectPackageMemberSourceLines(getPrimaryField())) != null)
return srcLine;
if ((srcLine = inspectPackageMemberSourceLines(getPrimaryClass())) != null)
return srcLine;
// Last resort: throw exception
throw new IllegalStateException("BugInstance for " + getType()
+ " must contain at least one class, method, or field annotation");
}
public String getInstanceKey() {
String newValue = getInstanceKeyNew();
return newValue;
}
private String getInstanceKeyNew() {
StringBuilder buf = new StringBuilder(type);
for (BugAnnotation annotation : annotationList)
if (annotation.isSignificant() || annotation instanceof IntAnnotation
|| annotation instanceof LocalVariableAnnotation) {
buf.append(":");
buf.append(annotation.format("hash", null));
}
return buf.toString();
}
/**
* If given PackageMemberAnnotation is non-null, return its
* SourceLineAnnotation.
*
* @param packageMember
* a PackageMemberAnnotation
* @return the PackageMemberAnnotation's SourceLineAnnotation, or null if
* there is no SourceLineAnnotation
*/
private SourceLineAnnotation inspectPackageMemberSourceLines(PackageMemberAnnotation packageMember) {
return (packageMember != null) ? packageMember.getSourceLines() : null;
}
/**
* Get an Iterator over all bug annotations.
*/
public Iterator<BugAnnotation> annotationIterator() {
return annotationList.iterator();
}
/**
* Get an Iterator over all bug annotations.
*/
public List<? extends BugAnnotation> getAnnotations() {
return annotationList;
}
/** Get the first bug annotation with the specified class and role; return null if no
* such annotation exists;
* @param role
* @return
*/
public @CheckForNull <A extends BugAnnotation> A getAnnotationWithRole(Class<A> c, String role) {
for(BugAnnotation a : annotationList) {
if (c.isInstance(a) && Util.nullSafeEquals(role, a.getDescription()))
return c.cast(a);
}
return null;
}
/**
* Get the abbreviation of this bug instance's BugPattern. This is the same
* abbreviation used by the BugCode which the BugPattern is a particular
* species of.
*/
public String getAbbrev() {
BugPattern pattern = getBugPattern();
return pattern != null ? pattern.getAbbrev() : "<unknown bug pattern>";
}
/** clear the user designation. */
public void clearUserDesignation() {
userDesignation = null;
}
/**
* set the user designation object. This will clobber any existing
* annotationText (or any other BugDesignation field).
*/
@Deprecated
public void setUserDesignation(BugDesignation bd) {
userDesignation = bd;
}
/**
* return the user designation object, which may be null.
*
* A previous calls to getSafeUserDesignation(), setAnnotationText(), or
* setUserDesignation() will ensure it will be non-null [barring an
* intervening setUserDesignation(null)].
*
* @see #getNonnullUserDesignation()
*/
@Deprecated
@Nullable
public BugDesignation getUserDesignation() {
return userDesignation;
}
/**
* return the user designation object, creating one if necessary. So calling
* <code>getSafeUserDesignation().setDesignation("HARMLESS")</code> will
* always work without the possibility of a NullPointerException.
*
* @see #getUserDesignation()
*/
@Deprecated
@NonNull
public BugDesignation getNonnullUserDesignation() {
if (userDesignation == null)
userDesignation = new BugDesignation();
return userDesignation;
}
/**
* Get the user designation key. E.g., "MOSTLY_HARMLESS", "CRITICAL",
* "NOT_A_BUG", etc.
*
* If the user designation object is null,returns UNCLASSIFIED.
*
* To set the user designation key, call
* <code>getSafeUserDesignation().setDesignation("HARMLESS")</code>.
*
* @see I18N#getUserDesignation(String key)
* @return the user designation key
*/
@NonNull
public String getUserDesignationKey() {
if (userDesignation == null)
return BugDesignation.UNCLASSIFIED;
return userDesignation.getDesignationKey();
}
public @CheckForNull
String getUserName() {
if (userDesignation == null)
return null;
return userDesignation.getUser();
}
public long getUserTimestamp() {
if (userDesignation == null)
return Long.MAX_VALUE;
return userDesignation.getTimestamp();
}
@NonNull
public int getUserDesignationKeyIndex() {
return I18N.instance().getUserDesignationKeys(true).indexOf(getUserDesignationKey());
}
/**
* @param key
* @param bugCollection
* TODO
*/
public void setUserDesignationKey(String key, @CheckForNull BugCollection bugCollection) {
BugDesignation userDesignation = getNonnullUserDesignation();
if (userDesignation.getDesignationKey().equals(key))
return;
userDesignation.setDesignationKey(key);
Cloud plugin = bugCollection != null ? bugCollection.getCloud() : null;
if (plugin != null)
plugin.storeUserAnnotation(this);
}
/**
* s
*
* @param index
* @param bugCollection
* TODO
*/
public void setUserDesignationKeyIndex(int index, @CheckForNull BugCollection bugCollection) {
setUserDesignationKey(I18N.instance().getUserDesignationKey(index), bugCollection);
}
/**
* Set the user annotation text.
*
* @param annotationText
* the user annotation text
* @param bugCollection
* TODO
*/
public void setAnnotationText(String annotationText, @CheckForNull BugCollection bugCollection) {
final BugDesignation u = getNonnullUserDesignation();
String existingText = u.getAnnotationText();
if (existingText != null && existingText.equals(annotationText))
return;
u.setAnnotationText(annotationText);
Cloud plugin = bugCollection != null ? bugCollection.getCloud() : null;
if (plugin != null)
plugin.storeUserAnnotation(this);
}
/**
* Get the user annotation text.
*
* @return the user annotation text
*/
@NonNull
public String getAnnotationText() {
BugDesignation userDesignation = this.userDesignation;
if (userDesignation == null)
return "";
String s = userDesignation.getAnnotationText();
if (s == null)
return "";
return s;
}
public void setUser(String user) {
BugDesignation userDesignation = getNonnullUserDesignation();
userDesignation.setUser(user);
}
public void setUserAnnotationTimestamp(long timestamp) {
BugDesignation userDesignation = getNonnullUserDesignation();
userDesignation.setTimestamp(timestamp);
}
/**
* Determine whether or not the annotation text contains the given word.
*
* @param word
* the word
* @return true if the annotation text contains the word, false otherwise
*/
public boolean annotationTextContainsWord(String word) {
return getTextAnnotationWords().contains(word);
}
/**
* Get set of words in the text annotation.
*/
public Set<String> getTextAnnotationWords() {
HashSet<String> result = new HashSet<String>();
StringTokenizer tok = new StringTokenizer(getAnnotationText(), " \t\r\n\f.,:;-");
while (tok.hasMoreTokens()) {
result.add(tok.nextToken());
}
return result;
}
public boolean hasXmlProps() {
XmlProps props = xmlProps.get();
return props != null;
}
public XmlProps getXmlProps() {
XmlProps props = xmlProps.get();
if (props != null)
return props;
props = new XmlProps();
while (xmlProps.get() == null)
xmlProps.compareAndSet(null, props);
return xmlProps.get();
}
public boolean hasSomeUserAnnotation() {
return !getAnnotationText().equals("")
|| !getUserDesignationKey().equals(BugDesignation.UNCLASSIFIED);
}
private class BugPropertyIterator implements Iterator<BugProperty> {
private BugProperty prev, cur;
private boolean removed;
/*
* (non-Javadoc)
*
* @see java.util.Iterator#hasNext()
*/
public boolean hasNext() {
return findNext() != null;
}
/*
* (non-Javadoc)
*
* @see java.util.Iterator#next()
*/
public BugProperty next() {
BugProperty next = findNext();
if (next == null)
throw new NoSuchElementException();
prev = cur;
cur = next;
removed = false;
return cur;
}
/*
* (non-Javadoc)
*
* @see java.util.Iterator#remove()
*/
public void remove() {
if (cur == null || removed)
throw new IllegalStateException();
if (prev == null) {
propertyListHead = cur.getNext();
} else {
prev.setNext(cur.getNext());
}
if (cur == propertyListTail) {
propertyListTail = prev;
}
removed = true;
}
private BugProperty findNext() {
return cur == null ? propertyListHead : cur.getNext();
}
}
/**
* Get value of given property.
*
* @param name
* name of the property to get
* @return the value of the named property, or null if the property has not
* been set
*/
public String getProperty(String name) {
BugProperty prop = lookupProperty(name);
return prop != null ? prop.getValue() : null;
}
/**
* Get value of given property, returning given default value if the
* property has not been set.
*
* @param name
* name of the property to get
* @param defaultValue
* default value to return if propery is not set
* @return the value of the named property, or the default value if the
* property has not been set
*/
public String getProperty(String name, String defaultValue) {
String value = getProperty(name);
return value != null ? value : defaultValue;
}
/**
* Get an Iterator over the properties defined in this BugInstance.
*
* @return Iterator over properties
*/
public Iterator<BugProperty> propertyIterator() {
return new BugPropertyIterator();
}
/**
* Set value of given property.
*
* @param name
* name of the property to set
* @param value
* the value of the property
* @return this object, so calls can be chained
*/
public BugInstance setProperty(String name, String value) {
BugProperty prop = lookupProperty(name);
if (prop != null) {
prop.setValue(value);
} else {
prop = new BugProperty(name, value);
addProperty(prop);
}
return this;
}
/**
* Look up a property by name.
*
* @param name
* name of the property to look for
* @return the BugProperty with the given name, or null if the property has
* not been set
*/
public BugProperty lookupProperty(String name) {
BugProperty prop = propertyListHead;
while (prop != null) {
if (prop.getName().equals(name))
break;
prop = prop.getNext();
}
return prop;
}
/**
* Delete property with given name.
*
* @param name
* name of the property to delete
* @return true if a property with that name was deleted, or false if there
* is no such property
*/
public boolean deleteProperty(String name) {
BugProperty prev = null;
BugProperty prop = propertyListHead;
while (prop != null) {
if (prop.getName().equals(name))
break;
prev = prop;
prop = prop.getNext();
}
if (prop != null) {
if (prev != null) {
// Deleted node in interior or at tail of list
prev.setNext(prop.getNext());
} else {
// Deleted node at head of list
propertyListHead = prop.getNext();
}
if (prop.getNext() == null) {
// Deleted node at end of list
propertyListTail = prev;
}
return true;
} else {
// No such property
return false;
}
}
private void addProperty(BugProperty prop) {
if (propertyListTail != null) {
propertyListTail.setNext(prop);
propertyListTail = prop;
} else {
propertyListHead = propertyListTail = prop;
}
prop.setNext(null);
}
/**
* Add a Collection of BugAnnotations.
*
* @param annotationCollection
* Collection of BugAnnotations
*/
public BugInstance addAnnotations(Collection<? extends BugAnnotation> annotationCollection) {
for (BugAnnotation annotation : annotationCollection) {
add(annotation);
}
return this;
}
public BugInstance addClassAndMethod(MethodDescriptor methodDescriptor) {
addClass(ClassName.toDottedClassName(methodDescriptor.getSlashedClassName()));
add(MethodAnnotation.fromMethodDescriptor(methodDescriptor));
return this;
}
public BugInstance addClassAndMethod(XMethod xMethod) {
return addClassAndMethod(xMethod.getMethodDescriptor());
}
/**
* Add a class annotation and a method annotation for the class and method
* which the given visitor is currently visiting.
*
* @param visitor
* the BetterVisitor
* @return this object
*/
public BugInstance addClassAndMethod(PreorderVisitor visitor) {
addClass(visitor);
addMethod(visitor);
return this;
}
/**
* Add class and method annotations for given method.
*
* @param methodAnnotation
* the method
* @return this object
*/
public BugInstance addClassAndMethod(MethodAnnotation methodAnnotation) {
addClass(methodAnnotation.getClassName());
addMethod(methodAnnotation);
return this;
}
/**
* Add class and method annotations for given method.
*
* @param methodGen
* the method
* @param sourceFile
* source file the method is defined in
* @return this object
*/
public BugInstance addClassAndMethod(MethodGen methodGen, String sourceFile) {
addClass(methodGen.getClassName());
addMethod(methodGen, sourceFile);
return this;
}
/**
* Add class and method annotations for given class and method.
*
* @param javaClass
* the class
* @param method
* the method
* @return this object
*/
public BugInstance addClassAndMethod(JavaClass javaClass, Method method) {
addClass(javaClass.getClassName());
addMethod(javaClass, method);
return this;
}
/**
* Add a class annotation. If this is the first class annotation added, it
* becomes the primary class annotation.
*
* @param className
* the name of the class
* @param sourceFileName
* the source file of the class
* @return this object
*/
public BugInstance addClass(String className, String sourceFileName) {
ClassAnnotation classAnnotation = new ClassAnnotation(className, sourceFileName);
add(classAnnotation);
return this;
}
/**
* Add a class annotation. If this is the first class annotation added, it
* becomes the primary class annotation.
*
* @param className
* the name of the class
* @return this object
*/
public BugInstance addClass(@SlashedClassName(when = When.UNKNOWN) String className) {
ClassAnnotation classAnnotation = new ClassAnnotation(ClassName.toDottedClassName(className));
add(classAnnotation);
return this;
}
/**
* Add a class annotation for the classNode.
*
* @param classNode
* the ASM visitor
* @return this object
*/
public BugInstance addClass(ClassNode classNode) {
String dottedClassName = ClassName.toDottedClassName(classNode.name);
ClassAnnotation classAnnotation = new ClassAnnotation(dottedClassName);
add(classAnnotation);
return this;
}
/**
* Add a class annotation. If this is the first class annotation added, it
* becomes the primary class annotation.
*
* @param classDescriptor
* the class to add
* @return this object
*/
public BugInstance addClass(ClassDescriptor classDescriptor) {
add(ClassAnnotation.fromClassDescriptor(classDescriptor));
return this;
}
/**
* Add a class annotation. If this is the first class annotation added, it
* becomes the primary class annotation.
*
* @param jclass
* the JavaClass object for the class
* @return this object
*/
public BugInstance addClass(JavaClass jclass) {
addClass(jclass.getClassName());
return this;
}
/**
* Add a class annotation for the class that the visitor is currently
* visiting.
*
* @param visitor
* the BetterVisitor
* @return this object
*/
public BugInstance addClass(PreorderVisitor visitor) {
String className = visitor.getDottedClassName();
addClass(className);
return this;
}
/**
* Add a class annotation for the superclass of the class the visitor is
* currently visiting.
*
* @param visitor
* the BetterVisitor
* @return this object
*/
public BugInstance addSuperclass(PreorderVisitor visitor) {
String className = ClassName.toDottedClassName(visitor.getSuperclassName());
addClass(className);
return this;
}
public BugInstance addType(String typeDescriptor) {
TypeAnnotation typeAnnotation = new TypeAnnotation(typeDescriptor);
add(typeAnnotation);
return this;
}
public BugInstance addType(Type type) {
TypeAnnotation typeAnnotation = new TypeAnnotation(type);
add(typeAnnotation);
return this;
}
public BugInstance addFoundAndExpectedType(Type foundType, Type expectedType) {
add(new TypeAnnotation(foundType, TypeAnnotation.FOUND_ROLE));
add(new TypeAnnotation(expectedType, TypeAnnotation.EXPECTED_ROLE));
return this;
}
public BugInstance addFoundAndExpectedType(String foundType, String expectedType) {
add(new TypeAnnotation(foundType, TypeAnnotation.FOUND_ROLE));
add(new TypeAnnotation(expectedType, TypeAnnotation.EXPECTED_ROLE));
return this;
}
public BugInstance addEqualsMethodUsed(ClassDescriptor expectedClass) {
try {
Set<XMethod> targets = Hierarchy2.resolveVirtualMethodCallTargets(expectedClass, "equals", "(Ljava/lang/Object;)Z",
false, false);
addEqualsMethodUsed(targets);
} catch (ClassNotFoundException e) {
AnalysisContext.reportMissingClass(e);
}
return this;
}
public BugInstance addEqualsMethodUsed(@CheckForNull Collection<XMethod> equalsMethods) {
if (equalsMethods == null)
return this;
if (equalsMethods.size() < 5) {
for (XMethod m : equalsMethods) {
addMethod(m).describe(MethodAnnotation.METHOD_EQUALS_USED);
}
} else {
addMethod(equalsMethods.iterator().next()).describe(MethodAnnotation.METHOD_EQUALS_USED);
}
return this;
}
public BugInstance addTypeOfNamedClass(@DottedClassName String typeName) {
TypeAnnotation typeAnnotation = new TypeAnnotation("L" + typeName.replace('.', '/') + ";");
add(typeAnnotation);
return this;
}
public BugInstance addType(ClassDescriptor c) {
TypeAnnotation typeAnnotation = new TypeAnnotation(c.getSignature());
add(typeAnnotation);
return this;
}
/**
* Add a field annotation.
*
* @param className
* name of the class containing the field
* @param fieldName
* the name of the field
* @param fieldSig
* type signature of the field
* @param isStatic
* whether or not the field is static
* @return this object
*/
public BugInstance addField(String className, String fieldName, String fieldSig, boolean isStatic) {
addField(new FieldAnnotation(className, fieldName, fieldSig, isStatic));
return this;
}
/**
* Add a field annotation.
*
* @param className
* name of the class containing the field
* @param fieldName
* the name of the field
* @param fieldSig
* type signature of the field
* @param accessFlags
* access flags for the field
* @return this object
*/
public BugInstance addField(String className, String fieldName, String fieldSig, int accessFlags) {
addField(new FieldAnnotation(className, fieldName, fieldSig, accessFlags));
return this;
}
public BugInstance addField(PreorderVisitor visitor) {
FieldAnnotation fieldAnnotation = FieldAnnotation.fromVisitedField(visitor);
return addField(fieldAnnotation);
}
/**
* Add a field annotation
*
* @param fieldAnnotation
* the field annotation
* @return this object
*/
public BugInstance addField(FieldAnnotation fieldAnnotation) {
add(fieldAnnotation);
return this;
}
/**
* Add a field annotation for a FieldVariable matched in a ByteCodePattern.
*
* @param field
* the FieldVariable
* @return this object
*/
public BugInstance addField(FieldVariable field) {
return addField(field.getClassName(), field.getFieldName(), field.getFieldSig(), field.isStatic());
}
/**
* Add a field annotation for an XField.
*
* @param xfield
* the XField
* @return this object
*/
public BugInstance addOptionalField(@CheckForNull XField xfield) {
if (xfield == null)
return this;
return addField(xfield.getClassName(), xfield.getName(), xfield.getSignature(), xfield.isStatic());
}
/**
* Add a field annotation for an XField.
*
* @param xfield
* the XField
* @return this object
*/
public BugInstance addField(XField xfield) {
return addField(xfield.getClassName(), xfield.getName(), xfield.getSignature(), xfield.isStatic());
}
/**
* Add a field annotation for a FieldDescriptor.
*
* @param fieldDescriptor
* the FieldDescriptor
* @return this object
*/
public BugInstance addField(FieldDescriptor fieldDescriptor) {
FieldAnnotation fieldAnnotation = FieldAnnotation.fromFieldDescriptor(fieldDescriptor);
add(fieldAnnotation);
return this;
}
/**
* Add a field annotation for the field which has just been accessed by the
* method currently being visited by given visitor. Assumes that a
* getfield/putfield or getstatic/putstatic has just been seen.
*
* @param visitor
* the DismantleBytecode object
* @return this object
*/
public BugInstance addReferencedField(DismantleBytecode visitor) {
FieldAnnotation f = FieldAnnotation.fromReferencedField(visitor);
addField(f);
return this;
}
/**
* Add a field annotation for the field referenced by the FieldAnnotation
* parameter
*/
public BugInstance addReferencedField(FieldAnnotation fa) {
addField(fa);
return this;
}
/**
* Add a field annotation for the field which is being visited by given
* visitor.
*
* @param visitor
* the visitor
* @return this object
*/
public BugInstance addVisitedField(PreorderVisitor visitor) {
FieldAnnotation f = FieldAnnotation.fromVisitedField(visitor);
addField(f);
return this;
}
/**
* Local variable adders
*/
public BugInstance addOptionalLocalVariable(DismantleBytecode dbc, OpcodeStack.Item item) {
int register = item.getRegisterNumber();
if (register >= 0)
this.add(LocalVariableAnnotation.getLocalVariableAnnotation(dbc.getMethod(), register, dbc.getPC() - 1, dbc.getPC()));
return this;
}
/**
* Add a method annotation. If this is the first method annotation added, it
* becomes the primary method annotation.
*
* @param className
* name of the class containing the method
* @param methodName
* name of the method
* @param methodSig
* type signature of the method
* @param isStatic
* true if the method is static, false otherwise
* @return this object
*/
public BugInstance addMethod(String className, String methodName, String methodSig, boolean isStatic) {
addMethod(MethodAnnotation.fromForeignMethod(className, methodName, methodSig, isStatic));
return this;
}
/**
* Add a method annotation. If this is the first method annotation added, it
* becomes the primary method annotation.
*
* @param className
* name of the class containing the method
* @param methodName
* name of the method
* @param methodSig
* type signature of the method
* @param accessFlags
* accessFlags for the method
* @return this object
*/
public BugInstance addMethod(@SlashedClassName String className, String methodName, String methodSig, int accessFlags) {
addMethod(MethodAnnotation.fromForeignMethod(className, methodName, methodSig, accessFlags));
return this;
}
/**
* Add a method annotation. If this is the first method annotation added, it
* becomes the primary method annotation. If the method has source line
* information, then a SourceLineAnnotation is added to the method.
*
* @param methodGen
* the MethodGen object for the method
* @param sourceFile
* source file method is defined in
* @return this object
*/
public BugInstance addMethod(MethodGen methodGen, String sourceFile) {
String className = methodGen.getClassName();
MethodAnnotation methodAnnotation = new MethodAnnotation(className, methodGen.getName(), methodGen.getSignature(),
methodGen.isStatic());
addMethod(methodAnnotation);
addSourceLinesForMethod(methodAnnotation, SourceLineAnnotation.fromVisitedMethod(methodGen, sourceFile));
return this;
}
/**
* Add a method annotation. If this is the first method annotation added, it
* becomes the primary method annotation. If the method has source line
* information, then a SourceLineAnnotation is added to the method.
*
* @param javaClass
* the class the method is defined in
* @param method
* the method
* @return this object
*/
public BugInstance addMethod(JavaClass javaClass, Method method) {
MethodAnnotation methodAnnotation = new MethodAnnotation(javaClass.getClassName(), method.getName(),
method.getSignature(), method.isStatic());
SourceLineAnnotation methodSourceLines = SourceLineAnnotation.forEntireMethod(javaClass, method);
methodAnnotation.setSourceLines(methodSourceLines);
addMethod(methodAnnotation);
return this;
}
/**
* Add a method annotation. If this is the first method annotation added, it
* becomes the primary method annotation. If the method has source line
* information, then a SourceLineAnnotation is added to the method.
*
* @param classAndMethod
* JavaClassAndMethod identifying the method to add
* @return this object
*/
public BugInstance addMethod(JavaClassAndMethod classAndMethod) {
return addMethod(classAndMethod.getJavaClass(), classAndMethod.getMethod());
}
/**
* Add a method annotation for the method which the given visitor is
* currently visiting. If the method has source line information, then a
* SourceLineAnnotation is added to the method.
*
* @param visitor
* the BetterVisitor
* @return this object
*/
public BugInstance addMethod(PreorderVisitor visitor) {
MethodAnnotation methodAnnotation = MethodAnnotation.fromVisitedMethod(visitor);
addMethod(methodAnnotation);
addSourceLinesForMethod(methodAnnotation, SourceLineAnnotation.fromVisitedMethod(visitor));
return this;
}
/**
* Add a method annotation for the method which has been called by the
* method currently being visited by given visitor. Assumes that the visitor
* has just looked at an invoke instruction of some kind.
*
* @param visitor
* the DismantleBytecode object
* @return this object
*/
public BugInstance addCalledMethod(DismantleBytecode visitor) {
return addMethod(MethodAnnotation.fromCalledMethod(visitor)).describe(MethodAnnotation.METHOD_CALLED);
}
public BugInstance addCalledMethod(XMethod m) {
return addMethod(m).describe(MethodAnnotation.METHOD_CALLED);
}
/**
* Add a method annotation.
*
* @param className
* name of class containing called method
* @param methodName
* name of called method
* @param methodSig
* signature of called method
* @param isStatic
* true if called method is static, false if not
* @return this object
*/
public BugInstance addCalledMethod(String className, String methodName, String methodSig, boolean isStatic) {
return addMethod(MethodAnnotation.fromCalledMethod(className, methodName, methodSig, isStatic)).describe(
MethodAnnotation.METHOD_CALLED);
}
/**
* Add a method annotation for the method which is called by given
* instruction.
*
* @param cpg
* the constant pool for the method containing the call
* @param inv
* the InvokeInstruction
* @return this object
*/
public BugInstance addCalledMethod(ConstantPoolGen cpg, InvokeInstruction inv) {
String className = inv.getClassName(cpg);
String methodName = inv.getMethodName(cpg);
String methodSig = inv.getSignature(cpg);
addMethod(className, methodName, methodSig, inv.getOpcode() == Constants.INVOKESTATIC);
describe(MethodAnnotation.METHOD_CALLED);
return this;
}
/**
* Add a method annotation for the method which is called by given
* instruction.
*
* @param methodGen
* the method containing the call
* @param inv
* the InvokeInstruction
* @return this object
*/
public BugInstance addCalledMethod(MethodGen methodGen, InvokeInstruction inv) {
ConstantPoolGen cpg = methodGen.getConstantPool();
return addCalledMethod(cpg, inv);
}
/**
* Add a MethodAnnotation from an XMethod.
*
* @param xmethod
* the XMethod
* @return this object
*/
public BugInstance addMethod(XMethod xmethod) {
addMethod(MethodAnnotation.fromXMethod(xmethod));
return this;
}
/**
* Add a method annotation. If this is the first method annotation added, it
* becomes the primary method annotation.
*
* @param methodAnnotation
* the method annotation
* @return this object
*/
public BugInstance addMethod(MethodAnnotation methodAnnotation) {
add(methodAnnotation);
return this;
}
/**
* Add an integer annotation.
*
* @param value
* the integer value
* @return this object
*/
public BugInstance addInt(int value) {
add(new IntAnnotation(value));
return this;
}
/*
* Add an annotation about a parameter
*
* @param index parameter index, starting from 0
*
* @param role the role used to describe the parameter
*/
public BugInstance addParameterAnnotation(int index, String role) {
return addInt(index + 1).describe(role);
}
/**
* Add a String annotation.
*
* @param value
* the String value
* @return this object
*/
public BugInstance addString(String value) {
add(StringAnnotation.fromRawString(value));
return this;
}
/**
* Add a String annotation.
*
* @param c
* the char value
* @return this object
*/
public BugInstance addString(char c) {
add(StringAnnotation.fromRawString(Character.toString(c)));
return this;
}
/**
* Add a source line annotation.
*
* @param sourceLine
* the source line annotation
* @return this object
*/
public BugInstance addSourceLine(SourceLineAnnotation sourceLine) {
add(sourceLine);
return this;
}
/**
* Add a source line annotation for instruction whose PC is given in the
* method that the given visitor is currently visiting. Note that if the
* method does not have line number information, then no source line
* annotation will be added.
*
* @param visitor
* a BytecodeScanningDetector that is currently visiting the
* method
* @param pc
* bytecode offset of the instruction
* @return this object
*/
public BugInstance addSourceLine(BytecodeScanningDetector visitor, int pc) {
SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstruction(visitor.getClassContext(),
visitor, pc);
if (sourceLineAnnotation != null)
add(sourceLineAnnotation);
return this;
}
/**
* Add a source line annotation for instruction whose PC is given in the
* method that the given visitor is currently visiting. Note that if the
* method does not have line number information, then no source line
* annotation will be added.
*
* @param classContext
* the ClassContext
* @param visitor
* a PreorderVisitor that is currently visiting the method
* @param pc
* bytecode offset of the instruction
* @return this object
*/
public BugInstance addSourceLine(ClassContext classContext, PreorderVisitor visitor, int pc) {
SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstruction(classContext, visitor, pc);
if (sourceLineAnnotation != null)
add(sourceLineAnnotation);
return this;
}
/**
* Add a source line annotation for the given instruction in the given
* method. Note that if the method does not have line number information,
* then no source line annotation will be added.
*
* @param classContext
* the ClassContext
* @param methodGen
* the method being visited
* @param sourceFile
* source file the method is defined in
* @param handle
* the InstructionHandle containing the visited instruction
* @return this object
*/
public BugInstance addSourceLine(ClassContext classContext, MethodGen methodGen, String sourceFile,
@NonNull InstructionHandle handle) {
SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstruction(classContext, methodGen,
sourceFile, handle);
if (sourceLineAnnotation != null)
add(sourceLineAnnotation);
return this;
}
/**
* Add a source line annotation describing a range of instructions.
*
* @param classContext
* the ClassContext
* @param methodGen
* the method
* @param sourceFile
* source file the method is defined in
* @param start
* the start instruction in the range
* @param end
* the end instruction in the range (inclusive)
* @return this object
*/
public BugInstance addSourceLine(ClassContext classContext, MethodGen methodGen, String sourceFile, InstructionHandle start,
InstructionHandle end) {
// Make sure start and end are really in the right order.
if (start.getPosition() > end.getPosition()) {
InstructionHandle tmp = start;
start = end;
end = tmp;
}
SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstructionRange(classContext, methodGen,
sourceFile, start, end);
if (sourceLineAnnotation != null)
add(sourceLineAnnotation);
return this;
}
/**
* Add source line annotation for given Location in a method.
*
* @param classContext
* the ClassContext
* @param method
* the Method
* @param location
* the Location in the method
* @return this BugInstance
*/
public BugInstance addSourceLine(ClassContext classContext, Method method, Location location) {
return addSourceLine(classContext, method, location.getHandle());
}
/**
* Add source line annotation for given Location in a method.
*
* @param methodDescriptor
* the method
* @param location
* the Location in the method
* @return this BugInstance
*/
public BugInstance addSourceLine(MethodDescriptor methodDescriptor, Location location) {
try {
IAnalysisCache analysisCache = Global.getAnalysisCache();
ClassContext classContext = analysisCache.getClassAnalysis(ClassContext.class, methodDescriptor.getClassDescriptor());
Method method = analysisCache.getMethodAnalysis(Method.class, methodDescriptor);
return addSourceLine(classContext, method, location);
} catch (CheckedAnalysisException e) {
return addSourceLine(SourceLineAnnotation.createReallyUnknown(methodDescriptor.getClassDescriptor()
.toDottedClassName()));
}
}
/**
* Add source line annotation for given Location in a method.
*
* @param classContext
* the ClassContext
* @param method
* the Method
* @param handle
* InstructionHandle of an instruction in the method
* @return this BugInstance
*/
public BugInstance addSourceLine(ClassContext classContext, Method method, InstructionHandle handle) {
SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstruction(classContext, method,
handle.getPosition());
if (sourceLineAnnotation != null)
add(sourceLineAnnotation);
return this;
}
/**
* Add a source line annotation describing the source line numbers for a
* range of instructions in the method being visited by the given visitor.
* Note that if the method does not have line number information, then no
* source line annotation will be added.
*
* @param visitor
* a BetterVisitor which is visiting the method
* @param startPC
* the bytecode offset of the start instruction in the range
* @param endPC
* the bytecode offset of the end instruction in the range
* @return this object
*/
public BugInstance addSourceLineRange(BytecodeScanningDetector visitor, int startPC, int endPC) {
SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstructionRange(visitor.getClassContext(),
visitor, startPC, endPC);
if (sourceLineAnnotation != null)
add(sourceLineAnnotation);
return this;
}
/**
* Add a source line annotation describing the source line numbers for a
* range of instructions in the method being visited by the given visitor.
* Note that if the method does not have line number information, then no
* source line annotation will be added.
*
* @param classContext
* the ClassContext
* @param visitor
* a BetterVisitor which is visiting the method
* @param startPC
* the bytecode offset of the start instruction in the range
* @param endPC
* the bytecode offset of the end instruction in the range
* @return this object
*/
public BugInstance addSourceLineRange(ClassContext classContext, PreorderVisitor visitor, int startPC, int endPC) {
SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstructionRange(classContext, visitor,
startPC, endPC);
if (sourceLineAnnotation != null)
add(sourceLineAnnotation);
return this;
}
/**
* Add a source line annotation for instruction currently being visited by
* given visitor. Note that if the method does not have line number
* information, then no source line annotation will be added.
*
* @param visitor
* a BytecodeScanningDetector visitor that is currently visiting
* the instruction
* @return this object
*/
public BugInstance addSourceLine(BytecodeScanningDetector visitor) {
SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstruction(visitor);
if (sourceLineAnnotation != null)
add(sourceLineAnnotation);
return this;
}
/**
* Add a non-specific source line annotation. This will result in the entire
* source file being displayed.
*
* @param className
* the class name
* @param sourceFile
* the source file name
* @return this object
*/
public BugInstance addUnknownSourceLine(String className, String sourceFile) {
SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.createUnknown(className, sourceFile);
if (sourceLineAnnotation != null)
add(sourceLineAnnotation);
return this;
}
/**
* Format a string describing this bug instance.
*
* @return the description
*/
public String getMessageWithoutPrefix() {
BugPattern bugPattern = getBugPattern();
String pattern, shortPattern;
pattern = getLongDescription();
shortPattern = bugPattern.getShortDescription();
try {
FindBugsMessageFormat format = new FindBugsMessageFormat(pattern);
return format.format(annotationList.toArray(new BugAnnotation[annotationList.size()]), getPrimaryClass());
} catch (RuntimeException e) {
AnalysisContext.logError("Error generating bug msg ", e);
return shortPattern + " [Error generating customized description]";
}
}
String getLongDescription() {
return getBugPattern().getLongDescription().replaceAll("BUG_PATTERN", type);
}
public String getAbridgedMessage() {
BugPattern bugPattern = getBugPattern();
String pattern, shortPattern;
if (bugPattern == null)
shortPattern = pattern = "Error2: missing bug pattern for key " + type;
else {
pattern = getLongDescription().replaceAll(" in \\{1\\}", "");
shortPattern = bugPattern.getShortDescription();
}
try {
FindBugsMessageFormat format = new FindBugsMessageFormat(pattern);
return format.format(annotationList.toArray(new BugAnnotation[annotationList.size()]), getPrimaryClass(), true);
} catch (RuntimeException e) {
AnalysisContext.logError("Error generating bug msg ", e);
return shortPattern + " [Error3 generating customized description]";
}
}
/**
* Format a string describing this bug instance.
*
* @return the description
*/
public String getMessage() {
BugPattern bugPattern = getBugPattern();
String pattern = bugPattern.getAbbrev() + ": " + getLongDescription();
FindBugsMessageFormat format = new FindBugsMessageFormat(pattern);
try {
return format.format(annotationList.toArray(new BugAnnotation[annotationList.size()]), getPrimaryClass());
} catch (RuntimeException e) {
AnalysisContext.logError("Error generating bug msg ", e);
return bugPattern.getShortDescription() + " [Error generating customized description]";
}
}
/**
* Format a string describing this bug pattern, with the priority and type
* at the beginning. e.g.
* "(High Priority Correctness) Guaranteed null pointer dereference..."
*/
public String getMessageWithPriorityType() {
return "(" + this.getPriorityTypeString() + ") " + this.getMessage();
}
public String getMessageWithPriorityTypeAbbreviation() {
return this.getPriorityTypeAbbreviation() + " " + this.getMessage();
}
/**
* Add a description to the most recently added bug annotation.
*
* @param description
* the description to add
* @return this object
*/
public BugInstance describe(String description) {
annotationList.get(annotationList.size() - 1).setDescription(description);
return this;
}
/**
* Convert to String. This method returns the "short" message describing the
* bug, as opposed to the longer format returned by getMessage(). The short
* format is appropriate for the tree view in a GUI, where the annotations
* are listed separately as part of the overall bug instance.
*/
@Override
public String toString() {
return I18N.instance().getShortMessage(type);
}
public void writeXML(XMLOutput xmlOutput) throws IOException {
writeXML(xmlOutput, null, false);
}
public void writeXML(XMLOutput xmlOutput, BugCollection bugCollection, boolean addMessages) throws IOException {
XMLAttributeList attributeList = new XMLAttributeList().addAttribute("type", type).addAttribute("priority",
String.valueOf(priority));
BugPattern pattern = getBugPattern();
if (pattern != null) {
// The bug abbreviation and pattern category are
// emitted into the XML for informational purposes only.
// (The information is redundant, but might be useful
// for processing tools that want to make sense of
// bug instances without looking at the plugin descriptor.)
attributeList.addAttribute("abbrev", pattern.getAbbrev());
attributeList.addAttribute("category", pattern.getCategory());
}
if (addMessages) {
// Add a uid attribute, if we have a unique id.
attributeList.addAttribute("instanceHash", getInstanceHash());
attributeList.addAttribute("instanceOccurrenceNum", Integer.toString(getInstanceOccurrenceNum()));
attributeList.addAttribute("instanceOccurrenceMax", Integer.toString(getInstanceOccurrenceMax()));
attributeList.addAttribute("rank", Integer.toString(getBugRank()));
} else if (oldInstanceHash != null && !isInstanceHashConsistent()) {
attributeList.addAttribute("oldInstanceHash", oldInstanceHash);
}
if (firstVersion > 0)
attributeList.addAttribute("first", Long.toString(firstVersion));
if (lastVersion >= 0)
attributeList.addAttribute("last", Long.toString(lastVersion));
if (introducedByChangeOfExistingClass)
attributeList.addAttribute("introducedByChange", "true");
if (removedByChangeOfPersistingClass)
attributeList.addAttribute("removedByChange", "true");
if (bugCollection != null) {
Cloud cloud = bugCollection.getCloudLazily();
if (cloud != null && cloud.communicationInitiated()) {
long firstSeen = cloud.getFirstSeen(this);
attributeList.addAttribute("firstSeen", firstSeenXMLFormat().format(firstSeen));
int reviews = cloud.getNumberReviewers(this);
UserDesignation consensus = cloud.getConsensusDesignation(this);
if (!cloud.isInCloud(this)) {
attributeList.addAttribute("isInCloud", "false");
}
if (reviews > 0) {
attributeList.addAttribute("reviews", Integer.toString(reviews));
if (consensus != UserDesignation.UNCLASSIFIED)
attributeList.addAttribute("consensus", consensus.toString());
}
if (addMessages) {
int ageInDays = ageInDays(bugCollection, firstSeen);
attributeList.addAttribute("ageInDays", Integer.toString(ageInDays));
if (reviews > 0 && consensus != UserDesignation.UNCLASSIFIED) {
if (consensus.score() < 0)
attributeList.addAttribute("notAProblem", "true");
if (consensus.score() > 0)
attributeList.addAttribute("shouldFix", "true");
}
}
} else if (hasXmlProps()) {
XmlProps props = getXmlProps();
if (props.firstSeen != null)
attributeList.addOptionalAttribute("firstSeen", firstSeenXMLFormat().format(props.firstSeen));
if (props.reviewCount > 0) {
if (props.consensus != null)
attributeList.addOptionalAttribute("consensus", props.consensus);
attributeList.addAttribute("reviews", Integer.toString(props.reviewCount));
}
if (!props.isInCloud())
attributeList.addAttribute("isInCloud", "false");
if (addMessages) {
UserDesignation consesus = UserDesignation.valueOf(props.consensus);
if (consesus.shouldFix())
attributeList.addAttribute("shouldFix", "true");
else if (consesus.notAProblem())
attributeList.addAttribute("notAProblem", "true");
if (props.firstSeen != null) {
int ageInDays = ageInDays(bugCollection, props.firstSeen.getTime());
attributeList.addAttribute("ageInDays", Integer.toString(ageInDays));
}
}
}
}
xmlOutput.openTag(ELEMENT_NAME, attributeList);
// write out the user's designation & comment
if (userDesignation != null) {
userDesignation.writeXML(xmlOutput);
}
if (addMessages) {
BugPattern bugPattern = getBugPattern();
xmlOutput.openTag("ShortMessage");
xmlOutput.writeText(bugPattern != null ? bugPattern.getShortDescription() : this.toString());
xmlOutput.closeTag("ShortMessage");
xmlOutput.openTag("LongMessage");
if (FindBugsDisplayFeatures.isAbridgedMessages())
xmlOutput.writeText(this.getAbridgedMessage());
else
xmlOutput.writeText(this.getMessageWithoutPrefix());
xmlOutput.closeTag("LongMessage");
}
Map<BugAnnotation, Void> primaryAnnotations;
if (addMessages) {
primaryAnnotations = new IdentityHashMap<BugAnnotation, Void>();
primaryAnnotations.put(getPrimarySourceLineAnnotation(), null);
primaryAnnotations.put(getPrimaryClass(), null);
primaryAnnotations.put(getPrimaryField(), null);
primaryAnnotations.put(getPrimaryMethod(), null);
} else {
primaryAnnotations = Collections.<BugAnnotation, Void> emptyMap();
}
boolean foundSourceAnnotation = false;
for (BugAnnotation annotation : annotationList) {
if (annotation instanceof SourceLineAnnotation)
foundSourceAnnotation = true;
annotation.writeXML(xmlOutput, addMessages, primaryAnnotations.containsKey(annotation));
}
if (!foundSourceAnnotation && addMessages) {
SourceLineAnnotation synth = getPrimarySourceLineAnnotation();
if (synth != null) {
synth.setSynthetic(true);
synth.writeXML(xmlOutput, addMessages, false);
}
}
if (propertyListHead != null) {
BugProperty prop = propertyListHead;
while (prop != null) {
prop.writeXML(xmlOutput);
prop = prop.getNext();
}
}
xmlOutput.closeTag(ELEMENT_NAME);
}
/**
* @param bugCollection
* @param firstSeen
* @return
*/
private int ageInDays(BugCollection bugCollection, long firstSeen) {
long age = bugCollection.getAnalysisTimestamp() - firstSeen;
if (age < 0)
age = 0;
int ageInDays = (int) (age / 1000 / 3600 / 24);
return ageInDays;
}
private static final String ELEMENT_NAME = "BugInstance";
public BugInstance addOptionalAnnotation(@CheckForNull BugAnnotation annotation) {
if (annotation == null)
return this;
return add(annotation);
}
public BugInstance addOptionalAnnotation(@CheckForNull BugAnnotation annotation, String role) {
if (annotation == null)
return this;
return add(annotation).describe(role);
}
public BugInstance add(@Nonnull BugAnnotation annotation) {
if (annotation == null)
throw new IllegalArgumentException("Missing BugAnnotation!");
// Add to list
annotationList.add(annotation);
// This object is being modified, so the cached hashcode
// must be invalidated
cachedHashCode = INVALID_HASH_CODE;
return this;
}
public BugInstance addSomeSourceForTopTwoStackValues(ClassContext classContext, Method method, Location location) {
int pc = location.getHandle().getPosition();
OpcodeStack stack = OpcodeStackScanner.getStackAt(classContext.getJavaClass(), method, pc);
BugAnnotation a1 = getSomeSource(classContext, method, location, stack, 1);
BugAnnotation a0 = getSomeSource(classContext, method, location, stack, 0);
addOptionalUniqueAnnotations(a0, a1);
return this;
}
public BugInstance addSourceForTopStackValue(ClassContext classContext, Method method, Location location) {
BugAnnotation b = getSourceForTopStackValue(classContext, method, location);
return this.addOptionalAnnotation(b);
}
public static @CheckForNull
BugAnnotation getSourceForTopStackValue(ClassContext classContext, Method method, Location location) {
return getSourceForStackValue(classContext, method, location, 0);
}
public static @CheckForNull
BugAnnotation getSourceForStackValue(ClassContext classContext, Method method, Location location, int depth) {
int pc = location.getHandle().getPosition();
OpcodeStack stack = OpcodeStackScanner.getStackAt(classContext.getJavaClass(), method, pc);
BugAnnotation a0 = getSomeSource(classContext, method, location, stack, depth);
return a0;
}
public static @CheckForNull
BugAnnotation getSomeSource(ClassContext classContext, Method method, Location location, OpcodeStack stack, int stackPos) {
int pc = location.getHandle().getPosition();
try {
BugAnnotation result = ValueNumberSourceInfo.getFromValueNumber(classContext, method, location, stackPos);
if (result != null)
return result;
} catch (DataflowAnalysisException e) {
AnalysisContext.logError("Couldn't find value source", e);
} catch (CFGBuilderException e) {
AnalysisContext.logError("Couldn't find value source", e);
}
return getValueSource(stack.getStackItem(stackPos), method, pc);
}
public static @javax.annotation.CheckForNull
BugAnnotation getValueSource(OpcodeStack.Item item, Method method, int pc) {
LocalVariableAnnotation lv = LocalVariableAnnotation.getLocalVariableAnnotation(method, item, pc);
if (lv != null && lv.isNamed())
return lv;
BugAnnotation a = getFieldOrMethodValueSource(item);
if (a != null)
return a;
Object c = item.getConstant();
if (c instanceof String) {
a = new StringAnnotation((String) c);
a.setDescription(StringAnnotation.STRING_CONSTANT_ROLE);
return a;
}
if (c instanceof Integer) {
a = new IntAnnotation((Integer) c);
a.setDescription(IntAnnotation.INT_VALUE);
return a;
}
return null;
}
public BugInstance addValueSource(@CheckForNull OpcodeStack.Item item, DismantleBytecode dbc) {
if (item != null)
addValueSource(item, dbc.getMethod(), dbc.getPC());
return this;
}
public BugInstance addValueSource(OpcodeStack.Item item, Method method, int pc) {
addOptionalAnnotation(getValueSource(item, method, pc));
return this;
}
/**
* @param item
*/
public BugInstance addFieldOrMethodValueSource(OpcodeStack.Item item) {
addOptionalAnnotation(getFieldOrMethodValueSource(item));
return this;
}
public BugInstance addOptionalUniqueAnnotations(BugAnnotation... annotations) {
HashSet<BugAnnotation> added = new HashSet<BugAnnotation>();
for (BugAnnotation a : annotations)
if (a != null && added.add(a))
add(a);
return this;
}
public BugInstance addOptionalUniqueAnnotationsWithFallback(BugAnnotation fallback, BugAnnotation... annotations) {
HashSet<BugAnnotation> added = new HashSet<BugAnnotation>();
for (BugAnnotation a : annotations)
if (a != null && added.add(a))
add(a);
if (added.isEmpty())
add(fallback);
return this;
}
public static @CheckForNull
BugAnnotation getFieldOrMethodValueSource(@CheckForNull OpcodeStack.Item item) {
if (item == null)
return null;
XField xField = item.getXField();
if (xField != null) {
FieldAnnotation a = FieldAnnotation.fromXField(xField);
a.setDescription(FieldAnnotation.LOADED_FROM_ROLE);
return a;
}
XMethod xMethod = item.getReturnValueOf();
if (xMethod != null) {
MethodAnnotation a = MethodAnnotation.fromXMethod(xMethod);
a.setDescription(MethodAnnotation.METHOD_RETURN_VALUE_OF);
return a;
}
return null;
}
private void addSourceLinesForMethod(MethodAnnotation methodAnnotation, SourceLineAnnotation sourceLineAnnotation) {
if (sourceLineAnnotation != null) {
// Note: we don't add the source line annotation directly to
// the bug instance. Instead, we stash it in the MethodAnnotation.
// It is much more useful there, and it would just be distracting
// if it were displayed in the UI, since it would compete for
// attention
// with the actual bug location source line annotation (which is
// much
// more important and interesting).
methodAnnotation.setSourceLines(sourceLineAnnotation);
}
}
@Override
public int hashCode() {
if (cachedHashCode == INVALID_HASH_CODE) {
int hashcode = type.hashCode() + priority;
Iterator<BugAnnotation> i = annotationIterator();
while (i.hasNext())
hashcode += i.next().hashCode();
if (hashcode == INVALID_HASH_CODE)
hashcode = INVALID_HASH_CODE + 1;
cachedHashCode = hashcode;
}
return cachedHashCode;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof BugInstance))
return false;
BugInstance other = (BugInstance) o;
if (!type.equals(other.type) || priority != other.priority)
return false;
if (annotationList.size() != other.annotationList.size())
return false;
int numAnnotations = annotationList.size();
for (int i = 0; i < numAnnotations; ++i) {
BugAnnotation lhs = annotationList.get(i);
BugAnnotation rhs = other.annotationList.get(i);
if (!lhs.equals(rhs))
return false;
}
return true;
}
public int compareTo(BugInstance other) {
int cmp;
cmp = type.compareTo(other.type);
if (cmp != 0)
return cmp;
cmp = priority - other.priority;
if (cmp != 0)
return cmp;
// Compare BugAnnotations lexicographically
int pfxLen = Math.min(annotationList.size(), other.annotationList.size());
for (int i = 0; i < pfxLen; ++i) {
BugAnnotation lhs = annotationList.get(i);
BugAnnotation rhs = other.annotationList.get(i);
cmp = lhs.compareTo(rhs);
if (cmp != 0)
return cmp;
}
// All elements in prefix were the same,
// so use number of elements to decide
return annotationList.size() - other.annotationList.size();
}
/**
* @param firstVersion
* The firstVersion to set.
*/
public void setFirstVersion(long firstVersion) {
if (lastVersion >= 0 && firstVersion > lastVersion)
throw new IllegalArgumentException(firstVersion + ".." + lastVersion);
this.firstVersion = firstVersion;
}
public void clearHistory() {
setFirstVersion(0);
setLastVersion(-1);
setIntroducedByChangeOfExistingClass(false);
setRemovedByChangeOfPersistingClass(false);
}
/**
* @return Returns the firstVersion.
*/
public long getFirstVersion() {
return firstVersion;
}
public void setHistory(BugInstance from) {
long first = from.getFirstVersion();
long last = from.getLastVersion();
if (first > 0 && last >= 0 && first > last) {
throw new IllegalArgumentException("from has version range " + first + "..." + last + " in " + from.getBugPattern()
+ "\n" + from.getMessage());
}
setFirstVersion(first);
setLastVersion(last);
this.removedByChangeOfPersistingClass = from.removedByChangeOfPersistingClass;
this.introducedByChangeOfExistingClass = from.introducedByChangeOfExistingClass;
}
/**
* @param lastVersion
* The lastVersion to set.
*/
public void setLastVersion(long lastVersion) {
if (lastVersion >= 0 && firstVersion > lastVersion)
throw new IllegalArgumentException(firstVersion + ".." + lastVersion);
this.lastVersion = lastVersion;
}
/** Mark the bug instance is being alive (still present in the last version) */
public void setLive() {
this.lastVersion = -1;
}
/**
* @return Returns the lastVersion.
*/
public long getLastVersion() {
return lastVersion;
}
public boolean isDead() {
return lastVersion != -1;
}
/**
* @param introducedByChangeOfExistingClass
* The introducedByChangeOfExistingClass to set.
*/
public void setIntroducedByChangeOfExistingClass(boolean introducedByChangeOfExistingClass) {
this.introducedByChangeOfExistingClass = introducedByChangeOfExistingClass;
}
/**
* @return Returns the introducedByChangeOfExistingClass.
*/
public boolean isIntroducedByChangeOfExistingClass() {
return introducedByChangeOfExistingClass;
}
/**
* @param removedByChangeOfPersistingClass
* The removedByChangeOfPersistingClass to set.
*/
public void setRemovedByChangeOfPersistingClass(boolean removedByChangeOfPersistingClass) {
this.removedByChangeOfPersistingClass = removedByChangeOfPersistingClass;
}
/**
* @return Returns the removedByChangeOfPersistingClass.
*/
public boolean isRemovedByChangeOfPersistingClass() {
return removedByChangeOfPersistingClass;
}
/**
* @param instanceHash
* The instanceHash to set.
*/
public void setInstanceHash(String instanceHash) {
this.instanceHash = instanceHash;
}
/**
* @param oldInstanceHash
* The oldInstanceHash to set.
*/
public void setOldInstanceHash(String oldInstanceHash) {
this.oldInstanceHash = oldInstanceHash;
}
/**
* @return Returns the instanceHash.
*/
public String getInstanceHash() {
String hash = instanceHash;
if (hash != null)
return hash;
MessageDigest digest = Util.getMD5Digest();
String key = getInstanceKey();
byte[] data;
try {
data = digest.digest(key.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException(e);
}
hash = new BigInteger(1, data).toString(16);
instanceHash = hash;
return hash;
}
public boolean isInstanceHashConsistent() {
return oldInstanceHash == null || getInstanceHash().equals(oldInstanceHash);
}
/**
* @param instanceOccurrenceNum
* The instanceOccurrenceNum to set.
*/
public void setInstanceOccurrenceNum(int instanceOccurrenceNum) {
this.instanceOccurrenceNum = instanceOccurrenceNum;
}
/**
* @return Returns the instanceOccurrenceNum.
*/
public int getInstanceOccurrenceNum() {
return instanceOccurrenceNum;
}
/**
* @param instanceOccurrenceMax
* The instanceOccurrenceMax to set.
*/
public void setInstanceOccurrenceMax(int instanceOccurrenceMax) {
this.instanceOccurrenceMax = instanceOccurrenceMax;
}
/**
* @return Returns the instanceOccurrenceMax.
*/
public int getInstanceOccurrenceMax() {
return instanceOccurrenceMax;
}
public DetectorFactory getDetectorFactory() {
return detectorFactory;
}
private void optionalAdd(Collection<BugAnnotation> c, BugAnnotation a) {
if (a != null)
c.add(a);
}
public List<BugAnnotation> getAnnotationsForMessage(boolean showContext) {
ArrayList<BugAnnotation> result = new ArrayList<BugAnnotation>();
HashSet<BugAnnotation> primaryAnnotations = new HashSet<BugAnnotation>();
// This ensures the order of the primary annotations of the bug
FieldAnnotation primeField = getPrimaryField();
MethodAnnotation primeMethod = getPrimaryMethod();
ClassAnnotation primeClass = getPrimaryClass();
SourceLineAnnotation primarySourceLineAnnotation = getPrimarySourceLineAnnotation();
optionalAdd(primaryAnnotations, primarySourceLineAnnotation);
optionalAdd(primaryAnnotations, primeMethod);
optionalAdd(primaryAnnotations, primeField);
optionalAdd(primaryAnnotations, primeClass);
if (primarySourceLineAnnotation != null
&& (showContext || !primarySourceLineAnnotation.getDescription().equals(SourceLineAnnotation.DEFAULT_ROLE)))
result.add(primarySourceLineAnnotation);
if (primeMethod != null && (showContext || !primeMethod.getDescription().equals(MethodAnnotation.DEFAULT_ROLE)))
result.add(primeMethod);
optionalAdd(result, primeField);
String fieldClass = "";
String methodClass = "";
if (primeField != null)
fieldClass = primeField.getClassName();
if (primeMethod != null)
methodClass = primeMethod.getClassName();
if (showContext && (primaryAnnotations.size() < 2)
|| (!(primeClass.getClassName().equals(fieldClass) || primeClass.getClassName().equals(methodClass)))) {
optionalAdd(result, primeClass);
}
for (BugAnnotation b : getAnnotations()) {
if (primaryAnnotations.contains(b))
continue;
if (b instanceof LocalVariableAnnotation && !((LocalVariableAnnotation) b).isNamed())
continue;
if (b instanceof SourceLineAnnotation && ((SourceLineAnnotation) b).isUnknown())
continue;
result.add(b);
}
return result;
}
/**
* These are properties read from an analysis XML file. These properties
* should not take precedence over information from the Cloud - rather, this
* should be used when the cloud is unavailable, or when communicating with
* it is not desired for performance or complexity reasons.
*/
static public class XmlProps {
private Date firstSeen = null;
private int reviewCount = 0;
private boolean isInCloud = true;
private String consensus;
public @CheckForNull Date getFirstSeen() {
return firstSeen;
}
public int getReviewCount() {
return reviewCount;
}
public @CheckForNull String getConsensus() {
return consensus;
}
public boolean isInCloud() {
return isInCloud;
}
public void setFirstSeen(Date firstSeen) {
this.firstSeen = firstSeen;
}
public void setReviewCount(int reviewCount) {
this.reviewCount = reviewCount;
}
public void setConsensus(String consensus) {
this.consensus = consensus;
}
public void setIsInCloud(boolean inCloud) {
isInCloud = inCloud;
}
}
}
// vim:ts=4
|
package edu.umd.cs.findbugs;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import org.apache.bcel.Repository;
import org.apache.bcel.classfile.Code;
import org.apache.bcel.classfile.CodeException;
import org.apache.bcel.classfile.Constant;
import org.apache.bcel.classfile.ConstantClass;
import org.apache.bcel.classfile.ConstantDouble;
import org.apache.bcel.classfile.ConstantFloat;
import org.apache.bcel.classfile.ConstantInteger;
import org.apache.bcel.classfile.ConstantLong;
import org.apache.bcel.classfile.ConstantString;
import org.apache.bcel.classfile.ConstantUtf8;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.LocalVariable;
import org.apache.bcel.classfile.LocalVariableTable;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.BasicType;
import org.apache.bcel.generic.Type;
import edu.umd.cs.findbugs.ba.AnalysisContext;
import edu.umd.cs.findbugs.ba.AnalysisFeatures;
import edu.umd.cs.findbugs.ba.XFactory;
import edu.umd.cs.findbugs.ba.XField;
import edu.umd.cs.findbugs.visitclass.Constants2;
import edu.umd.cs.findbugs.visitclass.DismantleBytecode;
import edu.umd.cs.findbugs.visitclass.LVTHelper;
import edu.umd.cs.findbugs.visitclass.PreorderVisitor;
/**
* tracks the types and numbers of objects that are currently on the operand stack
* throughout the execution of method. To use, a detector should instantiate one for
* each method, and call <p>stack.sawOpcode(this,seen);</p> at the bottom of their sawOpcode method.
* at any point you can then inspect the stack and see what the types of objects are on
* the stack, including constant values if they were pushed. The types described are of
* course, only the static types.
* There are some outstanding opcodes that have yet to be implemented, I couldn't
* find any code that actually generated these, so i didn't put them in because
* I couldn't test them:
* <ul>
* <li>dup2_x2</li>
* <li>jsr_w</li>
* <li>wide</li>
* </ul>
*/
public class OpcodeStack implements Constants2
{
private static final boolean DEBUG
= SystemProperties.getBoolean("ocstack.debug");
private List<Item> stack;
private List<Item> lvValues;
private List<Integer> lastUpdate;
private int jumpTarget;
private Stack<List<Item>> jumpStack;
private boolean seenTransferOfControl = false;
private boolean useIterativeAnalysis
= AnalysisContext.currentAnalysisContext().getBoolProperty(AnalysisFeatures.INTERATIVE_OPCODE_STACK_ANALYSIS);
public static class Item
{
public static final int SIGNED_BYTE = 1;
public static final int RANDOM_INT = 2;
public static final int LOW_8_BITS_CLEAR = 3;
public static final int HASHCODE_INT = 4;
public static final int INTEGER_SUM = 5;
public static final int AVERAGE_COMPUTED_USING_DIVISION = 6;
public static final int FLOAT_MATH = 7;
public static final int RANDOM_INT_REMAINDER = 8;
public static final int HASHCODE_INT_REMAINDER = 9;
public static final Object UNKNOWN = null;
private int specialKind;
private String signature;
private Object constValue = UNKNOWN;
private FieldAnnotation field;
private XField xfield;
private boolean isNull = false;
private int registerNumber = -1;
private boolean isInitialParameter = false;
private boolean couldBeZero = false;
private Object userValue = null;
public int getSize() {
if (signature.equals("J") || signature.equals("D")) return 2;
return 1;
}
private static boolean equals(Object o1, Object o2) {
if (o1 == o2) return true;
if (o1 == null || o2 == null) return false;
return o1.equals(o2);
}
@Override
public int hashCode() {
int r = 42 + specialKind;
if (signature != null)
r+= signature.hashCode();
r *= 31;
if (constValue != null)
r+= constValue.hashCode();
r *= 31;
if (field != null)
r+= field.hashCode();
r *= 31;
if (isInitialParameter)
r += 17;
r += registerNumber;
return r;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Item)) return false;
Item that = (Item) o;
return equals(this.signature, that.signature)
&& equals(this.constValue, that.constValue)
&& equals(this.field, that.field)
&& this.isNull == that.isNull
&& this.specialKind == that.specialKind
&& this.registerNumber == that.registerNumber
&& this.isInitialParameter == that.isInitialParameter
&& this.couldBeZero == that.couldBeZero
&& this.userValue == that.userValue;
}
@Override
public String toString() {
StringBuffer buf = new StringBuffer("< ");
buf.append(signature);
switch(specialKind) {
case SIGNED_BYTE:
buf.append(", byte_array_load");
break;
case RANDOM_INT:
buf.append(", random_int");
break;
case LOW_8_BITS_CLEAR:
buf.append(", low8clear");
break;
case HASHCODE_INT:
buf.append(", hashcode_int");
break;
case INTEGER_SUM:
buf.append(", int_sum");
break;
case AVERAGE_COMPUTED_USING_DIVISION:
buf.append(", averageComputingUsingDivision");
break;
case FLOAT_MATH:
buf.append(", floatMath");
break;
case HASHCODE_INT_REMAINDER:
buf.append(", hashcode_int_rem");
break;
case RANDOM_INT_REMAINDER:
buf.append(", random_int_rem");
break;
}
if (constValue != UNKNOWN) {
buf.append(", ");
buf.append(constValue);
}
if (xfield!= UNKNOWN) {
buf.append(", ");
buf.append(xfield);
}
if (isInitialParameter) {
buf.append(", IP");
}
if (isNull) {
buf.append(", isNull");
}
if (registerNumber != -1) {
buf.append(", r");
buf.append(registerNumber);
}
if (couldBeZero) buf.append(", cbz");
buf.append(" >");
return buf.toString();
}
public static Item merge(Item i1, Item i2) {
if (i1 == null) return i2;
if (i2 == null) return i1;
if (i1.equals(i2)) return i1;
Item m = new Item();
m.isNull = false;
m.couldBeZero = i1.couldBeZero || i2.couldBeZero;
if (equals(i1.signature,i2.signature))
m.signature = i1.signature;
if (equals(i1.constValue,i2.constValue))
m.constValue = i1.constValue;
if (equals(i1.xfield,i2.xfield)) {
m.field = i1.field;
m.xfield = i1.xfield;
}
if (i1.isNull == i2.isNull)
m.isNull = i1.isNull;
if (i1.registerNumber == i2.registerNumber)
m.registerNumber = i1.registerNumber;
if (i1.specialKind == i2.specialKind)
m.specialKind = i1.specialKind;
else if (i1.specialKind == FLOAT_MATH || i2.specialKind == FLOAT_MATH)
m.specialKind = FLOAT_MATH;
if (DEBUG) System.out.println("Merge " + i1 + " and " + i2 + " gives " + m);
return m;
}
public Item(String signature, int constValue) {
this(signature, (Object)(Integer)constValue);
}
public Item(String signature) {
this(signature, UNKNOWN);
}
public Item(String signature, FieldAnnotation f, int reg) {
this.signature = signature;
field = f;
if (f != null)
xfield = XFactory.createXField(f);
registerNumber = reg;
}
public Item(Item it) {
this.signature = it.signature;
this.constValue = it.constValue;
this.field = it.field;
this.xfield = it.xfield;
this.isNull = it.isNull;
this.registerNumber = it.registerNumber;
this.couldBeZero = it.couldBeZero;
this.userValue = it.userValue;
this.isInitialParameter = it.isInitialParameter;
this.specialKind = it.specialKind;
}
public Item(Item it, int reg) {
this.signature = it.signature;
this.constValue = it.constValue;
this.field = it.field;
this.isNull = it.isNull;
this.registerNumber = reg;
this.couldBeZero = it.couldBeZero;
this.userValue = it.userValue;
this.isInitialParameter = it.isInitialParameter;
this.specialKind = it.specialKind;
}
public Item(String signature, FieldAnnotation f) {
this(signature, f, -1);
}
public Item(String signature, Object constantValue) {
this.signature = signature;
constValue = constantValue;
if (constantValue instanceof Integer) {
int value = (Integer) constantValue;
if (value != 0 && (value & 0xff) == 0)
specialKind = LOW_8_BITS_CLEAR;
if (value == 0) couldBeZero = true;
}
else if (constantValue instanceof Long) {
long value = (Long) constantValue;
if (value != 0 && (value & 0xff) == 0)
specialKind = LOW_8_BITS_CLEAR;
if (value == 0) couldBeZero = true;
}
}
public Item() {
signature = "Ljava/lang/Object;";
constValue = null;
isNull = true;
}
public JavaClass getJavaClass() throws ClassNotFoundException {
String baseSig;
if (isPrimitive())
return null;
if (isArray()) {
baseSig = getElementSignature();
} else {
baseSig = signature;
}
if (baseSig.length() == 0)
return null;
baseSig = baseSig.substring(1, baseSig.length() - 1);
baseSig = baseSig.replace('/', '.');
return Repository.lookupClass(baseSig);
}
public boolean isArray() {
return signature.startsWith("[");
}
public boolean isInitialParameter() {
return isInitialParameter;
}
public String getElementSignature() {
if (!isArray())
return signature;
else {
int pos = 0;
int len = signature.length();
while (pos < len) {
if (signature.charAt(pos) != '[')
break;
pos++;
}
return signature.substring(pos);
}
}
public boolean isPrimitive() {
return !signature.startsWith("L");
}
public int getRegisterNumber() {
return registerNumber;
}
public String getSignature() {
return signature;
}
public boolean isNull() {
return isNull;
}
public Object getConstant() {
return constValue;
}
public FieldAnnotation getField() {
return field;
}
public XField getXField() {
return xfield;
}
/**
* @param specialKind The specialKind to set.
*/
public void setSpecialKind(int specialKind) {
this.specialKind = specialKind;
}
/**
* @return Returns the specialKind.
*/
public int getSpecialKind() {
return specialKind;
}
/**
* attaches a detector specified value to this item
*
* @param value the custom value to set
*/
public void setUserValue(Object value) {
userValue = value;
}
public boolean couldBeZero() {
return couldBeZero;
}
public boolean mustBeZero() {
Object value = getConstant();
return value instanceof Number && ((Number)value).intValue() == 0;
}
/**
* gets the detector specified value for this item
*
* @return the custom value
*/
public Object getUserValue() {
return userValue;
}
public boolean valueCouldBeNegative() {
return (getSpecialKind() == Item.RANDOM_INT
|| getSpecialKind() == Item.SIGNED_BYTE
|| getSpecialKind() == Item.HASHCODE_INT
|| getSpecialKind() == Item.RANDOM_INT_REMAINDER || getSpecialKind() == Item.HASHCODE_INT_REMAINDER);
}
}
@Override
public String toString() {
return stack.toString() + "::" + lvValues.toString();
}
public OpcodeStack()
{
stack = new ArrayList<Item>();
lvValues = new ArrayList<Item>();
jumpStack = new Stack<List<Item>>();
lastUpdate = new ArrayList<Integer>();
}
boolean needToMerge = true;
boolean reachOnlyByBranch = false;
public void mergeJumps(DismantleBytecode dbc) {
if (!needToMerge) return;
needToMerge = false;
if (convertJumpToOneZeroState == 3 || convertJumpToZeroOneState == 3) {
pop();
Item top = new Item("I");
top.couldBeZero = true;
push(top);
convertJumpToOneZeroState = convertJumpToZeroOneState = 0;
}
List<Item> jumpEntry = jumpEntries.get(dbc.getPC());
if (jumpEntry != null) {
if (DEBUG) {
System.out.println("XXXXXXX " + reachOnlyByBranch);
System.out.println("merging lvValues at jump target " + dbc.getPC() + " -> " + Integer.toString(System.identityHashCode(jumpEntry),16) + " " + jumpEntry);
System.out.println(" current lvValues " + lvValues);
}
if (reachOnlyByBranch) lvValues = new ArrayList<Item>(jumpEntry);
else mergeLists(lvValues, jumpEntry, false);
if (DEBUG)
System.out.println(" merged lvValues " + lvValues);
}
else if (dbc.getPC() == jumpTarget) {
jumpTarget = -1;
if (!jumpStack.empty()) {
List<Item> stackToMerge = jumpStack.pop();
if (DEBUG) {
System.out.println("************");
System.out.println("merging stacks at " + dbc.getPC() + " -> " + stackToMerge);
System.out.println(" current stack " + stack);
}
if (reachOnlyByBranch) lvValues = new ArrayList<Item>(stackToMerge);
else mergeLists(stack, stackToMerge, true);
if (DEBUG)
System.out.println(" updated stack " + stack);
} }
reachOnlyByBranch = false;
}
int convertJumpToOneZeroState = 0;
int convertJumpToZeroOneState = 0;
private void setLastUpdate(int reg, int pc) {
while (lastUpdate.size() <= reg) lastUpdate.add(0);
lastUpdate.set(reg, pc);
}
public int getLastUpdate(int reg) {
if (lastUpdate.size() <= reg) return 0;
return lastUpdate.get(reg);
}
public int getNumLastUpdates() {
return lastUpdate.size();
}
public void sawOpcode(DismantleBytecode dbc, int seen) {
int register;
String signature;
Item it, it2, it3;
Constant cons;
if (dbc.isRegisterStore())
setLastUpdate(dbc.getRegisterOperand(), dbc.getPC());
mergeJumps(dbc);
needToMerge = true;
switch (seen) {
case ICONST_1:
convertJumpToOneZeroState = 1;
break;
case GOTO:
if (convertJumpToOneZeroState == 1 && dbc.getBranchOffset() == 4)
convertJumpToOneZeroState = 2;
else
convertJumpToOneZeroState = 0;
break;
case ICONST_0:
if (convertJumpToOneZeroState == 2)
convertJumpToOneZeroState = 3;
else convertJumpToOneZeroState = 0;
break;
default:convertJumpToOneZeroState = 0;
}
switch (seen) {
case ICONST_0:
convertJumpToZeroOneState = 1;
break;
case GOTO:
if (convertJumpToZeroOneState == 1 && dbc.getBranchOffset() == 4)
convertJumpToZeroOneState = 2;
else
convertJumpToZeroOneState = 0;
break;
case ICONST_1:
if (convertJumpToZeroOneState == 2)
convertJumpToZeroOneState = 3;
else convertJumpToZeroOneState = 0;
break;
default:convertJumpToZeroOneState = 0;
}
try
{
switch (seen) {
case ALOAD:
pushByLocalObjectLoad(dbc, dbc.getRegisterOperand());
break;
case ALOAD_0:
case ALOAD_1:
case ALOAD_2:
case ALOAD_3:
pushByLocalObjectLoad(dbc, seen - ALOAD_0);
break;
case DLOAD:
pushByLocalLoad("D", dbc.getRegisterOperand());
break;
case DLOAD_0:
case DLOAD_1:
case DLOAD_2:
case DLOAD_3:
pushByLocalLoad("D", seen - DLOAD_0);
break;
case FLOAD:
pushByLocalLoad("F", dbc.getRegisterOperand());
break;
case FLOAD_0:
case FLOAD_1:
case FLOAD_2:
case FLOAD_3:
pushByLocalLoad("F", seen - FLOAD_0);
break;
case ILOAD:
pushByLocalLoad("I", dbc.getRegisterOperand());
break;
case ILOAD_0:
case ILOAD_1:
case ILOAD_2:
case ILOAD_3:
pushByLocalLoad("I", seen - ILOAD_0);
break;
case LLOAD:
pushByLocalLoad("J", dbc.getRegisterOperand());
break;
case LLOAD_0:
case LLOAD_1:
case LLOAD_2:
case LLOAD_3:
pushByLocalLoad("J", seen - LLOAD_0);
break;
case GETSTATIC:
{
Item i = new Item(dbc.getSigConstantOperand(),
FieldAnnotation.fromReferencedField(dbc));
push(i);
break;
}
case LDC:
case LDC_W:
case LDC2_W:
cons = dbc.getConstantRefOperand();
pushByConstant(dbc, cons);
break;
case INSTANCEOF:
pop();
push(new Item("I"));
break;
case IFEQ:
case IFNE:
case IFLT:
case IFLE:
case IFGT:
case IFGE:
case IFNONNULL:
case IFNULL:
seenTransferOfControl = true;
{
Item top = pop();
// if we see a test comparing a special negative value with 0,
// reset all other such values on the opcode stack
if (top.valueCouldBeNegative()
&& (seen == IFLT || seen == IFLE || seen == IFGT || seen == IFGE)) {
int specialKind = top.getSpecialKind();
for(Item item : stack) if (item.getSpecialKind() == specialKind) item.setSpecialKind(0);
for(Item item : lvValues) if (item.getSpecialKind() == specialKind) item.setSpecialKind(0);
}
}
addJumpValue(dbc.getBranchTarget());
break;
case LOOKUPSWITCH:
case TABLESWITCH:
seenTransferOfControl = true;
pop();
addJumpValue(dbc.getBranchTarget());
int pc = dbc.getBranchOffset() - dbc.getBranchTarget();
for(int offset : dbc.getSwitchOffsets())
addJumpValue(offset+pc);
break;
case ARETURN:
case DRETURN:
case FRETURN:
case IRETURN:
case LRETURN:
seenTransferOfControl = true;
pop();
break;
case MONITORENTER:
case MONITOREXIT:
case POP:
case PUTSTATIC:
pop();
break;
case IF_ACMPEQ:
case IF_ACMPNE:
case IF_ICMPEQ:
case IF_ICMPNE:
case IF_ICMPLT:
case IF_ICMPLE:
case IF_ICMPGT:
case IF_ICMPGE:
seenTransferOfControl = true;
pop(2);
addJumpValue(dbc.getBranchTarget());
break;
case POP2:
it = pop();
if (it.getSize() == 1) pop();
break;
case PUTFIELD:
pop(2);
break;
case IALOAD:
case SALOAD:
pop(2);
push(new Item("I"));
break;
case DUP:
handleDup();
break;
case DUP2:
handleDup2();
break;
case DUP_X1:
handleDupX1();
break;
case DUP_X2:
handleDupX2();
break;
case DUP2_X1:
handleDup2X1();
break;
case IINC:
register = dbc.getRegisterOperand();
it = getLVValue( register );
it2 = new Item("I", new Integer(dbc.getIntConstant()));
pushByIntMath( IADD, it2, it);
pushByLocalStore(register);
break;
case ATHROW:
pop();
seenTransferOfControl = true;
reachOnlyByBranch = true;
break;
case CHECKCAST:
{
String castTo = dbc.getClassConstantOperand();
if (castTo.charAt(0) != '[') castTo = "L" + castTo + ";";
it = new Item(pop());
it.signature = castTo;
push(it);
break;
}
case NOP:
break;
case RET:
case RETURN:
seenTransferOfControl = true;
reachOnlyByBranch = true;
break;
case GOTO:
case GOTO_W: //It is assumed that no stack items are present when
seenTransferOfControl = true;
reachOnlyByBranch = true;
if (getStackDepth() > 0) {
jumpStack.push(new ArrayList<Item>(stack));
pop();
jumpTarget = dbc.getBranchTarget();
}
addJumpValue(dbc.getBranchTarget());
break;
case SWAP:
handleSwap();
break;
case ICONST_M1:
case ICONST_0:
case ICONST_1:
case ICONST_2:
case ICONST_3:
case ICONST_4:
case ICONST_5:
push(new Item("I", (seen-ICONST_0)));
break;
case LCONST_0:
case LCONST_1:
push(new Item("J", (long)(seen-LCONST_0)));
break;
case DCONST_0:
case DCONST_1:
push(new Item("D", (double)(seen-DCONST_0)));
break;
case FCONST_0:
case FCONST_1:
case FCONST_2:
push(new Item("F", (float)(seen-FCONST_0)));
break;
case ACONST_NULL:
push(new Item());
break;
case ASTORE:
case DSTORE:
case FSTORE:
case ISTORE:
case LSTORE:
pushByLocalStore(dbc.getRegisterOperand());
break;
case ASTORE_0:
case ASTORE_1:
case ASTORE_2:
case ASTORE_3:
pushByLocalStore(seen - ASTORE_0);
break;
case DSTORE_0:
case DSTORE_1:
case DSTORE_2:
case DSTORE_3:
pushByLocalStore(seen - DSTORE_0);
break;
case FSTORE_0:
case FSTORE_1:
case FSTORE_2:
case FSTORE_3:
pushByLocalStore(seen - FSTORE_0);
break;
case ISTORE_0:
case ISTORE_1:
case ISTORE_2:
case ISTORE_3:
pushByLocalStore(seen - ISTORE_0);
break;
case LSTORE_0:
case LSTORE_1:
case LSTORE_2:
case LSTORE_3:
pushByLocalStore(seen - LSTORE_0);
break;
case GETFIELD:
pop();
push(new Item(dbc.getSigConstantOperand(),
FieldAnnotation.fromReferencedField(dbc)));
break;
case ARRAYLENGTH:
pop();
push(new Item("I"));
break;
case BALOAD:
{
pop(2);
Item v = new Item("I");
v.setSpecialKind(Item.SIGNED_BYTE);
push(v);
break;
}
case CALOAD:
pop(2);
push(new Item("I"));
break;
case DALOAD:
pop(2);
push(new Item("D"));
break;
case FALOAD:
pop(2);
push(new Item("F"));
break;
case LALOAD:
pop(2);
push(new Item("J"));
break;
case AASTORE:
case BASTORE:
case CASTORE:
case DASTORE:
case FASTORE:
case IASTORE:
case LASTORE:
case SASTORE:
pop(3);
break;
case BIPUSH:
case SIPUSH:
push(new Item("I", (Integer)dbc.getIntConstant()));
break;
case IADD:
case ISUB:
case IMUL:
case IDIV:
case IAND:
case IOR:
case IXOR:
case ISHL:
case ISHR:
case IREM:
case IUSHR:
it = pop();
it2 = pop();
pushByIntMath(seen, it2, it);
break;
case INEG:
it = pop();
if (it.getConstant() != null) {
push(new Item("I", new Integer(-(Integer) it.getConstant())));
} else {
push(new Item("I"));
}
break;
case LNEG:
it = pop();
if (it.getConstant() != null) {
push(new Item("J", new Long(-(Long) it.getConstant())));
} else {
push(new Item("J"));
}
break;
case DNEG:
it = pop();
if (it.getConstant() != null) {
push(new Item("D", new Double(-(Double) it.getConstant())));
} else {
push(new Item("D"));
}
break;
case LADD:
case LSUB:
case LMUL:
case LDIV:
case LAND:
case LOR:
case LXOR:
case LSHL:
case LSHR:
case LREM:
case LUSHR:
it = pop();
it2 = pop();
pushByLongMath(seen, it2, it);
break;
case LCMP:
handleLcmp();
break;
case FCMPG:
case FCMPL: handleFcmp();
break;
case DCMPG:
case DCMPL:
handleDcmp();
break;
case FADD:
case FSUB:
case FMUL:
case FDIV:
it = pop();
it2 = pop();
pushByFloatMath(seen, it, it2);
break;
case DADD:
case DSUB:
case DMUL:
case DDIV:
case DREM:
it = pop();
it2 = pop();
pushByDoubleMath(seen, it, it2);
break;
case I2B:
it = pop();
if (it.getConstant() != null) {
it =new Item("I", (byte)constantToInt(it));
} else {
it = new Item("I");
}
it.setSpecialKind(Item.SIGNED_BYTE);
push(it);
break;
case I2C:
it = pop();
if (it.getConstant() != null) {
push(new Item("I", (char)constantToInt(it)));
} else {
push(new Item("I"));
}
break;
case I2L:
case D2L:{
it = pop();
Item newValue;
if (it.getConstant() != null) {
newValue = new Item("J", constantToLong(it));
} else {
newValue = new Item("J");
}
newValue.setSpecialKind(it.getSpecialKind());
push(newValue);
}
break;
case I2S:
it = pop();
if (it.getConstant() != null) {
push(new Item("I", (short)constantToInt(it)));
} else {
push(new Item("I"));
}
break;
case L2I:
case D2I:
case F2I:
it = pop();
if (it.getConstant() != null) {
push(new Item("I",constantToInt(it)));
} else {
push(new Item("I"));
}
break;
case L2F:
case D2F:
case I2F:
it = pop();
if (it.getConstant() != null) {
push(new Item("F", new Float(constantToFloat(it))));
} else {
push(new Item("F"));
}
break;
case F2D:
case I2D:
case L2D:
it = pop();
if (it.getConstant() != null) {
push(new Item("D", constantToDouble(it)));
} else {
push(new Item("D"));
}
break;
case NEW:
pushBySignature("L" + dbc.getClassConstantOperand() + ";");
break;
case NEWARRAY:
pop();
signature = "[" + BasicType.getType((byte)dbc.getIntConstant()).getSignature();
pushBySignature(signature);
break;
// According to the VM Spec 4.4.1, anewarray and multianewarray
// can refer to normal class/interface types (encoded in
// "internal form"), or array classes (encoded as signatures
// beginning with "[").
case ANEWARRAY:
pop();
signature = dbc.getClassConstantOperand();
if (!signature.startsWith("[")) {
signature = "[L" + signature + ";";
}
pushBySignature(signature);
break;
case MULTIANEWARRAY:
int dims = dbc.getIntConstant();
while ((dims
pop();
}
signature = dbc.getClassConstantOperand();
if (!signature.startsWith("[")) {
dims = dbc.getIntConstant();
signature = "";
while ((dims
signature += "[";
signature += "L" + signature + ";";
}
pushBySignature(signature);
break;
case AALOAD:
pop();
it = pop();
pushBySignature(it.getElementSignature());
break;
case JSR:
push(new Item(""));
break;
case INVOKEINTERFACE:
case INVOKESPECIAL:
case INVOKESTATIC:
case INVOKEVIRTUAL:
processMethodCall(dbc, seen);
break;
default:
throw new UnsupportedOperationException("OpCode " + OPCODE_NAMES[seen] + " not supported " );
}
}
catch (RuntimeException e) {
//If an error occurs, we clear the stack and locals. one of two things will occur.
//Either the client will expect more stack items than really exist, and so they're condition check will fail,
//or the stack will resync with the code. But hopefully not false positives
// TODO: log this
if (DEBUG)
e.printStackTrace();
clear();
}
finally {
if (exceptionHandlers.get(dbc.getNextPC()))
push(new Item());
if (DEBUG) {
System.out.println(dbc.getNextPC() + "pc : " + OPCODE_NAMES[seen] + " stack depth: " + getStackDepth());
System.out.println(this);
}
}
}
/**
* @param it
* @return
*/
private int constantToInt(Item it) {
return ((Number)it.getConstant()).intValue();
}
/**
* @param it
* @return
*/
private float constantToFloat(Item it) {
return ((Number)it.getConstant()).floatValue();
}
/**
* @param it
* @return
*/
private double constantToDouble(Item it) {
return ((Number)it.getConstant()).doubleValue();
}
/**
* @param it
* @return
*/
private long constantToLong(Item it) {
return ((Number)it.getConstant()).longValue();
}
private void handleDcmp() {
Item it;
Item it2;
it = pop();
it2 = pop();
if ((it.getConstant() != null) && it2.getConstant() != null) {
double d = (Double) it.getConstant();
double d2 = (Double) it.getConstant();
if (d2 < d)
push(new Item("I", (Integer) (-1) ));
else if (d2 > d)
push(new Item("I", (Integer)1));
else
push(new Item("I", (Integer)0));
} else {
push(new Item("I"));
}
}
private void handleFcmp() {
Item it;
Item it2;
it = pop();
it2 = pop();
if ((it.getConstant() != null) && it2.getConstant() != null) {
float f = (Float) it.getConstant();
float f2 = (Float) it.getConstant();
if (f2 < f)
push(new Item("I", new Integer(-1)));
else if (f2 > f)
push(new Item("I", new Integer(1)));
else
push(new Item("I", new Integer(0)));
} else {
push(new Item("I"));
}
}
private void handleLcmp() {
Item it;
Item it2;
it = pop();
it2 = pop();
if ((it.getConstant() != null) && it2.getConstant() != null) {
long l = (Long) it.getConstant();
long l2 = (Long) it.getConstant();
if (l2 < l)
push(new Item("I", (Integer)(-1)));
else if (l2 > l)
push(new Item("I", (Integer)(1)));
else
push(new Item("I", (Integer)(0)));
} else {
push(new Item("I"));
}
}
private void handleSwap() {
Item i1 = pop();
Item i2 = pop();
push(i1);
push(i2);
}
private void handleDup() {
Item it;
it = pop();
push(it);
push(it);
}
private void handleDupX1() {
Item it;
Item it2;
it = pop();
it2 = pop();
push(it);
push(it2);
push(it);
}
private void handleDup2() {
Item it, it2;
it = pop();
if (it.getSize() == 2) {
push(it);
push(it);
}
else {
it2 = pop();
push(it2);
push(it);
push(it2);
push(it);
}
}
private void handleDup2X1() {
String signature;
Item it;
Item it2;
Item it3;
it = pop();
it2 = pop();
signature = it.getSignature();
if (signature.equals("J") || signature.equals("D")) {
push(it);
push(it2);
push(it);
} else {
it3 = pop();
push(it2);
push(it);
push(it3);
push(it2);
push(it);
}
}
private void handleDupX2() {
String signature;
Item it;
Item it2;
Item it3;
it = pop();
it2 = pop();
signature = it2.getSignature();
if (signature.equals("J") || signature.equals("D")) {
push(it);
push(it2);
push(it);
} else {
it3 = pop();
push(it);
push(it3);
push(it2);
push(it);
}
}
private void processMethodCall(DismantleBytecode dbc, int seen) {
String clsName = dbc.getClassConstantOperand();
String methodName = dbc.getNameConstantOperand();
String signature = dbc.getSigConstantOperand();
String appenderValue = null;
Item sbItem = null;
//TODO: stack merging for trinaries kills the constant.. would be nice to maintain.
if ("java/lang/StringBuffer".equals(clsName)
|| "java/lang/StringBuilder".equals(clsName)) {
if ("<init>".equals(methodName)) {
if ("(Ljava/lang/String;)V".equals(signature)) {
Item i = getStackItem(0);
appenderValue = (String)i.getConstant();
} else if ("()V".equals(signature)) {
appenderValue = "";
}
} else if ("toString".equals(methodName)) {
Item i = getStackItem(0);
appenderValue = (String)i.getConstant();
} else if ("append".equals(methodName) && signature.indexOf("II)") == -1) {
sbItem = getStackItem(1);
Item i = getStackItem(0);
Object sbVal = sbItem.getConstant();
Object sVal = i.getConstant();
if ((sbVal != null) && (sVal != null)) {
appenderValue = sbVal + sVal.toString();
} else if (sbItem.registerNumber >= 0) {
OpcodeStack.Item item = getLVValue(sbItem.registerNumber);
if (item != null)
item.constValue = null;
}
}
}
pushByInvoke(dbc, seen != INVOKESTATIC);
if (appenderValue != null) {
Item i = this.getStackItem(0);
i.constValue = appenderValue;
if (sbItem != null) {
i.registerNumber = sbItem.registerNumber;
i.field = sbItem.field;
i.xfield = sbItem.xfield;
i.userValue = sbItem.userValue;
if (sbItem.registerNumber >= 0)
setLVValue(sbItem.registerNumber, i );
}
return;
}
if ((clsName.equals("java/util/Random") || clsName.equals("java/security/SecureRandom")) && methodName.equals("nextInt") && signature.equals("()I")) {
Item i = pop();
i.setSpecialKind(Item.RANDOM_INT);
push(i);
}
else if (seen == INVOKEVIRTUAL && methodName.equals("hashCode") && signature.equals("()I")
|| seen == INVOKESTATIC && clsName.equals("java/lang/System") && methodName.equals("identityHashCode") && signature.equals("(Ljava/lang/Object;)I")) {
Item i = pop();
i.setSpecialKind(Item.HASHCODE_INT);
push(i);
}
}
private void mergeLists(List<Item> mergeInto, List<Item> mergeFrom, boolean errorIfSizesDoNotMatch) {
// merge stacks
int intoSize = mergeInto.size();
int fromSize = mergeFrom.size();
if (errorIfSizesDoNotMatch && intoSize != fromSize) {
if (DEBUG) {
System.out.println("Bad merging items");
System.out.println("current items: " + mergeInto);
System.out.println("jump items: " + mergeFrom);
}
} else {
if (DEBUG) {
System.out.println("Merging items");
System.out.println("current items: " + mergeInto);
System.out.println("jump items: " + mergeFrom);
}
for (int i = 0; i < Math.min(intoSize, fromSize); i++)
mergeInto.set(i, Item.merge(mergeInto.get(i), mergeFrom.get(i)));
if (DEBUG) {
System.out.println("merged items: " + mergeInto);
}
}
}
public void clear() {
stack.clear();
lvValues.clear();
jumpStack.clear();
}
BitSet exceptionHandlers = new BitSet();
private Map<Integer, List<Item>> jumpEntries = new HashMap<Integer, List<Item>>();
private void addJumpValue(int target) {
if (DEBUG)
System.out.println("Set jump entry at " + methodName + ":" + target + "pc to " + lvValues);
List<Item> atTarget = jumpEntries.get(target);
if (atTarget == null) {
if (DEBUG)
System.out.println("Was null");
jumpEntries.put(target, new ArrayList<Item>(lvValues));
if (false) {
System.out.println("jump entires are now...");
for (Integer pc : jumpEntries.keySet()) {
List<Item> list = jumpEntries.get(pc);
System.out.println(pc + "pc -> " + Integer.toString(System.identityHashCode(list),16) + " " + list);
}}
return;
}
mergeLists(atTarget, lvValues, false);
if (DEBUG)
System.out.println("merge target for " + methodName + ":" + target + "pc is " + atTarget);
}
private String methodName;
public int resetForMethodEntry(final DismantleBytecode v) {
methodName = v.getMethodName();
jumpEntries.clear();
lastUpdate.clear();
convertJumpToOneZeroState = convertJumpToZeroOneState = 0;
reachOnlyByBranch = false;
int result= resetForMethodEntry0(v);
Code code = v.getMethod().getCode();
if (code == null) return result;
if (useIterativeAnalysis) {
// FIXME: Be clever
if (DEBUG)
System.out.println(" --- Iterative analysis");
DismantleBytecode branchAnalysis = new DismantleBytecode() {
@Override
public void sawOpcode(int seen) {
OpcodeStack.this.sawOpcode(this, seen);
}
// perhaps we don't need this
// @Override
// public void sawBranchTo(int pc) {
// addJumpValue(pc);
};
branchAnalysis.setupVisitorForClass(v.getThisClass());
branchAnalysis.doVisitMethod(v.getMethod());
if (false && !jumpEntries.isEmpty())
branchAnalysis.doVisitMethod(v.getMethod());
if (DEBUG && !jumpEntries.isEmpty()) {
System.out.println("Found dataflow for jumps in " + v.getMethodName());
for (Integer pc : jumpEntries.keySet()) {
List<Item> list = jumpEntries.get(pc);
System.out.println(pc + " -> " + Integer.toString(System.identityHashCode(list),16) + " " + list);
}
}
resetForMethodEntry0(v);
if (DEBUG)
System.out.println(" --- End of Iterative analysis");
}
return result;
}
private int resetForMethodEntry0(PreorderVisitor v) {
if (DEBUG) System.out.println("
stack.clear();
jumpTarget = -1;
lvValues.clear();
jumpStack.clear();
reachOnlyByBranch = false;
seenTransferOfControl = false;
String className = v.getClassName();
String signature = v.getMethodSig();
exceptionHandlers.clear();
Method m = v.getMethod();
Code code = m.getCode();
if (code != null)
{
CodeException[] exceptionTable = code.getExceptionTable();
if (exceptionTable != null)
for(CodeException ex : exceptionTable)
exceptionHandlers.set(ex.getHandlerPC());
}
if (DEBUG) System.out.println(" --- " + className
+ " " + m.getName() + " " + signature);
Type[] argTypes = Type.getArgumentTypes(signature);
int reg = 0;
if (!m.isStatic()) {
Item it = new Item("L" + className+";");
it.isInitialParameter = true;
it.registerNumber = reg;
setLVValue( reg, it);
reg += it.getSize();
}
for (Type argType : argTypes) {
Item it = new Item(argType.getSignature());
it.registerNumber = reg;
it.isInitialParameter = true;
setLVValue(reg, it);
reg += it.getSize();
}
return reg;
}
public int getStackDepth() {
return stack.size();
}
public Item getStackItem(int stackOffset) {
if (stackOffset < 0 || stackOffset >= stack.size()) {
// assert false : "Can't get stack offset " + stackOffset + " from " + stack.toString();
return new Item("Lfindbugs/OpcodeStackError;");
}
int tos = stack.size() - 1;
int pos = tos - stackOffset;
try {
return stack.get(pos);
} catch (ArrayIndexOutOfBoundsException e) {
throw new ArrayIndexOutOfBoundsException(
"Requested item at offset " + stackOffset + " in a stack of size " + stack.size()
+", made request for position " + pos);
}
}
private Item pop() {
return stack.remove(stack.size()-1);
}
private void pop(int count)
{
while ((count
pop();
}
private void push(Item i) {
stack.add(i);
}
private void pushByConstant(DismantleBytecode dbc, Constant c) {
if (c instanceof ConstantClass)
push(new Item("Ljava/lang/Class;", ((ConstantClass)c).getConstantValue(dbc.getConstantPool())));
else if (c instanceof ConstantInteger)
push(new Item("I", new Integer(((ConstantInteger) c).getBytes())));
else if (c instanceof ConstantString) {
int s = ((ConstantString) c).getStringIndex();
push(new Item("Ljava/lang/String;", getStringFromIndex(dbc, s)));
}
else if (c instanceof ConstantFloat)
push(new Item("F", new Float(((ConstantFloat) c).getBytes())));
else if (c instanceof ConstantDouble)
push(new Item("D", new Double(((ConstantDouble) c).getBytes())));
else if (c instanceof ConstantLong)
push(new Item("J", new Long(((ConstantLong) c).getBytes())));
else
throw new UnsupportedOperationException("Constant type not expected" );
}
private void pushByLocalObjectLoad(DismantleBytecode dbc, int register) {
Method m = dbc.getMethod();
LocalVariableTable lvt = m.getLocalVariableTable();
if (lvt != null) {
LocalVariable lv = LVTHelper.getLocalVariableAtPC(lvt, register, dbc.getPC());
if (lv != null) {
String signature = lv.getSignature();
pushByLocalLoad(signature, register);
return;
}
}
pushByLocalLoad("", register);
}
private void pushByIntMath(int seen, Item lhs, Item rhs) {
if (DEBUG) System.out.println("pushByIntMath: " + rhs.getConstant() + " " + lhs.getConstant() );
Item newValue = new Item("I");
try {
if ((rhs.getConstant() != null) && lhs.getConstant() != null) {
Integer lhsValue = (Integer) lhs.getConstant();
Integer rhsValue = (Integer) rhs.getConstant();
if (seen == IADD)
newValue = new Item("I",lhsValue + rhsValue);
else if (seen == ISUB)
newValue = new Item("I",lhsValue - rhsValue);
else if (seen == IMUL)
newValue = new Item("I", lhsValue * rhsValue);
else if (seen == IDIV)
newValue = new Item("I", lhsValue / rhsValue);
else if (seen == IAND) {
newValue = new Item("I", lhsValue & rhsValue);
if ((rhsValue&0xff) == 0 && rhsValue != 0 || (lhsValue&0xff) == 0 && lhsValue != 0 )
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
} else if (seen == IOR)
newValue = new Item("I",lhsValue | rhsValue);
else if (seen == IXOR)
newValue = new Item("I",lhsValue ^ rhsValue);
else if (seen == ISHL) {
newValue = new Item("I",lhsValue << rhsValue);
if (rhsValue >= 8) newValue.specialKind = Item.LOW_8_BITS_CLEAR;
}
else if (seen == ISHR)
newValue = new Item("I",lhsValue >> rhsValue);
else if (seen == IREM)
newValue = new Item("I", lhsValue % rhsValue);
else if (seen == IUSHR)
newValue = new Item("I", lhsValue >>> rhsValue);
} else if (rhs.getConstant() != null && seen == ISHL && (Integer) rhs.getConstant() >= 8)
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
else if (lhs.getConstant() != null && seen == IAND && ((Integer) lhs.getConstant() & 0xff) == 0)
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
else if (rhs.getConstant() != null && seen == IAND && ((Integer) rhs.getConstant() & 0xff) == 0)
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
} catch (RuntimeException e) {
// ignore it
}
if (lhs.specialKind == Item.INTEGER_SUM && rhs.getConstant() != null ) {
int rhsValue = (Integer) rhs.getConstant();
if (seen == IDIV && rhsValue ==2 || seen == ISHR && rhsValue == 1)
newValue.specialKind = Item.AVERAGE_COMPUTED_USING_DIVISION;
}
if (seen == IADD && newValue.specialKind == 0 && lhs.getConstant() == null && rhs.getConstant() == null )
newValue.specialKind = Item.INTEGER_SUM;
if (seen == IREM && lhs.specialKind == Item.HASHCODE_INT)
newValue.specialKind = Item.HASHCODE_INT_REMAINDER;
if (seen == IREM && lhs.specialKind == Item.RANDOM_INT)
newValue.specialKind = Item.RANDOM_INT_REMAINDER;
if (DEBUG) System.out.println("push: " + newValue);
push(newValue);
}
private void pushByLongMath(int seen, Item lhs, Item rhs) {
Item newValue = new Item("J");
try {
if ((rhs.getConstant() != null) && lhs.getConstant() != null) {
Long lhsValue = ((Long) lhs.getConstant());
if (seen == LSHL) {
newValue =new Item("J", lhsValue << ((Number) rhs.getConstant()).intValue());
if (((Number) rhs.getConstant()).intValue() >= 8) newValue.specialKind = Item.LOW_8_BITS_CLEAR;
}
else if (seen == LSHR)
newValue =new Item("J", lhsValue >> ((Number) rhs.getConstant()).intValue());
else if (seen == LUSHR)
newValue =new Item("J", lhsValue >>> ((Number) rhs.getConstant()).intValue());
else {
Long rhsValue = ((Long) rhs.getConstant());
if (seen == LADD)
newValue = new Item("J", lhsValue + rhsValue);
else if (seen == LSUB)
newValue = new Item("J", lhsValue - rhsValue);
else if (seen == LMUL)
newValue = new Item("J", lhsValue * rhsValue);
else if (seen == LDIV)
newValue =new Item("J", lhsValue / rhsValue);
else if (seen == LAND) {
newValue = new Item("J", lhsValue & rhsValue);
if ((rhsValue&0xff) == 0 && rhsValue != 0 || (lhsValue&0xff) == 0 && lhsValue != 0 )
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
}
else if (seen == LOR)
newValue = new Item("J", lhsValue | rhsValue);
else if (seen == LXOR)
newValue =new Item("J", lhsValue ^ rhsValue);
else if (seen == LREM)
newValue =new Item("J", lhsValue % rhsValue);
}
}
else if (rhs.getConstant() != null && seen == LSHL && ((Integer) rhs.getConstant()) >= 8)
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
else if (lhs.getConstant() != null && seen == LAND && (((Long) lhs.getConstant()) & 0xff) == 0)
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
else if (rhs.getConstant() != null && seen == LAND && (((Long) rhs.getConstant()) & 0xff) == 0)
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
} catch (RuntimeException e) {
// ignore it
}
push(newValue);
}
private void pushByFloatMath(int seen, Item it, Item it2) {
Item result;
if ((it.getConstant() != null) && it2.getConstant() != null) {
if (seen == FADD)
result =new Item("F", ((Float) it2.getConstant()) + ((Float) it.getConstant()));
else if (seen == FSUB)
result =new Item("F", ((Float) it2.getConstant()) - ((Float) it.getConstant()));
else if (seen == FMUL)
result =new Item("F", ((Float) it2.getConstant()) * ((Float) it.getConstant()));
else if (seen == FDIV)
result =new Item("F", ((Float) it2.getConstant()) / ((Float) it.getConstant()));
else result =new Item("F");
} else {
result =new Item("F");
}
result.setSpecialKind(Item.FLOAT_MATH);
push(result);
}
private void pushByDoubleMath(int seen, Item it, Item it2) {
Item result;
if ((it.getConstant() != null) && it2.getConstant() != null) {
if (seen == DADD)
result = new Item("D", ((Double) it2.getConstant()) + ((Double) it.getConstant()));
else if (seen == DSUB)
result = new Item("D", ((Double) it2.getConstant()) - ((Double) it.getConstant()));
else if (seen == DMUL)
result = new Item("D", ((Double) it2.getConstant()) * ((Double) it.getConstant()));
else if (seen == DDIV)
result = new Item("D", ((Double) it2.getConstant()) / ((Double) it.getConstant()));
else
result = new Item("D");
} else {
result = new Item("D");
}
result.setSpecialKind(Item.FLOAT_MATH);
push(result);
}
private void pushByInvoke(DismantleBytecode dbc, boolean popThis) {
String signature = dbc.getSigConstantOperand();
pop(PreorderVisitor.getNumberArguments(signature)+(popThis ? 1 : 0));
pushBySignature(Type.getReturnType(signature).getSignature());
}
private String getStringFromIndex(DismantleBytecode dbc, int i) {
ConstantUtf8 name = (ConstantUtf8) dbc.getConstantPool().getConstant(i);
return name.getBytes();
}
private void pushBySignature(String s) {
if ("V".equals(s))
return;
push(new Item(s, null));
}
private void pushByLocalStore(int register) {
Item it = pop();
setLVValue( register, it );
}
private void pushByLocalLoad(String signature, int register) {
Item it = getLVValue(register);
if (it == null) {
Item item = new Item(signature);
item.registerNumber = register;
push(item);
}
else if (it.getRegisterNumber() >= 0)
push(it);
else {
push(new Item(it, register));
}
}
private void setLVValue(int index, Item value ) {
int addCount = index - lvValues.size() + 1;
while ((addCount
lvValues.add(null);
if (!useIterativeAnalysis && seenTransferOfControl)
value = Item.merge(value, lvValues.get(index) );
lvValues.set(index, value);
}
private Item getLVValue(int index) {
if (index >= lvValues.size())
return null;
return lvValues.get(index);
}
}
// vim:ts=4
|
package edu.umd.cs.findbugs.ba;
import org.apache.bcel.generic.InstructionHandle;
import edu.umd.cs.findbugs.annotations.NonNull;
/**
* A class representing a location in the CFG for a method.
* Essentially, it represents a static instruction, <em>with the important caveat</em>
* that CFGs have inlined JSR subroutines, meaning that a single InstructionHandle
* in a CFG may represent several static locations. To this end, a Location
* is comprised of both an InstructionHandle and the BasicBlock that
* contains it.
* <p/>
* <p> Location objects may be compared with each other using the equals() method,
* and may be used as keys in tree and hash maps and sets.
* Note that <em>it is only valid to compare Locations produced from the same CFG</em>.
*
* @author David Hovemeyer
* @see CFG
*/
public class Location implements Comparable<Location> {
private final InstructionHandle handle;
private final BasicBlock basicBlock;
/**
* Constructor.
*
* @param handle the instruction
* @param basicBlock the basic block containing the instruction
*/
public Location(@NonNull InstructionHandle handle, @NonNull BasicBlock basicBlock) {
if (handle == null) throw new NullPointerException("handle cannot be null");
if (basicBlock == null) throw new NullPointerException("basicBlock cannot be null");
this.handle = handle;
this.basicBlock = basicBlock;
}
/**
* Get the instruction handle.
*/
public InstructionHandle getHandle() {
return handle;
}
/**
* Get the basic block.
*/
public BasicBlock getBasicBlock() {
return basicBlock;
}
/**
* Return whether or not the Location is positioned at the
* first instruction in the basic block.
*/
public boolean isFirstInstructionInBasicBlock() {
return !basicBlock.isEmpty() && handle == basicBlock.getFirstInstruction();
}
/**
* Return whether or not the Location is positioned at the
* last instruction in the basic block.
*/
public boolean isLastInstructionInBasicBlock() {
return !basicBlock.isEmpty() && handle == basicBlock.getLastInstruction();
}
public int compareTo(Location other) {
int cmp = basicBlock.getId() - other.basicBlock.getId();
if (cmp != 0)
return cmp;
return handle.getPosition() - other.handle.getPosition();
}
public int hashCode() {
return System.identityHashCode(basicBlock) + handle.getPosition();
}
public boolean equals(Object o) {
if (!(o instanceof Location))
return false;
Location other = (Location) o;
return basicBlock == other.basicBlock && handle == other.handle;
}
public String toString() {
return handle.toString() + " in basic block " + basicBlock.getId();
}
}
// vim:ts=4
|
package com.jom;
import cern.colt.matrix.tdouble.DoubleFactory1D;
import cern.colt.matrix.tdouble.DoubleMatrix2D;
import cern.colt.matrix.tint.IntFactory1D;
import cern.colt.matrix.tint.IntFactory2D;
import cern.colt.matrix.tint.IntMatrix2D;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map.Entry;
class _SOLVERWRAPPER_IPOPT
{
final static int returnCode_Diverging_Iterates = 4;
final static int returnCode_Error_In_Step_Computation = -3;
final static int returnCode_Feasible_Point_Found = 6;
final static int returnCode_Infeasible_Problem_Detected = 2;
final static int returnCode_Insufficient_Memory = -102;
final static int returnCode_Internal_Error = -199;
final static int returnCode_Invalid_Number_Detected = -13;
final static int returnCode_Invalid_Option = -12;
final static int returnCode_Invalid_Problem_Definition = -11;
final static int returnCode_Maximum_CpuTime_Exceeded = -4;
final static int returnCode_Maximum_Iterations_Exceeded = -1;
final static int returnCode_NonIpopt_Exception_Thrown = -101;
final static int returnCode_Not_Enough_Degrees_Of_Freedom = -10;
final static int returnCode_Restoration_Failed = -2;
final static int returnCode_Search_Direction_Becomes_Too_Small = 3;
final static int returnCode_Solve_Succeeded = 0;
final static int returnCode_Solved_To_Acceptable_Level = 1;
final static int returnCode_Unrecoverable_Exception = -100;
final static int returnCode_User_Requested_Stop = 5;
private final HashMap<String, Object> param;
private final _INTERNAL_SolverIO s;
private final String solverLibraryName;
_SOLVERWRAPPER_IPOPT(_INTERNAL_SolverIO s, HashMap<String, Object> param)
{
this.s = s;
this.solverLibraryName = (String) param.get("solverLibraryName");
this.param = param;
}
static String errorMessage(int code)
{
switch (code)
{
case 0:
return "Solve_Succeeded. This message indicates that IPOPT found a (locally) optimal point within the desired tolerances";
case 1:
return "Solved_To_Acceptable_Level. This indicates that the algorithm did not converge to the ``desired'' tolerances, but that it "
+ "was able to obtain a point satisfying the ``acceptable'' tolerance level as specified by acceptable-* options. This may "
+ "happen if the desired tolerances are too small for the current problem";
case 2:
return "Infeasible_Problem_Detected. The restoration phase converged to a point that is a minimizer for the constraint violation (in"
+ " the -norm), but is not feasible for the original problem. This indicates that the problem may be infeasible (or at least"
+ " that the algorithm is stuck at a locally infeasible point). The returned point (the minimizer of the constraint "
+ "violation) might help you to find which constraint is causing the problem. If you believe that the NLP is feasible, it "
+ "might help to start the optimization from a different point.";
case 3:
return "Search_Direction_Becomes_Too_Small. This indicates that IPOPT is calculating very small step sizes and making very little "
+ "progress. This could happen if the problem has been solved to the best numerical accuracy possible given the current "
+ "scaling.";
case 4:
return "Diverging_Iterates. This message is printed if the max-norm of the iterates becomes larger than the value of the option "
+ "diverging_iterates_tol. This can happen if the problem is unbounded below and the iterates are diverging. ";
case 5:
return "User_Requested_Stop. This message is printed if the user call-back method intermediate_callback returned false";
case 6:
return "Feasible_Point_Found. This message is printed if the problem is ``square'' (i.e., it has as many equality constraints as "
+ "free variables) and IPOPT found a feasible point.";
case -1:
return "Maximum_Iterations_Exceeded. This indicates that IPOPT has exceeded the maximum number of iterations as specified by the "
+ "option max_iter";
case -2:
return "Restoration_Failed. This indicates that the restoration phase failed to find a feasible point that was acceptable to the "
+ "filter line search for the original problem. This could happen if the problem is highly degenerate, does not satisfy the "
+ "constraint qualification, or if your NLP code provides incorrect derivative information";
case -3:
return "Error_In_Step_Computation. This message is printed if IPOPT is unable to compute a search direction, despite several "
+ "attempts to modify the iteration matrix. Usually, the value of the regularization parameter then becomes too large. One "
+ "situation where this can happen is when values in the Hessian are invalid (NaN or Inf). You can check whether this is "
+ "true by using the check_derivatives_for_naninf option. ";
case -4:
return "Maximum_CpuTime_Exceeded. ";
case -10:
return "Not_Enough_Degrees_Of_Freedom. This indicates that your problem, as specified, has too few degrees of freedom. This can "
+ "happen if you have too many equality constraints, or if you fix too many variables (IPOPT removes fixed variables). ";
case -11:
return "Invalid_Problem_Definition. This indicates that there was an exception of some sort when building the IpoptProblem structure"
+ " in the C or Fortran interface. Likely there is an error in your model or the main routine. ";
case -12:
return "Invalid_Option. This indicates that there was some problem specifying the options. See the specific message for details.";
case -13:
return "Invalid_Number_Detected. ";
case -100:
return "Unrecoverable_Exception. This indicates that IPOPT has thrown an exception that does not have an internal return code. See "
+ "the specific message for details. ";
case -101:
return "NonIpopt_Exception_Thrown. An unknown exception was caught in IPOPT. This exception could have originated from your model or"
+ " any linked in third party code. ";
case -102:
return "Insufficient_Memory. An error occurred while trying to allocate memory. The problem may be too large for your current memory"
+ " and swap configuration. ";
case -199:
return "Internal_Error. An unknown internal error has occurred. Please notify the authors of IPOPT via the mailing list";
default:
throw new JOMException("JOM - IPOPT interface. Unknown IPOPT error message");
}
}
void solve()
{
_JNA_IPOPT g = (_JNA_IPOPT) Native.loadLibrary(solverLibraryName, _JNA_IPOPT.class);
final int n = this.s.in.numDecVariables;
final double[] x_L = s.in.primalSolutionLowerBound.toArray();
final double[] x_U = s.in.primalSolutionUpperBound.toArray();
final int m = s.in.numLpConstraints + s.in.numNlpConstraints;
final double[] g_L = s.in.constraintLowerBound.toArray();
final double[] g_U = s.in.constraintUpperBound.toArray();
LinkedHashMap<Integer, HashSet<Integer>> activeVarIds = (m == 0) ?
new LinkedHashMap<Integer, HashSet<Integer>>() :
s.in.lhsMinusRhsAccumulatedConstraint.getActiveVarIds();
int numNonZerosActiveVarIdsMatrix = 0;
if (m > 0) for (HashSet<Integer> colIds : activeVarIds.values()) numNonZerosActiveVarIdsMatrix += colIds.size();
final int nele_jac = (m == 0) ? 0 : numNonZerosActiveVarIdsMatrix;
final int numActiveCoordinates = nele_jac;
final int nele_hess = 1; // we will use automatic hessian calculation
final int index_style = 0; // C style
int[] aux_rowsArrayActiveVarIds = new int[numNonZerosActiveVarIdsMatrix];
int[] aux_colsArrayActiveVarIds = new int[numNonZerosActiveVarIdsMatrix];
int counter = 0;
for (Entry<Integer, HashSet<Integer>> e : activeVarIds.entrySet())
for (Integer dv : e.getValue())
{
aux_rowsArrayActiveVarIds[counter] = e.getKey();
aux_colsArrayActiveVarIds[counter++] = dv;
}
final int[] rowsArrayActiveVarIds = (s.in.lhsMinusRhsAccumulatedConstraint == null) ? new int[0] : aux_rowsArrayActiveVarIds;
final int[] colsArrayActiveVarIds = (s.in.lhsMinusRhsAccumulatedConstraint == null) ? new int[0] : aux_colsArrayActiveVarIds;
if ((rowsArrayActiveVarIds.length != numActiveCoordinates) || (colsArrayActiveVarIds.length != numActiveCoordinates))
throw new JOMException("JOM - IPOPT interface. Unexpected error");
IntMatrix2D coord = IntFactory2D.dense.make(nele_jac, 2);
if (s.in.lhsMinusRhsAccumulatedConstraint != null)
{
coord.viewColumn(0).assign(rowsArrayActiveVarIds);
coord.viewColumn(1).assign(colsArrayActiveVarIds);
}
final int[] indexesOfGradientActiveCoordinates = (s.in.lhsMinusRhsAccumulatedConstraint == null) ?
new int[0] :
DoubleMatrixND.sub2ind(coord, IntFactory1D.dense.make(new int[]{s.in.numConstraints, s.in.numDecVariables})).toArray();
_JNA_IPOPT_CallBack_Eval_F eval_f = new _JNA_IPOPT_CallBack_Eval_F()
{
@Override
public boolean callback(int n, Pointer x, boolean new_x, Pointer obj_value, Pointer user_data)
{
double[] values = x.getDoubleArray(0, n);
obj_value.write(0, new double[]{s.in.objectiveFunction.evaluate_internal(values).get(0)}, 0, 1);
return true;
}
};
_JNA_IPOPT_CallBack_Eval_G eval_g = new _JNA_IPOPT_CallBack_Eval_G()
{
@Override
public boolean callback(int n, Pointer x, boolean new_x, int m, Pointer g, Pointer user_data)
{
double[] values = x.getDoubleArray(0, n);
double[] gOut = s.in.lhsMinusRhsAccumulatedConstraint.evaluate_internal(values).elements().toArray();
if (gOut.length != m) throw new JOMException("JOM - IPOPT interface. Unexpected error");
g.write(0, gOut, 0, m);
return true;
}
};
_JNA_IPOPT_CallBack_Eval_Grad_F eval_grad_f = new _JNA_IPOPT_CallBack_Eval_Grad_F()
{
@Override
public boolean callback(int n, Pointer x, boolean new_x, Pointer grad_f, Pointer user_data)
{
double[] values = x.getDoubleArray(0, n);
grad_f.write(0, s.in.objectiveFunction.evaluateJacobian_internal(values).viewRow(0).toArray(), 0, n);
return true;
}
};
_JNA_IPOPT_CallBack_Eval_Jac_G eval_jac_g = new _JNA_IPOPT_CallBack_Eval_Jac_G()
{
@Override
public boolean callback(int n, Pointer x, boolean new_x, int m, int nele_jac, Pointer iRow, Pointer jCol, Pointer values, Pointer
user_data)
{
if (values == null)
{
/* Fill in the sparsity pattern --> fill in iRow and jCol arrays */
iRow.write(0, rowsArrayActiveVarIds, 0, nele_jac);
jCol.write(0, colsArrayActiveVarIds, 0, nele_jac);
return true;
} else
{
/* Return the values */
double[] xValues = x.getDoubleArray(0, n);
DoubleMatrix2D res = s.in.lhsMinusRhsAccumulatedConstraint.evaluateJacobian_internal(xValues);
double[] resSelectedIndexes = res.vectorize().viewSelection(indexesOfGradientActiveCoordinates).toArray();
values.write(0, resSelectedIndexes, 0, nele_jac);
return true;
}
}
};
_JNA_IPOPT_CallBack_Eval_H eval_h = new _JNA_IPOPT_CallBack_Eval_H()
{
@Override
public boolean callback(int n, Pointer x, boolean new_x, double obj_factor, int m, Pointer lambda, boolean new_lambda, int nele_hess,
Pointer iRow, Pointer jCol, Pointer values, Pointer user_data)
{
// return false;
if (!s.isLinearProblem()) // hessians are computed automatically
return false;
if (values == null) // problem is linear, hessian is zero
{
int[] auxVar = new int[nele_hess];
java.util.Arrays.fill(auxVar, 0);
/* Fill in the sparsity pattern --> fill in iRow and jCol arrays */
iRow.write(0, auxVar, 0, nele_hess);
jCol.write(0, auxVar, 0, nele_hess);
return true;
} else
{
/* Return the values */
double[] auxVar = new double[nele_hess];
java.util.Arrays.fill(auxVar, 0);
values.write(0, auxVar, 0, nele_hess);
return true;
}
}
};
Pointer nlp = g.CreateIpoptProblem(n, x_L, x_U, m, g_L, g_U, nele_jac, nele_hess, index_style, eval_f, eval_g, eval_grad_f, eval_jac_g,
eval_h);
try {
if (!s.in.toMinimize) g.AddIpoptNumOption(nlp, "obj_scaling_factor", -1);
/* Set specific parameters specified by the user */
for (Entry<String, Object> entry : this.param.entrySet())
{
String key = entry.getKey();
if (key.equalsIgnoreCase("solverLibraryName")) continue; // a non-IPOPT specific option
if (key.equals("maxSolverTimeInSeconds"))
{
final Double val_maxSolverTimeInSeconds = ((Number) entry.getValue()).doubleValue();
if (val_maxSolverTimeInSeconds > 0)
g.AddIpoptNumOption(nlp, "max_cpu_time", val_maxSolverTimeInSeconds);
continue;
}
Object value = entry.getValue();
if (value instanceof String)
g.AddIpoptStrOption(nlp, key, (String) value);
else if (value instanceof Integer)
g.AddIpoptIntOption(nlp, key, ((Integer) value).intValue());
else if (value instanceof Double)
g.AddIpoptNumOption(nlp, key, ((Double) value).doubleValue());
else
throw new JOMException("JOM - IPOPT interface. Unknown value type in parameters");
}
if (s.in.lhsMinusRhsAccumulatedConstraint != null)
if (s.in.lhsMinusRhsAccumulatedConstraint.isLinear())
{
g.AddIpoptStrOption(nlp, "jac_c_constant", "yes"); // equality constraints
// are linear => the
// jacobian is called
// once
g.AddIpoptStrOption(nlp, "jac_d_constant", "yes"); // inequality
// constraints are
// linear => the
// jacobian is called
// once
}
if (s.isLinearProblem())
{
g.AddIpoptStrOption(nlp, "hessian_approximation", "exact"); // the hessian
// is given
// exactly,
// and will be
// equal to 0
g.AddIpoptStrOption(nlp, "hessian_constant", "yes"); // the hessian is
// constant
// (objective
// function and
// constraints are
// quadratic or
// linear) => the
// hessian is called
// once
} else
{
g.AddIpoptStrOption(nlp, "hessian_approximation", "limited-memory");
g.AddIpoptStrOption(nlp, "hessian_constant", "no");
}
double[] x0 = s.in.primalInitialSolution.toArray();
double[] gArray = new double[m];
double[] obj_val = new double[1];
double[] mult_g = new double[m];
double[] mult_x_L = new double[n];
double[] mult_x_U = new double[n];
int status = g.IpoptSolve(nlp, x0, gArray, obj_val, mult_g, mult_x_L, mult_x_U, Pointer.NULL);
s.problemAlreadyAttemptedTobeSolved = true;
if (status == 0)
{ // Solve_Succeeded = 0
}
s.out.statusCode = status;
s.out.statusMessage = errorMessage(status);
s.out.primalSolution = DoubleFactory1D.dense.make(x0);
s.out.multiplierOfLowerBoundConstraintToPrimalVariables = DoubleFactory1D.dense.make(mult_x_L);
s.out.multiplierOfUpperBoundConstraintToPrimalVariables = DoubleFactory1D.dense.make(mult_x_U);
s.out.primalValuePerConstraint = DoubleFactory1D.dense.make(gArray);
s.out.multiplierOfConstraint = DoubleFactory1D.dense.make(mult_g);
s.out.primalCost = obj_val[0];
s.out.bestOptimalityBound = s.in.toMinimize? -Double.MAX_VALUE : Double.MAX_VALUE; //p.getDblAttrib(XPRSconstants.BESTBOUND); // pablo: this may not be the one for this
switch (status)
{
case returnCode_Solve_Succeeded:
case returnCode_Solved_To_Acceptable_Level:
case returnCode_Feasible_Point_Found:
s.out.solutionIsFeasible = true;
s.out.solutionIsOptimal = true;
s.out.feasibleSolutionDoesNotExist = false;
s.out.foundUnboundedSolution = false;
break;
case returnCode_Infeasible_Problem_Detected:
s.out.solutionIsFeasible = false;
s.out.solutionIsOptimal = false;
s.out.feasibleSolutionDoesNotExist = true;
s.out.foundUnboundedSolution = false;
break;
case returnCode_Search_Direction_Becomes_Too_Small:
case returnCode_Maximum_Iterations_Exceeded:
s.out.solutionIsFeasible = true;
s.out.solutionIsOptimal = false;
s.out.feasibleSolutionDoesNotExist = false;
s.out.foundUnboundedSolution = false;
break;
case returnCode_Diverging_Iterates:
s.out.solutionIsFeasible = true;
s.out.solutionIsOptimal = false;
s.out.feasibleSolutionDoesNotExist = false;
s.out.foundUnboundedSolution = true;
break;
case returnCode_User_Requested_Stop:
case returnCode_Restoration_Failed:
case returnCode_Error_In_Step_Computation:
case returnCode_Maximum_CpuTime_Exceeded:
case returnCode_Not_Enough_Degrees_Of_Freedom:
case returnCode_Invalid_Problem_Definition:
case returnCode_Invalid_Option:
case returnCode_Invalid_Number_Detected:
case returnCode_Unrecoverable_Exception:
case returnCode_NonIpopt_Exception_Thrown:
case returnCode_Insufficient_Memory:
case returnCode_Internal_Error:
s.out.solutionIsFeasible = false;
s.out.solutionIsOptimal = false;
s.out.feasibleSolutionDoesNotExist = false;
s.out.foundUnboundedSolution = false;
break;
}
} finally {
g.FreeIpoptProblem(nlp);
nlp = null;
}
}
}
|
package openaf.core;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.io.IOUtils;
import org.h2.tools.Server;
import org.mozilla.javascript.Scriptable;
import openaf.AFCmdBase;
import openaf.JSEngine;
import openaf.SimpleLog;
/**
* Core DB plugin
*
* @author Nuno Aguiar
*
*/
public class DB {
protected final String ORACLE_DRIVER = "oracle.jdbc.OracleDriver";
protected final Long LIMIT_RESULTS = 100000000L;
protected Connection con;
protected Server h2Server;
protected ConcurrentHashMap<String, PreparedStatement> preparedStatements = new ConcurrentHashMap<String, PreparedStatement>();
protected boolean convertDates = false;
public String url;
/**
* <odoc>
* <key>DB.db(aDriver, aURL, aLogin, aPassword)</key>
* Creates a new instance of the object DB providing java class aDriver (e.g. oracle.jdbc.OracleDriver)
* that must be included on OpenAF's classpath, a JDBC aURL, aLogin and aPassword. If the aDriver is
* null or undefined the Oracle driver will be used.
* </odoc>
*/
public void newDB(String driver, String url, String login, String pass) throws Exception {
// Are we in the wrong constructor?
if (pass == null || pass.equals("undefined")) {
if (url != null) {
// Ok, use it as if it was another constructor
connect(ORACLE_DRIVER, driver, url, login);
}
} else {
SimpleLog.log(SimpleLog.logtype.DEBUG, "New DB with driver='" + driver + "'|url='" + url + "'|login='"+login+"'|pass='"+pass+"'", null);
connect(driver, url, login, pass);
}
}
/**
* <odoc>
* <key>DB.close()</key>
* Closes the database connection for this DB object instance. In case of error an exception will be
* thrown.
* </odoc>
*/
public void close() throws SQLException {
if (con != null) {
try {
closeAllStatements();
con.close();
} catch (SQLException e) {
//SimpleLog.log(SimpleLog.logtype.ERROR, "Error closing database " + url + ": " + e.getMessage(), e);
throw e;
}
}
}
/**
* <odoc>
* <key>DB.getStatements() : Array</key>
* Returns the current list of database prepared statements that weren't closed it. Do close them,
* as soon as possible, using the DB.closeStatement or DB.closeAllStatements functions.
* </odoc>
*/
public Object getStatements() {
JSEngine.JSList statements = AFCmdBase.jse.getNewList(null);
statements.addAll(preparedStatements.keySet());
return statements.getList();
}
/**
* <odoc>
* <key>DB.getConnect() : JavaObject</key>
* Returns a Java database connection.
* </odoc>
*/
public Object getConnect() {
return con;
}
/**
* <odoc>
* <key>DB.closeStatement(aStatement)</key>
* Closes the corresponding prepared statement. If an error occurs during this process
* an exception will be thrown.
* </odoc>
*/
public void closeStatement(String aQuery) throws SQLException {
if (con != null) {
PreparedStatement ps = preparedStatements.get(aQuery);
if (ps != null) {
ps.close();
preparedStatements.remove(aQuery);
}
}
}
/**
* <odoc>
* <key>DB.closeAllStatements()</key>
* Tries to close all prepared statements for this DB object instance. If an error occurs
* during this process an exception will be thrown.
* </odoc>
*/
public void closeAllStatements() throws SQLException {
if (con != null) {
for(PreparedStatement ps : preparedStatements.values()) {
ps.close();
}
}
}
/**
* <odoc>
* <key>DB.q(aQuery) : Map</key>
* Performs aQuery (SQL) on the current DB object instance. It returns a Map with a
* results array that will have an element per result set line. In case of error an exception will be
* thrown.
* </odoc>
*/
public Object q(String query) throws IOException, SQLException {
if (con != null) {
try {
PreparedStatement ps = con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
int numberColumns = rs.getMetaData().getColumnCount();
JSEngine.JSMap no = AFCmdBase.jse.getNewMap(null);
JSEngine.JSList records = AFCmdBase.jse.getNewList(no.getMap());
while(rs.next()) { // && count < LIMIT_RESULTS) {
JSEngine.JSMap record = AFCmdBase.jse.getNewMap(records.getList());
for(int i = 1; i <= numberColumns; i++) {
if ((rs.getMetaData().getColumnType(i) == java.sql.Types.NUMERIC) ||
(rs.getMetaData().getColumnType(i) == java.sql.Types.DECIMAL) ||
(rs.getMetaData().getColumnType(i) == java.sql.Types.DOUBLE) ||
(rs.getMetaData().getColumnType(i) == java.sql.Types.FLOAT) ||
(rs.getMetaData().getColumnType(i) == java.sql.Types.INTEGER)) {
// TODO: Need to change for more performance
if (rs.getObject(i) != null) {
//jsong.writeNumberField(rs.getMetaData().getColumnName(i), new BigDecimal(rs.getObject(i).toString()));
record.put(rs.getMetaData().getColumnName(i), Double.valueOf(rs.getObject(i).toString()) );
} else {
//jsong.writeNumberField(rs.getMetaData().getColumnName(i), null);
record.put(rs.getMetaData().getColumnName(i), null);
}
} else {
if((rs.getMetaData().getColumnType(i) == java.sql.Types.CLOB) ||
(rs.getMetaData().getColumnType(i) == java.sql.Types.LONGVARCHAR)) {
try {
InputStream in;
if (rs.getMetaData().getColumnType(i) == java.sql.Types.CLOB)
in = rs.getClob(i).getAsciiStream();
else
in = rs.getAsciiStream(i);
StringWriter w = new StringWriter();
IOUtils.copy(in, w, (Charset) null);
record.put(rs.getMetaData().getColumnName(i), w.toString());
} catch(Exception e) {
SimpleLog.log(SimpleLog.logtype.DEBUG, "Problem getting clob", e);
record.put(rs.getMetaData().getColumnName(i), null);
}
continue;
}
if((rs.getMetaData().getColumnType(i) == java.sql.Types.BLOB) ||
(rs.getMetaData().getColumnType(i) == java.sql.Types.BINARY) ||
(rs.getMetaData().getColumnType(i) == java.sql.Types.LONGVARBINARY)) {
try {
InputStream in;
if (rs.getMetaData().getColumnType(i) == java.sql.Types.BLOB)
in = rs.getBlob(i).getBinaryStream();
else
in = rs.getBinaryStream(i);
record.put(rs.getMetaData().getColumnName(i), IOUtils.toByteArray(in));
} catch(Exception e) {
SimpleLog.log(SimpleLog.logtype.DEBUG, "Problem getting blob", e);
record.put(rs.getMetaData().getColumnName(i), null);
}
continue;
}
if (convertDates) {
if((rs.getMetaData().getColumnType(i) == java.sql.Types.DATE)) {
if (rs.getDate(i) != null)
record.put(rs.getMetaData().getColumnName(i), AFCmdBase.jse.newObject((Scriptable) AFCmdBase.jse.getGlobalscope(), "Date", new Object[] { rs.getDate(i).getTime() }));
else
record.put(rs.getMetaData().getColumnName(i), null);
continue;
}
if((rs.getMetaData().getColumnType(i) == java.sql.Types.TIMESTAMP) ||
(rs.getMetaData().getColumnType(i) == java.sql.Types.TIMESTAMP_WITH_TIMEZONE) ||
(rs.getMetaData().getColumnTypeName(i).equals("TIMESTAMP WITH TIME ZONE"))) {
if (rs.getTimestamp(i) != null)
record.put(rs.getMetaData().getColumnName(i), AFCmdBase.jse.newObject((Scriptable) AFCmdBase.jse.getGlobalscope(), "Date", new Object[] { rs.getTimestamp(i).getTime() }));
else
record.put(rs.getMetaData().getColumnName(i), null);
continue;
}
if((rs.getMetaData().getColumnType(i) == java.sql.Types.TIME) ||
(rs.getMetaData().getColumnType(i) == java.sql.Types.TIME_WITH_TIMEZONE)) {
if (rs.getTime(i) != null)
record.put(rs.getMetaData().getColumnName(i), AFCmdBase.jse.newObject((Scriptable) AFCmdBase.jse.getGlobalscope(), "Date", new Object[] { rs.getTime(i).getTime() }));
else
record.put(rs.getMetaData().getColumnName(i), null);
continue;
}
}
if (rs.getObject(i) != null) {
//jsong.writeStringField(rs.getMetaData().getColumnName(i), rs.getObject(i).toString());
record.put(rs.getMetaData().getColumnName(i), rs.getObject(i).toString());
} else {
//jsong.writeStringField(rs.getMetaData().getColumnName(i), null);
record.put(rs.getMetaData().getColumnName(i), null);
}
}
}
records.add(record.getMap());
}
rs.close();
ps.close();
no.put("results", records.getList());
return no.getMap();
} catch (SQLException e) {
throw e;
}
}
return null;
}
/**
* <odoc>
* <key>DB.qsRS(aQuery, arrayOfBindVariables) : Map</key>
* Performs aQuery (SQL) on the current DB object instance using the bind variables from the arrayOfBindVariables.
* It returns a java ResultSet object that should be closed after use. In case of error an
* exception will be thrown. If you specify to use keepStatement do close this
* query, as soon as possible, using DB.closeStatement(aQuery) (where you provide an exactly equal statement to
* aQuery) or DB.closeAllStatements.
* </odoc>
*/
public Object qsRS(String query, JSEngine.JSList bindVariables) throws IOException, SQLException {
if (con != null) {
try {
PreparedStatement ps = null;
ps = con.prepareStatement(query);
int ii = 0;
for (Object obj : bindVariables ) {
ii++;
ps.setObject(ii, obj);
}
ResultSet rs = ps.executeQuery();
return rs;
} catch (SQLException e) {
throw e;
}
}
return null;
}
/**
* <odoc>
* <key>DB.qs(aQuery, arrayOfBindVariables, keepStatement) : Map</key>
* Performs aQuery (SQL) on the current DB object instance using the bind variables from the arrayOfBindVariables.
* It returns a Map with a results array that will have an element per result set line. In case of error an
* exception will be thrown. Optionally you can specify to keepStatement (e.g. boolean) to keep from closing
* the prepared statement used for reuse in another qs call. If you specify to use keepStatement do close this
* query, as soon as possible, using DB.closeStatement(aQuery) (where you provide an exactly equal statement to
* aQuery) or DB.closeAllStatements.
* </odoc>
*/
public Object qs(String query, JSEngine.JSList bindVariables, boolean keepStatement) throws IOException, SQLException {
if (con != null) {
try {
PreparedStatement ps = null;
if (preparedStatements.containsKey(query)) {
ps = preparedStatements.get(query);
} else {
ps = con.prepareStatement(query);
if (keepStatement) preparedStatements.put(query, ps);
}
int ii = 0;
for (Object obj : bindVariables ) {
ii++;
ps.setObject(ii, obj);
}
ResultSet rs = ps.executeQuery();
int numberColumns = rs.getMetaData().getColumnCount();
JSEngine.JSMap no = AFCmdBase.jse.getNewMap(null);
JSEngine.JSList records = AFCmdBase.jse.getNewList(no.getMap());
while(rs.next()) { // && count < LIMIT_RESULTS) {
JSEngine.JSMap record = AFCmdBase.jse.getNewMap(records.getList());
for(int i = 1; i <= numberColumns; i++) {
if ((rs.getMetaData().getColumnType(i) == java.sql.Types.NUMERIC) ||
(rs.getMetaData().getColumnType(i) == java.sql.Types.DECIMAL) ||
(rs.getMetaData().getColumnType(i) == java.sql.Types.DOUBLE) ||
(rs.getMetaData().getColumnType(i) == java.sql.Types.FLOAT) ||
(rs.getMetaData().getColumnType(i) == java.sql.Types.INTEGER)) {
// TODO: Need to change for more performance
if (rs.getObject(i) != null) {
//jsong.writeNumberField(rs.getMetaData().getColumnName(i), new BigDecimal(rs.getObject(i).toString()));
record.put(rs.getMetaData().getColumnName(i), Double.valueOf(rs.getObject(i).toString()) );
} else {
//jsong.writeNumberField(rs.getMetaData().getColumnName(i), null);
record.put(rs.getMetaData().getColumnName(i), null);
}
} else {
if((rs.getMetaData().getColumnType(i) == java.sql.Types.CLOB) ||
(rs.getMetaData().getColumnType(i) == java.sql.Types.LONGVARCHAR)) {
InputStream in;
if (rs.getMetaData().getColumnType(i) == java.sql.Types.CLOB)
in = rs.getClob(i).getAsciiStream();
else
in = rs.getAsciiStream(i);
StringWriter w = new StringWriter();
IOUtils.copy(in, w, (Charset) null);
record.put(rs.getMetaData().getColumnName(i), w.toString());
continue;
}
if((rs.getMetaData().getColumnType(i) == java.sql.Types.BLOB) ||
(rs.getMetaData().getColumnType(i) == java.sql.Types.BINARY) ||
(rs.getMetaData().getColumnType(i) == java.sql.Types.LONGVARBINARY)) {
InputStream in;
if (rs.getMetaData().getColumnType(i) == java.sql.Types.BLOB)
in = rs.getBlob(i).getBinaryStream();
else
in = rs.getBinaryStream(i);
record.put(rs.getMetaData().getColumnName(i), IOUtils.toByteArray(in));
continue;
}
if (convertDates) {
if((rs.getMetaData().getColumnType(i) == java.sql.Types.DATE)) {
record.put(rs.getMetaData().getColumnName(i), AFCmdBase.jse.newObject((Scriptable) AFCmdBase.jse.getGlobalscope(), "Date", new Object[] { rs.getDate(i).getTime() }));
continue;
}
if((rs.getMetaData().getColumnType(i) == java.sql.Types.TIMESTAMP) ||
(rs.getMetaData().getColumnType(i) == java.sql.Types.TIMESTAMP_WITH_TIMEZONE) ||
(rs.getMetaData().getColumnTypeName(i).equals("TIMESTAMP WITH TIME ZONE"))) {
record.put(rs.getMetaData().getColumnName(i), AFCmdBase.jse.newObject((Scriptable) AFCmdBase.jse.getGlobalscope(), "Date", new Object[] { rs.getTimestamp(i).getTime() }));
continue;
}
if((rs.getMetaData().getColumnType(i) == java.sql.Types.TIME) ||
(rs.getMetaData().getColumnType(i) == java.sql.Types.TIME_WITH_TIMEZONE)) {
record.put(rs.getMetaData().getColumnName(i), AFCmdBase.jse.newObject((Scriptable) AFCmdBase.jse.getGlobalscope(), "Date", new Object[] { rs.getTime(i).getTime() }));
continue;
}
}
if (rs.getObject(i) != null) {
//jsong.writeStringField(rs.getMetaData().getColumnName(i), rs.getObject(i).toString());
record.put(rs.getMetaData().getColumnName(i), rs.getObject(i).toString());
} else {
//jsong.writeStringField(rs.getMetaData().getColumnName(i), null);
record.put(rs.getMetaData().getColumnName(i), null);
}
}
}
records.add(record.getMap());
}
rs.close();
if (!keepStatement) ps.close();
no.put("results", records.getList());
return no.getMap();
} catch (SQLException e) {
throw e;
}
}
return null;
}
/**
* <odoc>
* <key>DB.qLob(aSQL) : Object</key>
* Performs aSQL query on the current DB object instance. It tries to return only the first result set
* row and the first object that can be either a CLOB (returns a string) or a BLOB (byte array). In case
* of error an exception will be thrown.
* </odoc>
*/
public Object qLob(String sql) throws Exception {
if (con != null) {
try {
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
rs.next();
if(rs.getMetaData().getColumnType(1) == java.sql.Types.CLOB) {
StringWriter w = new StringWriter();
try {
InputStream in = rs.getClob(1).getAsciiStream();
IOUtils.copy(in, w, (Charset) null);
} catch(Exception e) {
SimpleLog.log(SimpleLog.logtype.DEBUG, "Problem getting clob", e);
}
return w.toString();
}
if (rs.getMetaData().getColumnType(1) == java.sql.Types.BLOB) {
try {
InputStream in = rs.getBlob(1).getBinaryStream();
return IOUtils.toByteArray(in);
} catch(Exception e) {
SimpleLog.log(SimpleLog.logtype.DEBUG, "Problem getting blob", e);
return null;
}
}
rs.close();
ps.close();
} catch (SQLException e) {
//SimpleLog.log(SimpleLog.logtype.ERROR, "Error executing query " + sql + ": " + e.getMessage(), e);
throw e;
}
}
return null;
}
/**
* <odoc>
* <key>DB.u(aSQL) : Number</key>
* Executes a SQL statement on the current DB object instance. On success it will return
* the number of rows affected. In case of error an exception will be thrown.
* </odoc>
*/
public int u(String sql) throws SQLException {
if (con != null) {
try {
Statement cs = con.createStatement();
int res = cs.executeUpdate(sql);
cs.close();
return res;
} catch (SQLException e) {
//SimpleLog.log(SimpleLog.logtype.ERROR, "Error executing sql " + sql + ": " + e.getMessage(), e);
throw e;
}
}
return -1;
}
/**
* <odoc>
* <key>DB.us(aSQL, anArray, keepStatement) : Number</key>
* Executes a SQL statement on the current DB object instance that can have bind variables that
* can be specified on anArray. On success it will return the number of rows affected. In case of
* error an exception will be thrown. Optionally you can specify to keepStatement (e.g. boolean) to keep from closing
* the prepared statement used for reuse in another us call. If you specify to use keepStatement do close this
* query, as soon as possible, using DB.closeStatement(aQuery) (where you provide an exactly equal statement to
* aQuery) or DB.closeAllStatements.
* </odoc>
*/
public int us(String sql, JSEngine.JSList objs, boolean keepStatement) throws SQLException {
if (con != null) {
try {
PreparedStatement ps = null;
if (preparedStatements.containsKey(sql)) {
ps = preparedStatements.get(sql);
keepStatement = true;
} else {
ps = con.prepareStatement(sql);
if (keepStatement) preparedStatements.put(sql, ps);
}
//if (objs instanceof JSEngine.JSList) {
int i = 0;
for (Object obj : objs ) {
i++;
ps.setObject(i, obj);
}
int res = ps.executeUpdate();
if (!keepStatement) ps.close();
return res;
} catch (SQLException e) {
throw e;
}
}
return -1;
}
/**
* <odoc>
* <key>DB.usArray(aSQL, anArrayOfArrays, aBatchSize, keepStatement) : Number</key>
* Executes, and commits, a batch of a SQL statement on the current DB object instance that can have bind variables that
* can be specified on an array, for each record, as part of anArrayOfArrays. On success it will return the number of rows
* affected. In case of error an exception will be thrown. Optionally you can specify to keepStatement (e.g. boolean) to keep
* from closing the prepared statement used for reuse in another usArray call. If you specify to use keepStatement do close this
* query, as soon as possible, using DB.closeStatement(aQuery) (where you provide an exactly equal statement to
* aQuery) or DB.closeAllStatements. You can also specify aBatchSize (default is 1000) to indicate when a commit
* should be performed while executing aSQL for each array of bind variables in anArrayOfArrays.\
* \
* Example:\
* \
* var values = [ [1,2], [2,2], [3,3], [4,5]];\
* db.usArray("INSERT INTO A (c1, c2) VALUES (?, ?)", values, 2);\
* \
* </odoc>
*/
public int usArray(String sql, JSEngine.JSList objs, int batchSize, boolean keepStatement) throws SQLException {
if (con != null) {
try {
PreparedStatement ps = null;
if (preparedStatements.containsKey(sql)) {
ps = preparedStatements.get(sql);
keepStatement = true;
} else {
ps = con.prepareStatement(sql);
if (keepStatement) preparedStatements.put(sql, ps);
}
int count = 0;
int res = 0;
if (batchSize <= 0) batchSize = 1000;
for(Object obj : objs) {
int i = 0;
for(Object sub : (JSEngine.JSList) obj) {
i++;
ps.setObject(i, sub);
}
ps.addBatch();
if (++count % batchSize == 0) {
int r[] = ps.executeBatch();
for(int j : r) {
res += j;
}
}
}
int r[] = ps.executeBatch();
for(int j : r) {
res += j;
}
if (!keepStatement) ps.close();
return res;
} catch (SQLException e) {
throw e;
}
}
return -1;
}
/**
* <odoc>
* <key>DB.uLob(aSQL, aLOB) : Number</key>
* Executes a SQL statement on the current DB object instance to update a CLOB or BLOB provided
* in aLOB. On success it will return the number of rows affected. In case of error an exception
* will be thrown.
* </odoc>
*/
public int uLob(String sql, Object lob) throws SQLException {
if (con != null) {
try {
PreparedStatement ps = con.prepareStatement(sql);
//Clob clobOut = con.createClob();
if (lob instanceof byte[]) {
ps.setBlob(1, new ByteArrayInputStream((byte []) lob));
} else {
StringReader sw = new StringReader((String) lob);
//IOUtils.copy(sw, clobOut.setAsciiStream(1));
ps.setCharacterStream(1, sw, ((String) lob).length());
//clobOut.free();
}
int res = ps.executeUpdate();
ps.close();
return res;
} catch (SQLException e) {
//SimpleLog.log(SimpleLog.logtype.ERROR, "Error executing sql " + sql + ": " + e.getMessage(), e);
throw e;
}
}
return -1;
}
/**
* <odoc>
* <key>DB.uLobs(aSQL, anArray) : Number</key>
* Executes a SQL statement on the current DB object instance that can have CLOB or BLOB bind
* variables that can be specified on anArray. On success it will return the number of rows
* affected. In case of error an exception will be thrown.
* </odoc>
*/
public int uLobs(String sql, JSEngine.JSList lobs) throws SQLException {
if (con != null) {
try {
PreparedStatement ps = con.prepareStatement(sql);
int i = 0;
for(Object lob : lobs) {
i++;
if (lob instanceof byte[]) {
ps.setBlob(i, new ByteArrayInputStream((byte []) lob));
} else {
StringReader sw = new StringReader((String) lob);
ps.setCharacterStream(i, sw, ((String) lob).length());
}
}
int res = ps.executeUpdate();
ps.close();
return res;
} catch (SQLException e) {
throw e;
}
}
return -1;
}
/**
* <odoc>
* <key>DB.commit()</key>
* Commits to the database the current database session on the current DB object instance.
* In case of error an exception will be thrown.
* </odoc>
*/
public void commit() throws SQLException {
if (con != null) {
try {
con.commit();
} catch (SQLException e) {
SimpleLog.log(SimpleLog.logtype.DEBUG, "Error while commit on " + url + ": " + e.getMessage(), e);
throw e;
}
}
}
/**
* <odoc>
* <key>DB.rollback()</key>
* Rollbacks the current database session on the current DB object instance.
* In case of error an exception will be thrown.
* </odoc>
*/
public void rollback() throws SQLException {
if (con != null) {
try {
con.rollback();
} catch (SQLException e) {
SimpleLog.log(SimpleLog.logtype.ERROR, "Error while rollback on " + url + ": " + e.getMessage(), e);
throw e;
}
}
}
protected void connect(String driver, String url, String login, String pass) throws Exception {
try {
Class.forName(driver);
this.url = url;
Properties props = new Properties();
props.setProperty("user", AFCmdBase.afc.dIP(login));
props.setProperty("password", AFCmdBase.afc.dIP(pass));
con = DriverManager.getConnection(url, props);
con.setAutoCommit(false);
} catch (ClassNotFoundException | SQLException e) {
//SimpleLog.log(SimpleLog.logtype.ERROR, "Error connecting to database " + url + " using " + driver + ": " + e.getMessage(), e);
throw e;
}
}
/**
* <odoc>
* <key>DB.h2StartServer(aPort, aListOfArguments) : String</key>
* Starts a H2 server on aPort (if provided) with an array of arguments (supported options are:
* -tcpPort, -tcpSSL, -tcpPassword, -tcpAllowOthers, -tcpDaemon, -trace, -ifExists, -baseDir, -key).
* After creating the access URL will be returned. In case of error an exception will be thrown.
* </odoc>
*/
public String h2StartServer(int port, JSEngine.JSList args) throws SQLException {
if (port < 0) {
} else {
ArrayList<String> al = new ArrayList<String>();
if (args != null) {
al.add("-tcpPort");
al.add(port + "");
for(Object o : args) {
al.add(o + "");
}
h2Server = Server.createTcpServer((String[]) al.toArray(new String[al.size()])).start();
return h2Server.getURL();
} else {
if(port > 0) {
al.add("-tcpPort");
al.add(port + "");
}
h2Server = Server.createTcpServer((String[]) al.toArray(new String[al.size()])).start();
return h2Server.getURL();
}
}
return "";
}
/**
* <odoc>
* <key>DB.h2StopServer()</key>
* Stops a H2 server started for this DB instance.
* </odoc>
*/
public void h2StopServer() {
h2Server.stop();
}
/**
* <odoc>
* <key>DB.convertDates(aFlag)</key>
* Sets to true or false (defaults to false) the conversion of Dates to javascript Date objects instead of strings.
* </odoc>
*/
public void convertDates(boolean toggle) {
convertDates = toggle;
}
}
|
package alma.acs.component.client;
import java.util.logging.Level;
import junit.framework.TestCase;
import org.omg.CORBA.ORB;
import org.omg.PortableServer.POA;
import si.ijs.maci.Client;
import alma.JavaContainerError.wrappers.AcsJContainerServicesEx;
import alma.acs.concurrent.DaemonThreadFactory;
import alma.acs.container.AcsManagerProxy;
import alma.acs.container.CleaningDaemonThreadFactory;
import alma.acs.container.ContainerServices;
import alma.acs.container.ContainerServicesImpl;
import alma.acs.container.corba.AcsCorba;
import alma.acs.logging.AcsLogger;
import alma.acs.logging.ClientLogManager;
import alma.acs.logging.engine.LogReceiver;
import alma.acs.util.ACSPorts;
import alma.alarmsystem.source.ACSAlarmSystemInterfaceFactory;
/**
* Base class for writing JUnit test clients for ACS components.
* Takes care of the communication with the ACS manager (local or provided in property <code>ACS.manager</code>).
*
* Provides the {@link ContainerServices}.
*
* @author hsommer Nov 21, 2002 5:53:05 PM
*/
public class ComponentClientTestCase extends TestCase
{
protected AcsCorba acsCorba;
private ContainerServicesImpl m_containerServices;
/**
* The thread factory used by <code>m_containerServices</code>.
*/
private CleaningDaemonThreadFactory m_threadFactory;
/**
* Special tests that need to call directly the manager API could use this proxy object.
* To be used sparingly, as we need to exercise (and extend if necessary) the regular
* classes such as ContainerServices.
*/
protected AcsManagerProxy m_acsManagerProxy;
protected AcsLogger m_logger;
private LogReceiver logReceiver;
/** from property ACS.manager, or defaults to localhost */
protected String m_managerLoc;
// manager client object
private ManagerClient managerClientImpl;
private Client m_managerClient;
private String m_namePrefix;
/**
* Subclasses must call this ctor.
* @param name the name used for the test case, and to talk with the ACS manager
* @throws Exception
*/
public ComponentClientTestCase(String name) throws Exception
{
super(name);
m_namePrefix = name;
}
/**
* Executes a single test method.
* Stray exceptions are logged using the test logger, so that they show in system logs.
* @see junit.framework.TestCase#runTest()
* @since ACS 6.0
*/
protected void runTest() throws Throwable {
try {
super.runTest();
}
catch (Throwable thr) {
if (m_logger != null) {
m_logger.log(Level.WARNING, "JUnit test error in " + getFullName(), thr);
}
throw thr;
}
}
/**
* Starts CORBA in the client process and connects to the manager and logger.
* <p>
* <b>Subclasses that override this method must call <code>super.setUp()</code>,
* likely before any other code in that method.</b>
*
* @see junit.framework.TestCase#setUp()
*/
protected void setUp() throws Exception
{
m_logger = ClientLogManager.getAcsLogManager().getLoggerForApplication(getFullName(), true);
m_logger.info("
m_logger.info("ComponentClientTestCase#setUp()");
POA rootPOA = null;
try
{
acsCorba = new AcsCorba(m_logger);
rootPOA = acsCorba.initCorbaForClient(false);
connectToManager();
m_threadFactory = new CleaningDaemonThreadFactory(m_namePrefix, m_logger);
m_containerServices = new ContainerServicesImpl(m_acsManagerProxy, rootPOA, acsCorba,
m_logger, m_acsManagerProxy.getManagerHandle(),
this.getClass().getName(), null, m_threadFactory) {
public AcsLogger getLogger() {
return m_logger;
}
};
managerClientImpl.setContainerServices(m_containerServices);
initRemoteLogging();
ACSAlarmSystemInterfaceFactory.init(m_containerServices);
}
catch (Exception ex1)
{
m_logger.log(Level.SEVERE, "failed to initialize the ORB, or connect to the ACS Manager, " +
"or to set up the container services.", ex1);
if (acsCorba != null) {
try {
acsCorba.shutdownORB(true, false);
acsCorba.doneCorba();
} catch (Exception ex2) {
// to JUnit we want to forward the original exception ex1,
// not any other exception from cleaning up the orb
// which we would not have done without the first exception.
// Thus we simply print ex2 but let ex1 fly
ex2.printStackTrace();
}
}
throw ex1;
}
}
/**
* Connects to the ACS Manager using {@link AcsManagerProxy}.
* @throws Exception
*/
protected void connectToManager() throws Exception
{
if (System.getProperty("ACS.manager") != null) {
m_managerLoc = System.getProperty("ACS.manager").trim();
}
else {
// default = localhost
String host = ACSPorts.getIP();
m_managerLoc = "corbaloc::" + host + ":" + ACSPorts.getManagerPort() + "/Manager";
}
managerClientImpl = new ManagerClient(getFullName(), m_logger)
{
public void disconnect()
{
m_logger.info("disconnected from manager");
m_acsManagerProxy.logoutFromManager();
m_acsManagerProxy = null;
throw new RuntimeException("disconnected from the manager");
}
};
ORB orb = acsCorba.getORB();
m_managerClient = managerClientImpl._this(orb);
m_acsManagerProxy = new AcsManagerProxy(m_managerLoc, orb, m_logger);
m_acsManagerProxy.loginToManager(m_managerClient, false);
}
protected String getFullName() {
String fullName = m_namePrefix + "#" + getName();
return fullName;
}
/**
* Gives access to the {@link ContainerServices} interface.
* This class plays the part of the role of the Java container that has to do with
* providing explicit services to the component, or test case respectively.
* <p>
*
* @return ContainerServices
*/
protected ContainerServices getContainerServices()
{
return m_containerServices;
}
/**
* Releases all previously obtained components (using manager), logs out from the manager,
* and terminates the CORBA ORB.
* <p>
* <b>Subclasses that override this method must call <code>super.tearDown()</code>, likely after any other code in that method.</b>
*
* @see junit.framework.TestCase#tearDown()
*/
protected void tearDown() throws Exception {
try {
m_acsManagerProxy.shutdownNotify();
m_containerServices.releaseAllComponents();
if (logReceiver != null && logReceiver.isInitialized()) {
logReceiver.stop();
}
m_acsManagerProxy.logoutFromManager();
ClientLogManager.getAcsLogManager().shutdown(true);
}
catch (Exception e) {
System.err.println("Exception in tearDown: ");
e.printStackTrace(System.err);
throw e;
}
finally {
ACSAlarmSystemInterfaceFactory.done();
m_containerServices.cleanUp();
m_threadFactory.cleanUp();
if (acsCorba != null) {
// @todo investigate COMP-2632 which happened here.
// Check if the wait_for_completion is buggy and returns too early.
// Then the overlapping call to doneCorba() ( -> orb.destroy()) would block this thread,
// and with bad timing luck it could block *after* the first shutdown called "shutdown_synch.notifyAll()"
// in ORB#shutdown, which could explain that the main thread hangs there forever.
acsCorba.shutdownORB(true, false);
// as a workaround for this problem, for now we run this async with a timeout
Thread destroyThread = (new DaemonThreadFactory("OrbDestroy")).newThread(new Runnable() {
public void run() {
acsCorba.doneCorba();
}
});
destroyThread.start();
destroyThread.join(20000);
}
// just in case... should give the OS time to reclaim ORB ports and so on
Thread.sleep(1000);
}
}
/**
* Sets up the test client logger(s) to send log records to the remote log service.
* Only one attempt to connect to the remote logger is made.
* If it fails, remote logging will be disabled.
* <p>
* Override this method to prevent remote logging.
*/
protected void initRemoteLogging()
{
String errMsg = null;
try {
if (!ClientLogManager.getAcsLogManager().initRemoteLogging(acsCorba.getORB(),
m_acsManagerProxy.getManager(), m_acsManagerProxy.getManagerHandle(), false) ) {
errMsg = "ACS central logging not available. ";
}
}
catch (Throwable thr) {
errMsg = "ACS central logging not available. Failed with unexpected error " + thr.toString();
}
if (errMsg != null) {
// if we can't get remote logging, then we disable it (saves memory to not add to the log record queue)
ClientLogManager.getAcsLogManager().suppressRemoteLogging();
m_logger.warning(errMsg);
}
}
/**
* Gets a {@link LogReceiver} which can be used
* to verify log messages from both local and remote processes.
* The returned <code>LogReceiver</code> is already initialized.
* If initialization fails, an exception is thrown.
* <p>
* To receive logs from the log service, use either
* {@link LogReceiver#getLogQueue()} or {@link LogReceiver#startCaptureLogs(java.io.PrintWriter)}.
*
* @throws AcsJContainerServicesEx if the LogReceiver fails to initialize within 20 seconds.
*/
protected LogReceiver getLogReceiver() throws AcsJContainerServicesEx {
if (logReceiver == null) {
boolean initOk = false;
try {
logReceiver = new LogReceiver();
// logReceiver.setVerbose(true);
initOk = logReceiver.initialize(acsCorba.getORB(), m_acsManagerProxy.getManager(), 20);
}
catch (Throwable thr) {
AcsJContainerServicesEx ex = new AcsJContainerServicesEx(thr);
ex.setContextInfo("Failed to obtain an initialized LogReceiver.");
throw ex;
}
if (!initOk) {
AcsJContainerServicesEx ex = new AcsJContainerServicesEx();
ex.setContextInfo("LogReceiver failed to initialize within 20 seconds.");
throw ex;
}
}
return logReceiver;
}
}
|
package com.lambeta;
import com.google.common.base.*;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import com.google.common.primitives.Chars;
import java.math.BigDecimal;
import java.text.Normalizer;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.google.common.base.Joiner.on;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Predicates.not;
import static com.google.common.base.Splitter.fixedLength;
import static com.google.common.base.Strings.isNullOrEmpty;
import static com.google.common.base.Strings.nullToEmpty;
import static com.google.common.collect.FluentIterable.from;
import static com.google.common.collect.Iterables.toArray;
import static java.lang.String.format;
public class UnderscoreString {
private static final String UPPER_UPPER_LOWER_CASE = "(\\p{Upper})(\\p{Upper}[\\p{Lower}0-9])";
private static final String LOWER_UPPER_CASE = "(\\p{Lower})(\\p{Upper})";
public static String capitalize(String word) {
return onCapitalize(word, true);
}
private static String onCapitalize(String word, boolean on) {
String trimWord = word.trim();
return trimWord.isEmpty()
? trimWord
: String.valueOf(on ? Ascii.toUpperCase(trimWord.charAt(0)) : Ascii.toLowerCase(trimWord.charAt(0))) +
trimWord.substring(1);
}
public static String slugify(String s) {
return trim(dasherize(toAscii(CharMatcher.JAVA_LETTER.negate().replaceFrom(nullToEmpty(s), "-"))), "-");
}
private static String toAscii(String str) {
return stripAccents(str).replaceAll("ß", "ss");
}
public static String trim(String word, String match) {
return CharMatcher.anyOf(match).trimFrom(word);
}
public static String trim(String word) {
return CharMatcher.WHITESPACE.trimFrom(word);
}
public static String ltrim(String word) {
return CharMatcher.WHITESPACE.trimLeadingFrom(word);
}
public static String ltrim(String word, String match) {
return CharMatcher.anyOf(match).trimLeadingFrom(word);
}
public static String rtrim(String word) {
return CharMatcher.WHITESPACE.trimTrailingFrom(word);
}
public static String rtrim(String word, String match) {
return CharMatcher.anyOf(match).trimTrailingFrom(word);
}
public static String repeat(String word) {
return repeat(word, 0);
}
public static String repeat(String word, int count) {
return Strings.repeat(word, count);
}
public static <T> String repeat(String word, int count, T insert) {
String repeat = repeat(word + insert, count);
return repeat.substring(0, repeat.length() - insert.toString().length());
}
public static String decapitalize(String word) {
return onCapitalize(word, false);
}
public static String join(String... args) {
return on("").skipNulls().join(args);
}
public static String reverse(String word) {
return new StringBuilder(word).reverse().toString();
}
public static String clean(String word) {
return collapseWhitespaces(trim(word));
}
public static String[] chop(String word, int fixedLength) {
Preconditions.checkArgument(fixedLength >= 0, "fixedLength must greater than or equal to zero");
if (fixedLength == 0) return new String[]{word};
return toArray(fixedLength(fixedLength).split(word), String.class);
}
public static String splice(String word, int start, int length, String replacement) {
return new StringBuilder(word).replace(start, start + length, replacement).toString();
}
public static char pred(char ch) {
return (char) (ch - 1);
}
public static char succ(char ch) {
return (char) (ch + 1);
}
public static String titleize(String sentence) {
String trimedSentence = trim(sentence);
StringBuilder sb = new StringBuilder();
int length = trimedSentence.length();
boolean capitalizeNext = true;
for (int i = 0; i < length; i++) {
char c = trimedSentence.charAt(i);
if (CharMatcher.anyOf("_- ").matches(c)) {
sb.append(c);
capitalizeNext = true;
} else if (capitalizeNext) {
sb.append(Character.toTitleCase(c));
capitalizeNext = false;
} else {
sb.append(Character.toLowerCase(c));
}
}
return sb.toString();
}
public static String camelize(String sentence) {
return CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, CharMatcher.anyOf("- ").collapseFrom(trim(sentence), '_'));
}
public static String dasherize(String sentence) {
String to = CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_HYPHEN, CharMatcher.WHITESPACE.collapseFrom(trim(upperUnderscored(sentence)), '-'));
return cleanBy(to, '-');
}
public static String underscored(String sentence) {
String to = CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_UNDERSCORE, CharMatcher.anyOf("- ").collapseFrom((upperUnderscored(trim(sentence))), '_'));
return cleanBy(to, '_');
}
public static String classify(String sentence) {
return capitalize(camelize(sentence));
}
public static String humanize(String sentence) {
return capitalize(replace(underscored(sentence), '_', ' '));
}
public static String surround(String word, String wrap) {
return format("%s%s%s", wrap, word, wrap);
}
public static String quote(String word) {
return surround(word, "\"");
}
public static String unquote(String word) {
return unquote(word, '"');
}
public static String unquote(String word, char match) {
if (word.charAt(0) == match && word.charAt(word.length() - 1) == match) {
return word.substring(1, word.length() - 1);
}
return word;
}
public static String numberFormat(double number) {
return numberFormat(number, 0);
}
public static String numberFormat(double number, int scale) {
return NumberFormat.getInstance().format(new BigDecimal(number).setScale(scale, 3));
}
public static String strRight(String sentence, String separator) {
return sentence.substring(sentence.indexOf(separator) + separator.length());
}
public static String strRightBack(String sentence, String separator) {
if (isNullOrEmpty(separator)) {
return sentence;
}
return sentence.substring(sentence.lastIndexOf(separator) + separator.length());
}
public static String strLeft(String sentence, String separator) {
if (isNullOrEmpty(separator)) {
return sentence;
}
return strLeftFrom(sentence, sentence.indexOf(separator));
}
public static String strLeftBack(String sentence, String separator) {
return strLeftFrom(sentence, sentence.lastIndexOf(separator));
}
private static String strLeftFrom(String sentence, int index) {
return index != -1 ? sentence.substring(0, index) : sentence;
}
private static String cleanBy(String to, char separator) {
return CharMatcher.anyOf(String.valueOf(separator)).collapseFrom(to, separator);
}
private static String replace(String sentence, char from, char to) {
return CharMatcher.anyOf(String.valueOf(from)).replaceFrom(sentence, to);
}
private static String upperUnderscored(String sentence) {
return on('_').join(sentence.replaceAll(UPPER_UPPER_LOWER_CASE, "$1 $2").replaceAll(LOWER_UPPER_CASE, "$1 $2").split(" "));
}
public static String toSentence(String[] strings) {
checkNotNull(strings, "words should not be null");
String lastOne = strings[strings.length - 1];
strings[strings.length - 1] = null;
return on(", ").skipNulls().join(strings) + " and " + lastOne;
}
public static int count(String sentence, String find) {
int nonReplacedLength = sentence.length();
int length = sentence.replace(find, "").length();
return (nonReplacedLength - length) / find.length();
}
public static String truncate(String sentence, int position, String pad) {
checkState(sentence.length() >= position);
return splice(sentence, position, sentence.length() - position + 1, pad);
}
public static String lpad(String sentence, int count) {
return lpad(sentence, count, ' ');
}
public static String lpad(String sentence, int count, char ch) {
return Strings.padStart(sentence, count, ch);
}
public static String rpad(String sentence, int count) {
return rpad(sentence, count, ' ');
}
public static String rpad(String sentence, int count, char ch) {
return Strings.padEnd(sentence, count, ch);
}
public static String lrpad(String sentence, int count) {
return lrpad(sentence, count, ' ');
}
public static String lrpad(String sentence, int count, char ch) {
int padEnd = (count - sentence.length()) / 2;
return rpad(lpad(sentence, count - padEnd, ch), count, ch);
}
public static String[] words(String sentence) {
return Iterables.toArray(Splitter.on(CharMatcher.WHITESPACE).split(CharMatcher.anyOf(" _-").collapseFrom(sentence, ' ')), String.class);
}
public static String prune(String sentence, int count) {
if (sentence.length() <= count) {
return sentence;
}
String[] words = words(sentence);
if (words.length == 1) {
return sentence;
}
int rest = count;
for (int i = 0; i < words.length; i++) {
rest = i == 0 ? rest - words[i].length() : rest - words[i].length() - 1;//backspace
if (rest < 0) {
if (i == 0) {
return rtrim(words[i], ",") + "...";
}
words[i - 1] = rtrim(words[i - 1], ",") + "...";
String[] target = new String[i];
System.arraycopy(words, 0, target, 0, i);
return on(' ').join(target);
}
}
return sentence;
}
public static boolean isBlank(String s) {
return Strings.isNullOrEmpty(s) || CharMatcher.WHITESPACE.matchesAllOf(s);
}
public static String replaceAll(String str, String find, String replace) {
return replaceAll(str, find, replace, false);
}
public static String replaceAll(String str, String find, String replace, boolean ignorecase) {
String findRegex = ignorecase ? "(?i)" + find : find;
return Pattern.compile(findRegex).matcher(nullToEmpty(str)).replaceAll(replace);
}
public static String swapCase(String str) {
List<Character> chars = Chars.asList(nullToEmpty(str).toCharArray());
return from(chars).transform(flip()).join(on(""));
}
private static Function<Character, String> flip() {
return new Function<Character, String>() {
@Override
public String apply(Character ch) {
if ('ß' == ch) return "SS";
return (Character.isUpperCase(ch) ? Character.toLowerCase(ch) : Character.toUpperCase(ch)) + "";
}
};
}
public static int naturalCmp(String str0, String str1) {
if (str0 == null) {
return -1;
}
if (str1 == null) {
return 1;
}
if (str0.equals(str1)) {
return 0;
}
Pattern numberRegex = Pattern.compile("(\\.\\d+|\\d+|\\D+)");
String[] token0 = reseq(numberRegex.matcher(str0));
String[] token1 = reseq(numberRegex.matcher(str1));
int minSize = Math.min(token0.length, token1.length);
for (int i = 0; i < minSize; i++) {
String a = token0[i];
String b = token1[i];
if (!a.equals(b)) {
double num0, num1;
try {
num0 = Double.parseDouble(a);
num1 = Double.parseDouble(b);
return num0 > num1 ? 1 : -1;
} catch (NumberFormatException e) {
return a.compareTo(b) > 0 ? 1 : -1;
}
}
}
if (token0.length != token1.length) {
return token0.length > token1.length ? 1 : -1;
}
return str0.compareTo(str1) > 0 ? 1 : -1;
}
private static String[] reseq(Matcher matcher) {
ArrayList<String> tokens = new ArrayList<>();
while (matcher.find()) {
tokens.add(matcher.group());
}
return tokens.toArray(new String[tokens.size()]);
}
public static String dedent(String str0) {
String str = nullToEmpty(str0);
return Pattern.compile(format("^[ \\t]{%d}", indent(str)), Pattern.MULTILINE).matcher(str).replaceAll("");
}
private static int indent(String str) {
if (Strings.isNullOrEmpty(str)) {
return 0;
}
String[] reseq = reseq(Pattern.compile("^[\\s\\t]*", Pattern.MULTILINE).matcher(str));
int indent = reseq[0].length();
for (int i = 1; i < reseq.length; i++) {
indent = Math.min(reseq[i].length(), indent);
}
return indent;
}
public static String commonPrefix(String s, String s1) {
return Strings.commonPrefix(s, s1);
}
public static String commonPrefix(String s, String s1, boolean ignoreCase) {
return ignoreCase ? s1.substring(0, commonPrefix(s.toLowerCase(), s1.toLowerCase()).length()) : commonPrefix(s, s1);
}
public static String commonSuffix(String s, String s1) {
return Strings.commonSuffix(s, s1);
}
public static String commonSuffix(String s, String s1, boolean ignoreCase) {
return ignoreCase ? s1.substring(s1.length() - commonSuffix(s.toLowerCase(), s1.toLowerCase()).length()) : commonSuffix(s, s1);
}
public static String chopPrefix(String s, String prefix) {
return s.startsWith(prefix) ? s.substring(prefix.length()) : s;
}
public static String chopPrefix(String s, String prefix, boolean ignoreCase) {
boolean prefixIgnoreCase = ignoreCase && s.toLowerCase().startsWith(prefix.toLowerCase());
return prefixIgnoreCase ? s.substring(prefix.length()) : chopPrefix(s, prefix);
}
public static String chopSuffix(String s, String suffix) {
return s.endsWith(suffix) ? s.substring(0, s.length() - suffix.length()) : s;
}
public static String chopSuffix(String s, String suffix, boolean ignoreCase) {
boolean suffixIgnoreCase = ignoreCase && s.toLowerCase().endsWith(suffix.toLowerCase());
return suffixIgnoreCase ? s.substring(0, s.length() - suffix.length()) : chopSuffix(s, suffix);
}
public static String screamingUnderscored(String s) {
return underscored(s).toUpperCase();
}
public static String stripAccents(String s) {
return Normalizer.normalize(s, Normalizer.Form.NFD).replaceAll("\\p{InCOMBINING_DIACRITICAL_MARKS}+", "");
}
public static String pascalize(String s) {
return titleize(underscored(s)).replace("_", "");
}
public static String translate(String str, HashMap<Character, Character> dictionary) {
return translate(str, dictionary, Sets.<Character>newHashSet());
}
public static String translate(String str, HashMap<Character, Character> dictionary, HashSet<Character> deletedChars) {
List<Character> chars = Chars.asList(nullToEmpty(str).toCharArray());
return from(chars).filter(without(deletedChars)).transform(in(dictionary)).filter(without(new HashSet<Character>(){{add(null);}})).join(on(""));
}
private static Function<Character, Character> in(final HashMap<Character, Character> dictionary) {
return new Function<Character, Character>() {
@Override
public Character apply(Character c) {
return dictionary.containsKey(c) ? dictionary.get(c) : c;
}
};
}
private static Predicate<Character> without(final HashSet<Character> deletedChars) {
return not(new Predicate<Character>() {
@Override
public boolean apply(Character c) {
return deletedChars.contains(c);
}
});
}
public static Optional<String> mixedCase(String s) {
boolean isMixedCase = CharMatcher.JAVA_LOWER_CASE.matchesAnyOf(s) && CharMatcher.JAVA_UPPER_CASE.matchesAnyOf(s);
return isMixedCase ? Optional.of(s) : Optional.<String>absent();
}
public static String collapseWhitespaces(String s) {
return CharMatcher.WHITESPACE.collapseFrom(s, ' ');
}
}
|
package org.joni;
import static org.joni.BitStatus.bsAt;
import static org.joni.Option.isCaptureGroup;
import static org.joni.Option.isDontCaptureGroup;
import java.util.Collections;
import java.util.Iterator;
import org.jcodings.Encoding;
import org.jcodings.specific.ASCIIEncoding;
import org.jcodings.specific.UTF8Encoding;
import org.jcodings.util.BytesHash;
import org.joni.constants.AnchorType;
import org.joni.exception.ErrorMessages;
import org.joni.exception.InternalException;
import org.joni.exception.ValueException;
public final class Regex {
int[] code; /* compiled pattern */
int codeLength;
boolean requireStack;
int numMem; /* used memory(...) num counted from 1 */
int numRepeat; /* OP_REPEAT/OP_REPEAT_NG id-counter */
int numNullCheck; /* OP_NULL_CHECK_START/END id counter */
int numCombExpCheck; /* combination explosion check */
int numCall; /* number of subexp call */
int captureHistory; /* (?@...) flag (1-31) */
int btMemStart; /* need backtrack flag */
int btMemEnd; /* need backtrack flag */
int stackPopLevel;
int[]repeatRangeLo;
int[]repeatRangeHi;
MatcherFactory factory;
final Encoding enc;
int options;
int userOptions;
Object userObject;
final int caseFoldFlag;
private BytesHash<NameEntry> nameTable; // named entries
/* optimization info (string search, char-map and anchors) */
SearchAlgorithm searchAlgorithm; /* optimize flag */
int thresholdLength; /* search str-length for apply optimize */
int anchor; /* BEGIN_BUF, BEGIN_POS, (SEMI_)END_BUF */
int anchorDmin; /* (SEMI_)END_BUF anchor distance */
int anchorDmax; /* (SEMI_)END_BUF anchor distance */
int subAnchor; /* start-anchor for exact or map */
byte[]exact;
int exactP;
int exactEnd;
byte[]map; /* used as BM skip or char-map */
int[]intMap; /* BM skip for exact_len > 255 */
int[]intMapBackward; /* BM skip for backward search */
int dMin; /* min-distance of exact or map */
int dMax; /* max-distance of exact or map */
byte[][]templates; /* fixed pattern strings not embedded in bytecode */
int templateNum;
public Regex(CharSequence cs) {
this(cs.toString());
}
public Regex(CharSequence cs, Encoding enc) {
this(cs.toString(), enc);
}
public Regex(String str) {
this(str.getBytes(), 0, str.length(), 0, UTF8Encoding.INSTANCE);
}
public Regex(String str, Encoding enc) {
this(str.getBytes(), 0, str.length(), 0, enc);
}
public Regex(byte[] bytes) {
this(bytes, 0, bytes.length, 0, ASCIIEncoding.INSTANCE);
}
public Regex(byte[] bytes, int p, int end) {
this(bytes, p, end, 0, ASCIIEncoding.INSTANCE);
}
public Regex(byte[] bytes, int p, int end, int option) {
this(bytes, p, end, option, ASCIIEncoding.INSTANCE);
}
public Regex(byte[]bytes, int p, int end, int option, Encoding enc) {
this(bytes, p, end, option, enc, Syntax.RUBY, WarnCallback.DEFAULT);
}
// onig_new
public Regex(byte[]bytes, int p, int end, int option, Encoding enc, Syntax syntax) {
this(bytes, p, end, option, Config.ENC_CASE_FOLD_DEFAULT, enc, syntax, WarnCallback.DEFAULT);
}
public Regex(byte[]bytes, int p, int end, int option, Encoding enc, WarnCallback warnings) {
this(bytes, p, end, option, enc, Syntax.RUBY, warnings);
}
// onig_new
public Regex(byte[]bytes, int p, int end, int option, Encoding enc, Syntax syntax, WarnCallback warnings) {
this(bytes, p, end, option, Config.ENC_CASE_FOLD_DEFAULT, enc, syntax, warnings);
}
// onig_alloc_init
public Regex(byte[]bytes, int p, int end, int option, int caseFoldFlag, Encoding enc, Syntax syntax, WarnCallback warnings) {
if ((option & (Option.DONT_CAPTURE_GROUP | Option.CAPTURE_GROUP)) ==
(Option.DONT_CAPTURE_GROUP | Option.CAPTURE_GROUP)) {
throw new ValueException(ErrorMessages.INVALID_COMBINATION_OF_OPTIONS);
}
if ((option & Option.NEGATE_SINGLELINE) != 0) {
option |= syntax.options;
option &= ~Option.SINGLELINE;
} else {
option |= syntax.options;
}
this.enc = enc;
this.options = option;
this.caseFoldFlag = caseFoldFlag;
new Analyser(this, syntax, bytes, p, end, warnings).compile();
}
public Matcher matcher(byte[]bytes) {
return matcher(bytes, 0, bytes.length);
}
public Matcher matcherNoRegion(byte[]bytes) {
return matcherNoRegion(bytes, 0, bytes.length);
}
public Matcher matcher(byte[]bytes, int p, int end) {
return factory.create(this, numMem == 0 ? null : new Region(numMem + 1), bytes, p, end);
}
public Matcher matcherNoRegion(byte[]bytes, int p, int end) {
return factory.create(this, null, bytes, p, end);
}
public int numberOfCaptures() {
return numMem;
}
public int numberOfCaptureHistories() {
if (Config.USE_CAPTURE_HISTORY) {
int n = 0;
for (int i=0; i<=Config.MAX_CAPTURE_HISTORY_GROUP; i++) {
if (bsAt(captureHistory, i)) n++;
}
return n;
} else {
return 0;
}
}
private NameEntry nameFind(byte[]name, int nameP, int nameEnd) {
if (nameTable != null) return nameTable.get(name, nameP, nameEnd);
return null;
}
void renumberNameTable(int[]map) {
if (nameTable != null) {
for (NameEntry e : nameTable) {
if (e.backNum > 1) {
for (int i=0; i<e.backNum; i++) {
e.backRefs[i] = map[e.backRefs[i]];
}
} else if (e.backNum == 1) {
e.backRef1 = map[e.backRef1];
}
}
}
}
void nameAdd(byte[]name, int nameP, int nameEnd, int backRef, Syntax syntax) {
if (nameEnd - nameP <= 0) throw new ValueException(ErrorMessages.EMPTY_GROUP_NAME);
NameEntry e = null;
if (nameTable == null) {
nameTable = new BytesHash<NameEntry>(); // 13, oni defaults to 5
} else {
e = nameFind(name, nameP, nameEnd);
}
if (e == null) {
// dup the name here as oni does ?, what for ? (it has to manage it, we don't)
e = new NameEntry(name, nameP, nameEnd);
nameTable.putDirect(name, nameP, nameEnd, e);
} else if (e.backNum >= 1 && !syntax.allowMultiplexDefinitionName()) {
throw new ValueException(ErrorMessages.MULTIPLEX_DEFINED_NAME, new String(name, nameP, nameEnd - nameP));
}
e.addBackref(backRef);
}
NameEntry nameToGroupNumbers(byte[]name, int nameP, int nameEnd) {
return nameFind(name, nameP, nameEnd);
}
public int nameToBackrefNumber(byte[]name, int nameP, int nameEnd, Region region) {
NameEntry e = nameToGroupNumbers(name, nameP, nameEnd);
if (e == null) throw new ValueException(ErrorMessages.UNDEFINED_NAME_REFERENCE,
new String(name, nameP, nameEnd - nameP));
switch(e.backNum) {
case 0:
throw new InternalException(ErrorMessages.PARSER_BUG);
case 1:
return e.backRef1;
default:
if (region != null) {
for (int i = e.backNum - 1; i >= 0; i
if (region.beg[e.backRefs[i]] != Region.REGION_NOTPOS) return e.backRefs[i];
}
}
return e.backRefs[e.backNum - 1];
}
}
String nameTableToString() {
StringBuilder sb = new StringBuilder();
if (nameTable != null) {
sb.append("name table\n");
for (NameEntry ne : nameTable) {
sb.append(" " + ne + "\n");
}
sb.append("\n");
}
return sb.toString();
}
public Iterator<NameEntry> namedBackrefIterator() {
return nameTable == null ? Collections.<NameEntry>emptyIterator() : nameTable.iterator();
}
public int numberOfNames() {
return nameTable == null ? 0 : nameTable.size();
}
public boolean noNameGroupIsActive(Syntax syntax) {
if (isDontCaptureGroup(options)) return false;
if (Config.USE_NAMED_GROUP) {
if (numberOfNames() > 0 && syntax.captureOnlyNamedGroup() && !isCaptureGroup(options)) return false;
}
return true;
}
/* set skip map for Boyer-Moor search */
void setupBMSkipMap() {
byte[]bytes = exact;
int p = exactP;
int end = exactEnd;
int len = end - p;
if (len < Config.CHAR_TABLE_SIZE) {
// map/skip
if (map == null) map = new byte[Config.CHAR_TABLE_SIZE];
for (int i=0; i<Config.CHAR_TABLE_SIZE; i++) map[i] = (byte)len;
for (int i=0; i<len-1; i++) map[bytes[p + i] & 0xff] = (byte)(len - 1 -i); // oxff ??
} else {
if (intMap == null) intMap = new int[Config.CHAR_TABLE_SIZE];
for (int i=0; i<len-1; i++) intMap[bytes[p + i] & 0xff] = len - 1 - i; // oxff ??
}
}
void setExactInfo(OptExactInfo e) {
if (e.length == 0) return;
// shall we copy that ?
exact = e.bytes;
exactP = 0;
exactEnd = e.length;
if (e.ignoreCase > 0) {
// encodings won't return toLowerTable for case insensitive search if it's not safe to use it directly
searchAlgorithm = enc.toLowerCaseTable() != null ? SearchAlgorithm.SLOW_IC_SB : SearchAlgorithm.SLOW_IC;
} else {
boolean allowReverse = enc.isReverseMatchAllowed(exact, exactP, exactEnd);
if (e.length >= 3 || (e.length >= 2 && allowReverse)) {
setupBMSkipMap();
if (allowReverse) {
searchAlgorithm = SearchAlgorithm.BM;
} else {
searchAlgorithm = SearchAlgorithm.BM_NOT_REV;
}
} else {
searchAlgorithm = enc.isSingleByte() ? SearchAlgorithm.SLOW_SB : SearchAlgorithm.SLOW;
}
}
dMin = e.mmd.min;
dMax = e.mmd.max;
if (dMin != MinMaxLen.INFINITE_DISTANCE) {
thresholdLength = dMin + (exactEnd - exactP);
}
}
void setOptimizeMapInfo(OptMapInfo m) {
map = m.map;
searchAlgorithm = enc.isSingleByte() ? SearchAlgorithm.MAP_SB : SearchAlgorithm.MAP;
dMin = m.mmd.min;
dMax = m.mmd.max;
if (dMin != MinMaxLen.INFINITE_DISTANCE) {
thresholdLength = dMin + 1;
}
}
void setSubAnchor(OptAnchorInfo anc) {
subAnchor |= anc.leftAnchor & AnchorType.BEGIN_LINE;
subAnchor |= anc.rightAnchor & AnchorType.END_LINE;
}
void clearOptimizeInfo() {
searchAlgorithm = SearchAlgorithm.NONE;
anchor = 0;
anchorDmax = 0;
anchorDmin = 0;
subAnchor = 0;
exact = null;
exactP = exactEnd = 0;
}
public String optimizeInfoToString() {
String s = "";
s += "optimize: " + searchAlgorithm.getName() + "\n";
s += " anchor: " + OptAnchorInfo.anchorToString(anchor);
if ((anchor & AnchorType.END_BUF_MASK) != 0) {
s += MinMaxLen.distanceRangeToString(anchorDmin, anchorDmax);
}
s += "\n";
if (searchAlgorithm != SearchAlgorithm.NONE) {
s += " sub anchor: " + OptAnchorInfo.anchorToString(subAnchor) + "\n";
}
s += "dmin: " + dMin + " dmax: " + dMax + "\n";
s += "threshold length: " + thresholdLength + "\n";
if (exact != null) {
s += "exact: [" + new String(exact, exactP, exactEnd - exactP) + "]: length: " + (exactEnd - exactP) + "\n";
} else if (searchAlgorithm == SearchAlgorithm.MAP || searchAlgorithm == SearchAlgorithm.MAP_SB) {
int n=0;
for (int i=0; i<Config.CHAR_TABLE_SIZE; i++) if (map[i] != 0) n++;
s += "map: n = " + n + "\n";
if (n > 0) {
int c=0;
s += "[";
for (int i=0; i<Config.CHAR_TABLE_SIZE; i++) {
if (map[i] != 0) {
if (c > 0) s += ", ";
c++;
if (enc.maxLength() == 1 && enc.isPrint(i)) s += ((char)i);
else s += i;
}
}
s += "]\n";
}
}
return s;
}
public Encoding getEncoding() {
return enc;
}
public int getOptions() {
return options;
}
public void setUserOptions(int options) {
this.userOptions = options;
}
public int getUserOptions() {
return userOptions;
}
public void setUserObject(Object object) {
this.userObject = object;
}
public Object getUserObject() {
return userObject;
}
}
|
package nl.fontys.sofa.limo.view.custom;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import nl.fontys.sofa.limo.api.dao.ProcedureCategoryDAO;
import nl.fontys.sofa.limo.domain.component.procedure.Procedure;
import nl.fontys.sofa.limo.domain.component.procedure.ProcedureCategory;
import nl.fontys.sofa.limo.domain.component.procedure.ProcedureResponsibilityDirection;
import nl.fontys.sofa.limo.domain.component.procedure.TimeType;
import nl.fontys.sofa.limo.domain.component.procedure.value.RangeValue;
import nl.fontys.sofa.limo.domain.component.procedure.value.SingleValue;
import nl.fontys.sofa.limo.domain.component.procedure.value.Value;
import nl.fontys.sofa.limo.view.custom.table.DragNDropTable;
import nl.fontys.sofa.limo.view.custom.table.DragNDropTableModel;
import org.openide.util.Lookup;
public class ProcedureComponent extends JPanel implements ActionListener, MouseListener {
private DragNDropTable table;
private DragNDropTableModel model;
private JButton btn_add, btn_delete;
private JScrollPane sc_pane;
private ProcedureCategoryDAO procedureCategoryDao = Lookup.getDefault().lookup(ProcedureCategoryDAO.class);
private Value changedValue;
CellConstraints cc;
public ProcedureComponent() {
this(null);
}
public ProcedureComponent(List<Procedure> procedures) {
//LAYOUT
cc = new CellConstraints();
FormLayout layout = new FormLayout("5px, pref:grow, 5px, pref, 5px", "5px, pref, 10px, pref, pref:grow, 5px");
this.setLayout(layout);
//TABLEMODEL
List<List<Object>> valueList = new ArrayList<>();
if (procedures != null) {
for (Procedure p : procedures) {
ArrayList<Object> values = new ArrayList<>();
values.add(p.getName());
values.add(p.getCategory());
values.add(p.getTimeType());
values.add(p.getTime());
values.add(p.getCost());
values.add(p.getDirection());
valueList.add(values);
}
}
model = new DragNDropTableModel(new String[]{"Name", "Category", "Time Type", "Time Cost", "Money Cost", "Direction"},
valueList, new Class[]{String.class, String.class, TimeType.class, Value.class, Value.class, ProcedureResponsibilityDirection.class});
//TABLE
table = new DragNDropTable(model);
try {
table.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(new JComboBox(procedureCategoryDao.findAll().toArray())));
} catch (Exception e) {
table.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(new JComboBox(new ProcedureCategory[]{})));
}
table.getColumnModel().getColumn(2).setCellEditor(new DefaultCellEditor(new JComboBox(TimeType.values())));
table.getColumnModel().getColumn(5).setCellEditor(new DefaultCellEditor(new JComboBox(ProcedureResponsibilityDirection.values())));
//OTHER COMPONENTS
sc_pane = new JScrollPane(table);
btn_add = new JButton("+");
btn_delete = new JButton("-");
//ADD COMPONENTS TO PANEL
this.add(sc_pane, cc.xywh(2, 2, 1, 4));
this.add(btn_add, cc.xy(4, 2));
this.add(btn_delete, cc.xy(4, 4));
//ADD COMPONENTS TO LISTENER
btn_add.addActionListener(this);
btn_delete.addActionListener(this);
table.addMouseListener(this);
this.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(btn_delete)) {
int rowToDelete = table.getSelectedRow();
if (rowToDelete > -1) {
deleteProcedure(rowToDelete);
}
} else if (e.getSource().equals(btn_add)) {
addProcedure();
}
}
@Override
public void mouseClicked(MouseEvent e) {
if (e.getSource().equals(table)) {
System.out.println(getActiveTableState());
if (e.getClickCount() > 1) {
editProcedure();
}
}
}
public List<Procedure> getActiveTableState() {
List<List<Object>> values = ((DragNDropTableModel) table.getModel()).getValues();
ArrayList<Procedure> procedures = new ArrayList<>();
for (List<Object> value : values) {
Procedure p = new Procedure();
p.setName((String) value.get(0));
p.setCategory((String) value.get(1));
p.setTimeType((TimeType) value.get(2));
p.setTime((Value) value.get(3));
p.setCost((Value) value.get(4));
p.setDirection((ProcedureResponsibilityDirection) value.get(5));
procedures.add(p);
}
return procedures;
}
public void setProcedureTable(List<Procedure> procedures) {
List<List<Object>> valueList = new ArrayList<>();
if (procedures != null) {
for (Procedure p : procedures) {
ArrayList<Object> values = new ArrayList<>();
values.add(p.getName());
values.add(p.getCategory());
values.add(p.getTimeType());
values.add(p.getTime());
values.add(p.getCost());
values.add(p.getDirection());
valueList.add(values);
}
}
model = new DragNDropTableModel(new String[]{"Name", "Category", "Time Type", "Time Cost", "Money Cost", "Direction"},
valueList, new Class[]{String.class, String.class, TimeType.class, Value.class, Value.class, ProcedureResponsibilityDirection.class});
table.setModel(model);
model.fireTableDataChanged();
this.revalidate();
this.repaint();
}
private void addProcedure() {
new AddProcedureDialog();
}
private void deleteProcedure(int row) {
((DragNDropTableModel) table.getModel()).removeRow(row);
this.revalidate();
this.repaint();
}
private void editProcedure() {
changedValue = (Value) table.getValueAt(table.getSelectedRow(), table.getSelectedColumn());
new EditValueDialog((Value) table.getValueAt(table.getSelectedRow(), table.getSelectedColumn()));
table.setValueAt(changedValue, table.getSelectedRow(), table.getSelectedColumn());
this.revalidate();
this.repaint();
}
// <editor-fold desc="UNUSED LISTENER METHODS" defaultstate="collapsed">
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
//</editor-fold>
private class AddProcedureDialog extends JDialog implements ActionListener {
private JButton btn_addSave, btn_addCancel, btn_addTime, btn_addCost;
private final JLabel lbl_name, lbl_category, lbl_timeType, lbl_time, lbl_cost, lbl_direction;
private final JTextField tf_name, tf_cost, tf_time;
private JComboBox cbox_timeType, cbox_category, cbox_direction;
private Value timeValue, costValue;
private Procedure newProcedure;
public AddProcedureDialog() {
//LAYOUT
FormLayout layout = new FormLayout("5px, pref, 5px, pref, pref:grow, 5px, pref, 5px",
"5px, pref, 5px, pref, 5px, pref, 5px, pref, 5px, pref, 5px, pref, 5px, pref, 5px");
this.setLayout(layout);
//COMPONENTS
lbl_name = new JLabel("Name:");
tf_name = new JTextField();
lbl_category = new JLabel("Category:");
try {
cbox_category = new JComboBox(procedureCategoryDao.findAll().toArray());
} catch (Exception e) {
cbox_category = new JComboBox(new ProcedureCategory[]{});
}
lbl_timeType = new JLabel("Time Type:");
cbox_timeType = new JComboBox(TimeType.values());
lbl_time = new JLabel("Time Cost:");
tf_time = new JTextField();
tf_time.setEditable(false);
btn_addTime = new JButton("...");
lbl_cost = new JLabel("Money Cost:");
tf_cost = new JTextField();
tf_cost.setEditable(false);
btn_addCost = new JButton("...");
lbl_direction = new JLabel("Direction:");
cbox_direction = new JComboBox(ProcedureResponsibilityDirection.values());
btn_addSave = new JButton("Save");
btn_addCancel = new JButton("Cancel");
//ADD COMPONENTS
this.add(lbl_name, cc.xy(2, 2));
this.add(tf_name, cc.xyw(4, 2, 2));
this.add(lbl_category, cc.xy(2, 4));
this.add(cbox_category, cc.xyw(4, 4, 2));
this.add(lbl_timeType, cc.xy(2, 6));
this.add(cbox_timeType, cc.xyw(4, 6, 2));
this.add(lbl_time, cc.xy(2, 8));
this.add(tf_time, cc.xyw(4, 8, 2));
this.add(btn_addTime, cc.xy(7, 8));
this.add(lbl_cost, cc.xy(2, 10));
this.add(tf_cost, cc.xyw(4, 10, 2));
this.add(btn_addCost, cc.xy(7, 10));
this.add(lbl_direction, cc.xy(2, 12));
this.add(cbox_direction, cc.xyw(4, 12, 2));
this.add(btn_addSave, cc.xy(2, 14));
this.add(btn_addCancel, cc.xy(4, 14));
//ADD COMPONENTS TO LISTENER
btn_addCancel.addActionListener(this);
btn_addSave.addActionListener(this);
btn_addCost.addActionListener(this);
btn_addTime.addActionListener(this);
//DIALOG OPTIONS
this.setSize(250, 300);
this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
this.setModal(true);
this.setAlwaysOnTop(true);
this.setVisible(true);
}
private boolean isValidProcedure() {
return !(tf_name.getText().equals("") || tf_name.getText().equals("") || tf_cost.getText().equals(""));
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(btn_addCost)) {
new EditValueDialog(costValue);
if (costValue != null) {
costValue = changedValue;
tf_cost.setText(costValue.toString());
this.revalidate();
this.repaint();
}
}
if (e.getSource().equals(btn_addTime)) {
new EditValueDialog(timeValue);
timeValue = changedValue;
if (timeValue != null) {
tf_time.setText(timeValue.toString());
this.revalidate();
this.repaint();
}
}
if (e.getSource().equals(btn_addCancel)) {
this.dispose();
}
if (e.getSource().equals(btn_addSave)) {
if (isValidProcedure()) {
String name = tf_name.getText();
String category = "";
try {
category = cbox_category.getSelectedItem().toString();
} catch (Exception ex) {
}
TimeType timeType = (TimeType) cbox_timeType.getSelectedItem();
ProcedureResponsibilityDirection direction = (ProcedureResponsibilityDirection) cbox_direction.getSelectedItem();
newProcedure = new Procedure(name, category, costValue, timeValue, timeType, direction);
List<Object> newRow = new ArrayList<>();
newRow.add(newProcedure.getName());
newRow.add(newProcedure.getCategory());
newRow.add(newProcedure.getTimeType());
newRow.add(newProcedure.getTime());
newRow.add(newProcedure.getCost());
newRow.add(newProcedure.getDirection());
((DragNDropTableModel) table.getModel()).addRow(newRow);
((DragNDropTableModel) table.getModel()).fireTableDataChanged();
table.revalidate();
table.repaint();
this.dispose();
}
}
}
}
private class EditValueDialog extends JDialog implements ActionListener {
private final JButton btn_dialogSave, btn_dialogCancel;
private final JComboBox<String> cbox_valueType;
private final JTextField tf_value, tf_min, tf_max;
private final JPanel singlePanel, rangePanel;
private final JLabel lbl_type, lbl_value, lbl_min, lbl_max, lbl_error;
private int activeType = 0;
public EditValueDialog(Value value) {
//LAYOUT
FormLayout mainLayout = new FormLayout("5px, pref, 5px, pref, 5px, pref:grow, 5px",
"5px, pref, 5px, pref, 5px, pref, 5px, pref, 5px");
FormLayout rangeLayout = new FormLayout("5px, pref, 5px, pref:grow, 5px", "5px, pref, 5px, pref, 5px");
FormLayout singleLayout = new FormLayout("5px, pref, 5px, pref:grow, 5px", "5px, pref, 5px");
this.setLayout(mainLayout);
//COMPONENTS
tf_value = new JTextField();
tf_min = new JTextField();
tf_max = new JTextField();
singlePanel = new JPanel();
rangePanel = new JPanel();
lbl_type = new JLabel("Type: ");
lbl_value = new JLabel("Value: ");
lbl_min = new JLabel("Min: ");
lbl_max = new JLabel("Max: ");
lbl_error = new JLabel();
lbl_error.setForeground(Color.RED);
btn_dialogCancel = new JButton("Cancel");
btn_dialogSave = new JButton("Save");
cbox_valueType = new JComboBox<>(new String[]{"Single", "Range"});
//ADD COMPONENTS TO SINGLE PANEL
singlePanel.setLayout(singleLayout);
singlePanel.add(lbl_value, cc.xy(2, 2));
singlePanel.add(tf_value, cc.xy(4, 2));
//ADD COMPONENTS TO RANGE PANEL
rangePanel.setLayout(rangeLayout);
rangePanel.add(lbl_min, cc.xy(2, 2));
rangePanel.add(tf_min, cc.xy(4, 2));
rangePanel.add(lbl_max, cc.xy(2, 4));
rangePanel.add(tf_max, cc.xy(4, 4));
//ADD COMPONENTS TO DIALOG
this.add(lbl_type, cc.xy(2, 2));
this.add(cbox_valueType, cc.xyw(4, 2, 3));
if (value != null) {
if (value instanceof SingleValue) {
this.add(singlePanel, cc.xyw(2, 4, 5));
cbox_valueType.setSelectedIndex(0);
tf_value.setText(value.getValue() + "");
activeType = 0;
} else {
this.add(rangePanel, cc.xyw(2, 4, 5));
cbox_valueType.setSelectedIndex(1);
tf_min.setText(value.getMin() + "");
tf_max.setText(value.getMax() + "");
activeType = 1;
}
} else {
this.add(singlePanel, cc.xyw(2, 4, 5));
cbox_valueType.setSelectedIndex(0);
activeType = 0;
}
this.add(btn_dialogSave, cc.xy(2, 6));
this.add(btn_dialogCancel, cc.xy(4, 6));
this.add(lbl_error, cc.xyw(2, 8, 5));
//ADD COMPONENTS TO LISTENER
btn_dialogCancel.addActionListener(this);
btn_dialogSave.addActionListener(this);
cbox_valueType.addActionListener(this);
//DIALOG OPTIONS
this.setModal(true);
this.setSize(200, 250);
this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
this.setAlwaysOnTop(true);
this.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(cbox_valueType)) {
if (activeType != cbox_valueType.getSelectedIndex()) {
double activeValue;
if (activeType == 0) {
try {
if (tf_value.getText().equals("")) {
activeValue = 0;
} else {
activeValue = Double.parseDouble(tf_value.getText());
}
this.remove(singlePanel);
this.add(rangePanel, cc.xyw(2, 4, 5));
tf_min.setText(activeValue + "");
lbl_error.setText("");
} catch (NumberFormatException ex) {
cbox_valueType.setSelectedIndex(0);
}
} else {
try {
if (tf_value.getText().equals("")) {
activeValue = 0;
} else {
activeValue = Double.parseDouble(tf_min.getText());
}
this.remove(rangePanel);
this.add(singlePanel, cc.xyw(2, 4, 5));
tf_value.setText(activeValue + "");
lbl_error.setText("");
} catch (NumberFormatException ex) {
cbox_valueType.setSelectedIndex(1);
}
}
activeType = cbox_valueType.getSelectedIndex();
this.revalidate();
this.repaint();
}
}
if (e.getSource().equals(btn_dialogCancel)) {
this.dispose();
}
if (e.getSource().equals(btn_dialogSave)) {
if (activeType == 0) {
try {
changedValue = new SingleValue(Double.parseDouble(tf_value.getText()));
this.dispose();
} catch (NumberFormatException ex) {
lbl_error.setText("NOT A NUMBER");
}
} else {
try {
double min = Double.parseDouble(tf_min.getText());
double max = Double.parseDouble(tf_max.getText());
if (max > min) {
changedValue = new RangeValue(min, max);
this.dispose();
} else {
lbl_error.setText("MAX MUST BE BIGGER THAN MIN");
}
} catch (NumberFormatException ex) {
lbl_error.setText("NOT A NUMBER");
}
}
}
}
}
}
|
package cpw.mods.fml.relauncher;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.logging.Level;
import net.minecraft.launchwrapper.ITweaker;
import net.minecraft.launchwrapper.Launch;
import net.minecraft.launchwrapper.LaunchClassLoader;
import com.google.common.base.Strings;
import com.google.common.base.Throwables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.ObjectArrays;
import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.launcher.FMLTweaker;
import cpw.mods.fml.common.toposort.TopologicalSort;
import cpw.mods.fml.relauncher.IFMLLoadingPlugin.DependsOn;
import cpw.mods.fml.relauncher.IFMLLoadingPlugin.MCVersion;
import cpw.mods.fml.relauncher.IFMLLoadingPlugin.Name;
import cpw.mods.fml.relauncher.IFMLLoadingPlugin.TransformerExclusions;
public class CoreModManager
{
private static final Attributes.Name COREMODCONTAINSFMLMOD = new Attributes.Name("FMLCorePluginContainsFMLMod");
private static String[] rootPlugins = { "cpw.mods.fml.relauncher.FMLCorePlugin" , "net.minecraftforge.classloading.FMLForgePlugin" };
private static List<String> loadedCoremods = Lists.newArrayList();
private static List<FMLPluginWrapper> loadPlugins;
private static boolean deobfuscatedEnvironment;
private static FMLTweaker tweaker;
private static File mcDir;
private static List<String> reparsedCoremods = Lists.newArrayList();
private static class FMLPluginWrapper
{
public final String name;
public final IFMLLoadingPlugin coreModInstance;
public final List<String> predepends;
public final File location;
public FMLPluginWrapper(String name, IFMLLoadingPlugin coreModInstance, File location, String... predepends)
{
super();
this.name = name;
this.coreModInstance = coreModInstance;
this.location = location;
this.predepends = Lists.newArrayList(predepends);
}
@Override
public String toString()
{
return String.format("%s {%s}", this.name, this.predepends);
}
}
public static void handleLaunch(File mcDir, LaunchClassLoader classLoader, FMLTweaker tweaker)
{
CoreModManager.mcDir = mcDir;
CoreModManager.tweaker = tweaker;
try
{
// Are we in a 'decompiled' environment?
byte[] bs = classLoader.getClassBytes("net.minecraft.world.World");
if (bs != null)
{
FMLRelaunchLog.info("Managed to load a deobfuscated Minecraft name- we are in a deobfuscated environment. Skipping runtime deobfuscation");
deobfuscatedEnvironment = true;
}
}
catch (IOException e1)
{
}
if (!deobfuscatedEnvironment)
{
FMLRelaunchLog.fine("Enabling runtime deobfuscation");
}
try
{
classLoader.registerTransformer("cpw.mods.fml.common.asm.transformers.PatchingTransformer");
}
catch (Exception e)
{
FMLRelaunchLog.log(Level.SEVERE, e, "The patch transformer failed to load! This is critical, loading cannot continue!");
throw Throwables.propagate(e);
}
loadPlugins = new ArrayList<FMLPluginWrapper>();
for (String rootPluginName : rootPlugins)
{
loadCoreMod(classLoader, rootPluginName, new File(FMLTweaker.getJarLocation()));
}
if (loadPlugins.isEmpty())
{
throw new RuntimeException("A fatal error has occured - no valid fml load plugin was found - this is a completely corrupt FML installation.");
}
FMLRelaunchLog.fine("All fundamental core mods are successfully located");
// Now that we have the root plugins loaded - lets see what else might be around
String commandLineCoremods = System.getProperty("fml.coreMods.load","");
for (String coreModClassName : commandLineCoremods.split(","))
{
if (coreModClassName.isEmpty())
{
continue;
}
FMLRelaunchLog.info("Found a command line coremod : %s", coreModClassName);
loadCoreMod(classLoader, coreModClassName, null);
}
discoverCoreMods(mcDir, classLoader);
}
private static void discoverCoreMods(File mcDir, LaunchClassLoader classLoader)
{
FMLRelaunchLog.fine("Discovering coremods");
File coreMods = setupCoreModDir(mcDir);
FilenameFilter ff = new FilenameFilter()
{
@Override
public boolean accept(File dir, String name)
{
return name.endsWith(".jar");
}
};
File[] coreModList = coreMods.listFiles(ff);
File versionedModDir = new File(coreMods,FMLInjectionData.mccversion);
if (versionedModDir.isDirectory())
{
File[] versionedCoreMods = versionedModDir.listFiles(ff);
coreModList = ObjectArrays.concat(coreModList,versionedCoreMods, File.class);
}
Arrays.sort(coreModList);
for (File coreMod : coreModList)
{
FMLRelaunchLog.fine("Examining for coremod candidacy %s", coreMod.getName());
JarFile jar = null;
Attributes mfAttributes;
try
{
jar = new JarFile(coreMod);
if (jar.getManifest() == null)
{
// Not a coremod
continue;
}
mfAttributes = jar.getManifest().getMainAttributes();
}
catch (IOException ioe)
{
FMLRelaunchLog.log(Level.SEVERE, ioe, "Unable to read the jar file %s - ignoring", coreMod.getName());
continue;
}
finally
{
if (jar!=null)
{
try
{
jar.close();
}
catch (IOException e)
{
// Noise
}
}
}
String cascadedTweaker = mfAttributes.getValue("TweakClass");
if (cascadedTweaker != null)
{
FMLRelaunchLog.info("Loading tweaker %s from %s", cascadedTweaker, coreMod.getName());
handleCascadingTweak(coreMod, jar, cascadedTweaker, classLoader);
loadedCoremods.add(coreMod.getName());
continue;
}
String fmlCorePlugin = mfAttributes.getValue("FMLCorePlugin");
if (fmlCorePlugin == null)
{
// Not a coremod
FMLRelaunchLog.fine("Not found coremod data in %s", coreMod.getName());
continue;
}
try
{
classLoader.addURL(coreMod.toURI().toURL());
if (!mfAttributes.containsKey(COREMODCONTAINSFMLMOD))
{
FMLRelaunchLog.finest("Adding %s to the list of known coremods, it will not be examined again", coreMod.getName());
loadedCoremods.add(coreMod.getName());
}
else
{
FMLRelaunchLog.finest("Found FMLCorePluginContainsFMLMod marker in %s, it will be examined later for regular @Mod instances", coreMod.getName());
reparsedCoremods.add(coreMod.getName());
}
}
catch (MalformedURLException e)
{
FMLRelaunchLog.log(Level.SEVERE, e, "Unable to convert file into a URL. weird");
continue;
}
loadCoreMod(classLoader, fmlCorePlugin, coreMod);
}
}
private static Method ADDURL;
private static void handleCascadingTweak(File coreMod, JarFile jar, String cascadedTweaker, LaunchClassLoader classLoader)
{
try
{
// Have to manually stuff the tweaker into the parent classloader
if (ADDURL == null)
{
ADDURL = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
ADDURL.setAccessible(true);
}
ADDURL.invoke(classLoader.getClass().getClassLoader(), coreMod.toURI().toURL());
CoreModManager.tweaker.injectCascadingTweak(cascadedTweaker);
}
catch (Exception e)
{
FMLRelaunchLog.log(Level.INFO, e, "There was a problem trying to load the mod dir tweaker %s", coreMod.getAbsolutePath());
}
}
/**
* @param mcDir the minecraft home directory
* @return the coremod directory
*/
private static File setupCoreModDir(File mcDir)
{
File coreModDir = new File(mcDir,"mods");
try
{
coreModDir = coreModDir.getCanonicalFile();
}
catch (IOException e)
{
throw new RuntimeException(String.format("Unable to canonicalize the coremod dir at %s", mcDir.getName()),e);
}
if (!coreModDir.exists())
{
coreModDir.mkdir();
}
else if (coreModDir.exists() && !coreModDir.isDirectory())
{
throw new RuntimeException(String.format("Found a coremod file in %s that's not a directory", mcDir.getName()));
}
return coreModDir;
}
public static List<String> getLoadedCoremods()
{
return loadedCoremods;
}
public static List<String> getReparseableCoremods()
{
return reparsedCoremods;
}
private static FMLPluginWrapper loadCoreMod(LaunchClassLoader classLoader, String coreModClass, File location)
{
String coreModName = coreModClass.substring(coreModClass.lastIndexOf('.')+1);
try
{
FMLRelaunchLog.fine("Instantiating coremod class %s", coreModName);
classLoader.addTransformerExclusion(coreModClass);
Class<?> coreModClazz = Class.forName(coreModClass, true, classLoader);
Name coreModNameAnn = coreModClazz.getAnnotation(IFMLLoadingPlugin.Name.class);
if (coreModNameAnn!=null && !Strings.isNullOrEmpty(coreModNameAnn.value()))
{
coreModName = coreModNameAnn.value();
FMLRelaunchLog.finest("coremod named %s is loading", coreModName);
}
MCVersion requiredMCVersion = coreModClazz.getAnnotation(IFMLLoadingPlugin.MCVersion.class);
if (!Arrays.asList(rootPlugins).contains(coreModClass) && (requiredMCVersion == null || Strings.isNullOrEmpty(requiredMCVersion.value())))
{
FMLRelaunchLog.log(Level.WARNING, "The coremod %s does not have a MCVersion annotation, it may cause issues with this version of Minecraft", coreModClass);
}
else if (requiredMCVersion!=null && !FMLInjectionData.mccversion.equals(requiredMCVersion.value()))
{
FMLRelaunchLog.log(Level.SEVERE, "The coremod %s is requesting minecraft version %s and minecraft is %s. It will be ignored.", coreModClass, requiredMCVersion.value(), FMLInjectionData.mccversion);
return null;
}
else if (requiredMCVersion!=null)
{
FMLRelaunchLog.log(Level.FINE, "The coremod %s requested minecraft version %s and minecraft is %s. It will be loaded.", coreModClass, requiredMCVersion.value(), FMLInjectionData.mccversion);
}
TransformerExclusions trExclusions = coreModClazz.getAnnotation(IFMLLoadingPlugin.TransformerExclusions.class);
if (trExclusions!=null)
{
for (String st : trExclusions.value())
{
classLoader.addTransformerExclusion(st);
}
}
DependsOn deplist = coreModClazz.getAnnotation(IFMLLoadingPlugin.DependsOn.class);
String[] dependencies = new String[0];
if (deplist != null)
{
dependencies = deplist.value();
}
IFMLLoadingPlugin plugin = (IFMLLoadingPlugin) coreModClazz.newInstance();
FMLPluginWrapper wrap = new FMLPluginWrapper(coreModName, plugin, location, dependencies);
loadPlugins.add(wrap);
FMLRelaunchLog.fine("Loaded coremod %s", coreModName);
return wrap;
}
catch (ClassNotFoundException cnfe)
{
if (!Lists.newArrayList(rootPlugins).contains(coreModClass))
FMLRelaunchLog.log(Level.SEVERE, cnfe, "Coremod %s: Unable to class load the plugin %s", coreModName, coreModClass);
else
FMLRelaunchLog.fine("Skipping root plugin %s", coreModClass);
}
catch (ClassCastException cce)
{
FMLRelaunchLog.log(Level.SEVERE, cce, "Coremod %s: The plugin %s is not an implementor of IFMLLoadingPlugin", coreModName, coreModClass);
}
catch (InstantiationException ie)
{
FMLRelaunchLog.log(Level.SEVERE, ie, "Coremod %s: The plugin class %s was not instantiable", coreModName, coreModClass);
}
catch (IllegalAccessException iae)
{
FMLRelaunchLog.log(Level.SEVERE, iae, "Coremod %s: The plugin class %s was not accessible", coreModName, coreModClass);
}
return null;
}
private static void sortCoreMods()
{
TopologicalSort.DirectedGraph<FMLPluginWrapper> sortGraph = new TopologicalSort.DirectedGraph<FMLPluginWrapper>();
Map<String, FMLPluginWrapper> pluginMap = Maps.newHashMap();
for (FMLPluginWrapper plug : loadPlugins)
{
sortGraph.addNode(plug);
pluginMap.put(plug.name, plug);
}
for (FMLPluginWrapper plug : loadPlugins)
{
for (String dep : plug.predepends)
{
if (!pluginMap.containsKey(dep))
{
FMLRelaunchLog.log(Level.SEVERE, "Missing coremod dependency - the coremod %s depends on coremod %s which isn't present.", plug.name, dep);
throw new RuntimeException();
}
sortGraph.addEdge(plug, pluginMap.get(dep));
}
}
try
{
loadPlugins = TopologicalSort.topologicalSort(sortGraph);
FMLRelaunchLog.fine("Sorted coremod list %s", loadPlugins);
}
catch (Exception e)
{
FMLLog.log(Level.SEVERE, e, "There was a problem performing the coremod sort");
throw Throwables.propagate(e);
}
}
public static void injectTransformers(LaunchClassLoader classLoader)
{
for (FMLPluginWrapper wrap : loadPlugins)
{
IFMLLoadingPlugin plug = wrap.coreModInstance;
if (plug.getASMTransformerClass()!=null)
{
for (String xformClass : plug.getASMTransformerClass())
{
FMLRelaunchLog.finest("Registering transformer %s", xformClass);
classLoader.registerTransformer(xformClass);
}
}
}
FMLRelaunchLog.fine("Running coremod plugins");
Map<String,Object> data = new HashMap<String,Object>();
data.put("mcLocation", mcDir);
data.put("coremodList", loadPlugins);
data.put("runtimeDeobfuscationEnabled", !deobfuscatedEnvironment);
for (FMLPluginWrapper pluginWrapper : loadPlugins)
{
IFMLLoadingPlugin plugin = pluginWrapper.coreModInstance;
FMLRelaunchLog.fine("Running coremod plugin %s", pluginWrapper.name);
data.put("coremodLocation", pluginWrapper.location);
plugin.injectData(data);
String setupClass = plugin.getSetupClass();
if (setupClass != null)
{
try
{
IFMLCallHook call = (IFMLCallHook) Class.forName(setupClass, true, classLoader).newInstance();
Map<String,Object> callData = new HashMap<String, Object>();
callData.put("mcLocation", mcDir);
callData.put("classLoader", classLoader);
callData.put("coremodLocation", pluginWrapper.location);
callData.put("deobfuscationFileName", FMLInjectionData.debfuscationDataName());
call.injectData(callData);
call.call();
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
FMLRelaunchLog.fine("Coremod plugin %s run successfully", plugin.getClass().getSimpleName());
String modContainer = plugin.getModContainerClass();
if (modContainer != null)
{
FMLInjectionData.containers.add(modContainer);
}
}
Launch.blackboard.put("fml.deobfuscatedEnvironment", deobfuscatedEnvironment);
tweaker.injectCascadingTweak("cpw.mods.fml.common.launcher.FMLDeobfTweaker");
}
}
|
package cpw.mods.fml.relauncher;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.logging.Level;
import net.minecraft.launchwrapper.ITweaker;
import net.minecraft.launchwrapper.LaunchClassLoader;
import com.google.common.base.Strings;
import com.google.common.base.Throwables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.ObjectArrays;
import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.launcher.FMLTweaker;
import cpw.mods.fml.common.toposort.TopologicalSort;
import cpw.mods.fml.relauncher.IFMLLoadingPlugin.DependsOn;
import cpw.mods.fml.relauncher.IFMLLoadingPlugin.MCVersion;
import cpw.mods.fml.relauncher.IFMLLoadingPlugin.Name;
import cpw.mods.fml.relauncher.IFMLLoadingPlugin.TransformerExclusions;
public class CoreModManager
{
private static String[] rootPlugins = { "cpw.mods.fml.relauncher.FMLCorePlugin" , "net.minecraftforge.classloading.FMLForgePlugin" };
private static List<String> loadedCoremods = Lists.newArrayList();
private static List<FMLPluginWrapper> loadPlugins;
private static boolean deobfuscatedEnvironment;
private static FMLTweaker tweaker;
private static File mcDir;
private static List<String> reparsedCoremods = Lists.newArrayList();
private static class FMLPluginWrapper
{
public final String name;
public final IFMLLoadingPlugin coreModInstance;
public final List<String> predepends;
public final File location;
public FMLPluginWrapper(String name, IFMLLoadingPlugin coreModInstance, File location, String... predepends)
{
super();
this.name = name;
this.coreModInstance = coreModInstance;
this.location = location;
this.predepends = Lists.newArrayList(predepends);
}
@Override
public String toString()
{
return String.format("%s {%s}", this.name, this.predepends);
}
}
public static void handleLaunch(File mcDir, LaunchClassLoader classLoader, FMLTweaker tweaker)
{
CoreModManager.mcDir = mcDir;
CoreModManager.tweaker = tweaker;
try
{
// Are we in a 'decompiled' environment?
byte[] bs = classLoader.getClassBytes("net.minecraft.world.World");
if (bs != null)
{
FMLRelaunchLog.info("Managed to load a deobfuscated Minecraft name- we are in a deobfuscated environment. Skipping runtime deobfuscation");
deobfuscatedEnvironment = true;
}
}
catch (IOException e1)
{
}
if (!deobfuscatedEnvironment)
{
FMLRelaunchLog.fine("Enabling runtime deobfuscation");
}
try
{
classLoader.registerTransformer("cpw.mods.fml.common.asm.transformers.PatchingTransformer");
}
catch (Exception e)
{
FMLRelaunchLog.log(Level.SEVERE, e, "The patch transformer failed to load! This is critical, loading cannot continue!");
throw Throwables.propagate(e);
}
loadPlugins = new ArrayList<FMLPluginWrapper>();
for (String rootPluginName : rootPlugins)
{
loadCoreMod(classLoader, rootPluginName, null);
}
if (loadPlugins.isEmpty())
{
throw new RuntimeException("A fatal error has occured - no valid fml load plugin was found - this is a completely corrupt FML installation.");
}
FMLRelaunchLog.fine("All fundamental core mods are successfully located");
// Now that we have the root plugins loaded - lets see what else might be around
String commandLineCoremods = System.getProperty("fml.coreMods.load","");
for (String coreModClassName : commandLineCoremods.split(","))
{
if (coreModClassName.isEmpty())
{
continue;
}
FMLRelaunchLog.info("Found a command line coremod : %s", coreModClassName);
loadCoreMod(classLoader, coreModClassName, null);
}
discoverCoreMods(mcDir, classLoader);
}
private static void discoverCoreMods(File mcDir, LaunchClassLoader classLoader)
{
FMLRelaunchLog.fine("Discovering coremods");
File coreMods = setupCoreModDir(mcDir);
FilenameFilter ff = new FilenameFilter()
{
@Override
public boolean accept(File dir, String name)
{
return name.endsWith(".jar");
}
};
File[] coreModList = coreMods.listFiles(ff);
File versionedModDir = new File(coreMods,FMLInjectionData.mccversion);
if (versionedModDir.isDirectory())
{
File[] versionedCoreMods = versionedModDir.listFiles(ff);
coreModList = ObjectArrays.concat(coreModList,versionedCoreMods, File.class);
}
Arrays.sort(coreModList);
for (File coreMod : coreModList)
{
FMLRelaunchLog.fine("Examining for coremod candidacy %s", coreMod.getName());
JarFile jar = null;
Attributes mfAttributes;
try
{
jar = new JarFile(coreMod);
if (jar.getManifest() == null)
{
// Not a coremod
continue;
}
mfAttributes = jar.getManifest().getMainAttributes();
}
catch (IOException ioe)
{
FMLRelaunchLog.log(Level.SEVERE, ioe, "Unable to read the jar file %s - ignoring", coreMod.getName());
continue;
}
finally
{
if (jar!=null)
{
try
{
jar.close();
}
catch (IOException e)
{
// Noise
}
}
}
String cascadedTweaker = mfAttributes.getValue("TweakClass");
if (cascadedTweaker != null)
{
FMLRelaunchLog.info("Loading tweaker %s from %s", cascadedTweaker, coreMod.getName());
handleCascadingTweak(coreMod, jar, cascadedTweaker, classLoader);
loadedCoremods.add(coreMod.getName());
continue;
}
String fmlCorePlugin = mfAttributes.getValue("FMLCorePlugin");
if (fmlCorePlugin == null)
{
// Not a coremod
continue;
}
try
{
classLoader.addURL(coreMod.toURI().toURL());
if (!mfAttributes.containsValue("FMLCorePluginContainsFMLMod"))
{
loadedCoremods.add(coreMod.getName());
}
else
{
reparsedCoremods.add(coreMod.getName());
}
}
catch (MalformedURLException e)
{
FMLRelaunchLog.log(Level.SEVERE, e, "Unable to convert file into a URL. weird");
continue;
}
loadCoreMod(classLoader, fmlCorePlugin, coreMod);
}
}
private static void handleCascadingTweak(File coreMod, JarFile jar, String cascadedTweaker, LaunchClassLoader classLoader)
{
try
{
classLoader.addURL(coreMod.toURI().toURL());
Class<? extends ITweaker> newTweakClass = (Class<? extends ITweaker>) Class.forName(cascadedTweaker, true, classLoader);
ITweaker newTweak = newTweakClass.newInstance();
CoreModManager.tweaker.injectCascadingTweak(newTweak);
}
catch (Exception e)
{
FMLRelaunchLog.log(Level.INFO, e, "There was a problem trying to load the mod dir tweaker %s", coreMod.getAbsolutePath());
}
}
/**
* @param mcDir the minecraft home directory
* @return the coremod directory
*/
private static File setupCoreModDir(File mcDir)
{
File coreModDir = new File(mcDir,"mods");
try
{
coreModDir = coreModDir.getCanonicalFile();
}
catch (IOException e)
{
throw new RuntimeException(String.format("Unable to canonicalize the coremod dir at %s", mcDir.getName()),e);
}
if (!coreModDir.exists())
{
coreModDir.mkdir();
}
else if (coreModDir.exists() && !coreModDir.isDirectory())
{
throw new RuntimeException(String.format("Found a coremod file in %s that's not a directory", mcDir.getName()));
}
return coreModDir;
}
public static List<String> getLoadedCoremods()
{
return loadedCoremods;
}
public static List<String> getReparseableCoremods()
{
return reparsedCoremods;
}
private static FMLPluginWrapper loadCoreMod(LaunchClassLoader classLoader, String coreModClass, File location)
{
String coreModName = coreModClass.substring(coreModClass.lastIndexOf('.')+1);
try
{
FMLRelaunchLog.fine("Instantiating coremod class %s", coreModName);
classLoader.addTransformerExclusion(coreModClass);
Class<?> coreModClazz = Class.forName(coreModClass, true, classLoader);
Name coreModNameAnn = coreModClazz.getAnnotation(IFMLLoadingPlugin.Name.class);
if (coreModNameAnn!=null && !Strings.isNullOrEmpty(coreModNameAnn.value()))
{
coreModName = coreModNameAnn.value();
FMLRelaunchLog.finest("coremod named %s is loading", coreModName);
}
MCVersion requiredMCVersion = coreModClazz.getAnnotation(IFMLLoadingPlugin.MCVersion.class);
if (!Arrays.asList(rootPlugins).contains(coreModClass) && (requiredMCVersion == null || Strings.isNullOrEmpty(requiredMCVersion.value())))
{
FMLRelaunchLog.log(Level.WARNING, "The coremod %s does not have a MCVersion annotation, it may cause issues with this version of Minecraft", coreModClass);
}
else if (requiredMCVersion!=null && !FMLInjectionData.mccversion.equals(requiredMCVersion.value()))
{
FMLRelaunchLog.log(Level.SEVERE, "The coremod %s is requesting minecraft version %s and minecraft is %s. It will be ignored.", coreModClass, requiredMCVersion.value(), FMLInjectionData.mccversion);
return null;
}
else if (requiredMCVersion!=null)
{
FMLRelaunchLog.log(Level.FINE, "The coremod %s requested minecraft version %s and minecraft is %s. It will be loaded.", coreModClass, requiredMCVersion.value(), FMLInjectionData.mccversion);
}
TransformerExclusions trExclusions = coreModClazz.getAnnotation(IFMLLoadingPlugin.TransformerExclusions.class);
if (trExclusions!=null)
{
for (String st : trExclusions.value())
{
classLoader.addTransformerExclusion(st);
}
}
DependsOn deplist = coreModClazz.getAnnotation(IFMLLoadingPlugin.DependsOn.class);
String[] dependencies = new String[0];
if (deplist != null)
{
dependencies = deplist.value();
}
IFMLLoadingPlugin plugin = (IFMLLoadingPlugin) coreModClazz.newInstance();
FMLPluginWrapper wrap = new FMLPluginWrapper(coreModName, plugin, location, dependencies);
loadPlugins.add(wrap);
FMLRelaunchLog.fine("Loaded coremod %s", coreModName);
return wrap;
}
catch (ClassNotFoundException cnfe)
{
if (!Lists.newArrayList(rootPlugins).contains(coreModClass))
FMLRelaunchLog.log(Level.SEVERE, cnfe, "Coremod %s: Unable to class load the plugin %s", coreModName, coreModClass);
else
FMLRelaunchLog.fine("Skipping root plugin %s", coreModClass);
}
catch (ClassCastException cce)
{
FMLRelaunchLog.log(Level.SEVERE, cce, "Coremod %s: The plugin %s is not an implementor of IFMLLoadingPlugin", coreModName, coreModClass);
}
catch (InstantiationException ie)
{
FMLRelaunchLog.log(Level.SEVERE, ie, "Coremod %s: The plugin class %s was not instantiable", coreModName, coreModClass);
}
catch (IllegalAccessException iae)
{
FMLRelaunchLog.log(Level.SEVERE, iae, "Coremod %s: The plugin class %s was not accessible", coreModName, coreModClass);
}
return null;
}
private static void sortCoreMods()
{
TopologicalSort.DirectedGraph<FMLPluginWrapper> sortGraph = new TopologicalSort.DirectedGraph<FMLPluginWrapper>();
Map<String, FMLPluginWrapper> pluginMap = Maps.newHashMap();
for (FMLPluginWrapper plug : loadPlugins)
{
sortGraph.addNode(plug);
pluginMap.put(plug.name, plug);
}
for (FMLPluginWrapper plug : loadPlugins)
{
for (String dep : plug.predepends)
{
if (!pluginMap.containsKey(dep))
{
FMLRelaunchLog.log(Level.SEVERE, "Missing coremod dependency - the coremod %s depends on coremod %s which isn't present.", plug.name, dep);
throw new RuntimeException();
}
sortGraph.addEdge(plug, pluginMap.get(dep));
}
}
try
{
loadPlugins = TopologicalSort.topologicalSort(sortGraph);
FMLRelaunchLog.fine("Sorted coremod list %s", loadPlugins);
}
catch (Exception e)
{
FMLLog.log(Level.SEVERE, e, "There was a problem performing the coremod sort");
throw Throwables.propagate(e);
}
}
public static void injectTransformers(LaunchClassLoader classLoader)
{
for (FMLPluginWrapper wrap : loadPlugins)
{
IFMLLoadingPlugin plug = wrap.coreModInstance;
if (plug.getASMTransformerClass()!=null)
{
for (String xformClass : plug.getASMTransformerClass())
{
FMLRelaunchLog.finest("Registering transformer %s", xformClass);
classLoader.registerTransformer(xformClass);
}
}
}
FMLRelaunchLog.fine("Running coremod plugins");
Map<String,Object> data = new HashMap<String,Object>();
data.put("mcLocation", mcDir);
data.put("coremodList", loadPlugins);
data.put("runtimeDeobfuscationEnabled", !deobfuscatedEnvironment);
for (FMLPluginWrapper pluginWrapper : loadPlugins)
{
IFMLLoadingPlugin plugin = pluginWrapper.coreModInstance;
FMLRelaunchLog.fine("Running coremod plugin %s", pluginWrapper.name);
data.put("coremodLocation", pluginWrapper.location);
plugin.injectData(data);
String setupClass = plugin.getSetupClass();
if (setupClass != null)
{
try
{
IFMLCallHook call = (IFMLCallHook) Class.forName(setupClass, true, classLoader).newInstance();
Map<String,Object> callData = new HashMap<String, Object>();
callData.put("mcLocation", mcDir);
callData.put("classLoader", classLoader);
callData.put("coremodLocation", pluginWrapper.location);
callData.put("deobfuscationFileName", FMLInjectionData.debfuscationDataName());
call.injectData(callData);
call.call();
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
FMLRelaunchLog.fine("Coremod plugin %s run successfully", plugin.getClass().getSimpleName());
String modContainer = plugin.getModContainerClass();
if (modContainer != null)
{
FMLInjectionData.containers.add(modContainer);
}
}
// Deobfuscation transformer, always last
if (!deobfuscatedEnvironment)
{
classLoader.registerTransformer("cpw.mods.fml.common.asm.transformers.DeobfuscationTransformer");
}
try
{
FMLRelaunchLog.fine("Validating minecraft");
Class<?> loaderClazz = Class.forName("cpw.mods.fml.common.Loader", true, classLoader);
Method m = loaderClazz.getMethod("injectData", Object[].class);
m.invoke(null, (Object)FMLInjectionData.data());
m = loaderClazz.getMethod("instance");
m.invoke(null);
FMLRelaunchLog.fine("Minecraft validated, launching...");
}
catch (Exception e)
{
// Load in the Loader, make sure he's ready to roll - this will initialize most of the rest of minecraft here
System.out.println("A CRITICAL PROBLEM OCCURED INITIALIZING MINECRAFT - LIKELY YOU HAVE AN INCORRECT VERSION FOR THIS FML");
throw new RuntimeException(e);
}
}
}
|
package com.example.zmotsing.myapplication;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.opengl.GLSurfaceView;
import android.opengl.GLU;
import android.os.Build;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import com.example.zmotsing.myapplication.Backend.BackendLogic;
import com.example.zmotsing.myapplication.Buttons.*;
import com.example.zmotsing.myapplication.Nodes.*;
import java.nio.FloatBuffer;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;
import javax.microedition.khronos.opengles.GL11ExtensionPack;
@TargetApi(Build.VERSION_CODES.KITKAT)
public class MyGLRenderer implements GLSurfaceView.Renderer {
//region Renderer Variables
final Handler TnHandler = new Handler();
private int[] Textures = new int[1]; //textures pointers
private int activeTexture = 0; //which texture is active (by index)
int i = 0;
private static Context myContext;
public static TravelingNode Tn;
public static BackgroundNode Bn;
public static LineStrip startLineStrip;
public static NodeType nodeTypeCreate = null;
static float transX,transY,transZ = -4;
public MyGLSurfaceView surfaceview;
public MyGLRenderer() {}
public static boolean nodeMovedFinished,Touched,bindMode,lBindMode,rBindMode,leftSet,rightSet,action_flag,TouchedDown,RedrawLine,actionDown,actionMoved,nodeMoved,pointerDown,pinchMoved,nodeIsTapped;
public static String rightBuffer,leftBuffer,curSpinVal;
public static Coord TouchEventCoord,TouchDownCoord,actionDownCoord,actionDownCoordGL, pointerDownCoord,pointerDownCoordGL,pointerMovedCoord,pointerMovedCoordGL,actionMovedCoord,actionMovedCoordGL;
public static double spacing;
public static Node curPressed,nodeWaitingBind,leftNode,rightNode;
public static int curSpinIndex;
float viewwidth,viewheight;
public static CopyOnWriteArrayList<Node> MasterNodeList = new CopyOnWriteArrayList<>();
public static CopyOnWriteArrayList<Node> StartNodeList = new CopyOnWriteArrayList<>();
public static CopyOnWriteArrayList<Node> CurrNodeList = new CopyOnWriteArrayList<>();
public static CopyOnWriteArrayList<Node> ifTempList = null;
static CopyOnWriteArrayList<Node> ButtonList = new CopyOnWriteArrayList<>();
public static TextManager inputTxt = new TextManager(1.0f, 0.0f, 0.5f, 0.0f);
public static TextManager outputTxt = new TextManager(1.0f, 0.0f, 0.0f, 0.0f);
static CopyOnWriteArrayList<Coord> StartControlPoints = new CopyOnWriteArrayList<>();
public static CopyOnWriteArrayList<Coord> MasterControlPoints = new CopyOnWriteArrayList<>();
public static CopyOnWriteArrayList<Coord> CurrControlPoints = new CopyOnWriteArrayList<>();
public static CopyOnWriteArrayList<Coord> ifTempPoints = null;
public static CopyOnWriteArrayList<Node> ButtonsToLoad = new CopyOnWriteArrayList<>();
public static CopyOnWriteArrayList<Node> NodesToLoad = new CopyOnWriteArrayList<>();
public static CopyOnWriteArrayList<String> inputTxtToLoad = new CopyOnWriteArrayList<>();
public static CopyOnWriteArrayList<String> outputTxtToLoad = new CopyOnWriteArrayList<>();
public static CopyOnWriteArrayList<Node> bindableNodes = new CopyOnWriteArrayList<>();
//endregion
private void setupGraphic(GL10 gl, Node n, boolean isOrtho)
{
//get the screen coordinate
Coord ScreenCoord = n.getCoord();
//get the drawable for this node
Drawable d = myContext.getResources().getDrawable(n.drawableInt);
Coord ScreenBRCoord;
Coord NewScreenCoord;
if(isOrtho)
{
n.Width = d.getIntrinsicWidth()/1200f;
n.Height = d.getIntrinsicHeight()/700f;
n.setCoord(ScreenCoord);
}
else {
//get the bottom right hand coordinate, scaling accordingly using scaling factor (scaling factor of one is actual size)
ScreenBRCoord = GetWorldCoords(gl, new Coord(ScreenCoord.X + n.scalingFactor * d.getIntrinsicWidth(), ScreenCoord.Y + n.scalingFactor * d.getIntrinsicHeight()));
//put the screen coordinates into opengl coordinates
NewScreenCoord = GetWorldCoords(gl, ScreenCoord);
//fin the opengl width and height
n.setCoord(NewScreenCoord);
n.Height = NewScreenCoord.Y - ScreenBRCoord.Y;
n.Width = ScreenBRCoord.X - NewScreenCoord.X;
}
n.setSprite();
n.spr.loadGLTexture(gl, myContext);
if(n.sprOptional != null) {
n.sprOptional.loadGLTexture(gl, myContext);
}
}
@Override
public void onDrawFrame(GL10 gl) {
//region Load in all graphics for new nodes
for (Node element : NodesToLoad) {
setupGraphic(gl,element,false);
if(ifTempList != null && element instanceof IfNode)
{
boolean ifHasEndNode = (ifTempList.size() > 1);
if (true)
{
ifTempList.add(ifTempList.size()-1,element);
ifTempPoints.add(ifTempPoints.size()-1,element.getCoord());
CurrNodeList.add(element);
CurrControlPoints.add(element.getCoord());
}
else
{
ifTempList.add(element);
ifTempPoints.add(element.getCoord());
CurrNodeList.add(element);
CurrControlPoints.add(element.getCoord());
}
ifTempList = null;
}
else
{
boolean currhasEndNode = (CurrNodeList.size() > 1);
if (currhasEndNode)
{
CurrNodeList.add(CurrNodeList.size() - 1, element);
CurrControlPoints.add(CurrControlPoints.size() - 1, element.getCoord());
}
else
{
CurrNodeList.add(element);
CurrControlPoints.add(element.getCoord());
}
}
MasterNodeList.add(element);
MasterControlPoints.add(element.getCoord());
RedrawLine = true;
}
NodesToLoad.clear();
for (Node element : ButtonsToLoad) {
//Node n = new OutputButton(element.co);
setupGraphic(gl,element,true);
ButtonList.add(element);
}
ButtonsToLoad.clear();
for(String element : inputTxtToLoad){
TextObject [] tempArr = inputTxt.addText(element);
for(int i=0; i<tempArr.length; i++)
{
tempArr[i].spr.loadGLTexture(gl, myContext);
}
}
inputTxtToLoad.clear();
for(String element : outputTxtToLoad){
TextObject [] tempArr = outputTxt.addText(element);
for(int i=0; i<tempArr.length; i++)
{
tempArr[i].spr.loadGLTexture(gl, myContext);
}
}
outputTxtToLoad.clear();
//endregion
//region Redraw linestrip
boolean redrawAllLines = false;
if (RedrawLine)
{
redrawAllLines = true;
if(StartControlPoints.size() > 2)
{
startLineStrip = new LineStrip(Spline.interpolate(StartControlPoints, 60, CatmullRomType.Chordal));
}
else if(StartControlPoints.size() == 2)
{
startLineStrip = new LineStrip(StartControlPoints);
}
Tn.tLineStrip = startLineStrip;
RedrawLine = false;
}
//endregion
//region Touch Motion Detection Logic
if(actionDown){
actionDown = false;
actionDownCoordGL = GetWorldCoords(gl, actionDownCoord);
if(getNodeTouched(actionDownCoordGL,MasterNodeList, false) != null) {
MyGLSurfaceView.moveNodeTimer = new Timer();
MyGLSurfaceView.moveNodeTimer.schedule(new TimerTask() {
@Override
public void run() {
MyGLSurfaceView.swipeMode = false;
MyGLSurfaceView.nodeMoveMode = true;
nodeIsTapped = true;
}
}, 800);
}
}
if(pointerDown){
pointerDown = false;
pointerDownCoordGL = GetWorldCoords(gl, pointerDownCoord);
spacing = Math.sqrt(
Math.pow((actionDownCoordGL.X - pointerDownCoordGL.X), 2) +
Math.pow((actionDownCoordGL.Y - pointerDownCoordGL.Y), 2));
}
if(actionMoved){
actionMoved = false;
actionMovedCoordGL = GetWorldCoords(gl, actionMovedCoord);
translateX(actionMovedCoordGL.X - actionDownCoordGL.X);
translateY(actionMovedCoordGL.Y - actionDownCoordGL.Y);
actionDownCoordGL = actionMovedCoordGL;
}else if(nodeMoved){
nodeMoved = false;
actionMovedCoordGL = GetWorldCoords(gl, actionMovedCoord);
Node tempNode = getNodeTouched(actionMovedCoordGL, MasterNodeList, false);
if(tempNode != null) {
int tempint = MasterNodeList.indexOf(tempNode);
Coord tempc = MasterControlPoints.get(tempint);
tempc.X =actionMovedCoordGL.X;
tempc.Y =actionMovedCoordGL.Y;
tempNode.setCoord(tempc);
RedrawLine = true;
}
}else if(false)
//(pinchMoved)
{
pinchMoved = false;
actionMovedCoordGL = GetWorldCoords(gl, actionMovedCoord);
pointerMovedCoordGL = GetWorldCoords(gl, pointerMovedCoord);
double newSpacing = Math.sqrt(
Math.pow((actionMovedCoordGL.X - pointerMovedCoordGL.X), 2) +
Math.pow((actionMovedCoordGL.Y - pointerMovedCoordGL.Y), 2));
transZ += (newSpacing - spacing)*1.4;
spacing = newSpacing;
}
if(nodeIsTapped)
{
nodeIsTapped = false;
Node tempNode = getNodeTouched(actionDownCoordGL, MasterNodeList, false);
if(tempNode != null) {
CurrControlPoints = tempNode.controlPoints;
CurrNodeList = tempNode.nodeList;
}
}
//endregion
// Clears the screen and depth buffer.
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
//region Translation for swipe
if(transY != 0 && transX != 0)
{
float tempX = transX;
float tempY = transY;
transX = transY = 0;
int i = 0;
for (Node element : StartNodeList) {
Coord co = element.getCoord();
co.X += tempX;
co.Y += tempY;
if(element instanceof IfNode)
{
((IfNode)element).translateNodes(tempX,tempY);
((IfNode)element).ifControlPoints.set(0,co);
}
if(element instanceof EndNode)
{
Log.w("Printed", "Translated END NODE" + element.hashCode());
}
StartControlPoints.set(i, co);
element.setCoord(co);
i++;
}
Coord co = Tn.getCoord();
co.X += tempX;
co.Y += tempY;
Tn.setCoord(co);
RedrawLine = true;
}
//endregion
//region Draw All Elements
switchToOrtho(gl);
Bn.spr.draw(gl);
switchBackToFrustum(gl);
gl.glTranslatef(0, 0, transZ);
for (TextObject element : inputTxt.getTextList()) {
element.spr.draw(gl);
}
for(TextObject element: outputTxt.getTextList()) {
element.spr.draw(gl);
}
if (startLineStrip != null) {
startLineStrip.draw(gl); // ( NEW )
}
for (Node element : StartNodeList) {
if(element instanceof IfNode)
{
((IfNode)element).drawTruePath(gl, redrawAllLines);
}
element.spr.draw(gl);
}
redrawAllLines = false;
Tn.spr.draw(gl);
switchToOrtho(gl);
for (Node element : ButtonList) {
if(element == curPressed)
{
element.drawPressed(gl);
}
else
{
element.draw(gl);
}
}
//endregion
//region ButtonDown detection
if (TouchedDown) {
TouchedDown = false;
Node n = getNodeTouched(GetWorldCoords(gl,TouchDownCoord), ButtonList, true);
curPressed = n;
}
//endregion
//region NodeBinding and ButtonPress Detection
if (Touched) {
Touched = false;
if(bindMode)
{
switchBackToFrustum(gl);
Node bindNode = getNodeTouched(GetWorldCoords(gl, TouchEventCoord), bindableNodes, false);
switchToOrtho(gl);
if(bindNode != null)
{
bindMode = false;
if(lBindMode)
{
leftNode = bindNode;
if(rightSet)
{
bindTriple();
}
else
{
leftSet = true;
Activity thisAct = (Activity) myContext;
thisAct.runOnUiThread(new Runnable() {
@Override
public void run() {
if(nodeWaitingBind.getTitle().equals("if"))
ifMenu();
else
mathMenu();
}
});
}
}
else if(rBindMode)
{
rightNode = bindNode;
if(leftSet)
{
bindTriple();
}
else
{
rightSet = true;
Activity thisAct = (Activity) myContext;
thisAct.runOnUiThread(new Runnable() {
@Override
public void run() {
if(nodeWaitingBind.getTitle().equals("if"))
ifMenu();
else
mathMenu();
}
});
}
}
else
{
BackendLogic.initializeOutputNode(nodeWaitingBind.getID(), bindNode.getID());
}
}
}
else
{
Node n = getNodeTouched(GetWorldCoords(gl,TouchDownCoord), ButtonList, true);
if (n != null) {
n.action(surfaceview);
}
}
}
//endregion
switchBackToFrustum(gl);
// Replace the current matrix with the identity matrix
gl.glLoadIdentity();
}
public void switchBackToFrustum(GL10 gl)
{
gl.glEnable(gl.GL_DEPTH_TEST);
gl.glMatrixMode(gl.GL_PROJECTION);
gl.glPopMatrix();
gl.glMatrixMode(gl.GL_MODELVIEW);
}
public void switchToOrtho(GL10 gl)
{
gl.glDisable(gl.GL_DEPTH_TEST);
gl.glMatrixMode(gl.GL_PROJECTION);
gl.glPushMatrix();
gl.glLoadIdentity();
//gl.glViewport(0, 0, viewwidth, viewheight);
//GLU.gluOrtho2D(gl,0f, viewwidth,0f, viewheight);
//GLU.gluOrtho2D(gl,0f, viewwidth,viewheight,0f );
//gl.glOrthof(0, 558, 0, 321, -5, 1);
gl.glMatrixMode(gl.GL_MODELVIEW);
gl.glLoadIdentity();
}
public void onSurfaceChanged(GL10 gl, int width, int height) {
//sets the viewport size
gl.glViewport(0, 0, width, height); //WHOLE SCREEN
viewwidth = width;
viewheight = height;
// Select the projection matrix
gl.glMatrixMode(GL10.GL_PROJECTION);
// Reset the projection matrix
gl.glLoadIdentity();
// Calculate the aspect ratio of the window
GLU.gluPerspective(gl, 45.0f,
(float) width / (float) height,
0.1f, 100.0f);
// Select the modelview matrix
gl.glMatrixMode(GL10.GL_MODELVIEW);
// Reset the modelview matrix
gl.glLoadIdentity();
}
@Override
public void onSurfaceCreated(GL10 gl, javax.microedition.khronos.egl.EGLConfig eglConfig) {
RedrawLine = false;
Coord Start = new Coord(200f, 200f);
CurrControlPoints = StartControlPoints;
CurrNodeList = StartNodeList;
nodeTypeCreate = NodeType.START;
addControlPoints(Start.X, Start.Y);
nodeTypeCreate = NodeType.END;
addControlPoints(400f, 200f);
// nodeTypeCreate = NodeType.OUTPUT;
// addControlPoints(200f, 100f);
// nodeTypeCreate = NodeType.OUTPUT;
// addControlPoints(250f, 50f);
// nodeTypeCreate = NodeType.OUTPUT;
// addControlPoints(400f, 26f);
Tn = new TravelingNode(Start,StartNodeList,startLineStrip);
Bn = new BackgroundNode(new Coord(0f, 0f));
final Runnable myRunnable = new Runnable() {
public void run() {
Tn.action(surfaceview);
}
};
Tn.setHandler(myRunnable,TnHandler);
float bs = 1.61f; // buttonspacing
// ButtonList.add(new OutputButton(new Coord(-2.1f, 1.5f)));
// ButtonList.add(new InputButton(new Coord(-.49f, 1.5f)));
// ButtonList.add(new IfButton(new Coord(1.12f, 1.5f)));
float button_x = -0.78f;
float button_y = 0.9f;
float button_dx = .427f;
float button_dy = -0.185f;
ButtonsToLoad.add(new OutputButton(new Coord(button_x, button_y)));
button_x += button_dx;
ButtonsToLoad.add(new InputButton(new Coord(button_x, button_y)));
button_x += button_dx;
ButtonsToLoad.add(new IfButton(new Coord(button_x, button_y)));
button_x = -0.78f; button_y += button_dy;
ButtonsToLoad.add(new StorageButton (new Coord(button_x, button_y)));
button_x += button_dx;
ButtonsToLoad.add(new SetButton(new Coord(button_x, button_y)));
button_x += button_dx;
ButtonsToLoad.add(new MathButton(new Coord(button_x, button_y)));
ButtonsToLoad.add(new PlayButton(new Coord(0.88f, 0.81f)));
//nody = new NodeSprite();
for (TextObject c : inputTxt.getTextList()) {
c.spr.loadGLTexture(gl, myContext);
}
for (TextObject c : outputTxt.getTextList()) {
c.spr.loadGLTexture(gl, myContext);
}
Bn.setSprite();
Bn.spr.loadGLTexture(gl,myContext);
Tn.setSprite();
Tn.spr.loadGLTexture(gl, myContext);
//Tn.start();
//square.loadGLTexture(gl, myContext);
gl.glEnable(GL10.GL_TEXTURE_2D); //Enable Texture Mapping
gl.glShadeModel(GL10.GL_SMOOTH); //Enable Smooth Shading
gl.glClearColor(0.0f, 0.0f, 0.0f, 0.5f); //Black Background
gl.glClearDepthf(1.0f); //Depth Buffer Setup
gl.glEnable(GL10.GL_DEPTH_TEST); //Enables Depth Testing
gl.glDepthFunc(GL10.GL_LEQUAL); //The Type Of Depth Testing To Do
//Really Nice Perspective Calculations
gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST);
for (Node c : StartNodeList) {
StartControlPoints.add(c.getCoord());
}
startLineStrip = new LineStrip(Spline.interpolate(StartControlPoints, 60, CatmullRomType.Chordal));
}
private static String tempBuffer;
public static void addControlPoints(float x, float y) {
Node n = null;
Activity thisAct = (Activity) myContext;
if(nodeTypeCreate != null)
{
switch (nodeTypeCreate)
{
case INPUT:
n = new InputNode(new Coord(x, y),CurrNodeList,CurrControlPoints);
BackendLogic.initializeInputNode(n.getID());
bindableNodes.add(n);
break;
case OUTPUT:
//region OutputNode Fold
n = new OutputNode(new Coord(x, y),CurrNodeList,CurrControlPoints);
final Node curNodeOut = n;
AlertDialog.Builder builderOut = new AlertDialog.Builder(myContext);
builderOut.setPositiveButton("Node Value", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
nodeWaitingBind = curNodeOut;
lBindMode = false;
rBindMode = false;
bindMode = true;
dialog.dismiss();
}
});
builderOut.setNegativeButton("Constant Value", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
final int nID = curNodeOut.getID();
tempBuffer = "";
AlertDialog.Builder builder = new AlertDialog.Builder(myContext);
final TextView textView = new TextView(myContext);
textView.setHeight(50);
textView.setTextColor(Color.GREEN);
textView.setBackgroundColor(Color.BLACK);
builder.setView(textView)
.setCancelable(false)
.setOnKeyListener(new DialogInterface.OnKeyListener() {
@Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP) {
if (keyCode == KeyEvent.KEYCODE_ENTER) {
BackendLogic.initializeOutputNode(nID, tempBuffer);
((InputMethodManager) myContext.getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
dialog.dismiss();
return true;
} else if (keyCode == KeyEvent.KEYCODE_DEL) {
int bufLength = tempBuffer.length();
if (bufLength > 0) {
tempBuffer = tempBuffer.substring(0, bufLength - 1);
CharSequence tempTxt = textView.getText();
CharSequence newTxt = tempTxt.subSequence(0, tempTxt.length() - 1);
textView.setText(newTxt);
}
return true;
}
char tempChar = (char) event.getUnicodeChar();
textView.append(tempChar + "");
tempBuffer += tempChar;
return true;
}
return false;
}
});
AlertDialog alert = builder.create();
alert.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
alert.getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
alert.show();
alert.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
((InputMethodManager) myContext.getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
dialog.dismiss();
}
});
AlertDialog alertOut = builderOut.create();
alertOut.show();
break;
//endregion
case START:
n = new StartNode(new Coord(x, y),CurrNodeList,CurrControlPoints);
break;
case END:
n = new EndNode(new Coord(x, y),CurrNodeList,CurrControlPoints);
break;
case IF:
//region IFNode Fold
ifTempList = CurrNodeList;
ifTempPoints = CurrControlPoints;
leftSet = false;
rightSet = false;
leftNode = null;
rightNode = null;
n = new IfNode(new Coord(x, y),CurrNodeList,CurrControlPoints);
NodesToLoad.add(n);
MyGLRenderer.nodeTypeCreate = NodeType.END;
addControlPoints(x-50f, y -50f);
BackendLogic.initializeIfNode(n.getID());
nodeWaitingBind = n;
curSpinIndex = 0;
thisAct.runOnUiThread(new Runnable() {
@Override
public void run() {
ifMenu();
}
});
break;
//endregion
case STORAGE:
//region StorageNode Fold
n = new StorageNode(new Coord(x, y),CurrNodeList,CurrControlPoints);
final Node curNodeStr = n;
AlertDialog.Builder builderStr = new AlertDialog.Builder(myContext);
builderStr.setPositiveButton("Set Empty", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
BackendLogic.initializeStorageNode(curNodeStr.getID());
bindableNodes.add(curNodeStr);
dialog.dismiss();
}
});
builderStr.setNegativeButton("Set Initial Value", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
final int nID = curNodeStr.getID();
tempBuffer = "";
AlertDialog.Builder builder = new AlertDialog.Builder(myContext);
final TextView textView = new TextView(myContext);
textView.setHeight(50);
textView.setTextColor(Color.GREEN);
textView.setBackgroundColor(Color.BLACK);
builder.setView(textView)
.setCancelable(false)
.setOnKeyListener(new DialogInterface.OnKeyListener() {
@Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP) {
if (keyCode == KeyEvent.KEYCODE_ENTER) {
boolean tempIsNum = tempBuffer.matches("-?\\d+(\\.\\d+)?");
BackendLogic.initializeStorageNode(nID, tempBuffer, tempIsNum);
bindableNodes.add(curNodeStr);
((InputMethodManager) myContext.getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
dialog.dismiss();
return true;
} else if (keyCode == KeyEvent.KEYCODE_DEL) {
int bufLength = tempBuffer.length();
if (bufLength > 0) {
tempBuffer = tempBuffer.substring(0, bufLength - 1);
CharSequence tempTxt = textView.getText();
CharSequence newTxt = tempTxt.subSequence(0, tempTxt.length() - 1);
textView.setText(newTxt);
}
return true;
}
char tempChar = (char) event.getUnicodeChar();
textView.append(tempChar + "");
tempBuffer += tempChar;
return true;
}
return false;
}
});
AlertDialog alert = builder.create();
alert.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
alert.getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
alert.show();
alert.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
((InputMethodManager) myContext.getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
dialog.dismiss();
}
});
AlertDialog alertStr = builderStr.create();
alertStr.show();
break;
//endregion
case SET:
//region SetNode Fold
n = new SetNode(new Coord(x,y), CurrNodeList, CurrControlPoints);
break;
//endregion
case MATH:
//region MathNode Fold
leftSet = false;
rightSet = false;
leftNode = null;
rightNode = null;
n = new MathNode(new Coord(x,y), CurrNodeList, CurrControlPoints);
BackendLogic.initializeMathNode(n.getID());
nodeWaitingBind = n;
curSpinIndex = 0;
thisAct.runOnUiThread(new Runnable() {
@Override
public void run() {
mathMenu();
}
});
bindableNodes.add(n);
break;
//endregion
}
nodeTypeCreate = null;
}
else
{
return;
}
if(!n.getTitle().equals("if"))
NodesToLoad.add(n);
}
public static void translateZ(int z) {
transZ += z;
}
public static void translateY(float y) {
transY += y;
}
public static void translateX(float x) {
transX += x;
}
/**
* Calculates the transform from screen coordinate
* system to world coordinate system coordinates
* for a specific point, given a camera position.
*
* @param touch Coord point of screen touch, the
* actual position on physical screen (ej: 160, 240)
* @return position in WCS.
*/
public Coord GetWorldCoords(GL10 gl, Coord touch, float z) {
GL11 gl11 = (GL11) gl;
GL11ExtensionPack gl11ext = (GL11ExtensionPack) gl;
int[] viewport = new int[4];
float[] modelview = new float[16];
float[] projection = new float[16];
float winX, winY;
FloatBuffer winZ = FloatBuffer.allocate(4);
gl11.glGetFloatv(gl11.GL_MODELVIEW_MATRIX, modelview, 0); // Retrieve The Modelview Matrix
gl11.glGetFloatv(gl11.GL_PROJECTION_MATRIX, projection, 0);
gl11.glGetIntegerv(gl11.GL_VIEWPORT, viewport, 0);
winX = touch.X;
winY = (float) viewport[3] - touch.Y;
gl11.glReadPixels((int) touch.X, (int) winY, 1, 1, gl11ext.GL_DEPTH_COMPONENT, gl11.GL_FLOAT, winZ);
float[] output = new float[4];
GLU.gluUnProject(winX, winY, winZ.get(), modelview, 0, projection, 0, viewport, 0, output, 0);
//Log.w("WorldCoord", output[0] + " , " + output[1]);
return new Coord(output[0] * Math.abs(transZ), output[1] * Math.abs(transZ));
}
public Coord GetWorldCoords(GL10 gl, Coord touch) {
return GetWorldCoords(gl,touch, 0);
}
public void setContext(Context context) {
myContext = context;
}
public Node getNodeTouched(Coord glCoord, CopyOnWriteArrayList<Node> nList, boolean isOrtho)
{
int offset = isOrtho? 4:1;
float x = glCoord.X/offset;
float y = glCoord.Y/offset;
for (int j = nList.size() - 1; j >= 0; j
Node c = nList.get(j);
if (x > c.LBound && x < c.RBound && y < c.UBound && y > c.DBound) {
Log.w("Node dims", "Coord: (" + c.getCoord().X + " , " + c.getCoord().Y + ")" + " width: " + c.Width + " height: " + c.Height);
Log.w("Node TOUCHED", "Coord: (" + x + " , " + y + ")" + "At index:" + j);
return c;
}
}
return null;
}
//region Menu fold
public static void ifMenu()
{
Spinner ifSpinner = new Spinner(myContext);
String[] arraySpinnerIF = new String[] {
"==", "!=", ">", ">=", "<", "<="
};
ArrayAdapter<String> adapterIF = new ArrayAdapter<String>(myContext,
android.R.layout.simple_spinner_item, arraySpinnerIF);
ifSpinner.setAdapter(adapterIF);
ifSpinner.setSelection(curSpinIndex);
ifSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
curSpinVal = parent.getItemAtPosition(position).toString();
curSpinIndex = position;
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
AlertDialog.Builder builderIf = new AlertDialog.Builder(myContext);
builderIf.setView(ifSpinner)
.setPositiveButton("Right Value", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
Activity thisAct = (Activity) myContext;
thisAct.runOnUiThread(new Runnable() {
@Override
public void run() {
rightBindMenu();
}
});
}
})
.setNegativeButton("Left Value", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
Activity thisAct = (Activity) myContext;
thisAct.runOnUiThread(new Runnable() {
@Override
public void run() {
leftBindMenu();
}
});
}
});
AlertDialog alertIF = builderIf.create();
alertIF.show();
}
public static void mathMenu()
{
Spinner mathSpinner = new Spinner(myContext);
String[] arraySpinnerMath = new String[] {
"+", "-", "*", "/", "^", "%"
};
ArrayAdapter<String> adapterMath = new ArrayAdapter<String>(myContext,
android.R.layout.simple_spinner_item, arraySpinnerMath);
mathSpinner.setAdapter(adapterMath);
mathSpinner.setSelection(curSpinIndex);
mathSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
curSpinVal = parent.getItemAtPosition(position).toString();
curSpinIndex = position;
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
AlertDialog.Builder builderIf = new AlertDialog.Builder(myContext);
builderIf.setView(mathSpinner)
.setPositiveButton("Right Value", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
Activity thisAct = (Activity) myContext;
thisAct.runOnUiThread(new Runnable() {
@Override
public void run() {
rightBindMenu();
}
});
}
})
.setNegativeButton("Left Value", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
Activity thisAct = (Activity) myContext;
thisAct.runOnUiThread(new Runnable() {
@Override
public void run() {
leftBindMenu();
}
});
}
});
AlertDialog alertIF = builderIf.create();
alertIF.show();
}
public static void rightBindMenu()
{
AlertDialog.Builder builder = new AlertDialog.Builder(myContext);
builder.setPositiveButton("Node Value", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
rightBuffer = null;
bindMode = true;
rBindMode = true;
dialog.dismiss();
}
});
builder.setNegativeButton("Constant Value", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
tempBuffer = "";
AlertDialog.Builder builder = new AlertDialog.Builder(myContext);
final TextView textView = new TextView(myContext);
textView.setHeight(50);
textView.setTextColor(Color.GREEN);
textView.setBackgroundColor(Color.BLACK);
builder.setView(textView)
.setCancelable(false)
.setOnKeyListener(new DialogInterface.OnKeyListener() {
@Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP) {
if (keyCode == KeyEvent.KEYCODE_ENTER) {
rightBuffer = tempBuffer;
if(leftSet)
{
bindTriple();
((InputMethodManager) myContext.getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
dialog.dismiss();
return true;
}
rightSet = true;
((InputMethodManager) myContext.getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
dialog.dismiss();
Activity thisAct = (Activity) myContext;
thisAct.runOnUiThread(new Runnable() {
@Override
public void run() {
if(nodeWaitingBind.getTitle().equals("if"))
ifMenu();
else
mathMenu();
}
});
return true;
} else if (keyCode == KeyEvent.KEYCODE_DEL) {
int bufLength = tempBuffer.length();
if (bufLength > 0) {
tempBuffer = tempBuffer.substring(0, bufLength - 1);
CharSequence tempTxt = textView.getText();
CharSequence newTxt = tempTxt.subSequence(0, tempTxt.length() - 1);
textView.setText(newTxt);
}
return true;
}
char tempChar = (char) event.getUnicodeChar();
textView.append(tempChar + "");
tempBuffer += tempChar;
return true;
}
return false;
}
});
AlertDialog alert = builder.create();
alert.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
alert.getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
alert.show();
alert.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
((InputMethodManager) myContext.getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public static void leftBindMenu()
{
AlertDialog.Builder builder = new AlertDialog.Builder(myContext);
builder.setPositiveButton("Node Value", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
leftBuffer = null;
bindMode = true;
lBindMode = true;
dialog.dismiss();
}
});
builder.setNegativeButton("Constant Value", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
tempBuffer = "";
AlertDialog.Builder builder = new AlertDialog.Builder(myContext);
final TextView textView = new TextView(myContext);
textView.setHeight(50);
textView.setTextColor(Color.GREEN);
textView.setBackgroundColor(Color.BLACK);
builder.setView(textView)
.setCancelable(false)
.setOnKeyListener(new DialogInterface.OnKeyListener() {
@Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP) {
if (keyCode == KeyEvent.KEYCODE_ENTER) {
leftBuffer = tempBuffer;
if(rightSet)
{
bindTriple();
((InputMethodManager) myContext.getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
dialog.dismiss();
return true;
}
leftSet = true;
((InputMethodManager) myContext.getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
dialog.dismiss();
Activity thisAct = (Activity) myContext;
thisAct.runOnUiThread(new Runnable() {
@Override
public void run() {
if(nodeWaitingBind.getTitle().equals("if"))
ifMenu();
else
mathMenu();
}
});
return true;
} else if (keyCode == KeyEvent.KEYCODE_DEL) {
int bufLength = tempBuffer.length();
if (bufLength > 0) {
tempBuffer = tempBuffer.substring(0, bufLength - 1);
CharSequence tempTxt = textView.getText();
CharSequence newTxt = tempTxt.subSequence(0, tempTxt.length() - 1);
textView.setText(newTxt);
}
return true;
}
char tempChar = (char) event.getUnicodeChar();
textView.append(tempChar + "");
tempBuffer += tempChar;
return true;
}
return false;
}
});
AlertDialog alert = builder.create();
alert.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
alert.getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
alert.show();
alert.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
((InputMethodManager) myContext.getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
//endregion
public static void bindTriple(){
if(leftNode != null)
{
if(rightNode != null)
{
BackendLogic.setBackendTrip(nodeWaitingBind.getID(), leftNode.getID(), curSpinVal, rightNode.getID());
}
else
{
boolean tempIsNum = rightBuffer.matches("-?\\d+(\\.\\d+)?");
BackendLogic.setBackendTrip(nodeWaitingBind.getID(), leftNode.getID(), curSpinVal, rightBuffer, tempIsNum);
}
}
else if(rightNode != null)
{
boolean tempIsNum = leftBuffer.matches("-?\\d+(\\.\\d+)?");
BackendLogic.setBackendTrip(nodeWaitingBind.getID(), leftBuffer, tempIsNum, curSpinVal, rightNode.getID());
}
else
{
boolean tempLeftNum = leftBuffer.matches("-?\\d+(\\.\\d+)?");
boolean tempRightNum = rightBuffer.matches("-?\\d+(\\.\\d+)?");
BackendLogic.setBackendTrip(nodeWaitingBind.getID(), leftBuffer, tempLeftNum, curSpinVal, rightBuffer, tempRightNum);
}
}
}
|
package com.thindeck.cockpit;
import com.thindeck.api.Base;
import com.thindeck.api.Repo;
import java.io.IOException;
import org.takes.Request;
import org.takes.Response;
import org.takes.Take;
import org.takes.misc.Href;
import org.takes.rs.xe.XeAppend;
import org.takes.rs.xe.XeChain;
import org.takes.rs.xe.XeDirectives;
import org.takes.rs.xe.XeLink;
import org.takes.rs.xe.XeSource;
import org.takes.rs.xe.XeTransform;
import org.xembly.Directives;
/**
* Repos.
*
* @author Yegor Bugayenko (yegor@teamed.io)
* @version $Id$
* @since 0.5
* @checkstyle ClassDataAbstractionCouplingCheck (500 lines)
* @checkstyle MultipleStringLiteralsCheck (500 lines)
*/
public final class TkRepos implements Take {
/**
* Base.
*/
private final transient Base base;
/**
* Ctor.
* @param bse Base
*/
TkRepos(final Base bse) {
this.base = bse;
}
@Override
public Response act(final Request req) throws IOException {
final Href home = new Href("/r");
return new RsPage(
"/xsl/repos.xsl",
this.base,
req,
new XeLink("add", "/add"),
new XeAppend(
"repos",
new XeTransform<>(
new RqUser(req, this.base).get().repos().iterate(),
// @checkstyle AnonInnerLengthCheck (50 lines)
new XeTransform.Func<Repo>() {
@Override
public XeSource transform(final Repo repo)
throws IOException {
return new XeAppend(
"repo",
new XeDirectives(
new Directives().add("name").set(
repo.name()
)
),
new XeChain(
new XeLink("open", home.path(repo.name())),
new XeLink(
"delete",
home.path(repo.name()).path("delete")
)
)
);
}
}
)
)
);
}
}
|
package com.palsulich.nyubustracker.activities;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.ColorDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
import com.palsulich.nyubustracker.R;
import com.palsulich.nyubustracker.adapters.StopAdapter;
import com.palsulich.nyubustracker.adapters.TimeAdapter;
import com.palsulich.nyubustracker.helpers.BusManager;
import com.palsulich.nyubustracker.helpers.FileGrabber;
import com.palsulich.nyubustracker.models.Bus;
import com.palsulich.nyubustracker.models.Route;
import com.palsulich.nyubustracker.models.Stop;
import com.palsulich.nyubustracker.models.Time;
import org.json.JSONException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;
import se.emilsjolander.stickylistheaders.StickyListHeadersListView;
public class MainActivity extends Activity{
Stop startStop; // Stop object to keep track of the start location of the desired route.
Stop endStop; // Keep track of the desired end location.
ArrayList<Route> routesBetweenStartAndEnd; // List of all routes between start and end.
ArrayList<Time> timesBetweenStartAndEnd; // List of all times between start and end.
HashMap<String, Boolean> clickableMapMarkers; // Hash of all markers which are clickable (so we don't zoom in on buses).
ArrayList<Marker> busesOnMap = new ArrayList<Marker>();
Time nextBusTime;
// mFileGrabber helps to manage cached files/pull new files from the network.
FileGrabber mFileGrabber;
Timer timeUntilTimer; // Timer used to refresh the "time until next bus" every minute, on the minute.
Timer busRefreshTimer; // Timer used to refresh the bus locations every few seconds.
private GoogleMap mMap; // Map to display all stops, segments, and buses.
private boolean haveAMap = false; // Flag to see if the device can display a map.
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
MapFragment mFrag = ((MapFragment) getFragmentManager().findFragmentById(R.id.map));
if (mFrag != null) mMap = mFrag.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
// The Map is verified. It is now safe to manipulate the map.
mMap.getUiSettings().setRotateGesturesEnabled(false);
mMap.getUiSettings().setZoomControlsEnabled(false);
haveAMap = true;
}
else haveAMap = false;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Log.v("General Debugging", "onCreate!");
setContentView(R.layout.activity_main);
mFileGrabber = new FileGrabber(getCacheDir());
renewTimeUntilTimer(); // Creates and starts the timer to refresh time until next bus.
setUpMapIfNeeded(); // Instantiates mMap, if it needs to be.
if (haveAMap) mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
@Override
public boolean onMarkerClick(Marker marker) {
return !clickableMapMarkers.get(marker.getId()); // Return true to consume the event.
}
});
// List just for development use to display all
//final ListView listView = (ListView) findViewById(R.id.mainActivityList);
// Singleton BusManager to keep track of all stops, routes, etc.
final BusManager sharedManager = BusManager.getBusManager();
// Only parse stops, routes, buses, times, and segments if we don't have them. Could be more robust.
if (!sharedManager.hasStops() && !sharedManager.hasRoutes()) {
try {
// The Class being created from the parsing *does* the parsing.
// mFileGrabber.get*JSON() returns a JSONObject.
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
Stop.parseJSON(mFileGrabber.getStopJSON(networkInfo));
Route.parseJSON(mFileGrabber.getRouteJSON(networkInfo));
BusManager.parseTimes(mFileGrabber.getVersionJSON(networkInfo), mFileGrabber, networkInfo); // Must be after routes are parsed!
// Ensure we start the app with predefined favorite stops.
BusManager.syncFavoriteStops(getSharedPreferences(Stop.FAVORITES_PREF, MODE_PRIVATE));
if (haveAMap) Bus.parseJSON(mFileGrabber.getVehicleJSON(networkInfo));
if (haveAMap) BusManager.parseSegments(mFileGrabber.getSegmentsJSON(networkInfo));
if (networkInfo == null || !networkInfo.isConnected()){
Context context = getApplicationContext();
CharSequence text = "Unable to connect to the network.";
int duration = Toast.LENGTH_SHORT;
if (context != null){
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
for (Route r : sharedManager.getRoutes()){
Log.v("Hard Combine Debugging", "Route " + r.getLongName());
for (Stop s : r.getStops()){
Log.v("Hard Combine Debugging", s.getName() + " | " + s.getID());
}
}
// Initialize start and end stops. By default, they are Lafayette and Broadway.
setStartStop(sharedManager.getStopByName(mFileGrabber.getStartStopFile()));
setEndStop(sharedManager.getStopByName(mFileGrabber.getEndStopFile()));
// Update the map to show the corresponding stops, buses, and segments.
if (routesBetweenStartAndEnd != null) updateMapWithNewStartOrEnd();
// Get the location of the buses every 10 sec.
renewBusRefreshTimer();
}
/*
renewTimeUntilTimer() creates a new timer that calls setNextBusTime() every minute on the minute.
*/
private void renewTimeUntilTimer() {
Calendar rightNow = Calendar.getInstance();
if (timeUntilTimer != null) timeUntilTimer.cancel();
timeUntilTimer = new Timer();
timeUntilTimer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
if(startStop != null && endStop != null) setNextBusTime();
}
});
}
}, (60 - rightNow.get(Calendar.SECOND)) * 1000, 60000);
}
private void renewBusRefreshTimer(){
if(haveAMap){
if (busRefreshTimer != null) busRefreshTimer.cancel();
busRefreshTimer = new Timer();
busRefreshTimer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
try{
if (routesBetweenStartAndEnd != null){
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo == null || !networkInfo.isConnected()){
Context context = getApplicationContext();
CharSequence text = "Unable to connect to the network.";
int duration = Toast.LENGTH_SHORT;
if (context != null){
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
else{
Bus.parseJSON(mFileGrabber.getVehicleJSON(networkInfo));
updateMapWithNewBusLocations();
}
}
} catch (JSONException e){
e.printStackTrace();
}
}
});
}
}, 0, 10000);
}
}
@Override
public void onDestroy() {
super.onDestroy();
//Log.v("General Debugging", "onDestroy!");
cacheToAndStartStop(); // Remember user's preferences across lifetimes.
timeUntilTimer.cancel();
busRefreshTimer.cancel();
}
@Override
public void onPause() {
super.onPause();
//Log.v("General Debugging", "onPause!");
cacheToAndStartStop();
if (timeUntilTimer != null) timeUntilTimer.cancel();
if (busRefreshTimer != null) busRefreshTimer.cancel();
}
@Override
public void onResume() {
super.onResume();
//Log.v("General Debugging", "onResume!");
setNextBusTime();
renewTimeUntilTimer();
renewBusRefreshTimer();
setUpMapIfNeeded();
}
public void cacheToAndStartStop() {
FileGrabber mFileGrabber = new FileGrabber(getCacheDir());
if (endStop != null) mFileGrabber.setEndStop(endStop.getName()); // Creates or updates cache file.
if (startStop != null) mFileGrabber.setStartStop(startStop.getName());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public static Bitmap rotateBitmap(Bitmap source, float angle)
{
Matrix matrix = new Matrix();
matrix.postRotate(angle);
return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
}
// Clear the map of all buses and put them all back on in their new locations.
private void updateMapWithNewBusLocations(){
if (haveAMap){
BusManager sharedManager = BusManager.getBusManager();
for (Marker m : busesOnMap){
m.remove();
}
busesOnMap = new ArrayList<Marker>();
if (clickableMapMarkers == null) clickableMapMarkers = new HashMap<String, Boolean>(); // New set of buses means new set of clickable markers!
Route r = sharedManager.getRouteByName(nextBusTime.getRoute());
if (r != null){
for (Bus b : sharedManager.getBuses()){
//Log.v("BusLocations", "bus id: " + b.getID() + ", bus route: " + b.getRoute() + " vs route: " + r.getID());
if (b.getRoute().equals(r.getID())){
Marker mMarker = mMap.addMarker(new MarkerOptions()
.position(b.getLocation())
.icon(BitmapDescriptorFactory
.fromBitmap(
rotateBitmap(
BitmapFactory.decodeResource(
this.getResources(),
R.drawable.ic_bus_arrow),
b.getHeading())
))
.anchor(0.5f, 0.5f));
clickableMapMarkers.put(mMarker.getId(), false); // Unable to click on buses.
busesOnMap.add(mMarker);
}
}
}
}
}
// Clear the map, because we may have just changed what route we wish to display. Then, add everything back onto the map.
private void updateMapWithNewStartOrEnd(){
if (haveAMap){
setUpMapIfNeeded();
mMap.clear();
clickableMapMarkers = new HashMap<String, Boolean>();
LatLngBounds.Builder builder = new LatLngBounds.Builder();
boolean validBuilder = false;
BusManager sharedManager = BusManager.getBusManager();
Route r = sharedManager.getRouteByName(nextBusTime.getRoute());
if (r != null){
//Log.v("MapDebugging", "Updating map with route: " + r.getLongName());
for (Stop s : r.getStops()){
// Only put one representative from a family of stops on the p
Marker mMarker = mMap.addMarker(new MarkerOptions() // Adds a balloon for every stop to the map.
.position(s.getLocation())
.title(s.getName())
.anchor(0.5f, 0.5f)
.icon(BitmapDescriptorFactory
.fromBitmap(
BitmapFactory.decodeResource(
this.getResources(),
R.drawable.ic_map_stop))));
clickableMapMarkers.put(mMarker.getId(), true);
}
updateMapWithNewBusLocations();
// Adds the segments of every Route to the map.
for (PolylineOptions p : r.getSegments()){
//Log.v("MapDebugging", "Trying to add a segment to the map.");
if (p != null){
for (LatLng loc : p.getPoints()){
validBuilder = true;
builder.include(loc);
}
p.color(getResources().getColor(R.color.purple));
mMap.addPolyline(p);
}
//else Log.v("MapDebugging", "Segment was null for " + r.getID());
}
}
if (validBuilder){
LatLngBounds bounds = builder.build();
try{
mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 30));
} catch(IllegalStateException e) { // In case the view is not done being created.
e.printStackTrace();
mMap.moveCamera(
CameraUpdateFactory
.newLatLngBounds(
bounds,
this.getResources().getDisplayMetrics().widthPixels,
this.getResources().getDisplayMetrics().heightPixels,
100));
}
}
}
}
private void setEndStop(Stop stop) {
if (stop != null) { // Make sure we actually have a stop!
// Check there is a route between these stops.
ArrayList<Route> routes = new ArrayList<Route>(); // All the routes connecting the two.
for (Route r : startStop.getRoutes()) {
if (r.hasStop(stop.getName()) && stop.getTimesOfRoute(r.getLongName()).size() > 0) {
routes.add(r);
}
}
if (routes.size() > 0) {
endStop = stop;
((Button) findViewById(R.id.to_button)).setText(stop.getUltimateName());
if (startStop != null){
setNextBusTime(); // Don't set the next bus if we don't have a valid route.
if (routesBetweenStartAndEnd != null && haveAMap) updateMapWithNewStartOrEnd();
}
}
}
}
private void setStartStop(Stop stop) {
if (stop != null){
if (endStop == stop) { // We have an end stop and its name is the same as stopName.
// Swap the start and end stops.
Stop temp = startStop;
startStop = endStop;
((Button) findViewById(R.id.from_button)).setText(startStop.getUltimateName());
endStop = temp;
((Button) findViewById(R.id.to_button)).setText(endStop.getUltimateName());
setNextBusTime();
updateMapWithNewStartOrEnd();
}
else { // We have a new start. So, we must ensure the end is actually connected. If not, pick a random connected stop.
startStop = stop;
((Button) findViewById(R.id.from_button)).setText(stop.getUltimateName());
if (endStop != null){
// Loop through all connected Routes.
for (Route r : startStop.getRoutes()){
if (r.hasStop(endStop.getName()) && endStop.getTimesOfRoute(r.getLongName()).size() > 0){ // If the current endStop is connected, we don't have to change endStop.
setNextBusTime();
updateMapWithNewStartOrEnd();
return;
}
}
// If we did not return above, the current endStop is not connected to the new
// startStop. So, by default, pick the first connected stop.
BusManager sharedManager = BusManager.getBusManager();
setEndStop(sharedManager.getStopByName("715 Broadway at Washington Square"));
}
}
}
}
private void setNextBusTime() {
/*
Have a start stop that may have children, and an end stop that may have children.
Find all routes that have both stops (or their children).
Figure out which direction the user is going.
Get all times in that direction, on all available routes, from that start stop (or its children).
Insert the current time into that list and sort the list.
Next bus time is the first element after the current time.
Set the view values.
*/
if (timeUntilTimer != null) timeUntilTimer.cancel(); // Don't want to be interrupted in the middle of this.
if (busRefreshTimer != null) busRefreshTimer.cancel();
Calendar rightNow = Calendar.getInstance();
ArrayList<Route> startRoutes = startStop.getRoutes(); // All the routes leaving the start stop.
ArrayList<Route> endRoutes = endStop.getRoutes();
ArrayList<Route> availableRoutes = new ArrayList<Route>(); // All the routes connecting the two.
for (Route r : startRoutes) {
if (endRoutes.contains(r)){
availableRoutes.add(r);
}
}
int bestDistance = BusManager.distanceBetween(startStop, endStop);
int testDistance = BusManager.distanceBetween(startStop.getOppositeStop(), endStop.getOppositeStop());
if (testDistance < bestDistance){
startStop = startStop.getOppositeStop();
endStop = endStop.getOppositeStop();
}
testDistance = BusManager.distanceBetween(startStop, endStop.getOppositeStop());
if (testDistance < bestDistance){
endStop = endStop.getOppositeStop();
}
testDistance = BusManager.distanceBetween(startStop.getOppositeStop(), endStop);
if (testDistance < bestDistance){
startStop = startStop.getOppositeStop();
}
if (availableRoutes.size() > 0) {
ArrayList<Time> tempTimesBetweenStartAndEnd = new ArrayList<Time>();
for (Route r : availableRoutes) {
// Get the Times at this stop for this route.
ArrayList<Time> times;
if ((times = startStop.getTimesOfRoute(r.getLongName())).size() > 0){
tempTimesBetweenStartAndEnd.addAll(times);
}
}
if (tempTimesBetweenStartAndEnd.size() > 0){ // We actually found times.
// Here, we grab the list of all times of all routes between the start and end, add in the current
// time, then sort that list of times. That way, we know the first bus Time after the current time
// is the Time of the soonest next Bus.
timesBetweenStartAndEnd = new ArrayList<Time>(tempTimesBetweenStartAndEnd);
routesBetweenStartAndEnd = availableRoutes;
Time currentTime = new Time(rightNow.get(Calendar.HOUR_OF_DAY), rightNow.get(Calendar.MINUTE));
tempTimesBetweenStartAndEnd.add(currentTime);
Collections.sort(tempTimesBetweenStartAndEnd, Time.compare);
Collections.sort(timesBetweenStartAndEnd, Time.compare);
int index = tempTimesBetweenStartAndEnd.indexOf(currentTime);
nextBusTime = tempTimesBetweenStartAndEnd.get((index + 1) % tempTimesBetweenStartAndEnd.size());
((TextView) findViewById(R.id.next_bus)).setText(currentTime.getTimeAsStringUntil(nextBusTime));
((TextView) findViewById(R.id.times_button)).setText(nextBusTime.toString());
updateMapWithNewStartOrEnd();
}
}
renewBusRefreshTimer();
renewTimeUntilTimer();
}
CompoundButton.OnCheckedChangeListener cbListener = new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
Stop s = (Stop) buttonView.getTag();
s.setFavorite(isChecked);
getSharedPreferences(Stop.FAVORITES_PREF, MODE_PRIVATE)
.edit().putBoolean(s.getID(), isChecked)
.commit();
Log.v("Dialog", "Checkbox is " + isChecked);
}
};
public void createEndDialog(View view) {
// Get all stops connected to the start stop.
final ArrayList<Stop> connectedStops = BusManager.getBusManager().getConnectedStops(startStop);
ListView listView = new ListView(this); // ListView to populate the dialog.
AlertDialog.Builder builder = new AlertDialog.Builder(this); // Used to build the dialog with the list of connected Stops.
builder.setView(listView);
final Dialog dialog = builder.create();
// An adapter takes some data, then adapts it to fit into a view. The adapter supplies the individual view elements of
// the list view. So, in this case, we supply the StopAdapter with a list of stops, and it gives us back the nice
// views with a heart button to signify favorites and a TextView with the name of the stop.
// We provide the onClickListeners to the adapter, which then attaches them to the respective views.
StopAdapter adapter = new StopAdapter(getApplicationContext(), connectedStops,
new View.OnClickListener() {
@Override
public void onClick(View view) {
// Clicked on a Stop. So, make it the end and dismiss the dialog.
Stop s = (Stop) view.getTag();
setEndStop(s); // Actually set the end stop.
dialog.dismiss();
}
}, cbListener);
listView.setAdapter(adapter);
dialog.setCanceledOnTouchOutside(true);
dialog.show(); // Dismissed when a stop is clicked.
}
public void createStartDialog(View view) {
final ArrayList<Stop> stops = BusManager.getBusManager().getStops(); // Show every stop as an option to start.
ListView listView = new ListView(this);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(listView);
final Dialog dialog = builder.create();
StopAdapter adapter = new StopAdapter(getApplicationContext(), stops,
new View.OnClickListener() {
@Override
public void onClick(View view) {
Stop s = (Stop) view.getTag();
setStartStop(s); // Actually set the start stop.
dialog.dismiss();
}
}, cbListener);
listView.setAdapter(adapter);
dialog.setCanceledOnTouchOutside(true);
dialog.show();
}
public void createTimesDialog(View view) {
// Library provided ListView with headers that (gasp) stick to the top.
StickyListHeadersListView listView = new StickyListHeadersListView(this);
listView.setDivider(new ColorDrawable(0xffffff));
listView.setDividerHeight(1);
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
TimeAdapter adapter = new TimeAdapter(getApplicationContext(), timesBetweenStartAndEnd);
listView.setAdapter(adapter);
int index = timesBetweenStartAndEnd.indexOf(nextBusTime);
listView.setSelection(index);
builder.setView(listView);
Dialog dialog = builder.create();
dialog.setCanceledOnTouchOutside(true);
dialog.show();
}
}
|
package com.toomasr.sgf4j.gui;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import com.toomasr.sgf4j.Sgf;
import com.toomasr.sgf4j.board.BoardPane;
import com.toomasr.sgf4j.board.BoardStone;
import com.toomasr.sgf4j.board.CoordinateSquare;
import com.toomasr.sgf4j.board.GuiBoardListener;
import com.toomasr.sgf4j.board.StoneState;
import com.toomasr.sgf4j.board.VirtualBoard;
import com.toomasr.sgf4j.filetree.FileTreeView;
import com.toomasr.sgf4j.movetree.EmptyTriangle;
import com.toomasr.sgf4j.movetree.GlueStone;
import com.toomasr.sgf4j.movetree.GlueStoneType;
import com.toomasr.sgf4j.movetree.TreeStone;
import com.toomasr.sgf4j.parser.Game;
import com.toomasr.sgf4j.parser.GameNode;
import com.toomasr.sgf4j.parser.Util;
import com.toomasr.sgf4j.properties.AppState;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.ScrollPane.ScrollBarPolicy;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.TilePane;
import javafx.scene.layout.VBox;
public class MainUI {
private Button nextButton;
private GameNode currentMove = null;
private GameNode prevMove = null;
private Game game;
private VirtualBoard virtualBoard;
private BoardStone[][] board;
private GridPane movePane;
private GridPane boardPane;
private Map<GameNode, TreeStone> nodeToTreeStone = new HashMap<>();
private TextArea commentArea;
private Button previousButton;
private ScrollPane treePaneScrollPane;
public MainUI() {
board = new BoardStone[19][19];
virtualBoard = new VirtualBoard();
virtualBoard.addBoardListener(new GuiBoardListener(this));
}
public Pane buildUI() throws Exception {
HBox topHBox = new HBox();
enableKeyboardShortcuts(topHBox);
VBox fileTreePane = generateFileTreePane();
fileTreePane.setAlignment(Pos.CENTER);
topHBox.getChildren().add(fileTreePane);
GridPane boardPane = generateBoardPane();
TilePane buttonPane = generateButtonPane();
VBox treePane = generateMoveTreePane();
VBox centerVbox = new VBox();
centerVbox.setMaxWidth(600);
centerVbox.setAlignment(Pos.CENTER);
centerVbox.getChildren().add(boardPane);
centerVbox.getChildren().add(buttonPane);
centerVbox.getChildren().add(treePane);
topHBox.getChildren().add(centerVbox);
VBox mostRightBox = new VBox();
mostRightBox = generateCommentPane();
topHBox.getChildren().add(mostRightBox);
String game = "src/main/resources/game.sgf";
initializeGame(Paths.get(game));
return topHBox;
}
private VBox generateCommentPane() {
VBox rtrn = new VBox();
commentArea = new TextArea();
commentArea.setFocusTraversable(false);
commentArea.setWrapText(true);
commentArea.setPrefSize(300, 600);
rtrn.getChildren().add(commentArea);
return rtrn;
}
private void initializeGame(Path pathToSgf) {
this.game = Sgf.createFromPath(pathToSgf);
currentMove = this.game.getRootNode();
prevMove = null;
// reset our virtual board and actual board
virtualBoard = new VirtualBoard();
virtualBoard.addBoardListener(new GuiBoardListener(this));
boardPane.getChildren().clear();
for (int i = 0; i < 21; i++) {
if (i > 1 && i < 20) {
board[i - 1] = new BoardStone[19];
}
for (int j = 0; j < 21; j++) {
if (i == 0 || j == 0 || i == 20 || j == 20) {
CoordinateSquare btn = new CoordinateSquare(i, j);
boardPane.add(btn, i, j);
}
else {
BoardStone btn = new BoardStone(i, j);
boardPane.add(btn, i, j);
board[i - 1][j - 1] = btn;
}
}
}
placePreGameStones(game);
// construct the tree of the moves
nodeToTreeStone = new HashMap<>();
movePane.getChildren().clear();
movePane.add(new EmptyTriangle(), 1, 0);
GameNode rootNode = game.getRootNode();
populateMoveTreePane(rootNode, 0);
showMarkersForMove(rootNode);
showCommentForMove(rootNode);
}
private void placePreGameStones(Game game) {
// if there are any moves that should already be on the board
// then lets make it so
if (game.getProperty("AB") != null) {
String[] blackStones = game.getProperty("AB").split(",");
for (int i = 0; i < blackStones.length; i++) {
int[] moveCoords = Util.alphaToCoords(blackStones[i]);
virtualBoard.placeStone(StoneState.BLACK, moveCoords[0], moveCoords[1]);
}
}
// and the same story for white
if (game.getProperty("AW") != null) {
String[] blackStones = game.getProperty("AW").split(",");
for (int i = 0; i < blackStones.length; i++) {
int[] moveCoords = Util.alphaToCoords(blackStones[i]);
virtualBoard.placeStone(StoneState.WHITE, moveCoords[0], moveCoords[1]);
}
}
}
private void populateMoveTreePane(GameNode node, int depth) {
// we draw out only actual moves
if (node.isMove()) {
TreeStone treeStone = new TreeStone(node);
if (node.getPrevNode() == null || !node.getPrevNode().isMove()) {
treeStone = new TreeStone(node, false, true);
}
else if (node.getNextNode() == null) {
treeStone = new TreeStone(node, true, false);
}
movePane.add(treeStone, node.getMoveNo() + 1, node.getVisualDepth());
nodeToTreeStone.put(node, treeStone);
treeStone.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
TreeStone stone = (TreeStone) event.getSource();
fastForwardTo(stone.getMove());
}
});
}
// and draw the next node on this line of play
if (node.getNextNode() != null) {
populateMoveTreePane(node.getNextNode(), depth + node.getVisualDepth());
}
// populate the children also
if (node.hasChildren()) {
Set<GameNode> children = node.getChildren();
// will determine whether the glue stone should be a single
// diagonal or a multiple (diagonal and vertical)
GlueStoneType gStoneType = children.size() > 1 ? GlueStoneType.MULTIPLE : GlueStoneType.DIAGONAL;
for (Iterator<GameNode> ite = children.iterator(); ite.hasNext();) {
GameNode childNode = ite.next();
// the last glue shouldn't be a MULTIPLE
if (GlueStoneType.MULTIPLE.equals(gStoneType) && !ite.hasNext()) {
gStoneType = GlueStoneType.DIAGONAL;
}
// also draw all the "missing" glue stones
for (int i = node.getVisualDepth()+2; i < childNode.getVisualDepth(); i++) {
movePane.add(new GlueStone(GlueStoneType.VERTICAL), node.getMoveNo() + 1, i);
}
// glue stone for the node
movePane.add(new GlueStone(gStoneType), node.getMoveNo() + 1, childNode.getVisualDepth());
// and draw the actual node
populateMoveTreePane(childNode, depth + childNode.getVisualDepth());
}
}
}
/*
* Generates the boilerplate for the move tree pane. The
* pane is actually populated during game initialization.
*/
private VBox generateMoveTreePane() {
VBox rtrn = new VBox();
movePane = new GridPane();
movePane.setPadding(new Insets(0, 0, 0, 0));
movePane.setStyle("-fx-background-color: white");
treePaneScrollPane = new ScrollPane(movePane);
treePaneScrollPane.setPrefHeight(150);
treePaneScrollPane.setHbarPolicy(ScrollBarPolicy.ALWAYS);
treePaneScrollPane.setVbarPolicy(ScrollBarPolicy.AS_NEEDED);
rtrn.getChildren().add(treePaneScrollPane);
return rtrn;
}
private void fastForwardTo(GameNode move) {
// clear the board
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
board[i][j].removeStone();
}
}
placePreGameStones(game);
deHighLightStoneInTree(currentMove);
removeMarkersForNode(currentMove);
virtualBoard.fastForwardTo(move);
highLightStoneOnBoard(move);
}
private VBox generateFileTreePane() {
VBox vbox = new VBox();
vbox.setPrefWidth(200);
TreeView<File> treeView = new FileTreeView();
treeView.setFocusTraversable(false);
vbox.getChildren().add(treeView);
treeView.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
if (event.getClickCount() == 2) {
TreeItem<File> item = treeView.getSelectionModel().getSelectedItem();
File file = item.getValue().toPath().toFile();
if (file.isFile()) {
initializeGame(item.getValue().toPath());
}
AppState.getInstance().addProperty(AppState.CURRENT_FILE, file.getAbsolutePath());
}
}
});
return vbox;
}
private TilePane generateButtonPane() {
TilePane pane = new TilePane();
pane.setAlignment(Pos.CENTER);
pane.setMaxWidth(700);
pane.getStyleClass().add("bordered");
TextField moveNoField = new TextField("0");
moveNoField.setFocusTraversable(false);
moveNoField.setMaxWidth(40);
moveNoField.setEditable(false);
nextButton = new Button("Next");
nextButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
handleNextPressed();
}
});
previousButton = new Button("Previous");
previousButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
handlePreviousPressed();
}
});
pane.setPrefColumns(1);
pane.getChildren().add(previousButton);
pane.getChildren().add(moveNoField);
pane.getChildren().add(nextButton);
return pane;
}
private void handleNextPressed() {
if (currentMove.getNextNode() != null) {
prevMove = currentMove;
currentMove = currentMove.getNextNode();
virtualBoard.makeMove(currentMove, prevMove);
// scroll the scrollpane to make
// the highlighted move visible
ensureVisibleForActiveTreeNode(currentMove);
}
}
public void playMove(GameNode move, GameNode prevMove) {
this.currentMove = move;
this.prevMove = prevMove;
// we actually have a previous move!
if (prevMove != null) {
// de-highlight previously highlighted move
if (prevMove.isMove()) {
deHighLightStoneOnBoard(prevMove);
}
// even non moves can haver markers
removeMarkersForNode(prevMove);
}
if (move != null) {
highLightStoneOnBoard(move);
}
// highlight stone in the tree pane
deHighLightStoneInTree(prevMove);
highLightStoneInTree(move);
// show the associated comment
showCommentForMove(move);
// handle the prev and new markers
showMarkersForMove(move);
nextButton.requestFocus();
}
public void handlePreviousPressed() {
if (currentMove.getParentNode() != null) {
prevMove = currentMove;
currentMove = currentMove.getParentNode();
virtualBoard.undoMove(prevMove, currentMove);
}
}
public void undoMove(GameNode move, GameNode prevMove) {
this.currentMove = prevMove;
this.prevMove = move;
if (move != null) {
removeMarkersForNode(move);
}
if (prevMove != null) {
showMarkersForMove(prevMove);
showCommentForMove(prevMove);
if (prevMove.isMove())
highLightStoneOnBoard(prevMove);
}
deHighLightStoneInTree(move);
highLightStoneInTree(prevMove);
ensureVisibleForActiveTreeNode(prevMove);
// rather have previous move button have focus
previousButton.requestFocus();
}
private void ensureVisibleForActiveTreeNode(GameNode move) {
if (move != null && move.isMove()) {
TreeStone stone = nodeToTreeStone.get(move);
// the movetree is not yet fully operational and some
// points don't exist in the map yet
if (stone == null)
return;
double width = treePaneScrollPane.getContent().getBoundsInLocal().getWidth();
double x = stone.getBoundsInParent().getMaxX();
double scrollTo = ((x) - 11 * 30) / (width - 21 * 30);
treePaneScrollPane.setHvalue(scrollTo);
}
}
private void highLightStoneInTree(GameNode move) {
TreeStone stone = nodeToTreeStone.get(move);
// can remove the null check at one point when the
// tree is fully implemented
if (stone != null) {
stone.highLight();
stone.requestFocus();
}
}
private void deHighLightStoneInTree(GameNode node) {
if (node != null && node.isMove()) {
TreeStone stone = nodeToTreeStone.get(node);
if (stone != null) {
stone.deHighLight();
}
else {
throw new RuntimeException("Unable to find node for move " + node);
}
}
}
private void showCommentForMove(GameNode move) {
String comment = move.getProperty("C");
if (comment == null) {
comment = "";
}
// some helpers I used for parsing needs to be undone - see the Parser.java
// in sgf4j project
comment = comment.replaceAll("@@@@@", "\\\\\\[");
comment = comment.replaceAll("
// lets do some replacing - see http://www.red-bean.com/sgf/sgf4.html#text
comment = comment.replaceAll("\\\\\n", "");
comment = comment.replaceAll("\\\\:", ":");
comment = comment.replaceAll("\\\\\\]", "]");
comment = comment.replaceAll("\\\\\\[", "[");
commentArea.setText(comment);
}
private void showMarkersForMove(GameNode move) {
String markerProp = move.getProperty("L");
if (markerProp != null) {
int alphaIdx = 0;
String[] markers = markerProp.split("\\]\\[");
for (int i = 0; i < markers.length; i++) {
int[] coords = Util.alphaToCoords(markers[i]);
board[coords[0]][coords[1]].addOverlayText(Util.alphabet[alphaIdx++]);
}
}
}
private void removeMarkersForNode(GameNode node) {
String markerProp = node.getProperty("L");
if (markerProp != null) {
String[] markers = markerProp.split("\\]\\[");
for (int i = 0; i < markers.length; i++) {
int[] coords = Util.alphaToCoords(markers[i]);
board[coords[0]][coords[1]].removeOverlayText();
}
}
}
private void highLightStoneOnBoard(GameNode move) {
String currentMove = move.getMoveString();
int[] moveCoords = Util.alphaToCoords(currentMove);
board[moveCoords[0]][moveCoords[1]].highLightStone();
}
private void deHighLightStoneOnBoard(GameNode prevMove) {
String prevMoveAsStr = prevMove.getMoveString();
int[] moveCoords = Util.alphaToCoords(prevMoveAsStr);
board[moveCoords[0]][moveCoords[1]].deHighLightStone();
}
private GridPane generateBoardPane() {
boardPane = new BoardPane(19, 19);
for (int i = 0; i < 21; i++) {
if (i > 1 && i < 20) {
board[i - 1] = new BoardStone[19];
}
for (int j = 0; j < 21; j++) {
if (i == 0 || j == 0 || i == 20 || j == 20) {
CoordinateSquare btn = new CoordinateSquare(i, j);
boardPane.add(btn, i, j);
}
else {
BoardStone btn = new BoardStone(i, j);
boardPane.add(btn, i, j);
board[i - 1][j - 1] = btn;
}
}
}
return boardPane;
}
private void enableKeyboardShortcuts(HBox topHBox) {
topHBox.setOnKeyPressed(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
if (event.getEventType().equals(KeyEvent.KEY_PRESSED)) {
if (event.getCode().equals(KeyCode.LEFT)) {
handlePreviousPressed();
}
else if (event.getCode().equals(KeyCode.RIGHT)) {
handleNextPressed();
}
}
}
});
}
public BoardStone[][] getBoard() {
return this.board;
}
}
|
package door.nfc.sakailab.com.nfcdooropen;
import android.app.Activity;
import android.content.Intent;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.json.JSONException;
import org.json.JSONObject;
public class NfcReadActivity extends Activity implements RequestTask.RequestCallBack<JSONObject> {
private TextView mIdLabel;
private Button mRegButton;
// private static final String REQUEST_ID_PARAM_NAME = "name";
private static final String ID_REQUEST_API = Config.SERVER_URL + "/api/v0/user";
private static final String REQUEST_ID_PARAM_IDM = "idm";
private String mIdm = "";
@Override
public void doCallBack(JSONObject result) {
Log.d(Config.DEBUG_TAG, result.toString());
// mRegButton.setVisibility(View.VISIBLE);
}
@Override
public void onFailed() {
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.nfcread_activity_layout);
mIdLabel = (TextView) findViewById(R.id.nfc_id_label);
mRegButton = (Button) findViewById(R.id.register_button);
// mRegButton.setVisibility(View.GONE);
Intent intent = getIntent();
String action = intent.getAction();
// NFCAction
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)
|| NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)
|| NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)) {
Log.d("DEBUG_TAG", "NFC DISCOVERD:" + action);
// IDm
String idm = getIdm(getIntent());
if (idm != null) {
Log.d(Config.DEBUG_TAG, idm);
mIdm = idm;
mIdLabel.setText(idm);
requestIdm();
}
}
}
private void requestIdm() {
try {
JSONObject vals = new JSONObject();
// vals.put(REQUEST_ID_PARAM_IDM, "5678cc8c9scd9cd8scd");
vals.put(REQUEST_ID_PARAM_IDM, mIdm);
RequestTask task = new RequestTask(this, ID_REQUEST_API, vals, this, RequestTask.REQUEST_MODE_GET);
task.execute();
} catch (JSONException e) {
e.printStackTrace();
}
}
protected String getIdm(Intent intent) {
String idm = null;
StringBuffer idmByte = new StringBuffer();
byte[] rawIdm = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
if (rawIdm != null) {
for (int i = 0; i < rawIdm.length; i++) {
idmByte.append(String.format("%1$02x", rawIdm[i] & 0xff));
}
idm = idmByte.toString();
}
return idm;
}
}
|
package com.xpn.xwiki.web;
import com.xpn.xwiki.XWiki;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.doc.XWikiAttachment;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.objects.BaseObject;
import java.io.IOException;
import java.util.Date;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class SkinAction extends XWikiAction
{
private static final Log log = LogFactory.getLog(SkinAction.class);
public String render(XWikiContext context) throws XWikiException
{
XWiki xwiki = context.getWiki();
XWikiRequest request = context.getRequest();
XWikiResponse response = context.getResponse();
XWikiDocument doc = context.getDoc();
String baseskin = xwiki.getBaseSkin(context, true);
XWikiDocument baseskindoc = xwiki.getDocument(baseskin, context);
String defaultbaseskin = xwiki.getDefaultBaseSkin(context);
String path = request.getPathInfo();
log.debug("document: " + doc.getFullName() + " ; baseskin: " + baseskin + " ; defaultbaseskin: " + defaultbaseskin);
int idx = path.lastIndexOf("/");
while (idx > 0) {
try {
String filename = Utils.decode(path.substring(idx + 1), context);
log.debug("Trying '" + filename + "'");
if (renderSkin(filename, doc, context))
return null;
if (renderSkin(filename, baseskin, context))
return null;
if (renderSkin(filename, baseskindoc, context))
return null;
if (renderSkin(filename, defaultbaseskin, context))
return null;
} catch (XWikiException ex) {
// TODO: ignored for the moment, this must be rethinked
log.debug(new Integer(idx), ex);
}
idx = path.lastIndexOf("/", idx - 1);
}
return "docdoesnotexist";
}
private boolean renderSkin(String filename, XWikiDocument doc, XWikiContext context)
throws XWikiException
{
log.debug("Rendering file '" + filename + "' within the '" + doc.getFullName() + "' document");
XWiki xwiki = context.getWiki();
XWikiResponse response = context.getResponse();
try {
if (doc.isNew()) {
log.debug("The skin document does not exist; trying on the filesystem");
} else {
log.debug("... as object property");
BaseObject object = doc.getObject("XWiki.XWikiSkins", 0);
String content = null;
if (object != null) {
content = object.getStringValue(filename);
}
if ((content != null) && (!content.equals(""))) {
// Choose the right content type
String mimetype = xwiki.getEngineContext().getMimeType(filename.toLowerCase());
if (mimetype.equals("text/css") || isJavascriptMimeType(mimetype)) {
content = context.getWiki().parseContent(content, context);
}
response.setContentType(mimetype);
response.setDateHeader("Last-Modified", doc.getDate().getTime());
// Sending the content of the attachment
response.setContentLength(content.length());
response.getWriter().write(content);
return true;
}
log.debug("... as attachment");
XWikiAttachment attachment = doc.getAttachment(filename);
if (attachment != null) {
// Sending the content of the attachment
byte[] data = attachment.getContent(context);
String mimetype = xwiki.getEngineContext().getMimeType(filename.toLowerCase());
if ("text/css".equals(mimetype) || isJavascriptMimeType(mimetype)) {
data = context.getWiki().parseContent(new String(data), context).getBytes();
}
response.setContentType(mimetype);
response.setDateHeader("Last-Modified", attachment.getDate().getTime());
response.setContentLength(data.length);
response.getOutputStream().write(data);
return true;
}
log.debug("... as fs document");
}
if (doc.getSpace().equals("skins")) {
String path = "skins/" + doc.getName() + "/" + filename;
if (!context.getWiki().resourceExists(path)) {
log.info("Skin file '" + path + "' does not exist");
path = "skins/" + context.getWiki().getBaseSkin(context) + "/" + filename;
}
if (!context.getWiki().resourceExists(path)) {
log.info("Skin file '" + path + "' does not exist");
path = "skins/" + context.getWiki().getDefaultBaseSkin(context) + "/" + filename;
}
if (!context.getWiki().resourceExists(path)) {
log.info("Skin file '" + path + "' does not exist");
return false;
}
log.debug("Rendering file '" + path + "'");
byte[] data = context.getWiki().getResourceContentAsBytes(path);
if ((data != null) && (data.length != 0)) {
// Choose the right content type
String mimetype =
xwiki.getEngineContext().getMimeType(filename.toLowerCase());
if ("text/css".equals(mimetype) || isJavascriptMimeType(mimetype)) {
data =
context.getWiki().parseContent(new String(data), context).getBytes();
}
response.setContentType(mimetype);
response.setDateHeader("Last-Modified", (new Date()).getTime());
// Sending the content of the attachment
response.setContentLength(data.length);
response.getOutputStream().write(data);
return true;
}
}
} catch (IOException e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_APP,
XWikiException.ERROR_XWIKI_APP_SEND_RESPONSE_EXCEPTION,
"Exception while sending response",
e);
}
return false;
}
private boolean renderSkin(String filename, String skin, XWikiContext context)
throws XWikiException
{
log.debug("Rendering file '" + filename + "' from the '" + skin + "' skin directory");
XWiki xwiki = context.getWiki();
XWikiResponse response = context.getResponse();
try {
response.setDateHeader("Expires", (new Date()).getTime() + 30 * 24 * 3600 * 1000L);
String path = "/skins/" + skin + "/" + filename;
// Choose the right content type
String mimetype = context.getEngineContext().getMimeType(filename.toLowerCase());
if (mimetype != null)
response.setContentType(mimetype);
else
response.setContentType("application/octet-stream");
// Sending the content of the file
byte[] data = context.getWiki().getResourceContentAsBytes(path);
if (data == null || data.length == 0)
return false;
if ("text/css".equals(mimetype) || isJavascriptMimeType(mimetype)) {
data = context.getWiki().parseContent(new String(data), context).getBytes();
}
response.getOutputStream().write(data);
return true;
} catch (IOException e) {
if (skin.equals(xwiki.getDefaultBaseSkin(context)))
throw new XWikiException(XWikiException.MODULE_XWIKI_APP,
XWikiException.ERROR_XWIKI_APP_SEND_RESPONSE_EXCEPTION,
"Exception while sending response",
e);
else
return false;
}
}
/**
* @param mimetype the mime type to check
* @return true if the mime type represents a javascript file
*/
private boolean isJavascriptMimeType(String mimetype)
{
return (mimetype.equals("text/javascript") || mimetype.equals("application/x-javascript")
|| mimetype.equals("application/javascript"));
}
}
|
package dataGridSrv1;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.RemoteCacheManager;
import org.infinispan.client.hotrod.configuration.ConfigurationBuilder;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@EnableAutoConfiguration
public class DataGridWritter {
// Constantes de la clase
private static final String JDG_HOST = "jdg.host";
private static final String HOTROD_PORT = "jdg.hotrod.port";
private static final String PROPERTIES_FILE = "jdg.properties";
private static final String PRENDAS_KEY = "prendas";
public static final String ID_TRAZA = "
// Variables globales
private RemoteCacheManager cacheManager;
private RemoteCache<String, Object> cache = null;
private final static DatagridListener listener = new DatagridListener();
@RequestMapping("/")
String homeMethod() {
return "<br><h1><strong>dataGridSrv1</strong></h1></br>"
+ "<br>Poner prendas en la caché: datagrid-srv1.accenture.cloud/put?parametro1=¶metro2=</h1></br>"
+ "<br>Sacar prendas de la caché: datagrid-srv1.accenture.cloud/get?parametro1=</h1></br>";
}
@RequestMapping("/put")
String putMethod(@RequestParam(value = "parametro1", defaultValue = "1") String sParametro1,
@RequestParam(value = "parametro2", defaultValue = "1") String sParametro2) {
// variables
int iParametro1,iParametro2;
HashMap<String, Prenda> prendasMap;
long lTimeBefore, lTimeAfter;
long timeGetCacheData = 0;
long timePutCacheData = 0;
long timeGetCacheListas = 0;
long contadorPuts = 0;
try {
init();
try {
iParametro1 = Integer.parseInt(sParametro1);
} catch (Exception e) {
iParametro1 = 1;
}
try {
iParametro2 = Integer.parseInt(sParametro2);
} catch (Exception e) {
iParametro2 = 1;
}
lTimeBefore = System.currentTimeMillis();
prendasMap = (HashMap<String, Prenda>) cache.get(PRENDAS_KEY);
lTimeAfter = System.currentTimeMillis();
timeGetCacheListas = lTimeAfter - lTimeBefore;
// Si el HashMap no existe, ceamos uno nuevo
if (prendasMap == null)
prendasMap = new HashMap<String, Prenda>();
// Generamos las prendas con el id secuencial del indice del for
for (int i = 0; i < iParametro1; i++) {
int idPrendaTratar = iParametro2 + i;
// Si ya existe, no la inserto
lTimeBefore = System.currentTimeMillis();
Prenda prendaEnCache = (Prenda) cache.get(String.valueOf(idPrendaTratar));
lTimeAfter = System.currentTimeMillis();
// acumulo el tiempo del get
timeGetCacheData += (lTimeAfter - lTimeBefore);
if (cache.get(String.valueOf(idPrendaTratar)) == null) {
Prenda pPrenda = calculoPrenda(String.valueOf(idPrendaTratar));
prendasMap.put(pPrenda.getPrendaName(), pPrenda);
lTimeBefore = System.currentTimeMillis();
cache.put(pPrenda.getPrendaName(), pPrenda);
lTimeAfter = System.currentTimeMillis();
// acumulo el tiempo del put y contabilizo la insercion
timePutCacheData += (lTimeAfter - lTimeBefore);
contadorPuts++;
}
}
if (contadorPuts > 0){
lTimeBefore = System.currentTimeMillis();
cache.put(PRENDAS_KEY, prendasMap);
lTimeAfter = System.currentTimeMillis();
}
// Traza
System.out.println(ID_TRAZA + "GET del HashMap en " + timeGetCacheListas + " milisegundos");
System.out.println(ID_TRAZA + "Media de GET de prenda " + (timeGetCacheData/iParametro1) + " milisegundos (" + sParametro1 + " GETs realizados en " + timeGetCacheData + " milisegundos)");
if (contadorPuts > 0){
System.out.println(ID_TRAZA + "Media de PUT de prenda " + (timePutCacheData/contadorPuts) + " milisegundos (" + contadorPuts + " PUTs realizados en " + timePutCacheData + " milisegundos)");
System.out.println(ID_TRAZA + "PUT del HashMap en " + (lTimeAfter - lTimeBefore) + " milisegundos");
}
else{
System.out.println(ID_TRAZA + "Se produjeron 0 inserciones y no se modificará el HashMap");
}
System.out.println(ID_TRAZA + "La lista de prendas tiene " + prendasMap.size());
} catch (Exception e) {
e.printStackTrace();
return "<br><h1><strong>dataGridSrv1</strong></h1></br>" + "<br>PUT Finalizado con Error.</br>"
+ "<br>error:\n " + e.getStackTrace().toString() + "\n\n...</br>";
}
String sRetorno = "<br><h1><strong>dataGridSrv1 Método PUT</strong></h1></br>";
sRetorno += "<br>GET del HashMap en " + timeGetCacheListas + " milisegundos</br>";
sRetorno += "<br>Media de GET de prenda " + (timeGetCacheData/iParametro1) + " milisegundos (" + sParametro1 + " GETs realizados en " + timeGetCacheData + " milisegundos)</br>";
if (contadorPuts > 0){
sRetorno += "<br>Media de PUT de prenda " + (timePutCacheData/contadorPuts) + " milisegundos (" + contadorPuts + " PUTs realizados en " + timePutCacheData + " milisegundos)</br>";
sRetorno += "<br>PUT del HashMap en " + (lTimeAfter - lTimeBefore) + " milisegundos</br>";
}
else{
sRetorno += "<br>Se produjeron 0 inserciones y no se modificará el HashMap</br>";
}
sRetorno += "<br>La lista de prendas tiene " + prendasMap.size()+ "</br>";
return sRetorno;
}
/**
* Metodo retorna valores de la cache
*
* @param sId
* @return
*/
@RequestMapping("/get")
String getMethod(@RequestParam(value = "parametro1", defaultValue = "1") String sId) {
// variables
HashMap<String, Prenda> prendasMap;
long lTimeBefore, lTimeAfter;
Prenda pPrenda;
long timeGetCacheData = 0;
long timePutCacheData = 0;
long timeGetCacheListas = 0;
long contadorPuts = 0;
boolean bSoloGet = false;
try {
init();
// Obtenemos el HashMap de prendas
lTimeBefore = System.currentTimeMillis();
prendasMap = (HashMap<String, Prenda>) cache.get(PRENDAS_KEY);
lTimeAfter = System.currentTimeMillis();
timeGetCacheListas = lTimeAfter - lTimeBefore;
if (cache.get(sId) != null) {
lTimeBefore = System.currentTimeMillis();
pPrenda = (Prenda) cache.get(sId);
lTimeAfter = System.currentTimeMillis();
// acumulo el tiempo del get
timeGetCacheData += (lTimeAfter - lTimeBefore);
// Traza
System.out.println(ID_TRAZA + "GET del HashMap en " + timeGetCacheListas + " milisegundos");
System.out.println(ID_TRAZA + "Media de GET de prenda " + timeGetCacheData + " milisegundos");
bSoloGet = true;
} else {
pPrenda = calculoPrenda(sId);
lTimeBefore = System.currentTimeMillis();
//cache.put(sId, pPrenda);
cache.put(sId, pPrenda, 2, TimeUnit.MINUTES, 1, TimeUnit.MINUTES);
lTimeAfter = System.currentTimeMillis();
// acumulo el tiempo del put y contabilizo la insercion
timePutCacheData += (lTimeAfter - lTimeBefore);
// Actualizamos el HashMap de prendas y lo subimos a la
prendasMap.put(sId, pPrenda);
lTimeBefore = System.currentTimeMillis();
cache.put(PRENDAS_KEY, prendasMap);
lTimeAfter = System.currentTimeMillis();
// Traza
System.out.println(ID_TRAZA + "GET del HashMap en " + timeGetCacheListas + " milisegundos");
System.out.println(ID_TRAZA + "GET de prenda " + timeGetCacheData + " milisegundos");
System.out.println(ID_TRAZA + "PUT de prenda " + timePutCacheData + " milisegundos");
System.out.println(ID_TRAZA + "PUT del HashMap en " + (lTimeAfter - lTimeBefore) + " milisegundos");
}
} catch (Exception e) {
e.printStackTrace();
return "<br><h1><strong>dataGridSrv1</strong></h1></br>" + "<br>GET Finalizado con Error.</br>"
+ "<br>error:\n " + e.getStackTrace().toString() + "\n\n...</br>";
}
String sRetorno = "<br><h1><strong>dataGridSrv1</strong></h1></br>" + "<br>Datos de la cache.</br>";
sRetorno += "<br>GET del HashMap en " + (lTimeAfter - lTimeBefore) + " milisegundos</br>";
sRetorno += "<br>GET de prenda " + (lTimeAfter - lTimeBefore) + " milisegundos</br>";
if (!bSoloGet){sRetorno += "<br>PUT de prenda " + (lTimeAfter - lTimeBefore) + " milisegundos</br>";}
if (!bSoloGet){sRetorno += "<br>PUT del HashMap en " + (lTimeAfter - lTimeBefore) + " milisegundos</br>";}
sRetorno += "<br>La lista de prendas tiene " + prendasMap.size();
return sRetorno;
}
private void init() throws Exception {
if (cache==null){
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.addServer().host(jdgProperty(JDG_HOST)).port(Integer.parseInt(jdgProperty(HOTROD_PORT)));
System.out.println(
"
cacheManager = new RemoteCacheManager(builder.build());
cache = cacheManager.getCache("prendas");
cache.addClientListener(listener);
if (!cache.containsKey(PRENDAS_KEY)) {
Map<String, Prenda> prendasMap = new HashMap<String, Prenda>();
cache.put(PRENDAS_KEY, prendasMap);
}
}
catch (Exception e) {
System.out.println("Init Caught: " + e);
e.printStackTrace();
throw e;
}
}
}
private Prenda calculoPrenda(String sNombrePrenda) {
// Creo la prenda
Prenda pNuevaPrenda = new Prenda(sNombrePrenda);
// Pongo colores por defecto
pNuevaPrenda.addColor("Negro");
pNuevaPrenda.addColor("Blanco");
pNuevaPrenda.addColor("Azul");
// Retardo de 100 Milisegundos
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
return pNuevaPrenda;
}
public static String jdgProperty(String name) {
Properties props = new Properties();
try {
props.load(DataGridWritter.class.getClassLoader().getResourceAsStream(PROPERTIES_FILE));
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
return props.getProperty(name);
}
public static void main(String[] args) throws Exception {
SpringApplication.run(DataGridWritter.class, args);
}
}
|
package de.gymnew.sudoku.model;
public class Block extends Cluster {
public Block(int x, int y, Sudoku sudoku) {
super();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
fields.add(sudoku.getField(x + i, y + j));
}
}
}
}
|
package de.konsultaner.tetris;
import java.util.Arrays;
import java.util.Random;
public class Tetris {
private int matrixWidth;
private int matrixHeight;
private Brick[] bricks;
private Brick[] field;
private Brick currentBrick;
private Brick nextBrick;
private GRAVITY gravity = GRAVITY.BOTTOM;
public enum GRAVITY {
LEFT,RIGHT,TOP,BOTTOM
}
public Tetris(int matrixWidth, int matrixHeight) {
this.matrixWidth = matrixWidth;
this.matrixHeight = matrixHeight;
}
public void setGravity(GRAVITY gravity) {
this.gravity = gravity;
}
public void addBrick(Brick brick){
Brick[] enlargedBricks = new Brick[field.length+1];
java.lang.System.arraycopy(field,0,enlargedBricks,0,enlargedBricks.length);
enlargedBricks[enlargedBricks.length-1] = brick;
bricks = enlargedBricks;
}
public void renderNextTick(){
if(!fall()){
Random random = new Random();
Brick[] enlargedField = new Brick[field.length+1];
java.lang.System.arraycopy(field,0,enlargedField,0,enlargedField.length);
enlargedField[enlargedField.length-1] = currentBrick.copy();
field = enlargedField;
currentBrick = nextBrick;
nextBrick = bricks[random.nextInt(bricks.length)];
}
}
/**
* Clears rows that are full and to be cleared, gravity is taken in consideration
* @return An array of rows that have been cleared out, rows are marked with 1
*/
int[][] clearFullRows(){
int[][] field = getCurrentFieldMatrix();
int[] clearRows = new int[field.length];
int[] clearColumns = new int[field.length>0?field[0].length:0];
int[][] resultMatrix = new int[clearRows.length][clearColumns.length];
Arrays.fill(clearRows, 1);
Arrays.fill(clearColumns, 1);
for (int rowIndex = 0; rowIndex < field.length; rowIndex++) {
for (int columnIndex = 0; columnIndex < field[rowIndex].length; columnIndex++) {
if(gravity == GRAVITY.BOTTOM || gravity == GRAVITY.TOP) {
clearRows[rowIndex] |= field[rowIndex][columnIndex];
clearColumns[columnIndex] = 0;
}else{
clearRows[rowIndex] = 0;
clearColumns[columnIndex] |= field[rowIndex][columnIndex];
}
}
}
// clear out brick
for (Brick brick: bricks ) {
brick.clearRows(clearRows);
brick.clearColumns(clearColumns);
}
// generate result matrix
for (int rowIndex = 0; rowIndex < resultMatrix.length; rowIndex++) {
for (int columnIndex = 0; columnIndex < resultMatrix[rowIndex].length; columnIndex++) {
resultMatrix[rowIndex][columnIndex] = clearRows[rowIndex] | clearColumns[columnIndex];
}
}
return resultMatrix;
}
public int[][] getCurrentFieldMatrix(){
int[][] resultMatrix = new int[matrixHeight][matrixWidth];
for (int i = 0; i < field.length; i++) {
for (int brickRowIndex = 0; brickRowIndex < field[i].matrix.length; brickRowIndex++) {
for (int brickColumnIndex = 0; brickColumnIndex < field[i].matrix[brickRowIndex].length; brickColumnIndex++) {
if(field[i].matrix[brickRowIndex][brickColumnIndex] == 1){
resultMatrix[field[i].y+brickRowIndex][field[i].x+brickColumnIndex] = i;
}
}
}
}
return resultMatrix;
}
private boolean fall(){
return moveBrick(currentBrick,gravity);
}
public boolean moveLeft(){
switch (gravity){
case TOP: return moveBrick(currentBrick,GRAVITY.RIGHT);
case RIGHT: return moveBrick(currentBrick,GRAVITY.BOTTOM);
case BOTTOM: return moveBrick(currentBrick,GRAVITY.LEFT);
case LEFT: return moveBrick(currentBrick,GRAVITY.TOP);
}
return false;
}
public boolean moveRight(){
switch (gravity){
case TOP: return moveBrick(currentBrick,GRAVITY.LEFT);
case RIGHT: return moveBrick(currentBrick,GRAVITY.TOP);
case BOTTOM: return moveBrick(currentBrick,GRAVITY.RIGHT);
case LEFT: return moveBrick(currentBrick,GRAVITY.BOTTOM);
}
return false;
}
boolean moveBrick(Brick brick, GRAVITY direction){
int[][] fieldMatrix = getCurrentFieldMatrix();
for (int rowIndex = 0; rowIndex < fieldMatrix.length; rowIndex++) {
for (int columnIndex = 0; columnIndex < fieldMatrix[rowIndex].length; columnIndex++) {
int nextCurrentBrickX = brick.x + (direction == GRAVITY.RIGHT?1:0) - (direction == GRAVITY.LEFT?1:0);
int nextCurrentBrickY = brick.y + (direction == GRAVITY.BOTTOM?1:0) - (direction == GRAVITY.TOP?1:0);
for (int brickRowIndex = 0; brickRowIndex < brick.matrix.length; brickRowIndex++) {
for (int brickColumnIndex = 0; brickColumnIndex < brick.matrix[brickRowIndex].length; brickColumnIndex++) {
if(brick.matrix[brickRowIndex][brickColumnIndex] == 1){
if(
rowIndex+nextCurrentBrickY+brickRowIndex >= fieldMatrix.length ||
columnIndex+nextCurrentBrickX+brickColumnIndex >= fieldMatrix[rowIndex+nextCurrentBrickY+brickRowIndex].length ||
fieldMatrix[rowIndex+nextCurrentBrickY+brickRowIndex][columnIndex+nextCurrentBrickX+brickColumnIndex] >= 0
) {
return false;
}
}
}
}
}
}
return true;
}
public class Brick implements Cloneable{
int x,y;
int red,green,blue,white;
private int[][] matrix;
public Brick(int[][] matrix) {
this.matrix = matrix;
}
protected Brick copy(){
try{
return this.clone();
} catch (CloneNotSupportedException ignore) { }
return null;
}
@Override
protected Brick clone() throws CloneNotSupportedException {
Brick clone;
try {
clone = (Brick) super.clone();
}
catch (CloneNotSupportedException ex) {
throw new CloneNotSupportedException();
}
return clone;
}
void rotateCW(){
}
void rotateCCW(){
}
public void clearRows(int[] clearRows) {
int[][] newMatrix = new int[0][0];
int clearedRows = 0;
for (int i = 0; i < clearRows.length; i++) {
if(clearRows[i] == 0){
int rowIndex = i - y;
if(rowIndex > 0 && rowIndex < matrix.length){
if(newMatrix.length > 0){
newMatrix = Arrays.copyOf(newMatrix,newMatrix.length+1);
}else{
newMatrix = new int[1][matrix[rowIndex].length];
}
newMatrix[newMatrix.length-1] = Arrays.copyOf(matrix[rowIndex],matrix[rowIndex].length);
}
}else clearedRows++;
}
matrix = newMatrix;
if(gravity == GRAVITY.BOTTOM){
y+=clearedRows;
}
if(gravity == GRAVITY.TOP){
y-=clearedRows;
}
}
public void clearColumns(int[] clearColumns) {
}
}
}
|
// JSBuiltInFunctions.java
package ed.js.engine;
import java.io.*;
import java.util.*;
import java.lang.reflect.*;
import com.twmacinta.util.*;
import ed.log.*;
import ed.js.*;
import ed.js.e4x.*;
import ed.js.func.*;
import ed.io.*;
import ed.net.*;
import ed.util.*;
import ed.security.*;
/**
* @anonymous name : {SYSOUT}, desc : {Dumps a string to standard output.}, param : {type : (string), name : (s), desc : (the string to print)}
* @anonymous name : {assert}, desc : {Verifies a given condition and terminates the flow of execution if false.} param : {type : (boolean), name : (cond), desc : (condition to test)}
* @anonymous name : {download}, desc : {Downloads the file at a given URL.}, return : {type : (file), desc : (downloaded file)}, param : {type : (string), name : (url), desc : (url of the file to download)}
* @anonymous name : {fork}, desc : {Creates a new thread to run a given function. Once created, the thread can be run and it's return data fetched, as shown in the example.}, example : { x = fork(function() { return 3; });
x.run();
x.returnData(); // will print 3 } param : {type : (function), name : (f), desc : (function to execute in a separate thread)}, return : {type : (thread), desc : (the thread generated)}
* @anonymous name : {isAlpha} desc : {Determines if the input is a single alphabetic character.} return : {type : (boolean), desc : (if the given string is a single alphabetic character)}, param : { type : (string), name : (ch), desc : (character to check)}
* @anonymous name : {isArray} desc : {Checks that a given object is an array.} param : {type : (any), name : (arr), desc : (object to check)}, return : {type : (boolean), desc : (if the object is an array)}
* @anonymous name : {isBool} desc : {Checks that a given object is a boolean value.} param : {type : (any), name : (arr), desc : (object to check)}, return : {type : (boolean), desc : (if the object is a boolean value)}
* @anonymous name : {isDate} desc : {Checks that a given object is a date object.} param : {type : (any), name : (arr), desc : (object to check)}, return : {type : (boolean), desc : (if the object is a date object)}
* @anonymous name : {isDigit} desc : {Checks that a given object is a string representing a single digit.} param : {type : (any), name : (arr), desc : (object to check)}, return : {type : (boolean), desc : (if the object is a string representing a single digit)}
* @anonymous name : {isFunction} desc : {Checks that a given object is a function.} param : {type : (any), name : (arr), desc : (object to check)}, return : {type : (boolean), desc : (if the object is a function)}
* @anonymous name : {isNumber} desc : {Checks that a given object is a number.} param : {type : (any), name : (arr), desc : (object to check)}, return : {type : (boolean), desc : (if the object is a number)}
* @anonymous name : {isObject} desc : {Checks that a given object is an object.} param : {type : (any), name : (arr), desc : (object to check)}, return : {type : (boolean), desc : (if the object is an object)}
* @anonymous name : {isRegExp} desc : {Checks that a given object is a regular expression.} param : {type : (any), name : (arr), desc : (object to check)}, return : {type : (boolean), desc : (if the object is a regular expression)}
* @anonymous name : {isRegex} desc : {Checks that a given object is a regular expression.} param : {type : (any), name : (arr), desc : (object to check)}, return : {type : (boolean), desc : (if the object is a regular expression)}
* @anonymous name : {isSpace} desc : {Checks that a given object is a single whitespace character.} param : {type : (any), name : (arr), desc : (object to check)}, return : {type : (boolean), desc : (if the object is a single whitespace character)}
* @anonymous name : {isString} desc : {Checks that a given object is a string.} param : {type : (any), name : (arr), desc : (object to check)}, return : {type : (boolean), desc : (if the object is a string)}
* @anonymous name : {javaStatic} desc : {Calls a static java function.}, param : {type : (string), name : (cls), desc : (Java class to call)}, param : {type : (string), name : (method), desc : (method to call within the class)}, param : {type : (any), name : (params), desc : (some number of arguments to be passed to the java function)}
* @anonymous name : {javaStaticProp}, desc : {Returns the value of a given static Java property.}, param : {type : (string), name : (cls), desc : (Java class)}, param : {type : (string), name : (property), desc : (method to call within the class)}, return : {type : (any), desc : (the value of the requested property)}
* @anonymous name : {md5} desc : {Returns an md5 encoding of the given object.} param : {type : (any), name : (thing), desc : (object to be encoded)}, return : {type : (string), desc : (md5 hash of the given object)}
* @anonymous name : {parseBool} desc : {Converts an object into a boolean value. Objects that, when converted to a string, start with "t", "T", or "1" are true. Everything else is false. } param : {type : (any), name : (obj), desc : (object to be converted into a boolean)}, return : { type : (boolean) desc : (the boolean equivalent of the given object)}
* @anonymous name : {parseDate} desc : {Converts a date or string into a date object.} param : {type : (string|Date), name : (d), desc : (object to be converted into a date)}, return : { type : (Date) desc : (the date equivalent of the given object)}
* @anonymous name : {parseNumber} desc : {Converts an object into a numeric value. } param : {type : (any), name : (obj), desc : (object to be converted into a number)}, return : { type : (number) desc : (the numeric equivalent of the given object)}
* @anonymous name : {printnoln} desc : {Prints a string with no terminating newline.} param : {type : (string) name : (str), desc : (string to print)}
* @anonymous name : {processArgs} desc : {Assigns the values passed to a function in the variable <tt>arguments</tt> to a list of given variable names.} param : {type : (any) name : (param), desc : (a series of variable names to which to assign arguments)}
* @anonymous name : {sleep} desc : {Pauses the thread's execution for a given number of milliseconds.} param : {type : (number) name : (ms), desc : (the number of milliseconds for which to pause)}
* @anonymous name : {sysexec} desc : {Executes a system command.} param : {type : (string) name : (cmd), desc : (command to execute)}, param : {type : (string), name : (in) desc : (input to command) isOptional : (true)}, param : {isOptional : (true) type : (Object), name : (env), desc : (environmental variables to use)} param : {type : (string) name : (loc) desc : (path from which to execute the command) isOptional : (true)} return : { type : (Object) desc : (the output of the command)}
* @expose
*/
public class JSBuiltInFunctions {
static {
JS._debugSIStart( "JSBuiltInFunctions" );
}
/** Returns a new scope in which the builtin functions are defined.
* @return the new scope
*/
public static Scope create(){
return create( "Built-In" );
}
/** Returns a new scope with a given name in which the builtin functions are defined.
* @return the new scope
*/
public static Scope create( String name ){
return create( name , null );
}
/** Returns a new scope with a given name in which the builtin functions are defined.
* @return the new scope
*/
public static Scope create( String name , File root ){
Scope s = new Scope( name , null , root );
try {
s.putAll( _base );
_setup( s );
}
catch ( RuntimeException re ){
re.printStackTrace();
System.exit(-1);
}
s.setGlobal( true );
s.lock();
return s;
}
public static class jsassert extends JSFunctionCalls1 {
public jsassert(){
JSFunction myThrows = new JSFunctionCalls2(){
public Object call( Scope scope , Object exctype, Object f,
Object extra[] ){
if( ! ( f instanceof JSFunction ) ){
if ( exctype instanceof JSFunction && f == null ){
f = exctype;
exctype = null;
}
else
throw new RuntimeException( "Second argument to assert.throws must be a function" );
}
try {
((JSFunction)f).call( scope , null );
}
catch(JSException e){
if ( exctype == null )
return true;
if( exctype instanceof JSString || exctype instanceof String ){
if( e.getObject().equals( exctype.toString() ) )
return Boolean.TRUE;
}
Object desc = e.getObject();
if( desc instanceof Throwable && match( (Throwable) desc , exctype ) )
return Boolean.TRUE;
Throwable cause = e.getCause();
if( match( cause , exctype ) )
return Boolean.TRUE;
throw new JSException( "given function threw something else: " + cause.toString() );
}
catch(Throwable e){
if ( exctype == null )
return true;
if( match( e , exctype.toString() ) ) {
return Boolean.TRUE;
}
// FIXME: what if exctype is a JSFunction (i.e.
// an exception type?
// Find out how to do instanceof in JS API
throw new JSException( "given function threw something else: " + e.toString() );
}
// Didn't throw anything
throw new JSException( "given function did not throw " + exctype );
}
};
set("throws", myThrows);
set("raises", myThrows);
set( "eq" , new JSFunctionCalls3(){
public Object call( Scope scope , Object a , Object b , Object extraMsg , Object extra[] ){
if ( JSInternalFunctions.JS_eq( a , b ) )
return true;
String msg = "not the same [" + a + "] != [" + b + "]";
//msg += " (" + _getClass( a ) + ") (" + _getClass(b) + ")";
if ( extraMsg != null )
msg += " " + extraMsg;
throw new JSException( msg );
}
} );
set( "lt" , new JSFunctionCalls3(){
public Object call( Scope scope , Object a , Object b , Object extraMsg , Object extra[] ){
if ( JSInternalFunctions.JS_lt( a , b ) )
return true;
String msg = "[" + a + "] is not less than [" + b + "]";
if ( extraMsg != null )
msg += " " + extraMsg;
throw new JSException( msg );
}
} );
set( "gt" , new JSFunctionCalls3(){
public Object call( Scope scope , Object a , Object b , Object extraMsg , Object extra[] ){
if ( JSInternalFunctions.JS_gt( a , b ) )
return true;
String msg = "[" + a + "] is not greater than [" + b + "]";
if ( extraMsg != null )
msg += " " + extraMsg;
throw new JSException( msg );
}
} );
set( "neq" , new JSFunctionCalls3(){
public Object call( Scope scope , Object a , Object b , Object extraMsg , Object extra[] ){
if ( ! JSInternalFunctions.JS_eq( a , b ) )
return true;
String msg = "are the same [" + a + "] != [" + b + "]";
if ( extraMsg != null )
msg += " " + extraMsg;
throw new JSException( msg );
}
} );
}
static String _getClass( Object o ){
if ( o == null )
return null;
return o.getClass().getName();
}
public Object call( Scope scope , Object foo , Object extra[] ){
if ( JSInternalFunctions.JS_evalToBool( foo ) )
return Boolean.TRUE;
if ( extra != null && extra.length > 0 && extra[0] != null )
throw new JSException( "assert failed : " + extra[0] );
throw new JSException( "assert failed" );
}
public boolean match( Throwable e , Object exctype ){
if( exctype instanceof JSString || exctype instanceof String ){
String s = exctype.toString();
String gotExc = e.getClass().toString();
if( gotExc.equals( "class " + s ) ) return true;
if( gotExc.equals( "class java.lang." + s ) )
return true;
if( e instanceof JSException && ((JSException)e).getObject().equals( s ) )
return true;
// FIXME: check subclasses?
}
return false;
}
}
/** @unexpose */
public static Class _getClass( String name )
throws Exception {
final int colon = name.indexOf( ":" );
if ( colon < 0 )
return Class.forName( name );
String base = name.substring( 0 , colon );
Class c = Class.forName( base );
String inner = "$" + name.substring( colon + 1 );
for ( Class child : c.getClasses() ){
if ( child.getName().endsWith( inner ) )
return child;
}
throw new JSException( "can't find inner class [" + inner + "] on [" + c.getName() + "]" );
}
public static class javaCreate extends JSFunctionCalls1 {
public Object call( Scope scope , Object clazzNameJS , Object extra[] ){
String clazzName = clazzNameJS.toString();
if ( ! Security.isCoreJS() )
throw new JSException( "you can't do create a :" + clazzName + " from [" + Security.getTopJS() + "]" );
Class clazz = null;
try {
clazz = _getClass( clazzName );
}
catch ( Exception e ){
throw new JSException( "can't find class for [" + clazzName + "]" );
}
Constructor[] allCons = clazz.getConstructors();
Arrays.sort( allCons , NativeBridge._consLengthComparator );
for ( int i=0; i<allCons.length; i++ ){
Object params[] = NativeBridge.doParamsMatch( allCons[i].getParameterTypes() , extra , scope );
if ( params != null ){
try {
return allCons[i].newInstance( params );
}
catch ( RuntimeException re ){
ed.lang.StackTraceHolder.getInstance().fix( re );
throw re;
}
catch ( Exception e ){
throw new JSException( "can' instantiate" , e );
}
}
}
throw new RuntimeException( "can't find valid constructor" );
}
}
public static class javaStatic extends JSFunctionCalls2 {
public Object call( Scope scope , Object clazzNameJS , Object methodNameJS , Object extra[] ){
final boolean debug = false;
String clazzName = clazzNameJS.toString();
if ( ! Security.isCoreJS() )
throw new JSException( "you can't use a :" + clazzName + " from [" + Security.getTopJS() + "]" );
Class clazz = null;
try {
clazz = _getClass( clazzName );
}
catch ( Exception e ){
throw new JSException( "can't find class for [" + clazzName + "]" );
}
Method[] all = clazz.getMethods();
Arrays.sort( all , NativeBridge._methodLengthComparator );
for ( int i=0; i<all.length; i++ ){
Method m = all[i];
if ( debug ) System.out.println( m.getName() );
if ( ( m.getModifiers() & Modifier.STATIC ) == 0 ){
if ( debug ) System.out.println( "\t not static" );
continue;
}
if ( ! m.getName().equals( methodNameJS.toString() ) ){
if ( debug ) System.out.println( "\t wrong name" );
continue;
}
Object params[] = NativeBridge.doParamsMatch( m.getParameterTypes() , extra , scope , debug );
if ( params == null ){
if ( debug ) System.out.println( "\t params don't match" );
continue;
}
try {
return m.invoke( null , params );
}
catch ( Exception e ){
e.printStackTrace();
throw new JSException( "can't call" , e );
}
}
throw new RuntimeException( "can't find valid method" );
}
}
public static class javaStaticProp extends JSFunctionCalls2 {
public Object call( Scope scope , Object clazzNameJS , Object fieldNameJS , Object extra[] ){
String clazzName = clazzNameJS.toString();
if ( ! Security.isCoreJS() )
throw new JSException( "you can't use a :" + clazzName + " from [" + Security.getTopJS() + "]" );
Class clazz = null;
try {
clazz = _getClass( clazzName );
}
catch ( JSException e ){
throw e;
}
catch ( Exception e ){
throw new JSException( "can't find class for [" + clazzName + "]" );
}
try {
return clazz.getField( fieldNameJS.toString() ).get( null );
}
catch ( NoSuchFieldException n ){
throw new JSException( "can't find field [" + fieldNameJS + "] from [" + clazz.getName() + "]" );
}
catch ( Exception e ){
throw new JSException( "can't get field [" + fieldNameJS + "] from [" + clazz.getName() + "] b/c " + e );
}
}
}
public static class print extends JSFunctionCalls1 {
print(){
this( true );
}
print( boolean newLine ){
super();
_newLine = newLine;
}
public Object call( Scope scope , Object foo , Object extra[] ){
if ( _newLine )
System.out.println( foo );
else
System.out.print( foo );
return null;
}
final boolean _newLine;
}
public static class NewObject extends JSFunctionCalls0{
public Object call( Scope scope , Object extra[] ){
if( extra != null && extra.length > 0
&& extra[0] instanceof JSObject ) {
scope.setThis( extra[0] );
return extra[0];
}
return new JSObjectBase();
}
public Object get( Object o ){
if ( o == null )
return null;
if ( o.toString().equals( "prototype" ) )
return JSObjectBase._objectLowFunctions;
return super.get( o );
}
protected void init(){
/**
* Copies all properties from the source to the destination object.
* Not in JavaScript spec! Please refer to Prototype docs!
*/
set( "extend", new Prototype.Object_extend() );
set( "values", new Prototype.Object_values() );
set( "keys", new Prototype.Object_keys() );
}
};
public static class NewDate extends JSFunctionCalls1 {
public Object call( Scope scope , Object t , Object extra[] ){
if ( t == null )
return new JSDate();
if ( ! ( t instanceof Number ) )
return new JSDate();
return new JSDate( ((Number)t).longValue() );
}
}
public static class CrID extends JSFunctionCalls1 {
public CrID(){
set( "isValid" , new JSFunctionCalls1(){
public Object call( Scope scope , Object idString , Object extra[] ){
if ( idString == null )
return false;
if ( idString instanceof ed.db.ObjectId )
return true;
return ed.db.ObjectId.isValid( idString.toString() );
}
}
);
}
public Object call( Scope scope , Object idString , Object extra[] ){
if ( idString == null )
return ed.db.ObjectId.get();
if ( idString instanceof ed.db.ObjectId )
return idString;
return new ed.db.ObjectId( idString.toString() );
}
public JSObject newOne(){
throw new JSException( "ObjectId is not a constructor" );
}
}
public static class sleep extends JSFunctionCalls1 {
public Object call( Scope scope , Object timeObj , Object extra[] ){
if ( ! ( timeObj instanceof Number ) )
return false;
try {
Thread.sleep( ((Number)timeObj).longValue() );
}
catch ( Exception e ){
return false;
}
return true;
}
}
public static class isXXX extends JSFunctionCalls1 {
isXXX( Class c ){
_c = c;
}
public Object call( Scope scope , Object o , Object extra[] ){
return _c.isInstance( o );
}
final Class _c;
}
public static class isNaN extends JSFunctionCalls1 {
public Object call( Scope scope , Object o , Object extra[] ){
return o.equals(Double.NaN);
}
}
public static class isXXXs extends JSFunctionCalls1 {
isXXXs( Class ... c ){
_c = c;
}
public Object call( Scope scope , Object o , Object extra[] ){
for ( int i=0; i<_c.length; i++ )
if ( _c[i].isInstance( o ) )
return true;
return false;
}
final Class _c[];
}
public static class fork extends JSFunctionCalls1 {
public Object call( final Scope scope , final Object funcJS , final Object extra[] ){
if ( ! ( funcJS instanceof JSFunction ) )
throw new JSException( "fork has to take a function" );
final JSFunction func = (JSFunction)funcJS;
final Thread t = new Thread( "fork" ){
public void run(){
try {
_result = func.call( scope , extra );
}
catch ( Throwable t ){
if ( scope.get( "log" ) != null )
((Logger)scope.get( "log" ) ).error( "error in fork" , t );
else
t.printStackTrace();
}
}
public Object returnData()
throws InterruptedException {
join();
return _result;
}
private Object _result;
};
return t;
}
}
public static class processArgs extends JSFunctionCalls0 {
public Object call( Scope scope , Object [] args){
JSArray a = (JSArray)scope.get("arguments");
for(int i = 0; i < args.length; i++){
scope.put(args[i].toString(), a.getInt(i), true);
}
return null;
}
}
/** Returns if a given scope is the main scope.
* @param the scope to check
* @return if the given scope is the main scope
*/
public static final boolean isBase( Scope s ){
return s == _base;
}
private static final Scope _base; // these are things that aren't modifiable, so its safe if there is only 1 copy
//private static final Scope _myScope; // this is the security hole. need to get rid off TODO
static {
Scope s = new Scope( "base" , null );
try {
_setupBase( s );
}
catch ( RuntimeException re ){
re.printStackTrace();
System.exit( -1 );
}
finally {
_base = s;
_base.lock();
_base.setGlobal( true );
}
}
public static class eval extends JSFunctionCalls1 {
public Object call( Scope scope , Object thing , Object [] args){
Scope s = scope;
Object t = scope.getThis();
if ( t instanceof Scope )
s = (Scope)t;
return s.eval( thing.toString() );
}
}
public static class CreatePackage extends JSFunctionCalls1 {
public Object call( Scope scope , Object funcObject , Object [] args){
if ( ! ( funcObject instanceof JSFunction ) )
throw new RuntimeException( "createPackage needs to take a function" );
Scope global = scope.child();
global.setGlobal( true );
Scope toPass = global.child();
JSFunction func = (JSFunction)funcObject;
func.setUsePassedInScopeTL( true );
func.call( toPass , args );
func.setUsePassedInScopeTL( false );
JSObject thePackage = new JSObjectBase();
for ( String s : global.keySet() )
thePackage.set( s , global.get( s ) );
return thePackage;
}
}
/**
* everything that gets put into the scope that is a JSObjetBase gets locked
*/
private static void _setupBase( Scope s ){
s.put( "sysexec" , new ed.io.SysExec() , true );
s.put( "print" , new print() , true );
s.put( "printnoln" , new print( false ) , true );
s.put( "SYSOUT" , new print() , true );
s.put( "sleep" , new sleep() , true );
s.put( "fork" , new fork() , true );
s.put( "eval" , new eval() , true );
CrID crid = new CrID();
s.put( "CrID" , crid , true );
s.put( "ObjID" , crid , true );
s.put( "ObjId" , crid , true );
s.put( "ObjectID" , crid , true );
s.put( "ObjectId" , crid , true );
s.put( "parseBool" , new JSFunctionCalls1(){
public Object call( Scope scope , Object b , Object extra[] ){
if ( b == null )
return false;
String s = b.toString();
if ( s.length() == 0 )
return false;
char c = s.charAt( 0 );
return c == 't' || c == 'T' || c == '1';
}
} , true );
s.put( "parseFloat" ,
new JSFunctionCalls1(){
public Object call( Scope scope , Object a , Object extra[] ){
if ( a == null )
return Double.NaN;
try {
return Double.parseDouble( a.toString() );
}
catch ( Exception e ){}
return Double.NaN;
}
}
, true );
s.put( "parseInt" ,
new JSFunctionCalls2(){
public Object call( Scope scope , Object a , Object b , Object extra[] ){
if ( a == null )
return Double.NaN;
if ( a instanceof Number )
return ((Number)a).intValue();
String s = a.toString();
try {
if ( b != null && b instanceof Number ){
return StringParseUtil.parseIntRadix( s , ((Number)b).intValue() );
}
return StringParseUtil.parseIntRadix( s , 10 );
}
catch ( Exception e ){}
return Double.NaN;
}
}
, true );
s.put( "parseDate" ,
new JSFunctionCalls1(){
public Object call( Scope scope , Object a , Object extra[] ){
if ( a == null )
return null;
if ( a instanceof JSDate )
return a;
if ( ! ( a instanceof String || a instanceof JSString ) )
return null;
long t = JSDate.parseDate( a.toString() , 0 );
if ( t == 0 )
return null;
return new JSDate( t );
}
} , true );
s.put( "NaN" , Double.NaN , true );
s.put( "Infinity" , Double.POSITIVE_INFINITY , true );
s.put( "md5" , new JSFunctionCalls1(){
public Object call( Scope scope , Object b , Object extra[] ){
synchronized ( _myMd5 ){
_myMd5.Init();
_myMd5.Update( b.toString() );
return new JSString( _myMd5.asHex() );
}
}
private final MD5 _myMd5 = new MD5();
} , true );
s.put( "isArray" , new isXXX( JSArray.class ) , true );
s.put( "isBool" , new isXXX( Boolean.class ) , true );
s.put( "isNumber" , new isXXX( Number.class ) , true );
s.put( "isDate" , new isXXX( JSDate.class ) , true );
s.put( "isFunction" , new isXXX( JSFunction.class ) , true );
s.put( "isRegExp" , new isXXX( JSRegex.class ) , true );
s.put( "isRegex" , new isXXX( JSRegex.class ) , true );
s.put( "isNaN", new isNaN(), true);
s.put( "isString" , new isXXXs( String.class , JSString.class ) , true );
s.put( "isObject" , new JSFunctionCalls1(){
public Object call( Scope scope , Object o , Object extra[] ){
if ( o == null )
return false;
if ( ! ( o instanceof JSObject ) )
return false;
if ( o instanceof JSString )
return false;
return true;
}
} , true );
s.put( "isAlpha" , new JSFunctionCalls1(){
public Object call( Scope scope , Object o , Object extra[] ){
char c = getChar( o );
return Character.isLetter( c );
}
} , true );
s.put( "isSpace" , new JSFunctionCalls1(){
public Object call( Scope scope , Object o , Object extra[] ){
char c = getChar( o );
return Character.isWhitespace( c );
}
} , true );
s.put( "isDigit" , new JSFunctionCalls1(){
public Object call( Scope scope , Object o , Object extra[] ){
char c = getChar( o );
return Character.isDigit( c );
}
} , true );
s.put( "isXMLName" , new JSFunctionCalls1() {
public Object call( Scope scope , Object o , Object extra[] ){
return ed.js.e4x.E4X.isXMLName( o );
}
} , true );
s.put( "__self" , new JSFunctionCalls1(){
public Object call( Scope scope , Object o , Object extra[] ){
return o;
}
} , true );
s.put( "javaCreate" , new javaCreate() , true );
s.put( "javaStatic" , new javaStatic() , true );
s.put( "javaStaticProp" , new javaStaticProp() , true );
s.put( "JSCaptcha" , new JSCaptcha() , true );
s.put( "MimeTypes" , new ed.appserver.MimeTypes() , true );
s.put( "Base64" , new ed.util.Base64() , true );
s.put( "download" , new HttpDownload.downloadFunc() , true );
s.put( "XMLHttpRequest" , XMLHttpRequest._cons , true );
s.put( "processArgs", new processArgs(), true );
// mail stuff till i'm done
s.put( "JAVAXMAILTO" , javax.mail.Message.RecipientType.TO , true );
s.put( "createPackage" , new CreatePackage() );
JSON.init( s );
Encoding.install( s );
for ( String key : s.keySet() ){
Object val = s.get( key );
if ( val instanceof JSObjectBase )
((JSObjectBase)val).lock();
}
ed.db.migrate.Drivers.init( s );
}
private static void _setup( Scope s ){
// core js
s.put( "Object" , new NewObject() , true );
s.put( "Array" , new JSArray.JSArrayCons() , true );
s.put( "Boolean" , new JSBoolean.Cons() , true );
s.put( "Date" , new JSDate.Cons() , true );
s.put( "JSDate" , s.get( "Date" ) , true ); // b/c Eliot always types this
s.put( "String" , new JSString.JSStringCons() , true );
s.put( "XML" , new ENode.Cons() , true );
s.put( "XMLList" , new XMLList.ListCons() , true );
s.put( "Namespace" , new Namespace.Cons() , true );
s.put( "QName" , new QName.Cons() , true );
s.put( "RegExp" , new JSRegex.Cons() , true );
s.put( "Regexp" , s.get( "RegExp" ) , true ); // for Ruby technically
s.put( "Function" , new JSInternalFunctions.FunctionCons() , true );
s.put( "Math" , new JSMath() , true );
s.put( "Class", Prototype.newCopy() , true );
s.put( "Number" , new JSNumber.Cons() , true );
s.put( "parseNumber" , s.get( "Number" ) , true );
// extensions
s.put( "Exception" , new JSException.cons() , true );
s.put( "Map" , new JSMap.Cons() , true );
s.put( "assert" , new jsassert() , true );
s.lock();
}
private static char getChar( Object o ){
if ( o instanceof Character )
return (Character)o;
if ( o instanceof JSString )
o = o.toString();
if ( o instanceof String ){
String s = (String)o;
if ( s.length() == 1 )
return s.charAt( 0 );
}
return 0;
}
static {
JS._debugSIDone( "JSBuiltInFunctions" );
}
}
|
package ezvcard.io.xml;
import static ezvcard.io.xml.XCardQNames.GROUP;
import static ezvcard.io.xml.XCardQNames.PARAMETERS;
import static ezvcard.io.xml.XCardQNames.VCARD;
import static ezvcard.io.xml.XCardQNames.VCARDS;
import static ezvcard.util.IOUtils.utf8Writer;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.xml.namespace.QName;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.TransformerException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
import ezvcard.VCard;
import ezvcard.VCardDataType;
import ezvcard.VCardVersion;
import ezvcard.io.CannotParseException;
import ezvcard.io.EmbeddedVCardException;
import ezvcard.io.SkipMeException;
import ezvcard.io.StreamReader;
import ezvcard.io.StreamWriter;
import ezvcard.io.scribe.VCardPropertyScribe;
import ezvcard.io.scribe.VCardPropertyScribe.Result;
import ezvcard.parameter.VCardParameters;
import ezvcard.property.VCardProperty;
import ezvcard.property.Xml;
import ezvcard.util.IOUtils;
import ezvcard.util.ListMultimap;
import ezvcard.util.XmlUtils;
//@formatter:off
//@formatter:on
public class XCardDocument {
private final VCardVersion version4 = VCardVersion.V4_0; //xCard only supports 4.0
private final Document document;
private Element root;
/**
* Creates an xCard document.
*/
public XCardDocument() {
this(createXCardsRoot());
}
private static Document createXCardsRoot() {
Document document = XmlUtils.createDocument();
Element root = document.createElementNS(VCARDS.getNamespaceURI(), VCARDS.getLocalPart());
document.appendChild(root);
return document;
}
/**
* Parses an xCard document from a string.
* @param xml the XML string to read the vCards from
* @throws SAXException if there's a problem parsing the XML
*/
public XCardDocument(String xml) throws SAXException {
this(XmlUtils.toDocument(xml));
}
/**
* Parses an xCard document from an input stream.
* @param in the input stream to read the vCards from
* @throws IOException if there's a problem reading from the input stream
* @throws SAXException if there's a problem parsing the XML
*/
public XCardDocument(InputStream in) throws SAXException, IOException {
this(XmlUtils.toDocument(in));
}
/**
* Parses an xCard document from a file.
* @param file the file to read the vCards from
* @throws IOException if there's a problem reading from the file
* @throws SAXException if there's a problem parsing the XML
*/
public XCardDocument(File file) throws SAXException, IOException {
this(readFile(file));
}
private static Document readFile(File file) throws SAXException, IOException {
InputStream in = new FileInputStream(file);
try {
return XmlUtils.toDocument(in);
} finally {
IOUtils.closeQuietly(in);
}
}
/**
* <p>
* Parses an xCard document from a reader.
* </p>
* <p>
* Note that use of this constructor is discouraged. It ignores the
* character encoding that is defined within the XML document itself, and
* should only be used if the encoding is undefined or if the encoding needs
* to be ignored for whatever reason. The
* {@link #XCardDocument(InputStream)} constructor should be used instead,
* since it takes the XML document's character encoding into account when
* parsing.
* </p>
* @param reader the reader to read the vCards from
* @throws IOException if there's a problem reading from the reader
* @throws SAXException if there's a problem parsing the XML
*/
public XCardDocument(Reader reader) throws SAXException, IOException {
this(XmlUtils.toDocument(reader));
}
/**
* Wraps an existing XML DOM object.
* @param document the XML DOM that contains the xCard document
*/
public XCardDocument(Document document) {
this.document = document;
XCardNamespaceContext nsContext = new XCardNamespaceContext(version4, "v");
XPath xpath = XPathFactory.newInstance().newXPath();
xpath.setNamespaceContext(nsContext);
try {
//find the <vcards> element
root = (Element) xpath.evaluate("//" + nsContext.getPrefix() + ":" + VCARDS.getLocalPart(), document, XPathConstants.NODE);
} catch (XPathExpressionException e) {
//never thrown because xpath expression is hard coded
throw new RuntimeException(e);
}
}
/**
* Creates a {@link StreamReader} object that reads vCards from this XML
* document.
* @return the writer
*/
public StreamReader reader() {
return new XCardDocumentStreamReader();
}
/**
* Creates a {@link StreamWriter} object that adds vCards to this XML
* document.
* @return the writer
*/
public XCardDocumentStreamWriter writer() {
return new XCardDocumentStreamWriter();
}
/**
* Gets the XML document that was generated.
* @return the XML document
*/
public Document getDocument() {
return document;
}
/**
* Parses all of the vCards from this XML document. Modifications made to
* these {@link VCard} objects will NOT be applied to the XML document.
* @return the parsed vCards
*/
public List<VCard> getVCards() {
List<VCard> vcards = new ArrayList<VCard>();
try {
StreamReader reader = reader();
VCard vcard = null;
while ((vcard = reader.readNext()) != null) {
vcards.add(vcard);
}
} catch (IOException e) {
//won't be thrown
}
return vcards;
}
public void add(VCard vcard) {
writer().write(vcard);
}
/**
* Writes the XML document to a string without pretty-printing it.
* @return the XML string
*/
public String write() {
return write(-1);
}
/**
* Writes the XML document to a string and pretty-prints it.
* @param indent the number of indent spaces to use for pretty-printing
* @return the XML string
*/
public String write(int indent) {
StringWriter sw = new StringWriter();
try {
write(sw, indent);
} catch (TransformerException e) {
//writing to string
}
return sw.toString();
}
/**
* Writes the XML document to an output stream without pretty-printing it.
* @param out the output stream
* @throws TransformerException if there's a problem writing to the output
* stream
*/
public void write(OutputStream out) throws TransformerException {
write(out, -1);
}
/**
* Writes the XML document to an output stream and pretty-prints it.
* @param out the output stream
* @param indent the number of indent spaces to use for pretty-printing
* @throws TransformerException if there's a problem writing to the output
* stream
*/
public void write(OutputStream out, int indent) throws TransformerException {
write(utf8Writer(out), indent);
}
/**
* Writes the XML document to a file without pretty-printing it.
* @param file the file
* @throws TransformerException if there's a problem writing to the file
* @throws IOException if there's a problem writing to the file
*/
public void write(File file) throws TransformerException, IOException {
write(file, -1);
}
/**
* Writes the XML document to a file and pretty-prints it.
* @param file the file stream
* @param indent the number of indent spaces to use for pretty-printing
* @throws TransformerException if there's a problem writing to the file
* @throws IOException if there's a problem writing to the file
*/
public void write(File file, int indent) throws TransformerException, IOException {
Writer writer = utf8Writer(file);
try {
write(writer, indent);
} finally {
IOUtils.closeQuietly(writer);
}
}
/**
* Writes the XML document to a writer without pretty-printing it.
* @param writer the writer
* @throws TransformerException if there's a problem writing to the writer
*/
public void write(Writer writer) throws TransformerException {
write(writer, -1);
}
/**
* Writes the XML document to a writer and pretty-prints it.
* @param writer the writer
* @param indent the number of indent spaces to use for pretty-printing
* @throws TransformerException if there's a problem writing to the writer
*/
public void write(Writer writer, int indent) throws TransformerException {
Map<String, String> properties = new HashMap<String, String>();
if (indent >= 0) {
properties.put(OutputKeys.INDENT, "yes");
properties.put("{http://xml.apache.org/xslt}indent-amount", indent + "");
}
XmlUtils.toWriter(document, writer, properties);
}
private class XCardDocumentStreamReader extends StreamReader {
private final Iterator<Element> vcardElements;
{
List<Element> list = (root == null) ? Collections.<Element> emptyList() : getChildElements(root, VCARD);
vcardElements = list.iterator();
}
private VCard vcard;
@Override
public VCard readNext() {
try {
return super.readNext();
} catch (IOException e) {
//will not be thrown
throw new RuntimeException(e);
}
}
@Override
protected VCard _readNext() throws IOException {
if (!vcardElements.hasNext()) {
return null;
}
vcard = new VCard();
vcard.setVersion(version4);
parseVCardElement(vcardElements.next());
return vcard;
}
public void close() throws IOException {
//empty
}
private void parseVCardElement(Element vcardElement) {
List<Element> children = XmlUtils.toElementList(vcardElement.getChildNodes());
for (Element child : children) {
if (GROUP.getNamespaceURI().equals(child.getNamespaceURI()) && GROUP.getLocalPart().equals(child.getLocalName())) {
String group = child.getAttribute("name");
if (group.length() == 0) {
group = null;
}
List<Element> grandChildren = XmlUtils.toElementList(child.getChildNodes());
for (Element grandChild : grandChildren) {
parseAndAddElement(grandChild, group);
}
continue;
}
parseAndAddElement(child, null);
}
}
/**
* Parses a property element from the XML document and adds the property
* to the vCard.
* @param element the element to parse
* @param group the group name or null if the property does not belong
* to a group
* @param vcard the vCard object
* @param warningsBuf the list to add the warnings to
*/
private void parseAndAddElement(Element element, String group) {
VCardParameters parameters = parseParameters(element);
VCardProperty property;
String propertyName = element.getLocalName();
String ns = element.getNamespaceURI();
QName qname = new QName(ns, propertyName);
VCardPropertyScribe<? extends VCardProperty> scribe = index.getPropertyScribe(qname);
try {
Result<? extends VCardProperty> result = scribe.parseXml(element, parameters);
property = result.getProperty();
property.setGroup(group);
for (String warning : result.getWarnings()) {
warnings.add(null, propertyName, warning);
}
} catch (SkipMeException e) {
warnings.add(null, propertyName, 22, e.getMessage());
return;
} catch (CannotParseException e) {
String xml = XmlUtils.toString(element);
warnings.add(null, propertyName, 33, xml, e.getMessage());
scribe = index.getPropertyScribe(Xml.class);
Result<? extends VCardProperty> result = scribe.parseXml(element, parameters);
property = result.getProperty();
property.setGroup(group);
} catch (EmbeddedVCardException e) {
warnings.add(null, propertyName, 34);
return;
}
vcard.addProperty(property);
}
/**
* Parses the property parameters (aka "sub types").
* @param element the property's XML element
* @return the parsed parameters
*/
private VCardParameters parseParameters(Element element) {
VCardParameters parameters = new VCardParameters();
List<Element> roots = XmlUtils.toElementList(element.getElementsByTagNameNS(PARAMETERS.getNamespaceURI(), PARAMETERS.getLocalPart()));
for (Element root : roots) { // foreach "<parameters>" element (there should only be 1 though)
List<Element> parameterElements = XmlUtils.toElementList(root.getChildNodes());
for (Element parameterElement : parameterElements) {
String name = parameterElement.getLocalName().toUpperCase();
List<Element> valueElements = XmlUtils.toElementList(parameterElement.getChildNodes());
if (valueElements.isEmpty()) {
String value = parameterElement.getTextContent();
parameters.put(name, value);
continue;
}
for (Element valueElement : valueElements) {
String value = valueElement.getTextContent();
parameters.put(name, value);
}
}
}
return parameters;
}
private List<Element> getChildElements(Element parent, QName qname) {
List<Element> elements = new ArrayList<Element>();
for (Element child : XmlUtils.toElementList(parent.getChildNodes())) {
if (qname.getLocalPart().equals(child.getLocalName()) && qname.getNamespaceURI().equals(child.getNamespaceURI())) {
elements.add(child);
}
}
return elements;
}
}
public class XCardDocumentStreamWriter extends StreamWriter {
/**
* Defines the names of the XML elements that are used to hold each
* parameter's value.
*/
private final Map<String, VCardDataType> parameterDataTypes = new HashMap<String, VCardDataType>();
{
registerParameterDataType(VCardParameters.ALTID, VCardDataType.TEXT);
registerParameterDataType(VCardParameters.CALSCALE, VCardDataType.TEXT);
registerParameterDataType(VCardParameters.GEO, VCardDataType.URI);
registerParameterDataType(VCardParameters.LABEL, VCardDataType.TEXT);
registerParameterDataType(VCardParameters.LANGUAGE, VCardDataType.LANGUAGE_TAG);
registerParameterDataType(VCardParameters.MEDIATYPE, VCardDataType.TEXT);
registerParameterDataType(VCardParameters.PID, VCardDataType.TEXT);
registerParameterDataType(VCardParameters.PREF, VCardDataType.INTEGER);
registerParameterDataType(VCardParameters.SORT_AS, VCardDataType.TEXT);
registerParameterDataType(VCardParameters.TYPE, VCardDataType.TEXT);
registerParameterDataType(VCardParameters.TZ, VCardDataType.URI);
}
@Override
public void write(VCard vcard) {
try {
super.write(vcard);
} catch (IOException e) {
//won't be thrown because writing to DOM
}
}
@Override
protected void _write(VCard vcard, List<VCardProperty> properties) throws IOException {
ListMultimap<String, VCardProperty> propertiesByGroup = new ListMultimap<String, VCardProperty>(); //group the types by group name (null = no group name)
for (VCardProperty property : properties) {
propertiesByGroup.put(property.getGroup(), property);
}
//marshal each type object
Element vcardElement = createElement(VCARD);
for (Map.Entry<String, List<VCardProperty>> entry : propertiesByGroup) {
String groupName = entry.getKey();
Element parent;
if (groupName != null) {
Element groupElement = createElement(GROUP);
groupElement.setAttribute("name", groupName);
vcardElement.appendChild(groupElement);
parent = groupElement;
} else {
parent = vcardElement;
}
for (VCardProperty property : entry.getValue()) {
try {
Element propertyElement = marshalProperty(property, vcard);
parent.appendChild(propertyElement);
} catch (SkipMeException e) {
//skip property
} catch (EmbeddedVCardException e) {
//skip property
}
}
}
if (root == null) {
root = createElement(VCARDS);
Element documentRoot = XmlUtils.getRootElement(document);
if (documentRoot == null) {
document.appendChild(root);
} else {
documentRoot.appendChild(root);
}
}
root.appendChild(vcardElement);
}
@Override
protected VCardVersion getTargetVersion() {
return VCardVersion.V4_0;
}
/**
* Registers the data type of an experimental parameter. Experimental
* parameters use the "unknown" data type by default.
* @param parameterName the parameter name (e.g. "x-foo")
* @param dataType the data type or null to remove
*/
public void registerParameterDataType(String parameterName, VCardDataType dataType) {
parameterName = parameterName.toLowerCase();
if (dataType == null) {
parameterDataTypes.remove(parameterName);
} else {
parameterDataTypes.put(parameterName, dataType);
}
}
public void close() throws IOException {
//empty
}
/**
* Marshals a type object to an XML element.
* @param type the type object to marshal
* @param vcard the vcard the type belongs to
* @return the XML element
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
private Element marshalProperty(VCardProperty type, VCard vcard) {
VCardPropertyScribe scribe = index.getPropertyScribe(type);
VCardParameters parameters = scribe.prepareParameters(type, version4, vcard);
QName qname = scribe.getQName();
Element propertyElement = createElement(qname);
//marshal the parameters
if (!parameters.isEmpty()) {
Element parametersElement = marshalParameters(parameters);
propertyElement.appendChild(parametersElement);
}
//marshal the value
scribe.writeXml(type, propertyElement);
return propertyElement;
}
private Element marshalParameters(VCardParameters parameters) {
Element parametersElement = createElement(PARAMETERS);
for (Map.Entry<String, List<String>> parameter : parameters) {
String parameterName = parameter.getKey().toLowerCase();
Element parameterElement = createElement(parameterName);
for (String parameterValue : parameter.getValue()) {
VCardDataType dataType = parameterDataTypes.get(parameterName);
String dataTypeElementName = (dataType == null) ? "unknown" : dataType.getName().toLowerCase();
Element dataTypeElement = createElement(dataTypeElementName);
dataTypeElement.setTextContent(parameterValue);
parameterElement.appendChild(dataTypeElement);
}
parametersElement.appendChild(parameterElement);
}
return parametersElement;
}
/**
* Creates a new XML element.
* @param name the name of the XML element
* @return the new XML element
*/
private Element createElement(String name) {
return createElement(name, version4.getXmlNamespace());
}
/**
* Creates a new XML element.
* @param name the name of the XML element
* @param ns the namespace of the XML element
* @return the new XML element
*/
private Element createElement(String name, String ns) {
return document.createElementNS(ns, name);
}
/**
* Creates a new XML element.
* @param qname the element name
* @return the new XML element
*/
private Element createElement(QName qname) {
return createElement(qname.getLocalPart(), qname.getNamespaceURI());
}
}
}
|
package gin.misc;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.pmw.tinylog.Logger;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.DataKey;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.PackageDeclaration;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
import com.github.javaparser.ast.body.EnumDeclaration;
import com.github.javaparser.ast.body.MethodDeclaration;
import com.github.javaparser.ast.expr.ObjectCreationExpr;
/**
* This class provides utility methods to annotate JavaParser method AST nodes
* with their fully qualified names. Call annotateCompilationUnit() to do the
* grunt work.
*/
public class FullyQualifiedNames {
/**the key used to track fully qualified names for methods in JavaParser nodes*/
public static final DataKey<String> NODEKEY_FQ_METHOD_NAME = new DataKey<String>() { };
/**the key used to track numbers of anon inner classes in JavaParser nodes*/
public static final DataKey<Integer> NODEKEY_ANON_INNER_CLASS_NUM = new DataKey<Integer>() { };
// general approach was suggested here:
// to find the class containing the field or the method
// to find if a class is contained in another class
// to find the package definition of the file hosting the class
public static void annotateCompilationUnit(CompilationUnit cu) {
// add a reference number to each anon inner class
preProcessAnonInnerClasses(cu);
// now, for every node in the CU, annotate with fully qualified name
List<MethodDeclaration> nodes = cu.getChildNodesByType(MethodDeclaration.class);
for(MethodDeclaration m : nodes) {
m.setData(NODEKEY_FQ_METHOD_NAME, getFQName(m));
}
}
/** see note in getFQName() about this regex */
final static Pattern methodSignaturePattern = Pattern.compile("[^\\s>]+\\(.*?\\)");
/**
* @param m - MethodDeclaration
* @return the fully qualified name and signature for the specified method;
* e.g. containing.package.TopLevelClass$InnerClass.myMethod(Foo,Bar)
*/
public static String getFQName(MethodDeclaration m) {
Node current = m;
Node parent = m.getParentNode().orElse(null);
// Get signature...
String signature = m.getDeclarationAsString(false, false, false); // we don't use getSignature() as that doesn't include generics; this does.
// Strip out return type if provided
// Note (Issue #52): return type might include spaces as part of a generic type.
// We want the method name, which is the string not containing whitespace or > symbols
// finishing before a (
// so, method name matches the regex "[^\s>]+\("
// of course we also want to keep the signature, which is everything else up to the )
// so the regex is actually "[^\s>]+\(.*?\)"
Matcher matcher = methodSignaturePattern.matcher(signature);
if (!matcher.find()) {
Logger.error("Couldn't parse this method name: " + m.getDeclarationAsString());
System.exit(-1);
}
signature = matcher.group();
// Remove all spaces
signature = signature.replaceAll("\\s", "");
String name = "." + signature;
while ((parent = current.getParentNode().orElse(null)) != null) {
if ((current instanceof ClassOrInterfaceDeclaration) && (parent instanceof CompilationUnit)) { // top level class
PackageDeclaration p = ((CompilationUnit)parent).getPackageDeclaration().orElse(null);
if (p != null) {
name = p.getNameAsString() + "." + ((ClassOrInterfaceDeclaration)current).getNameAsString() + name;
} else {
name = ((ClassOrInterfaceDeclaration)current).getNameAsString() + name;
}
} else if ((current instanceof EnumDeclaration) && (parent instanceof CompilationUnit)) { // top level enum
PackageDeclaration p = ((CompilationUnit)parent).getPackageDeclaration().orElse(null);
if (p != null) {
name = p.getNameAsString() + "." + ((EnumDeclaration)current).getNameAsString() + name;
} else {
name = ((EnumDeclaration)current).getNameAsString() + name;
}
} else if (current instanceof ClassOrInterfaceDeclaration) { // non-top-level class with a name
String curName = ((ClassOrInterfaceDeclaration)current).getNameAsString();
name = "$" + curName + name;
} else if ((current instanceof ObjectCreationExpr) && ((ObjectCreationExpr)current).getAnonymousClassBody().isPresent()) { // what we've seen so far is contained in an object creation expression, so an anonymous inner class
int num = ((ObjectCreationExpr)current).getData(NODEKEY_ANON_INNER_CLASS_NUM);
name = "$" + num + name;
}
// ignore any methods other than the bottom-level one!
current = parent;
}
return name;
}
public static void preProcessAnonInnerClasses(CompilationUnit root) {
preProcessAnonInnerClasses(root, 0, 1);
}
private static int preProcessAnonInnerClasses(Node currentNode, int level, int nextNumberAtThisLevel) {
// look at all child nodes of this level:
// (depth first search)
for (Node childNode : currentNode.getChildNodes()) {
// is the child an anon inner class?
// (ObjectCreationExpr with an anon class body)
// if so, annotate with a number
if ((childNode instanceof ObjectCreationExpr) && (((ObjectCreationExpr)childNode).getAnonymousClassBody().isPresent())) {
childNode.setData(NODEKEY_ANON_INNER_CLASS_NUM, nextNumberAtThisLevel);
nextNumberAtThisLevel++;
}
// recursive call to look at the child nodes of this child
if ((childNode instanceof ClassOrInterfaceDeclaration) || // named inner class
((childNode instanceof ObjectCreationExpr) && (((ObjectCreationExpr)childNode).getAnonymousClassBody().isPresent()))) { // anon inner class
// if we're exploring child nodes of an inner class - any type -
// then increment level and reset counter to 1
preProcessAnonInnerClasses(childNode, level + 1, 1);
} else {
// otherwise continue with counter as it is at current level
nextNumberAtThisLevel = preProcessAnonInnerClasses(childNode, level, nextNumberAtThisLevel);
}
}
return nextNumberAtThisLevel;
}
/**
* This will take the supplied method name, and:
* if it appears to be fully qualified, return it unchanged
* if it appears to be missing the package or top-level class name, it will add those, retrieved from the supplied CompilationUnit
*
* This will not make any assumptions about inner classes:
* the supplied method name must be relative to the top-level class
* @param methodName - String
* @param cu - CompilationUnit
* @return methodName
*/
public static String makeMethodNameFullyQualified(String methodName, CompilationUnit cu) {
String className = getClassName(cu);
PackageDeclaration p = ((CompilationUnit)cu).getPackageDeclaration().orElse(null);
String packageName = p != null ? p.getNameAsString() + "." : "";
if (!methodName.startsWith(packageName) || packageName.isEmpty()) {
if (!methodName.startsWith(className)) {
methodName = className + methodName;
}
methodName = packageName + methodName;
}
return methodName;
}
private static String getClassName(CompilationUnit cu) {
List<ClassOrInterfaceDeclaration> l = cu.getChildNodesByType(ClassOrInterfaceDeclaration.class);
if (!l.isEmpty()) {
// find public class!
for (ClassOrInterfaceDeclaration cd : l) {
if (cd.isPublic()) {
return cd.getNameAsString() + ".";
}
}
} else { // no top level class; maybe an enum instead?
List<EnumDeclaration> l2 = cu.getChildNodesByType(EnumDeclaration.class);
if (!l2.isEmpty()) {
for (EnumDeclaration ed : l2) {
if (ed.isPublic()) {
return ed.getNameAsString() + ".";
}
}
}
}
// otherwise... no class name? shouldn't get here
return "";
}
}
|
package HxCKDMS.gkpk.data;
import HxCKDMS.HxCCore.api.Utils.LogHelper;
import HxCKDMS.gkpk.block.BlockExtractor;
import HxCKDMS.gkpk.block.BlockFermenter;
import HxCKDMS.gkpk.block.tile.TileEntityExtractor;
import HxCKDMS.gkpk.block.tile.TileEntityFermenter;
import HxCKDMS.gkpk.data.recipe.GKPKRecipe;
import HxCKDMS.gkpk.event.GEventHandler;
import HxCKDMS.gkpk.items.ItemEthanol;
import HxCKDMS.gkpk.items.ItemExtract;
import HxCKDMS.gkpk.items.ItemPharmacyBook;
import cpw.mods.fml.common.registry.GameRegistry;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemBlock;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraftforge.common.MinecraftForge;
import java.util.HashMap;
public class Registry {
public HashMap<String, Drug> drugs = new HashMap<>();
public BlockExtractor blockextractor = new BlockExtractor();
public ItemEthanol itemEthanol = new ItemEthanol();
public ItemExtract itemExtract = new ItemExtract();
public BlockFermenter fermenter = new BlockFermenter();
public ItemPharmacyBook pbook = new ItemPharmacyBook();
public void preInit() {
// Default compound set
drugs.put("nodu", new Drug("Nodularin", 0xF4F4F4, "", 0, 0, new PotionEffect(Potion.hunger.getId(), TimeConst.TICKS_PER_MINUTE, 4), new PotionEffect(Potion.digSlowdown.getId(), TimeConst.TICKS_PER_MINUTE * 2, 2))); // From zombie flesh
drugs.put("ttx", new Drug("Tetrodotoxin", 0xFEFEFE, "desaturate", TimeConst.TICKS_PER_MINUTE, 4, new PotionEffect(Potion.moveSlowdown.getId(), TimeConst.TICKS_PER_MINUTE *2, 50), new PotionEffect(Potion.wither.getId(), TimeConst.TICKS_PER_MINUTE, 3))); // From pufferfish
drugs.put("ethanol", new Drug("Ethanol", 0x000000, "blur", TimeConst.TICKS_PER_MINUTE * 2, 4, new PotionEffect(Potion.hunger.getId(), TimeConst.TICKS_PER_MINUTE, 2), new PotionEffect(Potion.moveSlowdown.getId(), TimeConst.TICKS_PER_MINUTE * 2, 2))); // internal
drugs.put("musc", new Drug("Muscimol", 0x30FF30, "sobel", TimeConst.TICKS_PER_MINUTE * 2, 2, new PotionEffect(Potion.damageBoost.getId(), TimeConst.TICKS_PER_MINUTE, 1), new PotionEffect(Potion.moveSlowdown.getId(), TimeConst.TICKS_PER_MINUTE * 2, 2))); // From red mushroom
MinecraftForge.EVENT_BUS.register(new GEventHandler());
}
public void init() {
GameRegistry.registerItem(itemEthanol, "gEthanol"); // Ethanol
GameRegistry.registerItem(itemExtract, "gExtractItem"); // NBTBased Extract Item
GameRegistry.registerBlock(blockextractor, "gExtractor"); // Extractor
GameRegistry.registerBlock(fermenter, "gFermenter"); // Fermenter
GameRegistry.registerTileEntity(TileEntityFermenter.class, "GKPK_Fermenter"); // TE for fermenter
GameRegistry.registerTileEntity(TileEntityExtractor.class, "GKPK_Extractor"); // TE for Extactor
}
public void postInit() {
//Extractor Recipes
GKPKRecipe.Extracting().registerExtractRecipe(Items.rotten_flesh, "nodu");
// GKPKRecipe.Extracting().registerExtractRecipe(ItemBlock.getItemFromBlock(Blocks.red_mushroom), "musc");
GKPKRecipe.Extracting().registerExtractRecipe(Items.fish, 3, "ttx");
LogHelper.info("There has been " + drugs.size() + " drugs initialized!", "GKPK");
LogHelper.info("There has been " + GKPKRecipe.Extracting().getExtractList().size() + " Extractor recipes initialized!", "GKPK");
}
}
|
package ameba.feature;
import ameba.container.Container;
import ameba.core.Application;
import ameba.event.Event;
import ameba.event.EventBus;
import ameba.event.Listener;
import ameba.event.SystemEventBus;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.glassfish.hk2.api.ServiceLocator;
import javax.inject.Inject;
import javax.ws.rs.core.Feature;
import java.util.List;
import java.util.Map;
/**
* @author icode
*/
public abstract class AmebaFeature implements Feature {
private static EventBus EVENT_BUS = EventBus.createMix();
private static Map<Class<? extends Event>, List<Listener>> listeners;
@Inject
private ServiceLocator locator;
@Inject
private Application application;
public static void publishEvent(Event event) {
EVENT_BUS.publish(event);
}
private void initDev() {
if (listeners == null) {
listeners = Maps.newConcurrentMap();
SystemEventBus.subscribe(Container.BeginReloadEvent.class,
new Listener<Container.BeginReloadEvent>() {
@Override
public void onReceive(Container.BeginReloadEvent event) {
if (listeners != null) {
for (Class ev : listeners.keySet()) {
for (Listener listener : listeners.get(ev)) {
EVENT_BUS.unsubscribe(ev, listener);
}
}
listeners.clear();
}
}
});
}
}
private <E extends Event> void subscribe(Class<E> eventClass, final Listener<E> listener) {
if (application.getMode().isDev()) {
initDev();
List<Listener> list = listeners.get(eventClass);
if (list == null) {
list = Lists.newArrayList();
listeners.put(eventClass, list);
}
list.add(listener);
}
EVENT_BUS.subscribe(eventClass, listener);
}
protected <E extends Event> void subscribeEvent(Class<E> eventClass, final Listener<E> listener) {
locator.inject(listener);
locator.postConstruct(listener);
subscribe(eventClass, listener);
}
protected <E extends Event> Listener subscribeEvent(Class<E> eventClass, final Class<? extends Listener<E>> listenerClass) {
Listener<E> listener = locator.createAndInitialize(listenerClass);
subscribe(eventClass, listener);
return listener;
}
protected <E extends Event> void unsubscribeEvent(Class<E> eventClass, final Listener<E> listener) {
locator.preDestroy(listener);
if (application.getMode().isDev()) {
List<Listener> list = listeners.get(eventClass);
if (list != null) list.remove(listener);
}
EVENT_BUS.unsubscribe(eventClass, listener);
}
protected <E extends Event> void subscribeSystemEvent(Class<E> eventClass, final Listener<E> listener) {
locator.inject(listener);
locator.postConstruct(listener);
SystemEventBus.subscribe(eventClass, listener);
}
protected <E extends Event> void unsubscribeSystemEvent(Class<E> eventClass, final Listener<E> listener) {
locator.preDestroy(listener);
SystemEventBus.unsubscribe(eventClass, listener);
}
protected <E extends Event> Listener subscribeSystemEvent(Class<E> eventClass, final Class<? extends Listener<E>> listenerClass) {
Listener<E> listener = locator.createAndInitialize(listenerClass);
SystemEventBus.subscribe(eventClass, listener);
return listener;
}
}
|
package bj.pranie.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
registry.addViewController("/login").setViewName("index");
registry.addViewController("/user/regulations").setViewName("user/regulations");
}
}
|
package binarytree;
import datastructures.tree.BinarySearchTree;
import datastructures.tree.TreeNode;
public class CheckBSTHasDeadEnd {
private BinarySearchTree<Integer> tree = null;
private TreeNode<Integer> root = null;
public CheckBSTHasDeadEnd() {
tree = new BinarySearchTree<Integer>();
}
public void constructTree(String[] input) {
for (String line : input) {
String[] values = line.split(" ");
String action = values[0];
switch (action) {
case "insertRoot":
tree = new BinarySearchTree<Integer>();
root = tree.insertRoot(Integer.parseInt(values[1]));
break;
case "insert":
tree.insert(root, Integer.parseInt(values[1]));
break;
}
}
}
public boolean hasDeadEnd() {
return hasDeadEnd(root, new Range(0, Integer.MAX_VALUE));
}
private boolean hasDeadEnd(TreeNode<Integer> root, Range range) {
if (root == null) {
return false;
} else if (root.left == null && root.right == null) {
return Math.abs(root.data - range.min) <= 1 && Math.abs(range.max - root.data) <= 1;
} else {
return hasDeadEnd(root.left, new Range(range.min, root.data))
|| hasDeadEnd(root.right, new Range(root.data, range.max));
}
}
private class Range {
private int min;
private int max;
Range(int min, int max) {
this.min = min;
this.max = max;
}
}
}
|
package isoladinosauri;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import isoladinosauri.modellodati.Carnivoro;
import isoladinosauri.modellodati.Carogna;
import isoladinosauri.modellodati.Dinosauro;
import isoladinosauri.modellodati.Erbivoro;
import isoladinosauri.modellodati.Vegetale;
public class ClientHandler extends Thread {
private Socket socket;
private static final int MAX = 40;
private static final String ERRORE = "Errore lettura file";
private Partita partita;
private Utente utente;
public ClientHandler(Socket socket, Partita partita) {
this.socket = socket;
this.partita = partita;
}
public boolean cercaNelFile(String nomeFileFisico, String parametro1, String parametro2, String carSplit, int posSplit) {
boolean trovato = false;
try {
FileReader fileReader = new FileReader(nomeFileFisico);
BufferedReader br;
br = new BufferedReader(fileReader);
String rigaFile = br.readLine();
while(rigaFile!=null) {
if(parametro2!=null) {
if(rigaFile.split(carSplit)[posSplit].equals(parametro1) && rigaFile.split(carSplit)[posSplit+1].equals(parametro2)) {
trovato=true;
break;
}
}
else {
if(rigaFile.split(carSplit)[posSplit].equals(parametro1)) {
trovato=true;
break;
}
}
rigaFile = br.readLine();
}
br.close();
}
catch(IOException ioException)
{
System.err.println(ERRORE);
}
return trovato;
}
public void scriviNelFile(String nomeFileFisico, String riga) {
try {
FileWriter fileWriter = new FileWriter (nomeFileFisico,true); //true=append
fileWriter.write(riga);
fileWriter.close();
}
catch(IOException ioException)
{
System.err.println(ERRORE);
}
}
public String creaUtente(String request) {
String answer;
String nickname = request.split(",")[1].split("=")[1];
String password = request.split(",")[2].split("=")[1];
//cerco nel file Utenti.txt se l'utente e' gia' esistente
boolean trovato = cercaNelFile("Utenti.txt",nickname,null," ",0);
if(trovato) {
answer="@no,@usernameOccupato";
}
else {
answer="@ok";
scriviNelFile("Utenti.txt",nickname+" "+password+"\n");
System.out.println("Dati: " + nickname + "," + password);
this.utente = new Utente(nickname,password);
System.out.println("Dati: " + this.utente.getNomeUtente() + "," + this.utente.getPassword());
}
return answer;
}
public String login(String request) {
String token;
String answer = new String();
String nickname = request.split(",")[1].split("=")[1];
String password = request.split(",")[2].split("=")[1];
//verifico se c'e' nel file Utenti.txt
boolean trovato = cercaNelFile("Utenti.txt",nickname,password," ",0);
if(trovato) {
//cerco se il token e' gia' loggato
boolean trovatoToken = cercaNelFile("Token.txt",nickname,null," ",0);
if(!trovatoToken) {
//aggiorno il file Token.txt
token = nickname+"-"+password;
scriviNelFile("Token.txt",nickname+" "+token+"\n");
answer = "@ok,"+token;
}
else {
answer = "@no,@UTENTE_GIA_LOGGATO";
}
}
else if(!trovato) {
answer = "@no,@autenticazioneFallita";
}
return answer;
}
public String creaRazza(String request) {
String answer = new String();
String token = request.split(",")[1].split("=")[1];
String nomeRazza = request.split(",")[2].split("=")[1];
String tipoRazza = request.split(",")[3].split("=")[1];
//verifico se c'e' il token nel file Token.txt
boolean trovato = cercaNelFile("Token.txt",token,null," ",1);
if(trovato) {
int turnoCorrente = 1; //solo per test
Giocatore giocatore = new Giocatore(this.partita, turnoCorrente, nomeRazza, tipoRazza);
giocatore.setUtente(this.utente);
System.out.println("Utente: " + this.utente.getNomeUtente());
this.partita.aggiungiGiocatore(giocatore);
answer = "@ok";
}
else if(!trovato) {
answer = "@no,@tokenNonValido";
}
return answer;
}
public String accessoPartita(String request) {
String nomeUtente = new String();
String answer = new String();
int nGiocatori = 0;
String token = request.split(",")[1].split("=")[1];
try { // cerco se il token e' valido
FileReader fileToken = new FileReader("Token.txt");
BufferedReader br = new BufferedReader(fileToken);
String rigaFile = br.readLine();
boolean trovato=false;
while(rigaFile!=null) {
if(rigaFile.split(" ")[1].equals(token)) {
trovato=true;
nomeUtente=rigaFile.split(" ")[0];
break;
}
rigaFile = br.readLine();
}
br.close();
// verifico se il giocatore ha gia' effettuato l'accesso
boolean trovatoTokenInPartita = cercaNelFile("TokenInPartita.txt",token,null," ",1);
if(!trovatoTokenInPartita) {
//conto il numero di giocatori (token) nel file tokenInPartita
FileReader fileTokenInPartitaRD = new FileReader("TokenInPartita.txt");
br = new BufferedReader(fileTokenInPartitaRD);
rigaFile = br.readLine();
while(rigaFile!=null) {
nGiocatori++;
rigaFile = br.readLine();
}
br.close();
if(trovato && nGiocatori<8) {
//aggiorno il file TokenInPartita.txt
scriviNelFile("TokenInPartita.txt",nomeUtente+" "+token+"\n");
answer = "@ok";
}
else if(!trovato) {
answer = "@no,@tokenNonValido";
}
else if(nGiocatori>=8) {
answer = "@no,@troppiGiocatori";
}
}
else {
answer = "@no,@ACCESSO_GIA_EFFETTUATO";
}
}
catch(IOException ioException)
{
System.err.println(ERRORE);
}
return answer;
}
public String uscitaPartita(String request) {
String answer = new String();
String token = request.split(",")[1].split("=")[1];
// cerco se il token e' in partita
boolean trovato = cercaNelFile("TokenInPartita.txt",token,null," ",1);
try {
if(trovato) {
//aggiorno il file TokenInPartita.txt cancellando il token
//copio i token escluso quello che devo eliminare in un file tmp
FileReader fileTokenInPartita = new FileReader("TokenInPartita.txt");
FileWriter fileTmpToken = new FileWriter ("TmpToken.txt",true); //true=append
BufferedReader br = new BufferedReader(fileTokenInPartita);
String rigaFile = br.readLine();
while(rigaFile!=null) {
if(rigaFile.split(" ")[1].equals(token)!=true) {
fileTmpToken.write(rigaFile+"\n");
}
rigaFile = br.readLine();
}
br.close();
fileTmpToken.close();
//elimino il vecchio TokenInPartita.txt e poi rinomino il TmpToken.txt in TokenInPartita.txt
File daEliminare = new File("TokenInPartita.txt");
if(daEliminare.exists()) {
daEliminare.delete();
}
File fileNomeVecchio = new File("TmpToken.txt");
File fileNomeNuovo = new File("TokenInPartita.txt");
fileNomeVecchio.renameTo(fileNomeNuovo);
answer = "@ok";
}
else if(!trovato) {
answer = "@no,@tokenNonValido";
}
}
catch(IOException ioException)
{
System.err.println(ERRORE);
}
return answer;
}
public String listaGiocatori(String request) {
String answer = new String();
String token = request.split(",")[1].split("=")[1];
//verifico se c'e' nel file Token.txt
boolean trovato = false;
trovato = cercaNelFile("Token.txt",token,null," ",1);
try {
if(trovato) {
//accedo al file tokenInPartita.txt per fornire la lista dei giocatori in partita
String listaGiocatori = new String ();
FileReader fileTokenInPartita = new FileReader("TokenInPartita.txt");
BufferedReader br = new BufferedReader(fileTokenInPartita);
String rigaFile = br.readLine();
while(rigaFile!=null) {
listaGiocatori = listaGiocatori.concat(",").concat(rigaFile.split(" ")[0]); //FIXME nn so se va
rigaFile = br.readLine();
}
br.close();
answer = "@listaGiocatori"+listaGiocatori;
}
else if(!trovato) {
answer = "@no,@tokenNonValido";
}
}
catch(IOException ioException)
{
System.err.println(ERRORE);
}
return answer;
}
public String logout(String request) {
String answer = new String();
String token = request.split(",")[1].split("=")[1];
//verifico se c'e' nel file Token.txt
boolean trovato = cercaNelFile("Token.txt",token,null," ",1);
try {
if(trovato) {
//aggiorno il file Token.txt cancellando il token che vuole fare il logout
//copio i token escluso quello che devo eliminare in un file tmp
FileReader fileToken = new FileReader("Token.txt");
FileWriter fileTmpTokenLogout = new FileWriter ("TmpTokenLogout.txt",true); //true=append
BufferedReader br = new BufferedReader(fileToken);
String rigaFile = br.readLine();
while(rigaFile!=null) {
if(rigaFile.split(" ")[1].equals(token)!=true) {
fileTmpTokenLogout.write(rigaFile+"\n");
}
rigaFile = br.readLine();
}
br.close();
fileTmpTokenLogout.close();
//elimino il vecchio Token.txt e poi rinomino il TmpTokenLogout.txt in Token.txt
File daEliminare = new File("Token.txt");
if(daEliminare.exists()) {
daEliminare.delete();
}
File fileNomeVecchio = new File("TmpTokenLogout.txt");
File fileNomeNuovo = new File("Token.txt");
fileNomeVecchio.renameTo(fileNomeNuovo);
answer = "@ok";
}
else if(!trovato) {
answer = "@no,@tokenNonValido";
}
}
catch(IOException ioException)
{
System.err.println(ERRORE);
}
return answer;
}
private Giocatore individuaGiocatore (String nomeUtente) {
int i=0;
if(this.partita.getGiocatori().isEmpty()) {
return null;
} else {
for(i=0; i<this.partita.getGiocatori().size();i++) {
if(partita.getGiocatori().get(i).getUtente().getNomeUtente().equals(nomeUtente)) {
break;
}
}
}
return this.partita.getGiocatori().get(i);
}
public String mappaGenerale(String request) {
String token = request.split(",")[1].split("=")[1];
String answer;
Cella[][] mappa = this.partita.getIsola().getMappa();
//verifico se c'e' nel file Token.txt
boolean trovatoToken = cercaNelFile("Token.txt",token,null," ",1);
if(trovatoToken) {
//accedo al file TokenInPartita.txt per verificare se e' in partita
boolean trovatoInPartita = cercaNelFile("TokenInPartita.txt",token,null," ",1);
if(trovatoInPartita) {
Giocatore giocatore = this.individuaGiocatore(token.split("-")[0]);
answer = "@mappaGenerale,{40,40},";
//traduco la mappa di tipo Cella in tipo String
for(int i=MAX-1; i>=0; i
for(int j=0; j<MAX; j++) {
if(!giocatore.getMappaVisibile()[i][j]) {
answer = answer.concat("[b]");
} else {
if(mappa[i][j]==null) {
answer = answer.concat("[a]");
} else {
if(mappa[i][j].getOccupante() instanceof Carogna) {
answer = answer.concat("[c]");
} else {
if(mappa[i][j].getOccupante() instanceof Vegetale) {
answer = answer.concat("[v]");
}
}
}
}
}
answer = answer.concat(";");
}
}
else {
answer = "@no,@nonInPartita";
}
}
else {
answer = "@no,@tokenNonValido";
}
return answer;
}
private boolean verificaIdDinosauro(String id) {
if(Integer.parseInt(id)>=11 && Integer.parseInt(id)<=85) {
for(int i=0;i<partita.getGiocatori().size();i++) {
for(int j=0;j<partita.getGiocatori().size();j++) {
if(partita.getGiocatori().get(i).getDinosauri().get(j).getId().equals(id)) {
return true;
}
}
}
}
return false;
}
public String listaDinosauri(String request) {
String token;
String answer = new String();
String listaDino = new String();
token = request.split(",")[1].split("=")[1];
//verifico se c'e' nel file Token.txt
boolean trovato = cercaNelFile("Token.txt",token,null," ",1);
if(trovato) {
//accedo al file tokenInPartita.txt per verificare se l'utente si trova in partita
boolean inPartita = cercaNelFile("TokenInPartita.txt",token,null," ",1);
if(inPartita) {
Giocatore giocatore = this.individuaGiocatore(token.split("-")[0]);
for(int k=0; k<giocatore.getDinosauri().size(); k++) {
listaDino += ","+giocatore.getDinosauri().get(k).getId();
}
}
else {
//TODO: ?? dalle specifiche: ''..altrimenti non si e' in partita, e cio' e' definito dal simbolo +'' ??
}
answer = "@listaDinosauri"+listaDino;
}
else if(!trovato) {
answer = "@no,@tokenNonValido";
}
return answer;
}
public String vistaLocale(String request) {
String token = request.split(",")[1].split("=")[1];
String idDino = request.split(",")[2].split("=")[1];
String answer = new String();
Cella[][] mappa = this.partita.getIsola().getMappa();
//verifico se c'e' nel file Token.txt
boolean trovatoToken = cercaNelFile("Token.txt",token,null," ",1);
if(trovatoToken) {
//accedo al file TokenInPartita.txt per verificare se e' in partita
boolean trovatoInPartita = cercaNelFile("TokenInPartita.txt",token,null," ",1);
if(trovatoInPartita) {
Giocatore giocatore = this.individuaGiocatore(token.split("-")[0]);
Dinosauro dinosauro = this.individuaDinosauro(idDino);
if(dinosauro!=null) {
int[] vista = partita.getTurnoCorrente().ottieniVisuale(dinosauro.getRiga(), dinosauro.getColonna(), dinosauro.calcolaRaggioVisibilita());
int maxR = vista[2]-vista[0];
int maxC = vista[3]-vista[1];
answer = "@vistaLocale,{"+vista[0]+","+vista[1]+"}"+","+"{"+vista[2]+","+vista[3]+"}";
for(int i=maxR-1; i>vista[0]; i
for(int j=vista[1]; j<maxC; j++) {
if(mappa[i][j]==null) {
answer = answer.concat("[a]");
} else {
if(mappa[i][j].getOccupante() instanceof Dinosauro) {
answer = answer.concat("[d,").concat(mappa[i][j].getDinosauro().getEnergia()+"").concat("]");
} else {
if(mappa[i][j].getOccupante() instanceof Carogna) {
Carogna carogna = (Carogna)mappa[i][j].getOccupante();
answer = answer.concat("[c,").concat(carogna.getEnergia()+"").concat("]");
} else {
if(mappa[i][j].getOccupante() instanceof Vegetale) {
Vegetale vegetale = (Vegetale)mappa[i][j].getOccupante();
answer = answer.concat("[v,").concat(vegetale.getEnergia()+"").concat("]");
} else {
answer = answer.concat("[t]");
}
}
}
}
}
answer = answer.concat(";");
}
}
else {
answer = "@no,@idNonValido";
}
}
else {
answer = "@no,@nonInPartita";
}
}
else {
answer = "@no,@tokenNonValido";
}
return answer;
}
public String statoDinosauro(String request) {
String token = request.split(",")[1].split("=")[1];
String idDino = request.split(",")[2].split("=")[1];
String answer = new String();
// Cella[][] mappa = this.partita.getIsola().getMappa();
//verifico se c'e' nel file Token.txt
boolean trovatoToken = cercaNelFile("Token.txt",token,null," ",1);
if(trovatoToken) {
//accedo al file TokenInPartita.txt per verificare se e' in partita
boolean trovatoInPartita = cercaNelFile("TokenInPartita.txt",token,null," ",1);
if(trovatoInPartita) {
Giocatore giocatore = this.individuaGiocatore(token.split("-")[0]);
Dinosauro dinosauro = this.individuaDinosauro(idDino);
if(dinosauro!=null) {
//cerco se il dinosauro appartiene al giocatore
boolean proprioDino = false;
for(int i=0; i<giocatore.getDinosauri().size(); i++) {
if(giocatore.getDinosauri().get(i).getId().equals(idDino)) {
proprioDino = true;
}
}
String user = token.split("-")[0];
String razza = giocatore.getNomeSpecie();
String tipo = new String();
if(dinosauro instanceof Carnivoro) {
tipo = "c";
} else {
if(dinosauro instanceof Erbivoro) {
tipo = "e";
}
}
int riga = dinosauro.getRiga();
int colonna = dinosauro.getColonna();
int dimensione = dinosauro.getEnergiaMax()/1000;
if(proprioDino) {
int energia = dinosauro.getEnergia();
//FIXME: turni vissuti
int turni = 1;//turni vissuti ??
answer = "@statoDinosauro"+","+user+","+razza+","+tipo+","+"{"+riga+","+colonna+"}"+","+dimensione+","+energia+","+turni;
}
else {
answer = "@statoDinosauro"+","+user+","+razza+","+tipo+","+"{"+riga+","+colonna+"}"+","+dimensione;
}
}
else {
answer = "@no,@idNonValido";
}
}
else {
answer = "@no,@nonInPartita";
}
}
else {
answer = "@no,@tokenNonValido";
}
return answer;
}
public String deponiUovo(String request) {
String token = request.split(",")[1].split("=")[1];
String idDino = request.split(",")[2].split("=")[1];
String idDinoNato = new String();
String answer = new String();
// Cella[][] mappa = this.partita.getIsola().getMappa();
//verifico se c'e' nel file Token.txt
boolean trovatoToken = cercaNelFile("Token.txt",token,null," ",1);
if(trovatoToken) {
//accedo al file TokenInPartita.txt per verificare se e' in partita
boolean trovatoInPartita = cercaNelFile("TokenInPartita.txt",token,null," ",1);
if(trovatoInPartita) {
Giocatore giocatore = this.individuaGiocatore(token.split("-")[0]);
Dinosauro dinosauro = this.individuaDinosauro(idDino);
if(dinosauro!=null) {
if(dinosauro.getEtaDinosauro()<dinosauro.getDurataVita()) {
//FIXME: eta' attuale e' il numero dei turni e non delle mosse
answer = "@no,@raggiuntoLimiteMosseDinosauro";
} else {
int stato = giocatore.eseguiDeposizionedeponiUovo(dinosauro);
switch (stato) {
case 0:
answer = "@no,@raggiuntoNumeroMaxDinosauri";
break;
case 1:
//FIXME: fornire l'id del nuovo dinosauro nato
answer = "@ok,"+idDinoNato;
break;
case -2:
answer = "@no,@mortePerInedia";
break;
}
}
}
else {
answer = "@no,@idNonValido";
}
}
else {
answer = "@no,@nonInPartita";
}
}
else {
answer = "@no,@tokenNonValido";
}
return answer;
}
private Dinosauro individuaDinosauro (String id) {
if(this.partita.getGiocatori().isEmpty()) {
return null;
} else {
for(int i=0; i<this.partita.getGiocatori().size();i++) {
for(int j=0; j<this.partita.getGiocatori().get(i).getDinosauri().size();j++) {
if(this.partita.getGiocatori().get(i).getDinosauri().get(j).getId().equals(id)) {
return this.partita.getGiocatori().get(i).getDinosauri().get(j);
}
}
}
}
return null;
}
public String cresciDinosauro(String request) {
String answer = new String();
String token = request.split(",")[1].split("=")[1];
String idDino = request.split(",")[2].split("=")[1];
//verifico se c'e' nel file Token.txt
boolean trovatoToken = cercaNelFile("Token.txt",token,null," ",1);
boolean trovatoInPartita = cercaNelFile("TokenInPartita.txt",token,null," ",1);
if(trovatoToken) {
if(trovatoInPartita) {
if(this.verificaIdDinosauro(idDino)) {
Dinosauro dinosauro = this.individuaDinosauro(idDino);
if(dinosauro.getEtaDinosauro()<dinosauro.getDurataVita()) {
int statoCrescita = dinosauro.aumentaDimensione();
if(statoCrescita==1) {
//azione di crescita eseguita correttamente
answer = "@ok";
} else {
if(statoCrescita==0) {
answer = "@no,@raggiuntaDimensioneMax";
} else { //se stato crescita e' ==-1 il dinosauro deve essere rimosso perche' sebza energia
answer = "@no,@mortePerInedia";
}
}
} else {
answer = "@no,@raggiuntoLimiteMosseDinosauro";
}
} else {
answer = "@no,@idNonValido";
}
} else {
answer = "@no,@nonInPartita";
}
} else {
answer = "@no,@tokenNonValido";
}
return answer;
}
public String muoviDinosauro(String request) {
String token = request.split(",")[1].split("=")[1];
String answer = new String();
String idDino = request.split(",")[2].split("=")[1];
System.out.println(request);
System.out.println(request.split("=")[3]);
String destinazione = request.split("=")[3].replace("{","").replace("}", ""); //espressa come "X,Y"
int riga = Integer.parseInt(destinazione.split(",")[0]);
int colonna = Integer.parseInt(destinazione.split(",")[1]);
System.out.println("riga, colonna " + riga + "," + colonna);
this.partita.getIsola().stampaMappaRidotta();
//verifico se c'e' nel file Token.txt
boolean trovatoToken = cercaNelFile("Token.txt",token,null," ",1);
boolean trovatoInPartita = cercaNelFile("TokenInPartita.txt",token,null," ",1);
if(trovatoToken) {
if(trovatoInPartita) {
if(this.verificaIdDinosauro(idDino)) {
Dinosauro dinosauro = this.individuaDinosauro(idDino);
if(dinosauro.getEtaDinosauro()<=dinosauro.getDurataVita()) {
int statoMovimento = partita.getTurnoCorrente().spostaDinosauro(dinosauro, riga, colonna);
switch(statoMovimento) {
case -2:
answer = "@no,@mortePerInedia";
break;
case -1:
answer = "@no,@destinazioneNonValida";
break;
case 0:
answer = "@ok,@combattimento,p";
break;
case 1:
answer = "@ok";
break;
case 2:
answer = "@ok,@combattimento,v";
break;
}
} else {
answer = "@no,@raggiuntoLimiteMosseDinosauro";
}
} else {
answer = "@no,@idNonValido";
}
} else {
answer = "@no,@nonInPartita";
}
} else {
answer = "@no,@tokenNonValido";
}
return answer;
}
public void run() {
String comando = new String();
String answer;
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
while (true) {
String request = bufferedReader.readLine();
if(request!=null) {
comando = request.split(",")[0];
}
//FIXME
// if (comando == null) {
// System.out.println("Client closed connection.");
// break;
// } else
if (comando.equals("@creaUtente")) {
answer = creaUtente(request);
bufferedWriter.write(answer);
}
else if (comando.equals("@login")) {
answer=login(request);
bufferedWriter.write(answer);
}
else if (comando.equals("@creaRazza")) {
answer=creaRazza(request);
bufferedWriter.write(answer);
}
else if (comando.equals("@accessoPartita")) {
answer=accessoPartita(request);
bufferedWriter.write(answer);
}
else if (comando.equals("@uscitaPartita")) {
answer=uscitaPartita(request);
bufferedWriter.write(answer);
}
else if (comando.equals("@listaGiocatori")) {
answer=listaGiocatori(request);
bufferedWriter.write(answer);
}
else if (comando.equals("@logout")) {
answer=logout(request);
bufferedWriter.write(answer);
}
else if (comando.equals("@mappaGenerale")) {
answer=mappaGenerale(request);
bufferedWriter.write(answer);
}
else if (comando.equals("@listaDinosauri")) {
answer = listaDinosauri(request);
bufferedWriter.write(answer);
}
else if (comando.equals("@vistaLocale")) {
answer = vistaLocale(request);
bufferedWriter.write(answer);
}
else if (comando.equals("@statoDinosauro")) {
answer = statoDinosauro(request);
bufferedWriter.write(answer);
}
else if (comando.equals("@muoviDinosauro")) {
answer = muoviDinosauro(request);
bufferedWriter.write(answer);
}
else if (comando.equals("@cresciDinosauro")) {
answer = cresciDinosauro(request);
bufferedWriter.write(answer);
}
else if (comando.equals("@deponiUovo")) {
answer = deponiUovo(request);
bufferedWriter.write(answer);
}
else {
bufferedWriter.write("@unknownCommand");
}
bufferedWriter.newLine();
bufferedWriter.flush();
}
}
catch (IOException e) {
System.out.println("Error in the connection with the client.");
}
}
}
|
package br.com.dbsoft.task;
import java.sql.Connection;
import java.sql.Date;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import javax.annotation.PreDestroy;
import org.apache.log4j.Logger;
import br.com.dbsoft.error.DBSIOException;
import br.com.dbsoft.message.DBSMessage;
import br.com.dbsoft.message.DBSMessage.MESSAGE_TYPE;
import br.com.dbsoft.message.DBSMessages;
import br.com.dbsoft.util.DBSBoolean;
import br.com.dbsoft.util.DBSDate;
import br.com.dbsoft.util.DBSFormat;
import br.com.dbsoft.util.DBSIO;
import br.com.dbsoft.util.DBSNumber;
/**
* @author ricardo.villar
*
* @param <DataModelClass>
*/
public class DBSTask<DataModelClass> implements IDBSTaskEventsListener {
public static enum TaskState {
STOPPED ("Stopped", 1),
RUNNING ("Running", 2),
SCHEDULED ("Scheduled", 3);
private String wName;
private int wCode;
private TaskState(String pName, int pCode) {
this.wName = pName;
this.wCode = pCode;
}
public String getName() {
return wName;
}
public int getCode() {
return wCode;
}
public static TaskState get(int pCode) {
switch (pCode) {
case 1:
return TaskState.STOPPED;
case 2:
return TaskState.RUNNING;
case 3:
return TaskState.SCHEDULED;
default:
return TaskState.STOPPED;
}
}
}
public static enum RunStatus{
EMPTY ("Empty", 0),
SUCCESS ("Success", 1),
INTERRUPTED ("Interrupted", 2),
ERROR ("Error", 3);
private String wName;
private int wCode;
private RunStatus(String pName, int pCode) {
this.wName = pName;
this.wCode = pCode;
}
public String getName() {
return wName;
}
public int getCode() {
return wCode;
}
public static RunStatus get(Integer pCode) {
switch (pCode) {
case 0:
return RunStatus.EMPTY;
case 1:
return RunStatus.SUCCESS;
case 2:
return RunStatus.INTERRUPTED;
case 3:
return RunStatus.ERROR;
default:
return RunStatus.EMPTY;
}
}
}
protected Logger wLogger = Logger.getLogger(this.getClass());
protected Connection wConnection;
protected static DBSMessage wMessageError = new DBSMessage(MESSAGE_TYPE.ERROR,"Erro: %s");
protected DBSMessages<DBSMessage> wMessages = new DBSMessages<DBSMessage>(DBSMessage.class);
private List<IDBSTaskEventsListener> wEventListeners = new ArrayList<IDBSTaskEventsListener>();
private int wId;
private String wName = "";
private int wSteps = 1;
private int wSubSteps = 1;
private String wCurrentStepName = "";
private int wCurrentSubStep = 1;
private int wCurrentStep;
private TaskState wTaskState = TaskState.STOPPED;
private RunStatus wRunStatus = RunStatus.EMPTY;
private RunStatus wLastRunStatus = RunStatus.EMPTY;
private Long wTimeOut = 0L;
private Long wTimeStarted = 0L;
private Long wTimeEnded = 0L;
private Date wScheduleDate;
private int wRetryOnErrorSeconds = 0;
private int wRetryOnErrorTimes = 0;
private Timer wTimer;// = new Timer();
private RunByThread wRunThread;
private boolean wMultiTask = true;
private DataModelClass wDataModel; //Armazenamento auxiliar de dados vinculados a esta tarefa
private DataModelClass wDataModelValueOriginal; //Armazenamento auxiliar de dados vinculados a esta tarefa
private Double wPercentageCompleted = 0D;
private String wUserName;
private String wUserPassword;
private boolean wReRun = true;
private int wRetryOnErrorCount = 0;
private boolean wTransactionEnabled = true;
public DBSTask(){
pvFireEventInitializeTask();
}
public DBSTask(Connection pConnection) {
wConnection = pConnection;
pvFireEventInitializeTask();
}
public DBSTask(IDBSTaskEventsListener pEventListener) {
addEventListener(pEventListener);
pvFireEventInitializeTask();
}
public DBSTask(IDBSTaskEventsListener pEventListener, Connection pConnection) {
wConnection = pConnection;
addEventListener(pEventListener);
pvFireEventInitializeTask();
}
public final void addEventListener(IDBSTaskEventsListener pEventListener) {
if (!wEventListeners.contains(pEventListener)){
wEventListeners.add(pEventListener);
}
}
public final void removeEventListener(IDBSTaskEventsListener pEventListener) {
if (wEventListeners.contains(pEventListener)){
wEventListeners.remove(pEventListener);
}
}
/**
* Excluir todos os eventListeners vinculados a esta tarefa.
*/
public final void removeAllEventListeners() {
wEventListeners.clear();
}
public Thread getThread(){
return wRunThread;
}
public Connection getConnection() {return wConnection;}
public void setConnection(Connection pConnection) {wConnection = pConnection;}
public String getUserName() {return wUserName;}
public void setUserName(String pUserName) {
wUserName = pUserName;
if (pUserName == null){
wUserPassword = null;
}
}
public String getUserPassword() {return wUserPassword;}
public void setUserPassword(String pUserPassword) {wUserPassword = pUserPassword;}
public Long getTimeElapsed() {
if (getTaskState() == TaskState.RUNNING){
wTimeEnded = System.currentTimeMillis();
}
return wTimeEnded - wTimeStarted;
}
public Long getTimeOut() {
return wTimeOut;
}
public void setTimeOut(Long pTimeOut) {
wTimeOut = pTimeOut;
}
/**
* Retorna se tarefa ultrapassou o tempo permitido.
* @return
*/
public boolean isTimeOut(){
if (wTimeOut == 0L){
return false;
}
return ((System.currentTimeMillis() - wTimeStarted) < wTimeOut);
}
/**
* Retorna a hora iniciada
* @return
*/
public Long getTimeStarted(){
return wTimeStarted;
}
/**
* Identificador auxiliar
* @return
*/
public final int getId() {
return wId;
}
/**
* Identificardos auxiliar
* @param wId
*/
public final void setId(int wId) {
this.wId = wId;
}
public final void setTransationEnabled(Boolean pTransactionEnabled){
wTransactionEnabled = DBSBoolean.toBoolean(pTransactionEnabled);
}
public final Boolean getTransationEnabled(){
return wTransactionEnabled;
}
public final String getName() {return wName;}
/**
* Configura o nome da tarefa
* @param pName
*/
public final void setName(String pName) {this.wName = pName;}
public final String getCurrentStepName() {return wCurrentStepName;}
/**
* Configura o nome da etapa
* @param pName
* @throws DBSIOException
*/
public final void setCurrentStepName(String pCurrentStepName) throws DBSIOException {
if (wCurrentStepName != pCurrentStepName){
wCurrentStepName = pCurrentStepName;
pvFireEventTaskUpdated();
}
}
public final boolean isMultiTarefa() {return wMultiTask;}
public final void setMultiTask(boolean pMultiTask) {wMultiTask = pMultiTask;}
public final int getRetryOnErrorSeconds() {return wRetryOnErrorSeconds;}
public final void setRetryOnErrorSeconds(int pRetryOnErrorSeconds) {wRetryOnErrorSeconds = pRetryOnErrorSeconds;}
public final int getRetryOnErrorTimes() {return wRetryOnErrorTimes;}
public final void setRetryOnErrorTimes(int pRetryOnErrorTimes) {wRetryOnErrorTimes = pRetryOnErrorTimes;}
public final DataModelClass getDataModel() {
return wDataModel;
}
@SuppressWarnings("unchecked")
public final void setDataModel(DataModelClass pDataModel) throws InstantiationException, IllegalAccessException {
wDataModelValueOriginal = (DataModelClass) pDataModel.getClass().newInstance();
DBSIO.copyDataModelFieldsValue(pDataModel, wDataModelValueOriginal);
wDataModel = pDataModel;
}
public final DataModelClass getDataModelValueOriginal() {
return wDataModelValueOriginal;
}
public final RunStatus getLastRunStatus() {
return wLastRunStatus;
}
public final void setLastRunStatus(RunStatus pLastRunStatus) {
wLastRunStatus = pLastRunStatus;
}
public final void setLastRunStatus(Integer pLastRunStatus) {
setLastRunStatus(RunStatus.get(pLastRunStatus));
}
public final RunStatus getRunStatus() {
return wRunStatus;
}
public final TaskState getTaskState() {
return wTaskState;
}
public final Integer getSteps() {
return wSteps;
}
public final void setSteps(Integer pSteps) {
if(pSteps>0){
wSteps = pSteps;
pvSetCurrentStep(1);
}
}
public final Integer getCurrentStep() {
return wCurrentStep;
}
public final Integer getSubSteps() {
return wSubSteps;
}
public final void setSubSteps(int pSubSteps) {
if(pSubSteps>0){
wSubSteps = pSubSteps;
pvSetCurrentSubStep(0);
}
}
public final void endSubStep() throws DBSIOException{
int xNextSubStep = wCurrentSubStep+1;
if (xNextSubStep > wSubSteps){
wLogger.error(getName() + ":Quantidade de SubsSteps total de " + wSubSteps + " é inferior a " + xNextSubStep);
}else{
pvSetCurrentSubStep(xNextSubStep);
//Calcula percentual atual e dispara evento que percentual mudou
pvCalcPercentageCompleted();
}
}
public final Integer getCurrentSubStep() {
return wCurrentSubStep;
}
public final Double getPercentageCompleted(){
return wPercentageCompleted;
}
public void setReRun(Boolean pReRun){
wReRun = pReRun;
}
public Boolean getReRun(){
return wReRun;
}
public final Date getScheduleDate() {return wScheduleDate;}
public synchronized final void setScheduleDate(Date pScheduleDate) throws DBSIOException {
pvRetryReset();
pvScheduleDate(pScheduleDate);
}
/**
* Indica se tarefa foi interrompida
* @return
*/
public final Boolean isInterrupted() {
return (wRunStatus == RunStatus.INTERRUPTED &&
wTaskState != TaskState.RUNNING);
}
public final boolean isRunning(){
return (wTaskState==TaskState.RUNNING);
}
public final boolean isActive(){
return (wTaskState!=TaskState.STOPPED);
}
public synchronized final void run() throws DBSIOException{
try {
pvRetryReset();
pvRunTask();
} catch (Exception e) {
wLogger.error(e);
DBSIO.throwIOException(e.getMessage());
}
}
public synchronized final void kill() {
try{
if (wRunThread != null){
wRunThread.kill();
}
interrupt();
pvDesativaAgendamento();
pvSetTaskState(pvGetNotRunnigTaskState());
removeAllEventListeners();
}catch(Exception e){
wLogger.error(getName(), e);
}
}
public synchronized final void interrupt() throws DBSIOException{
pvInterrupt(RunStatus.INTERRUPTED);
}
public synchronized final void reset() throws DBSIOException{
pvSetRunStatus(RunStatus.EMPTY);
setSteps(getSteps());
wPercentageCompleted = 0D;
}
private void pvRunTask() throws DBSIOException{
if (!isRunning()){
try{
if (wMultiTask){
if (wRunThread == null || !wRunThread.isAlive()){
wRunThread = new RunByThread();
wRunThread.setName(wName);
}
wRunThread.start();
}else{
//Executa sem multitarefa
pvRunTaskSteps();
}
}catch(Exception e){
wLogger.error(getName(), e);
pvInterrupt(RunStatus.ERROR);
throw new DBSIOException(e);
}
}else{
wLogger.warn("Tarefa já em execução. Nova solicitação de execução foi ignorada.");
}
}
private synchronized void pvRunTaskSteps() throws DBSIOException{
wTimeStarted = System.currentTimeMillis();
wTimeEnded = wTimeStarted;
while (wReRun){
wReRun = false;
try{
if (!isRunning()){
pvSetTaskState(TaskState.RUNNING);
//Reseta para a etapa inicial
reset();
//Dispara evento e verifica se pode iniciar
if (pvFireEventBeforeRun()){
for (int xStep = 1; xStep < wSteps + 1; xStep++){
Thread.yield();
pvSetCurrentStep(xStep);
pvCalcPercentageCompleted();
if (!pvFireEventStep()
&& getRunStatus() != RunStatus.INTERRUPTED){
pvInterrupt(RunStatus.ERROR);
break;
}
//Finaliza se foi interrompido
if (getRunStatus() == RunStatus.INTERRUPTED){
break;
}
}
//Configura
if (getRunStatus() == RunStatus.EMPTY){
pvSetRunStatus(RunStatus.SUCCESS);
}
setLastRunStatus(getRunStatus());
wTimeEnded = System.currentTimeMillis();
if (getRunStatus() != RunStatus.INTERRUPTED){
pvFireEventAfterRun();
}
}
}else{
wLogger.error("pvRunTaskSteps:Tarefa já se contra em execução:" + wRunThread.getName() + ":" + wRunThread.getId());
}
}catch(Exception e){
wLogger.error(getName(), e);
pvInterrupt(RunStatus.ERROR);
setLastRunStatus(getRunStatus());
throw new DBSIOException(e);
}finally{
pvSetTaskState(pvGetNotRunnigTaskState());
//Se foi configurado a quantidade de segundos para uma nova tentativa...
if (wRetryOnErrorSeconds > 0
&& wRetryOnErrorTimes > 0){
if (getRunStatus() == RunStatus.ERROR){
wReRun = false;
//Incrementa contador de erro
wRetryOnErrorCount++;
//Ignora nova tentariva se houver controle de quantidade de tentaticas em caso de erro e esta tiver sido ultrapassada.
if (wRetryOnErrorTimes != 0
&& wRetryOnErrorCount > wRetryOnErrorTimes){
wLogger.warn(getName() + ":Ultrapassada a quantidade máxima de " + wRetryOnErrorTimes + " tentativas de execução.");
//Zera qualquer agendamente anterior
setScheduleDate(null);
}else{
//Faz agendamento para nova tentativa
pvRetrySchedule();
}
}else{
//Zera contador de erro
wRetryOnErrorCount = 0;
}
}
}
}
wReRun = true;
}
/**
* Zera controle de tentativas por erro
*/
private final void pvRetryReset(){
wRetryOnErrorCount = 0;
}
private void pvAtivaAgendamento() throws DBSIOException{
pvKillTimer();
//Cria novo agendamento
if (wScheduleDate != null){
Timestamp xNow = DBSDate.getNowTimestamp();
if (!wScheduleDate.before(xNow)){
//Cria timer
wTimer = new Timer("Timer - " + getName());
wTimer.schedule(new RunByTimer(), wScheduleDate);
//COnfigura como agendado.
pvSetTaskState(TaskState.SCHEDULED);
wLogger.info(getName() + " agendada para: " + DBSFormat.getFormattedDateTime(wScheduleDate));
}else{
wLogger.error("Data/Hora[" + DBSFormat.getFormattedDateTime(wScheduleDate) + "]" +
" menor que a data/hora[" + DBSFormat.getFormattedDateTime(xNow) + "] atual.");
}
}
}
/**
* Desativa o agendamento e cancela o timer se estiver ativo
*/
private void pvDesativaAgendamento(){
wScheduleDate = null;
pvKillTimer();
}
/**
* Cancela o timer se estiver ativo
*/
private void pvKillTimer(){
if (wTimer != null) {
wTimer.cancel();
wTimer.purge();
}
}
private void pvCalcPercentageCompleted() throws DBSIOException{
if (wSteps != 0){
Double xCurrentStep = (double) (wCurrentStep -1);
Double xCurrentSubStep = (double) wCurrentSubStep;
//Se estiver iniciado o processamento
if (getTaskState() == TaskState.RUNNING){
//Se for inicio
if (xCurrentStep==0 &&
xCurrentSubStep==0){
wPercentageCompleted = 0.001;
}else{
double xP = DBSNumber.divide(xCurrentStep, (double) wSteps);
xP += ((1 / (double) wSteps) * xCurrentSubStep / wSubSteps);
wPercentageCompleted = xP * 100;
}
//Se processamento estiver parado
}else{
//Se finalizado com sucesso
if (wCurrentStep == wSteps &&
getRunStatus() == RunStatus.SUCCESS){
wPercentageCompleted = 100D;
}else{
wPercentageCompleted = 0D;
}
}
//Se quantida de estapas for 0.
}else{
wPercentageCompleted = 100D;
}
wPercentageCompleted = DBSNumber.round(wPercentageCompleted, 3);
pvFireEventTaskUpdated();
}
private final void pvSetCurrentStep(Integer pCurrentStep) {
wCurrentStep = pCurrentStep;
setSubSteps(1);//Reseta a quantidade de substeps sempre que o step for trocado. O substep deve ser definido dinamicamente dentro do evento step
}
private final void pvSetCurrentSubStep(int pCurrentSubStep) {
wCurrentSubStep = pCurrentSubStep;
}
private final void pvSetTaskState(TaskState pRunState) throws DBSIOException {
if (wTaskState != pRunState){
wTaskState = pRunState;
pvFireEventTaskStateChanged();
pvCalcPercentageCompleted();
}
}
private final void pvSetRunStatus(RunStatus pRunStatus) throws DBSIOException {
if (wRunStatus != pRunStatus){
wRunStatus = pRunStatus;
pvFireEventRunStatusChanged();
pvFireEventTaskUpdated();
}
}
private final void pvInterrupt(RunStatus pRunStatus) throws DBSIOException{
if (isRunning()){
pvSetRunStatus(pRunStatus);
pvFireEventInterrupted();
}
}
@PreDestroy
private void pvFinalize() {
pvFireEventFinalizeTask();
kill();
try {
super.finalize();
} catch (Throwable ignore) {}
}
/**
* Programa um novo agendamento a partir da quantidade de segundos definida em getSecondsToRetry,
* caso a seja uma tarefa agendada e houve erro.
* @throws DBSIOException
*/
private void pvRetrySchedule() throws DBSIOException{
if (wRetryOnErrorSeconds > 0
&& wRetryOnErrorTimes > 0){
Date xData = DBSDate.getNowDate();
xData = DBSDate.getDateAddSeconds(xData, wRetryOnErrorSeconds);
wLogger.warn(getName() + ":Tentativa " + wRetryOnErrorCount + " de " + wRetryOnErrorTimes + " será executada em: " + DBSFormat.getFormattedDateCustom(xData, "dd/MM/yyyy HH:mm:ss"));
pvScheduleDate(xData);
}
}
/**
* Ativa agendamento
* @param pScheduleDate
* @throws DBSIOException
*/
private final void pvScheduleDate(Date pScheduleDate) throws DBSIOException {
wScheduleDate = pScheduleDate;
pvAtivaAgendamento();
}
private TaskState pvGetNotRunnigTaskState(){
if (wScheduleDate != null
&& wScheduleDate.after(DBSDate.getNowTimestamp())){
return TaskState.SCHEDULED;
}else{
return TaskState.STOPPED;
}
}
private boolean pvFireEventInitializeTask() {
DBSTaskEvent xE = new DBSTaskEvent(this);
//Chame o metodo(evento) local para quando esta classe for extendida
initializeTask(xE);
for (int xX=0; xX<wEventListeners.size(); xX++){
wEventListeners.get(xX).initializeTask(xE);
}
return xE.isOk();
}
private void pvFireEventFinalizeTask(){
DBSTaskEvent xE = new DBSTaskEvent(this);
//Chame o metodo(evento) local para quando esta classe for extendida
finalizeTask(xE);
for (int xX=0; xX<wEventListeners.size(); xX++){
wEventListeners.get(xX).finalizeTask(xE);
}
}
private boolean pvFireEventBeforeRun() throws DBSIOException{
// System.out.println("Tarefa " + getName() + ":BEFORE RUN:" + wRunThread.getId());
DBSTaskEvent xE = new DBSTaskEvent(this);
try{
openConnection();
//Chame o metodo(evento) local para quando esta classe for extendida
beforeRun(xE);
if (xE.isOk()){
for (int xX=0; xX<wEventListeners.size(); xX++){
wEventListeners.get(xX).beforeRun(xE);
//Sai em caso de erro
if (!xE.isOk()){break;}
}
}
return xE.isOk();
}catch(Exception e){
wLogger.error("BeforeRun:", e);
throw e;
}finally{
closeConnection();
}
}
private void pvFireEventAfterRun() throws DBSIOException{
// System.out.println("Tarefa " + getName() + ":AFTER RUN:" + wRunThread.getId());
DBSTaskEvent xE = new DBSTaskEvent(this);
try{
openConnection();
//Chame o metodo(evento) local para quando esta classe for extendida
afterRun(xE);
for (int xX=0; xX<wEventListeners.size(); xX++){
wEventListeners.get(xX).afterRun(xE);
}
}catch(Exception e){
wLogger.error("AfterRun", e);
throw e;
}finally{
closeConnection();
}
}
/**
* Dispara evento a cada nova etapa da tarefa
* @return
* @throws DBSIOException
*/
private boolean pvFireEventStep() throws DBSIOException{
// System.out.println("STEP + " + wRunThread.getId());
DBSTaskEvent xE = new DBSTaskEvent(this);
Boolean xOk = true;
try{
openConnection();
if (getTransationEnabled()){
DBSIO.beginTrans(wConnection);
}
//Chame o metodo(evento) local para quando esta classe for extendida
step(xE);
xOk = xE.isOk() && getRunStatus() == RunStatus.EMPTY;
// wLogger.info("Step:" + getCurrentStep() + ":" + getCurrentStepName() + ":" + getRunStatus().getName());
if (xOk){
for (int xX=0; xX<wEventListeners.size(); xX++){
wEventListeners.get(xX).step(xE);
xOk = (xE.isOk() && getRunStatus() == RunStatus.EMPTY);
if (!xOk){break;}
Thread.yield();
}
}
if (getTransationEnabled()){
DBSIO.endTrans(wConnection, xOk);
}
return xE.isOk();
}catch(Exception e){
wLogger.error("Step:" + getCurrentStep() + ":" + getCurrentStepName(), e);
DBSIO.endTrans(wConnection, false);
throw e;
}finally{
closeConnection();
}
}
private void pvFireEventTaskStateChanged() throws DBSIOException{
DBSTaskEvent xE = new DBSTaskEvent(this);
//Chame o metodo(evento) local para quando esta classe for extendida
taskStateChanged(xE);
for (int xX=0; xX<wEventListeners.size(); xX++){
wEventListeners.get(xX).taskStateChanged(xE);
}
}
private void pvFireEventRunStatusChanged() throws DBSIOException{
DBSTaskEvent xE = new DBSTaskEvent(this);
//Chame o metodo(evento) local para quando esta classe for extendida
runStatusChanged(xE);
for (int xX=0; xX<wEventListeners.size(); xX++){
wEventListeners.get(xX).runStatusChanged(xE);
}
}
private void pvFireEventInterrupted() throws DBSIOException {
DBSTaskEvent xE = new DBSTaskEvent(this);
//Chame o metodo(evento) local para quando esta classe for extendida
interrupted(xE);
wLogger.warn("Interrupt:Step:" + getCurrentStep() + ":" + getCurrentStepName());
for (int xX=0; xX<wEventListeners.size(); xX++){
wEventListeners.get(xX).interrupted(xE);
}
}
private void pvFireEventTaskUpdated() throws DBSIOException{
DBSTaskEvent xE = new DBSTaskEvent(this);
//Chame o metodo(evento) local para quando esta classe for extendida
taskUpdated(xE);
for (int xX=0; xX<wEventListeners.size(); xX++){
wEventListeners.get(xX).taskUpdated(xE);
}
}
public class NotifyObject{}
private class RunByThread extends Thread{
private Boolean wKeepAlive = true;
private NotifyObject wNO = new NotifyObject();
public void kill(){
wKeepAlive = false;
synchronized(wNO){
wNO.notify();
}
}
@Override
public void start() {
//Se tarefa for nova
if (getState() == State.NEW){
//Inicia pela primeira vez a tarefa
super.start();
}else{
//Acorda a tarefa que estava em espera
synchronized(wNO){
wNO.notify();
}
}
}
@Override
public void run() {
//Executa as etapas novamente enquando a tarefa estiver ativa(on)
while (wKeepAlive){
//Executa as estapas
try {
pvRunTaskSteps();
synchronized(wNO){
wNO.wait();
}
} catch (InterruptedException | DBSIOException e) {
wLogger.error(e);
}
}
}
}
private class RunByTimer extends TimerTask{
@Override
public void run() {
try{
wLogger.info("Inicio:Timer");
pvRunTask();
} catch (Exception e) {
wLogger.error(e);
}
}
}
@Override
public void initializeTask(DBSTaskEvent pEvent){
}
@Override
public void finalizeTask(DBSTaskEvent pEvent) {
}
@Override
public void beforeRun(DBSTaskEvent pEvent) throws DBSIOException{
}
@Override
public void afterRun(DBSTaskEvent pEvent) throws DBSIOException {
}
@Override
public void interrupted(DBSTaskEvent pEvent) {
}
@Override
public void step(DBSTaskEvent pEvent) throws DBSIOException{
}
@Override
public void taskStateChanged(DBSTaskEvent pEvent) {
}
@Override
public void runStatusChanged(DBSTaskEvent pEvent) {
}
@Override
public void taskUpdated(DBSTaskEvent pEvent) {
}
protected void createConnection() throws DBSIOException{
}
protected void destroyConnection() throws DBSIOException{
DBSIO.closeConnection(wConnection);
}
public synchronized boolean openConnection() {
try {
if ((wConnection!=null && wConnection.isClosed()) ||
wConnection==null){
try {
createConnection();
return true;
} catch (DBSIOException e) {
wMessageError.setMessageText(e.getLocalizedMessage());
addMessage(wMessageError);
}
}
} catch (SQLException e) {
wMessageError.setMessageTextParameters(e.getLocalizedMessage());
addMessage(wMessageError);
}
return false;
}
public synchronized void closeConnection(){
if (wConnection != null){
try {
if (!wConnection.isClosed()){
try {
destroyConnection();
} catch (DBSIOException e) {
wMessageError.setMessageText(e.getLocalizedMessage());
addMessage(wMessageError);
}
}
} catch (SQLException e) {
wMessageError.setMessageTextParameters(e.getLocalizedMessage());
addMessage(wMessageError);
}
}
}
public String getMessageText(){
return wMessages.getCurrentMessageText();
}
public String getMessageTooltip(){
return wMessages.getCurrentMessageTooltip();
}
public DBSMessages<DBSMessage> getMessages(){
return wMessages;
}
/**
* @return
*/
public Boolean getHasMessage(){
if (wMessages.getCurrentMessageKey()!=null){
return true;
}else{
return false;
}
}
public void setMessageValidated(Boolean pIsValidated){
if (wMessages!=null){
String xMessageKey = wMessages.getCurrentMessageKey();
wMessages.setValidated(pIsValidated);
messageValidated(xMessageKey, pIsValidated);
}
}
protected void messageValidated(String pMessageKey, Boolean pIsValidated){}
/**
* Limpa fila de mensagens
*/
protected void clearMessages(){
wMessages.clear();
}
protected void addMessage(String pMessageKey, MESSAGE_TYPE pMessageType, String pMessageText){
addMessage(pMessageKey, pMessageType, pMessageText, "");
}
protected void addMessage(MESSAGE_TYPE pMessageType, String pMessageText){
wMessages.add(pMessageType, pMessageText);
}
/**
* Adiciona uma mensagem a fila
* @param pMessage
*/
protected void addMessage(DBSMessage pMessage){
addMessage(pMessage.getMessageText(), pMessage.getMessageType(), pMessage.getMessageText(), pMessage.getMessageTooltip());
}
/**
* Adiciona uma mensagem a fila
* @param pMessage
*/
protected void addMessage(String pMessageKey, MESSAGE_TYPE pMessageType, String pMessageText, String pMessageTooltip){
//Configura o icone do dialog confome o tipo de mensagem
wMessages.add(pMessageKey, pMessageType, pMessageText, pMessageTooltip);
}
/**
* Remove uma mensagem da fila
* @param pMessageKey
*/
protected void removeMessage(String pMessageKey){
wMessages.remove(pMessageKey);
}
/**
* Retorna se mensagem foi validada
* @param pMessageKey
* @return
*/
protected boolean isMessageValidated(String pMessageKey){
return wMessages.isValidated(pMessageKey);
}
protected boolean isMessageValidated(DBSMessage pMessage){
return isMessageValidated(pMessage.getMessageText());
}
}
|
package istc.bigdawg.planner;
import java.util.LinkedHashMap;
import java.util.List;
import javax.ws.rs.core.Response;
import istc.bigdawg.monitoring.Monitor;
import istc.bigdawg.packages.QueriesAndPerformanceInformation;
import istc.bigdawg.signature.Signature;
import org.apache.log4j.Logger;
import org.mortbay.log.Log;
import istc.bigdawg.executor.Executor;
import istc.bigdawg.executor.plan.QueryExecutionPlan;
import istc.bigdawg.packages.CrossIslandQueryNode;
import istc.bigdawg.packages.CrossIslandQueryPlan;
import istc.bigdawg.parsers.UserQueryParser;
import istc.bigdawg.postgresql.PostgreSQLHandler.QueryResult;
public class Planner {
private static Logger logger = Logger.getLogger(Planner.class.getName());
// private static Integer maxSerial = 0;
public static Response processQuery(String userinput, boolean isTrainingMode) throws Exception {
// UNROLLING
logger.debug("User query received. Parsing...");
LinkedHashMap<String, String> crossIslandQuery = UserQueryParser.getUnwrappedQueriesByIslands(userinput);
CrossIslandQueryPlan ciqp = new CrossIslandQueryPlan(crossIslandQuery);
for (String k : ciqp.getMemberKeySet()) {
if (k.equals("A_OUTPUT")) {
// this is the root; save for later.
continue;
}
CrossIslandQueryNode ciqn = ciqp.getMember(k);
int choice = getGetPerformanceAndPickTheBest(ciqn, isTrainingMode);
// currently there should be just one island, therefore one child, root.
QueryExecutionPlan qep = ciqp.getMember(k).getQEP(choice);
// EXECUTE THE RESULT SUB RESULT
logger.debug("Executing query cross-island subquery "+k+"...");
Executor.executePlan(qep);
}
// pass this to monitor, and pick your favorite
CrossIslandQueryNode ciqn = ciqp.getRoot();
int choice = getGetPerformanceAndPickTheBest(ciqn, isTrainingMode);
// currently there should be just one island, therefore one child, root.
QueryExecutionPlan qep = ciqp.getRoot().getQEP(choice);
// EXECUTE THE RESULT
logger.debug("Executing query execution tree...");
return compileResults(ciqp.getSerial(), Executor.executePlan(qep));
}
/**
* CALL MONITOR: Parses the userinput, generate alternative join plans, and
* GIVE IT TO MONITOR Note: this generates the result
*
* @param userinput
*/
public static int getGetPerformanceAndPickTheBest(CrossIslandQueryNode ciqn, boolean isTrainingMode) throws Exception {
int choice = 0;
List<QueryExecutionPlan> qeps = ciqn.getAllQEPs();
Signature signature = ciqn.getSignature();
if (isTrainingMode) {
Log.debug("Running in Training Mode...");
// now call the corresponding monitor function to deliver permuted.
Monitor.addBenchmarks(qeps, signature, false);
QueriesAndPerformanceInformation qnp = Monitor.getBenchmarkPerformance(qeps);
// does some magic to pick out the best query, store it to the query plan queue
long minDuration = Long.MAX_VALUE;
for (int i = 0; i < qnp.qList.size(); i++){
long currentDuration = qnp.pInfo.get(i);
if (currentDuration < minDuration){
minDuration = currentDuration;
choice = i;
}
}
} else {
Log.debug("Running in production mode!!!");
Signature closest = Monitor.getClosestSignature(signature);
double distance = signature.compare(closest);
Log.debug("Minimum distance between queries: " + distance);
if (closest != null){
Log.debug("Closest query found");
QueriesAndPerformanceInformation qnp = Monitor.getBenchmarkPerformance(closest);
// TODO does some magic to match the best query from the closest
// signature to a query plan for the current query
// Placeholder: This assumes that the order of
// permutations for a similar query will be the
// same as that of the current query
long minDuration = Long.MAX_VALUE;
for (int i = 0; i < qnp.qList.size(); i++){
long currentDuration = qnp.pInfo.get(i);
if (currentDuration < minDuration){
minDuration = currentDuration;
choice = i;
}
}
} else {
Log.debug("No queries that are even slightly similar");
Monitor.addBenchmarks(qeps, signature, true);
}
}
return choice;
};
/**
* FINAL COMPILATION Receive result and send it to user
*
* @param querySerial
* @param result
* @return 0 if no error; otherwise incomplete
*/
public static Response compileResults(int querySerial, QueryResult result) {
logger.debug("[BigDAWG] PLANNER: Query "+querySerial+" is completed. Result:\n");
// print the result;
StringBuffer out = new StringBuffer();
List<List<String>> rows = result.getRows();
List<String> cols = result.getColNames();
for (String name : cols) {
out.append("\t" + name);
}
out.append("\n");
int rowCounter = 1;
for (List<String> row : rows) {
out.append(rowCounter + ".");
for (String s : row) {
out.append("\t" + s);
}
out.append("\n");
rowCounter += 1;
}
System.out.println(out);
return Response.status(200).entity(out.toString()).build();
}
}
|
package cn.cerc.mis.core;
import cn.cerc.db.core.ISession;
import cn.cerc.db.core.LanguageResource;
import cn.cerc.db.core.Utils;
import cn.cerc.db.redis.JedisFactory;
import cn.cerc.db.redis.RedisRecord;
import cn.cerc.mis.other.MemoryBuffer;
import com.google.gson.Gson;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;
import redis.clients.jedis.Jedis;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Map;
@Component
@Scope(WebApplicationContext.SCOPE_REQUEST)
//@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class AppClient implements Serializable {
// private static final Logger log = LoggerFactory.getLogger(AppClient.class);
private static final long serialVersionUID = -3593077761901636920L;
public static final int Version = 1;
public static final String COOKIE_ROOT_PATH = "/";
public static final String phone = "phone";
public static final String android = "android";
public static final String iphone = "iphone";
public static final String wechat = "weixin";
public static final String pad = "pad";
public static final String pc = "pc";
public static final String kanban = "kanban";
public static final String ee = "ee";
private final HttpServletRequest request;
private final HttpServletResponse response;
private String cookieId = "";
private final String key;
private String token;
private String device;
private String deviceId;
private String language;
public AppClient(HttpServletRequest request, HttpServletResponse response) {
this.request = request;
this.response = response;
Cookie[] cookies = this.request.getCookies();
if (cookies != null) {
for (Cookie cookie : request.getCookies()) {
if (cookie.getName().equals(ISession.COOKIE_ID)) {
this.cookieId = cookie.getValue();
break;
}
}
}
if (Utils.isEmpty(this.cookieId)) {
this.cookieId = Utils.getGuid();
if (response != null) {
Cookie cookie = new Cookie(ISession.COOKIE_ID, cookieId);
cookie.setPath(COOKIE_ROOT_PATH);
cookie.setHttpOnly(true);
this.response.addCookie(cookie);
}
}
this.key = MemoryBuffer.buildObjectKey(AppClient.class, this.cookieId, AppClient.Version);
try (Jedis redis = JedisFactory.getJedis()) {
this.device = request.getParameter(ISession.CLIENT_DEVICE);
if (!Utils.isEmpty(device))
redis.hset(key, ISession.CLIENT_DEVICE, device);
else {
this.device = redis.hget(key, ISession.CLIENT_DEVICE);
if (Utils.isEmpty(device)) {
device = pc;
redis.hset(key, ISession.CLIENT_DEVICE, device);
}
}
this.deviceId = request.getParameter(ISession.CLIENT_ID);
if (!Utils.isEmpty(deviceId))
redis.hset(key, ISession.CLIENT_ID, deviceId);
else {
this.deviceId = redis.hget(key, ISession.CLIENT_ID);
if (Utils.isEmpty(deviceId)) {
if (cookies != null) {
for (Cookie cookie : request.getCookies()) {
if (cookie.getName().equals(ISession.CLIENT_ID)) {
this.deviceId = cookie.getValue();
break;
}
}
}
}
// if (Utils.isEmpty(deviceId)) {
// deviceId = Utils.getGuid();
// redis.hset(key, ISession.CLIENT_ID, deviceId);
// if (response != null) {
// Cookie cookie = new Cookie(ISession.CLIENT_ID, deviceId);
// cookie.setPath(COOKIE_ROOT_PATH);
// cookie.setHttpOnly(true);
// this.response.addCookie(cookie);
}
this.language = request.getParameter(ISession.LANGUAGE_ID);
if (!Utils.isEmpty(language))
redis.hset(key, ISession.LANGUAGE_ID, language);
else {
this.language = redis.hget(key, ISession.LANGUAGE_ID);
if (Utils.isEmpty(language)) {
language = LanguageResource.appLanguage;
redis.hset(key, ISession.LANGUAGE_ID, language);
}
}
this.token = request.getParameter(ISession.TOKEN);
if (!Utils.isEmpty(token))
redis.hset(key, ISession.TOKEN, token);
else
this.token = redis.hget(key, ISession.TOKEN);
redis.expire(key, RedisRecord.TIMEOUT);
}
}
/**
* cookie id
*/
public String getCookieId() {
return this.cookieId;
}
public String getToken() {
return token;
}
public void delete(String field) {
try (Jedis redis = JedisFactory.getJedis()) {
redis.hdel(key, field);
}
}
public String getId() {
return this.deviceId;
}
public void setId(String value) {
this.deviceId = value == null ? "" : value;
request.setAttribute(ISession.CLIENT_ID, deviceId);
try (Jedis redis = JedisFactory.getJedis()) {
redis.hset(key, ISession.CLIENT_ID, deviceId);
}
if (value != null && value.length() == 28)// openid
setDevice(phone);
}
public String getDevice() {
return Utils.isEmpty(device) ? pc : device;
}
public void setDevice(String value) {
this.device = Utils.isEmpty(value) ? pc : value;
request.setAttribute(ISession.CLIENT_DEVICE, device);
try (Jedis redis = JedisFactory.getJedis()) {
redis.hset(key, ISession.CLIENT_DEVICE, device);
}
}
public String getLanguage() {
return this.language;
}
public boolean isPhone() {
return phone.equals(getDevice()) || android.equals(getDevice()) || iphone.equals(getDevice())
|| wechat.equals(getDevice());
}
public boolean isKanban() {
return kanban.equals(getDevice());
}
/**
* IPrequest.getRemoteAddr() IP
* <p>
* x-forwarded-for IPunknownIPIP
* <p>
* x-forwarded-for192.168.1.110, 192.168.1.120, 192.168.1.130, 192.168.1.100
* <p>
* IP 192.168.1.110
*
* @param request HttpServletRequest
*
* @return IP
*/
public static String getClientIP(HttpServletRequest request) {
if (request == null)
return "";
try {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
ip = request.getHeader("Proxy-Client-IP");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
ip = request.getHeader("WL-Proxy-Client-IP");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
ip = request.getHeader("HTTP_CLIENT_IP");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
ip = request.getRemoteAddr();
if ("0:0:0:0:0:0:0:1".equals(ip))
ip = "0.0.0.0";
String[] arr = ip.split(",");
ip = Arrays.stream(arr).findFirst().orElse("").trim();
return ip;
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
@Override
public String toString() {
Map<String, String> items;
try (Jedis redis = JedisFactory.getJedis()) {
items = redis.hgetAll(key);
}
return new Gson().toJson(items);
}
}
|
package it.dc.bridge.proxy;
import java.util.logging.Logger;
import org.eclipse.californium.core.CoapClient;
import org.eclipse.californium.core.CoapResponse;
import org.eclipse.californium.core.coap.Request;
import it.dc.bridge.rd.ResourceDirectory;
public class CoAPProxy implements Runnable {
/* the logger */
private static final Logger LOGGER = Logger.getGlobal();
private static final CoAPProxy proxy = new CoAPProxy();
/*
* Since the CoAPProxy is a singleton,
* the constructor must be private.
*/
private CoAPProxy() {}
/**
* The CoAP Proxy is a Singleton.
* This method returns the class instance.
*
* @return the class instance
*/
public static CoAPProxy getInstance() {
return proxy;
}
/**
* Obtains the context associated to the specific resource path and sends
* a specific request message to the CoAP Server.
*
* @param RDPath the resource path inside the RD
* @param request the request message
* @return the response message
*/
public static CoapResponse callMethod(final String RDPath, final Request request) {
// take the node context from the RD (the path is unique within the RD)
String context = ResourceDirectory.getInstance().getContextFromResource(RDPath);
// take the resource path within the CoAP Server from the RD
String path = ResourceDirectory.getInstance().getResourcePath(RDPath);
CoapClient client = new CoapClient(context+path);
CoapResponse response = client.advanced(request);
if (response==null) {
LOGGER.warning("No response received.");
}
return response;
}
public void run() {
// TODO Auto-generated method stub
}
}
|
package cn.cerc.mis.core;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Map;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;
import com.google.gson.Gson;
import cn.cerc.db.core.ISession;
import cn.cerc.db.core.LanguageResource;
import cn.cerc.db.core.Utils;
import cn.cerc.db.redis.JedisFactory;
import cn.cerc.db.redis.RedisRecord;
import cn.cerc.mis.other.MemoryBuffer;
import redis.clients.jedis.Jedis;
@Component
@Scope(WebApplicationContext.SCOPE_REQUEST)
//@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class AppClient implements Serializable {
// private static final Logger log = LoggerFactory.getLogger(AppClient.class);
private static final long serialVersionUID = -3593077761901636920L;
public static final int Version = 1;
public static final String COOKIE_ROOT_PATH = "/";
public static final String phone = "phone";
public static final String android = "android";
public static final String iphone = "iphone";
public static final String wechat = "weixin";
public static final String pad = "pad";
public static final String pc = "pc";
public static final String kanban = "kanban";
public static final String ee = "ee";
private final HttpServletRequest request;
private final HttpServletResponse response;
private String cookieId = "";
private final String key;
private String token;
private String device;
private String deviceId;
private String language;
public AppClient(HttpServletRequest request, HttpServletResponse response) {
this.request = request;
this.response = response;
Cookie[] cookies = this.request.getCookies();
if (cookies != null) {
for (Cookie cookie : request.getCookies()) {
if (cookie.getName().equals(ISession.COOKIE_ID)) {
this.cookieId = cookie.getValue();
break;
}
}
}
if (Utils.isEmpty(this.cookieId)) {
this.cookieId = Utils.getGuid();
if (response != null) {
Cookie cookie = new Cookie(ISession.COOKIE_ID, cookieId);
cookie.setPath(COOKIE_ROOT_PATH);
cookie.setHttpOnly(true);
this.response.addCookie(cookie);
}
}
this.key = MemoryBuffer.buildObjectKey(AppClient.class, this.cookieId, AppClient.Version);
try (Jedis redis = JedisFactory.getJedis()) {
this.device = request.getParameter(ISession.CLIENT_DEVICE);
if (!Utils.isEmpty(device))
redis.hset(key, ISession.CLIENT_DEVICE, device);
else {
this.device = redis.hget(key, ISession.CLIENT_DEVICE);
if (Utils.isEmpty(device)) {
device = pc;
redis.hset(key, ISession.CLIENT_DEVICE, device);
}
}
this.deviceId = request.getParameter(ISession.CLIENT_ID);
if (!Utils.isEmpty(deviceId))
redis.hset(key, ISession.CLIENT_ID, deviceId);
else {
this.deviceId = redis.hget(key, ISession.CLIENT_ID);
if (Utils.isEmpty(deviceId)) {
if (cookies != null) {
for (Cookie cookie : request.getCookies()) {
if (cookie.getName().equals(ISession.CLIENT_ID)) {
this.deviceId = cookie.getValue();
break;
}
}
}
}
// if (Utils.isEmpty(deviceId)) {
// deviceId = Utils.getGuid();
// redis.hset(key, ISession.CLIENT_ID, deviceId);
// if (response != null) {
// Cookie cookie = new Cookie(ISession.CLIENT_ID, deviceId);
// cookie.setPath(COOKIE_ROOT_PATH);
// cookie.setHttpOnly(true);
// this.response.addCookie(cookie);
}
this.language = request.getParameter(ISession.LANGUAGE_ID);
if (!Utils.isEmpty(language))
redis.hset(key, ISession.LANGUAGE_ID, language);
else {
this.language = redis.hget(key, ISession.LANGUAGE_ID);
if (Utils.isEmpty(language)) {
language = LanguageResource.appLanguage;
redis.hset(key, ISession.LANGUAGE_ID, language);
}
}
this.token = request.getParameter(ISession.TOKEN);
if (!Utils.isEmpty(token))
redis.hset(key, ISession.TOKEN, token);
else
this.token = redis.hget(key, ISession.TOKEN);
redis.expire(key, RedisRecord.TIMEOUT);
}
}
/**
* cookie id
*/
public String getCookieId() {
return this.cookieId;
}
public String getToken() {
return token;
}
public void delete(String field) {
try (Jedis redis = JedisFactory.getJedis()) {
redis.hdel(key, field);
}
}
public String getId() {
return this.deviceId;
}
public void setId(String value) {
this.deviceId = value == null ? "" : value;
request.setAttribute(ISession.CLIENT_ID, deviceId);
try (Jedis redis = JedisFactory.getJedis()) {
redis.hset(key, ISession.CLIENT_ID, deviceId);
}
if (value != null && value.length() == 28)// openid
setDevice(phone);
}
public String getDevice() {
return Utils.isEmpty(device) ? pc : device;
}
public void setDevice(String value) {
this.device = Utils.isEmpty(value) ? pc : value;
request.setAttribute(ISession.CLIENT_DEVICE, device);
try (Jedis redis = JedisFactory.getJedis()) {
redis.hset(key, ISession.CLIENT_DEVICE, device);
}
}
public String getLanguage() {
return this.language;
}
public boolean isPhone() {
return phone.equals(getDevice()) || android.equals(getDevice()) || iphone.equals(getDevice())
|| wechat.equals(getDevice());
}
public boolean isKanban() {
return kanban.equals(getDevice());
}
/**
* IPrequest.getRemoteAddr() IP
* <p>
* x-forwarded-for IPunknownIPIP
* <p>
* x-forwarded-for192.168.1.110, 192.168.1.120, 192.168.1.130, 192.168.1.100
* <p>
* IP 192.168.1.110
*
* @param request HttpServletRequest
*
* @return IP
*/
public static String getClientIP(HttpServletRequest request) {
if (request == null)
return "";
try {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
ip = request.getHeader("Proxy-Client-IP");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
ip = request.getHeader("WL-Proxy-Client-IP");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
ip = request.getHeader("HTTP_CLIENT_IP");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
ip = request.getRemoteAddr();
if ("0:0:0:0:0:0:0:1".equals(ip))
ip = "0.0.0.0";
String[] arr = ip.split(",");
ip = Arrays.stream(arr).findFirst().orElse("").trim();
return ip;
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
@Override
public String toString() {
Map<String, String> items;
try (Jedis redis = JedisFactory.getJedis()) {
items = redis.hgetAll(key);
}
return new Gson().toJson(items);
}
}
|
package javax.jmdns.impl;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;
import javax.jmdns.impl.constants.DNSConstants;
import javax.jmdns.impl.constants.DNSRecordClass;
/**
* An outgoing DNS message.
*
* @author Arthur van Hoff, Rick Blair, Werner Randelshofer
*/
public final class DNSOutgoing extends DNSMessage {
public static class MessageOutputStream extends ByteArrayOutputStream {
private final DNSOutgoing _out;
private final int _offset;
MessageOutputStream(int size, DNSOutgoing out) {
this(size, out, 0);
}
MessageOutputStream(int size, DNSOutgoing out, int offset) {
super(size);
_out = out;
_offset = offset;
}
void writeByte(int value) {
this.write(value & 0xFF);
}
void writeBytes(String str, int off, int len) {
for (int i = 0; i < len; i++) {
writeByte(str.charAt(off + i));
}
}
void writeBytes(byte data[]) {
if (data != null) {
writeBytes(data, 0, data.length);
}
}
void writeBytes(byte data[], int off, int len) {
for (int i = 0; i < len; i++) {
writeByte(data[off + i]);
}
}
void writeShort(int value) {
writeByte(value >> 8);
writeByte(value);
}
void writeInt(int value) {
writeShort(value >> 16);
writeShort(value);
}
void writeUTF(String str, int off, int len) {
// compute utf length
int utflen = 0;
for (int i = 0; i < len; i++) {
int ch = str.charAt(off + i);
if ((ch >= 0x0001) && (ch <= 0x007F)) {
utflen += 1;
} else {
if (ch > 0x07FF) {
utflen += 3;
} else {
utflen += 2;
}
}
}
// write utf length
writeByte(utflen);
// write utf data
for (int i = 0; i < len; i++) {
int ch = str.charAt(off + i);
if ((ch >= 0x0001) && (ch <= 0x007F)) {
writeByte(ch);
} else {
if (ch > 0x07FF) {
writeByte(0xE0 | ((ch >> 12) & 0x0F));
writeByte(0x80 | ((ch >> 6) & 0x3F));
writeByte(0x80 | ((ch >> 0) & 0x3F));
} else {
writeByte(0xC0 | ((ch >> 6) & 0x1F));
writeByte(0x80 | ((ch >> 0) & 0x3F));
}
}
}
}
void writeName(String name) {
writeName(name, true);
}
void writeName(String name, boolean useCompression) {
String aName = name;
while (true) {
int n = aName.indexOf('.');
if (n < 0) {
n = aName.length();
}
if (n <= 0) {
writeByte(0);
return;
}
String label = aName.substring(0, n);
if (useCompression && USE_DOMAIN_NAME_COMPRESSION) {
Integer offset = _out._names.get(aName);
if (offset != null) {
int val = offset.intValue();
writeByte((val >> 8) | 0xC0);
writeByte(val & 0xFF);
return;
}
_out._names.put(aName, Integer.valueOf(this.size() + _offset));
writeUTF(label, 0, label.length());
} else {
writeUTF(label, 0, label.length());
}
aName = aName.substring(n);
if (aName.startsWith(".")) {
aName = aName.substring(1);
}
}
}
void writeQuestion(DNSQuestion question) {
writeName(question.getName());
writeShort(question.getRecordType().indexValue());
writeShort(question.getRecordClass().indexValue());
}
void writeRecord(DNSRecord rec, long now) {
writeName(rec.getName());
writeShort(rec.getRecordType().indexValue());
writeShort(rec.getRecordClass().indexValue() | ((rec.isUnique() && _out.isMulticast()) ? DNSRecordClass.CLASS_UNIQUE : 0));
writeInt((now == 0) ? rec.getTTL() : rec.getRemainingTTL(now));
// We need to take into account the 2 size bytes
MessageOutputStream record = new MessageOutputStream(512, _out, _offset + this.size() + 2);
rec.write(record);
byte[] byteArray = record.toByteArray();
writeShort(byteArray.length);
write(byteArray, 0, byteArray.length);
}
}
/**
* This can be used to turn off domain name compression. This was helpful for tracking problems interacting with other mdns implementations.
*/
public static boolean USE_DOMAIN_NAME_COMPRESSION = true;
Map<String, Integer> _names;
private int _maxUDPPayload;
private final MessageOutputStream _questionsBytes;
private final MessageOutputStream _answersBytes;
private final MessageOutputStream _authoritativeAnswersBytes;
private final MessageOutputStream _additionalsAnswersBytes;
private final static int HEADER_SIZE = 12;
private InetSocketAddress _destination;
/**
* Create an outgoing multicast query or response.
*
* @param flags
*/
public DNSOutgoing(int flags) {
this(flags, true, DNSConstants.MAX_MSG_TYPICAL);
}
/**
* Create an outgoing query or response.
*
* @param flags
* @param multicast
*/
public DNSOutgoing(int flags, boolean multicast) {
this(flags, multicast, DNSConstants.MAX_MSG_TYPICAL);
}
/**
* Create an outgoing query or response.
*
* @param flags
* @param multicast
* @param senderUDPPayload
* The sender's UDP payload size is the number of bytes of the largest UDP payload that can be reassembled and delivered in the sender's network stack.
*/
public DNSOutgoing(int flags, boolean multicast, int senderUDPPayload) {
super(flags, 0, multicast);
_names = new HashMap<String, Integer>();
_maxUDPPayload = (senderUDPPayload > 0 ? senderUDPPayload : DNSConstants.MAX_MSG_TYPICAL);
_questionsBytes = new MessageOutputStream(senderUDPPayload, this);
_answersBytes = new MessageOutputStream(senderUDPPayload, this);
_authoritativeAnswersBytes = new MessageOutputStream(senderUDPPayload, this);
_additionalsAnswersBytes = new MessageOutputStream(senderUDPPayload, this);
}
/**
* Get the forced destination address if a specific one was set.
*
* @return a forced destination address or null if no address is forced.
*/
public InetSocketAddress getDestination() {
return _destination;
}
/**
* Force a specific destination address if packet is sent.
*
* @param destination
* Set a destination address a packet should be sent to (instead the default one). You could use null to unset the forced destination.
*/
public void setDestination(InetSocketAddress destination) {
_destination = destination;
}
/**
* Return the number of byte available in the message.
*
* @return available space
*/
public int availableSpace() {
return _maxUDPPayload - HEADER_SIZE - _questionsBytes.size() - _answersBytes.size() - _authoritativeAnswersBytes.size() - _additionalsAnswersBytes.size();
}
/**
* Add a question to the message.
*
* @param rec
* @exception IOException
*/
public void addQuestion(DNSQuestion rec) throws IOException {
MessageOutputStream record = new MessageOutputStream(512, this);
record.writeQuestion(rec);
byte[] byteArray = record.toByteArray();
record.close();
if (byteArray.length < this.availableSpace()) {
_questions.add(rec);
_questionsBytes.write(byteArray, 0, byteArray.length);
} else {
throw new IOException("message full");
}
}
/**
* Add an answer if it is not suppressed.
*
* @param in
* @param rec
* @exception IOException
*/
public void addAnswer(DNSIncoming in, DNSRecord rec) throws IOException {
if ((in == null) || !rec.suppressedBy(in)) {
this.addAnswer(rec, 0);
}
}
/**
* Add an answer to the message.
*
* @param rec
* @param now
* @exception IOException
*/
public void addAnswer(DNSRecord rec, long now) throws IOException {
if (rec != null) {
if ((now == 0) || !rec.isExpired(now)) {
MessageOutputStream record = new MessageOutputStream(512, this);
record.writeRecord(rec, now);
byte[] byteArray = record.toByteArray();
record.close();
if (byteArray.length < this.availableSpace()) {
_answers.add(rec);
_answersBytes.write(byteArray, 0, byteArray.length);
} else {
throw new IOException("message full");
}
}
}
}
/**
* Add an authoritative answer to the message.
*
* @param rec
* @exception IOException
*/
public void addAuthorativeAnswer(DNSRecord rec) throws IOException {
MessageOutputStream record = new MessageOutputStream(512, this);
record.writeRecord(rec, 0);
byte[] byteArray = record.toByteArray();
record.close();
if (byteArray.length < this.availableSpace()) {
_authoritativeAnswers.add(rec);
_authoritativeAnswersBytes.write(byteArray, 0, byteArray.length);
} else {
throw new IOException("message full");
}
}
/**
* Add an additional answer to the record. Omit if there is no room.
*
* @param in
* @param rec
* @exception IOException
*/
public void addAdditionalAnswer(DNSIncoming in, DNSRecord rec) throws IOException {
MessageOutputStream record = new MessageOutputStream(512, this);
record.writeRecord(rec, 0);
byte[] byteArray = record.toByteArray();
record.close();
if (byteArray.length < this.availableSpace()) {
_additionals.add(rec);
_additionalsAnswersBytes.write(byteArray, 0, byteArray.length);
} else {
throw new IOException("message full");
}
}
/**
* Builds the final message buffer to be send and returns it.
*
* @return bytes to send.
*/
public byte[] data() {
long now = System.currentTimeMillis(); // System.currentTimeMillis()
_names.clear();
MessageOutputStream message = new MessageOutputStream(_maxUDPPayload, this);
message.writeShort(_multicast ? 0 : this.getId());
message.writeShort(this.getFlags());
message.writeShort(this.getNumberOfQuestions());
message.writeShort(this.getNumberOfAnswers());
message.writeShort(this.getNumberOfAuthorities());
message.writeShort(this.getNumberOfAdditionals());
for (DNSQuestion question : _questions) {
message.writeQuestion(question);
}
for (DNSRecord record : _answers) {
message.writeRecord(record, now);
}
for (DNSRecord record : _authoritativeAnswers) {
message.writeRecord(record, now);
}
for (DNSRecord record : _additionals) {
message.writeRecord(record, now);
}
byte[] result = message.toByteArray();
try {
message.close();
} catch (IOException exception) {}
return result;
}
/**
* Debugging.
*/
String print(boolean dump) {
StringBuilder buf = new StringBuilder();
buf.append(this.print());
if (dump) {
buf.append(this.print(this.data()));
}
return buf.toString();
}
@Override
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append(isQuery() ? "dns[query:" : "dns[response:");
buf.append(" id=0x");
buf.append(Integer.toHexString(this.getId()));
if (this.getFlags() != 0) {
buf.append(", flags=0x");
buf.append(Integer.toHexString(this.getFlags()));
if (this.isResponse()) {
buf.append(":r");
}
if (this.isAuthoritativeAnswer()) {
buf.append(":aa");
}
if (this.isTruncated()) {
buf.append(":tc");
}
}
if (this.getNumberOfQuestions() > 0) {
buf.append(", questions=");
buf.append(this.getNumberOfQuestions());
}
if (this.getNumberOfAnswers() > 0) {
buf.append(", answers=");
buf.append(this.getNumberOfAnswers());
}
if (this.getNumberOfAuthorities() > 0) {
buf.append(", authorities=");
buf.append(this.getNumberOfAuthorities());
}
if (this.getNumberOfAdditionals() > 0) {
buf.append(", additionals=");
buf.append(this.getNumberOfAdditionals());
}
if (this.getNumberOfQuestions() > 0) {
buf.append("\nquestions:");
for (DNSQuestion question : _questions) {
buf.append("\n\t");
buf.append(question);
}
}
if (this.getNumberOfAnswers() > 0) {
buf.append("\nanswers:");
for (DNSRecord record : _answers) {
buf.append("\n\t");
buf.append(record);
}
}
if (this.getNumberOfAuthorities() > 0) {
buf.append("\nauthorities:");
for (DNSRecord record : _authoritativeAnswers) {
buf.append("\n\t");
buf.append(record);
}
}
if (this.getNumberOfAdditionals() > 0) {
buf.append("\nadditionals:");
for (DNSRecord record : _additionals) {
buf.append("\n\t");
buf.append(record);
}
}
buf.append("\nnames=");
buf.append(_names);
buf.append("]");
return buf.toString();
}
/**
* @return the maxUDPPayload
*/
public int getMaxUDPPayload() {
return this._maxUDPPayload;
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.akiban.cserver;
import java.io.DataInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.akiban.ais.ddl.DDLSource;
import com.akiban.ais.io.MySQLSource;
import com.akiban.ais.io.Reader;
import com.akiban.ais.message.AISExecutionContext;
import com.akiban.ais.message.AISRequest;
import com.akiban.ais.message.AISResponse;
import com.akiban.ais.model.AkibaInformationSchema;
import com.akiban.cserver.message.ShutdownRequest;
import com.akiban.cserver.message.ShutdownResponse;
import com.akiban.cserver.store.PersistitStore;
import com.akiban.cserver.store.Store;
import com.akiban.message.AkibaConnection;
import com.akiban.message.ErrorResponse;
import com.akiban.message.ExecutionContext;
import com.akiban.message.Message;
import com.akiban.message.MessageRegistry;
import com.akiban.network.AkibaNetworkHandler;
import com.akiban.network.CommEventNotifier;
import com.akiban.network.NetworkHandlerFactory;
/**
*
* @author peter
*/
public class CServer {
private static final Log LOG = LogFactory.getLog(CServer.class.getName());
private static final String AIS_DDL_NAME = "akiba_information_schema.ddl";
/**
* Config property name and default for the port on which the CServer will
* listen for requests.
*/
private static final String P_CSERVER_HOST = "cserver.host|localhost";
/**
* Config property name and default for the port on which the CServer will
* listen for requests.
*/
private static final String P_CSERVER_PORT = "cserver.port|8080";
/**
* Config property name and default for the MySQL server host from which
* CServer will obtain the AIS.
*/
private static final String P_AISHOST = "mysql.host|localhost";
/**
* Config property port and default for the MySQL server host from which
* Cserver will obtain the AIS.
*/
private static final String P_AISPORT = "mysql.port|3306";
/**
* Config property name and default for the MySQL server host from which
* CServer will obtain the AIS.
*/
private static final String P_AISUSER = "mysql.username|akiba";
/**
* Config property name and default for the MySQL server host from which
* CServer will obtain the AIS.
*/
private static final String P_AISPASSWORD = "mysql.password|akibaDB";
private final RowDefCache rowDefCache = new RowDefCache();
private final CServerConfig config = new CServerConfig();
private final Store store = new PersistitStore(config, rowDefCache);
private AkibaInformationSchema ais0;
private AkibaInformationSchema ais;
private volatile boolean stopped = false;
private Map<Integer, Thread> threadMap = new TreeMap<Integer, Thread>();
public void start() throws Exception {
MessageRegistry.initialize();
MessageRegistry.only().registerModule("com.akiban.cserver");
MessageRegistry.only().registerModule("com.akiban.ais");
MessageRegistry.only().registerModule("com.akiban.message");
ChannelNotifier callback = new ChannelNotifier();
NetworkHandlerFactory.initializeNetwork(property(P_CSERVER_HOST),
property(P_CSERVER_PORT), (CommEventNotifier) callback);
loadAis0();
store.startUp();
}
public void stop() throws Exception {
stopped = true;
final List<Thread> copy;
synchronized (threadMap) {
copy = new ArrayList<Thread>(threadMap.values());
}
// for now I think this is the only way to make these threads
// bail from their reads.
for (final Thread thread : copy) {
thread.interrupt();
}
store.shutDown();
NetworkHandlerFactory.closeNetwork();
}
public class ChannelNotifier implements CommEventNotifier {
@Override
public void onConnect(AkibaNetworkHandler handler) {
if (LOG.isInfoEnabled()) {
LOG.info("Connection #" + handler.getId() + " created");
}
final String threadName = "CServer_" + handler.getId();
final Thread thread = new Thread(new CServerRunnable(
AkibaConnection.createConnection(handler)), threadName);
thread.setDaemon(true);
thread.start();
synchronized (threadMap) {
threadMap.put(handler.getId(), thread);
}
}
@Override
public void onDisconnect(AkibaNetworkHandler handler) {
final Thread thread = threadMap.remove(handler.getId());
if (thread != null && thread.isAlive()) {
thread.interrupt();
if (LOG.isInfoEnabled()) {
LOG.info("Connection #" + handler.getId() + " ended");
}
} else {
LOG.error("CServer thread for connection #" + handler.getId()
+ " was missing or dead");
}
}
}
public class CServerContext implements ExecutionContext,
AISExecutionContext, CServerShutdownExecutionContext {
public Store getStore() {
return store;
}
@Override
public void executeRequest(AkibaConnection connection,
AISRequest request) throws Exception {
acquireAIS();
AISResponse aisResponse = new AISResponse(ais);
connection.send(aisResponse);
}
@Override
public void executeResponse(AkibaConnection connection,
AISResponse response) throws Exception {
ais = response.ais();
installAIS();
}
@Override
public void executeRequest(AkibaConnection connection,
ShutdownRequest request) throws Exception {
if (LOG.isInfoEnabled()) {
LOG.info("CServer stopping due to ShutdownRequest");
}
stop();
ShutdownResponse response = new ShutdownResponse();
connection.send(response);
}
}
/**
* A Runnable that reads Network messages, acts on them and returns results.
*
* @author peter
*
*/
private class CServerRunnable implements Runnable {
private final AkibaConnection connection;
private final ExecutionContext context = new CServerContext();
private int requestCounter;
public CServerRunnable(final AkibaConnection connection) {
this.connection = connection;
}
public void run() {
Message message = null;
while (!stopped) {
try {
message = connection.receive();
if (LOG.isTraceEnabled()) {
LOG.trace("Serving message " + message);
}
message.execute(connection, context);
requestCounter++;
} catch (InterruptedException e) {
if (LOG.isInfoEnabled()) {
LOG.info("Thread " + Thread.currentThread().getName()
+ (stopped ? " stopped" : " interrupted"));
}
} catch (Exception e) {
if (LOG.isErrorEnabled()) {
LOG.error("Unexpected error on " + message, e);
}
if (message != null) {
try {
connection.send(new ErrorResponse(e));
} catch (Exception f) {
LOG.error("Caught " + f.getClass()
+ " while sending error response to "
+ message + ": " + f.getMessage(), f);
}
}
}
}
}
}
public RowDefCache getRowDefCache() {
return rowDefCache;
}
/**
* Acquire an AkibaInformationSchema from MySQL and install it into the
* local RowDefCache.
*
* This method always refreshes the locally cached AkibaInformationSchema to
* support schema modifications at the MySQL head.
*
* @return an AkibaInformationSchema
* @throws Exception
*/
public void acquireAIS() throws Exception {
readAISFromMySQL();
installAIS();
}
private void readAISFromMySQL() throws Exception {
for (;;) {
try {
if (LOG.isInfoEnabled()) {
LOG.info(String.format("Attempting to load AIS from %s",
property(P_AISHOST)));
}
ais = new Reader(new MySQLSource(property(P_AISHOST),
property(P_AISPORT), property(P_AISUSER),
property(P_AISPASSWORD))).load();
break;
} catch (com.mysql.jdbc.exceptions.jdbc4.CommunicationsException e) {
try {
Thread.sleep(30000L);
} catch (InterruptedException ie) {
break;
}
}
}
}
private void installAIS() {
LOG.info("Installing AIS in ChunkServer");
rowDefCache.clear();
rowDefCache.setAIS(ais0);
rowDefCache.setAIS(ais);
}
/**
* Loads the built-in primordial table definitions for the akiba_information_schema
* tables.
* @throws Exception
*/
private void loadAis0() throws Exception {
final DataInputStream stream = new DataInputStream(getClass()
.getClassLoader().getResourceAsStream(AIS_DDL_NAME));
// TODO: ugly, but gets the job done
final StringBuilder sb = new StringBuilder();
for (;;) {
final String line = stream.readLine();
if (line == null) {
break;
}
sb.append(line);
sb.append("\n");
}
this.ais0 = (new DDLSource()).buildAISFromString(sb.toString());
rowDefCache.setAIS(ais0);
}
/**
* @param args
* the command line arguments
*/
public static void main(String[] args) throws Exception {
final CServer server = new CServer();
server.config.load();
if (server.config.getException() != null) {
LOG.fatal("CServer configuration failed");
return;
}
server.start();
// HAZEL: MySQL Conference Demo 4/2010: MySQL/Drizzle/Memcache to Chunk Server
/*
com.thimbleware.jmemcached.protocol.MemcachedCommandHandler.registerCallback(
new com.thimbleware.jmemcached.protocol.MemcachedCommandHandler.Callback()
{
public byte[] get(byte[] key)
{
byte[] result = null;
String request = new String(key);
String[] tokens = request.split(":");
if (tokens.length == 4)
{
String schema = tokens[0];
String table = tokens[1];
String colkey = tokens[2];
String colval = tokens[3];
try
{
List<RowData> list = null;
// list = store.fetchRows(schema, table, colkey, colval, colval);
java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream();
java.io.ObjectOutputStream out = new java.io.ObjectOutputStream(bos);
out.writeObject(list);
out.close();
result = bos.toByteArray();
}
catch (Exception e)
{
result = new String("read error: " + e.getMessage()).getBytes();
}
}
else
{
result = new String("invalid key: " + request).getBytes();
}
return result;
}
});
com.thimbleware.jmemcached.Main.main(new String[0]);
*/
}
public String property(final String key) {
return config.property(key);
}
public String property(final String key, final String dflt) {
return config.property(key, dflt);
}
}
|
package com.quickblox.q_municate.ui.mediacall;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.quickblox.q_municate.App;
import com.quickblox.q_municate.R;
import com.quickblox.q_municate.ui.base.BaseLogeableActivity;
import com.quickblox.q_municate.ui.media.MediaPlayerManager;
import com.quickblox.q_municate.ui.videocall.VideoCallFragment;
import com.quickblox.q_municate.ui.voicecall.VoiceCallFragment;
import com.quickblox.q_municate_core.core.exceptions.QBRTCSessionIsAbsentException;
import com.quickblox.q_municate_core.models.AppSession;
import com.quickblox.q_municate_core.models.User;
import com.quickblox.q_municate_core.qb.commands.push.QBSendPushCommand;
import com.quickblox.q_municate_core.qb.helpers.QBVideoChatHelper;
import com.quickblox.q_municate_core.qb.helpers.call.VideoChatHelperListener;
import com.quickblox.q_municate_core.service.QBService;
import com.quickblox.q_municate_core.service.QBServiceConsts;
import com.quickblox.q_municate_core.utils.ConstsCore;
import com.quickblox.videochat.webrtc.QBRTCClient;
import com.quickblox.videochat.webrtc.QBRTCConfig;
import com.quickblox.videochat.webrtc.QBRTCTypes;
import com.quickblox.videochat.webrtc.view.QBGLVideoView;
import com.quickblox.videochat.webrtc.view.QBRTCVideoTrack;
import com.quickblox.videochat.webrtc.view.VideoCallBacks;
import org.webrtc.VideoRenderer;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* Receives callbacks from {@link QBVideoChatHelper}
*
* Methods not related with UI call on {@link QBVideoChatHelper} instance.
*
* There are few {@link Map} which store tasks:
* <ul>
* <li>{@link #callTasksMap} - it's just </li>
* <li>{@link #waitingTasksMap}} - it's map of waiting client readiness tasks</li>
* </ul>
*
* When {@link CallActivity#onClientReady()} method called all {@link #waitingTasksMap}} will be executed.
*
*
*/
public class CallActivity extends BaseLogeableActivity implements IncomingCallFragmentInterface, OutgoingCallFragmentInterface, VideoChatHelperListener {
private static final String TAG = CallActivity.class.getSimpleName();
private static final String CALL_INTEGRATION = "CALL_INTEGRATION";
// Call tasks identificator
private static final String START_CALL_TASK = "start_call_task";
private static final String REJECT_CALL_TASK = "reject_call_task";
private static final String ACCEPT_CALL_TASK = "accept_call_task";
private static final String HANG_UP_CALL_TASK = "hang_up_call_task";
private static final String ON_MIC_TASK = "on_mic_task";
private static final String OFF_MIC_TASK = "off_mic_task";
private static final String ON_CAM_TASK = "on_cam_task";
private static final String OFF_CAM_TASK = "off_cam_task";
private static final String SWITCH_CAM_TASK = "switch_cam_task";
private static final String SWITCH_SPEACKER_TASK = "switch_speaker_task";
/**
* Current call opponent
*/
private User opponent;
/**
* Call direction type. Could be INCOMMING or OUTGOING
*/
private ConstsCore.CALL_DIRECTION_TYPE call_direction_type;
/**
* Call type. Could be AUDIO or VIDEO
*/
private QBRTCTypes.QBConferenceType call_type;
/**
* Executes all non UI call logic, throws callbacks related with call state, video tracks and session existence.
*/
private QBVideoChatHelper videoChatHelper;
/**
* Map of all video call tasks
*/
private HashMap<String, Runnable> callTasksMap;
/**
* Queue of called tasks
*/
private Queue<Runnable> callTasksQueue;
/**
* Map of waiting tasks
*/
private Map<String, Runnable> waitingTasksMap;
// Thre fields for closing activity if user didn't response in a set period.
private Runnable closeIncomeCallTimerTask;
private ScheduledThreadPoolExecutor singleTheadScheduledExecutor;
private ScheduledFuture<?> closeIncomeCallFutureTask;
/**
* Caller video view
*/
private QBGLVideoView localVideoView;
/**
* Callee video view
*/
private QBGLVideoView remoteVideoView;
/**
* Map of opponents video views
*/
private Map<VideoTracks, Set<Runnable>> videoTracksSetEnumMap;
private MediaPlayerManager mediaPlayer;
private Map<String, String> userInfo = new HashMap<String, String>();
private boolean isCleintReadyAccept;
/**
* Starts activity with params in bundle
* @param context - application context
* @param friend - call opponent
* @param callType - call type (AUDIO|VIDEO)
*/
public static void start(Context context, User friend, QBRTCTypes.QBConferenceType callType) {
Log.d(CALL_INTEGRATION, "CallActivity. START STATIC CALL ACTIVITY");
Log.i(TAG, "Friend.isOnline() = " + friend.isOnline());
Intent intent = new Intent(context, CallActivity.class);
intent.putExtra(ConstsCore.EXTRA_FRIEND, friend);
intent.putExtra(ConstsCore.CALL_DIRECTION_TYPE_EXTRA, ConstsCore.CALL_DIRECTION_TYPE.OUTGOING);
intent.putExtra(ConstsCore.CALL_TYPE_EXTRA, callType);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
context.startActivity(intent);
}
/**
* Start call task
*/
public void startCall() {
if (waitingTasksMap != null && !waitingTasksMap.containsKey(REJECT_CALL_TASK)) {
Log.d(CALL_INTEGRATION, "CallActivity. startCall() executed");
Runnable callTask = callTasksMap.get(START_CALL_TASK);
executeCallTask(callTask);
}
}
/**
* Start call accepting task
*/
@Override
public void acceptCallClick() {
Log.d(CALL_INTEGRATION, "CallActivity. acceptCall() executed");
cancelPlayer();
showOutgoingFragment();
if (isCleintReadyAccept) {
Runnable acceptTask = callTasksMap.get(ACCEPT_CALL_TASK);
executeCallTask(acceptTask);
} else {
waitingTasksMap.put(ACCEPT_CALL_TASK, callTasksMap.get(ACCEPT_CALL_TASK));
}
}
/**
* Start call rejecting task
*/
@Override
public void rejectCallClick() {
Log.d(CALL_INTEGRATION, "CallActivity. rejectCall() executed");
cancelPlayer();
if (isCleintReadyAccept) {
Runnable rejectTask = callTasksMap.get(REJECT_CALL_TASK);
executeCallTask(rejectTask);
} else {
waitingTasksMap.put(REJECT_CALL_TASK, callTasksMap.get(REJECT_CALL_TASK));
}
}
/**
* Start turn on mic task
*/
@Override
public void onMic() {
Log.d(CALL_INTEGRATION, "CallActivity. onMic() executed");
Runnable onMicTask = callTasksMap.get(ON_MIC_TASK);
executeCallTask(onMicTask);
}
/**
* Start turn off mic task
*/
@Override
public void offMic() {
Log.d(CALL_INTEGRATION, "CallActivity. offMic() executed");
Runnable offMicTask = callTasksMap.get(OFF_MIC_TASK);
executeCallTask(offMicTask);
}
/**
* Start turn on cam task
*/
@Override
public void onCam() {
Log.d(CALL_INTEGRATION, "CallActivity. onCam() executed");
Runnable onCamTask = callTasksMap.get(ON_CAM_TASK);
executeCallTask(onCamTask);
}
/**
* Start turn off cam task
*/
@Override
public void offCam() {
Log.d(CALL_INTEGRATION, "CallActivity. offCam() executed");
Runnable offCamTask = callTasksMap.get(OFF_CAM_TASK);
executeCallTask(offCamTask);
}
/**
* Start cam switching task
*/
@Override
public void switchCam() {
Log.d(CALL_INTEGRATION, "CallActivity. switchCam() executed");
Runnable switchCamTask = callTasksMap.get(SWITCH_CAM_TASK);
executeCallTask(switchCamTask);
}
/**
* Start cam switching task
*/
@Override
public void switchSpeaker() {
Log.d(CALL_INTEGRATION, "CallActivity. switchSpeaker() executed");
Runnable switchSpeakerTask = callTasksMap.get(SWITCH_SPEACKER_TASK);
executeCallTask(switchSpeakerTask);
}
/**
* Start hang up task
*/
@Override
public void hangUpClick() {
Log.d(CALL_INTEGRATION, "CallActivity. hungUp() executed");
Runnable hungUpTask = callTasksMap.get(HANG_UP_CALL_TASK);
executeCallTask(hungUpTask);
}
/**
* Start local straming task
*/
@Override
public void onLocalVideoViewCreated() {
for (Runnable runnable : videoTracksSetEnumMap.get(VideoTracks.LOCAL_VIDEO_TRACK)) {
executeCallTask(runnable);
}
}
/**
* Start remote streaming task
*/
@Override
public void onRemoteVideoViewCreated() {
for (Runnable runnable : videoTracksSetEnumMap.get(VideoTracks.REMOTE_VIDEO_TRACK)) {
executeCallTask(runnable);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(CALL_INTEGRATION, "onCreate call activity" + this);
Log.d(CALL_INTEGRATION, "CallActivity. QBRTCClient start listening calls");
QBRTCClient.getInstance().prepareToProcessCalls(this);
if(getIntent().getExtras() != null) {
parseIntentExtras(getIntent().getExtras());
}
canPerformLogout.set(false);
setContentView(R.layout.activity_main_call);
actionBar.hide();
mediaPlayer = App.getInstance().getMediaPlayer();
// Queue for storing tasks which was called while activity doesn't have link on VideoChatHelper
callTasksQueue = new LinkedList<>();
// Prepare video tracks sets for storing in map in relation with video track type
videoTracksSetEnumMap = new EnumMap<>(VideoTracks.class);
for (VideoTracks videoTracks : VideoTracks.values()){
videoTracksSetEnumMap.put(videoTracks, new HashSet<Runnable>());
}
// Map of task which called before RTCClient was redy to processing calls
waitingTasksMap = new TreeMap<>();
// Init map of allowed call's tasks
initCallTasksMap();
if(call_direction_type == ConstsCore.CALL_DIRECTION_TYPE.OUTGOING){
startCall();
}
addAction(QBServiceConsts.SEND_PUSH_MESSAGES_FAIL_ACTION, failAction);
}
private void parseIntentExtras(Bundle extras) {
call_direction_type = (ConstsCore.CALL_DIRECTION_TYPE) extras.getSerializable(
ConstsCore.CALL_DIRECTION_TYPE_EXTRA);
call_type = (QBRTCTypes.QBConferenceType) extras.getSerializable(ConstsCore.CALL_TYPE_EXTRA);
// sessionId = extras.getString(ConstsCore.SESSION_ID, "");
opponent = (User) extras.getSerializable(ConstsCore.EXTRA_FRIEND);
Log.i(TAG, "opponentId=" + opponent);
}
private void initCallTasksMap() {
Log.d(CALL_INTEGRATION, "CallActivity. Set up tasks map");
callTasksMap = new HashMap<>();
// Main tasks
callTasksMap.put(START_CALL_TASK, initStartCallTask());
callTasksMap.put(ACCEPT_CALL_TASK, initAcceptCallTask());
callTasksMap.put(REJECT_CALL_TASK, initRejectCallTask());
callTasksMap.put(HANG_UP_CALL_TASK, initHangUpCallTask());
// Mic tasks
callTasksMap.put(ON_MIC_TASK, initMicOnTask());
callTasksMap.put(OFF_MIC_TASK, initMicOffTask());
// Cam tasks
callTasksMap.put(ON_CAM_TASK, initCamOnTask());
callTasksMap.put(OFF_CAM_TASK, initCamOffTask());
// Switch cam input and speaker output
callTasksMap.put(SWITCH_CAM_TASK, initSwitchCamTask());
callTasksMap.put(SWITCH_SPEACKER_TASK, initSwitchSpeakerTask());
Log.d(CALL_INTEGRATION, "CallActivity. Set up tasks map finished");
}
private void executeCallTask(Runnable runnable) {
if (videoChatHelper != null) {
runOnUiThread(runnable);
} else {
callTasksQueue.add(runnable);
// Toast.makeText(this, VIDEOCHAT_HAS_NOT_REDY + "." + TASK_WILL_BE_EXECUTED_IN_NEAREST_TIME, Toast.LENGTH_LONG).show();
}
}
@Override
protected void onStart() {
super.onStart();
if (videoChatHelper != null) {
try {
videoChatHelper.setCamState(true);
} catch (QBRTCSessionIsAbsentException e) {
Log.d(CALL_INTEGRATION, e.getMessage() + " setMicState to true");
}
// videoChatHelper.addVideoChatHelperListener(this);
}
}
@Override
protected void onResume() {
Log.d(CALL_INTEGRATION, "Resume call activity " + this);
super.onResume();
// Call activity's lifecycle methods on GLSurfaceViews to allow system mange GL rendering
if (getLocalVideoView() != null){
getLocalVideoView().onResume();
}
if (getLocalVideoView() != null){
getRemoteVideoView().onResume();
}
}
@Override
protected void onPause() {
Log.d(CALL_INTEGRATION, "Pause call activity " + this);
super.onPause();
// Call activity's lifecycle methods on GLSurfaceViews to allow system mange GL rendering
if (getLocalVideoView() != null){
getLocalVideoView().onPause();
}
if (getLocalVideoView() != null){
getRemoteVideoView().onPause();
}
}
@Override
protected void onStop() {
Log.d(CALL_INTEGRATION, "Stop call activity " + this);
super.onStop();
if (videoChatHelper != null) {
// videoChatHelper.removeVideoChatHelperListener(this);
try {
videoChatHelper.setCamState(false);
} catch (QBRTCSessionIsAbsentException e) {
Log.d(CALL_INTEGRATION, e.getMessage() + " setMicState to false");
}
}
}
@Override
protected void onDestroy() {
Log.d(CALL_INTEGRATION, "Destroy call activity" + this);
stopIncomeCallTimer();
cancelPlayer();
if (QBRTCClient.isInitiated()) {
QBRTCClient.getInstance().close(true);
}
if (videoChatHelper != null) {
videoChatHelper.setClientClosed();
videoChatHelper.removeVideoChatHelperListener(this);
}
super.onDestroy();
}
public void initIncomingCallTask() {
singleTheadScheduledExecutor = new ScheduledThreadPoolExecutor(1);
closeIncomeCallTimerTask = new Runnable() {
@Override
public void run() {
Log.d(CALL_INTEGRATION, "Execute Income call timer close");
if (currentFragment instanceof IncomingCallFragment) {
Log.d(CALL_INTEGRATION, "IncomingCallFragment close with rejectCall");
executeCallTask(callTasksMap.get(REJECT_CALL_TASK));
} else {
Log.d(CALL_INTEGRATION, "OutgoingCallFragment close with hangUpCall");
executeCallTask(callTasksMap.get(HANG_UP_CALL_TASK));
}
}
};
}
public void startIncomeCallTimer() {
Log.d(CALL_INTEGRATION, "Start Income call timer");
if (singleTheadScheduledExecutor == null) {
initIncomingCallTask();
}
closeIncomeCallFutureTask = singleTheadScheduledExecutor
.schedule(closeIncomeCallTimerTask, QBRTCConfig.getAnswerTimeInterval(), TimeUnit.SECONDS);
}
public void stopIncomeCallTimer() {
Log.d(CALL_INTEGRATION, "Stop Income call timer");
if (singleTheadScheduledExecutor != null) {
closeIncomeCallFutureTask.cancel(true);
singleTheadScheduledExecutor.shutdown();
singleTheadScheduledExecutor = null;
}
}
/**
* Throw push notification about call if user ofline
* @param friend
*/
private void notifyFriendOnCall(User friend) {
if (!friend.isOnline()) {
String callMsg = getResources().getString(R.string.dlg_offline_call,
AppSession.getSession().getUser().getFullName());
QBSendPushCommand.start(this, callMsg, friend.getUserId());
}
}
private void showOutgoingFragment() {
Log.d(CALL_INTEGRATION, "CallActivity. showOutgoingFragment");
if (call_direction_type.equals(ConstsCore.CALL_DIRECTION_TYPE.OUTGOING)) {
playOutgoingRingtone();
}
OutgoingCallFragment outgoingCallFragment = (QBRTCTypes.QBConferenceType.QB_CONFERENCE_TYPE_VIDEO.equals(
call_type)) ? new VideoCallFragment() : new VoiceCallFragment();
Bundle bundle = new Bundle();
bundle.putSerializable(ConstsCore.CALL_DIRECTION_TYPE_EXTRA, call_direction_type);
bundle.putSerializable(ConstsCore.EXTRA_FRIEND, opponent);
bundle.putSerializable(ConstsCore.CALL_TYPE_EXTRA, call_type);
outgoingCallFragment.setArguments(bundle);
setCurrentFragment(outgoingCallFragment);
}
private void showIncomingFragment() {
Log.d(CALL_INTEGRATION, "CallActivity. showIncomingFragment");
playIncomingRingtone();
IncomingCallFragment incomingCallFragment = IncomingCallFragment.newInstance(call_type,
opponent);
setCurrentFragment(incomingCallFragment);
}
private void showToastMessage(final String message) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(CallActivity.this, message, Toast.LENGTH_SHORT).show();
}
});
}
/* // TODO REVIEW REQUIREMENT OF THIS METHOD
private void showOutgoingFragment(User opponentId,
QBRTCTypes.QBConferenceType callType, String sessionId) {
Log.d(CALL_INTEGRATION, "sCallActivity. showOutgoingFragment");
// TODO WHY JUST FOR VIDEO FRAGMENT BUNDLE ARE USING
Bundle bundle = VideoCallFragment.generateArguments(opponentId,
call_direction_type, callType, sessionId);
OutgoingCallFragment outgoingCallFragment = (QBRTCTypes.QBConferenceType.QB_CONFERENCE_TYPE_VIDEO.equals(
call_type)) ? new VideoCallFragment() : new VoiceCallFragment();
outgoingCallFragment.setArguments(bundle);
if (outgoingCallFragment instanceof VideoCallFragment) {
setCurrentFragment(outgoingCallFragment);
} else {
setCurrentFragment(outgoingCallFragment);
}
}*/
private void playOutgoingRingtone() {
if (mediaPlayer != null) {
mediaPlayer.playSound("calling.mp3", true);
}
}
private void playIncomingRingtone() {
if (mediaPlayer != null) {
mediaPlayer.playDefaultRingTone();
}
}
protected void cancelPlayer() {
if (mediaPlayer != null) {
mediaPlayer.stopPlaying();
}
}
@Override
public void onReceiveNewSession() {
Log.d(CALL_INTEGRATION, "CallActivity. onReceiveNewSession");
}
@Override
public void onUserNotAnswer(Integer integer) {
Log.d(CALL_INTEGRATION, "CallActivity. onUserNotAnswer");
showToastMessage(getString(R.string.user_not_answer));
}
@Override
public void onCallRejectByUser(Integer integer, Map<String, String> stringStringMap) {
Log.d(CALL_INTEGRATION, "CallActivity. onCallRejectByUser");
showToastMessage(getString(R.string.user_reject_call));
}
@Override
public void onReceiveHangUpFromUser(Integer integer) {
Log.d(CALL_INTEGRATION, "CallActivity. onReceiveHangUpFromUser");
if(!isCleintReadyAccept){
waitingTasksMap.clear();
finish();
}
if (currentFragment instanceof IncomingCallFragment
|| currentFragment instanceof OutgoingCallFragment){
showToastMessage(getString(R.string.user_hang_up_call));
}
}
@Override
public void onSessionClosed() {
Log.d(CALL_INTEGRATION, "CallActivity. onSessionClosed");
cancelPlayer();
finish();
}
@Override
public void onSessionStartClose() {
Log.d(CALL_INTEGRATION, "CallActivity. onSessionStartClose");
}
@Override
public void onLocalVideoTrackReceive(final QBRTCVideoTrack videoTrack) {
if (getLocalVideoView() == null) {
videoTracksSetEnumMap.get(VideoTracks.LOCAL_VIDEO_TRACK).add(initLocalVideoTrackTask(videoTrack));
} else {
initLocalVideoTrack(videoTrack);
}
}
@Override
public void onRemoteVideoTrackReceive(final QBRTCVideoTrack videoTrack, Integer userID) {
if (getRemoteVideoView() == null) {
videoTracksSetEnumMap.get(VideoTracks.REMOTE_VIDEO_TRACK).add(initRemoteVideoTrackTask(videoTrack));
} else {
initRemoteVideoTrack(videoTrack);
}
}
@Override
public void onClientReady() {
Log.d(CALL_INTEGRATION, "CallActivity. onClientReady");
isCleintReadyAccept = true;
//Execute if call was accepted
for (String key : waitingTasksMap.keySet()) {
executeCallTask(waitingTasksMap.get(key));
}
waitingTasksMap.clear();
}
@Override
public void onError(String s) {
Toast.makeText(this, s, Toast.LENGTH_LONG).show();
}
/**
* Callback on service connected uses for QBVideoChatHelper instance receive
* @param service
*/
@Override
public void onConnectedToService(QBService service) {
super.onConnectedToService(service);
if (videoChatHelper == null) {
Log.d(CALL_INTEGRATION, "CallActivity. onConnectedToService");
videoChatHelper = (QBVideoChatHelper) service.getHelper(QBService.VIDEO_CHAT_HELPER);
videoChatHelper.addVideoChatHelperListener(this);
if (call_direction_type != null) {
if (ConstsCore.CALL_DIRECTION_TYPE.INCOMING.equals(call_direction_type)) {
showIncomingFragment();
} else {
notifyFriendOnCall(opponent);
showOutgoingFragment();
}
}
executeScheduledTasks();
}
}
/**
* Executes all scheduled tasks as soon as we receive QBVideoChatHelper instance
*/
private void executeScheduledTasks() {
Log.d(CALL_INTEGRATION, "CallActivity. executeScheduledTasks");
for (Runnable task : callTasksQueue) {
// callTasksHandler.post(task);
runOnUiThread(task);
}
}
private Runnable initStartCallTask() {
return new Runnable() {
@Override
public void run() {
final List<Integer> opponents = new ArrayList<>();
opponents.add(opponent.getUserId());
Log.d(CALL_INTEGRATION, "CallActivity. initStartCallTask lunched");
videoChatHelper.startCall(userInfo, opponents, call_type);
}
};
}
private Runnable initAcceptCallTask() {
return new Runnable() {
@Override
public void run() {
Log.d(CALL_INTEGRATION, "CallActivity. initAcceptCallTask lunched");
try {
videoChatHelper.acceptCall(userInfo);
} catch (QBRTCSessionIsAbsentException e) {
Log.d(CALL_INTEGRATION, e.getMessage() + " acceptCall");
}
}
};
}
private Runnable initRejectCallTask() {
return new Runnable() {
@Override
public void run() {
Log.d(CALL_INTEGRATION, "CallActivity. initRejectCallTask lunched");
cancelPlayer();
try {
videoChatHelper.rejectCall(userInfo);
} catch (QBRTCSessionIsAbsentException e) {
Log.d(CALL_INTEGRATION, e.getMessage() + " rejectCall");
}
}
};
}
private Runnable initMicOffTask() {
return new Runnable() {
@Override
public void run() {
Log.d(CALL_INTEGRATION, "CallActivity. initMicOffTask lunched");
try {
videoChatHelper.setMicState(false);
} catch (QBRTCSessionIsAbsentException e) {
Log.d(CALL_INTEGRATION, e.getMessage() + " setMicState to false");
}
}
};
}
private Runnable initMicOnTask() {
return new Runnable() {
@Override
public void run() {
Log.d(CALL_INTEGRATION, "CallActivity. initMicOnTask lunched");
try {
videoChatHelper.setMicState(true);
} catch (QBRTCSessionIsAbsentException e) {
Log.d(CALL_INTEGRATION, e.getMessage() + " setMicState to true");
}
}
};
}
private Runnable initCamOnTask() {
return new Runnable() {
@Override
public void run() {
Log.d(CALL_INTEGRATION, "CallActivity. initCamOnTask lunched");
try {
videoChatHelper.setCamState(true);
} catch (QBRTCSessionIsAbsentException e) {
Log.d(CALL_INTEGRATION, e.getMessage() + " setCamState to true");
}
}
};
}
private Runnable initCamOffTask() {
return new Runnable() {
@Override
public void run() {
Log.d(CALL_INTEGRATION, "CallActivity. initCamOffTask lunched");
try {
videoChatHelper.setCamState(false);
} catch (QBRTCSessionIsAbsentException e) {
Log.d(CALL_INTEGRATION, e.getMessage() + " setCamState to false");
}
}
};
}
private Runnable initSwitchSpeakerTask() {
return new Runnable() {
@Override
public void run() {
Log.d(CALL_INTEGRATION, "CallActivity. initSwitchSpeakerTask lunched");
try {
videoChatHelper.switchMic();
} catch (QBRTCSessionIsAbsentException e) {
Log.d(CALL_INTEGRATION, e.getMessage() + " switchMic");
}
}
};
}
private Runnable initSwitchCamTask() {
return new Runnable() {
@Override
public void run() {
Log.d(CALL_INTEGRATION, "CallActivity. initSwitchCamTask lunched");
try {
videoChatHelper.switchCam(null);
} catch (QBRTCSessionIsAbsentException e) {
Log.d(CALL_INTEGRATION,e.getMessage() + " switchCam");
}
}
};
}
private Runnable initHangUpCallTask() {
return new Runnable() {
@Override
public void run() {
Log.d(CALL_INTEGRATION, "CallActivity. initHangUpCallTask lunched");
try {
videoChatHelper.hangUpCall(userInfo);
} catch (QBRTCSessionIsAbsentException e) {
CallActivity.this.finish();
Log.d(CALL_INTEGRATION, e.getMessage() + " hangUpCall");
}
}
};
}
private Runnable initRemoteVideoTrackTask(final QBRTCVideoTrack videoTrack) {
return new Runnable() {
@Override
public void run() {
initRemoteVideoTrack(videoTrack);
}
};
}
private Runnable initLocalVideoTrackTask(final QBRTCVideoTrack videoTrack) {
return new Runnable() {
@Override
public void run() {
initLocalVideoTrack(videoTrack);
}
};
}
@Override
public boolean isCanPerformLogoutInOnStop() {
return false;
}
public QBGLVideoView getLocalVideoView() {
return (QBGLVideoView) findViewById(R.id.localVideoView);
}
public QBGLVideoView getRemoteVideoView() {
return (QBGLVideoView) findViewById(R.id.remoteVideoView);
}
public void setLocalVideoView(QBGLVideoView videoView) {
this.localVideoView = videoView;
onLocalVideoViewCreated();
}
public void setRemoteVideoView(QBGLVideoView videoView) {
this.remoteVideoView = videoView;
onRemoteVideoViewCreated();
}
public QBVideoChatHelper getVideoChatHelper() {
return videoChatHelper;
}
private void initLocalVideoTrack(QBRTCVideoTrack videoTrack) {
Log.d(CALL_INTEGRATION, "CallActivity. onLocalVideoTrackReceive");
Log.d(CALL_INTEGRATION, "Video view is " + localVideoView);
videoTrack.addRenderer(new VideoRenderer(new VideoCallBacks(getLocalVideoView(), QBGLVideoView.Endpoint.LOCAL)));
getLocalVideoView().setVideoTrack(videoTrack, QBGLVideoView.Endpoint.LOCAL);
}
private void initRemoteVideoTrack(QBRTCVideoTrack videoTrack) {
Log.d(CALL_INTEGRATION, "CallActivity. onRemoteVideoTrackReceive");
Log.d(CALL_INTEGRATION, "Video view is " + remoteVideoView);
videoTrack.addRenderer(new VideoRenderer(new VideoCallBacks(getRemoteVideoView(), QBGLVideoView.Endpoint.REMOTE)));
getRemoteVideoView().setVideoTrack(videoTrack, QBGLVideoView.Endpoint.REMOTE);
}
enum VideoTracks {
LOCAL_VIDEO_TRACK,
REMOTE_VIDEO_TRACK
}
}
|
package legends.web;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import legends.helper.Templates;
import legends.model.World;
import legends.web.basic.Controller;
import legends.web.basic.RequestMapping;
import legends.web.util.SearchResult;
@Controller
public class SearchController {
private static final int SEARCH_LIMIT = 10;
@RequestMapping("/search")
public Template search(VelocityContext context) {
if (context.containsKey("query")) {
String query = context.get("query").toString().toLowerCase();
context.put("query", query);
context.put("regions", World.getRegions().stream().filter(e -> e.getName().toLowerCase().contains(query))
.collect(Collectors.toList()));
context.put("sites", World.getSites().stream().filter(e -> e.getName().toLowerCase().contains(query))
.collect(Collectors.toList()));
context.put("artifacts", World.getArtifacts().stream()
.filter(e -> e.getName().toLowerCase().contains(query)).collect(Collectors.toList()));
context.put("entities", World.getEntities().stream().filter(e -> e.getName().toLowerCase().contains(query))
.collect(Collectors.toList()));
context.put("hfs", World.getHistoricalFigures().stream()
.filter(e -> e.getName().toLowerCase().contains(query)).collect(Collectors.toList()));
return Templates.get("search.vm");
} else
return Templates.get("index.vm");
}
@RequestMapping("/search.json")
public Template searchJSON(VelocityContext context) {
String query = context.get("query").toString().toLowerCase();
List<SearchResult> results = new ArrayList<>();
World.getEntities().stream().filter(e -> e.getName().toLowerCase().contains(query)).limit(SEARCH_LIMIT)
.map(e -> new SearchResult(e.getName(), e.getURL())).forEach(results::add);
World.getSites().stream().filter(e -> e.getName().toLowerCase().contains(query)).limit(SEARCH_LIMIT)
.map(e -> new SearchResult(e.getName(), e.getURL())).forEach(results::add);
World.getStructures().stream().filter(e -> e.getName().toLowerCase().contains(query)).limit(SEARCH_LIMIT)
.map(e -> new SearchResult(e.getName(), e.getURL())).forEach(results::add);
World.getHistoricalFigures().stream().filter(e -> e.getName().toLowerCase().contains(query)).limit(SEARCH_LIMIT)
.map(e -> new SearchResult(e.getName(), e.getURL())).forEach(results::add);
World.getIdentities().stream().filter(e -> e.getName().toLowerCase().contains(query)).limit(SEARCH_LIMIT)
.map(e -> new SearchResult(e.getName(), e.getURL())).forEach(results::add);
World.getRegions().stream().filter(e -> e.getName().toLowerCase().contains(query)).limit(SEARCH_LIMIT)
.map(e -> new SearchResult(e.getName(), e.getURL())).forEach(results::add);
World.getArtifacts().stream().filter(e -> e.getName().toLowerCase().contains(query)).limit(SEARCH_LIMIT)
.map(e -> new SearchResult(e.getName(), e.getURL())).forEach(results::add);
World.getWorldConstructions().stream().filter(e -> e.getName().toLowerCase().contains(query)).limit(SEARCH_LIMIT)
.map(e -> new SearchResult(e.getName(), e.getURL())).forEach(results::add);
context.put("results", results);
context.put("contentType", "application/json");
return Templates.get("searchjson.vm");
}
}
|
package com.bnorm.fsm4j;
/**
* Simple interface that represents a transition between states.
*
* @param <S> the class type of the states.
* @author Brian Norman
* @version 1.0
* @since 1.0
*/
public interface Transition<S extends State> {
/**
* The state the transition originates from.
*
* @return the source state.
*/
S getSource();
/**
* The state the transition completes at.
*
* @return the destination state.
*/
S getDestination();
/**
* Returns {@code true} if the transition is a reentry into the originating state. If a transition is a reentry
* transition, any parent state's entry/exit actions are not called.
*
* @return if the source state is equal to the destination state.
*/
default boolean isReentrant() {
return getSource().equals(getDestination());
}
/**
* If the transition is allowed. This value could change given circumstances outside of the state machine so it is
* checked every time this is a possible transition.
*
* @return if the transition is currently allowed.
*/
default boolean allowed() {
return true;
}
}
|
package com.urbanairship.richpush.sample;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v4.app.NotificationCompat;
import android.text.Html;
import com.urbanairship.UAirship;
import com.urbanairship.push.PushMessage;
import com.urbanairship.push.notifications.DefaultNotificationFactory;
import com.urbanairship.richpush.RichPushMessage;
import com.urbanairship.util.NotificationIDGenerator;
import com.urbanairship.util.UAStringUtil;
import java.util.List;
/**
* A custom push notification builder to create inbox style notifications
* for rich push messages. In the case of standard push notifications, it will
* fall back to the default behavior.
*/
public class RichPushNotificationFactory extends DefaultNotificationFactory {
private static final int EXTRA_MESSAGES_TO_SHOW = 2;
private static final int INBOX_NOTIFICATION_ID = 9000000;
public RichPushNotificationFactory(Context context) {
super(context);
}
@Override
public Notification createNotification(PushMessage message, int notificationId) {
if (!UAStringUtil.isEmpty(message.getRichPushMessageId())) {
return createInboxNotification(message, notificationId);
} else {
return super.createNotification(message, notificationId);
}
}
@Override
public int getNextId(PushMessage pushMessage) {
if (!UAStringUtil.isEmpty(pushMessage.getRichPushMessageId())) {
return INBOX_NOTIFICATION_ID;
} else {
return NotificationIDGenerator.nextID();
}
}
/**
* Creates an inbox style notification summarizing the unread messages
* in the inbox
*
* @param message The push message from an Urban Airship push
* @param notificationId The push notification id
* @return An inbox style notification
*/
private Notification createInboxNotification(PushMessage message, int notificationId) {
Context context = UAirship.getApplicationContext();
String incomingAlert = message.getAlert();
List<RichPushMessage> unreadMessages = UAirship.shared().getRichPushManager().getRichPushInbox().getUnreadMessages();
int totalUnreadCount = unreadMessages.size();
// If we do not have any unread messages (message already read or they failed to fetch)
// show a normal notification.
if (totalUnreadCount == 0) {
return super.createNotification(message, notificationId);
}
Resources res = context.getResources();
String title = res.getQuantityString(R.plurals.inbox_notification_title, totalUnreadCount, totalUnreadCount);
Bitmap largeIcon = BitmapFactory.decodeResource(res, R.drawable.ua_launcher);
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle()
.addLine(Html.fromHtml("<b>" + incomingAlert + "</b>"));
// Add any extra messages to the notification style
int extraMessages = Math.min(EXTRA_MESSAGES_TO_SHOW, totalUnreadCount);
for (int i = 0; i < extraMessages; i++) {
inboxStyle.addLine(unreadMessages.get(i).getTitle());
}
// If we have more messages to show then the EXTRA_MESSAGES_TO_SHOW, add a summary
if (totalUnreadCount > EXTRA_MESSAGES_TO_SHOW) {
inboxStyle.setSummaryText(context.getString(R.string.inbox_summary, totalUnreadCount - EXTRA_MESSAGES_TO_SHOW));
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setContentTitle(title)
.setContentText(message.getAlert())
.setLargeIcon(largeIcon)
.setSmallIcon(R.drawable.ua_notification_icon)
.setNumber(totalUnreadCount)
.setAutoCancel(true)
.setStyle(inboxStyle)
.setDefaults(NotificationCompat.DEFAULT_SOUND | NotificationCompat.DEFAULT_VIBRATE);
// Notification actions
builder.extend(createNotificationActionsExtender(message, notificationId));
return builder.build();
}
/**
* Dismisses the inbox style notification if it exists
*/
public static void dismissInboxNotification() {
NotificationManager manager = (NotificationManager) UAirship.shared().
getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
manager.cancel(INBOX_NOTIFICATION_ID);
}
}
|
package lx.easydb.mapping;
import java.util.Iterator;
import lx.easydb.StringHelper;
import lx.easydb.dialect.Dialect;
public class PrimaryKey extends Constraint {
public PrimaryKey() {
}
public PrimaryKey(Column column) {
addColumn(column);
}
public PrimaryKey(Column[] columns) {
for (int i = 0; i < columns.length; i++) {
addColumn(columns[i]);
}
}
public String toSqlConstraintString(Dialect dialect) {
StringBuffer sb = StringHelper.createBuilder().append("primary key (");
return appendColumns(sb, dialect).append(")").toString();
}
protected String doToSqlConstraint(Dialect dialect, String constraintName) {
StringBuffer sb = StringHelper.createBuilder()
.append(dialect.getAddPrimaryKeyConstraintString(constraintName))
.append("(");
return appendColumns(sb, dialect).append(")").toString();
}
private StringBuffer appendColumns(StringBuffer sb, Dialect dialect) {
boolean append = false;
Iterator it = getColumns().iterator();
while (it.hasNext()) {
if (append)
sb.append(", ");
else
append = true;
Column column = (Column) it.next();
sb.append(column.getQuotedName(dialect));
}
return sb;
}
}
|
package com.distelli.europa;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashSet;
import java.util.Set;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.ErrorHandler;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletHolder;
import com.distelli.europa.EuropaConfiguration.EuropaStage;
import com.distelli.europa.db.RegistryBlobDb;
import com.distelli.europa.db.TokenAuthDb;
import com.distelli.europa.filters.StorageInitFilter;
import com.distelli.europa.filters.RegistryAuthFilter;
import com.distelli.europa.guice.*;
import com.distelli.europa.handlers.StaticContentErrorHandler;
import com.distelli.europa.monitor.*;
import com.distelli.europa.util.*;
import com.distelli.objectStore.impl.ObjectStoreModule;
import com.distelli.persistence.impl.PersistenceModule;
import com.distelli.utils.Log4JConfigurator;
import com.distelli.europa.db.TokenAuthDb;
import com.distelli.europa.db.RegistryBlobDb;
import com.distelli.europa.db.SequenceDb;
import com.distelli.europa.db.ContainerRepoDb;
import com.distelli.europa.db.RegistryCredsDb;
import com.distelli.europa.db.NotificationsDb;
import com.distelli.europa.db.RepoEventsDb;
import com.distelli.europa.db.RegistryManifestDb;
import com.distelli.webserver.*;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Provides;
import com.google.inject.Stage;
import java.util.Arrays;
import lombok.extern.log4j.Log4j;
import java.util.List;
import org.eclipse.jetty.util.ssl.SslContextFactory;
@Log4j
public class Europa
{
protected RequestHandlerFactory _requestHandlerFactory = null;
protected RequestContextFactory<EuropaRequestContext> _requestContextFactory = null;
protected List<RequestFilter<EuropaRequestContext>> _registryApiFilters = null;
protected List<RequestFilter<EuropaRequestContext>> _webappFilters = null;
protected StaticContentErrorHandler _staticContentErrorHandler = null;
protected int _port = 8080;
protected int _sslPort = 8443;
@Inject
protected SslContextFactory _sslContextFactory;
@Inject
protected MonitorQueue _monitorQueue;
protected Thread _monitorThread;
protected RouteMatcher _webappRouteMatcher = null;
protected RouteMatcher _registryApiRouteMatcher = null;
protected CmdLineArgs _cmdLineArgs = null;
protected EuropaStage _stage = null;
protected String _configFilePath = null;
public Europa(String[] args)
{
_cmdLineArgs = new CmdLineArgs(args);
boolean logToConsole = _cmdLineArgs.hasOption(Constants.LOG_TO_CONSOLE_ARG);
// Initialize Logging
File logsDir = new File("./logs/");
if(!logsDir.exists())
logsDir.mkdirs();
if(logToConsole)
Log4JConfigurator.configure(true);
else
Log4JConfigurator.configure(logsDir, "Europa");
Log4JConfigurator.setLogLevel("INFO");
Log4JConfigurator.setLogLevel("com.distelli.europa", "DEBUG");
Log4JConfigurator.setLogLevel("com.distelli.webserver", "ERROR");
Log4JConfigurator.setLogLevel("com.distelli.gcr", "ERROR");
Log4JConfigurator.setLogLevel("com.distelli.europa.monitor", "ERROR");
//Log4JConfigurator.setLogLevel("com.distelli.webserver", "DEBUG");
//Log4JConfigurator.setLogLevel("com.distelli.persistence", "DEBUG");
_configFilePath = _cmdLineArgs.getOption("config");
String portStr = _cmdLineArgs.getOption("port");
if(portStr != null)
{
try {
_port = Integer.parseInt(portStr);
} catch(NumberFormatException nfe) {
log.fatal("Invalid value for --port "+portStr);
System.exit(1);
}
}
portStr = _cmdLineArgs.getOption("ssl-port");
if(portStr != null)
{
try {
_sslPort = Integer.parseInt(portStr);
} catch(NumberFormatException nfe) {
log.fatal("Invalid value for --ssl-port "+portStr);
System.exit(1);
}
}
_stage = EuropaStage.prod;
String stageArg = _cmdLineArgs.getOption("stage");
if(stageArg != null) {
try {
_stage = EuropaStage.valueOf(stageArg);
} catch(Throwable t) {
throw(new RuntimeException("Invalid value for stage: "+stageArg, t));
}
}
initialize();
}
protected void initializeWebServer(Injector injector)
{
_webappFilters = Arrays.asList(injector.getInstance(StorageInitFilter.class));
_registryApiFilters = Arrays.asList(injector.getInstance(RegistryAuthFilter.class));
_requestContextFactory = new RequestContextFactory() {
public RequestContext getRequestContext(HTTPMethod httpMethod, HttpServletRequest request) {
return new EuropaRequestContext(httpMethod, request);
}
};
_requestHandlerFactory = new RequestHandlerFactory() {
public RequestHandler getRequestHandler(MatchedRoute route) {
return injector.getInstance(route.getRequestHandler());
}
};
_staticContentErrorHandler = injector.getInstance(StaticContentErrorHandler.class);
_registryApiRouteMatcher = RegistryApiRoutes.getRouteMatcher();
_webappRouteMatcher = WebAppRoutes.getRouteMatcher();
}
protected void initialize()
{
EuropaConfiguration europaConfiguration = null;
if(_configFilePath != null)
europaConfiguration = EuropaConfiguration.fromFile(new File(_configFilePath));
else
europaConfiguration = EuropaConfiguration.fromEnvironment();
europaConfiguration.setStage(_stage);
Injector injector = Guice.createInjector(Stage.PRODUCTION,
new PersistenceModule(),
new AjaxHelperModule(),
new ObjectStoreModule(),
new EuropaInjectorModule(europaConfiguration));
injector.injectMembers(this);
initializeWebServer(injector);
}
public void start()
{
RepoMonitor monitor = new RepoMonitor(_monitorQueue);
_monitorThread = new Thread(monitor);
_monitorThread.start();
WebServlet<EuropaRequestContext> servlet =
new WebServlet<EuropaRequestContext>(_webappRouteMatcher, _requestHandlerFactory);
servlet.setRequestContextFactory(_requestContextFactory);
if(_webappFilters != null)
servlet.setRequestFilters(_webappFilters);
WebServer webServer = new WebServer(_port, servlet, "/", _sslPort, _sslContextFactory);
ServletHolder staticHolder = new ServletHolder(DefaultServlet.class);
staticHolder.setInitParameter("resourceBase", "./public");
staticHolder.setInitParameter("dirAllowed","true");
staticHolder.setInitParameter("pathInfoOnly","true");
staticHolder.setInitParameter("etags", "true");
staticHolder.setInitParameter("gzip", "true");
staticHolder.setInitParameter("cacheControl", "max-age=3600");
|
package com.hubspot.singularity.resources;
import static com.hubspot.singularity.WebExceptions.badRequest;
import static com.hubspot.singularity.WebExceptions.checkBadRequest;
import static com.hubspot.singularity.WebExceptions.checkNotFound;
import static com.hubspot.singularity.WebExceptions.notFound;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.apache.curator.framework.recipes.leader.LeaderLatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.inject.Inject;
import com.hubspot.jackson.jaxrs.PropertyFiltering;
import com.hubspot.mesos.client.MesosClient;
import com.hubspot.mesos.json.MesosTaskMonitorObject;
import com.hubspot.mesos.json.MesosTaskStatisticsObject;
import com.hubspot.singularity.InvalidSingularityTaskIdException;
import com.hubspot.singularity.RequestType;
import com.hubspot.singularity.SingularityAction;
import com.hubspot.singularity.SingularityAuthorizationScope;
import com.hubspot.singularity.SingularityCreateResult;
import com.hubspot.singularity.SingularityDeploy;
import com.hubspot.singularity.SingularityKilledTaskIdRecord;
import com.hubspot.singularity.SingularityPendingDeploy;
import com.hubspot.singularity.SingularityPendingRequest;
import com.hubspot.singularity.SingularityPendingRequest.PendingType;
import com.hubspot.singularity.SingularityPendingTask;
import com.hubspot.singularity.SingularityPendingTaskId;
import com.hubspot.singularity.SingularityRequest;
import com.hubspot.singularity.SingularityRequestWithState;
import com.hubspot.singularity.SingularityShellCommand;
import com.hubspot.singularity.SingularitySlave;
import com.hubspot.singularity.SingularityTask;
import com.hubspot.singularity.SingularityTaskCleanup;
import com.hubspot.singularity.SingularityTaskId;
import com.hubspot.singularity.SingularityTaskIdsByStatus;
import com.hubspot.singularity.SingularityTaskMetadata;
import com.hubspot.singularity.SingularityTaskRequest;
import com.hubspot.singularity.SingularityTaskShellCommandHistory;
import com.hubspot.singularity.SingularityTaskShellCommandRequest;
import com.hubspot.singularity.SingularityTaskShellCommandRequestId;
import com.hubspot.singularity.SingularityTaskShellCommandUpdate;
import com.hubspot.singularity.SingularityTransformHelpers;
import com.hubspot.singularity.SingularityUser;
import com.hubspot.singularity.TaskCleanupType;
import com.hubspot.singularity.WebExceptions;
import com.hubspot.singularity.api.SingularityKillTaskRequest;
import com.hubspot.singularity.api.SingularityTaskMetadataRequest;
import com.hubspot.singularity.auth.SingularityAuthorizationHelper;
import com.hubspot.singularity.config.ApiPaths;
import com.hubspot.singularity.config.SingularityTaskMetadataConfiguration;
import com.hubspot.singularity.data.DeployManager;
import com.hubspot.singularity.data.DisasterManager;
import com.hubspot.singularity.data.RequestManager;
import com.hubspot.singularity.data.SingularityValidator;
import com.hubspot.singularity.data.SlaveManager;
import com.hubspot.singularity.data.TaskManager;
import com.hubspot.singularity.data.TaskRequestManager;
import com.hubspot.singularity.scheduler.SingularityDeployHealthHelper;
import com.ning.http.client.AsyncHttpClient;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiResponse;
import com.wordnik.swagger.annotations.ApiResponses;
import io.dropwizard.auth.Auth;
@Path(ApiPaths.TASK_RESOURCE_PATH)
@Produces({ MediaType.APPLICATION_JSON })
@Api(description="Manages Singularity tasks.", value=ApiPaths.TASK_RESOURCE_PATH)
public class TaskResource extends AbstractLeaderAwareResource {
private static final Logger LOG = LoggerFactory.getLogger(TaskResource.class);
private final TaskManager taskManager;
private final RequestManager requestManager;
private final SlaveManager slaveManager;
private final TaskRequestManager taskRequestManager;
private final MesosClient mesosClient;
private final SingularityAuthorizationHelper authorizationHelper;
private final SingularityTaskMetadataConfiguration taskMetadataConfiguration;
private final SingularityValidator validator;
private final DisasterManager disasterManager;
private final SingularityDeployHealthHelper deployHealthHelper;
private final DeployManager deployManager;
@Inject
public TaskResource(TaskRequestManager taskRequestManager, TaskManager taskManager, SlaveManager slaveManager, MesosClient mesosClient, SingularityTaskMetadataConfiguration taskMetadataConfiguration,
SingularityAuthorizationHelper authorizationHelper, RequestManager requestManager, SingularityValidator validator, DisasterManager disasterManager,
AsyncHttpClient httpClient, LeaderLatch leaderLatch, ObjectMapper objectMapper, SingularityDeployHealthHelper deployHealthHelper, DeployManager deployManager) {
super(httpClient, leaderLatch, objectMapper);
this.taskManager = taskManager;
this.taskRequestManager = taskRequestManager;
this.taskMetadataConfiguration = taskMetadataConfiguration;
this.slaveManager = slaveManager;
this.mesosClient = mesosClient;
this.requestManager = requestManager;
this.authorizationHelper = authorizationHelper;
this.validator = validator;
this.disasterManager = disasterManager;
this.deployHealthHelper = deployHealthHelper;
this.deployManager = deployManager;
}
@GET
@PropertyFiltering
@Path("/scheduled")
@ApiOperation("Retrieve list of scheduled tasks.")
public List<SingularityTaskRequest> getScheduledTasks(@Auth SingularityUser user, @QueryParam("useWebCache") Boolean useWebCache) {
if (!authorizationHelper.hasAdminAuthorization(user) && disasterManager.isDisabled(SingularityAction.EXPENSIVE_API_CALLS)) {
LOG.trace("Short circuting getScheduledTasks() to [] due to EXPENSIVE_API_CALLS disabled");
return Collections.emptyList();
}
return taskRequestManager.getTaskRequests(ImmutableList.copyOf(authorizationHelper.filterByAuthorizedRequests(user,
taskManager.getPendingTasks(useWebCache(useWebCache)), SingularityTransformHelpers.PENDING_TASK_TO_REQUEST_ID, SingularityAuthorizationScope.READ)));
}
@GET
@PropertyFiltering
@Path("/scheduled/ids")
@ApiOperation("Retrieve list of scheduled task IDs.")
public Iterable<SingularityPendingTaskId> getScheduledTaskIds(@Auth SingularityUser user, @QueryParam("useWebCache") Boolean useWebCache) {
return authorizationHelper.filterByAuthorizedRequests(user, taskManager.getPendingTaskIds(useWebCache(useWebCache)), SingularityTransformHelpers.PENDING_TASK_ID_TO_REQUEST_ID, SingularityAuthorizationScope.READ);
}
private SingularityPendingTaskId getPendingTaskIdFromStr(String pendingTaskIdStr) {
try {
return SingularityPendingTaskId.valueOf(pendingTaskIdStr);
} catch (InvalidSingularityTaskIdException e) {
throw badRequest("%s is not a valid pendingTaskId: %s", pendingTaskIdStr, e.getMessage());
}
}
private SingularityTaskId getTaskIdFromStr(String activeTaskIdStr) {
try {
return SingularityTaskId.valueOf(activeTaskIdStr);
} catch (InvalidSingularityTaskIdException e) {
throw badRequest("%s is not a valid taskId: %s", activeTaskIdStr, e.getMessage());
}
}
@GET
@PropertyFiltering
@Path("/scheduled/task/{pendingTaskId}")
@ApiOperation("Retrieve information about a pending task.")
public SingularityTaskRequest getPendingTask(@Auth SingularityUser user, @PathParam("pendingTaskId") String pendingTaskIdStr) {
Optional<SingularityPendingTask> pendingTask = taskManager.getPendingTask(getPendingTaskIdFromStr(pendingTaskIdStr));
checkNotFound(pendingTask.isPresent(), "Couldn't find %s", pendingTaskIdStr);
List<SingularityTaskRequest> taskRequestList = taskRequestManager.getTaskRequests(Collections.singletonList(pendingTask.get()));
checkNotFound(!taskRequestList.isEmpty(), "Couldn't find: " + pendingTaskIdStr);
authorizationHelper.checkForAuthorization(taskRequestList.get(0).getRequest(), user, SingularityAuthorizationScope.READ);
return taskRequestList.get(0);
}
@DELETE
@Path("/scheduled/task/{scheduledTaskId}")
@ApiOperation("Delete a scheduled task.")
public void deleteScheduledTask(@Auth SingularityUser user, @PathParam("scheduledTaskId") String taskId) {
SingularityTaskRequest taskRequest = getPendingTask(user, taskId);
SingularityRequest request = taskRequest.getRequest();
authorizationHelper.checkForAuthorization(request, user, SingularityAuthorizationScope.ADMIN);
checkBadRequest(request.getRequestType() == RequestType.ON_DEMAND, "Only ON_DEMAND tasks may be deleted.");
taskManager.deletePendingTask(taskRequest.getPendingTask().getPendingTaskId());
}
@GET
@PropertyFiltering
@Path("/scheduled/request/{requestId}")
@ApiOperation("Retrieve list of scheduled tasks for a specific request.")
public List<SingularityTaskRequest> getScheduledTasksForRequest(@Auth SingularityUser user, @PathParam("requestId") String requestId, @QueryParam("useWebCache") Boolean useWebCache) {
authorizationHelper.checkForAuthorizationByRequestId(requestId, user, SingularityAuthorizationScope.READ);
final List<SingularityPendingTask> tasks = Lists.newArrayList(Iterables.filter(taskManager.getPendingTasks(useWebCache(useWebCache)), SingularityPendingTask.matchingRequest(requestId)));
return taskRequestManager.getTaskRequests(tasks);
}
@GET
@Path("/ids/request/{requestId}")
@ApiOperation("Retrieve a list of task ids separated by status")
public Optional<SingularityTaskIdsByStatus> getTaskIdsByStatusForRequest(@Auth SingularityUser user, @PathParam("requestId") String requestId) {
authorizationHelper.checkForAuthorizationByRequestId(requestId, user, SingularityAuthorizationScope.READ);
Optional<SingularityRequestWithState> requestWithState = requestManager.getRequest(requestId);
if (!requestWithState.isPresent()) {
return Optional.absent();
}
Optional<SingularityPendingDeploy> pendingDeploy = deployManager.getPendingDeploy(requestId);
List<SingularityTaskId> cleaningTaskIds = taskManager.getCleanupTaskIds().stream().filter((t) -> t.getRequestId().equals(requestId)).collect(Collectors.toList());
List<SingularityPendingTaskId> pendingTaskIds = taskManager.getPendingTaskIdsForRequest(requestId);
List<SingularityTaskId> activeTaskIds = taskManager.getActiveTaskIdsForRequest(requestId);
activeTaskIds.removeAll(cleaningTaskIds);
List<SingularityTaskId> healthyTaskIds = new ArrayList<>();
List<SingularityTaskId> notYetHealthyTaskIds = new ArrayList<>();
Map<String, List<SingularityTaskId>> taskIdsByDeployId = activeTaskIds.stream().collect(Collectors.groupingBy(SingularityTaskId::getDeployId));
for (Map.Entry<String, List<SingularityTaskId>> entry : taskIdsByDeployId.entrySet()) {
Optional<SingularityDeploy> deploy = deployManager.getDeploy(requestId, entry.getKey());
List<SingularityTaskId> healthyTasksIdsForDeploy = deployHealthHelper.getHealthyTasks(
requestWithState.get().getRequest(),
deploy,
entry.getValue(),
pendingDeploy.isPresent() && pendingDeploy.get().getDeployMarker().getDeployId().equals(entry.getKey()));
for (SingularityTaskId taskId : entry.getValue()) {
if (healthyTasksIdsForDeploy.contains(taskId)) {
healthyTaskIds.add(taskId);
} else {
notYetHealthyTaskIds.add(taskId);
}
}
}
return Optional.of(new SingularityTaskIdsByStatus(healthyTaskIds, notYetHealthyTaskIds, pendingTaskIds, cleaningTaskIds));
}
@GET
@Path("/active/slave/{slaveId}")
@ApiOperation("Retrieve list of active tasks on a specific slave.")
public Iterable<SingularityTask> getTasksForSlave(@Auth SingularityUser user, @PathParam("slaveId") String slaveId, @QueryParam("useWebCache") Boolean useWebCache) {
Optional<SingularitySlave> maybeSlave = slaveManager.getObject(slaveId);
checkNotFound(maybeSlave.isPresent(), "Couldn't find a slave in any state with id %s", slaveId);
return authorizationHelper.filterByAuthorizedRequests(user, taskManager.getTasksOnSlave(taskManager.getActiveTaskIds(useWebCache(useWebCache)), maybeSlave.get()), SingularityTransformHelpers.TASK_TO_REQUEST_ID, SingularityAuthorizationScope.READ);
}
@GET
@PropertyFiltering
@Path("/active")
@ApiOperation("Retrieve the list of active tasks.")
public Iterable<SingularityTask> getActiveTasks(@Auth SingularityUser user, @QueryParam("useWebCache") Boolean useWebCache) {
return authorizationHelper.filterByAuthorizedRequests(user, taskManager.getActiveTasks(useWebCache(useWebCache)), SingularityTransformHelpers.TASK_TO_REQUEST_ID, SingularityAuthorizationScope.READ);
}
@GET
@PropertyFiltering
@Path("/cleaning")
@ApiOperation("Retrieve the list of cleaning tasks.")
public Iterable<SingularityTaskCleanup> getCleaningTasks(@Auth SingularityUser user, @QueryParam("useWebCache") Boolean useWebCache) {
if (!authorizationHelper.hasAdminAuthorization(user) && disasterManager.isDisabled(SingularityAction.EXPENSIVE_API_CALLS)) {
LOG.trace("Short circuting getCleaningTasks() to [] due to EXPENSIVE_API_CALLS disabled");
return Collections.emptyList();
}
return authorizationHelper.filterByAuthorizedRequests(user, taskManager.getCleanupTasks(useWebCache(useWebCache)), SingularityTransformHelpers.TASK_CLEANUP_TO_REQUEST_ID, SingularityAuthorizationScope.READ);
}
@GET
@Path("/killed")
@ApiOperation("Retrieve the list of killed tasks.")
public Iterable<SingularityKilledTaskIdRecord> getKilledTasks(@Auth SingularityUser user) {
return authorizationHelper.filterByAuthorizedRequests(user, taskManager.getKilledTaskIdRecords(), SingularityTransformHelpers.KILLED_TASK_ID_RECORD_TO_REQUEST_ID, SingularityAuthorizationScope.READ);
}
@GET
@PropertyFiltering
@Path("/lbcleanup")
@ApiOperation("Retrieve the list of tasks being cleaned from load balancers.")
public Iterable<SingularityTaskId> getLbCleanupTasks(@Auth SingularityUser user) {
return authorizationHelper.filterByAuthorizedRequests(user, taskManager.getLBCleanupTasks(), SingularityTransformHelpers.TASK_ID_TO_REQUEST_ID, SingularityAuthorizationScope.READ);
}
private SingularityTask checkActiveTask(String taskId, SingularityAuthorizationScope scope, SingularityUser user) {
SingularityTaskId taskIdObj = getTaskIdFromStr(taskId);
Optional<SingularityTask> task = taskManager.getTask(taskIdObj);
checkNotFound(task.isPresent() && taskManager.isActiveTask(taskId), "No active task with id %s", taskId);
if (task.isPresent()) {
authorizationHelper.checkForAuthorizationByRequestId(task.get().getTaskId().getRequestId(), user, scope);
}
return task.get();
}
@GET
@Path("/task/{taskId}")
@ApiOperation("Retrieve information about a specific active task.")
public SingularityTask getActiveTask(@Auth SingularityUser user, @PathParam("taskId") String taskId) {
return checkActiveTask(taskId, SingularityAuthorizationScope.READ, user);
}
@GET
@Path("/task/{taskId}/statistics")
@ApiOperation("Retrieve statistics about a specific active task.")
public MesosTaskStatisticsObject getTaskStatistics(@Auth SingularityUser user, @PathParam("taskId") String taskId) {
SingularityTask task = checkActiveTask(taskId, SingularityAuthorizationScope.READ, user);
String executorIdToMatch = null;
if (task.getMesosTask().hasExecutor()) {
executorIdToMatch = task.getMesosTask().getExecutor().getExecutorId().getValue();
} else {
executorIdToMatch = taskId;
}
for (MesosTaskMonitorObject taskMonitor : mesosClient.getSlaveResourceUsage(task.getHostname())) {
if (taskMonitor.getExecutorId().equals(executorIdToMatch)) {
return taskMonitor.getStatistics();
}
}
throw notFound("Couldn't find executor %s for %s on slave %s", executorIdToMatch, taskId, task.getHostname());
}
@GET
@Path("/task/{taskId}/cleanup")
@ApiOperation("Get the cleanup object for the task, if it exists")
public Optional<SingularityTaskCleanup> getTaskCleanup(@Auth SingularityUser user, @PathParam("taskId") String taskId) {
authorizationHelper.checkForAuthorizationByTaskId(taskId, user, SingularityAuthorizationScope.READ);
return taskManager.getTaskCleanup(taskId);
}
@DELETE
@Path("/task/{taskId}")
public SingularityTaskCleanup killTask(@Auth SingularityUser user, @PathParam("taskId") String taskId, @Context HttpServletRequest requestContext) {
return killTask(taskId, requestContext, null, user);
}
@DELETE
@Path("/task/{taskId}")
@Consumes({ MediaType.APPLICATION_JSON })
@ApiOperation(value="Attempt to kill task, optionally overriding an existing cleanup request (that may be waiting for replacement tasks to become healthy)", response=SingularityTaskCleanup.class)
@ApiResponses({
@ApiResponse(code=409, message="Task already has a cleanup request (can be overridden with override=true)")
})
public SingularityTaskCleanup killTask(@PathParam("taskId") String taskId,
@Context HttpServletRequest requestContext,
SingularityKillTaskRequest killTaskRequest,
@Auth SingularityUser user) {
final Optional<SingularityKillTaskRequest> maybeKillTaskRequest = Optional.fromNullable(killTaskRequest);
return maybeProxyToLeader(requestContext, SingularityTaskCleanup.class, maybeKillTaskRequest.orNull(), () -> killTask(taskId, maybeKillTaskRequest, user));
}
public SingularityTaskCleanup killTask(String taskId, Optional<SingularityKillTaskRequest> killTaskRequest, SingularityUser user) {
final SingularityTask task = checkActiveTask(taskId, SingularityAuthorizationScope.WRITE, user);
Optional<String> message = Optional.absent();
Optional<Boolean> override = Optional.absent();
Optional<String> actionId = Optional.absent();
Optional<Boolean> waitForReplacementTask = Optional.absent();
Optional<SingularityTaskShellCommandRequestId> runBeforeKillId = Optional.absent();
if (killTaskRequest.isPresent()) {
actionId = killTaskRequest.get().getActionId();
message = killTaskRequest.get().getMessage();
override = killTaskRequest.get().getOverride();
waitForReplacementTask = killTaskRequest.get().getWaitForReplacementTask();
if (killTaskRequest.get().getRunShellCommandBeforeKill().isPresent()) {
SingularityTaskShellCommandRequest shellCommandRequest = startShellCommand(task.getTaskId(), killTaskRequest.get().getRunShellCommandBeforeKill().get(), user);
runBeforeKillId = Optional.of(shellCommandRequest.getId());
}
}
TaskCleanupType cleanupType = TaskCleanupType.USER_REQUESTED;
if (waitForReplacementTask.or(Boolean.FALSE)) {
cleanupType = TaskCleanupType.USER_REQUESTED_TASK_BOUNCE;
validator.checkActionEnabled(SingularityAction.BOUNCE_TASK);
} else {
validator.checkActionEnabled(SingularityAction.KILL_TASK);
}
final long now = System.currentTimeMillis();
final SingularityTaskCleanup taskCleanup;
if (override.isPresent() && override.get()) {
LOG.debug("Requested destroy of {}", taskId);
cleanupType = TaskCleanupType.USER_REQUESTED_DESTROY;
taskCleanup = new SingularityTaskCleanup(user.getEmail(), cleanupType, now,
task.getTaskId(), message, actionId, runBeforeKillId);
taskManager.saveTaskCleanup(taskCleanup);
} else {
taskCleanup = new SingularityTaskCleanup(user.getEmail(), cleanupType, now,
task.getTaskId(), message, actionId, runBeforeKillId);
SingularityCreateResult result = taskManager.createTaskCleanup(taskCleanup);
if (result == SingularityCreateResult.EXISTED && userRequestedKillTakesPriority(taskId)) {
taskManager.saveTaskCleanup(taskCleanup);
} else {
while (result == SingularityCreateResult.EXISTED) {
Optional<SingularityTaskCleanup> cleanup = taskManager.getTaskCleanup(taskId);
if (cleanup.isPresent()) {
throw new WebApplicationException(Response.status(Status.CONFLICT).entity(cleanup.get()).type(MediaType.APPLICATION_JSON).build());
}
result = taskManager.createTaskCleanup(taskCleanup);
}
}
}
if (cleanupType == TaskCleanupType.USER_REQUESTED_TASK_BOUNCE) {
requestManager.addToPendingQueue(new SingularityPendingRequest(task.getTaskId().getRequestId(), task.getTaskId().getDeployId(), now, user.getEmail(),
PendingType.TASK_BOUNCE, Optional.<List<String>> absent(), Optional.<String> absent(), Optional.<Boolean> absent(), message, actionId));
}
return taskCleanup;
}
boolean userRequestedKillTakesPriority(String taskId) {
Optional<SingularityTaskCleanup> existingCleanup = taskManager.getTaskCleanup(taskId);
if (!existingCleanup.isPresent()) {
return true;
}
return existingCleanup.get().getCleanupType() != TaskCleanupType.USER_REQUESTED_DESTROY;
}
@Path("/commands/queued")
@ApiOperation(value="Retrieve a list of all the shell commands queued for execution")
public List<SingularityTaskShellCommandRequest> getQueuedShellCommands(@Auth SingularityUser user) {
authorizationHelper.checkAdminAuthorization(user);
return taskManager.getAllQueuedTaskShellCommandRequests();
}
@POST
@Path("/task/{taskId}/metadata")
@ApiOperation(value="Post metadata about a task that will be persisted along with it and displayed in the UI")
@ApiResponses({
@ApiResponse(code=400, message="Invalid metadata object or doesn't match allowed types"),
@ApiResponse(code=404, message="Task doesn't exist"),
@ApiResponse(code=409, message="Metadata with this type/timestamp already existed")
})
@Consumes({ MediaType.APPLICATION_JSON })
public void postTaskMetadata(@Auth SingularityUser user, @PathParam("taskId") String taskId, final SingularityTaskMetadataRequest taskMetadataRequest) {
SingularityTaskId taskIdObj = getTaskIdFromStr(taskId);
authorizationHelper.checkForAuthorizationByTaskId(taskId, user, SingularityAuthorizationScope.WRITE);
validator.checkActionEnabled(SingularityAction.ADD_METADATA);
WebExceptions.checkBadRequest(taskMetadataRequest.getTitle().length() < taskMetadataConfiguration.getMaxMetadataTitleLength(),
"Task metadata title too long, must be less than %s bytes", taskMetadataConfiguration.getMaxMetadataTitleLength());
int messageLength = taskMetadataRequest.getMessage().isPresent() ? taskMetadataRequest.getMessage().get().length() : 0;
WebExceptions.checkBadRequest(!taskMetadataRequest.getMessage().isPresent() || messageLength < taskMetadataConfiguration.getMaxMetadataMessageLength(),
"Task metadata message too long, must be less than %s bytes", taskMetadataConfiguration.getMaxMetadataMessageLength());
if (taskMetadataConfiguration.getAllowedMetadataTypes().isPresent()) {
WebExceptions.checkBadRequest(taskMetadataConfiguration.getAllowedMetadataTypes().get().contains(taskMetadataRequest.getType()), "%s is not one of the allowed metadata types %s",
taskMetadataRequest.getType(), taskMetadataConfiguration.getAllowedMetadataTypes().get());
}
WebExceptions.checkNotFound(taskManager.taskExistsInZk(taskIdObj), "Task %s not found in ZooKeeper (can not save metadata to tasks which have been persisted", taskIdObj);
final SingularityTaskMetadata taskMetadata = new SingularityTaskMetadata(taskIdObj, System.currentTimeMillis(), taskMetadataRequest.getType(), taskMetadataRequest.getTitle(),
taskMetadataRequest.getMessage(), user.getEmail(), taskMetadataRequest.getLevel());
SingularityCreateResult result = taskManager.saveTaskMetadata(taskMetadata);
WebExceptions.checkConflict(result == SingularityCreateResult.CREATED, "Task metadata conficted with existing metadata for %s at %s", taskMetadata.getType(), taskMetadata.getTimestamp());
}
@POST
@Path("/task/{taskId}/command")
@ApiOperation(value="Run a configured shell command against the given task")
@ApiResponses({
@ApiResponse(code=400, message="Given shell command option doesn't exist"),
@ApiResponse(code=403, message="Given shell command doesn't exist")
})
@Consumes({ MediaType.APPLICATION_JSON })
public SingularityTaskShellCommandRequest runShellCommand(@Auth SingularityUser user, @PathParam("taskId") String taskId, final SingularityShellCommand shellCommand) {
SingularityTaskId taskIdObj = getTaskIdFromStr(taskId);
authorizationHelper.checkForAuthorizationByTaskId(taskId, user, SingularityAuthorizationScope.WRITE);
validator.checkActionEnabled(SingularityAction.RUN_SHELL_COMMAND);
if (!taskManager.isActiveTask(taskId)) {
throw WebExceptions.badRequest("%s is not an active task, can't run %s on it", taskId, shellCommand.getName());
}
return startShellCommand(taskIdObj, shellCommand, user);
}
private SingularityTaskShellCommandRequest startShellCommand(SingularityTaskId taskId, final SingularityShellCommand shellCommand, SingularityUser user) {
validator.checkValidShellCommand(shellCommand);
SingularityTaskShellCommandRequest shellRequest = new SingularityTaskShellCommandRequest(taskId, user.getEmail(), System.currentTimeMillis(), shellCommand);
taskManager.saveTaskShellCommandRequestToQueue(shellRequest);
return shellRequest;
}
@GET
@Path("/task/{taskId}/command")
@ApiOperation(value="Retrieve a list of shell commands that have run for a task")
public List<SingularityTaskShellCommandHistory> getShellCommandHisotry(@Auth SingularityUser user, @PathParam("taskId") String taskId) {
authorizationHelper.checkForAuthorizationByTaskId(taskId, user, SingularityAuthorizationScope.READ);
SingularityTaskId taskIdObj = getTaskIdFromStr(taskId);
return taskManager.getTaskShellCommandHistory(taskIdObj);
}
@GET
@Path("/task/{taskId}/command/{commandName}/{commandTimestamp}")
@ApiOperation(value="Retrieve a list of shell commands updates for a particular shell command on a task")
public List<SingularityTaskShellCommandUpdate> getShellCommandHisotryUpdates(@Auth SingularityUser user, @PathParam("taskId") String taskId, @PathParam("commandName") String commandName, @PathParam("commandTimestamp") Long commandTimestamp) {
authorizationHelper.checkForAuthorizationByTaskId(taskId, user, SingularityAuthorizationScope.READ);
SingularityTaskId taskIdObj = getTaskIdFromStr(taskId);
return taskManager.getTaskShellCommandUpdates(new SingularityTaskShellCommandRequestId(taskIdObj, commandName, commandTimestamp));
}
}
|
package me.dreamteam.tardis;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Database {
// Update high scores by connecting to the website
public void dbUpdateScore() throws Exception {
String dbDistance = Integer.toString(GProperties.gameTime) + "0";
String dbUsername = GProperties.username;
try {
// Send data
URL dbConnect = new URL("http://37.187.75.63/includes/highscores/update.php?username=" + dbUsername + "&distance=" + dbDistance);
URLConnection conn = dbConnect.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
if (GProperties.debug) {
System.out.println("DEBUG: [INFO] Retrieved the following from server:" + inputLine);
}
in.close();
} catch (Exception ex) {
if (GProperties.debug) {
System.out.println("DEBUG: [WARNING] " + ex.toString());
}
}
}
// Initiate connection to the SQLite database and get unlocked achievements
public void dbConnect() {
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:SSA.db");
System.out.println("DEBUG: [INFO] Opened database successfully");
//Check Achievements
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM achievements;");
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String desc = rs.getString("desc");
int unlocked = rs.getInt("unlocked");
if (id == 1 && unlocked == 0) {
GProperties.achFalcon = false;
}
if (id == 2 && unlocked == 0) {
GProperties.achMoth = false;
}
if (id == 1 && unlocked == 1) {
GProperties.achFalcon = true;
}
if (id == 2 && unlocked == 1) {
GProperties.achMoth = true;
}
}
rs.close();
stmt.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
}
// Update achievements if the player has made the successful criteria
public void dbUpdateAchievements() {
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:SSA.db");
c.setAutoCommit(false);
System.out.println("DEBUG: [INFO] Opened database successfully");
//Check Achievements
if (GProperties.gameTime + 0 >= 150) {
stmt = c.createStatement();
String sql = "UPDATE achievements set unlocked = 1 where id=1;";
stmt.executeUpdate(sql);
c.commit();
stmt.close();
}
if (GProperties.gameTime + 0 >= 300) {
stmt = c.createStatement();
String sql = "UPDATE achievements set unlocked = 1 where id=2;";
stmt.executeUpdate(sql);
c.commit();
stmt.close();
}
} catch (Exception e) {
System.err.println("DEBUG: [ERROR]" + e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
}
// Reset the database, for testing purposes
public void dbReset() {
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:SSA.db");
c.setAutoCommit(false);
System.out.println("DEBUG: [INFO] Opened database successfully");
stmt = c.createStatement();
String sql = "UPDATE achievements set unlocked = 0 where id=1; ";
String sql2 = "UPDATE achievements set unlocked = 0 where id=2; ";
stmt.executeUpdate(sql);
stmt.executeUpdate(sql2);
c.commit();
stmt.close();
System.out.println("DEBUG: [INFO] Successfully reset database and achievements");
} catch (Exception e) {
System.err.println("DEBUG: [ERROR]" + e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
}
}
|
package com.google.sps.data;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
public final class Folder {
private String folderName;
private String folderDefaultLanguage;
private String folderKey;
private String parentKey;
public Folder(
String folderName,
String folderDefaultLanguage) {
this.folderName = folderName;
this.folderDefaultLanguage = folderDefaultLanguage;
this.folderKey = "null";
}
public Folder(Entity entity, String key) {
this.folderName = (String) entity.getProperty("folderName");
this.folderDefaultLanguage = (String) entity.getProperty("folderDefaultLanguage");
this.folderKey = key;
}
public String getFolderName() {
return this.folderName;
}
public String getFolderDefaultLanguage() {
return this.folderDefaultLanguage;
}
public String getFolderKey() {
return this.folderKey;
}
public void setFolderName(String newFolderName) {
this.folderName = newFolderName;
}
public void setFolderKey(String folderKey) {
this.folderKey = folderKey;
}
public void setParentKey(String key) {
this.parentKey = key;
}
public Entity createEntity() {
// Set owner of folder
Entity folder = new Entity("Folder", KeyFactory.stringToKey(this.parentKey));
folder.setProperty("folderName", this.folderName);
folder.setProperty("folderDefaultLanguage", this.folderDefaultLanguage);
return folder;
}
}
|
package verification.platu.logicAnalysis;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Set;
import java.util.Stack;
import javax.swing.JOptionPane;
import lpn.parser.Abstraction;
import lpn.parser.ExprTree;
import lpn.parser.LhpnFile;
import lpn.parser.Place;
import lpn.parser.Transition;
import lpn.parser.LpnDecomposition.LpnProcess;
import main.Gui;
import verification.platu.MDD.MDT;
import verification.platu.MDD.Mdd;
import verification.platu.MDD.mddNode;
import verification.platu.common.IndexObjMap;
import verification.platu.lpn.LPNTranRelation;
import verification.platu.lpn.LpnTranList;
import verification.platu.main.Options;
import verification.platu.markovianAnalysis.ProbGlobalState;
import verification.platu.markovianAnalysis.ProbGlobalStateSet;
import verification.platu.markovianAnalysis.ProbLocalStateGraph;
import verification.platu.partialOrders.DependentSet;
import verification.platu.partialOrders.DependentSetComparator;
import verification.platu.partialOrders.ProbStaticDependencySets;
import verification.platu.partialOrders.StaticDependencySets;
import verification.platu.por1.AmpleSet;
import verification.platu.project.PrjState;
import verification.platu.stategraph.State;
import verification.platu.stategraph.StateGraph;
import verification.timed_state_exploration.zoneProject.EventSet;
import verification.timed_state_exploration.zoneProject.TimedPrjState;
import verification.timed_state_exploration.zoneProject.TimedStateSet;
import verification.timed_state_exploration.zoneProject.Zone;
public class Analysis {
private LinkedList<Transition> traceCex;
protected Mdd mddMgr = null;
private HashMap<Transition, HashSet<Transition>> cachedNecessarySets = new HashMap<Transition, HashSet<Transition>>();
/*
* visitedTrans is used in computeNecessary for a disabled transition of interest, to keep track of all transitions visited during trace-back.
*/
private HashSet<Transition> visitedTrans;
HashMap<Transition, StaticDependencySets> staticDependency = new HashMap<Transition, StaticDependencySets>();
public Analysis(StateGraph[] lpnList, State[] initStateArray, LPNTranRelation lpnTranRelation, String method) {
traceCex = new LinkedList<Transition>();
mddMgr = new Mdd(lpnList.length);
if (method.equals("dfs")) {
//if (Options.getPOR().equals("off")) {
//this.search_dfs(lpnList, initStateArray);
//this.search_dfs_mdd_1(lpnList, initStateArray);
//this.search_dfs_mdd_2(lpnList, initStateArray);
//else
// this.search_dfs_por(lpnList, initStateArray, lpnTranRelation, "state");
}
else if (method.equals("bfs")==true)
this.search_bfs(lpnList, initStateArray);
else if (method == "dfs_noDisabling")
//this.search_dfs_noDisabling(lpnList, initStateArray);
this.search_dfs_noDisabling_fireOrder(lpnList, initStateArray);
}
/**
* This constructor performs dfs.
* @param lpnList
*/
public Analysis(StateGraph[] lpnList){
traceCex = new LinkedList<Transition>();
mddMgr = new Mdd(lpnList.length);
// if (method.equals("dfs")) {
// if (Options.getPOR().equals("off")) {
// //this.search_dfs(lpnList, initStateArray);
// this.search_dfsNative(lpnList, initStateArray);
// //this.search_dfs_mdd_1(lpnList, initStateArray);
// //this.search_dfs_mdd_2(lpnList, initStateArray);
// else
// //behavior analysis
// boolean BA = true;
// if(BA==true)
// CompositionalAnalysis.searchCompositional(lpnList);
// this.search_dfs_por(lpnList, initStateArray, lpnTranRelation, "state");
// else
// this.search_dfs_por(lpnList, initStateArray, lpnTranRelation, "lpn");
// else if (method.equals("bfs")==true)
// this.search_bfs(lpnList, initStateArray);
// else if (method == "dfs_noDisabling")
// //this.search_dfs_noDisabling(lpnList, initStateArray);
// this.search_dfs_noDisabling_fireOrder(lpnList, initStateArray);
}
/**
* Recursively find all reachable project states.
*/
int iterations = 0;
int stack_depth = 0;
int max_stack_depth = 0;
public void search_recursive(final StateGraph[] lpnList,
final State[] curPrjState,
final ArrayList<LinkedList<Transition>> enabledList,
HashSet<PrjState> stateTrace) {
int lpnCnt = lpnList.length;
HashSet<PrjState> prjStateSet = new HashSet<PrjState>();
stack_depth++;
if (stack_depth > max_stack_depth)
max_stack_depth = stack_depth;
iterations++;
if (iterations % 50000 == 0)
System.out.println("iterations: " + iterations
+ ", # of prjStates found: " + prjStateSet.size()
+ ", max_stack_depth: " + max_stack_depth);
for (int index = 0; index < lpnCnt; index++) {
LinkedList<Transition> curEnabledSet = enabledList.get(index);
if (curEnabledSet == null)
continue;
for (Transition firedTran : curEnabledSet) {
// while(curEnabledSet.size() != 0) {
// LPNTran firedTran = curEnabledSet.removeFirst();
// TODO: (check) Not sure if lpnList[index] is correct
State[] nextStateArray = lpnList[index].fire(lpnList, curPrjState, firedTran);
// Add nextPrjState into prjStateSet
// If nextPrjState has been traversed before, skip to the next
// enabled transition.
PrjState nextPrjState = new PrjState(nextStateArray);
if (stateTrace.contains(nextPrjState) == true)
;// System.out.println("found a cycle");
if (prjStateSet.add(nextPrjState) == false) {
continue;
}
// Get the list of enabled transition sets, and call
// findsg_recursive.
ArrayList<LinkedList<Transition>> nextEnabledList = new ArrayList<LinkedList<Transition>>();
for (int i = 0; i < lpnCnt; i++) {
if (curPrjState[i] != nextStateArray[i]) {
StateGraph Lpn_tmp = lpnList[i];
nextEnabledList.add(i, Lpn_tmp.getEnabled(nextStateArray[i]));// firedTran,
// enabledList.get(i),
// false));
} else {
nextEnabledList.add(i, enabledList.get(i));
}
}
stateTrace.add(nextPrjState);
search_recursive(lpnList, nextStateArray, nextEnabledList,
stateTrace);
stateTrace.remove(nextPrjState);
}
}
}
/**
* An iterative implement of findsg_recursive().
*
* @param sgList
* @param start
* @param curLocalStateArray
* @param enabledArray
*/
@SuppressWarnings("unchecked")
public StateSetInterface search_dfs(final StateGraph[] sgList, final State[] initStateArray) {
System.out.println("
System.out.println("---> calling function search_dfs");
double peakUsedMem = 0;
double peakTotalMem = 0;
boolean failure = false;
int tranFiringCnt = 0;
int totalStates = 1;
int numLpns = sgList.length;
//Stack<State[]> stateStack = new Stack<State[]>();
HashSet<PrjState> stateStack = new HashSet<PrjState>();
Stack<LinkedList<Transition>> lpnTranStack = new Stack<LinkedList<Transition>>();
Stack<Integer> curIndexStack = new Stack<Integer>();
//HashSet<PrjState> prjStateSet = new HashSet<PrjState>();
// Set of PrjStates that have been seen before. Set class documentation
// for how it behaves. Timing Change.
// HashMap<PrjState, PrjState> prjStateSet = generateStateSet();
StateSetInterface prjStateSet = generateStateSet();
PrjState initPrjState;
// Create the appropriate type for the PrjState depending on whether timing is
// being used or not. Timing Change.
if(!Options.getTimingAnalysisFlag()){
// If not doing timing.
if (!Options.getMarkovianModelFlag())
initPrjState = new PrjState(initStateArray);
else
initPrjState = new ProbGlobalState(initStateArray);
}
else{
// If timing is enabled.
initPrjState = new TimedPrjState(initStateArray);
// Set the initial values of the inequality variables.
//((TimedPrjState) initPrjState).updateInequalityVariables();
}
prjStateSet.add(initPrjState);
if(Options.getMarkovianModelFlag()) {
((ProbGlobalStateSet) prjStateSet).setInitState(initPrjState);
}
PrjState stateStackTop;
stateStackTop = initPrjState;
if (Options.getDebugMode())
printStateArray(stateStackTop.toStateArray(), "~~~~ stateStackTop ~~~~");
stateStack.add(stateStackTop);
constructDstLpnList(sgList);
if (Options.getDebugMode())
printDstLpnList(sgList);
LpnTranList initEnabled;
if(!Options.getTimingAnalysisFlag()){ // Timing Change.
initEnabled = sgList[0].getEnabledFromTranVector(initStateArray[0]);
// The init
}
else
{
// When timing is enabled, it is the project state that will determine
// what is enabled since it contains the zone. This indicates the zeroth zone
// contained in the project and the zeroth LPN to get the transitions from.
initEnabled = ((TimedPrjState) stateStackTop).getPossibleEvents(0, 0);
}
lpnTranStack.push(initEnabled.clone());
curIndexStack.push(0);
if (Options.getDebugMode()) {
System.out.println("+++++++ Push trans onto lpnTranStack ++++++++");
printTransList(initEnabled, "initEnabled");
}
main_while_loop: while (failure == false && stateStack.size() != 0) {
if (Options.getDebugMode()) {
System.out.println("~~~~~~~~~~~ loop begins ~~~~~~~~~~~");
}
long curTotalMem = Runtime.getRuntime().totalMemory();
long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
if (curTotalMem > peakTotalMem)
peakTotalMem = curTotalMem;
if (curUsedMem > peakUsedMem)
peakUsedMem = curUsedMem;
if (stateStack.size() > max_stack_depth)
max_stack_depth = stateStack.size();
iterations++;
if (iterations % 100000 == 0) {
System.out.println("---> #iteration " + iterations
+ "> # LPN transition firings: " + tranFiringCnt
+ ", # of prjStates found: " + totalStates
+ ", stack_depth: " + stateStack.size()
+ " used memory: " + (float) curUsedMem / 1000000
+ " free memory: "
+ (float) Runtime.getRuntime().freeMemory() / 1000000);
}
State[] curStateArray = stateStackTop.toStateArray(); //stateStack.peek();
int curIndex = curIndexStack.peek();
LinkedList<Transition> curEnabled = lpnTranStack.peek();
if (failureTranIsEnabled(curEnabled)) {
return null;
}
if (Options.getDebugMode()) {
printStateArray(curStateArray, "
printTransList(curEnabled, "+++++++ curEnabled trans ++++++++");
}
// If all enabled transitions of the current LPN are considered,
// then consider the next LPN
// by increasing the curIndex.
// Otherwise, if all enabled transitions of all LPNs are considered,
// then pop the stacks.
if (curEnabled.size() == 0) {
lpnTranStack.pop();
if (Options.getDebugMode()) {
System.out.println("+++++++ Pop trans off lpnTranStack ++++++++");
printTranStack(lpnTranStack, "***** lpnTranStack *****");
}
curIndexStack.pop();
curIndex++;
while (curIndex < numLpns) {
// System.out.println("call getEnabled on curStateArray at 1: ");
if(!Options.getTimingAnalysisFlag()){ // Timing Change
curEnabled = sgList[curIndex].getEnabledFromTranVector(curStateArray[curIndex]).clone();
}
else{
// Get the enabled transitions from the zone that are associated with
// the current LPN.
curEnabled = ((TimedPrjState) stateStackTop).getPossibleEvents(0, curIndex);
}
if (curEnabled.size() > 0) {
if (Options.getDebugMode()) {
printTransList(curEnabled, "+++++++ Push trans onto lpnTranStack ++++++++");
}
lpnTranStack.push(curEnabled);
curIndexStack.push(curIndex);
break;
}
curIndex++;
}
}
if (curIndex == numLpns) {
if (Options.getDebugMode()) {
printStateArray(stateStackTop.toStateArray(), "~~~~ Remove stateStackTop from stateStack ~~~~");
}
stateStack.remove(stateStackTop);
stateStackTop = stateStackTop.getFather();
continue;
}
Transition firedTran = curEnabled.removeLast();
if (Options.getDebugMode()) {
System.out.println("
System.out.println("Fired transition: " + firedTran.getFullLabel());
System.out.println("
}
State[] nextStateArray;
PrjState nextPrjState; // Moved this definition up. Timing Change.
// The next state depends on whether timing is in use or not.
// Timing Change.
if(!Options.getTimingAnalysisFlag()){
nextStateArray = sgList[curIndex].fire(sgList, curStateArray, firedTran);
if (!Options.getMarkovianModelFlag())
nextPrjState = new PrjState(nextStateArray);
else
nextPrjState = new ProbGlobalState(nextStateArray);
}
else{
// Get the next timed state and extract the next un-timed states.
nextPrjState = sgList[curIndex].fire(sgList, stateStackTop,
(EventSet) firedTran);
nextStateArray = nextPrjState.toStateArray();
}
tranFiringCnt++;
// Check if the firedTran causes disabling error or deadlock.
LinkedList<Transition>[] curEnabledArray = new LinkedList[numLpns];
LinkedList<Transition>[] nextEnabledArray = new LinkedList[numLpns];
for (int i = 0; i < numLpns; i++) {
LinkedList<Transition> enabledList;
if(!Options.getTimingAnalysisFlag()){ // Timing Change.
enabledList = sgList[i].getEnabledFromTranVector(curStateArray[i]);
}
else{
// Get the enabled transitions from the Zone for the appropriate
// LPN.
//enabledList = ((TimedPrjState) stateStackTop).getEnabled(i);
enabledList = ((TimedPrjState) stateStackTop).getPossibleEvents(0, i);
}
curEnabledArray[i] = enabledList;
if(!Options.getTimingAnalysisFlag()){ // Timing Change.
enabledList = sgList[i].getEnabledFromTranVector(nextStateArray[i]);
}
else{
//enabledList = ((TimedPrjState) nextPrjState).getEnabled(i);
enabledList = ((TimedPrjState) nextPrjState).getPossibleEvents(0, i);
}
nextEnabledArray[i] = enabledList;
// TODO: (temp) Stochastic model does not need disabling error?
if (Options.getReportDisablingError() && !Options.getMarkovianModelFlag()) {
Transition disabledTran = firedTran.disablingError(
curEnabledArray[i], nextEnabledArray[i]);
if (disabledTran != null) {
System.err.println("Disabling Error: "
+ disabledTran.getFullLabel() + " is disabled by "
+ firedTran.getFullLabel());
failure = true;
break main_while_loop;
}
}
}
if(!Options.getTimingAnalysisFlag()){
if (Analysis.deadLock(sgList, nextStateArray) == true) {
System.out.println("*** Verification failed: deadlock.");
failure = true;
break main_while_loop;
}
}
else{
if (Analysis.deadLock(nextEnabledArray)){
System.out.println("*** Verification failed: deadlock.");
failure = true;
JOptionPane.showMessageDialog(Gui.frame,
"The system deadlocked.", "Error",
JOptionPane.ERROR_MESSAGE);
break main_while_loop;
}
}
//PrjState nextPrjState = new PrjState(nextStateArray); // Moved earlier. Timing Change.
boolean existingState;
existingState = prjStateSet.contains(nextPrjState); //|| stateStack.contains(nextPrjState);
//existingState = prjStateSet.keySet().contains(nextPrjState); //|| stateStack.contains(nextPrjState);
if (existingState == false) {
prjStateSet.add(nextPrjState);
//prjStateSet.put(nextPrjState,nextPrjState);
stateStackTop.setChild(nextPrjState);
nextPrjState.setFather(stateStackTop);
if (Options.getMarkovianModelFlag() || Options.getOutputSgFlag()) {
stateStackTop.addNextGlobalState(firedTran, nextPrjState);
}
// else {
// if (Options.getDebugMode()) {
// printStateArray(curStateArray);
// printStateArray(nextStateArray);
// System.out.println("stateStackTop: ");
// printStateArray(stateStackTop.toStateArray());
// System.out.println("firedTran = " + firedTran.getName());
// printNextStateMap(stateStackTop.getNextStateMap());
stateStackTop = nextPrjState;
stateStack.add(stateStackTop);
lpnTranStack.push((LpnTranList) nextEnabledArray[0].clone());
curIndexStack.push(0);
totalStates++;
if (Options.getDebugMode()) {
printStateArray(stateStackTop.toStateArray(), "~~~~~~~ Add global state to stateStack ~~~~~~~");
System.out.println("+++++++ Push trans onto lpnTranStack ++++++++");
printTransList(nextEnabledArray[0], "");
printTranStack(lpnTranStack, "******** lpnTranStack ***********");
}
}
else { // existingState == true
if (Options.getMarkovianModelFlag()) {
PrjState nextPrjStInStateSet = ((ProbGlobalStateSet) prjStateSet).get(nextPrjState);
stateStackTop.addNextGlobalState(firedTran, nextPrjStInStateSet);
}
else if (Options.getOutputSgFlag()) { // non-stochastic model, but need to draw global state graph.
for (PrjState prjSt : prjStateSet) {
if (prjSt.equals(nextPrjState)) {
stateStackTop.addNextGlobalState(firedTran, prjSt);
break;
}
}
}
else {
if (Options.getOutputSgFlag()) {
if (Options.getDebugMode()) {
printStateArray(curStateArray, "******* curStateArray *******");
printStateArray(nextStateArray, "******* nextStateArray *******");
printStateArray(stateStackTop.toStateArray(), "stateStackTop: ");
System.out.println("firedTran = " + firedTran.getFullLabel());
// System.out.println("nextStateMap for stateStackTop before firedTran being added: ");
// printNextGlobalStateMap(stateStackTop.getNextStateMap());
}
}
}
}
// Build transition rate map on global state.
if (Options.getMarkovianModelFlag()) {
for (State localSt : stateStackTop.toStateArray()) {
for (Transition t : localSt.getEnabledTransitions()) {
double tranRate = ((ProbLocalStateGraph) localSt.getLpn().getStateGraph()).getTranRate(localSt, t);
((ProbGlobalState) stateStackTop).addNextGlobalTranRate(t, tranRate);
}
}
}
}
double totalStateCnt =0;
totalStateCnt = prjStateSet.size();
System.out.println("---> final numbers: # LPN transition firings: " + tranFiringCnt
+ ", # of prjStates found: " + totalStateCnt
+ ", max_stack_depth: " + max_stack_depth
+ ", peak total memory: " + peakTotalMem / 1000000 + " MB"
+ ", peak used memory: " + peakUsedMem / 1000000 + " MB");
if(Options.getTimingAnalysisFlag() && !failure){
JOptionPane.showMessageDialog(Gui.frame,
"Verification was successful.", "Success",
JOptionPane.INFORMATION_MESSAGE);
System.out.println(prjStateSet.toString());
}
if (Options.getOutputLogFlag())
writePerformanceResultsToLogFile(false, tranFiringCnt, totalStateCnt, peakTotalMem / 1000000, peakUsedMem / 1000000);
if (Options.getOutputSgFlag()) {
System.out.println("outputSGPath = " + Options.getPrjSgPath());
// TODO: Andrew: I don't think you need the toHashSet() now.
//drawGlobalStateGraph(sgList, prjStateSet.toHashSet(), true);
drawGlobalStateGraph(sgList, initPrjState, prjStateSet);
}
// try{
// File stateFile = new File(Options.getPrjSgPath() + Options.getLogName() + ".txt");
// FileWriter fileWritter = new FileWriter(stateFile,true);
// BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
// // TODO: Need to merge variable vectors from different local states.
// ArrayList<Integer> vector;
// String curPrjStInfo = "";
// for (PrjState prjSt : prjStateSet) {
// // marking
// curPrjStInfo += "marking: ";
// for (State localSt : prjSt.toStateArray())
// curPrjStInfo += intArrayToString("markings", localSt) + "\n";
// // variable vector
// curPrjStInfo += "var values: ";
// for (State localSt : prjSt.toStateArray()) {
// localSt.getLpn().getAllVarsWithValuesAsInt(localSt.getVariableVector());
// //curPrjStInfo += intArrayToString("vars", localSt)+ "\n";
// // tranVector
// curPrjStInfo += "tran vector: ";
// for (State localSt : prjSt.toStateArray())
// curPrjStInfo += boolArrayToString("enabled trans", localSt)+ "\n";
// bufferWritter.write(curPrjStInfo);
// //bufferWritter.flush();
// bufferWritter.close();
// System.out.println("Done writing state file.");
// }catch(IOException e){
// e.printStackTrace();
return prjStateSet;
}
// private boolean failureCheck(LinkedList<Transition> curEnabled) {
// boolean failureTranIsEnabled = false;
// for (Transition tran : curEnabled) {
// if (tran.isFail()) {
// JOptionPane.showMessageDialog(Gui.frame,
// "Failure transition " + tran.getLabel() + " is enabled.", "Error",
// JOptionPane.ERROR_MESSAGE);
// failureTranIsEnabled = true;
// break;
// return failureTranIsEnabled;
// /**
// * Generates the appropriate version of a HashSet<PrjState> for storing
// * the "already seen" set of project states.
// * @return
// * Returns a HashSet<PrjState>, a StateSet, or a ProbGlobalStateSet
// * depending on the type.
// */
// private HashSet<PrjState> generateStateSet(){
// boolean timed = Options.getTimingAnalysisFlag();
// boolean subsets = Zone.getSubsetFlag();
// boolean supersets = Zone.getSupersetFlag();
// if(Options.getMarkovianModelFlag()){
// return new ProbGlobalStateSet();
// else if(timed && (subsets || supersets)){
// return new TimedStateSet();
// return new HashSet<PrjState>();
/**
* Generates the appropriate version of a HashSet<PrjState> for storing
* the "already seen" set of project states.
* @return
* Returns a HashSet<PrjState>, a StateSet, or a ProbGlobalStateSet
* depending on the type.
*/
private StateSetInterface generateStateSet(){
boolean timed = Options.getTimingAnalysisFlag();
boolean subsets = Zone.getSubsetFlag();
boolean supersets = Zone.getSupersetFlag();
if(Options.getMarkovianModelFlag()){
return new ProbGlobalStateSet();
}
else if(timed && (subsets || supersets)){
return new TimedStateSet();
}
return new HashSetWrapper();
}
private boolean failureTranIsEnabled(LinkedList<Transition> curPersistentTrans) {
boolean failureTranIsEnabled = false;
for (Transition tran : curPersistentTrans) {
if (tran.isFail()) {
if(Zone.get_writeLogFile() != null){
try {
Zone.get_writeLogFile().write(tran.getLabel());
Zone.get_writeLogFile().newLine();
} catch (IOException e) {
e.printStackTrace();
}
}
JOptionPane.showMessageDialog(Gui.frame,
"Failure transition " + tran.getLabel() + " is enabled.", "Error",
JOptionPane.ERROR_MESSAGE);
failureTranIsEnabled = true;
break;
}
}
return failureTranIsEnabled;
}
public void drawGlobalStateGraph(StateGraph[] sgList, PrjState initGlobalState, StateSetInterface globalStateSet) {
try {
String fileName = null;
if (Options.getPOR().toLowerCase().equals("off")) {
fileName = Options.getPrjSgPath() + "full_sg.dot";
}
else {
fileName = Options.getPrjSgPath() + Options.getPOR().toLowerCase() + "_"
+ Options.getCycleClosingMthd().toLowerCase() + "_"
+ Options.getCycleClosingPersistentMethd().toLowerCase() + "_sg.dot";
}
BufferedWriter out = new BufferedWriter(new FileWriter(fileName));
NumberFormat num = NumberFormat.getNumberInstance();//NumberFormat.getInstance();
num.setMaximumFractionDigits(6);
num.setGroupingUsed(false);
out.write("digraph G {\n");
for (PrjState curGlobalState : globalStateSet) {
// Build composite current global state.
String curVarNames = "";
String curVarValues = "";
String curMarkings = "";
String curEnabledTrans = "";
String curGlobalStateIndex = "";
String curGlobalStateProb = null;
HashMap<String, Integer> vars = new HashMap<String, Integer>();
for (State curLocalState : curGlobalState.toStateArray()) {
curGlobalStateIndex = curGlobalStateIndex + "_" + "S" + curLocalState.getIndex();
LhpnFile curLpn = curLocalState.getLpn();
for(int i = 0; i < curLpn.getVarIndexMap().size(); i++) {
vars.put(curLpn.getVarIndexMap().getKey(i), curLocalState.getVariableVector()[i]);
}
curMarkings = curMarkings + "," + intArrayToString("markings", curLocalState);
if (!boolArrayToString("enabled trans", curLocalState).equals(""))
curEnabledTrans = curEnabledTrans + "," + boolArrayToString("enabled trans", curLocalState);
}
for (String vName : vars.keySet()) {
Integer vValue = vars.get(vName);
curVarValues = curVarValues + vValue + ", ";
curVarNames = curVarNames + vName + ", ";
}
if (!curVarNames.isEmpty() && !curVarValues.isEmpty()) {
curVarNames = curVarNames.substring(0, curVarNames.lastIndexOf(","));
curVarValues = curVarValues.substring(0, curVarValues.lastIndexOf(","));
}
curMarkings = curMarkings.substring(curMarkings.indexOf(",")+1, curMarkings.length());
curEnabledTrans = curEnabledTrans.substring(curEnabledTrans.indexOf(",")+1, curEnabledTrans.length());
if (Options.getMarkovianModelFlag()) {
// State probability after steady state analysis.
curGlobalStateProb = num.format(((ProbGlobalState) curGlobalState).getCurrentProb());
}
curGlobalStateIndex = curGlobalStateIndex.substring(curGlobalStateIndex.indexOf("_")+1, curGlobalStateIndex.length());
if (curGlobalState.equals(initGlobalState)) {
out.write("Inits[shape=plaintext, label=\"<" + curVarNames + ">\"]\n");
if (!Options.getMarkovianModelFlag())
out.write(curGlobalStateIndex + "[shape=ellipse,label=\"" + curGlobalStateIndex + "\\n<"+curVarValues+">"
+ "\\n<"+curEnabledTrans+">" + "\\n<"+curMarkings+">" + "\", style=filled]\n");
else
out.write(curGlobalStateIndex + "[shape=ellipse,label=\"" + curGlobalStateIndex + "\\n<"+curVarValues+">"
+ "\\n<"+curEnabledTrans+">" + "\\n<"+curMarkings+">" + "\\nProb = " + curGlobalStateProb + "\", style=filled]\n");
}
else {
if (!Options.getMarkovianModelFlag())
out.write(curGlobalStateIndex + "[shape=ellipse,label=\"" + curGlobalStateIndex + "\\n<"+curVarValues+">"
+ "\\n<"+curEnabledTrans+">" + "\\n<"+curMarkings+">" + "\"]\n");
else
out.write(curGlobalStateIndex + "[shape=ellipse,label=\"" + curGlobalStateIndex + "\\n<"+curVarValues+">"
+ "\\n<"+curEnabledTrans+">" + "\\n<"+curMarkings+">" + "\\nProb = " + curGlobalStateProb + "\"]\n");
}
// Build transitions to next global states.
// Set <Transition> outgoingTrans = null;
// if (!Options.getMarkovianModelFlag()) {
// outgoingTrans = curGlobalState.getOutgoingTrans();
// else {
// outgoingTrans = ((ProbGlobalState) curGlobalState).getOutgoingTranSetForProbGlobalState();
//for (Transition outTran : outgoingTrans) {
for (Transition outTran : curGlobalState.getNextGlobalStateMap().keySet()) {
PrjState nextGlobalState = null;
nextGlobalState = curGlobalState.getNextGlobalStateMap().get(outTran);
String nextGlobalStateIndex = "";
for (State nextLocalState : nextGlobalState.toStateArray()) {
nextGlobalStateIndex = nextGlobalStateIndex + "_" + "S" + nextLocalState.getIndex();
}
nextGlobalStateIndex = nextGlobalStateIndex.substring(nextGlobalStateIndex.indexOf("_")+1, nextGlobalStateIndex.length());
String outTranName = outTran.getLabel();
if (!Options.getMarkovianModelFlag()) {
if (outTran.isFail() && !outTran.isPersistent())
out.write(curGlobalStateIndex + "->" + nextGlobalStateIndex + "[label=\"" + outTranName + "\", fontcolor=red]\n");
else if (!outTran.isFail() && outTran.isPersistent())
out.write(curGlobalStateIndex + "->" + nextGlobalStateIndex + "[label=\"" + outTranName + "\", fontcolor=blue]\n");
else if (outTran.isFail() && outTran.isPersistent())
out.write(curGlobalStateIndex + "->" + nextGlobalStateIndex + "[label=\"" + outTranName + "\", fontcolor=purple]\n");
else
out.write(curGlobalStateIndex + "->" + nextGlobalStateIndex + "[label=\"" + outTranName + "\"]\n");
}
else {
State localState = curGlobalState.toStateArray()[outTran.getLpn().getLpnIndex()];
String outTranRate = num.format(((ProbLocalStateGraph) localState.getStateGraph()).getTranRate(localState, outTran));
if (outTran.isFail() && !outTran.isPersistent())
out.write(curGlobalStateIndex + "->" + nextGlobalStateIndex
+ "[label=\"" + outTranName + "\\n" + outTranRate + "\", fontcolor=red]\n");
else if (!outTran.isFail() && outTran.isPersistent())
out.write(curGlobalStateIndex + "->" + nextGlobalStateIndex
+ "[label=\"" + outTranName + "\\n" + outTranRate + "\", fontcolor=blue]\n");
else if (outTran.isFail() && outTran.isPersistent())
out.write(curGlobalStateIndex + "->" + nextGlobalStateIndex
+ "[label=\"" + outTranName + "\\n" + outTranRate + "\", fontcolor=purple]\n");
else
out.write(curGlobalStateIndex + "->" + nextGlobalStateIndex
+ "[label=\"" + outTranName + "\\n" + outTranRate + "\"]\n");
}
}
}
out.write("}");
out.close();
}
catch (Exception e) {
e.printStackTrace();
System.err.println("Error producing global state graph as dot file.");
}
}
private void drawDependencyGraphs(LhpnFile[] lpnList) {
String fileName = Options.getPrjSgPath() + "dependencyGraph.dot";
BufferedWriter out;
try {
out = new BufferedWriter(new FileWriter(fileName));
out.write("digraph G {\n");
for (Transition curTran : staticDependency.keySet()) {
String curTranStr = curTran.getLpn().getLabel() + "_" + curTran.getLabel();
out.write(curTranStr + "[shape=\"box\"];");
out.newLine();
}
for (Transition curTran : staticDependency.keySet()) {
StaticDependencySets curStaticSets = staticDependency.get(curTran);
String curTranStr = curTran.getLpn().getLabel() + "_" + curTran.getLabel();
for (Transition curTranInDisable : curStaticSets.getOtherTransDisableCurTranSet()) {
String curTranInDisableStr = curTranInDisable.getLpn().getLabel() + "_" + curTranInDisable.getLabel();
out.write(curTranInDisableStr + "->" + curTranStr + "[color=\"chocolate\"];");
out.newLine();
}
// for (Transition curTranInDisable : curStaticSets.getCurTranDisableOtherTransSet()) {
// String curTranInDisableStr = lpnList[curTranInDisable.getLpnIndex()].getLabel()
// + "_" + lpnList[curTranInDisable.getLpnIndex()].getTransition(curTranInDisable.getTranIndex()).getName();
// out.write(curTranStr + "->" + curTranInDisableStr + "[color=\"chocolate\"];");
// out.newLine();
// for (Transition curTranInDisable : curStaticSets.getDisableSet()) {
// String curTranInDisableStr = lpnList[curTranInDisable.getLpnIndex()].getLabel()
// + "_" + lpnList[curTranInDisable.getLpnIndex()].getTransition(curTranInDisable.getTranIndex()).getName();
// out.write(curTranStr + "->" + curTranInDisableStr + "[color=\"blue\"];");
// out.newLine();
HashSet<Transition> enableByBringingToken = new HashSet<Transition>();
for (Place p : curTran.getPreset()) {
for (Transition presetTran : p.getPreset()) {
enableByBringingToken.add(presetTran);
}
}
for (Transition curTranInCanEnable : enableByBringingToken) {
String curTranInCanEnableStr = curTranInCanEnable.getLpn().getLabel() + "_" + curTranInCanEnable.getLabel();
out.write(curTranStr + "->" + curTranInCanEnableStr + "[color=\"mediumaquamarine\"];");
out.newLine();
}
for (HashSet<Transition> canEnableOneConjunctSet : curStaticSets.getOtherTransSetCurTranEnablingTrue()) {
for (Transition curTranInCanEnable : canEnableOneConjunctSet) {
String curTranInCanEnableStr = curTranInCanEnable.getLpn().getLabel() + "_" + curTranInCanEnable.getLabel();
out.write(curTranStr + "->" + curTranInCanEnableStr + "[color=\"deepskyblue\"];");
out.newLine();
}
}
}
out.write("}");
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private String intArrayToString(String type, State curState) {
String arrayStr = "";
if (type.equals("markings")) {
for (int i=0; i< curState.getMarking().length; i++) {
if (curState.getMarking()[i] == 1) {
arrayStr = arrayStr + curState.getLpn().getPlaceList()[i] + ",";
}
// String tranName = curState.getLpn().getAllTransitions()[i].getName();
// if (curState.getTranVector()[i])
// System.out.println(tranName + " " + "Enabled");
// else
// System.out.println(tranName + " " + "Not Enabled");
}
arrayStr = arrayStr.substring(0, arrayStr.lastIndexOf(","));
}
else if (type.equals("vars")) {
for (int i=0; i< curState.getVariableVector().length; i++) {
arrayStr = arrayStr + curState.getVariableVector()[i] + ",";
}
if (arrayStr.contains(","))
arrayStr = arrayStr.substring(0, arrayStr.lastIndexOf(","));
}
return arrayStr;
}
private String boolArrayToString(String type, State curState) {
String arrayStr = "";
if (type.equals("enabled trans")) {
for (int i=0; i< curState.getTranVector().length; i++) {
if (curState.getTranVector()[i]) {
//arrayStr = arrayStr + curState.getLpn().getAllTransitions()[i].getFullLabel() + ", ";
arrayStr = arrayStr + curState.getLpn().getAllTransitions()[i].getLabel() + ", ";
}
}
if (arrayStr != "")
arrayStr = arrayStr.substring(0, arrayStr.lastIndexOf(","));
}
return arrayStr;
}
private void printStateArray(State[] stateArray, String title) {
if (title != null)
System.out.println(title);
for (int i=0; i<stateArray.length; i++) {
System.out.println("S" + stateArray[i].getIndex() + "(" + stateArray[i].getLpn().getLabel() +"): ");
System.out.println("\tmarkings: " + intArrayToString("markings", stateArray[i]));
System.out.println("\tvar values: " + intArrayToString("vars", stateArray[i]));
System.out.println("\tenabled trans: " + boolArrayToString("enabled trans", stateArray[i]));
}
System.out.println("
}
private void printTransList(LinkedList<Transition> tranList, String title) {
if (title != null && !title.equals(""))
System.out.println("+++++++" + title + "+++++++");
for (int i=0; i< tranList.size(); i++)
System.out.println(tranList.get(i).getFullLabel() + ", ");
System.out.println("+++++++++++++");
}
// private void writeIntegerStackToDebugFile(Stack<Integer> curIndexStack, String title) {
// if (title != null)
// System.out.println(title);
// for (int i=0; i < curIndexStack.size(); i++) {
// System.out.println(title + "[" + i + "]" + curIndexStack.get(i));
private void printDstLpnList(StateGraph[] lpnList) {
System.out.println("++++++ dstLpnList ++++++");
for (int i=0; i<lpnList.length; i++) {
LhpnFile curLPN = lpnList[i].getLpn();
System.out.println("LPN: " + curLPN.getLabel());
Transition[] allTrans = curLPN.getAllTransitions();
for (int j=0; j< allTrans.length; j++) {
System.out.println(allTrans[j].getLabel() + ": ");
for (int k=0; k< allTrans[j].getDstLpnList().size(); k++) {
System.out.println(allTrans[j].getDstLpnList().get(k).getLabel() + ",");
}
System.out.print("\n");
}
System.out.println("
}
System.out.println("++++++++++++++++++++");
}
private void constructDstLpnList(StateGraph[] sgList) {
for (int i=0; i<sgList.length; i++) {
LhpnFile curLPN = sgList[i].getLpn();
Transition[] allTrans = curLPN.getAllTransitions();
for (int j=0; j<allTrans.length; j++) {
Transition curTran = allTrans[j];
for (int k=0; k<sgList.length; k++) {
curTran.setDstLpnList(sgList[k].getLpn());
}
}
}
}
/**
* This method performs first-depth search on an array of LPNs and applies partial order reduction technique with trace-back on LPNs.
* @param sgList
* @param initStateArray
* @param cycleClosingMthdIndex
* @return
*/
public StateSetInterface searchPOR_taceback(final StateGraph[] sgList, final State[] initStateArray) {
System.out.println("---> calling function searchPOR_traceback");
System.out.println("---> " + Options.getPOR());
System.out.println("---> " + Options.getCycleClosingMthd());
System.out.println("---> " + Options.getCycleClosingPersistentMethd());
double peakUsedMem = 0;
double peakTotalMem = 0;
boolean failure = false;
int tranFiringCnt = 0;
int totalStates = 1;
int numLpns = sgList.length;
LhpnFile[] lpnList = new LhpnFile[numLpns];
for (int i=0; i<numLpns; i++) {
lpnList[i] = sgList[i].getLpn();
}
HashSet<PrjState> stateStack = new HashSet<PrjState>();
Stack<LinkedList<Transition>> lpnTranStack = new Stack<LinkedList<Transition>>();
StateSetInterface prjStateSet = generateStateSet();
PrjState initPrjState;
// Create the appropriate type for the PrjState depending on whether timing is
// being used or not.
if (!Options.getMarkovianModelFlag()) {
initPrjState = new PrjState(initStateArray);
}
else {
initPrjState = new ProbGlobalState(initStateArray);
}
prjStateSet.add(initPrjState);
if(Options.getMarkovianModelFlag()) {
((ProbGlobalStateSet) prjStateSet).setInitState(initPrjState);
}
PrjState stateStackTop = initPrjState;
if (Options.getDebugMode())
printStateArray(stateStackTop.toStateArray(), "%%%%%%% stateStackTop %%%%%%%%");
stateStack.add(stateStackTop);
constructDstLpnList(sgList);
if (Options.getDebugMode())
printDstLpnList(sgList);
// Determine statistically the dependency relations between transitions.
HashMap<Integer, Transition[]> allTransitions = new HashMap<Integer, Transition[]>(lpnList.length);
//HashMap<Transition, StaticSets> staticSetsMap = new HashMap<Transition, StaticSets>();
HashMap<Transition, Integer> allProcessTransInOneLpn = new HashMap<Transition, Integer>();
HashMap<Transition, LpnProcess> allTransitionsToLpnProcesses = new HashMap<Transition, LpnProcess>();
for (int lpnIndex=0; lpnIndex<lpnList.length; lpnIndex++) {
allTransitions.put(lpnIndex, lpnList[lpnIndex].getAllTransitions());
Abstraction abs = new Abstraction(lpnList[lpnIndex]);
abs.decomposeLpnIntoProcesses();
allProcessTransInOneLpn = (HashMap<Transition, Integer>)abs.getTransWithProcIDs();
HashMap<Integer, LpnProcess> processMapForOneLpn = new HashMap<Integer, LpnProcess>();
for (Transition curTran: allProcessTransInOneLpn.keySet()) {
Integer procId = allProcessTransInOneLpn.get(curTran);
if (!processMapForOneLpn.containsKey(procId)) {
LpnProcess newProcess = new LpnProcess(procId);
newProcess.addTranToProcess(curTran);
if (curTran.getPreset() != null) {
if (newProcess.getStateMachineFlag()
&& ((curTran.getPreset().length > 1)
|| (curTran.getPostset().length > 1))) {
newProcess.setStateMachineFlag(false);
}
Place[] preset = curTran.getPreset();
for (Place p : preset) {
newProcess.addPlaceToProcess(p);
}
}
processMapForOneLpn.put(procId, newProcess);
allTransitionsToLpnProcesses.put(curTran, newProcess);
}
else {
LpnProcess curProcess = processMapForOneLpn.get(procId);
curProcess.addTranToProcess(curTran);
if (curTran.getPreset() != null) {
if (curProcess.getStateMachineFlag()
&& (curTran.getPreset().length > 1
|| curTran.getPostset().length > 1)) {
curProcess.setStateMachineFlag(false);
}
Place[] preset = curTran.getPreset();
for (Place p : preset) {
curProcess.addPlaceToProcess(p);
}
}
allTransitionsToLpnProcesses.put(curTran, curProcess);
}
}
}
HashMap<Transition, Integer> tranFiringFreq = null;
// if (Options.getUseDependentQueue())
tranFiringFreq = new HashMap<Transition, Integer>(allTransitions.keySet().size());
// Need to build conjuncts for each transition's enabling condition first before dealing with dependency and enable sets.
for (int lpnIndex=0; lpnIndex<lpnList.length; lpnIndex++) {
for (Transition curTran: allTransitions.get(lpnIndex)) {
if (curTran.getEnablingTree() != null)
curTran.buildConjunctsOfEnabling(curTran.getEnablingTree());
}
}
for (int lpnIndex=0; lpnIndex<lpnList.length; lpnIndex++) {
if (Options.getDebugMode()) {
System.out.println("=======LPN = " + lpnList[lpnIndex].getLabel() + "=======");
}
for (Transition curTran: allTransitions.get(lpnIndex)) {
StaticDependencySets curStatic = null;
if (!Options.getMarkovianModelFlag())
curStatic = new StaticDependencySets(curTran, allTransitionsToLpnProcesses);
else
curStatic = new ProbStaticDependencySets(curTran, allTransitionsToLpnProcesses);
curStatic.buildOtherTransSetCurTranEnablingTrue();
curStatic.buildCurTranDisableOtherTransSet();
if (Options.getPORdeadlockPreserve())
curStatic.buildOtherTransDisableCurTranSet();
else
curStatic.buildModifyAssignSet();
if (Options.getMarkovianModelFlag() && Options.getTranRatePorDef().toLowerCase().equals("full")) {
((ProbStaticDependencySets) curStatic).buildCurTranModifyOtherTransRatesSet();
((ProbStaticDependencySets) curStatic).buildOtherTransModifyCurTranRateSet();
}
staticDependency.put(curTran, curStatic);
tranFiringFreq.put(curTran, 0);
}
}
if (Options.getDebugMode()) {
printStaticSetsMap(lpnList);
}
LpnTranList initPersistentTrans = getPersistentSet(initStateArray, null, tranFiringFreq, sgList, lpnList, prjStateSet, stateStackTop);
lpnTranStack.push(initPersistentTrans);
if (Options.getDebugMode()) {
printTransList(initPersistentTrans, "+++++++ Push trans onto lpnTranStack @ 1++++++++");
drawDependencyGraphs(lpnList);
}
updateLocalPersistentSetTbl(initPersistentTrans, sgList, initStateArray);
main_while_loop: while (failure == false && stateStack.size() != 0) {
if (Options.getDebugMode()) {
System.out.println("~~~~~~~~~~~ loop begins ~~~~~~~~~~~");
}
long curTotalMem = Runtime.getRuntime().totalMemory();
long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
if (curTotalMem > peakTotalMem)
peakTotalMem = curTotalMem;
if (curUsedMem > peakUsedMem)
peakUsedMem = curUsedMem;
if (stateStack.size() > max_stack_depth)
max_stack_depth = stateStack.size();
iterations++;
if (iterations % 100000 == 0) {
System.out.println("---> #iteration " + iterations
+ "> # LPN transition firings: " + tranFiringCnt
+ ", # of prjStates found: " + totalStates
+ ", stack_depth: " + stateStack.size()
+ " used memory: " + (float) curUsedMem / 1000000
+ " free memory: "
+ (float) Runtime.getRuntime().freeMemory() / 1000000);
}
State[] curStateArray = stateStackTop.toStateArray(); //stateStack.peek();
LinkedList<Transition> curPersistentTrans = lpnTranStack.peek();
if (failureTranIsEnabled(curPersistentTrans)) {
return null;
}
if (curPersistentTrans.size() == 0) {
lpnTranStack.pop();
prjStateSet.add(stateStackTop);
if (Options.getDebugMode()) {
System.out.println("+++++++ Pop trans off lpnTranStack ++++++++");
printTranStack(lpnTranStack, "
System.out.println("
printPrjStateSet(prjStateSet);
System.out.println("%%%%%%% Remove stateStackTop from stateStack %%%%%%%%");
}
stateStack.remove(stateStackTop);
stateStackTop = stateStackTop.getFather();
continue;
}
Transition firedTran = curPersistentTrans.removeLast();
//Transition firedTran = curPersistentTrans.removelast();
if (Options.getDebugMode()) {
System.out.println("
System.out.println("Fired Transition: " + firedTran.getFullLabel());
System.out.println("
}
Integer freq = tranFiringFreq.get(firedTran) + 1;
tranFiringFreq.put(firedTran, freq);
// if (Options.getDebugMode()) {
// System.out.println("~~~~~~tranFiringFreq~~~~~~~");
// //printHashMap(tranFiringFreq, sgList);
State[] nextStateArray = sgList[firedTran.getLpn().getLpnIndex()].fire(sgList, curStateArray, firedTran);
tranFiringCnt++;
PrjState nextPrjState;
if (!Options.getMarkovianModelFlag())
nextPrjState = new PrjState(nextStateArray);
else
nextPrjState = new ProbGlobalState(nextStateArray);
// Check if the firedTran causes disabling error or deadlock.
// TODO: (temp) Stochastic model does not need disabling error?
if (Options.getReportDisablingError() && !Options.getMarkovianModelFlag()) {
for (int i=0; i<numLpns; i++) {
Transition disabledTran = firedTran.disablingError(curStateArray[i].getEnabledTransitions(), nextStateArray[i].getEnabledTransitions());
if (disabledTran != null) {
System.err.println("Disabling Error: "
+ disabledTran.getFullLabel() + " is disabled by "
+ firedTran.getFullLabel());
failure = true;
break main_while_loop;
}
}
}
LpnTranList nextPersistentTrans = new LpnTranList();
nextPersistentTrans = getPersistentSet(curStateArray, nextStateArray, tranFiringFreq, sgList, lpnList, prjStateSet, stateStackTop);
// check for possible deadlock
if (nextPersistentTrans.size() == 0) {
System.out.println("*** Verification failed: deadlock.");
failure = true;
break main_while_loop;
}
//updateLocalPersistentSetTbl(nextPersistentTrans, sgList, nextStateArray);
// Moved earlier.
// PrjState nextPrjState;
// if (!Options.getMarkovianModelFlag())
// nextPrjState = new PrjState(nextStateArray);
// else
// nextPrjState = new ProbGlobalState(nextStateArray);
boolean existingState;
existingState = prjStateSet.contains(nextPrjState);//|| stateStack.contains(nextPrjState);
if (existingState == false) {
if (Options.getDebugMode()) {
System.out.println("%%%%%%% existingSate == false %%%%%%%%");
printStateArray(curStateArray, "******* curStateArray *******");
printStateArray(nextStateArray, "******* nextStateArray *******");
printStateArray(stateStackTop.toStateArray(), "stateStackTop");
System.out.println("firedTran = " + firedTran.getFullLabel());
// printNextGlobalStateMap(stateStackTop.getNextStateMap());
System.out.println("
}
prjStateSet.add(nextPrjState);
//updateLocalPersistentSetTbl(nextPersistentTrans, sgList, nextStateArray);
stateStackTop.setChild(nextPrjState);
nextPrjState.setFather(stateStackTop);
if (Options.getMarkovianModelFlag() || Options.getOutputSgFlag()) {
stateStackTop.addNextGlobalState(firedTran, nextPrjState);
}
stateStackTop = nextPrjState;
stateStack.add(stateStackTop);
lpnTranStack.push(nextPersistentTrans.clone());
updateLocalPersistentSetTbl(nextPersistentTrans, sgList, nextStateArray);
totalStates++;
if (Options.getDebugMode()) {
printStateArray(stateStackTop.toStateArray(), "%%%%%%% Add global state to stateStack %%%%%%%%");
printTransList(nextPersistentTrans, "+++++++ Push trans onto lpnTranStack @ 2++++++++");
}
}
else { // existingState = true
if (Options.getMarkovianModelFlag()) {
PrjState nextPrjStInStateSet = ((ProbGlobalStateSet) prjStateSet).get(nextPrjState);
stateStackTop.addNextGlobalState(firedTran, nextPrjStInStateSet);
}
else if (Options.getOutputSgFlag()) { // non-stochastic model, but need to draw global state graph.
for (PrjState prjSt : prjStateSet) {
if (prjSt.toStateArray().equals(nextPrjState.toStateArray())) {
stateStackTop.addNextGlobalState(firedTran, prjSt);
break;
}
}
}
else {
if (Options.getOutputSgFlag()) {
if (Options.getDebugMode()) {
printStateArray(curStateArray, "******* curStateArray *******");
printStateArray(nextStateArray, "******* nextStateArray *******");
System.out.println("stateStackTop: ");
printStateArray(stateStackTop.toStateArray(), "stateStackTop: ");
System.out.println("firedTran = " + firedTran.getFullLabel());
// System.out.println("nextStateMap for stateStackTop before firedTran being added: ");
// printNextGlobalStateMap(stateStackTop.getNextStateMap());
System.out.println("
}
}
}
if (!Options.getCycleClosingMthd().toLowerCase().equals("no_cycleclosing")) {
// Cycle closing check
if (prjStateSet.contains(nextPrjState) && stateStack.contains(nextPrjState)) {
if (Options.getDebugMode()) {
System.out.println("
System.out.println("Global state " + printGlobalStateLabel(nextPrjState) + " has been seen before and is on state stack.");
}
HashSet<Transition> nextPersistentSet = new HashSet<Transition>();
HashSet<Transition> curPersistentSet = new HashSet<Transition>();
for (Transition t : nextPersistentTrans)
nextPersistentSet.add(t);
for (State curSt : curStateArray) {
if (curSt.getStateGraph().getEnabledSetTbl().get(curSt) != null) {
curPersistentSet.addAll(curSt.getStateGraph().getEnabledSetTbl().get(curSt));
}
}
LpnTranList newNextPersistent = new LpnTranList();
newNextPersistent = computeCycleClosingTrans(curStateArray, nextStateArray, staticDependency,
tranFiringFreq, sgList, prjStateSet, nextPrjState, nextPersistentSet, curPersistentSet, stateStack);
if (newNextPersistent != null && !newNextPersistent.isEmpty()) {
//LpnTranList newNextPersistentTrans = getLpnTranList(newNextPersistent, sgList);
// Yohji
// if (Options.getDebugMode()) {
// printStateArray(stateStackTop.toStateArray(), "%%%%%%% Add state to stateStack %%%%%%%%");
// System.out.println("stateStackTop: ");
// printStateArray(stateStackTop.toStateArray(), "stateStackTop");
//// System.out.println("nextStateMap for stateStackTop: ");
//// printNextGlobalStateMap(nextPrjState.getNextStateMap());
lpnTranStack.push(newNextPersistent.clone());
updateLocalPersistentSetTbl(newNextPersistent, sgList, nextStateArray);
if (Options.getDebugMode()) {
printTransList(newNextPersistent, "+++++++ Push these trans onto lpnTranStack @ Cycle Closing ++++++++");
printTranStack(lpnTranStack, "******* lpnTranStack ***************");
}
}
}
}
else {
updateLocalPersistentSetTbl(nextPersistentTrans, sgList, nextStateArray);
}
}
}
double totalStateCnt = prjStateSet.size();
System.out.println("---> final numbers: # LPN transition firings: " + tranFiringCnt
+ ", # of prjStates found: " + totalStateCnt
+ ", max_stack_depth: " + max_stack_depth
+ ", peak total memory: " + peakTotalMem / 1000000 + " MB"
+ ", peak used memory: " + peakUsedMem / 1000000 + " MB");
if (Options.getOutputLogFlag())
writePerformanceResultsToLogFile(true, tranFiringCnt, totalStateCnt, peakTotalMem / 1000000, peakUsedMem / 1000000);
if (Options.getOutputSgFlag()) {
System.out.println("outputSGPath = " + Options.getPrjSgPath());
drawGlobalStateGraph(sgList, initPrjState, prjStateSet);
}
return prjStateSet;
}
/**
* Print the prjState's label. The label consists of full labels of each local state that composes it.
* @param prjState
* @return
*/
private String printGlobalStateLabel(PrjState prjState) {
String prjStateLabel = "";
for (State local : prjState.toStateArray()) {
prjStateLabel += local.getFullLabel() + "_";
}
return prjStateLabel.substring(0, prjStateLabel.lastIndexOf("_"));
}
private void writePerformanceResultsToLogFile(boolean isPOR, int tranFiringCnt, double totalStateCnt,
double peakTotalMem, double peakUsedMem) {
try {
String fileName = null;
if (isPOR) {
fileName = Options.getPrjSgPath() + Options.getLogName() + "_" + Options.getPOR() + "_"
+ Options.getCycleClosingMthd() + "_" + Options.getCycleClosingPersistentMethd() + ".log";
}
else
fileName = Options.getPrjSgPath() + Options.getLogName() + "_full" + ".log";
BufferedWriter out = new BufferedWriter(new FileWriter(fileName));
out.write("tranFiringCnt" + "\t" + "prjStateCnt" + "\t" + "maxStackDepth" + "\t" + "peakTotalMem(MB)" + "\t" + "peakUsedMem(MB)\n");
out.write(tranFiringCnt + "\t" + totalStateCnt + "\t" + max_stack_depth + "\t" + peakTotalMem + "\t"
+ peakUsedMem + "\n");
out.close();
}
catch (Exception e) {
e.printStackTrace();
System.err.println("Error producing performance results.");
}
}
private void printTranStack(Stack<LinkedList<Transition>> lpnTranStack, String title) {
if (title != null)
System.out.println(title);
for (int i=0; i<lpnTranStack.size(); i++) {
LinkedList<Transition> tranList = lpnTranStack.get(i);
for (int j=0; j<tranList.size(); j++) {
System.out.println(tranList.get(j).getFullLabel());
}
System.out.println("
}
}
private void printNextGlobalStateMap(HashMap<Transition, PrjState> nextStateMap) {
for (Transition t: nextStateMap.keySet()) {
System.out.println(t.getFullLabel() + " -> ");
State[] stateArray = nextStateMap.get(t).getStateArray();
for (int i=0; i<stateArray.length; i++) {
System.out.print("S" + stateArray[i].getIndex() + "(" + stateArray[i].getLpn().getLabel() +")" +", ");
}
System.out.println("");
}
}
// private LpnTranList convertToLpnTranList(HashSet<Transition> newNextPersistent) {
// LpnTranList newNextPersistentTrans = new LpnTranList();
// for (Transition lpnTran : newNextPersistent) {
// newNextPersistentTrans.add(lpnTran);
// return newNextPersistentTrans;
private LpnTranList computeCycleClosingTrans(State[] curStateArray,
State[] nextStateArray,
HashMap<Transition, StaticDependencySets> staticSetsMap,
HashMap<Transition, Integer> tranFiringFreq,
StateGraph[] sgList, StateSetInterface prjStateSet,
PrjState nextPrjState, HashSet<Transition> nextPersistent,
HashSet<Transition> curPersistent, HashSet<PrjState> stateStack) {
for (State s : nextStateArray)
if (s == null)
throw new NullPointerException();
String cycleClosingMthd = Options.getCycleClosingMthd();
LpnTranList newNextPersistent = new LpnTranList();
HashSet<Transition> nextEnabled = new HashSet<Transition>();
HashSet<Transition> curEnabled = new HashSet<Transition>();
for (int lpnIndex=0; lpnIndex<nextStateArray.length; lpnIndex++) {
LhpnFile curLpn = sgList[lpnIndex].getLpn();
for (int i=0; i < curLpn.getAllTransitions().length; i++) {
Transition tran = curLpn.getAllTransitions()[i];
if (nextStateArray[lpnIndex].getTranVector()[i])
nextEnabled.add(tran);
if (curStateArray[lpnIndex].getTranVector()[i])
curEnabled.add(tran);
}
}
// Cycle closing on global state graph
if (Options.getDebugMode()) {
//System.out.println("~~~~~~~ existing global state ~~~~~~~~");
}
if (cycleClosingMthd.equals("strong")) {
newNextPersistent.addAll(setSubstraction(curEnabled, nextPersistent));
updateLocalPersistentSetTbl(newNextPersistent, sgList, nextStateArray);
}
else if (cycleClosingMthd.equals("behavioral")) {
if (Options.getDebugMode()) {
}
HashSet<Transition> curReduced = setSubstraction(curEnabled, curPersistent);
HashSet<Transition> oldNextStatePersistent = new HashSet<Transition>();
DependentSetComparator depComp = new DependentSetComparator(tranFiringFreq);
PriorityQueue<DependentSet> dependentSetQueue = new PriorityQueue<DependentSet>(nextEnabled.size(), depComp);
// TODO: Is oldNextPersistent correctly obtained below?
if (Options.getDebugMode())
printStateArray(nextStateArray,"******* nextStateArray *******");
for (int lpnIndex=0; lpnIndex < sgList.length; lpnIndex++) {
if (sgList[lpnIndex].getEnabledSetTbl().get(nextStateArray[lpnIndex]) != null) {
LpnTranList oldLocalNextPersistentTrans = sgList[lpnIndex].getEnabledSetTbl().get(nextStateArray[lpnIndex]);
// if (Options.getDebugMode()) {
// printTransitionSet(oldLocalNextPersistentTrans, "oldLocalNextPersistentTrans");
for (Transition oldLocalTran : oldLocalNextPersistentTrans)
oldNextStatePersistent.add(oldLocalTran);
}
}
HashSet<Transition> ignored = setSubstraction(curReduced, oldNextStatePersistent);
boolean isCycleClosingPersistentComputation = true;
for (Transition seed : ignored) {
HashSet<Transition> dependent = new HashSet<Transition>();
dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,isCycleClosingPersistentComputation);
if (Options.getDebugMode()) {
printIntegerSet(dependent, "dependent set for ignored transition " + seed.getFullLabel());
}
// TODO: Is this still necessary?
// boolean dependentOnlyHasDummyTrans = true;
// for (LpnTransitionPair dependentTran : dependent) {
// dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans
// && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName());
// if ((newNextPersistent.size() == 0 || dependent.size() < newNextPersistent.size()) && !dependentOnlyHasDummyTrans)
// newNextPersistent = (HashSet<LpnTransitionPair>) dependent.clone();
// DependentSet dependentSet = new DependentSet(newNextPersistent, seed,
// isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName()));
DependentSet dependentSet = new DependentSet(dependent, seed,isDummyTran(seed.getLabel()));
dependentSetQueue.add(dependentSet);
}
cachedNecessarySets.clear();
if (!dependentSetQueue.isEmpty()) {
// System.out.println("depdentSetQueue is NOT empty.");
// newNextPersistent = dependentSetQueue.poll().getDependent();
// TODO: Will newNextPersistentTmp - oldNextPersistent be safe?
HashSet<Transition> newNextPersistentTmp = dependentSetQueue.poll().getDependent();
//newNextPersistent = setSubstraction(newNextPersistentTmp, oldNextPersistent);
newNextPersistent.addAll(setSubstraction(newNextPersistentTmp, oldNextStatePersistent));
updateLocalPersistentSetTbl(newNextPersistent, sgList, nextStateArray);
}
if (Options.getDebugMode()) {
//printIntegerSet(newNextPersistent, "newNextPersistent");
System.out.println("******** behavioral: end of cycle closing check *****");
}
}
else if (cycleClosingMthd.equals("state_search")) {
// TODO: complete cycle closing check for state search.
}
return newNextPersistent;
}
private void updateLocalPersistentSetTbl(LpnTranList nextPersistentTrans,
StateGraph[] sgList, State[] nextStateArray) {
// Persistent set at each state is stored in the enabledSetTbl in each state graph.
for (Transition tran : nextPersistentTrans) {
int lpnIndex = tran.getLpn().getLpnIndex();
State nextState = nextStateArray[lpnIndex];
LpnTranList curPersistentTrans = sgList[lpnIndex].getEnabledSetTbl().get(nextState);
if (curPersistentTrans != null) {
if (!curPersistentTrans.contains(tran))
curPersistentTrans.add(tran);
}
else {
LpnTranList newLpnTranList = new LpnTranList();
newLpnTranList.add(tran);
sgList[lpnIndex].getEnabledSetTbl().put(nextStateArray[lpnIndex], newLpnTranList);
}
}
if (Options.getDebugMode()) {
printPersistentSetTbl(sgList);
}
}
private void printPrjStateSet(StateSetInterface prjStateSet) {
for (PrjState curGlobal : prjStateSet) {
State[] curStateArray = curGlobal.toStateArray();
printStateArray(curStateArray, null);
System.out.println("
}
}
// /**
// * This method performs first-depth search on multiple LPNs and applies partial order reduction technique with the trace-back.
// * @param sgList
// * @param initStateArray
// * @param cycleClosingMthdIndex
// * @return
// */
// public StateGraph[] search_dfsPORrefinedCycleRule(final StateGraph[] sgList, final State[] initStateArray, int cycleClosingMthdIndex) {
// if (cycleClosingMthdIndex == 1)
// else if (cycleClosingMthdIndex == 2)
// else if (cycleClosingMthdIndex == 4)
// double peakUsedMem = 0;
// double peakTotalMem = 0;
// boolean failure = false;
// int tranFiringCnt = 0;
// int totalStates = 1;
// int numLpns = sgList.length;
// HashSet<PrjState> stateStack = new HashSet<PrjState>();
// Stack<LinkedList<Transition>> lpnTranStack = new Stack<LinkedList<Transition>>();
// Stack<Integer> curIndexStack = new Stack<Integer>();
// HashSet<PrjState> prjStateSet = new HashSet<PrjState>();
// PrjState initPrjState = new PrjState(initStateArray);
// prjStateSet.add(initPrjState);
// PrjState stateStackTop = initPrjState;
// System.out.println("%%%%%%% Add states to stateStack %%%%%%%%");
// printStateArray(stateStackTop.toStateArray());
// stateStack.add(stateStackTop);
// // Prepare static pieces for POR
// HashMap<Integer, HashMap<Integer, StaticSets>> staticSetsMap = new HashMap<Integer, HashMap<Integer, StaticSets>>();
// Transition[] allTransitions = sgList[0].getLpn().getAllTransitions();
// HashMap<Integer, StaticSets> tmpMap = new HashMap<Integer, StaticSets>();
// HashMap<Integer, Integer> tranFiringFreq = new HashMap<Integer, Integer>(allTransitions.length);
// for (Transition curTran: allTransitions) {
// StaticSets curStatic = new StaticSets(sgList[0].getLpn(), curTran, allTransitions);
// curStatic.buildDisableSet();
// curStatic.buildEnableSet();
// curStatic.buildModifyAssignSet();
// tmpMap.put(curTran.getIndex(), curStatic);
// tranFiringFreq.put(curTran.getIndex(), 0);
// staticSetsMap.put(sgList[0].getLpn().getLpnIndex(), tmpMap);
// printStaticSetMap(staticSetsMap);
// System.out.println("call getPersistent on initStateArray at 0: ");
// boolean init = true;
// PersistentSet initPersistent = new PersistentSet();
// initPersistent = sgList[0].getPersistent(initStateArray[0], staticSetsMap, init, tranFiringFreq);
// HashMap<State, LpnTranList> initEnabledSetTbl = (HashMap<State, LpnTranList>) sgList[0].copyEnabledSetTbl();
// lpnTranStack.push(initPersistent.getPersistentSet());
// curIndexStack.push(0);
// System.out.println("+++++++ Push trans onto lpnTranStack ++++++++");
// printTransitionSet((LpnTranList) initPersistent.getPersistentSet(), "");
// main_while_loop: while (failure == false && stateStack.size() != 0) {
// System.out.println("$$$$$$$$$$$ loop begins $$$$$$$$$$");
// long curTotalMem = Runtime.getRuntime().totalMemory();
// long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
// if (curTotalMem > peakTotalMem)
// peakTotalMem = curTotalMem;
// if (curUsedMem > peakUsedMem)
// peakUsedMem = curUsedMem;
// if (stateStack.size() > max_stack_depth)
// max_stack_depth = stateStack.size();
// iterations++;
// if (iterations % 100000 == 0) {
// System.out.println("---> #iteration " + iterations
// + "> # LPN transition firings: " + tranFiringCnt
// + ", # of prjStates found: " + totalStates
// + ", stack_depth: " + stateStack.size()
// + " used memory: " + (float) curUsedMem / 1000000
// + " free memory: "
// + (float) Runtime.getRuntime().freeMemory() / 1000000);
// State[] curStateArray = stateStackTop.toStateArray(); //stateStack.peek();
// int curIndex = curIndexStack.peek();
//// System.out.println("curIndex = " + curIndex);
// //PersistentSet curPersistent = new PersistentSet();
// //LinkedList<Transition> curPersistentTrans = curPersistent.getPersistentSet();
// LinkedList<Transition> curPersistentTrans = lpnTranStack.peek();
//// printStateArray(curStateArray);
//// System.out.println("+++++++ curPersistent trans ++++++++");
//// printTransLinkedList(curPersistentTrans);
// // If all enabled transitions of the current LPN are considered,
// // then consider the next LPN
// // by increasing the curIndex.
// // Otherwise, if all enabled transitions of all LPNs are considered,
// // then pop the stacks.
// if (curPersistentTrans.size() == 0) {
// lpnTranStack.pop();
//// System.out.println("+++++++ Pop trans off lpnTranStack ++++++++");
// curIndexStack.pop();
//// System.out.println("+++++++ Pop index off curIndexStack ++++++++");
// curIndex++;
//// System.out.println("curIndex = " + curIndex);
// while (curIndex < numLpns) {
// System.out.println("call getEnabled on curStateArray at 1: ");
// LpnTranList tmpPersistentTrans = (LpnTranList) (sgList[curIndex].getPersistent(curStateArray[curIndex], staticSetsMap, init, tranFiringFreq)).getPersistentSet();
// curPersistentTrans = tmpPersistentTrans.clone();
// //printTransitionSet(curEnabled, "curEnabled set");
// if (curPersistentTrans.size() > 0) {
// System.out.println("+++++++ Push trans onto lpnTranStack ++++++++");
// printTransLinkedList(curPersistentTrans);
// lpnTranStack.push(curPersistentTrans);
// curIndexStack.push(curIndex);
// printIntegerStack("curIndexStack after push 1", curIndexStack);
// break;
// curIndex++;
// if (curIndex == numLpns) {
// prjStateSet.add(stateStackTop);
// System.out.println("%%%%%%% Remove stateStackTop from stateStack %%%%%%%%");
// printStateArray(stateStackTop.toStateArray());
// stateStack.remove(stateStackTop);
// stateStackTop = stateStackTop.getFather();
// continue;
// Transition firedTran = curPersistentTrans.removeLast();
// System.out.println("
// System.out.println("Fired transition: " + firedTran.getName());
// System.out.println("
// Integer freq = tranFiringFreq.get(firedTran.getIndex()) + 1;
// tranFiringFreq.put(firedTran.getIndex(), freq);
// System.out.println("~~~~~~tranFiringFreq~~~~~~~");
// printHashMap(tranFiringFreq, allTransitions);
// State[] nextStateArray = sgList[curIndex].fire(sgList, curStateArray, firedTran);
// tranFiringCnt++;
// Check if the firedTran causes disabling error or deadlock.
// @SuppressWarnings("unchecked")
// LinkedList<Transition>[] curPersistentArray = new LinkedList[numLpns];
// @SuppressWarnings("unchecked")
// LinkedList<Transition>[] nextPersistentArray = new LinkedList[numLpns];
// boolean updatedPersistentDueToCycleRule = false;
// for (int i = 0; i < numLpns; i++) {
// StateGraph sg_tmp = sgList[i];
// System.out.println("call getPersistent on curStateArray at 2: i = " + i);
// PersistentSet PersistentList = new PersistentSet();
// if (init) {
// PersistentList = initPersistent;
// sg_tmp.setEnabledSetTbl(initEnabledSetTbl);
// init = false;
// else
// PersistentList = sg_tmp.getPersistent(curStateArray[i], staticSetsMap, init, tranFiringFreq);
// curPersistentArray[i] = PersistentList.getPersistentSet();
// System.out.println("call getPersistentRefinedCycleRule on nextStateArray at 3: i = " + i);
// PersistentList = sg_tmp.getPersistentRefinedCycleRule(curStateArray[i], nextStateArray[i], staticSetsMap, stateStack, stateStackTop, init, cycleClosingMthdIndex, i, tranFiringFreq);
// nextPersistentArray[i] = PersistentList.getPersistentSet();
// if (!updatedPersistentDueToCycleRule && PersistentList.getPersistentChanged()) {
// updatedPersistentDueToCycleRule = true;
// for (LinkedList<Transition> tranList : curPersistentArray) {
// printTransLinkedList(tranList);
//// for (LinkedList<Transition> tranList : curPersistentArray) {
//// printTransLinkedList(tranList);
//// for (LinkedList<Transition> tranList : nextPersistentArray) {
//// printTransLinkedList(tranList);
// Transition disabledTran = firedTran.disablingError(
// curStateArray[i].getEnabledTransitions(), nextStateArray[i].getEnabledTransitions());
// if (disabledTran != null) {
// System.err.println("Disabling Error: "
// + disabledTran.getFullLabel() + " is disabled by "
// + firedTran.getFullLabel());
// failure = true;
// break main_while_loop;
// if (Analysis.deadLock(sgList, nextStateArray, staticSetsMap, init, tranFiringFreq) == true) {
// failure = true;
// break main_while_loop;
// PrjState nextPrjState = new PrjState(nextStateArray);
// Boolean existingState = prjStateSet.contains(nextPrjState) || stateStack.contains(nextPrjState);
// if (existingState == true && updatedPersistentDueToCycleRule) {
// // cycle closing
// System.out.println("%%%%%%% existingSate == true %%%%%%%%");
// stateStackTop.setChild(nextPrjState);
// nextPrjState.setFather(stateStackTop);
// stateStackTop = nextPrjState;
// stateStack.add(stateStackTop);
// System.out.println("%%%%%%% Add state to stateStack %%%%%%%%");
// printStateArray(stateStackTop.toStateArray());
// System.out.println("+++++++ Push trans onto lpnTranStack ++++++++");
// printTransitionSet((LpnTranList) nextPersistentArray[0], "");
// lpnTranStack.push((LpnTranList) nextPersistentArray[0].clone());
// curIndexStack.push(0);
// if (existingState == false) {
// System.out.println("%%%%%%% existingSate == false %%%%%%%%");
// stateStackTop.setChild(nextPrjState);
// nextPrjState.setFather(stateStackTop);
// stateStackTop = nextPrjState;
// stateStack.add(stateStackTop);
// System.out.println("%%%%%%% Add state to stateStack %%%%%%%%");
// printStateArray(stateStackTop.toStateArray());
// System.out.println("+++++++ Push trans onto lpnTranStack ++++++++");
// printTransitionSet((LpnTranList) nextPersistentArray[0], "");
// lpnTranStack.push((LpnTranList) nextPersistentArray[0].clone());
// curIndexStack.push(0);
// totalStates++;
// // end of main_while_loop
// double totalStateCnt = prjStateSet.size();
// System.out.println("---> final numbers: # LPN transition firings: " + tranFiringCnt
// + ", # of prjStates found: " + totalStateCnt
// + ", max_stack_depth: " + max_stack_depth
// + ", peak total memory: " + peakTotalMem / 1000000 + " MB"
// + ", peak used memory: " + peakUsedMem / 1000000 + " MB");
// // This currently works for a single LPN.
// return sgList;
// return null;
private void printStaticSetsMap( LhpnFile[] lpnList) {
System.out.println("============ staticSetsMap ============");
for (Transition lpnTranPair : staticDependency.keySet()) {
StaticDependencySets statSets = staticDependency.get(lpnTranPair);
printLpnTranPair(statSets.getTran(), statSets.getDisableSet(), "disableSet");
for (HashSet<Transition> setOneConjunctTrue : statSets.getOtherTransSetCurTranEnablingTrue()) {
printLpnTranPair(statSets.getTran(), setOneConjunctTrue, "enableBySetingEnablingTrue for one conjunct");
}
}
}
private void printLpnTranPair(Transition curTran,
HashSet<Transition> TransitionSet, String setName) {
System.out.println(setName + " for transition " + curTran.getFullLabel() + " is: ");
if (TransitionSet.isEmpty()) {
System.out.println("empty");
}
else {
for (Transition lpnTranPair: TransitionSet)
System.out.print(lpnTranPair.getFullLabel() + "\n");
System.out.println();
}
}
// private Transition[] assignStickyTransitions(LhpnFile lpn) {
// // allProcessTrans is a hashmap from a transition to its process color (integer).
// HashMap<Transition, Integer> allProcessTrans = new HashMap<Transition, Integer>();
// // create an Abstraction object to call the divideProcesses method.
// Abstraction abs = new Abstraction(lpn);
// abs.decomposeLpnIntoProcesses();
// allProcessTrans.putAll(
// (HashMap<Transition, Integer>)abs.getTransWithProcIDs().clone());
// HashMap<Integer, LpnProcess> processMap = new HashMap<Integer, LpnProcess>();
// for (Iterator<Transition> tranIter = allProcessTrans.keySet().iterator(); tranIter.hasNext();) {
// Transition curTran = tranIter.next();
// Integer procId = allProcessTrans.get(curTran);
// if (!processMap.containsKey(procId)) {
// LpnProcess newProcess = new LpnProcess(procId);
// newProcess.addTranToProcess(curTran);
// if (curTran.getPreset() != null) {
// Place[] preset = curTran.getPreset();
// for (Place p : preset) {
// newProcess.addPlaceToProcess(p);
// processMap.put(procId, newProcess);
// else {
// LpnProcess curProcess = processMap.get(procId);
// curProcess.addTranToProcess(curTran);
// if (curTran.getPreset() != null) {
// Place[] preset = curTran.getPreset();
// for (Place p : preset) {
// curProcess.addPlaceToProcess(p);
// for(Iterator<Integer> processMapIter = processMap.keySet().iterator(); processMapIter.hasNext();) {
// LpnProcess curProc = processMap.get(processMapIter.next());
// curProc.assignStickyTransitions();
// curProc.printProcWithStickyTrans();
// return lpn.getAllTransitions();
// private void printLpnTranPair(LhpnFile[] lpnList, Transition curTran,
// HashSet<Transition> curDisable, String setName) {
// System.out.print(setName + " for " + curTran.getName() + "(" + curTran.getIndex() + ")" + " is: ");
// if (curDisable.isEmpty()) {
// System.out.println("empty");
// else {
// for (Transition lpnTranPair: curDisable) {
// System.out.print("(" + lpnList[lpnTranPair.getLpnIndex()].getLabel()
// + ", " + lpnList[lpnTranPair.getLpnIndex()].getAllTransitions()[lpnTranPair.getTranIndex()].getName() + ")," + "\t");
// System.out.print("\n");
/**
* Return the set of all LPN transitions that are enabled in 'state'.
* The enabledSetTbl (for each StateGraph obj) stores the persistent set for each state of each LPN.
* @param stateArray
* @param prjStateSet
* @param enable
* @param disableByStealingToken
* @param disable
* @param sgList
* @return
*/
private LpnTranList getPersistentSet(State[] curStateArray, State[] nextStateArray,
HashMap<Transition, Integer> tranFiringFreq, StateGraph[] sgList, LhpnFile[] lpnList,
StateSetInterface prjStateSet, PrjState stateStackTop) {
State[] stateArray = null;
if (nextStateArray == null)
stateArray = curStateArray;
else
stateArray = nextStateArray;
for (State s : stateArray)
if (s == null)
throw new NullPointerException();
LpnTranList persistentSet = new LpnTranList();
HashSet<Transition> curEnabled = new HashSet<Transition>();
for (int lpnIndex=0; lpnIndex<stateArray.length; lpnIndex++) {
curEnabled.addAll(sgList[lpnIndex].getEnabledFromTranVector(stateArray[lpnIndex]));
}
if (Options.getDebugMode()) {
System.out.println("******* Partial Order Reduction *******");
String name = null;
String globalStateLabel = "";
if (curStateArray == null)
name = "nextStateArray";
else
name = "curStateArray";
for (State st : stateArray) {
globalStateLabel += st.getFullLabel() + "_";
}
System.out.println(name + ": " +globalStateLabel.substring(0, globalStateLabel.lastIndexOf("_")));
printIntegerSet(curEnabled, "Enabled set");
System.out.println("******* Begin POR *******");
}
if (curEnabled.isEmpty()) {
return persistentSet;
}
HashSet<Transition> ready = computePersistentSet(stateArray, curEnabled, tranFiringFreq, sgList);
if (Options.getDebugMode()) {
System.out.println("******* End POR *******");
printIntegerSet(ready, "Persistent set");
System.out.println("********************");
}
if (tranFiringFreq != null) {
LinkedList<Transition> readyList = new LinkedList<Transition>();
for (Transition inReady : ready) {
readyList.add(inReady);
}
mergeSort(readyList, tranFiringFreq);
for (Transition inReady : readyList) {
persistentSet.addFirst(inReady);
}
}
else {
for (Transition tran : ready) {
persistentSet.add(tran);
}
}
return persistentSet;
}
private LinkedList<Transition> mergeSort(LinkedList<Transition> array, HashMap<Transition, Integer> tranFiringFreq) {
if (array.size() == 1)
return array;
int middle = array.size() / 2;
LinkedList<Transition> left = new LinkedList<Transition>();
LinkedList<Transition> right = new LinkedList<Transition>();
for (int i=0; i<middle; i++) {
left.add(i, array.get(i));
}
for (int i=middle; i<array.size();i++) {
right.add(i-middle, array.get(i));
}
left = mergeSort(left, tranFiringFreq);
right = mergeSort(right, tranFiringFreq);
return merge(left, right, tranFiringFreq);
}
private LinkedList<Transition> merge(LinkedList<Transition> left,
LinkedList<Transition> right, HashMap<Transition, Integer> tranFiringFreq) {
LinkedList<Transition> result = new LinkedList<Transition>();
while (left.size() > 0 || right.size() > 0) {
if (left.size() > 0 && right.size() > 0) {
if (tranFiringFreq.get(left.peek()) <= tranFiringFreq.get(right.peek())) {
result.addLast(left.poll());
}
else {
result.addLast(right.poll());
}
}
else if (left.size()>0) {
result.addLast(left.poll());
}
else if (right.size()>0) {
result.addLast(right.poll());
}
}
return result;
}
/**
* Return the set of all LPN transitions that are enabled in 'state'. The "init" flag indicates whether a transition
* needs to be evaluated.
* @param nextState
* @param stateStackTop
* @param enable
* @param disableByStealingToken
* @param disable
* @param init
* @param cycleClosingMthdIndex
* @param lpnIndex
* @param isNextState
* @return
*/
private LpnTranList getPersistentRefinedCycleRule(State[] curStateArray, State[] nextStateArray, HashMap<Transition,StaticDependencySets> staticSetsMap,
boolean init, HashMap<Transition,Integer> tranFiringFreq, StateGraph[] sgList,
HashSet<PrjState> stateStack, PrjState stateStackTop) {
// PersistentSet nextPersistent = new PersistentSet();
// if (nextState == null) {
// throw new NullPointerException();
// if(PersistentSetTbl.containsKey(nextState) == true && stateOnStack(nextState, stateStack)) {
// System.out.println("~~~~~~~ existing state in enabledSetTbl and on stateStack: S" + nextState.getIndex() + "~~~~~~~~");
// printTransitionSet((LpnTranList)PersistentSetTbl.get(nextState), "Old Persistent at this state: ");
// // Cycle closing check
// LpnTranList nextPersistentTransOld = (LpnTranList) nextPersistent.getPersistentSet();
// nextPersistentTransOld = PersistentSetTbl.get(nextState);
// LpnTranList curPersistentTrans = PersistentSetTbl.get(curState);
// LpnTranList curReduced = new LpnTranList();
// LpnTranList curEnabled = curState.getEnabledTransitions();
// for (int i=0; i<curEnabled.size(); i++) {
// if (!curPersistentTrans.contains(curEnabled.get(i))) {
// curReduced.add(curEnabled.get(i));
// if (!nextPersistentTransOld.containsAll(curReduced)) {
// System.out.println("((((((((((((((((((((()))))))))))))))))))))");
// printTransitionSet(curEnabled, "curEnabled:");
// printTransitionSet(curPersistentTrans, "curPersistentTrans:");
// printTransitionSet(curReduced, "curReduced:");
// printTransitionSet(nextState.getEnabledTransitions(), "nextEnabled:");
// printTransitionSet(nextPersistentTransOld, "nextPersistentTransOld:");
// nextPersistent.setPersistentChanged();
// HashSet<Transition> curEnabledIndicies = new HashSet<Transition>();
// for (int i=0; i<curEnabled.size(); i++) {
// curEnabledIndicies.add(curEnabled.get(i).getIndex());
// // transToAdd = curReduced - nextPersistentOld
// LpnTranList overlyReducedTrans = getSetSubtraction(curReduced, nextPersistentTransOld);
// HashSet<Integer> transToAddIndices = new HashSet<Integer>();
// for (int i=0; i<overlyReducedTrans.size(); i++) {
// transToAddIndices.add(overlyReducedTrans.get(i).getIndex());
// HashSet<Integer> nextPersistentNewIndices = (HashSet<Integer>) curEnabledIndicies.clone();
// for (Integer tranToAdd : transToAddIndices) {
// HashSet<Transition> dependent = new HashSet<Transition>();
// //Transition enabledTransition = this.lpn.getAllTransitions()[tranToAdd];
// dependent = computeDependent(curState,tranToAdd,dependent,curEnabledIndicies,staticMap);
// // printIntegerSet(dependent, "dependent set for enabled transition " + this.lpn.getAllTransitions()[enabledTran]);
// boolean dependentOnlyHasDummyTrans = true;
// for (Integer curTranIndex : dependent) {
// Transition curTran = this.lpn.getAllTransitions()[curTranIndex];
// dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans && isDummyTran(curTran.getName());
// if (dependent.size() < nextPersistentNewIndices.size() && !dependentOnlyHasDummyTrans)
// nextPersistentNewIndices = (HashSet<Integer>) dependent.clone();
// if (nextPersistentNewIndices.size() == 1)
// break;
// LpnTranList nextPersistentNew = new LpnTranList();
// for (Integer nextPersistentNewIndex : nextPersistentNewIndices) {
// nextPersistentNew.add(this.getLpn().getTransition(nextPersistentNewIndex));
// LpnTranList transToAdd = getSetSubtraction(nextPersistentNew, nextPersistentTransOld);
// boolean allTransToAddFired = false;
// if (cycleClosingMthdIndex == 2) {
// // For every transition t in transToAdd, if t was fired in the any state on stateStack, there is no need to put it to the new Persistent of nextState.
// if (transToAdd != null) {
// LpnTranList transToAddCopy = transToAdd.copy();
// HashSet<Integer> stateVisited = new HashSet<Integer>();
// stateVisited.add(nextState.getIndex());
// allTransToAddFired = allTransToAddFired(transToAddCopy,
// allTransToAddFired, stateVisited, stateStackTop, lpnIndex);
// // Update the old Persistent of the next state
// if (!allTransToAddFired || cycleClosingMthdIndex == 1) {
// nextPersistent.getPersistentSet().clear();
// nextPersistent.getPersistentSet().addAll(transToAdd);
// PersistentSetTbl.get(nextState).addAll(transToAdd);
// printTransitionSet(nextPersistentNew, "nextPersistentNew:");
// printTransitionSet(transToAdd, "transToAdd:");
// System.out.println("((((((((((((((((((((()))))))))))))))))))))");
// if (cycleClosingMthdIndex == 4) {
// nextPersistent.getPersistentSet().clear();
// nextPersistent.getPersistentSet().addAll(overlyReducedTrans);
// PersistentSetTbl.get(nextState).addAll(overlyReducedTrans);
// printTransitionSet(nextPersistentNew, "nextPersistentNew:");
// printTransitionSet(transToAdd, "transToAdd:");
// System.out.println("((((((((((((((((((((()))))))))))))))))))))");
// // enabledSetTble stores the Persistent set at curState.
// // The fully enabled set at each state is stored in the tranVector in each state.
// return (PersistentSet) nextPersistent;
// for (State s : nextStateArray)
// if (s == null)
// throw new NullPointerException();
// cachedNecessarySets.clear();
// String cycleClosingMthd = Options.getCycleClosingMthd();
// PersistentSet nextPersistent = new PersistentSet();
// HashSet<Transition> nextEnabled = new HashSet<Transition>();
//// boolean allEnabledAreSticky = false;
// for (int lpnIndex=0; lpnIndex<nextStateArray.length; lpnIndex++) {
// State nextState = nextStateArray[lpnIndex];
// if (init) {
// LhpnFile curLpn = sgList[lpnIndex].getLpn();
// //allEnabledAreSticky = true;
// for (int i=0; i < curLpn.getAllTransitions().length; i++) {
// Transition tran = curLpn.getAllTransitions()[i];
// if (sgList[lpnIndex].isEnabled(tran,nextState)){
// nextEnabled.add(new Transition(curLpn.getLpnIndex(), i));
// //allEnabledAreSticky = allEnabledAreSticky && tran.isSticky();
// //sgList[lpnIndex].getEnabledSetTbl().put(nextStateArray[lpnIndex], new LpnTranList());
// else {
// LhpnFile curLpn = sgList[lpnIndex].getLpn();
// for (int i=0; i < curLpn.getAllTransitions().length; i++) {
// Transition tran = curLpn.getAllTransitions()[i];
// if (nextStateArray[lpnIndex].getTranVector()[i]) {
// nextEnabled.add(new Transition(curLpn.getLpnIndex(), i));
// //allEnabledAreSticky = allEnabledAreSticky && tran.isSticky();
// //sgList[lpnIndex].getEnabledSetTbl().put(nextStateArray[lpnIndex], new LpnTranList());
// DependentSetComparator depComp = new DependentSetComparator(tranFiringFreq);
// PriorityQueue<DependentSet> dependentSetQueue = new PriorityQueue<DependentSet>(nextEnabled.size(), depComp);
// LhpnFile[] lpnList = new LhpnFile[sgList.length];
// for (int i=0; i<sgList.length; i++)
// lpnList[i] = sgList[i].getLpn();
// HashMap<Transition, LpnTranList> transToAddMap = new HashMap<Transition, LpnTranList>();
// Integer cycleClosingLpnIndex = -1;
// for (int lpnIndex=0; lpnIndex<nextStateArray.length; lpnIndex++) {
// State curState = curStateArray[lpnIndex];
// State nextState = nextStateArray[lpnIndex];
// if(sgList[lpnIndex].getEnabledSetTbl().containsKey(nextState) == true
// && !sgList[lpnIndex].getEnabledSetTbl().get(nextState).isEmpty()
// && stateOnStack(lpnIndex, nextState, stateStack)
// && nextState.getIndex() != curState.getIndex()) {
// cycleClosingLpnIndex = lpnIndex;
// System.out.println("~~~~~~~ existing state in enabledSetTbl for LPN " + sgList[lpnIndex].getLpn().getLabel() +": S" + nextState.getIndex() + "~~~~~~~~");
// printPersistentSet((LpnTranList)sgList[lpnIndex].getEnabledSetTbl().get(nextState), "Old Persistent at this state: ");
// LpnTranList oldLocalNextPersistentTrans = sgList[lpnIndex].getEnabledSetTbl().get(nextState);
// LpnTranList curLocalPersistentTrans = sgList[lpnIndex].getEnabledSetTbl().get(curState);
// LpnTranList reducedLocalTrans = new LpnTranList();
// LpnTranList curLocalEnabledTrans = curState.getEnabledTransitions();
// System.out.println("The firedTran is a cycle closing transition.");
// if (cycleClosingMthd.toLowerCase().equals("behavioral") || cycleClosingMthd.toLowerCase().equals("state_search")) {
// // firedTran is a cycle closing transition.
// for (int i=0; i<curLocalEnabledTrans.size(); i++) {
// if (!curLocalPersistentTrans.contains(curLocalEnabledTrans.get(i))) {
// reducedLocalTrans.add(curLocalEnabledTrans.get(i));
// if (!oldLocalNextPersistentTrans.containsAll(reducedLocalTrans)) {
// printTransitionSet(curLocalEnabledTrans, "curLocalEnabled:");
// printTransitionSet(curLocalPersistentTrans, "curPersistentTrans:");
// printTransitionSet(reducedLocalTrans, "reducedLocalTrans:");
// printTransitionSet(nextState.getEnabledTransitions(), "nextLocalEnabled:");
// printTransitionSet(oldLocalNextPersistentTrans, "nextPersistentTransOld:");
// // nextPersistent.setPersistentChanged();
// // ignoredTrans should not be empty here.
// LpnTranList ignoredTrans = getSetSubtraction(reducedLocalTrans, oldLocalNextPersistentTrans);
// HashSet<Transition> ignored = new HashSet<Transition>();
// for (int i=0; i<ignoredTrans.size(); i++) {
// ignored.add(new Transition(lpnIndex, ignoredTrans.get(i).getIndex()));
// HashSet<Transition> newNextPersistent = (HashSet<Transition>) nextEnabled.clone();
// if (cycleClosingMthd.toLowerCase().equals("behavioral")) {
// for (Transition seed : ignored) {
// HashSet<Transition> dependent = new HashSet<Transition>();
// dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,staticSetsMap, lpnList);
// printIntegerSet(dependent, sgList, "dependent set for ignored transition " + sgList[seed.getLpnIndex()].getLpn().getLabel()
// + "(" + sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName() + ")");
// boolean dependentOnlyHasDummyTrans = true;
// for (Transition dependentTran : dependent) {
// dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans
// && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName());
// if (dependent.size() < newNextPersistent.size() && !dependentOnlyHasDummyTrans)
// newNextPersistent = (HashSet<Transition>) dependent.clone();
//// if (nextPersistentNewIndices.size() == 1)
//// break;
// DependentSet dependentSet = new DependentSet(newNextPersistent, seed,
// isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName()));
// dependentSetQueue.add(dependentSet);
// LpnTranList newLocalNextPersistentTrans = new LpnTranList();
// for (Transition tran : newNextPersistent) {
// if (tran.getLpnIndex() == lpnIndex)
// newLocalNextPersistentTrans.add(sgList[lpnIndex].getLpn().getTransition(tran.getTranIndex()));
// LpnTranList transToAdd = getSetSubtraction(newLocalNextPersistentTrans, oldLocalNextPersistentTrans);
// transToAddMap.put(seed, transToAdd);
// else if (cycleClosingMthd.toLowerCase().equals("state_search")) {
// // For every transition t in ignored, if t was fired in any state on stateStack, there is no need to put it to the new Persistent of nextState.
// HashSet<Integer> stateVisited = new HashSet<Integer>();
// stateVisited.add(nextState.getIndex());
// LpnTranList trulyIgnoredTrans = ignoredTrans.copy();
// trulyIgnoredTrans = allIgnoredTransFired(trulyIgnoredTrans, stateVisited, stateStackTop, lpnIndex, sgList[lpnIndex]);
// if (!trulyIgnoredTrans.isEmpty()) {
// HashSet<Transition> trulyIgnored = new HashSet<Transition>();
// for (Transition tran : trulyIgnoredTrans) {
// trulyIgnored.add(new Transition(tran.getLpn().getLpnIndex(), tran.getIndex()));
// for (Transition seed : trulyIgnored) {
// HashSet<Transition> dependent = new HashSet<Transition>();
// dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,staticSetsMap, lpnList);
// printIntegerSet(dependent, sgList, "dependent set for trulyIgnored transition " + sgList[seed.getLpnIndex()].getLpn().getLabel()
// + "(" + sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName() + ")");
// boolean dependentOnlyHasDummyTrans = true;
// for (Transition dependentTran : dependent) {
// dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans
// && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName());
// if (dependent.size() < newNextPersistent.size() && !dependentOnlyHasDummyTrans)
// newNextPersistent = (HashSet<Transition>) dependent.clone();
// DependentSet dependentSet = new DependentSet(newNextPersistent, seed,
// isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName()));
// dependentSetQueue.add(dependentSet);
// LpnTranList newLocalNextPersistentTrans = new LpnTranList();
// for (Transition tran : newNextPersistent) {
// if (tran.getLpnIndex() == lpnIndex)
// newLocalNextPersistentTrans.add(sgList[lpnIndex].getLpn().getTransition(tran.getTranIndex()));
// LpnTranList transToAdd = getSetSubtraction(newLocalNextPersistentTrans, oldLocalNextPersistentTrans);
// transToAddMap.put(seed, transToAdd);
// else { // All ignored transitions were fired before. It is safe to close the current cycle.
// HashSet<Transition> oldLocalNextPersistent = new HashSet<Transition>();
// for (Transition tran : oldLocalNextPersistentTrans)
// oldLocalNextPersistent.add(new Transition(tran.getLpn().getLpnIndex(), tran.getIndex()));
// for (Transition seed : oldLocalNextPersistent) {
// HashSet<Transition> dependent = new HashSet<Transition>();
// dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,staticSetsMap, lpnList);
// printIntegerSet(dependent, sgList, "dependent set for transition in oldNextPersistent is " + sgList[seed.getLpnIndex()].getLpn().getLabel()
// + "(" + sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName() + ")");
// boolean dependentOnlyHasDummyTrans = true;
// for (Transition dependentTran : dependent) {
// dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans
// && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName());
// if (dependent.size() < newNextPersistent.size() && !dependentOnlyHasDummyTrans)
// newNextPersistent = (HashSet<Transition>) dependent.clone();
// DependentSet dependentSet = new DependentSet(newNextPersistent, seed,
// isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName()));
// dependentSetQueue.add(dependentSet);
// else {
// // oldNextPersistentTrans.containsAll(curReducedTrans) == true (safe to close the current cycle)
// HashSet<Transition> newNextPersistent = (HashSet<Transition>) nextEnabled.clone();
// HashSet<Transition> oldLocalNextPersistent = new HashSet<Transition>();
// for (Transition tran : oldLocalNextPersistentTrans)
// oldLocalNextPersistent.add(new Transition(tran.getLpn().getLpnIndex(), tran.getIndex()));
// for (Transition seed : oldLocalNextPersistent) {
// HashSet<Transition> dependent = new HashSet<Transition>();
// dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,staticSetsMap, lpnList);
// printIntegerSet(dependent, sgList, "dependent set for transition in oldNextPersistent is " + sgList[seed.getLpnIndex()].getLpn().getLabel()
// + "(" + sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName() + ")");
// boolean dependentOnlyHasDummyTrans = true;
// for (Transition dependentTran : dependent) {
// dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans
// && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName());
// if (dependent.size() < newNextPersistent.size() && !dependentOnlyHasDummyTrans)
// newNextPersistent = (HashSet<Transition>) dependent.clone();
// DependentSet dependentSet = new DependentSet(newNextPersistent, seed,
// isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName()));
// dependentSetQueue.add(dependentSet);
// else if (cycleClosingMthd.toLowerCase().equals("strong")) {
// LpnTranList ignoredTrans = getSetSubtraction(reducedLocalTrans, oldLocalNextPersistentTrans);
// HashSet<Transition> ignored = new HashSet<Transition>();
// for (int i=0; i<ignoredTrans.size(); i++) {
// ignored.add(new Transition(lpnIndex, ignoredTrans.get(i).getIndex()));
// HashSet<Transition> allNewNextPersistent = new HashSet<Transition>();
// for (Transition seed : ignored) {
// HashSet<Transition> newNextPersistent = (HashSet<Transition>) nextEnabled.clone();
// HashSet<Transition> dependent = new HashSet<Transition>();
// dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,staticSetsMap, lpnList);
// printIntegerSet(dependent, sgList, "dependent set for transition in curLocalEnabled is " + sgList[seed.getLpnIndex()].getLpn().getLabel()
// + "(" + sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName() + ")");
// boolean dependentOnlyHasDummyTrans = true;
// for (Transition dependentTran : dependent) {
// dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans
// && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName());
// if (dependent.size() < newNextPersistent.size() && !dependentOnlyHasDummyTrans)
// newNextPersistent = (HashSet<Transition>) dependent.clone();
// allNewNextPersistent.addAll(newNextPersistent);
// // The strong cycle condition requires all seeds in ignored to be included in the allNewNextPersistent, as well as dependent set for each seed.
// // So each seed should have the same new Persistent set.
// for (Transition seed : ignored) {
// DependentSet dependentSet = new DependentSet(allNewNextPersistent, seed,
// isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName()));
// dependentSetQueue.add(dependentSet);
// else { // firedTran is not a cycle closing transition. Compute next Persistent.
//// if (nextEnabled.size() == 1)
//// return nextEnabled;
// System.out.println("The firedTran is NOT a cycle closing transition.");
// HashSet<Transition> ready = null;
// for (Transition seed : nextEnabled) {
// System.out.println("@ partialOrderReduction, consider transition " + sgList[seed.getLpnIndex()].getLpn().getLabel()
// + "("+ sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()) + ")");
// HashSet<Transition> dependent = new HashSet<Transition>();
// Transition enabledTransition = sgList[seed.getLpnIndex()].getLpn().getAllTransitions()[seed.getTranIndex()];
// boolean enabledIsDummy = false;
//// if (enabledTransition.isSticky()) {
//// dependent = (HashSet<Transition>) nextEnabled.clone();
//// else {
//// dependent = computeDependent(curStateArray,seed,dependent,nextEnabled,staticMap, lpnList);
// dependent = computeDependent(curStateArray,seed,dependent,nextEnabled,staticSetsMap,lpnList);
// printIntegerSet(dependent, sgList, "dependent set for enabled transition " + sgList[seed.getLpnIndex()].getLpn().getLabel()
// + "(" + enabledTransition.getName() + ")");
// if (isDummyTran(enabledTransition.getName()))
// enabledIsDummy = true;
// for (Transition inDependent : dependent) {
// if(inDependent.getLpnIndex() == cycleClosingLpnIndex) {
// // check cycle closing condition
// break;
// DependentSet dependentSet = new DependentSet(dependent, seed, enabledIsDummy);
// dependentSetQueue.add(dependentSet);
// ready = dependentSetQueue.poll().getDependent();
//// // Update the old Persistent of the next state
//// boolean allTransToAddFired = false;
//// if (cycleClosingMthdIndex == 2) {
//// // For every transition t in transToAdd, if t was fired in the any state on stateStack, there is no need to put it to the new Persistent of nextState.
//// if (transToAdd != null) {
//// LpnTranList transToAddCopy = transToAdd.copy();
//// HashSet<Integer> stateVisited = new HashSet<Integer>();
//// stateVisited.add(nextState.getIndex());
//// allTransToAddFired = allTransToAddFired(transToAddCopy,
//// allTransToAddFired, stateVisited, stateStackTop, lpnIndex);
//// // Update the old Persistent of the next state
//// if (!allTransToAddFired || cycleClosingMthdIndex == 1) {
//// nextPersistent.getPersistentSet().clear();
//// nextPersistent.getPersistentSet().addAll(transToAdd);
//// PersistentSetTbl.get(nextState).addAll(transToAdd);
//// printTransitionSet(nextPersistentNew, "nextPersistentNew:");
//// printTransitionSet(transToAdd, "transToAdd:");
//// System.out.println("((((((((((((((((((((()))))))))))))))))))))");
//// if (cycleClosingMthdIndex == 4) {
//// nextPersistent.getPersistentSet().clear();
//// nextPersistent.getPersistentSet().addAll(ignoredTrans);
//// PersistentSetTbl.get(nextState).addAll(ignoredTrans);
//// printTransitionSet(nextPersistentNew, "nextPersistentNew:");
//// printTransitionSet(transToAdd, "transToAdd:");
//// System.out.println("((((((((((((((((((((()))))))))))))))))))))");
//// // enabledSetTble stores the Persistent set at curState.
//// // The fully enabled set at each state is stored in the tranVector in each state.
//// return (PersistentSet) nextPersistent;
return null;
}
private LpnTranList allIgnoredTransFired(LpnTranList ignoredTrans,
HashSet<Integer> stateVisited, PrjState stateStackEntry, int lpnIndex, StateGraph sg) {
State state = stateStackEntry.get(lpnIndex);
System.out.println("state = " + state.getIndex());
State predecessor = stateStackEntry.getFather().get(lpnIndex);
if (predecessor != null)
System.out.println("predecessor = " + predecessor.getIndex());
if (predecessor == null || stateVisited.contains(predecessor.getIndex())) {
return ignoredTrans;
}
else
stateVisited.add(predecessor.getIndex());
LpnTranList predecessorOldPersistent = sg.getEnabledSetTbl().get(predecessor);//enabledSetTbl.get(predecessor);
for (Transition oldPersistentTran : predecessorOldPersistent) {
State tmpState = sg.getNextStateMap().get(predecessor).get(oldPersistentTran);
if (tmpState.getIndex() == state.getIndex()) {
ignoredTrans.remove(oldPersistentTran);
break;
}
}
if (ignoredTrans.size()==0) {
return ignoredTrans;
}
else {
ignoredTrans = allIgnoredTransFired(ignoredTrans, stateVisited, stateStackEntry.getFather(), lpnIndex, sg);
}
return ignoredTrans;
}
// for (Transition oldPersistentTran : oldPersistent) {
// State successor = nextStateMap.get(nextState).get(oldPersistentTran);
// if (stateVisited.contains(successor.getIndex())) {
// break;
// else
// stateVisited.add(successor.getIndex());
// LpnTranList successorOldPersistent = enabledSetTbl.get(successor);
// // Either successor or sucessorOldPersistent should not be null for a nonterminal state graph.
// HashSet<Transition> transToAddFired = new HashSet<Transition>();
// for (Transition tran : transToAddCopy) {
// if (successorOldPersistent.contains(tran))
// transToAddFired.add(tran);
// transToAddCopy.removeAll(transToAddFired);
// if (transToAddCopy.size() == 0) {
// allTransFired = true;
// break;
// else {
// allTransFired = allTransToAddFired(successorOldPersistent, nextState, successor,
// transToAddCopy, allTransFired, stateVisited, stateStackEntry, lpnIndex);
// return allTransFired;
/**
* An iterative implement of findsg_recursive().
* @param lpnList
* @param curLocalStateArray
* @param enabledArray
*/
/**
* An iterative implement of findsg_recursive().
* @param lpnList
* @param curLocalStateArray
* @param enabledArray
*/
public Stack<State[]> search_dfs_noDisabling_fireOrder(final StateGraph[] lpnList, final State[] initStateArray) {
boolean firingOrder = false;
long peakUsedMem = 0;
long peakTotalMem = 0;
boolean failure = false;
int tranFiringCnt = 0;
int arraySize = lpnList.length;
HashSet<PrjLpnState> globalStateTbl = new HashSet<PrjLpnState>();
@SuppressWarnings("unchecked")
IndexObjMap<LpnState>[] lpnStateCache = new IndexObjMap[arraySize];
//HashMap<LpnState, LpnState>[] lpnStateCache1 = new HashMap[arraySize];
Stack<LpnState[]> stateStack = new Stack<LpnState[]>();
Stack<LpnTranList[]> lpnTranStack = new Stack<LpnTranList[]>();
//get initial enable transition set
LpnTranList initEnabled = new LpnTranList();
LpnTranList initFireFirst = new LpnTranList();
LpnState[] initLpnStateArray = new LpnState[arraySize];
for (int i = 0; i < arraySize; i++)
{
lpnStateCache[i] = new IndexObjMap<LpnState>();
LinkedList<Transition> enabledTrans = lpnList[i].getEnabled(initStateArray[i]);
HashSet<Transition> enabledSet = new HashSet<Transition>();
if(!enabledTrans.isEmpty())
{
for(Transition tran : enabledTrans) {
enabledSet.add(tran);
initEnabled.add(tran);
}
}
LpnState curLpnState = new LpnState(lpnList[i].getLpn(), initStateArray[i], enabledSet);
lpnStateCache[i].add(curLpnState);
initLpnStateArray[i] = curLpnState;
}
LpnTranList[] initEnabledSet = new LpnTranList[2];
initEnabledSet[0] = initFireFirst;
initEnabledSet[1] = initEnabled;
lpnTranStack.push(initEnabledSet);
stateStack.push(initLpnStateArray);
globalStateTbl.add(new PrjLpnState(initLpnStateArray));
main_while_loop: while (failure == false && stateStack.empty() == false) {
long curTotalMem = Runtime.getRuntime().totalMemory();
long curUsedMem = Runtime.getRuntime().totalMemory()
- Runtime.getRuntime().freeMemory();
if (curTotalMem > peakTotalMem)
peakTotalMem = curTotalMem;
if (curUsedMem > peakUsedMem)
peakUsedMem = curUsedMem;
if (stateStack.size() > max_stack_depth)
max_stack_depth = stateStack.size();
iterations++;
//if(iterations>2)break;
if (iterations % 100000 == 0)
System.out.println("---> #iteration " + iterations
+ "> # LPN transition firings: " + tranFiringCnt
+ ", # of prjStates found: " + globalStateTbl.size()
+ ", current_stack_depth: " + stateStack.size()
+ ", total MDD nodes: " + mddMgr.nodeCnt()
+ " used memory: " + (float) curUsedMem / 1000000
+ " free memory: "
+ (float) Runtime.getRuntime().freeMemory() / 1000000);
LpnTranList[] curEnabled = lpnTranStack.peek();
LpnState[] curLpnStateArray = stateStack.peek();
// If all enabled transitions of the current LPN are considered,
// then consider the next LPN
// by increasing the curIndex.
// Otherwise, if all enabled transitions of all LPNs are considered,
// then pop the stacks.
if(curEnabled[0].size()==0 && curEnabled[1].size()==0){
lpnTranStack.pop();
stateStack.pop();
continue;
}
Transition firedTran = null;
if(curEnabled[0].size() != 0)
firedTran = curEnabled[0].removeFirst();
else
firedTran = curEnabled[1].removeFirst();
traceCex.addLast(firedTran);
State[] curStateArray = new State[arraySize];
for( int i = 0; i < arraySize; i++)
curStateArray[i] = curLpnStateArray[i].getState();
StateGraph sg = null;
for (int i=0; i<lpnList.length; i++) {
if (lpnList[i].getLpn().equals(firedTran.getLpn())) {
sg = lpnList[i];
}
}
State[] nextStateArray = sg.fire(lpnList, curStateArray, firedTran);
// Check if the firedTran causes disabling error or deadlock.
@SuppressWarnings("unchecked")
HashSet<Transition>[] extendedNextEnabledArray = new HashSet[arraySize];
for (int i = 0; i < arraySize; i++) {
HashSet<Transition> curEnabledSet = curLpnStateArray[i].getEnabled();
LpnTranList nextEnabledList = lpnList[i].getEnabled(nextStateArray[i]);
HashSet<Transition> nextEnabledSet = new HashSet<Transition>();
for(Transition tran : nextEnabledList) {
nextEnabledSet.add(tran);
}
extendedNextEnabledArray[i] = nextEnabledSet;
//non_disabling
for(Transition curTran : curEnabledSet) {
if(curTran == firedTran)
continue;
if(nextEnabledSet.contains(curTran) == false) {
int[] nextMarking = nextStateArray[i].getMarking();
// Not sure if the code below is correct.
int[] preset = lpnList[i].getLpn().getPresetIndex(curTran.getLabel());
boolean included = true;
if (preset != null && preset.length > 0) {
for (int pp : preset) {
boolean temp = false;
for (int mi = 0; mi < nextMarking.length; mi++) {
if (nextMarking[mi] == pp) {
temp = true;
break;
}
}
if (temp == false)
{
included = false;
break;
}
}
}
if(preset==null || preset.length==0 || included==true) {
extendedNextEnabledArray[i].add(curTran);
}
}
}
}
boolean deadlock=true;
for(int i = 0; i < arraySize; i++) {
if(extendedNextEnabledArray[i].size() != 0){
deadlock = false;
break;
}
}
if(deadlock==true) {
failure = true;
break main_while_loop;
}
// Add nextPrjState into prjStateSet
// If nextPrjState has been traversed before, skip to the next
// enabled transition.
LpnState[] nextLpnStateArray = new LpnState[arraySize];
for(int i = 0; i < arraySize; i++) {
HashSet<Transition> lpnEnabledSet = new HashSet<Transition>();
for(Transition tran : extendedNextEnabledArray[i]) {
lpnEnabledSet.add(tran);
}
LpnState tmp = new LpnState(lpnList[i].getLpn(), nextStateArray[i], lpnEnabledSet);
LpnState tmpCached = (LpnState)(lpnStateCache[i].add(tmp));
nextLpnStateArray[i] = tmpCached;
}
boolean newState = globalStateTbl.add(new PrjLpnState(nextLpnStateArray));
if(newState == false) {
traceCex.removeLast();
continue;
}
stateStack.push(nextLpnStateArray);
LpnTranList[] nextEnabledSet = new LpnTranList[2];
LpnTranList fireFirstTrans = new LpnTranList();
LpnTranList otherTrans = new LpnTranList();
for(int i = 0; i < arraySize; i++)
{
for(Transition tran : nextLpnStateArray[i].getEnabled())
{
if(firingOrder == true)
if(curLpnStateArray[i].getEnabled().contains(tran))
otherTrans.add(tran);
else
fireFirstTrans.add(tran);
else
fireFirstTrans.add(tran);
}
}
nextEnabledSet[0] = fireFirstTrans;
nextEnabledSet[1] = otherTrans;
lpnTranStack.push(nextEnabledSet);
}// END while (stateStack.empty() == false)
// graph.write(String.format("graph_%s_%s-tran_%s-state.gv",mode,tranFiringCnt,
// prjStateSet.size()));
System.out.println("SUMMARY: # LPN transition firings: "
+ tranFiringCnt + ", # of prjStates found: "
+ globalStateTbl.size() + ", max_stack_depth: " + max_stack_depth);
/*
* by looking at stateStack, generate the trace showing the counter-exPersistent.
*/
if (failure == true) {
System.out.println("
System.out.println("the deadlock trace:");
//update traceCex from stateStack
// LpnState[] cur = null;
// LpnState[] next = null;
for(Transition tran : traceCex)
System.out.println(tran.getFullLabel());
}
System.out.println("Modules' local states: ");
for (int i = 0; i < arraySize; i++) {
System.out.println("module " + lpnList[i].getLpn().getLabel() + ": "
+ lpnList[i].reachSize());
}
return null;
}
/**
* findsg using iterative approach based on DFS search. The states found are
* stored in MDD.
*
* When a state is considered during DFS, only one enabled transition is
* selected to fire in an iteration.
*
* @param lpnList
* @param curLocalStateArray
* @param enabledArray
* @return a linked list of a sequence of LPN transitions leading to the
* failure if it is not empty.
*/
public Stack<State[]> search_dfs_mdd_1(final StateGraph[] lpnList, final State[] initStateArray) {
System.out.println("---> calling function search_dfs_mdd_1");
long peakUsedMem = 0;
long peakTotalMem = 0;
long peakMddNodeCnt = 0;
int memUpBound = 500; // Set an upper bound of memory in MB usage to
// trigger MDD compression.
boolean compressed = false;
boolean failure = false;
int tranFiringCnt = 0;
int totalStates = 1;
int arraySize = lpnList.length;
int newStateCnt = 0;
Stack<State[]> stateStack = new Stack<State[]>();
Stack<LinkedList<Transition>> lpnTranStack = new Stack<LinkedList<Transition>>();
Stack<Integer> curIndexStack = new Stack<Integer>();
mddNode reachAll = null;
mddNode reach = mddMgr.newNode();
int[] localIdxArray = Analysis.getLocalStateIdxArray(lpnList, initStateArray, true);
mddMgr.add(reach, localIdxArray, compressed);
stateStack.push(initStateArray);
LpnTranList initEnabled = lpnList[0].getEnabled(initStateArray[0]);
lpnTranStack.push(initEnabled.clone());
curIndexStack.push(0);
int numMddCompression = 0;
main_while_loop: while (failure == false && stateStack.empty() == false) {
long curTotalMem = Runtime.getRuntime().totalMemory();
long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
if (curTotalMem > peakTotalMem)
peakTotalMem = curTotalMem;
if (curUsedMem > peakUsedMem)
peakUsedMem = curUsedMem;
if (stateStack.size() > max_stack_depth)
max_stack_depth = stateStack.size();
iterations++;
if (iterations % 100000 == 0) {
long curMddNodeCnt = mddMgr.nodeCnt();
peakMddNodeCnt = peakMddNodeCnt > curMddNodeCnt ? peakMddNodeCnt : curMddNodeCnt;
System.out.println("---> #iteration " + iterations
+ "> # LPN transition firings: " + tranFiringCnt
+ ", # of prjStates found: " + totalStates
+ ", stack depth: " + stateStack.size()
+ ", total MDD nodes: " + curMddNodeCnt
+ " used memory: " + (float) curUsedMem / 1000000
+ " free memory: "
+ (float) Runtime.getRuntime().freeMemory() / 1000000);
if (curUsedMem >= memUpBound * 1000000) {
mddMgr.compress(reach);
numMddCompression++;
if (reachAll == null)
reachAll = reach;
else {
mddNode newReachAll = mddMgr.union(reachAll, reach);
if (newReachAll != reachAll) {
mddMgr.remove(reachAll);
reachAll = newReachAll;
}
}
mddMgr.remove(reach);
reach = mddMgr.newNode();
if(memUpBound < 1500)
memUpBound *= numMddCompression;
}
}
State[] curStateArray = stateStack.peek();
int curIndex = curIndexStack.peek();
LinkedList<Transition> curEnabled = lpnTranStack.peek();
// If all enabled transitions of the current LPN are considered,
// then consider the next LPN
// by increasing the curIndex.
// Otherwise, if all enabled transitions of all LPNs are considered,
// then pop the stacks.
if (curEnabled.size() == 0) {
lpnTranStack.pop();
curIndexStack.pop();
curIndex++;
while (curIndex < arraySize) {
LpnTranList enabledCached = (lpnList[curIndex].getEnabled(curStateArray[curIndex]));
if (enabledCached.size() > 0) {
curEnabled = enabledCached.clone();
lpnTranStack.push(curEnabled);
curIndexStack.push(curIndex);
break;
} else
curIndex++;
}
}
if (curIndex == arraySize) {
stateStack.pop();
continue;
}
Transition firedTran = curEnabled.removeLast();
State[] nextStateArray = lpnList[curIndex].fire(lpnList, curStateArray,firedTran);
tranFiringCnt++;
// Check if the firedTran causes disabling error or deadlock.
LinkedList<Transition>[] curEnabledArray = new LinkedList[arraySize];
LinkedList<Transition>[] nextEnabledArray = new LinkedList[arraySize];
for (int i = 0; i < arraySize; i++) {
StateGraph lpn_tmp = lpnList[i];
LinkedList<Transition> enabledList = lpn_tmp.getEnabled(curStateArray[i]);
curEnabledArray[i] = enabledList;
enabledList = lpn_tmp.getEnabled(nextStateArray[i]);
nextEnabledArray[i] = enabledList;
Transition disabledTran = firedTran.disablingError(
curEnabledArray[i], nextEnabledArray[i]);
if (disabledTran != null) {
System.err.println("Disabling Error: "
+ disabledTran.getFullLabel() + " is disabled by "
+ firedTran.getFullLabel());
failure = true;
break main_while_loop;
}
}
if (Analysis.deadLock(lpnList, nextStateArray) == true) {
failure = true;
break main_while_loop;
}
/*
* Check if the local indices of nextStateArray already exist.
* if not, add it into reachable set, and push it onto stack.
*/
localIdxArray = Analysis.getLocalStateIdxArray(lpnList, nextStateArray, true);
Boolean existingState = false;
if (reachAll != null && mddMgr.contains(reachAll, localIdxArray) == true)
existingState = true;
else if (mddMgr.contains(reach, localIdxArray) == true)
existingState = true;
if (existingState == false) {
mddMgr.add(reach, localIdxArray, compressed);
newStateCnt++;
stateStack.push(nextStateArray);
lpnTranStack.push((LpnTranList) nextEnabledArray[0].clone());
curIndexStack.push(0);
totalStates++;
}
}
double totalStateCnt = mddMgr.numberOfStates(reach);
System.out.println("---> run statistics: \n"
+ "# LPN transition firings: " + tranFiringCnt + "\n"
+ "# of prjStates found: " + totalStateCnt + "\n"
+ "max_stack_depth: " + max_stack_depth + "\n"
+ "peak MDD nodes: " + peakMddNodeCnt + "\n"
+ "peak used memory: " + peakUsedMem / 1000000 + " MB\n"
+ "peak total memory: " + peakTotalMem / 1000000 + " MB\n");
return null;
}
/**
* findsg using iterative approach based on DFS search. The states found are
* stored in MDD.
*
* It is similar to findsg_dfs_mdd_1 except that when a state is considered
* during DFS, all enabled transition are fired, and all its successor
* states are found in an iteration.
*
* @param lpnList
* @param curLocalStateArray
* @param enabledArray
* @return a linked list of a sequence of LPN transitions leading to the
* failure if it is not empty.
*/
public Stack<State[]> search_dfs_mdd_2(final StateGraph[] lpnList, final State[] initStateArray) {
System.out.println("---> calling function search_dfs_mdd_2");
int tranFiringCnt = 0;
int totalStates = 0;
int arraySize = lpnList.length;
long peakUsedMem = 0;
long peakTotalMem = 0;
long peakMddNodeCnt = 0;
int memUpBound = 1000; // Set an upper bound of memory in MB usage to
// trigger MDD compression.
boolean failure = false;
MDT state2Explore = new MDT(arraySize);
state2Explore.push(initStateArray);
totalStates++;
long peakState2Explore = 0;
Stack<Integer> searchDepth = new Stack<Integer>();
searchDepth.push(1);
boolean compressed = false;
mddNode reachAll = null;
mddNode reach = mddMgr.newNode();
main_while_loop:
while (failure == false && state2Explore.empty() == false) {
long curTotalMem = Runtime.getRuntime().totalMemory();
long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
if (curTotalMem > peakTotalMem)
peakTotalMem = curTotalMem;
if (curUsedMem > peakUsedMem)
peakUsedMem = curUsedMem;
iterations++;
if (iterations % 100000 == 0) {
int mddNodeCnt = mddMgr.nodeCnt();
peakMddNodeCnt = peakMddNodeCnt > mddNodeCnt ? peakMddNodeCnt : mddNodeCnt;
int state2ExploreSize = state2Explore.size();
peakState2Explore = peakState2Explore > state2ExploreSize ? peakState2Explore : state2ExploreSize;
System.out.println("---> #iteration " + iterations
+ "> # LPN transition firings: " + tranFiringCnt
+ ", # of prjStates found: " + totalStates
+ ", # states to explore: " + state2ExploreSize
+ ", # MDT nodes: " + state2Explore.nodeCnt()
+ ", total MDD nodes: " + mddNodeCnt
+ " used memory: " + (float) curUsedMem / 1000000
+ " free memory: "
+ (float) Runtime.getRuntime().freeMemory() / 1000000);
if (curUsedMem >= memUpBound * 1000000) {
mddMgr.compress(reach);
if (reachAll == null)
reachAll = reach;
else {
mddNode newReachAll = mddMgr.union(reachAll, reach);
if (newReachAll != reachAll) {
mddMgr.remove(reachAll);
reachAll = newReachAll;
}
}
mddMgr.remove(reach);
reach = mddMgr.newNode();
}
}
State[] curStateArray = state2Explore.pop();
State[] nextStateArray = null;
int states2ExploreCurLevel = searchDepth.pop();
if(states2ExploreCurLevel > 1)
searchDepth.push(states2ExploreCurLevel-1);
int[] localIdxArray = Analysis.getLocalStateIdxArray(lpnList, curStateArray, false);
mddMgr.add(reach, localIdxArray, compressed);
int nextStates2Explore = 0;
for (int index = arraySize - 1; index >= 0; index
StateGraph curLpn = lpnList[index];
State curState = curStateArray[index];
LinkedList<Transition> curEnabledSet = curLpn.getEnabled(curState);
LpnTranList curEnabled = (LpnTranList) curEnabledSet.clone();
while (curEnabled.size() > 0) {
Transition firedTran = curEnabled.removeLast();
// TODO: (check) Not sure if curLpn.fire is correct.
nextStateArray = curLpn.fire(lpnList, curStateArray, firedTran);
tranFiringCnt++;
for (int i = 0; i < arraySize; i++) {
StateGraph lpn_tmp = lpnList[i];
if (curStateArray[i] == nextStateArray[i])
continue;
LinkedList<Transition> curEnabled_l = lpn_tmp.getEnabled(curStateArray[i]);
LinkedList<Transition> nextEnabled = lpn_tmp.getEnabled(nextStateArray[i]);
Transition disabledTran = firedTran.disablingError(curEnabled_l, nextEnabled);
if (disabledTran != null) {
System.err.println("Verification failed: disabling error: "
+ disabledTran.getFullLabel()
+ " disabled by "
+ firedTran.getFullLabel() + "!!!");
failure = true;
break main_while_loop;
}
}
if (Analysis.deadLock(lpnList, nextStateArray) == true) {
System.err.println("Verification failed: deadlock.");
failure = true;
break main_while_loop;
}
/*
* Check if the local indices of nextStateArray already exist.
*/
localIdxArray = Analysis.getLocalStateIdxArray(lpnList, nextStateArray, false);
Boolean existingState = false;
if (reachAll != null && mddMgr.contains(reachAll, localIdxArray) == true)
existingState = true;
else if (mddMgr.contains(reach, localIdxArray) == true)
existingState = true;
else if(state2Explore.contains(nextStateArray)==true)
existingState = true;
if (existingState == false) {
totalStates++;
//mddMgr.add(reach, localIdxArray, compressed);
state2Explore.push(nextStateArray);
nextStates2Explore++;
}
}
}
if(nextStates2Explore > 0)
searchDepth.push(nextStates2Explore);
}
System.out.println("
+ "---> run statistics: \n"
+ " # Depth of search (Length of Cex): " + searchDepth.size() + "\n"
+ " # LPN transition firings: " + (double)tranFiringCnt/1000000 + " M\n"
+ " # of prjStates found: " + (double)totalStates / 1000000 + " M\n"
+ " peak states to explore : " + (double) peakState2Explore / 1000000 + " M\n"
+ " peak MDD nodes: " + peakMddNodeCnt + "\n"
+ " peak used memory: " + peakUsedMem / 1000000 + " MB\n"
+ " peak total memory: " + peakTotalMem /1000000 + " MB\n"
+ "_____________________________________");
return null;
}
public LinkedList<Transition> search_bfs(final StateGraph[] sgList, final State[] initStateArray) {
System.out.println("---> starting search_bfs");
long peakUsedMem = 0;
long peakTotalMem = 0;
long peakMddNodeCnt = 0;
int memUpBound = 1000; // Set an upper bound of memory in MB usage to
// trigger MDD compression.
int arraySize = sgList.length;
for (int i = 0; i < arraySize; i++)
sgList[i].addState(initStateArray[i]);
mddNode reachSet = null;
mddNode reach = mddMgr.newNode();
MDT frontier = new MDT(arraySize);
MDT image = new MDT(arraySize);
frontier.push(initStateArray);
State[] curStateArray = null;
int tranFiringCnt = 0;
int totalStates = 0;
int imageSize = 0;
boolean verifyError = false;
bfsWhileLoop: while (true) {
if (verifyError == true)
break;
long curTotalMem = Runtime.getRuntime().totalMemory();
long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
if (curTotalMem > peakTotalMem)
peakTotalMem = curTotalMem;
if (curUsedMem > peakUsedMem)
peakUsedMem = curUsedMem;
long curMddNodeCnt = mddMgr.nodeCnt();
peakMddNodeCnt = peakMddNodeCnt > curMddNodeCnt ? peakMddNodeCnt : curMddNodeCnt;
iterations++;
System.out.println("iteration " + iterations
+ "> # LPN transition firings: " + tranFiringCnt
+ ", # of prjStates found: " + totalStates
+ ", total MDD nodes: " + curMddNodeCnt
+ " used memory: " + (float) curUsedMem / 1000000
+ " free memory: "
+ (float) Runtime.getRuntime().freeMemory() / 1000000);
if (curUsedMem >= memUpBound * 1000000) {
mddMgr.compress(reach);
if (reachSet == null)
reachSet = reach;
else {
mddNode newReachSet = mddMgr.union(reachSet, reach);
if (newReachSet != reachSet) {
mddMgr.remove(reachSet);
reachSet = newReachSet;
}
}
mddMgr.remove(reach);
reach = mddMgr.newNode();
}
while(frontier.empty() == false) {
boolean deadlock = true;
// Stack<State[]> curStateArrayList = frontier.pop();
// while(curStateArrayList.empty() == false) {
// curStateArray = curStateArrayList.pop();
{
curStateArray = frontier.pop();
int[] localIdxArray = Analysis.getLocalStateIdxArray(sgList, curStateArray, false);
mddMgr.add(reach, localIdxArray, false);
totalStates++;
for (int i = 0; i < arraySize; i++) {
LinkedList<Transition> curEnabled = sgList[i].getEnabled(curStateArray[i]);
if (curEnabled.size() > 0)
deadlock = false;
for (Transition firedTran : curEnabled) {
// TODO: (check) Not sure if sgList[i].fire is correct.
State[] nextStateArray = sgList[i].fire(sgList, curStateArray, firedTran);
tranFiringCnt++;
/*
* Check if any transitions can be disabled by fireTran.
*/
LinkedList<Transition> nextEnabled = sgList[i].getEnabled(nextStateArray[i]);
Transition disabledTran = firedTran.disablingError(curEnabled, nextEnabled);
if (disabledTran != null) {
System.err.println("*** Verification failed: disabling error: "
+ disabledTran.getFullLabel()
+ " disabled by "
+ firedTran.getFullLabel() + "!!!");
verifyError = true;
break bfsWhileLoop;
}
localIdxArray = Analysis.getLocalStateIdxArray(sgList, nextStateArray, false);
if (mddMgr.contains(reachSet, localIdxArray) == false && mddMgr.contains(reach, localIdxArray) == false && frontier.contains(nextStateArray) == false) {
if(image.contains(nextStateArray)==false) {
image.push(nextStateArray);
imageSize++;
}
}
}
}
}
/*
* If curStateArray deadlocks (no enabled transitions), terminate.
*/
if (deadlock == true) {
System.err.println("*** Verification failed: deadlock.");
verifyError = true;
break bfsWhileLoop;
}
}
if(image.empty()==true) break;
System.out.println("---> size of image: " + imageSize);
frontier = image;
image = new MDT(arraySize);
imageSize = 0;
}
System.out.println("---> final numbers: # LPN transition firings: " + tranFiringCnt / 1000000 + "M\n"
+ "---> # of prjStates found: " + (double) totalStates / 1000000 + "M\n"
+ "---> peak total memory: " + peakTotalMem / 1000000F + " MB\n"
+ "---> peak used memory: " + peakUsedMem / 1000000F + " MB\n"
+ "---> peak MDD nodes: " + peakMddNodeCnt);
return null;
}
/**
* BFS findsg using iterative approach. THe states found are stored in MDD.
*
* @param lpnList
* @param curLocalStateArray
* @param enabledArray
* @return a linked list of a sequence of LPN transitions leading to the
* failure if it is not empty.
*/
public LinkedList<Transition> search_bfs_mdd_localFirings(final StateGraph[] lpnList, final State[] initStateArray) {
System.out.println("---> starting search_bfs");
long peakUsedMem = 0;
long peakTotalMem = 0;
int arraySize = lpnList.length;
for (int i = 0; i < arraySize; i++)
lpnList[i].addState(initStateArray[i]);
// mddNode reachSet = mddMgr.newNode();
// mddMgr.add(reachSet, curLocalStateArray);
mddNode reachSet = null;
mddNode exploredSet = null;
LinkedList<State>[] nextSetArray = (LinkedList<State>[]) (new LinkedList[arraySize]);
for (int i = 0; i < arraySize; i++)
nextSetArray[i] = new LinkedList<State>();
mddNode initMdd = mddMgr.doLocalFirings(lpnList, initStateArray, null);
mddNode curMdd = initMdd;
reachSet = curMdd;
mddNode nextMdd = null;
int[] curStateArray = null;
int tranFiringCnt = 0;
boolean verifyError = false;
bfsWhileLoop: while (true) {
if (verifyError == true)
break;
long curTotalMem = Runtime.getRuntime().totalMemory();
long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
if (curTotalMem > peakTotalMem)
peakTotalMem = curTotalMem;
if (curUsedMem > peakUsedMem)
peakUsedMem = curUsedMem;
curStateArray = mddMgr.next(curMdd, curStateArray);
if (curStateArray == null) {
// Break the loop if no new next states are found.
// System.out.println("nextSet size " + nextSet.size());
if (nextMdd == null)
break bfsWhileLoop;
if (exploredSet == null)
exploredSet = curMdd;
else {
mddNode newExplored = mddMgr.union(exploredSet, curMdd);
if (newExplored != exploredSet)
mddMgr.remove(exploredSet);
exploredSet = newExplored;
}
mddMgr.remove(curMdd);
curMdd = nextMdd;
nextMdd = null;
iterations++;
System.out.println("iteration " + iterations
+ "> # LPN transition firings: " + tranFiringCnt
+ ", # of union calls: " + mddNode.numCalls
+ ", # of union cache nodes: " + mddNode.cacheNodes
+ ", total MDD nodes: " + mddMgr.nodeCnt()
+ " used memory: " + (float) curUsedMem / 1000000
+ " free memory: "
+ (float) Runtime.getRuntime().freeMemory() / 1000000);
System.out.println("---> # of prjStates found: " + mddMgr.numberOfStates(reachSet)
+ ", CurSet.Size = " + mddMgr.numberOfStates(curMdd));
continue;
}
if (exploredSet != null && mddMgr.contains(exploredSet, curStateArray) == true)
continue;
// If curStateArray deadlocks (no enabled transitions), terminate.
if (Analysis.deadLock(lpnList, curStateArray) == true) {
System.err.println("*** Verification failed: deadlock.");
verifyError = true;
break bfsWhileLoop;
}
// Do firings of non-local LPN transitions.
for (int index = arraySize - 1; index >= 0; index
StateGraph curLpn = lpnList[index];
LinkedList<Transition> curLocalEnabled = curLpn.getEnabled(curStateArray[index]);
if (curLocalEnabled.size() == 0 || curLocalEnabled.getFirst().isLocal() == true)
continue;
for (Transition firedTran : curLocalEnabled) {
if (firedTran.isLocal() == true)
continue;
// TODO: (check) Not sure if curLpn.fire is correct.
State[] nextStateArray = curLpn.fire(lpnList, curStateArray, firedTran);
tranFiringCnt++;
@SuppressWarnings("unused")
ArrayList<LinkedList<Transition>> nextEnabledArray = new ArrayList<LinkedList<Transition>>(1);
for (int i = 0; i < arraySize; i++) {
if (curStateArray[i] == nextStateArray[i].getIndex())
continue;
StateGraph lpn_tmp = lpnList[i];
LinkedList<Transition> curEnabledList = lpn_tmp.getEnabled(curStateArray[i]);
LinkedList<Transition> nextEnabledList = lpn_tmp.getEnabled(nextStateArray[i].getIndex());
Transition disabledTran = firedTran.disablingError(curEnabledList, nextEnabledList);
if (disabledTran != null) {
System.err.println("Verification failed: disabling error: "
+ disabledTran.getFullLabel()
+ ": is disabled by "
+ firedTran.getFullLabel() + "!!!");
verifyError = true;
break bfsWhileLoop;
}
}
if (Analysis.deadLock(lpnList, nextStateArray) == true) {
verifyError = true;
break bfsWhileLoop;
}
// Add nextPrjState into prjStateSet
// If nextPrjState has been traversed before, skip to the
// next
// enabled transition.
int[] nextIdxArray = Analysis.getIdxArray(nextStateArray);
if (reachSet != null && mddMgr.contains(reachSet, nextIdxArray) == true)
continue;
mddNode newNextMdd = mddMgr.doLocalFirings(lpnList, nextStateArray, reachSet);
mddNode newReachSet = mddMgr.union(reachSet, newNextMdd);
if (newReachSet != reachSet)
mddMgr.remove(reachSet);
reachSet = newReachSet;
if (nextMdd == null)
nextMdd = newNextMdd;
else {
mddNode tmpNextMdd = mddMgr.union(nextMdd, newNextMdd);
if (tmpNextMdd != nextMdd)
mddMgr.remove(nextMdd);
nextMdd = tmpNextMdd;
mddMgr.remove(newNextMdd);
}
}
}
}
System.out.println("---> final numbers: # LPN transition firings: "
+ tranFiringCnt + "\n" + "---> # of prjStates found: "
+ (mddMgr.numberOfStates(reachSet)) + "\n"
+ "---> peak total memory: " + peakTotalMem / 1000000F
+ " MB\n" + "---> peak used memory: " + peakUsedMem / 1000000F
+ " MB\n" + "---> peak MMD nodes: " + mddMgr.peakNodeCnt());
return null;
}
/**
* partial order reduction (Original version of Hao's POR with behavioral analysis)
* This method is not used anywhere. See searchPOR_behavioral for POR with behavioral analysis.
*
* @param lpnList
* @param curLocalStateArray
* @param enabledArray
*/
public Stack<State[]> search_dfs_por(final StateGraph[] lpnList, final State[] initStateArray, LPNTranRelation lpnTranRelation, String approach) {
System.out.println("---> Calling search_dfs with partial order reduction");
long peakUsedMem = 0;
long peakTotalMem = 0;
double stateCount = 1;
int max_stack_depth = 0;
int iterations = 0;
boolean useMdd = true;
mddNode reach = mddMgr.newNode();
//init por
verification.platu.por1.AmpleSet ampleClass = new verification.platu.por1.AmpleSet();
//AmpleSubset ampleClass = new AmpleSubset();
HashMap<Transition,HashSet<Transition>> indepTranSet = new HashMap<Transition,HashSet<Transition>>();
if(approach == "state")
indepTranSet = ampleClass.getIndepTranSet_FromState(lpnList, lpnTranRelation);
else if (approach == "lpn")
indepTranSet = ampleClass.getIndepTranSet_FromLPN(lpnList);
System.out.println("finish get independent set!!!!");
boolean failure = false;
int tranFiringCnt = 0;
int arraySize = lpnList.length;;
HashSet<PrjState> stateStack = new HashSet<PrjState>();
Stack<LpnTranList> lpnTranStack = new Stack<LpnTranList>();
Stack<HashSet<Transition>> firedTranStack = new Stack<HashSet<Transition>>();
//get initial enable transition set
@SuppressWarnings("unchecked")
LinkedList<Transition>[] initEnabledArray = new LinkedList[arraySize];
for (int i = 0; i < arraySize; i++) {
lpnList[i].getLpn().setLpnIndex(i);
initEnabledArray[i] = lpnList[i].getEnabled(initStateArray[i]);
}
//set initEnableSubset
//LPNTranSet initEnableSubset = ampleClass.generateAmpleList(false, approach,initEnabledArray, indepTranSet);
LpnTranList initEnableSubset = ampleClass.generateAmpleTranSet(initEnabledArray, indepTranSet);
/*
* Initialize the reach state set with the initial state.
*/
HashSet<PrjState> prjStateSet = new HashSet<PrjState>();
PrjState initPrjState = new PrjState(initStateArray);
if (useMdd) {
int[] initIdxArray = Analysis.getIdxArray(initStateArray);
mddMgr.add(reach, initIdxArray, true);
}
else
prjStateSet.add(initPrjState);
stateStack.add(initPrjState);
PrjState stateStackTop = initPrjState;
lpnTranStack.push(initEnableSubset);
firedTranStack.push(new HashSet<Transition>());
/*
* Start the main search loop.
*/
main_while_loop:
while(failure == false && stateStack.size() != 0) {
long curTotalMem = Runtime.getRuntime().totalMemory();
long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
if (curTotalMem > peakTotalMem)
peakTotalMem = curTotalMem;
if (curUsedMem > peakUsedMem)
peakUsedMem = curUsedMem;
if (stateStack.size() > max_stack_depth)
max_stack_depth = stateStack.size();
iterations++;
if (iterations % 500000 == 0) {
if (useMdd==true)
stateCount = mddMgr.numberOfStates(reach);
else
stateCount = prjStateSet.size();
System.out.println("---> #iteration " + iterations
+ "> # LPN transition firings: " + tranFiringCnt
+ ", # of prjStates found: " + stateCount
+ ", max_stack_depth: " + max_stack_depth
+ ", total MDD nodes: " + mddMgr.nodeCnt()
+ " used memory: " + (float) curUsedMem / 1000000
+ " free memory: "
+ (float) Runtime.getRuntime().freeMemory() / 1000000);
}
State[] curStateArray = stateStackTop.toStateArray();
LpnTranList curEnabled = lpnTranStack.peek();
// for (LPNTran tran : curEnabled)
// for (int i = 0; i < arraySize; i++)
// if (lpnList[i] == tran.getLpn())
// if (tran.isEnabled(curStateArray[i]) == false) {
// System.out.println("transition " + tran.getFullLabel() + " not enabled in the current state");
// System.exit(0);
// If all enabled transitions of the current LPN are considered, then consider the next LPN
// by increasing the curIndex.
// Otherwise, if all enabled transitions of all LPNs are considered, then pop the stacks.
if(curEnabled.size() == 0) {
lpnTranStack.pop();
firedTranStack.pop();
stateStack.remove(stateStackTop);
stateStackTop = stateStackTop.getFather();
if (stateStack.size() > 0)
traceCex.removeLast();
continue;
}
Transition firedTran = curEnabled.removeFirst();
firedTranStack.peek().add(firedTran);
traceCex.addLast(firedTran);
//System.out.println(tranFiringCnt + ": firedTran: "+ firedTran.getFullLabel());
// TODO: (??) Not sure if the state graph sg below is correct.
StateGraph sg = null;
for (int i=0; i<lpnList.length; i++) {
if (lpnList[i].getLpn().equals(firedTran.getLpn())) {
sg = lpnList[i];
}
}
State[] nextStateArray = sg.fire(lpnList, curStateArray, firedTran);
tranFiringCnt++;
// Check if the firedTran causes disabling error or deadlock.
@SuppressWarnings("unchecked")
LinkedList<Transition>[] curEnabledArray = new LinkedList[arraySize];
@SuppressWarnings("unchecked")
LinkedList<Transition>[] nextEnabledArray = new LinkedList[arraySize];
for (int i = 0; i < arraySize; i++) {
lpnList[i].getLpn().setLpnIndex(i);
StateGraph lpn_tmp = lpnList[i];
LinkedList<Transition> enabledList = lpn_tmp.getEnabled(curStateArray[i]);
curEnabledArray[i] = enabledList;
enabledList = lpn_tmp.getEnabled(nextStateArray[i]);
nextEnabledArray[i] = enabledList;
Transition disabledTran = firedTran.disablingError(curEnabledArray[i], nextEnabledArray[i]);
if(disabledTran != null) {
System.out.println("---> Disabling Error: " + disabledTran.getFullLabel() + " is disabled by " + firedTran.getFullLabel());
System.out.println("Current state:");
for(int ii = 0; ii < arraySize; ii++) {
System.out.println("module " + lpnList[ii].getLpn().getLabel());
System.out.println(curStateArray[ii]);
System.out.println("Enabled set: " + curEnabledArray[ii]);
}
System.out.println("======================\nNext state:");
for(int ii = 0; ii < arraySize; ii++) {
System.out.println("module " + lpnList[ii].getLpn().getLabel());
System.out.println(nextStateArray[ii]);
System.out.println("Enabled set: " + nextEnabledArray[ii]);
}
System.out.println();
failure = true;
break main_while_loop;
}
}
if (Analysis.deadLock(lpnList, nextStateArray) == true) {
System.out.println("---> Deadlock.");
// System.out.println("Deadlock state:");
// for(int ii = 0; ii < arraySize; ii++) {
// System.out.println("module " + lpnList[ii].getLabel());
// System.out.println(nextStateArray[ii]);
// System.out.println("Enabled set: " + nextEnabledArray[ii]);
failure = true;
break main_while_loop;
}
/*
// Add nextPrjState into prjStateSet
// If nextPrjState has been traversed before, skip to the next
// enabled transition.
//exist cycle
*/
PrjState nextPrjState = new PrjState(nextStateArray);
boolean isExisting = false;
int[] nextIdxArray = null;
if(useMdd==true)
nextIdxArray = Analysis.getIdxArray(nextStateArray);
if (useMdd == true)
isExisting = mddMgr.contains(reach, nextIdxArray);
else
isExisting = prjStateSet.contains(nextPrjState);
if (isExisting == false) {
if (useMdd == true) {
mddMgr.add(reach, nextIdxArray, true);
}
else
prjStateSet.add(nextPrjState);
//get next enable transition set
//LPNTranSet nextEnableSubset = ampleClass.generateAmpleList(false, approach, nextEnabledArray, indepTranSet);
LpnTranList nextEnableSubset = ampleClass.generateAmpleTranSet(nextEnabledArray, indepTranSet);
// LPNTranSet nextEnableSubset = new LPNTranSet();
// for (int i = 0; i < arraySize; i++)
// for (LPNTran tran : nextEnabledArray[i])
// nextEnableSubset.addLast(tran);
stateStack.add(nextPrjState);
stateStackTop.setChild(nextPrjState);
nextPrjState.setFather(stateStackTop);
stateStackTop = nextPrjState;
lpnTranStack.push(nextEnableSubset);
firedTranStack.push(new HashSet<Transition>());
// for (int i = 0; i < arraySize; i++)
// for (LPNTran tran : nextEnabledArray[i])
// System.out.print(tran.getFullLabel() + ", ");
// System.out.println("\n");
// for (LPNTran tran : nextEnableSubset)
// System.out.print(tran.getFullLabel() + ", ");
// HashSet<LPNTran> allEnabledSet = new HashSet<LPNTran>();
// for (int i = 0; i < arraySize; i++) {
// for (LPNTran tran : nextEnabledArray[i]) {
// allEnabledSet.add(tran);
// System.out.print(tran.getFullLabel() + ", ");
// System.out.println("\n");
// if(nextEnableSubset.size() > 0) {
// for (LPNTran tran : nextEnableSubset) {
// if (allEnabledSet.contains(tran) == false) {
// System.out.println("\n\n" + tran.getFullLabel() + " in reduced set but not enabled\n");
// System.exit(0);
// System.out.print(tran.getFullLabel() + ", ");
// System.out.println("\n
continue;
}
/*
* Remove firedTran from traceCex if its successor state already exists.
*/
traceCex.removeLast();
/*
* When firedTran forms a cycle in the state graph, consider all enabled transitions except those
* 1. already fired in the current state,
* 2. in the ample set of the next state.
*/
if(stateStack.contains(nextPrjState)==true && curEnabled.size()==0) {
//System.out.println("formed a cycle......");
LpnTranList original = new LpnTranList();
LpnTranList reduced = new LpnTranList();
//LPNTranSet nextStateAmpleSet = ampleClass.generateAmpleList(false, approach, nextEnabledArray, indepTranSet);
LpnTranList nextStateAmpleSet = ampleClass.generateAmpleTranSet(nextEnabledArray, indepTranSet);
// System.out.println("Back state's ample set:");
// for(LPNTran tran : nextStateAmpleSet)
// System.out.print(tran.getFullLabel() + ", ");
// System.out.println("\n");
int enabledTranCnt = 0;
LpnTranList[] tmp = new LpnTranList[arraySize];
for (int i = 0; i < arraySize; i++) {
tmp[i] = new LpnTranList();
for (Transition tran : curEnabledArray[i]) {
original.addLast(tran);
if (firedTranStack.peek().contains(tran)==false && nextStateAmpleSet.contains(tran)==false) {
tmp[i].addLast(tran);
reduced.addLast(tran);
enabledTranCnt++;
}
}
}
LpnTranList ampleSet = new LpnTranList();
if(enabledTranCnt > 0)
//ampleSet = ampleClass.generateAmpleList(false, approach, tmp, indepTranSet);
ampleSet = ampleClass.generateAmpleTranSet(tmp, indepTranSet);
LpnTranList sortedAmpleSet = ampleSet;
/*
* Sort transitions in ampleSet for better performance for MDD.
* Not needed for hash table.
*/
if (useMdd == true) {
LpnTranList[] newCurEnabledArray = new LpnTranList[arraySize];
for (int i = 0; i < arraySize; i++)
newCurEnabledArray[i] = new LpnTranList();
for (Transition tran : ampleSet)
newCurEnabledArray[tran.getLpn().getLpnIndex()].addLast(tran);
sortedAmpleSet = new LpnTranList();
for (int i = 0; i < arraySize; i++) {
LpnTranList localEnabledSet = newCurEnabledArray[i];
for (Transition tran : localEnabledSet)
sortedAmpleSet.addLast(tran);
}
}
// for(LPNTran tran : original)
// System.out.print(tran.getFullLabel() + ", ");
// System.out.println("\n");
// for(LPNTran tran : ampleSet)
// System.out.print(tran.getFullLabel() + ", ");
// System.out.println("\n");
// for(LPNTran tran : firedTranStack.peek())
// allCurEnabled.remove(tran);
lpnTranStack.pop();
lpnTranStack.push(sortedAmpleSet);
// for (int i = 0; i < arraySize; i++) {
// for (LPNTran tran : curEnabledArray[i]) {
// System.out.print(tran.getFullLabel() + ", ");
// System.out.println("\n");
// for(LPNTran tran : allCurEnabled)
// System.out.print(tran.getFullLabel() + ", ");
}
//System.out.println("Backtrack........\n");
}//END while (stateStack.empty() == false)
if (useMdd==true)
stateCount = mddMgr.numberOfStates(reach);
else
stateCount = prjStateSet.size();
//long curTotalMem = Runtime.getRuntime().totalMemory();
long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
System.out.println("SUMMARY: # LPN transition firings: " + tranFiringCnt
+ ", # of prjStates found: " + stateCount
+ ", max_stack_depth: " + max_stack_depth
+ ", used memory: " + (float) curUsedMem / 1000000
+ ", free memory: "
+ (float) Runtime.getRuntime().freeMemory() / 1000000);
return null;
}
/**
* partial order reduction with behavioral analysis. (Adapted from search_dfs_por.)
*
* @param sgList
* @param curLocalStateArray
* @param enabledArray
*/
public StateGraph[] searchPOR_behavioral(final StateGraph[] sgList, final State[] initStateArray, LPNTranRelation lpnTranRelation, String approach) {
System.out.println("---> calling function searchPOR_behavioral");
System.out.println("---> " + Options.getPOR());
long peakUsedMem = 0;
long peakTotalMem = 0;
double stateCount = 1;
int max_stack_depth = 0;
int iterations = 0;
//boolean useMdd = true;
boolean useMdd = false;
mddNode reach = mddMgr.newNode();
//init por
AmpleSet ampleClass = new AmpleSet();
//AmpleSubset ampleClass = new AmpleSubset();
HashMap<Transition,HashSet<Transition>> indepTranSet = new HashMap<Transition,HashSet<Transition>>();
if(approach == "state")
indepTranSet = ampleClass.getIndepTranSet_FromState(sgList, lpnTranRelation);
else if (approach == "lpn")
indepTranSet = ampleClass.getIndepTranSet_FromLPN(sgList);
System.out.println("finish get independent set!!!!");
boolean failure = false;
int tranFiringCnt = 0;
int arraySize = sgList.length;;
HashSet<PrjState> stateStack = new HashSet<PrjState>();
Stack<LpnTranList> lpnTranStack = new Stack<LpnTranList>();
Stack<HashSet<Transition>> firedTranStack = new Stack<HashSet<Transition>>();
//get initial enable transition set
@SuppressWarnings("unchecked")
LinkedList<Transition>[] initEnabledArray = new LinkedList[arraySize];
for (int i = 0; i < arraySize; i++) {
sgList[i].getLpn().setLpnIndex(i);
initEnabledArray[i] = sgList[i].getEnabled(initStateArray[i]);
}
//set initEnableSubset
//LPNTranSet initEnableSubset = ampleClass.generateAmpleList(false, approach,initEnabledArray, indepTranSet);
LpnTranList initEnableSubset = ampleClass.generateAmpleTranSet(initEnabledArray, indepTranSet);
/*
* Initialize the reach state set with the initial state.
*/
HashSet<PrjState> prjStateSet = new HashSet<PrjState>();
PrjState initPrjState = new PrjState(initStateArray);
if (useMdd) {
int[] initIdxArray = Analysis.getIdxArray(initStateArray);
mddMgr.add(reach, initIdxArray, true);
}
else
prjStateSet.add(initPrjState);
stateStack.add(initPrjState);
PrjState stateStackTop = initPrjState;
lpnTranStack.push(initEnableSubset);
firedTranStack.push(new HashSet<Transition>());
/*
* Start the main search loop.
*/
main_while_loop:
while(failure == false && stateStack.size() != 0) {
long curTotalMem = Runtime.getRuntime().totalMemory();
long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
if (curTotalMem > peakTotalMem)
peakTotalMem = curTotalMem;
if (curUsedMem > peakUsedMem)
peakUsedMem = curUsedMem;
if (stateStack.size() > max_stack_depth)
max_stack_depth = stateStack.size();
iterations++;
if (iterations % 500000 == 0) {
if (useMdd==true)
stateCount = mddMgr.numberOfStates(reach);
else
stateCount = prjStateSet.size();
System.out.println("---> #iteration " + iterations
+ "> # LPN transition firings: " + tranFiringCnt
+ ", # of prjStates found: " + stateCount
+ ", max_stack_depth: " + max_stack_depth
+ ", total MDD nodes: " + mddMgr.nodeCnt()
+ " used memory: " + (float) curUsedMem / 1000000
+ " free memory: "
+ (float) Runtime.getRuntime().freeMemory() / 1000000);
}
State[] curStateArray = stateStackTop.toStateArray();
LpnTranList curEnabled = lpnTranStack.peek();
// for (LPNTran tran : curEnabled)
// for (int i = 0; i < arraySize; i++)
// if (lpnList[i] == tran.getLpn())
// if (tran.isEnabled(curStateArray[i]) == false) {
// System.out.println("transition " + tran.getFullLabel() + " not enabled in the current state");
// System.exit(0);
// If all enabled transitions of the current LPN are considered, then consider the next LPN
// by increasing the curIndex.
// Otherwise, if all enabled transitions of all LPNs are considered, then pop the stacks.
if(curEnabled.size() == 0) {
lpnTranStack.pop();
firedTranStack.pop();
stateStack.remove(stateStackTop);
stateStackTop = stateStackTop.getFather();
if (stateStack.size() > 0)
traceCex.removeLast();
continue;
}
Transition firedTran = curEnabled.removeFirst();
firedTranStack.peek().add(firedTran);
traceCex.addLast(firedTran);
StateGraph sg = null;
for (int i=0; i<sgList.length; i++) {
if (sgList[i].getLpn().equals(firedTran.getLpn())) {
sg = sgList[i];
}
}
State[] nextStateArray = sg.fire(sgList, curStateArray, firedTran);
tranFiringCnt++;
// Check if the firedTran causes disabling error or deadlock.
@SuppressWarnings("unchecked")
LinkedList<Transition>[] curEnabledArray = new LinkedList[arraySize];
@SuppressWarnings("unchecked")
LinkedList<Transition>[] nextEnabledArray = new LinkedList[arraySize];
for (int i = 0; i < arraySize; i++) {
sgList[i].getLpn().setLpnIndex(i);
StateGraph lpn_tmp = sgList[i];
LinkedList<Transition> enabledList = lpn_tmp.getEnabled(curStateArray[i]);
curEnabledArray[i] = enabledList;
enabledList = lpn_tmp.getEnabled(nextStateArray[i]);
nextEnabledArray[i] = enabledList;
Transition disabledTran = firedTran.disablingError(curEnabledArray[i], nextEnabledArray[i]);
if(disabledTran != null) {
System.out.println("---> Disabling Error: " + disabledTran.getFullLabel() + " is disabled by " + firedTran.getFullLabel());
System.out.println("Current state:");
for(int ii = 0; ii < arraySize; ii++) {
System.out.println("module " + sgList[ii].getLpn().getLabel());
System.out.println(curStateArray[ii]);
System.out.println("Enabled set: " + curEnabledArray[ii]);
}
System.out.println("======================\nNext state:");
for(int ii = 0; ii < arraySize; ii++) {
System.out.println("module " + sgList[ii].getLpn().getLabel());
System.out.println(nextStateArray[ii]);
System.out.println("Enabled set: " + nextEnabledArray[ii]);
}
System.out.println();
failure = true;
break main_while_loop;
}
}
if (Analysis.deadLock(sgList, nextStateArray) == true) {
System.out.println("---> Deadlock.");
// System.out.println("Deadlock state:");
// for(int ii = 0; ii < arraySize; ii++) {
// System.out.println("module " + lpnList[ii].getLabel());
// System.out.println(nextStateArray[ii]);
// System.out.println("Enabled set: " + nextEnabledArray[ii]);
failure = true;
break main_while_loop;
}
/*
// Add nextPrjState into prjStateSet
// If nextPrjState has been traversed before, skip to the next
// enabled transition.
//exist cycle
*/
PrjState nextPrjState = new PrjState(nextStateArray);
boolean isExisting = false;
int[] nextIdxArray = null;
if(useMdd==true)
nextIdxArray = Analysis.getIdxArray(nextStateArray);
if (useMdd == true)
isExisting = mddMgr.contains(reach, nextIdxArray);
else
isExisting = prjStateSet.contains(nextPrjState);
if (isExisting == false) {
if (useMdd == true) {
mddMgr.add(reach, nextIdxArray, true);
}
else
prjStateSet.add(nextPrjState);
//get next enable transition set
//LPNTranSet nextEnableSubset = ampleClass.generateAmpleList(false, approach, nextEnabledArray, indepTranSet);
LpnTranList nextEnableSubset = ampleClass.generateAmpleTranSet(nextEnabledArray, indepTranSet);
// LPNTranSet nextEnableSubset = new LPNTranSet();
// for (int i = 0; i < arraySize; i++)
// for (LPNTran tran : nextEnabledArray[i])
// nextEnableSubset.addLast(tran);
stateStack.add(nextPrjState);
stateStackTop.setChild(nextPrjState);
nextPrjState.setFather(stateStackTop);
stateStackTop = nextPrjState;
lpnTranStack.push(nextEnableSubset);
firedTranStack.push(new HashSet<Transition>());
// for (int i = 0; i < arraySize; i++)
// for (LPNTran tran : nextEnabledArray[i])
// System.out.print(tran.getFullLabel() + ", ");
// System.out.println("\n");
// for (LPNTran tran : nextEnableSubset)
// System.out.print(tran.getFullLabel() + ", ");
// HashSet<LPNTran> allEnabledSet = new HashSet<LPNTran>();
// for (int i = 0; i < arraySize; i++) {
// for (LPNTran tran : nextEnabledArray[i]) {
// allEnabledSet.add(tran);
// System.out.print(tran.getFullLabel() + ", ");
// System.out.println("\n");
// if(nextEnableSubset.size() > 0) {
// for (LPNTran tran : nextEnableSubset) {
// if (allEnabledSet.contains(tran) == false) {
// System.out.println("\n\n" + tran.getFullLabel() + " in reduced set but not enabled\n");
// System.exit(0);
// System.out.print(tran.getFullLabel() + ", ");
// System.out.println("\n
continue;
}
/*
* Remove firedTran from traceCex if its successor state already exists.
*/
traceCex.removeLast();
/*
* When firedTran forms a cycle in the state graph, consider all enabled transitions except those
* 1. already fired in the current state,
* 2. in the ample set of the next state.
*/
if(stateStack.contains(nextPrjState)==true && curEnabled.size()==0) {
//System.out.println("formed a cycle......");
LpnTranList original = new LpnTranList();
LpnTranList reduced = new LpnTranList();
//LPNTranSet nextStateAmpleSet = ampleClass.generateAmpleList(false, approach, nextEnabledArray, indepTranSet);
LpnTranList nextStateAmpleSet = ampleClass.generateAmpleTranSet(nextEnabledArray, indepTranSet);
// System.out.println("Back state's ample set:");
// for(LPNTran tran : nextStateAmpleSet)
// System.out.print(tran.getFullLabel() + ", ");
// System.out.println("\n");
int enabledTranCnt = 0;
LpnTranList[] tmp = new LpnTranList[arraySize];
for (int i = 0; i < arraySize; i++) {
tmp[i] = new LpnTranList();
for (Transition tran : curEnabledArray[i]) {
original.addLast(tran);
if (firedTranStack.peek().contains(tran)==false && nextStateAmpleSet.contains(tran)==false) {
tmp[i].addLast(tran);
reduced.addLast(tran);
enabledTranCnt++;
}
}
}
LpnTranList ampleSet = new LpnTranList();
if(enabledTranCnt > 0)
//ampleSet = ampleClass.generateAmpleList(false, approach, tmp, indepTranSet);
ampleSet = ampleClass.generateAmpleTranSet(tmp, indepTranSet);
LpnTranList sortedAmpleSet = ampleSet;
/*
* Sort transitions in ampleSet for better performance for MDD.
* Not needed for hash table.
*/
if (useMdd == true) {
LpnTranList[] newCurEnabledArray = new LpnTranList[arraySize];
for (int i = 0; i < arraySize; i++)
newCurEnabledArray[i] = new LpnTranList();
for (Transition tran : ampleSet)
newCurEnabledArray[tran.getLpn().getLpnIndex()].addLast(tran);
sortedAmpleSet = new LpnTranList();
for (int i = 0; i < arraySize; i++) {
LpnTranList localEnabledSet = newCurEnabledArray[i];
for (Transition tran : localEnabledSet)
sortedAmpleSet.addLast(tran);
}
}
// for(LPNTran tran : original)
// System.out.print(tran.getFullLabel() + ", ");
// System.out.println("\n");
// for(LPNTran tran : ampleSet)
// System.out.print(tran.getFullLabel() + ", ");
// System.out.println("\n");
// for(LPNTran tran : firedTranStack.peek())
// allCurEnabled.remove(tran);
lpnTranStack.pop();
lpnTranStack.push(sortedAmpleSet);
// for (int i = 0; i < arraySize; i++) {
// for (LPNTran tran : curEnabledArray[i]) {
// System.out.print(tran.getFullLabel() + ", ");
// System.out.println("\n");
// for(LPNTran tran : allCurEnabled)
// System.out.print(tran.getFullLabel() + ", ");
}
//System.out.println("Backtrack........\n");
}//END while (stateStack.empty() == false)
if (useMdd==true)
stateCount = mddMgr.numberOfStates(reach);
else
stateCount = prjStateSet.size();
//long curTotalMem = Runtime.getRuntime().totalMemory();
long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
System.out.println("SUMMARY: # LPN transition firings: " + tranFiringCnt
+ ", # of prjStates found: " + stateCount
+ ", max_stack_depth: " + max_stack_depth
+ ", used memory: " + (float) curUsedMem / 1000000
+ ", free memory: "
+ (float) Runtime.getRuntime().freeMemory() / 1000000);
return sgList;
}
// /**
// * Check if this project deadlocks in the current state 'stateArray'.
// * @param sgList
// * @param stateArray
// * @param staticSetsMap
// * @param enableSet
// * @param disableByStealingToken
// * @param disableSet
// * @param init
// * @return
// */
// // Called by search search_dfsPOR
// public boolean deadLock(StateGraph[] sgList, State[] stateArray, HashMap<Transition,StaticSets> staticSetsMap,
// boolean init, HashMap<Transition, Integer> tranFiringFreq, HashSet<PrjState> stateStack, PrjState stateStackTop, int cycleClosingMethdIndex) {
// boolean deadlock = true;
// System.out.println("@ deadlock:");
//// for (int i = 0; i < stateArray.length; i++) {
//// LinkedList<Transition> tmp = getAmple(stateArray, null, staticSetsMap, init, tranFiringFreq, sgList, stateStack, stateStackTop, cycleClosingMethdIndex).getAmpleSet();
//// if (tmp.size() > 0) {
//// deadlock = false;
//// break;
// LinkedList<Transition> tmp = getAmple(stateArray, null, staticSetsMap, init, tranFiringFreq, sgList, stateStack, stateStackTop, cycleClosingMethdIndex).getAmpleSet();
// if (tmp.size() > 0) {
// deadlock = false;
// System.out.println("@ end of deadlock");
// return deadlock;
public static boolean deadLock(StateGraph[] lpnArray, State[] stateArray) {
boolean deadlock = true;
for (int i = 0; i < stateArray.length; i++) {
LinkedList<Transition> tmp = lpnArray[i].getEnabled(stateArray[i]);
if (tmp.size() > 0) {
deadlock = false;
break;
}
}
return deadlock;
}
public static boolean deadLock(StateGraph[] lpnArray, int[] stateIdxArray) {
boolean deadlock = true;
for (int i = 0; i < stateIdxArray.length; i++) {
LinkedList<Transition> tmp = lpnArray[i].getEnabled(stateIdxArray[i]);
if (tmp.size() > 0) {
deadlock = false;
break;
}
}
return deadlock;
}
public static boolean deadLock(LinkedList<Transition>[] lpnList) {
boolean deadlock = true;
for (int i = 0; i < lpnList.length; i++) {
LinkedList<Transition> tmp = lpnList[i];
if (tmp.size() > 0) {
deadlock = false;
break;
}
}
return deadlock;
}
// /*
// * Scan enabledArray, identify all sticky transitions other the firedTran, and return them.
// *
// * Arguments remain constant.
// */
// public static LpnTranList[] getStickyTrans(LpnTranList[] enabledArray, Transition firedTran) {
// int arraySize = enabledArray.length;
// LpnTranList[] stickyTranArray = new LpnTranList[arraySize];
// for (int i = 0; i < arraySize; i++) {
// stickyTranArray[i] = new LpnTranList();
// for (Transition tran : enabledArray[i]) {
// if (tran != firedTran)
// stickyTranArray[i].add(tran);
// if(stickyTranArray[i].size()==0)
// stickyTranArray[i] = null;
// return stickyTranArray;
/**
* Identify if any sticky transitions in currentStickyTransArray can existing in the nextState. If so, add them to
* nextStickyTransArray.
*
* Arguments: curStickyTransArray and nextState are constant, nextStickyTransArray may be added with sticky transitions
* from curStickyTransArray.
*
* Return: sticky transitions from curStickyTransArray that are not marking disabled in nextState.
*/
public static LpnTranList[] checkStickyTrans(
LpnTranList[] curStickyTransArray, LpnTranList[] nextEnabledArray,
LpnTranList[] nextStickyTransArray, State nextState, LhpnFile LPN) {
int arraySize = curStickyTransArray.length;
LpnTranList[] stickyTransArray = new LpnTranList[arraySize];
boolean[] hasStickyTrans = new boolean[arraySize];
for (int i = 0; i < arraySize; i++) {
HashSet<Transition> tmp = new HashSet<Transition>();
if(nextStickyTransArray[i] != null)
for(Transition tran : nextStickyTransArray[i])
tmp.add(tran);
stickyTransArray[i] = new LpnTranList();
hasStickyTrans[i] = false;
for (Transition tran : curStickyTransArray[i]) {
if (tran.isPersistent() == true && tmp.contains(tran)==false) {
int[] nextMarking = nextState.getMarking();
int[] preset = LPN.getPresetIndex(tran.getLabel());//tran.getPreSet();
boolean included = false;
if (preset != null && preset.length > 0) {
for (int pp : preset) {
for (int mi = 0; i < nextMarking.length; i++) {
if (nextMarking[mi] == pp) {
included = true;
break;
}
}
if (included == false)
break;
}
}
if(preset==null || preset.length==0 || included==true) {
stickyTransArray[i].add(tran);
hasStickyTrans[i] = true;
}
}
}
if(stickyTransArray[i].size()==0)
stickyTransArray[i] = null;
}
return stickyTransArray;
}
/*
* Return an array of indices for the given stateArray.
*/
private static int[] getIdxArray(State[] stateArray) {
int[] idxArray = new int[stateArray.length];
for(int i = 0; i < stateArray.length; i++) {
idxArray[i] = stateArray[i].getIndex();
}
return idxArray;
}
private static int[] getLocalStateIdxArray(StateGraph[] sgList, State[] stateArray, boolean reverse) {
int arraySize = sgList.length;
int[] localIdxArray = new int[arraySize];
for(int i = 0; i < arraySize; i++) {
if(reverse == false)
localIdxArray[i] = sgList[i].getLocalState(stateArray[i]).getIndex();
else
localIdxArray[arraySize - i - 1] = sgList[i].getLocalState(stateArray[i]).getIndex();
//System.out.print(localIdxArray[i] + " ");
}
//System.out.println();
return localIdxArray;
}
private void printPersistentSetTbl(StateGraph[] sgList) {
for (int i=0; i<sgList.length; i++) {
System.out.println("******* Stored persistent sets for state graph " + sgList[i].getLpn().getLabel() + " *******");
for (State s : sgList[i].getEnabledSetTbl().keySet()) {
System.out.print(s.getFullLabel() + " -> ");
printTransList(sgList[i].getEnabledSetTbl().get(s), "");
}
}
}
private HashSet<Transition> computePersistentSet(State[] curStateArray,
HashSet<Transition> curEnabled, HashMap<Transition,Integer> tranFiringFreq, StateGraph[] sgList) {
if (curEnabled.size() == 1)
return curEnabled;
HashSet<Transition> ready = new HashSet<Transition>();
// for (Transition enabledTran : curEnabled) {
// if (staticMap.get(enabledTran).getOtherTransDisableCurTranSet().isEmpty()) {
// ready.add(enabledTran);
// return ready;
// if (Options.getUseDependentQueue()) {
DependentSetComparator depComp = new DependentSetComparator(tranFiringFreq);
PriorityQueue<DependentSet> dependentSetQueue = new PriorityQueue<DependentSet>(curEnabled.size(), depComp);
for (Transition enabledTran : curEnabled) {
if (Options.getDebugMode())
System.out.println("@ beginning of partialOrderReduction, consider seed transition " + enabledTran.getFullLabel());
HashSet<Transition> dependent = new HashSet<Transition>();
boolean enabledIsDummy = false;
boolean isCycleClosingPersistentComputation = false;
dependent = computeDependent(curStateArray,enabledTran,dependent,curEnabled,isCycleClosingPersistentComputation);
if (Options.getDebugMode())
printIntegerSet(dependent, "@ end of partialOrderReduction, dependent set for enabled transition "
+ enabledTran.getFullLabel());
// TODO: temporarily dealing with dummy transitions (This requires the dummy transitions to have "_dummy" in their names.)
if(isDummyTran(enabledTran.getLabel()))
enabledIsDummy = true;
DependentSet dependentSet = new DependentSet(dependent, enabledTran, enabledIsDummy);
dependentSetQueue.add(dependentSet);
}
//cachedNecessarySets.clear();
ready = dependentSetQueue.poll().getDependent();
//return ready;
// else {
// for (Transition enabledTran : curEnabled) {
// if (Options.getDebugMode())
// System.out.print("@ beginning of partialOrderReduction, consider seed transition " + getNamesOfLPNandTrans(enabledTran));
// HashSet<Transition> dependent = new HashSet<Transition>();
// boolean isCycleClosingPersistentComputation = false;
// dependent = computeDependent(curStateArray,enabledTran,dependent,curEnabled,isCycleClosingPersistentComputation);
// if (Options.getDebugMode()) {
// printIntegerSet(dependent, "@ end of partialOrderReduction, dependent set for enabled transition "
// + getNamesOfLPNandTrans(enabledTran));
// if (ready.isEmpty() || dependent.size() < ready.size())
// ready = dependent;
// if (ready.size() == 1) {
// cachedNecessarySets.clear();
// return ready;
cachedNecessarySets.clear();
return ready;
}
// private HashSet<Transition> partialOrderReduction(State[] curStateArray,
// HashSet<Transition> curEnabled, HashMap<Transition, StaticSets> staticMap,
// HashMap<Transition,Integer> tranFiringFreqMap, StateGraph[] sgList, LhpnFile[] lpnList) {
// if (curEnabled.size() == 1)
// return curEnabled;
// HashSet<Transition> ready = new HashSet<Transition>();
// for (Transition enabledTran : curEnabled) {
// if (staticMap.get(enabledTran).getOtherTransDisableCurTranSet().isEmpty()) {
// ready.add(enabledTran);
// return ready;
// if (Options.getUseDependentQueue()) {
// DependentSetComparator depComp = new DependentSetComparator(tranFiringFreqMap);
// PriorityQueue<DependentSet> dependentSetQueue = new PriorityQueue<DependentSet>(curEnabled.size(), depComp);
// for (Transition enabledTran : curEnabled) {
// if (Options.getDebugMode()){
// writeStringWithEndOfLineToPORDebugFile("@ beginning of partialOrderReduction, consider seed transition " + getNamesOfLPNandTrans(enabledTran));
// HashSet<Transition> dependent = new HashSet<Transition>();
// boolean enabledIsDummy = false;
// boolean isCycleClosingPersistentComputation = false;
// dependent = computeDependent(curStateArray,enabledTran,dependent,curEnabled,staticMap,isCycleClosingPersistentComputation);
// if (Options.getDebugMode()) {
// writeIntegerSetToPORDebugFile(dependent, "@ end of partialOrderReduction, dependent set for enabled transition "
// + getNamesOfLPNandTrans(enabledTran));
// // TODO: temporarily dealing with dummy transitions (This requires the dummy transitions to have "_dummy" in their names.)
// if(isDummyTran(enabledTran.getName()))
// enabledIsDummy = true;
// DependentSet dependentSet = new DependentSet(dependent, enabledTran, enabledIsDummy);
// dependentSetQueue.add(dependentSet);
// //cachedNecessarySets.clear();
// ready = dependentSetQueue.poll().getDependent();
// //return ready;
// else {
// for (Transition enabledTran : curEnabled) {
// if (Options.getDebugMode()){
// writeStringWithEndOfLineToPORDebugFile("@ beginning of partialOrderReduction, consider seed transition " + getNamesOfLPNandTrans(enabledTran));
// HashSet<Transition> dependent = new HashSet<Transition>();
// boolean isCycleClosingPersistentComputation = false;
// dependent = computeDependent(curStateArray,enabledTran,dependent,curEnabled,staticMap,isCycleClosingPersistentComputation);
// if (Options.getDebugMode()) {
// writeIntegerSetToPORDebugFile(dependent, "@ end of partialOrderReduction, dependent set for enabled transition "
// + getNamesOfLPNandTrans(enabledTran));
// if (ready.isEmpty() || dependent.size() < ready.size())
// ready = dependent;//(HashSet<Transition>) dependent.clone();
// if (ready.size() == 1) {
// cachedNecessarySets.clear();
// return ready;
// cachedNecessarySets.clear();
// return ready;
private boolean isDummyTran(String tranName) {
if (tranName.contains("_dummy"))
return true;
else
return false;
}
private HashSet<Transition> computeDependent(State[] curStateArray,
Transition seedTran, HashSet<Transition> dependent, HashSet<Transition> curEnabled, boolean isCycleClosingPersistentComputation) {
// disableSet is the set of transitions that can be disabled by firing enabledLpnTran, or can disable enabledLpnTran.
HashSet<Transition> disableSet = staticDependency.get(seedTran).getDisableSet();
HashSet<Transition> otherTransDisableEnabledTran = staticDependency.get(seedTran).getOtherTransDisableCurTranSet();
if (Options.getDebugMode()) {
System.out.println("@ beginning of computeDependent, consider transition " + seedTran.getFullLabel());
printIntegerSet(disableSet, "Disable set for " + seedTran.getFullLabel());
}
dependent.add(seedTran);
// for (Transition lpnTranPair : canModifyAssign) {
// if (curEnabled.contains(lpnTranPair))
// dependent.add(lpnTranPair);
if (Options.getDebugMode())
printIntegerSet(dependent, "@ computeDependent at 0, dependent set for " + seedTran.getFullLabel());
// dependent is equal to enabled. Terminate.
if (dependent.size() == curEnabled.size()) {
if (Options.getDebugMode()) {
System.out.println("Check 0: Size of dependent is equal to enabled. Return dependent.");
}
return dependent;
}
for (Transition tranInDisableSet : disableSet) {
if (Options.getDebugMode())
System.out.println("Consider transition in the disable set of "
+ seedTran.getFullLabel() + ": "
+ tranInDisableSet.getFullLabel());
if (curEnabled.contains(tranInDisableSet) && !dependent.contains(tranInDisableSet)
&& (!tranInDisableSet.isPersistent() || otherTransDisableEnabledTran.contains(tranInDisableSet))) {
dependent.addAll(computeDependent(curStateArray,tranInDisableSet,dependent,curEnabled,isCycleClosingPersistentComputation));
if (Options.getDebugMode()) {
printIntegerSet(dependent, "@ computeDependent at 1 for transition " + seedTran.getFullLabel());
}
}
else if (!curEnabled.contains(tranInDisableSet)) {
if(Options.getPOR().toLowerCase().equals("tboff") // no trace-back
|| (Options.getCycleClosingPersistentMethd().toLowerCase().equals("cctboff") && isCycleClosingPersistentComputation)) {
dependent.addAll(curEnabled);
break;
}
HashSet<Transition> necessary = null;
if (Options.getDebugMode()) {
printCachedNecessarySets();
}
if (cachedNecessarySets.containsKey(tranInDisableSet)) {
if (Options.getDebugMode()) {
printCachedNecessarySets();
System.out.println("@ computeDependent: Found transition " + tranInDisableSet.getFullLabel() + "in the cached necessary sets.");
}
necessary = cachedNecessarySets.get(tranInDisableSet);
}
else {
if (Options.getDebugMode())
System.out.println("==== Compute necessary using DFS ====");
if (visitedTrans == null)
visitedTrans = new HashSet<Transition>();
else
visitedTrans.clear();
necessary = computeNecessary(curStateArray,tranInDisableSet,dependent,curEnabled);//, tranInDisableSet.getFullLabel());
}
if (necessary != null && !necessary.isEmpty()) {
cachedNecessarySets.put(tranInDisableSet, necessary);
if (Options.getDebugMode())
printIntegerSet(necessary, "@ computeDependent, necessary set for transition " + tranInDisableSet.getFullLabel());
for (Transition tranNecessary : necessary) {
if (!dependent.contains(tranNecessary)) {
if (Options.getDebugMode()) {
printIntegerSet(dependent,"Check if the newly found necessary transition is in the dependent set of " + seedTran.getFullLabel());
System.out.println("It does not contain this transition found by computeNecessary: "
+ tranNecessary.getFullLabel() + ". Compute its dependent set.");
}
dependent.addAll(computeDependent(curStateArray,tranNecessary,dependent,curEnabled,isCycleClosingPersistentComputation));
}
else {
if (Options.getDebugMode()) {
printIntegerSet(dependent, "Check if the newly found necessary transition is in the dependent set. Dependent set for " + seedTran.getFullLabel());
System.out.println("It already contains this transition found by computeNecessary: "
+ tranNecessary.getFullLabel() + ".");
}
}
}
}
else {
if (Options.getDebugMode()) {
if (necessary == null)
System.out.println("necessary set for transition " + seedTran.getFullLabel() + " is null.");
else
System.out.println("necessary set for transition " + seedTran.getFullLabel() + " is empty.");
}
//dependent.addAll(curEnabled);
return curEnabled;
}
if (Options.getDebugMode()) {
printIntegerSet(dependent,"@ computeDependent at 2, dependent set for transition " + seedTran.getFullLabel());
}
}
else if (dependent.contains(tranInDisableSet)) {
if (Options.getDebugMode()) {
printIntegerSet(dependent,"@ computeDependent at 3 for transition " + seedTran.getFullLabel());
System.out.println("Transition " + tranInDisableSet.getFullLabel() + " is already in the dependent set of "
+ seedTran.getFullLabel() + ".");
}
}
}
return dependent;
}
// private String getNamesOfLPNandTrans(Transition tran) {
// return tran.getLpn().getLabel() + "(" + tran.getLabel() + ")";
private HashSet<Transition> computeNecessary(State[] curStateArray,
Transition tran, HashSet<Transition> dependent,
HashSet<Transition> curEnabled) {
if (Options.getDebugMode()) {
System.out.println("@ computeNecessary, consider transition: " + tran.getFullLabel());
}
if (cachedNecessarySets.containsKey(tran)) {
if (Options.getDebugMode()) {
printCachedNecessarySets();
System.out.println("@ computeNecessary: Found transition " + tran.getFullLabel()
+ "'s necessary set in the cached necessary sets. Return the cached necessary set.");
}
return cachedNecessarySets.get(tran);
}
// Search for transition(s) that can help to bring the marking(s).
HashSet<Transition> nMarking = null;
//Transition transition = lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex());
//int[] presetPlaces = lpnList[tran.getLpnIndex()].getPresetIndex(transition.getName());
for (int i=0; i < tran.getPreset().length; i++) {
int placeIndex = tran.getLpn().getPresetIndex(tran.getLabel())[i];
if (curStateArray[tran.getLpn().getLpnIndex()].getMarking()[placeIndex]==0) {
if (Options.getDebugMode()) {
System.out.println("
}
HashSet<Transition> nMarkingTemp = new HashSet<Transition>();
String placeName = tran.getLpn().getPlaceList()[placeIndex];
Transition[] presetTrans = tran.getLpn().getPlace(placeName).getPreset();
if (Options.getDebugMode()) {
System.out.println("@ nMarking: Consider preset place of " + tran.getFullLabel() + ": " + placeName);
}
for (int j=0; j < presetTrans.length; j++) {
Transition presetTran = presetTrans[j];
if (Options.getDebugMode()) {
System.out.println("@ nMarking: Preset of place " + placeName + " has transition(s): ");
for (int k=0; k<presetTrans.length; k++) {
System.out.print(presetTrans[k].getFullLabel() + ", ");
}
System.out.println("");
System.out.println("@ nMarking: Consider transition of " + presetTran.getFullLabel());
}
if (curEnabled.contains(presetTran)) {
if (Options.getDebugMode()) {
System.out.println("@ nMarking: curEnabled contains transition "
+ presetTran.getFullLabel() + "). Add to nMarkingTmp.");
}
nMarkingTemp.add(presetTran);
}
else {
if (visitedTrans.contains(presetTran)) {//seedTranInDisableSet.getVisitedTrans().contains(presetTran)) {
if (Options.getDebugMode()) {
System.out.println("@ nMarking: Transition " + presetTran.getFullLabel() + " was visted before");
}
if (cachedNecessarySets.containsKey(presetTran)) {
if (Options.getDebugMode()) {
printCachedNecessarySets();
System.out.println("@nMarking: Found transition " + presetTran.getFullLabel()
+ "'s necessary set in the cached necessary sets. Add it to nMarkingTemp.");
}
nMarkingTemp = cachedNecessarySets.get(presetTran);
}
continue;
}
else
visitedTrans.add(presetTran);
if (Options.getDebugMode()) {
System.out.println("~~~~~~~~~ transVisited ~~~~~~~~~");
for (Transition visitedTran :visitedTrans) {
System.out.println(visitedTran.getFullLabel());
}
System.out.println("@ nMarking, before call computeNecessary: consider transition: "
+ presetTran.getFullLabel());
System.out.println("@ nMarking: transition " + presetTran.getFullLabel() + " is not enabled. Compute its necessary set.");
}
HashSet<Transition> tmp = computeNecessary(curStateArray, presetTran, dependent, curEnabled);
if (tmp != null) {
nMarkingTemp.addAll(tmp);
if (Options.getDebugMode()) {
System.out.println("@ nMarking: tmp returned from computeNecessary for " + presetTran.getFullLabel() + " is not null.");
printIntegerSet(nMarkingTemp, presetTran.getFullLabel() + "'s nMarkingTemp");
}
}
else
if (Options.getDebugMode()) {
System.out.println("@ nMarking: necessary set for transition "
+ presetTran.getFullLabel() + " is null.");
}
}
}
if (!nMarkingTemp.isEmpty())
//if (nMarking == null || nMarkingTemp.size() < nMarking.size())
if (nMarking == null
|| setSubstraction(nMarkingTemp, dependent).size() < setSubstraction(nMarking, dependent).size())
nMarking = nMarkingTemp;
}
else
if (Options.getDebugMode()) {
System.out.println("@ nMarking: Place " + tran.getLpn().getLabel()
+ "(" + tran.getLpn().getPlaceList()[placeIndex] + ") is marked.");
}
}
if (nMarking != null && nMarking.size() ==1 && setSubstraction(nMarking, dependent).size() == 0) {
cachedNecessarySets.put(tran, nMarking);
if (Options.getDebugMode()) {
System.out.println("Return nMarking as necessary set.");
printCachedNecessarySets();
}
return nMarking;
}
// Search for transition(s) that can help to enable the current transition.
HashSet<Transition> nEnable = null;
int[] varValueVector = curStateArray[tran.getLpn().getLpnIndex()].getVariableVector();
//HashSet<Transition> canEnable = staticMap.get(tran).getEnableBySettingEnablingTrue();
ArrayList<HashSet<Transition>> canEnable = staticDependency.get(tran).getOtherTransSetCurTranEnablingTrue();
if (Options.getDebugMode()) {
System.out.println("
printIntegerSet(canEnable, "@ nEnable: " + tran.getFullLabel() + " can be enabled by");
}
if (tran.getEnablingTree() != null
&& tran.getEnablingTree().evaluateExpr(tran.getLpn().getAllVarsWithValuesAsString(varValueVector)) == 0.0
&& !canEnable.isEmpty()) {
for(int index=0; index < tran.getConjunctsOfEnabling().size(); index++) {
ExprTree conjunctExprTree = tran.getConjunctsOfEnabling().get(index);
HashSet<Transition> nEnableForOneConjunct = null;
if (Options.getDebugMode()) {
printIntegerSet(canEnable, "@ nEnable: " + tran.getFullLabel() + " can be enabled by");
System.out.println("@ nEnable: Consider conjunct for transition " + tran.getFullLabel() + ": "
+ conjunctExprTree.toString());
}
if (conjunctExprTree.evaluateExpr(tran.getLpn().getAllVarsWithValuesAsString(varValueVector)) == 0.0) {
HashSet<Transition> canEnableOneConjunctSet = staticDependency.get(tran).getOtherTransSetCurTranEnablingTrue().get(index);
nEnableForOneConjunct = new HashSet<Transition>();
if (Options.getDebugMode()) {
System.out.println("@ nEnable: Conjunct for transition " + tran.getFullLabel() + " "
+ conjunctExprTree.toString() + " is evaluated to FALSE.");
printIntegerSet(canEnableOneConjunctSet, "@ nEnable: Transitions that can enable this conjunct are");
}
for (Transition tranCanEnable : canEnableOneConjunctSet) {
if (curEnabled.contains(tranCanEnable)) {
nEnableForOneConjunct.add(tranCanEnable);
if (Options.getDebugMode()) {
System.out.println("@ nEnable: curEnabled contains transition " + tranCanEnable.getFullLabel() + ". Add to nEnableOfOneConjunct.");
}
}
else {
if (visitedTrans.contains(tranCanEnable)) {
if (Options.getDebugMode()) {
System.out.println("@ nEnable: Transition " + tranCanEnable.getFullLabel() + " was visted before.");
}
if (cachedNecessarySets.containsKey(tranCanEnable)) {
if (Options.getDebugMode()) {
printCachedNecessarySets();
System.out.println("@ nEnable: Found transition " + tranCanEnable.getFullLabel()
+ "'s necessary set in the cached necessary sets. Add it to nEnableOfOneConjunct.");
}
nEnableForOneConjunct.addAll(cachedNecessarySets.get(tranCanEnable));
}
continue;
}
else
visitedTrans.add(tranCanEnable);
if (Options.getDebugMode()) {
System.out.println("@ nEnable: Transition " + tranCanEnable.getFullLabel()
+ " is not enabled. Compute its necessary set.");
}
HashSet<Transition> tmp = computeNecessary(curStateArray, tranCanEnable, dependent, curEnabled);
if (tmp != null) {
nEnableForOneConjunct.addAll(tmp);
if (Options.getDebugMode()) {
System.out.println("@ nEnable: tmp returned from computeNecessary for " + tranCanEnable.getFullLabel() + ": ");
printIntegerSet(tmp, "");
printIntegerSet(nEnableForOneConjunct, tranCanEnable.getFullLabel() + "'s nEnableOfOneConjunct");
}
}
else
if (Options.getDebugMode()) {
System.out.println("@ nEnable: necessary set for transition "
+ tranCanEnable.getFullLabel() + " is null.");
}
}
}
if (!nEnableForOneConjunct.isEmpty()) {
if (nEnable == null
|| setSubstraction(nEnableForOneConjunct, dependent).size() < setSubstraction(nEnable, dependent).size()) {
//&& !nEnableForOneConjunct.isEmpty())) {
if (Options.getDebugMode()) {
System.out.println("@ nEnable: nEnable for transition " + tran.getFullLabel() +" is replaced by nEnableForOneConjunct.");
printIntegerSet(nEnable, "nEnable");
printIntegerSet(nEnableForOneConjunct, "nEnableForOneConjunct");
}
nEnable = nEnableForOneConjunct;
}
else {
if (Options.getDebugMode()) {
System.out.println("@ nEnable: nEnable for transition " + tran.getFullLabel() +" remains unchanged.");
printIntegerSet(nEnable, "nEnable");
}
}
}
}
else {
if (Options.getDebugMode()) {
System.out.println("@ nEnable: Conjunct for transition " + tran.getFullLabel() + " "
+ conjunctExprTree.toString() + " is evaluated to TRUE. No need to trace back on it.");
}
}
}
}
else {
if (Options.getDebugMode()) {
if (tran.getEnablingTree() == null) {
System.out.println("@ nEnable: transition " + tran.getFullLabel() + " has no enabling condition.");
}
else if (tran.getEnablingTree().evaluateExpr(tran.getLpn().getAllVarsWithValuesAsString(varValueVector)) !=0.0) {
System.out.println("@ nEnable: transition " + tran.getFullLabel() + "'s enabling condition is true.");
}
else if (tran.getEnablingTree() != null
&& tran.getEnablingTree().evaluateExpr(tran.getLpn().getAllVarsWithValuesAsString(varValueVector)) == 0.0
&& canEnable.isEmpty()) {
System.out.println("@ nEnable: transition " + tran.getFullLabel()
+ "'s enabling condition is false, but no other transitions that can help to enable it were found .");
}
printIntegerSet(nMarking, "=== nMarking for transition " + tran.getFullLabel());
printIntegerSet(nEnable, "=== nEnable for transition " + tran.getFullLabel());
}
}
if (nMarking != null && nEnable == null) {
if (!nMarking.isEmpty())
cachedNecessarySets.put(tran, nMarking);
if (Options.getDebugMode()) {
printCachedNecessarySets();
}
return nMarking;
}
else if (nMarking == null && nEnable != null) {
if (!nEnable.isEmpty())
cachedNecessarySets.put(tran, nEnable);
if (Options.getDebugMode()) {
printCachedNecessarySets();
}
return nEnable;
}
else if (nMarking == null && nEnable == null) {
return null;
}
else {
if (!nMarking.isEmpty() && !nEnable.isEmpty()) {
if (setSubstraction(nMarking, dependent).size() < setSubstraction(nEnable, dependent).size()) {
cachedNecessarySets.put(tran, nMarking);
if (Options.getDebugMode()) {
printCachedNecessarySets();
}
return nMarking;
}
else {
cachedNecessarySets.put(tran, nEnable);
if (Options.getDebugMode()) {
printCachedNecessarySets();
}
return nEnable;
}
}
else if (nMarking.isEmpty() && !nEnable.isEmpty()) {
cachedNecessarySets.put(tran, nEnable);
if (Options.getDebugMode()) {
printCachedNecessarySets();
}
return nEnable;
}
else if (!nMarking.isEmpty() && nEnable.isEmpty()) {
cachedNecessarySets.put(tran, nMarking);
if (Options.getDebugMode()) {
printCachedNecessarySets();
}
return nMarking;
}
else {
return null;
}
}
}
// private HashSet<Transition> computeNecessaryUsingDependencyGraphs(State[] curStateArray,
// Transition tran, HashSet<Transition> curEnabled,
// HashMap<Transition, StaticSets> staticMap,
// LhpnFile[] lpnList, Transition seedTran) {
// if (Options.getDebugMode()) {
//// System.out.println("@ computeNecessary, consider transition: " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ")");
// writeStringWithEndOfLineToPORDebugFile("@ computeNecessary, consider transition: " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ")");
// // Use breadth-first search to find the shorted path from the seed transition to an enabled transition.
// LinkedList<Transition> exploredTransQueue = new LinkedList<Transition>();
// HashSet<Transition> allExploredTrans = new HashSet<Transition>();
// exploredTransQueue.add(tran);
// //boolean foundEnabledTran = false;
// HashSet<Transition> canEnable = new HashSet<Transition>();
// while(!exploredTransQueue.isEmpty()){
// Transition curTran = exploredTransQueue.poll();
// allExploredTrans.add(curTran);
// if (cachedNecessarySets.containsKey(curTran)) {
// if (Options.getDebugMode()) {
// writeStringWithEndOfLineToPORDebugFile("Found transition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()).getName() + ")"
// + "'s necessary set in the cached necessary sets. Terminate BFS.");
// return cachedNecessarySets.get(curTran);
// canEnable = buildCanBringTokenSet(curTran,lpnList, curStateArray);
// if (Options.getDebugMode()) {
//// printIntegerSet(canEnable, lpnList, "Neighbors that can help to bring tokens to transition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + ") ");
// printIntegerSet(canEnable, lpnList, "Neighbors that can help to bring tokens to transition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + ") ");
// // Decide if canSetEnablingTrue set can help to enable curTran.
// Transition curTransition = lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex());
// int[] varValueVector = curStateArray[curTran.getLpnIndex()].getVector();
// if (curTransition.getEnablingTree() != null
// && curTransition.getEnablingTree().evaluateExpr(lpnList[curTran.getLpnIndex()].getAllVarsWithValuesAsString(varValueVector)) == 0.0) {
// canEnable.addAll(staticMap.get(curTran).getEnableBySettingEnablingTrue());
// if (Options.getDebugMode()) {
//// printIntegerSet(canEnable, lpnList, "Neighbors that can help to set the enabling of transition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + ") ");
// printIntegerSet(staticMap.get(curTran).getEnableBySettingEnablingTrue(), lpnList, "Neighbors that can help to set the enabling transition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + ") ");
// if (Options.getDebugMode()) {
//// printIntegerSet(canEnable, lpnList, "Neighbors that can help to enable transition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + ") ");
// printIntegerSet(canEnable, lpnList, "Neighbors that can help to enable transition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + ") ");
// for (Transition neighborTran : canEnable) {
// if (curEnabled.contains(neighborTran)) {
// if (!neighborTran.equals(seedTran)) {
// HashSet<Transition> necessarySet = new HashSet<Transition>();
// necessarySet.add(neighborTran);
// // TODO: Is it true that the necessary set for a disabled transition only contains a single element before the dependent set of the element is computed?
// cachedNecessarySets.put(tran, necessarySet);
// if (Options.getDebugMode()) {
//// System.out.println("Enabled neighbor that can help to enable transition " + lpnList[curTran.getLpnIndex()].getLabel()
//// + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + "): " + lpnList[neighborTran.getLpnIndex()].getLabel()
//// + "(" + lpnList[neighborTran.getLpnIndex()].getTransition(neighborTran.getTranIndex()) + ").");
// writeStringWithEndOfLineToPORDebugFile("Enabled neighbor that can help to enable transition " + lpnList[curTran.getLpnIndex()].getLabel()
// + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + "): " + lpnList[neighborTran.getLpnIndex()].getLabel()
// + "(" + lpnList[neighborTran.getLpnIndex()].getTransition(neighborTran.getTranIndex()) + ").");
// return necessarySet;
// else if (neighborTran.equals(seedTran) && canEnable.size()==1) {
// if (Options.getDebugMode()) {
//// System.out.println("Enabled neighbor that can help to enable transition " + lpnList[curTran.getLpnIndex()].getLabel()
//// + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + "): " + lpnList[neighborTran.getLpnIndex()].getLabel()
//// + "(" + lpnList[neighborTran.getLpnIndex()].getTransition(neighborTran.getTranIndex()) + "). But " + lpnList[neighborTran.getLpnIndex()].getLabel()
//// + "(" + lpnList[neighborTran.getLpnIndex()].getTransition(neighborTran.getTranIndex()) + ") is the seed transition. Return null necessary set.");
// writeStringWithEndOfLineToPORDebugFile("Enabled neighbor that can help to enable transition " + lpnList[curTran.getLpnIndex()].getLabel()
// + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + "): " + lpnList[neighborTran.getLpnIndex()].getLabel()
// + "(" + lpnList[neighborTran.getLpnIndex()].getTransition(neighborTran.getTranIndex()) + "). But " + lpnList[neighborTran.getLpnIndex()].getLabel()
// + "(" + lpnList[neighborTran.getLpnIndex()].getTransition(neighborTran.getTranIndex()) + ") is the seed transition. Return null necessary set.");
// return null;
//// if (exploredTransQueue.isEmpty()) {
//// System.out.println("exploredTransQueue is empty. Return null necessary set.");
//// writeStringWithNewLineToPORDebugFile("exploredTransQueue is empty. Return null necessary set.");
//// return null;
// if (!allExploredTrans.contains(neighborTran)) {
// allExploredTrans.add(neighborTran);
// exploredTransQueue.add(neighborTran);
// canEnable.clear();
// return null;
private void printCachedNecessarySets() {
System.out.println("================ cached necessary sets =================");
for (Transition key : cachedNecessarySets.keySet()) {
System.out.print(key.getLpn().getLabel() + "(" + key.getLabel() + ") => ");
for (Transition necessary : cachedNecessarySets.get(key)) {
System.out.print(necessary.getLpn().getLabel() + "(" + necessary.getLabel() + ") ");
}
System.out.println("");
}
}
private HashSet<Transition> setSubstraction(
HashSet<Transition> left, HashSet<Transition> right) {
HashSet<Transition> sub = new HashSet<Transition>();
for (Transition lpnTranPair : left) {
if (!right.contains(lpnTranPair))
sub.add(lpnTranPair);
}
return sub;
}
public boolean stateOnStack(int lpnIndex, State curState, HashSet<PrjState> stateStack) {
boolean isStateOnStack = false;
for (PrjState prjState : stateStack) {
State[] stateArray = prjState.toStateArray();
if(stateArray[lpnIndex].equals(curState)) {// (stateArray[lpnIndex] == curState) {
isStateOnStack = true;
break;
}
}
return isStateOnStack;
}
private void printIntegerSet(HashSet<Transition> Trans, String setName) {
if (!setName.isEmpty())
System.out.print(setName + ": ");
if (Trans == null) {
System.out.println("null");
}
else if (Trans.isEmpty()) {
System.out.println("empty");
}
else {
for (Transition lpnTranPair : Trans) {
System.out.print(lpnTranPair.getLabel() + "("
+ lpnTranPair.getLpn().getLabel() + "),");
}
System.out.println();
}
}
private void printIntegerSet(ArrayList<HashSet<Transition>> transSet, String setName) {
if (!setName.isEmpty())
System.out.print(setName + ": ");
if (transSet == null) {
System.out.println("null");
}
else if (transSet.isEmpty()) {
System.out.println("empty");
}
else {
for (HashSet<Transition> lpnTranPairSet : transSet) {
for (Transition lpnTranPair : lpnTranPairSet)
System.out.print(lpnTranPair.getLpn().getLabel() + "("
+ lpnTranPair.getLabel() + "),");
}
System.out.println();
}
}
}
|
package mho.wheels.ordering;
import mho.wheels.structures.Pair;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import static mho.wheels.iterables.IterableUtils.*;
/**
* An enumeration consisting of the elements {@code LT} (less than), {@code EQ} (equal to), and {@code GT} (greater
* than). Ordering-related utilities are also provided.
*/
public enum Ordering {
LT,
EQ,
GT;
/**
* Converts an integer to an ordering, based on comparing the integer to zero. This is useful because C-style
* ordering-related methods often use negative integers to mean "less than", zero to mean "equal to", and positive
* integers to mean "greater than".
*
* <ul>
* <li>{@code i} may be any {@code int}.</li>
* <li>The result is not null.</li>
* </ul>
*
* @param i an {@code int}
* @return whether {@code i} is greater than, less than, or equal to zero
*/
public static @NotNull Ordering fromInt(int i) {
if (i > 0) return GT;
if (i < 0) return LT;
return EQ;
}
public int toInt() {
switch (this) {
case LT: return -1;
case EQ: return 0;
case GT: return 1;
}
throw new IllegalStateException("unreachable");
}
/**
* Returns the opposite ordering: {@code EQ} stays {@code EQ}, and {@code LT} and {@code GT} switch places.
*
* <ul>
* <li>{@code this} may be any {@code Ordering}.</li>
* <li>The result is not null.</li>
* </ul>
*
* @return the opposite or inverse ordering
*/
public @NotNull Ordering invert() {
switch (this) {
case LT: return GT;
case EQ: return EQ;
case GT: return LT;
}
throw new IllegalStateException("unreachable");
}
/**
* Compares two values using their default {@code Comparator}.
*
* <ul>
* <li>{@code a} cannot be null.</li>
* <li>{@code b} cannot be null.</li>
* <li>{@code a} and {@code b} must be comparable by their default comparator.</li>
* <li>The result is not null.</li>
* </ul>
*
* @param a the first value
* @param b the second value
* @param <T> the type of {@code a} and {@code b}
* @return whether {@code a} is less than, equal to, or greater than {@code b}
*/
public static @NotNull <T extends Comparable<T>> Ordering compare(@NotNull T a, @NotNull T b) {
return fromInt(a.compareTo(b));
}
/**
* Compares two values using a provided {@code Comparator}.
*
* <ul>
* <li>{@code comparator} cannot be null.</li>
* <li>{@code a} cannot be null.</li>
* <li>{@code b} cannot be null.</li>
* <li>{@code a} and {@code b} must be comparable by {@code comparator}.</li>
* <li>The result is not null.</li>
* </ul>
*
* @param comparator the {@code Comparator} used to compare {@code a} and {@code b}
* @param a the first value
* @param b the second value
* @param <T> the type of {@code a} and {@code b}
* @return whether {@code a} is less than, equal to, or greater than {@code b}
*/
public static @NotNull <T> Ordering compare(@NotNull Comparator<T> comparator, @Nullable T a, @Nullable T b) {
return fromInt(comparator.compare(a, b));
}
/**
* Whether {@code a} and {@code b} are equal with respect to their default {@code Comparator}.
*
* <ul>
* <li>{@code a} cannot be null.</li>
* <li>{@code b} cannot be null.</li>
* <li>{@code a} and {@code b} must be comparable by their default comparator.</li>
* <li>The result may be either {@code boolean}.</li>
* </ul>
*
* @param a the first value
* @param b the second value
* @param <T> the type of {@code a} and {@code b}
* @return a=b
*/
public static <T extends Comparable<T>> boolean eq(@NotNull T a, @NotNull T b) {
return a.compareTo(b) == 0;
}
public static <T extends Comparable<T>> boolean ne(@NotNull T a, @NotNull T b) {
return a.compareTo(b) != 0;
}
/**
* Whether {@code a} is less than b {@code b} with respect to their default {@code Comparator}.
*
* <ul>
* <li>{@code a} cannot be null.</li>
* <li>{@code b} cannot be null.</li>
* <li>{@code a} and {@code b} must be comparable by their default comparator.</li>
* <li>The result may be either {@code boolean}.</li>
* </ul>
*
* @param a the first value
* @param b the second value
* @param <T> the type of {@code a} and {@code b}
* @return a{@literal <}b
*/
public static <T extends Comparable<T>> boolean lt(@NotNull T a, @NotNull T b) {
return a.compareTo(b) < 0;
}
/**
* Whether {@code a} is greater than b {@code b} with respect to their default {@code Comparator}.
*
* <ul>
* <li>{@code a} cannot be null.</li>
* <li>{@code b} cannot be null.</li>
* <li>{@code a} and {@code b} must be comparable by their default comparator.</li>
* <li>The result may be either {@code boolean}.</li>
* </ul>
*
* @param a the first value
* @param b the second value
* @param <T> the type of {@code a} and {@code b}
* @return a{@literal >}b
*/
public static <T extends Comparable<T>> boolean gt(@NotNull T a, @NotNull T b) {
return a.compareTo(b) > 0;
}
public static <T extends Comparable<T>> boolean le(@NotNull T a, @NotNull T b) {
return a.compareTo(b) <= 0;
}
public static <T extends Comparable<T>> boolean ge(@NotNull T a, @NotNull T b) {
return a.compareTo(b) >= 0;
}
/**
* Whether {@code a} and {@code b} are equal with respect to a provided {@code Comparator}.
*
* <ul>
* <li>{@code comparator} cannot be null.</li>
* <li>{@code a} cannot be null.</li>
* <li>{@code b} cannot be null.</li>
* <li>{@code a} and {@code b} must be comparable by {@code comparator}.</li>
* <li>The result may be either {@code boolean}.</li>
* </ul>
*
* @param comparator the {@code Comparator} used to compare {@code a} and {@code b}
* @param a the first value
* @param b the second value
* @param <T> the type of {@code a} and {@code b}
* @return a=<sub>{@code comparator}</sub>b
*/
public static <T> boolean eq(@NotNull Comparator<T> comparator, T a, T b) {
return comparator.compare(a, b) == 0;
}
public static <T> boolean ne(@NotNull Comparator<T> comparator, T a, T b) {
return comparator.compare(a, b) != 0;
}
/**
* Whether {@code a} is less than {@code b} with respect to a provided {@code Comparator}.
*
* <ul>
* <li>{@code comparator} cannot be null.</li>
* <li>{@code a} cannot be null.</li>
* <li>{@code b} cannot be null.</li>
* <li>{@code a} and {@code b} must be comparable by {@code comparator}.</li>
* <li>The result may be either {@code boolean}.</li>
* </ul>
*
* @param comparator the {@code Comparator} used to compare {@code a} and {@code b}
* @param a the first value
* @param b the second value
* @param <T> the type of {@code a} and {@code b}
* @return a{@literal <}<sub>{@code comparator}</sub>b
*/
public static <T> boolean lt(@NotNull Comparator<T> comparator, T a, T b) {
return comparator.compare(a, b) < 0;
}
/**
* Whether {@code a} is greater than {@code b} with respect to a provided {@code Comparator}.
*
* <ul>
* <li>{@code comparator} cannot be null.</li>
* <li>{@code a} cannot be null.</li>
* <li>{@code b} cannot be null.</li>
* <li>{@code a} and {@code b} must be comparable by {@code comparator}.</li>
* <li>The result may be either {@code boolean}.</li>
* </ul>
*
* @param comparator the {@code Comparator} used to compare {@code a} and {@code b}
* @param a the first value
* @param b the second value
* @param <T> the type of {@code a} and {@code b}
* @return a{@literal >}<sub>{@code comparator}</sub>b
*/
public static <T> boolean gt(@NotNull Comparator<T> comparator, T a, T b) {
return comparator.compare(a, b) > 0;
}
public static <T> boolean le(@NotNull Comparator<T> comparator, T a, T b) {
return comparator.compare(a, b) <= 0;
}
public static <T> boolean ge(@NotNull Comparator<T> comparator, T a, T b) {
return comparator.compare(a, b) >= 0;
}
/**
* Returns the smaller of {@code a} and {@code b} with respect to their default {@code Comparator}.
*
* <ul>
* <li>{@code a} cannot be null.</li>
* <li>{@code b} cannot be null.</li>
* <li>{@code a} and {@code b} must be comparable by their default comparator.</li>
* <li>The result is not null.</li>
* </ul>
*
* @param a the first value
* @param b the second value
* @param <T> the type of {@code a} and {@code b}
* @return min({@code a}, {@code b})
*/
@SuppressWarnings("JavaDoc")
public static @NotNull <T extends Comparable<T>> T min(@NotNull T a, @NotNull T b) {
return lt(a, b) ? a : b;
}
/**
* Returns the larger of {@code a} and {@code b} with respect to their default {@code Comparator}.
*
* <ul>
* <li>{@code a} cannot be null.</li>
* <li>{@code b} cannot be null.</li>
* <li>{@code a} and {@code b} must be comparable by their default comparator.</li>
* <li>The result is not null.</li>
* </ul>
*
* @param a the first value
* @param b the second value
* @param <T> the type of {@code a} and {@code b}
* @return max({@code a}, {@code b})
*/
@SuppressWarnings("JavaDoc")
public static @NotNull <T extends Comparable<T>> T max(@NotNull T a, @NotNull T b) {
return gt(a, b) ? a : b;
}
/**
* Returns the smaller and the larger of {@code a} and {@code b} with respect to their default {@code Comparator}.
*
* <ul>
* <li>{@code a} cannot be null.</li>
* <li>{@code b} cannot be null.</li>
* <li>{@code a} and {@code b} must be comparable by their default comparator.</li>
* <li>The result is not null, and neither of its elements is null.</li>
* </ul>
*
* @param a the first value
* @param b the second value
* @param <T> the type of {@code a} and {@code b}
* @return (min({@code a}, {@code b}), max({@code a}, {@code b}))
*/
@SuppressWarnings("JavaDoc")
public static @NotNull <T extends Comparable<T>> Pair<T, T> minMax(@NotNull T a, @NotNull T b) {
return lt(a, b) ? new Pair<>(a, b) : new Pair<>(b, a);
}
/**
* Returns the smaller of {@code a} and {@code b} with respect to {@code comparator}.
*
* <ul>
* <li>{@code comparator} cannot be null.</li>
* <li>{@code a} may be any {@code T}.</li>
* <li>{@code b} may be any {@code T}.</li>
* <li>{@code a} and {@code b} must be comparable by {@code comparator}.</li>
* <li>The result may be any {@code T}.</li>
* </ul>
*
* @param comparator the {@code Comparator} used to compare {@code a} and {@code b}
* @param a the first value
* @param b the second value
* @param <T> the type of {@code a} and {@code b}
* @return min<sub>{@code comparator}</sub>({@code a}, {@code b})
*/
@SuppressWarnings("JavaDoc")
public static <T> T min(@NotNull Comparator<T> comparator, T a, T b) {
return lt(comparator, a, b) ? a : b;
}
/**
* Returns the larger of {@code a} and {@code b} with respect to {@code comparator}.
*
* <ul>
* <li>{@code comparator} cannot be null.</li>
* <li>{@code a} may be any {@code T}.</li>
* <li>{@code b} may be any {@code T}.</li>
* <li>{@code a} and {@code b} must be comparable by {@code comparator}.</li>
* <li>The result may be any {@code T}.</li>
* </ul>
*
* @param comparator the {@code Comparator} used to compare {@code a} and {@code b}
* @param a the first value
* @param b the second value
* @param <T> the type of {@code a} and {@code b}
* @return max<sub>{@code comparator}</sub>({@code a}, {@code b})
*/
@SuppressWarnings("JavaDoc")
public static <T> T max(@NotNull Comparator<T> comparator, T a, T b) {
return gt(comparator, a, b) ? a : b;
}
/**
* Returns the smaller and the larger of {@code a} and {@code b} with respect to {@code comparator}.
*
* <ul>
* <li>{@code comparator} cannot be null.</li>
* <li>{@code a} may be any {@code T}.</li>
* <li>{@code b} may be any {@code T}.</li>
* <li>{@code a} and {@code b} must be comparable by {@code comparator}.</li>
* <li>The result may be any {@code T}.</li>
* </ul>
*
* @param comparator the {@code Comparator} used to compare {@code a} and {@code b}
* @param a the first value
* @param b the second value
* @param <T> the type of {@code a} and {@code b}
* @return (min<sub>{@code comparator}</sub>({@code a}, {@code b}),
* max<sub>{@code comparator}</sub>({@code a}, {@code b}))
*/
@SuppressWarnings("JavaDoc")
public static <T> Pair<T, T> minMax(@NotNull Comparator<T> comparator, T a, T b) {
return lt(comparator, a, b) ? new Pair<>(a, b) : new Pair<>(b, a);
}
/**
* Returns the smallest element of {@code xs} with respect to the default {@code Comparator} of type {@code T}.
*
* <ul>
* <li>{@code xs} cannot be empty or infinite and cannot contain nulls.</li>
* <li>Every pair of elements in {@code xs} must be comparable by their default comparator.</li>
* <li>The result is not null.</li>
* </ul>
*
* @param xs an {@code Iterable} of elements
* @param <T> the type of elements in {@code xs}
* @return min({@code xs})
*/
@SuppressWarnings("JavaDoc")
public static @NotNull <T extends Comparable<T>> T minimum(@NotNull Iterable<T> xs) {
T min = null;
boolean first = true;
for (T x : xs) {
if (first) {
min = x;
first = false;
} else {
if (lt(x, min)) {
min = x;
}
}
}
if (first) {
throw new IllegalArgumentException("xs cannot be empty.");
}
if (min == null) {
throw new NullPointerException();
}
return min;
}
/**
* Returns the largest element of {@code xs} with respect to the default {@code Comparator} of type {@code T}.
*
* <ul>
* <li>{@code xs} cannot be empty or infinite and cannot contain nulls.</li>
* <li>Every pair of elements in {@code xs} must be comparable by their default comparator.</li>
* <li>The result is not null.</li>
* </ul>
*
* @param xs an {@code Iterable} of elements
* @param <T> the type of elements in {@code xs}
* @return max({@code xs})
*/
@SuppressWarnings("JavaDoc")
public static @NotNull <T extends Comparable<T>> T maximum(@NotNull Iterable<T> xs) {
T max = null;
boolean first = true;
for (T x : xs) {
if (first) {
max = x;
first = false;
} else {
if (gt(x, max)) {
max = x;
}
}
}
if (first) {
throw new IllegalArgumentException("xs cannot be empty.");
}
if (max == null) {
throw new NullPointerException();
}
return max;
}
/**
* Returns the smallest and largest elements of {@code xs} with respect to the default {@code Comparator} of type
* {@code T}.
*
* <ul>
* <li>{@code xs} cannot be empty or infinite and cannot contain nulls.</li>
* <li>Every pair of elements in {@code xs} must be comparable by their default comparator.</li>
* <li>The result is not null and neither of its elements is null.</li>
* </ul>
*
* @param xs an {@code Iterable} of elements
* @param <T> the type of elements in {@code xs}
* @return (min({@code xs}), max({@code xs}))
*/
@SuppressWarnings("JavaDoc")
public static @NotNull <T extends Comparable<T>> Pair<T, T> minimumMaximum(@NotNull Iterable<T> xs) {
T min = null;
T max = null;
boolean first = true;
for (T x : xs) {
if (first) {
min = x;
max = x;
first = false;
} else {
if (lt(x, min)) {
min = x;
} else if (gt(x, max)) {
max = x;
}
}
}
if (first) {
throw new IllegalArgumentException("xs cannot be empty.");
}
if (min == null) {
throw new NullPointerException();
}
return new Pair<>(min, max);
}
/**
* Returns the smallest element of {@code xs} with respect to {@code comparator}.
*
* <ul>
* <li>{@code comparator} cannot be null.</li>
* <li>{@code xs} cannot be empty or infinite and cannot contain nulls.</li>
* <li>Every pair of elements in {@code xs} must be comparable by {@code comparator}.</li>
* <li>The result may be any {@code T}.</li>
* </ul>
*
* @param comparator the {@code Comparator} used to compare the elements of {@code xs}
* @param xs an {@code Iterable} of elements
* @param <T> the type of elements in {@code xs}
* @return min<sub>{@code comparator}</sub>({@code xs})
*/
@SuppressWarnings("JavaDoc")
public static <T> T minimum(@NotNull Comparator<T> comparator, @NotNull Iterable<T> xs) {
return foldl1((x, y) -> min(comparator, x, y), xs);
}
/**
* Returns the largest element of {@code xs} with respect to {@code comparator}.
*
* <ul>
* <li>{@code comparator} cannot be null.</li>
* <li>{@code xs} cannot be empty or infinite and cannot contain nulls.</li>
* <li>Every pair of elements in {@code xs} must be comparable by {@code comparator}.</li>
* <li>The result may be any {@code T}.</li>
* </ul>
*
* @param comparator the {@code Comparator} used to compare the elements of {@code xs}
* @param xs an {@code Iterable} of elements
* @param <T> the type of elements in {@code xs}
* @return max<sub>{@code comparator}</sub>({@code xs})
*/
@SuppressWarnings("JavaDoc")
public static <T> T maximum(@NotNull Comparator<T> comparator, @NotNull Iterable<T> xs) {
return foldl1((x, y) -> max(comparator, x, y), xs);
}
/**
* Returns the smallest and largest elements of {@code xs} with respect to {@code comparator}.
*
* <ul>
* <li>{@code comparator} cannot be null.</li>
* <li>{@code xs} cannot be empty or infinite and cannot contain nulls.</li>
* <li>Every pair of elements in {@code xs} must be comparable by {@code comparator}.</li>
* <li>The result is not null and neither of its elements is null.</li>
* </ul>
*
* @param comparator the {@code Comparator} used to compare the elements of {@code xs}
* @param xs an {@code Iterable} of elements
* @param <T> the type of elements in {@code xs}
* @return (min<sub>{@code comparator}</sub>({@code xs}), max<sub>{@code comparator}</sub>({@code xs}))
*/
@SuppressWarnings("JavaDoc")
public static <T> Pair<T, T> minimumMaximum(@NotNull Comparator<T> comparator, @NotNull Iterable<T> xs) {
T min = null;
T max = null;
boolean first = true;
for (T x : xs) {
if (first) {
min = x;
max = x;
first = false;
} else {
if (lt(comparator, x, min)) {
min = x;
} else if (gt(comparator, x, max)) {
max = x;
}
}
}
if (first) {
throw new IllegalArgumentException("xs cannot be empty.");
}
return new Pair<>(min, max);
}
/**
* Returns the smallest {@code char} of {@code s} with respect to the default {@code char} ordering.
*
* <ul>
* <li>{@code s} cannot be empty.</li>
* <li>The result may be any {@code char}.</li>
* </ul>
*
* @param s a {@code String}
* @return min({@code s})
*/
@SuppressWarnings("JavaDoc")
public static char minimum(@NotNull String s) {
return foldl1(Ordering::min, fromString(s));
}
/**
* Returns the largest {@code char} of {@code s} with respect to the default {@code char} ordering.
*
* <ul>
* <li>{@code s} cannot be empty.</li>
* <li>The result may be any {@code char}.</li>
* </ul>
*
* @param s a {@code String}
* @return max({@code s})
*/
@SuppressWarnings("JavaDoc")
public static char maximum(@NotNull String s) {
return foldl1(Ordering::max, fromString(s));
}
/**
* Returns the smallest and largest {@code char}s of {@code s} with respect to the default {@code char} ordering.
*
* <ul>
* <li>{@code s} cannot be empty.</li>
* <li>The result is not null and neither of its elements is null.</li>
* </ul>
*
* @param s a {@code String}
* @return (min({@code xs}), max({@code xs}))
*/
@SuppressWarnings("JavaDoc")
public static @NotNull Pair<Character, Character> minimumMaximum(@NotNull String s) {
char min = '\0';
char max = '\0';
boolean first = true;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (first) {
min = c;
max = c;
first = false;
} else {
if (lt(c, min)) {
min = c;
} else if (gt(c, max)) {
max = c;
}
}
}
if (first) {
throw new IllegalArgumentException("s cannot be empty.");
}
return new Pair<>(min, max);
}
/**
* Returns the smallest {@code char} of {@code s} with respect to {@code comparator}.
*
* <ul>
* <li>{@code comparator} cannot be null.</li>
* <li>{@code s} cannot be empty.</li>
* <li>Every pair of {@code char}s in {@code s} must be comparable by {@code comparator}.</li>
* <li>The result may be any {@code char}.</li>
* </ul>
*
* @param comparator the {@code Comparator} used to compare the {@code char}s of {@code s}
* @param s a {@code String}
* @return min<sub>{@code comparator}</sub>({@code s})
*/
@SuppressWarnings("JavaDoc")
public static char minimum(@NotNull Comparator<Character> comparator, @NotNull String s) {
return foldl1((x, y) -> min(comparator, x, y), fromString(s));
}
/**
* Returns the largest {@code char} of {@code s} with respect to {@code comparator}.
*
* <ul>
* <li>{@code comparator} cannot be null.</li>
* <li>{@code s} cannot be empty.</li>
* <li>Every pair of {@code char}s in {@code s} must be comparable by {@code comparator}.</li>
* <li>The result may be any {@code char}.</li>
* </ul>
*
* @param comparator the {@code Comparator} used to compare the {@code char}s of {@code s}
* @param s a {@code String}
* @return max<sub>{@code comparator}</sub>({@code s})
*/
public static char maximum(@NotNull Comparator<Character> comparator, @NotNull String s) {
return foldl1((x, y) -> max(comparator, x, y), fromString(s));
}
/**
* Returns the smallest and largest {@code char}s of {@code s} with respect to {@code comparator}.
*
* <ul>
* <li>{@code comparator} cannot be null.</li>
* <li>{@code s} cannot be empty.</li>
* <li>Every pair of {@code char}s in {@code s} must be comparable by {@code comparator}.</li>
* <li>The result is not null and neither of its elements is null.</li>
* </ul>
*
* @param comparator the {@code Comparator} used to compare the {@code char}s of {@code s}
* @param s a {@code String}
* @return (min<sub>{@code comparator}</sub>({@code xs}), max<sub>{@code comparator}</sub>({@code xs}))
*/
@SuppressWarnings("JavaDoc")
public static @NotNull Pair<Character, Character> minimumMaximum(
@NotNull Comparator<Character> comparator,
@NotNull String s
) {
char min = '\0';
char max = '\0';
boolean first = true;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (first) {
min = c;
max = c;
first = false;
} else {
if (lt(comparator, c, min)) {
min = c;
} else if (gt(comparator, c, max)) {
max = c;
}
}
}
if (first) {
throw new IllegalArgumentException("s cannot be empty.");
}
return new Pair<>(min, max);
}
public static <T extends Comparable<T>> boolean increasing(@NotNull Iterable<T> xs) {
//noinspection Convert2MethodRef
return and(adjacentPairsWith((x, y) -> lt(x, y), xs));
}
public static <T extends Comparable<T>> boolean decreasing(@NotNull Iterable<T> xs) {
//noinspection Convert2MethodRef
return and(adjacentPairsWith((x, y) -> gt(x, y), xs));
}
public static <T extends Comparable<T>> boolean weaklyIncreasing(@NotNull Iterable<T> xs) {
//noinspection Convert2MethodRef
return and(adjacentPairsWith((x, y) -> le(x, y), xs));
}
public static <T extends Comparable<T>> boolean weaklyDecreasing(@NotNull Iterable<T> xs) {
//noinspection Convert2MethodRef
return and(adjacentPairsWith((x, y) -> ge(x, y), xs));
}
public static <T extends Comparable<T>> boolean zigzagging(@NotNull Iterable<T> xs) {
if (!lengthAtLeast(3, xs)) {
List<T> xsList = toList(xs);
switch (xsList.size()) {
case 0:
case 1: return true;
case 2: return xsList.get(0).equals(xsList.get(1));
default:
throw new IllegalStateException("unreachable");
}
}
Iterable<Pair<Ordering, Ordering>> compares = adjacentPairsWith(
Pair::new,
adjacentPairsWith(Ordering::compare, xs)
);
return all(p -> p.a != EQ && p.a == p.b.invert(), compares);
}
public static <T> boolean increasing(@NotNull Comparator<T> comparator, @NotNull Iterable<T> xs) {
return and(adjacentPairsWith((x, y) -> lt(comparator, x, y), xs));
}
public static <T> boolean decreasing(@NotNull Comparator<T> comparator, @NotNull Iterable<T> xs) {
return and(adjacentPairsWith((x, y) -> gt(comparator, x, y), xs));
}
public static <T> boolean weaklyIncreasing(@NotNull Comparator<T> comparator, @NotNull Iterable<T> xs) {
return and(adjacentPairsWith((x, y) -> le(comparator, x, y), xs));
}
public static <T> boolean weaklyDecreasing(@NotNull Comparator<T> comparator, @NotNull Iterable<T> xs) {
return and(adjacentPairsWith((x, y) -> ge(comparator, x, y), xs));
}
public static <T> boolean zigzagging(@NotNull Comparator<T> comparator, @NotNull Iterable<T> xs) {
if (!lengthAtLeast(3, xs)) {
List<T> xsList = toList(xs);
switch (xsList.size()) {
case 0:
case 1: return true;
case 2: return comparator.compare(xsList.get(0), xsList.get(1)) != 0;
default:
throw new IllegalStateException("unreachable");
}
}
Iterable<Pair<Ordering, Ordering>> compares = adjacentPairsWith(
Pair::new,
adjacentPairsWith((x, y) -> compare(comparator, x, y), xs)
);
return all(p -> p.a != EQ && p.a == p.b.invert(), compares);
}
public static boolean increasing(@NotNull String s) {
//noinspection Convert2MethodRef
return and(adjacentPairsWith((a, b) -> lt(a, b), fromString(s)));
}
public static boolean decreasing(@NotNull String s) {
//noinspection Convert2MethodRef
return and(adjacentPairsWith((a, b) -> gt(a, b), fromString(s)));
}
public static boolean weaklyIncreasing(@NotNull String s) {
//noinspection Convert2MethodRef
return and(adjacentPairsWith((a, b) -> le(a, b), fromString(s)));
}
public static boolean weaklyDecreasing(@NotNull String s) {
//noinspection Convert2MethodRef
return and(adjacentPairsWith((a, b) -> ge(a, b), fromString(s)));
}
public static boolean zigzagging(@NotNull String s) {
int length = s.length();
if (length < 3) {
switch (length) {
case 0:
case 1: return true;
case 2: return s.charAt(0) != s.charAt(1);
default:
throw new IllegalStateException("unreachable");
}
}
Iterable<Pair<Ordering, Ordering>> compares = adjacentPairsWith(
Pair::new,
adjacentPairsWith(Ordering::compare, fromString(s))
);
return all(p -> p.a != EQ && p.a == p.b.invert(), compares);
}
public static boolean increasing(@NotNull Comparator<Character> comparator, @NotNull String s) {
return and(adjacentPairsWith((x, y) -> lt(comparator, x, y), fromString(s)));
}
public static boolean decreasing(@NotNull Comparator<Character> comparator, @NotNull String s) {
return and(adjacentPairsWith((x, y) -> gt(comparator, x, y), fromString(s)));
}
public static boolean weaklyIncreasing(@NotNull Comparator<Character> comparator, @NotNull String s) {
return and(adjacentPairsWith((x, y) -> le(comparator, x, y), fromString(s)));
}
public static boolean weaklyDecreasing(@NotNull Comparator<Character> comparator, @NotNull String s) {
return and(adjacentPairsWith((x, y) -> ge(comparator, x, y), fromString(s)));
}
public static boolean zigzagging(@NotNull Comparator<Character> comparator, @NotNull String s) {
int length = s.length();
if (length < 3) {
switch (length) {
case 0:
case 1: return true;
case 2: return comparator.compare(s.charAt(0), s.charAt(1)) != 0;
default:
throw new IllegalStateException("unreachable");
}
}
Iterable<Pair<Ordering, Ordering>> compares = adjacentPairsWith(
Pair::new,
adjacentPairsWith((x, y) -> compare(comparator, x, y), fromString(s))
);
return all(p -> p.a != EQ && p.a == p.b.invert(), compares);
}
/**
* Reads an {@link Ordering} from a {@code String}.
*
* <ul>
* <li>{@code s} must be non-null.</li>
* <li>The result is non-null.</li>
* </ul>
*
* @param s the input {@code String}
* @return the {@code Ordering} represented by {@code s}, or {@code Optional.empty} if {@code s} does not represent
* an {@code Ordering}
*/
public static @NotNull Optional<Ordering> readStrict(@NotNull String s) {
switch (s) {
case "<":
return Optional.of(Ordering.LT);
case "=":
return Optional.of(Ordering.EQ);
case ">":
return Optional.of(Ordering.GT);
default:
return Optional.empty();
}
}
/**
* Converts {@code this} to a single-character {@code String}.
*
* <ul>
* <li>{@code this} may be any {@code Ordering}.</li>
* <li>The result may be "<", "=", or ">".</li>
* </ul>
*
* @return the {@code String} representing {@code this}
*/
public @NotNull String toString() {
switch (this) {
case LT: return "<";
case EQ: return "=";
case GT: return ">";
}
throw new IllegalStateException("unreachable");
}
}
|
package com.spotify.annoy;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteOrder;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.*;
public class ANNIndex implements AnnoyIndex {
private final ArrayList<Long> roots;
private MappedByteBuffer[] buffers;
private final int DIMENSION, MIN_LEAF_SIZE;
private final IndexType INDEX_TYPE;
private final int INDEX_TYPE_OFFSET;
// size of C structs in bytes (initialized in init)
private final int K_NODE_HEADER_STYLE;
private final int NODE_SIZE;
private final int INT_SIZE = 4;
private final int FLOAT_SIZE = 4;
private final int BLOCK_SIZE;
private RandomAccessFile memoryMappedFile;
/**
* Construct and load an Annoy index of a specific type (euclidean / angular).
*
* @param dimension dimensionality of tree, e.g. 40
* @param filename filename of tree
* @param indexType type of index
* @throws IOException if file can't be loaded
*/
public ANNIndex(final int dimension,
final String filename,
IndexType indexType) throws IOException {
this(dimension, filename, indexType, 0);
}
/**
* Construct and load an (Angular) Annoy index.
*
* @param dimension dimensionality of tree, e.g. 40
* @param filename filename of tree
* @throws IOException if file can't be loaded
*/
public ANNIndex(final int dimension,
final String filename) throws IOException {
this(dimension, filename, IndexType.ANGULAR);
}
ANNIndex(final int dimension,
final String filename,
IndexType indexType,
final int blockSize) throws IOException {
DIMENSION = dimension;
INDEX_TYPE = indexType;
INDEX_TYPE_OFFSET = (INDEX_TYPE == IndexType.ANGULAR) ? 4 : 8;
K_NODE_HEADER_STYLE = (INDEX_TYPE == IndexType.ANGULAR) ? 12 : 16;
// we can store up to MIN_LEAF_SIZE children in leaf nodes (we put
// them where the separating plane normally goes)
this.MIN_LEAF_SIZE = DIMENSION + 2;
this.NODE_SIZE = K_NODE_HEADER_STYLE + FLOAT_SIZE * DIMENSION;
this.BLOCK_SIZE = blockSize == 0 ?
Integer.MAX_VALUE / NODE_SIZE : blockSize * NODE_SIZE;
roots = new ArrayList<>();
load(filename);
}
private void load(final String filename) throws IOException {
memoryMappedFile = new RandomAccessFile(filename, "r");
long fileSize = memoryMappedFile.length();
if (fileSize == 0L) {
throw new IOException("Index is a 0-byte file?");
}
int buffIndex = (int) ((fileSize - 1) / BLOCK_SIZE);
int rest = (int) (fileSize % BLOCK_SIZE);
int blockSize = (rest > 0 ? rest : BLOCK_SIZE);
long position = fileSize - blockSize;
buffers = new MappedByteBuffer[buffIndex + 1];
boolean process = true;
int m = -1;
long index = fileSize;
while(position >= 0) {
MappedByteBuffer annBuf = memoryMappedFile.getChannel().map(
FileChannel.MapMode.READ_ONLY, position, blockSize);
annBuf.order(ByteOrder.LITTLE_ENDIAN);
buffers[buffIndex--] = annBuf;
for (int i = blockSize - NODE_SIZE; process && i >= 0; i -= NODE_SIZE) {
index -= NODE_SIZE;
int k = annBuf.getInt(i); // node[i].n_descendants
if (m == -1 || k == m) {
roots.add(index);
m = k;
} else {
process = false;
}
}
blockSize = BLOCK_SIZE;
position -= blockSize;
}
}
private float getFloatInAnnBuf(long pos) {
int b = (int) pos / BLOCK_SIZE;
int f = (int) pos % BLOCK_SIZE;
return buffers[b].getFloat(f);
}
private int getIntInAnnBuf(long pos) {
int b = (int) pos / BLOCK_SIZE;
int i = (int) pos % BLOCK_SIZE;
return buffers[b].getInt(i);
}
@Override
public void getNodeVector(final long nodeOffset, float[] v) {
MappedByteBuffer nodeBuf = buffers[(int) nodeOffset / BLOCK_SIZE];
int offset = (int) (nodeOffset % BLOCK_SIZE) + K_NODE_HEADER_STYLE;
for (int i = 0; i < DIMENSION; i++) {
v[i] = nodeBuf.getFloat(offset + i * FLOAT_SIZE);
}
}
@Override
public void getItemVector(int itemIndex, float[] v) {
getNodeVector(itemIndex * NODE_SIZE, v);
}
private float getNodeBias(final long nodeOffset) { // euclidean-only
return getFloatInAnnBuf(nodeOffset + 4);
}
public final float[] getItemVector(final int itemIndex) {
return getNodeVector(itemIndex * NODE_SIZE);
}
public float[] getNodeVector(final long nodeOffset) {
float[] v = new float[DIMENSION];
getNodeVector(nodeOffset, v);
return v;
}
private static float norm(final float[] u) {
float n = 0;
for (float x : u)
n += x * x;
return (float) Math.sqrt(n);
}
private static float euclideanDistance(final float[] u, final float[] v) {
float[] diff = new float[u.length];
for (int i = 0; i < u.length; i++)
diff[i] = u[i] - v[i];
return norm(diff);
}
public static float cosineMargin(final float[] u, final float[] v) {
double d = 0;
for (int i = 0; i < u.length; i++)
d += u[i] * v[i];
return (float) (d / (norm(u) * norm(v)));
}
public static float euclideanMargin(final float[] u,
final float[] v,
final float bias) {
float d = bias;
for (int i = 0; i < u.length; i++)
d += u[i] * v[i];
return d;
}
/**
* Closes this stream and releases any system resources associated
* with it. If the stream is already closed then invoking this
* method has no effect.
* <p/>
* <p> As noted in {@link AutoCloseable#close()}, cases where the
* close may fail require careful attention. It is strongly advised
* to relinquish the underlying resources and to internally
* <em>mark</em> the {@code Closeable} as closed, prior to throwing
* the {@code IOException}.
*
* @throws IOException if an I/O error occurs
*/
@Override
public void close() throws IOException {
memoryMappedFile.close();
}
private class PQEntry implements Comparable<PQEntry> {
PQEntry(final float margin, final long nodeOffset) {
this.margin = margin;
this.nodeOffset = nodeOffset;
}
private float margin;
private long nodeOffset;
@Override
public int compareTo(final PQEntry o) {
return Float.compare(o.margin, margin);
}
}
private static boolean isZeroVec(float[] v) {
for (int i = 0; i < v.length; i++)
if (v[i] != 0)
return false;
return true;
}
@Override
public final List<Integer> getNearest(final float[] queryVector,
final int nResults) {
PriorityQueue<PQEntry> pq = new PriorityQueue<>(
roots.size() * FLOAT_SIZE);
final float kMaxPriority = 1e30f;
for (long r : roots) {
pq.add(new PQEntry(kMaxPriority, r));
}
Set<Integer> nearestNeighbors = new HashSet<Integer>();
while (nearestNeighbors.size() < roots.size() * nResults && !pq.isEmpty()) {
PQEntry top = pq.poll();
long topNodeOffset = top.nodeOffset;
int nDescendants = getIntInAnnBuf(topNodeOffset);
float[] v = getNodeVector(topNodeOffset);
if (nDescendants == 1) { // n_descendants
// FIXME: does this ever happen?
if (isZeroVec(v))
continue;
nearestNeighbors.add((int) (topNodeOffset / NODE_SIZE));
} else if (nDescendants <= MIN_LEAF_SIZE) {
for (int i = 0; i < nDescendants; i++) {
int j = getIntInAnnBuf(topNodeOffset +
INDEX_TYPE_OFFSET +
i * INT_SIZE);
if (isZeroVec(getNodeVector(j * NODE_SIZE)))
continue;
nearestNeighbors.add(j);
}
} else {
float margin = (INDEX_TYPE == IndexType.ANGULAR) ?
cosineMargin(v, queryVector) :
euclideanMargin(v, queryVector, getNodeBias(topNodeOffset));
long childrenMemOffset = topNodeOffset + INDEX_TYPE_OFFSET;
long lChild = NODE_SIZE * getIntInAnnBuf(childrenMemOffset);
long rChild = NODE_SIZE * getIntInAnnBuf(childrenMemOffset + 4);
pq.add(new PQEntry(-margin, lChild));
pq.add(new PQEntry(margin, rChild));
}
}
ArrayList<PQEntry> sortedNNs = new ArrayList<PQEntry>();
int i = 0;
for (int nn : nearestNeighbors) {
float[] v = getItemVector(nn);
if (!isZeroVec(v)) {
sortedNNs.add(
new PQEntry((INDEX_TYPE == IndexType.ANGULAR) ?
cosineMargin(v, queryVector) :
-euclideanDistance(v, queryVector),
nn));
}
}
Collections.sort(sortedNNs);
ArrayList<Integer> result = new ArrayList<>(nResults);
for (i = 0; i < nResults && i < sortedNNs.size(); i++) {
result.add((int) sortedNNs.get(i).nodeOffset);
}
return result;
}
/**
* a test query program.
*
* @param args tree filename, dimension, indextype ("angular" or
* "euclidean" and query item id.
* @throws IOException if unable to load index
*/
public static void main(final String[] args) throws IOException {
String indexPath = args[0];
int dimension = Integer.parseInt(args[1]);
IndexType indexType = null;
if (args[2].toLowerCase().equals("angular"))
indexType = IndexType.ANGULAR;
else if (args[2].toLowerCase().equals("euclidean"))
indexType = IndexType.EUCLIDEAN;
else throw new RuntimeException("wrong index type specified");
int queryItem = Integer.parseInt(args[3]);
ANNIndex annIndex = new ANNIndex(dimension, indexPath, indexType);
float[] u = annIndex.getItemVector(queryItem);
System.out.printf("vector[%d]: ", queryItem);
for (float x : u) {
System.out.printf("%2.2f ", x);
}
System.out.printf("\n");
List<Integer> nearestNeighbors = annIndex.getNearest(u, 10);
for (int nn : nearestNeighbors) {
float[] v = annIndex.getItemVector(nn);
System.out.printf("%d %d %f\n",
queryItem, nn,
(indexType == IndexType.ANGULAR) ?
cosineMargin(u, v) : euclideanDistance(u, v));
}
}
}
|
package myessentials.entities;
import net.minecraftforge.common.util.ForgeDirection;
/**
* A rectangular shaped volume.
*/
public class Volume {
private final int minX, minY, minZ;
private final int maxX, maxY, maxZ;
public Volume(int minX, int minY, int minZ, int maxX, int maxY, int maxZ) {
this.minX = minX;
this.minY = minY;
this.minZ = minZ;
this.maxX = maxX;
this.maxY = maxY;
this.maxZ = maxZ;
}
public int getMinX() {
return minX;
}
public int getMinY() {
return minY;
}
public int getMinZ() {
return minZ;
}
public int getMaxX() {
return maxX;
}
public int getMaxY() {
return maxY;
}
public int getMaxZ() {
return maxZ;
}
public Volume translate(ForgeDirection direction) {
Volume volume = this;
switch (direction) {
case DOWN:
volume = new Volume(volume.getMinX(), -volume.getMaxZ(), volume.getMinY(), volume.getMaxX(), volume.getMinZ(), volume.getMaxY());
break;
case UP:
volume = new Volume(volume.getMinX(), volume.getMinZ(), volume.getMinY(), volume.getMaxX(), volume.getMaxZ(), volume.getMaxY());
break;
case NORTH:
volume = new Volume(volume.getMinX(), volume.getMinY(), - volume.getMaxZ(), volume.getMaxX(), volume.getMaxY(), volume.getMinZ());
break;
case WEST:
volume = new Volume(- volume.getMaxZ(), volume.getMinY(), volume.getMinX(), volume.getMinZ(), volume.getMaxY(), volume.getMaxX());
break;
case EAST:
volume = new Volume(volume.getMinZ(), volume.getMinY(), volume.getMinX(), volume.getMaxZ(), volume.getMaxY(), volume.getMaxX());
break;
case SOUTH:
// The translation on South is already the correct one.
break;
case UNKNOWN:
break;
}
return volume;
}
public Volume intersect(Volume other) {
if (other.getMaxX() >= minX && other.getMinX() <= maxX &&
other.getMaxY() >= minY && other.getMinY() <= maxY &&
other.getMaxZ() >= minZ && other.getMinZ() <= maxZ) {
int x1, y1, z1, x2, y2, z2;
x1 = (minX < other.getMinX()) ? other.getMinX() : minX;
y1 = (minY < other.getMinY()) ? other.getMinY() : minY;
z1 = (minZ < other.getMinZ()) ? other.getMinZ() : minZ;
x2 = (maxX > other.getMaxX()) ? other.getMaxX() : maxX;
y2 = (maxY > other.getMaxY()) ? other.getMaxY() : maxY;
z2= (maxZ > other.getMaxZ()) ? other.getMaxZ() : maxZ;
return new Volume(x1, y1, z1, x2, y2, z2);
}
return null;
}
public int getVolumeAmount() {
return (maxX - minX + 1) * (maxY - minY + 1) * (maxZ - minZ + 1);
}
@Override
public String toString() {
return "Volume(minX: " + minX + ", minY: " + minY + ", minZ: " + minZ + " | maxX: " + maxX + ", maxY: " + maxY + ", maxZ: " + maxZ + ")";
}
}
|
package ai.h2o.automl;
import ai.h2o.automl.StepDefinition.Step;
import hex.Model;
import hex.SplitFrame;
import hex.deeplearning.DeepLearningModel;
import hex.ensemble.StackedEnsembleModel;
import hex.glm.GLMModel;
import hex.tree.SharedTreeModel.SharedTreeParameters;
import hex.tree.drf.DRFModel;
import hex.tree.gbm.GBMModel;
import hex.tree.xgboost.XGBoostModel;
import hex.tree.xgboost.XGBoostModel.XGBoostParameters;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import water.DKV;
import water.Key;
import water.Lockable;
import water.exceptions.H2OIllegalArgumentException;
import water.fvec.Frame;
import water.runner.CloudSize;
import water.runner.H2ORunner;
import water.util.ArrayUtils;
import water.util.Log;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Stream;
import static junit.framework.TestCase.assertNotNull;
import static junit.framework.TestCase.assertNull;
import static junit.framework.TestCase.assertTrue;
import static org.junit.Assert.*;
@RunWith(H2ORunner.class)
@CloudSize(1)
public class AutoMLTest extends water.TestUtil {
@Test public void test_basic_automl_behaviour_using_cv() {
AutoML aml=null;
Frame fr=null;
try {
AutoMLBuildSpec autoMLBuildSpec = new AutoMLBuildSpec();
fr = parse_test_file("./smalldata/logreg/prostate_train.csv");
String target = "CAPSULE";
int tidx = fr.find(target);
fr.replace(tidx, fr.vec(tidx).toCategoricalVec()).remove(); DKV.put(fr);
autoMLBuildSpec.input_spec.training_frame = fr._key;
autoMLBuildSpec.input_spec.response_column = target;
autoMLBuildSpec.input_spec.sort_metric = "AUCPR";
// autoMLBuildSpec.build_models.exclude_algos = new Algo[] {Algo.XGBoost};
int maxModels = 10;
// autoMLBuildSpec.build_models.exploitation_ratio = 1;
autoMLBuildSpec.build_control.stopping_criteria.set_seed(1);
autoMLBuildSpec.build_control.stopping_criteria.set_max_models(maxModels);
autoMLBuildSpec.build_control.keep_cross_validation_models = false; //Prevent leaked keys from CV models
autoMLBuildSpec.build_control.keep_cross_validation_predictions = false; //Prevent leaked keys from CV predictions
aml = AutoML.startAutoML(autoMLBuildSpec);
aml.get();
Key[] modelKeys = aml.leaderboard().getModelKeys();
int count_se = 0, count_non_se = 0;
for (Key k : modelKeys) if (k.toString().startsWith("StackedEnsemble")) count_se++; else count_non_se++;
assertEquals("wrong amount of standard models", maxModels, count_non_se);
assertEquals("wrong amount of SE models", 2, count_se);
assertEquals(maxModels+2, aml.leaderboard().getModelCount());
} finally {
// Cleanup
if(aml!=null) aml.delete();
if(fr != null) fr.delete();
}
}
//important test: the basic execution path is very different when CV is disabled
// being for model training but also default leaderboard scoring
// also allows us to keep an eye on memory leaks.
@Test public void test_automl_with_cv_disabled() {
AutoML aml=null;
Frame fr=null;
try {
AutoMLBuildSpec autoMLBuildSpec = new AutoMLBuildSpec();
fr = parse_test_file("./smalldata/logreg/prostate_train.csv");
autoMLBuildSpec.input_spec.training_frame = fr._key;
autoMLBuildSpec.input_spec.response_column = "CAPSULE";
autoMLBuildSpec.build_control.stopping_criteria.set_max_models(3);
autoMLBuildSpec.build_control.nfolds = 0;
aml = AutoML.startAutoML(autoMLBuildSpec);
aml.get();
Key[] modelKeys = aml.leaderboard().getModelKeys();
int count_se = 0, count_non_se = 0;
for (Key k : modelKeys) if (k.toString().startsWith("StackedEnsemble")) count_se++; else count_non_se++;
assertEquals("wrong amount of standard models", 3, count_non_se);
assertEquals("no Stacked Ensemble expected if cross-validation is disabled", 0, count_se);
assertEquals(3, aml.leaderboard().getModelCount());
} finally {
// Cleanup
if(aml!=null) aml.delete();
if(fr != null) fr.delete();
}
}
@Test public void test_stacked_ensembles_trained_with_blending_frame_if_provided() {
List<Lockable> deletables = new ArrayList<>();
try {
final int seed = 62832;
final Frame fr = parse_test_file("./smalldata/logreg/prostate_train.csv"); deletables.add(fr);
final Frame test = parse_test_file("./smalldata/logreg/prostate_test.csv"); deletables.add(test);
String target = "CAPSULE";
int tidx = fr.find(target);
fr.replace(tidx, fr.vec(tidx).toCategoricalVec()).remove(); DKV.put(fr); deletables.add(fr);
test.replace(tidx, test.vec(tidx).toCategoricalVec()).remove(); DKV.put(test); deletables.add(test);
SplitFrame sf = new SplitFrame(fr, new double[] { 0.7, 0.3 }, null);
sf.exec().get();
Key<Frame>[] ksplits = sf._destination_frames;
final Frame train = ksplits[0].get(); deletables.add(train);
final Frame blending = ksplits[1].get(); deletables.add(blending);
AutoMLBuildSpec autoMLBuildSpec = new AutoMLBuildSpec();
autoMLBuildSpec.input_spec.training_frame = train._key;
autoMLBuildSpec.input_spec.blending_frame = blending._key;
autoMLBuildSpec.input_spec.leaderboard_frame = test._key;
autoMLBuildSpec.input_spec.response_column = target;
autoMLBuildSpec.build_control.stopping_criteria.set_max_models(5);
autoMLBuildSpec.build_control.nfolds = 0;
autoMLBuildSpec.build_control.stopping_criteria.set_seed(seed);
AutoML aml = AutoML.startAutoML(autoMLBuildSpec); deletables.add(aml);
aml.get();
Key[] modelKeys = aml.leaderboard().getModelKeys();
int count_se = 0, count_non_se = 0;
for (Key k : modelKeys) if (k.toString().startsWith("StackedEnsemble")) count_se++; else count_non_se++;
assertEquals("wrong amount of standard models", 5, count_non_se);
assertEquals("wrong amount of SE models", 2, count_se);
assertEquals(7, aml.leaderboard().getModelCount());
} finally {
// Cleanup
for (Lockable l: deletables) {
l.delete();
}
}
}
@Test public void test_no_stacked_ensemble_trained_if_only_one_algo() {
List<Lockable> deletables = new ArrayList<>();
try {
final int seed = 62832;
final Frame train = parse_test_file("./smalldata/logreg/prostate_train.csv"); deletables.add(train);
String target = "CAPSULE";
int tidx = train.find(target);
train.replace(tidx, train.vec(tidx).toCategoricalVec()).remove(); DKV.put(train); deletables.add(train);
AutoMLBuildSpec autoMLBuildSpec = new AutoMLBuildSpec();
autoMLBuildSpec.input_spec.training_frame = train._key;
autoMLBuildSpec.input_spec.response_column = target;
autoMLBuildSpec.build_control.stopping_criteria.set_max_models(3);
autoMLBuildSpec.build_control.stopping_criteria.set_seed(seed);
autoMLBuildSpec.build_models.include_algos = aro(Algo.GBM);
AutoML aml = AutoML.startAutoML(autoMLBuildSpec); deletables.add(aml);
aml.get();
Key[] modelKeys = aml.leaderboard().getModelKeys();
int count_se = 0, count_non_se = 0;
for (Key k : modelKeys) if (k.toString().startsWith("StackedEnsemble")) count_se++; else count_non_se++;
assertEquals("wrong amount of standard models", 3, count_non_se);
assertEquals("wrong amount of SE models", 0, count_se);
assertEquals(3, aml.leaderboard().getModelCount());
} finally {
// Cleanup
for (Lockable l: deletables) {
l.delete();
}
}
}
// timeout can cause interruption of steps at various levels, for example from top to bottom:
// - interruption after an AutoML model has been trained, preventing addition of more models
// - interruption when building the main model (if CV enabled)
// - interruption when building a CV model (for example right after building a tree)
// we want to leave the memory in a clean state after any of those interruptions.
// this test uses a slightly random timeout to ensure it will interrupt the training at various steps
@Test public void test_automl_basic_behaviour_on_timeout() {
AutoML aml=null;
Frame fr=null;
try {
AutoMLBuildSpec autoMLBuildSpec = new AutoMLBuildSpec();
fr = parse_test_file("./smalldata/logreg/prostate_train.csv");
autoMLBuildSpec.input_spec.training_frame = fr._key;
autoMLBuildSpec.input_spec.response_column = "CAPSULE";
autoMLBuildSpec.build_control.stopping_criteria.set_max_runtime_secs(1+new Random().nextInt(30));
autoMLBuildSpec.build_control.keep_cross_validation_models = false; //Prevent leaked keys from CV models
autoMLBuildSpec.build_control.keep_cross_validation_predictions = false; //Prevent leaked keys from CV predictions
aml = AutoML.startAutoML(autoMLBuildSpec);
aml.get();
// no assertion, we just want to check leaked keys
} finally {
// Cleanup
if(aml!=null) aml.delete();
if(fr != null) fr.delete();
}
}
@Test public void test_automl_basic_behaviour_on_grid_timeout() {
AutoML aml=null;
Frame fr=null;
try {
AutoMLBuildSpec autoMLBuildSpec = new AutoMLBuildSpec();
fr = parse_test_file("./smalldata/logreg/prostate_train.csv");
autoMLBuildSpec.input_spec.training_frame = fr._key;
autoMLBuildSpec.input_spec.response_column = "CAPSULE";
autoMLBuildSpec.build_models.exclude_algos = new Algo[] {Algo.DeepLearning, Algo.DRF, Algo.GLM};
autoMLBuildSpec.build_control.stopping_criteria.set_max_runtime_secs(8);
// autoMLBuildSpec.build_control.stopping_criteria.set_max_runtime_secs(new Random().nextInt(30));
autoMLBuildSpec.build_control.keep_cross_validation_models = false; //Prevent leaked keys from CV models
autoMLBuildSpec.build_control.keep_cross_validation_predictions = false; //Prevent leaked keys from CV predictions
aml = AutoML.startAutoML(autoMLBuildSpec);
aml.get();
// no assertion, we just want to check leaked keys
} finally {
// Cleanup
if(aml!=null) aml.delete();
if(fr != null) fr.delete();
}
}
@Ignore
@Test public void test_individual_model_max_runtime() {
AutoML aml=null;
Frame fr=null;
try {
AutoMLBuildSpec autoMLBuildSpec = new AutoMLBuildSpec();
// fr = parse_test_file("./smalldata/prostate/prostate_complete.csv"); //using slightly larger dataset to make this test useful
// autoMLBuildSpec.input_spec.response_column = "CAPSULE";
fr = parse_test_file("./smalldata/diabetes/diabetes_text_train.csv"); //using slightly larger dataset to make this test useful
autoMLBuildSpec.input_spec.response_column = "diabetesMed";
autoMLBuildSpec.input_spec.training_frame = fr._key;
int max_runtime_secs_per_model = 10;
autoMLBuildSpec.build_models.exclude_algos = aro(Algo.GLM, Algo.DeepLearning); // GLM still tends to take a bit more time than it should: nothing dramatic, but enough to fail UTs.
autoMLBuildSpec.build_control.stopping_criteria.set_seed(1);
autoMLBuildSpec.build_control.stopping_criteria.set_max_models(10);
autoMLBuildSpec.build_control.stopping_criteria.set_max_runtime_secs_per_model(max_runtime_secs_per_model);
autoMLBuildSpec.build_control.keep_cross_validation_models = false; //Prevent leaked keys from CV models
autoMLBuildSpec.build_control.keep_cross_validation_predictions = false; //Prevent leaked keys from CV predictions
aml = AutoML.startAutoML(autoMLBuildSpec);
aml.get();
int tolerance = (autoMLBuildSpec.build_control.nfolds + 1) * max_runtime_secs_per_model / 3; //generously adding 33% tolerance for each cv model + final model
for (Key<Model> key : aml.leaderboard().getModelKeys()) {
Model model = key.get();
double duration = model._output._total_run_time / 1e3;
assertTrue(key + " took longer than required: "+ duration,
duration - max_runtime_secs_per_model < tolerance);
}
} finally {
// Cleanup
if(aml!=null) aml.delete();
if(fr != null) fr.delete();
}
}
@Test public void KeepCrossValidationFoldAssignmentEnabledTest() {
AutoML aml = null;
Frame fr = null;
Model leader = null;
try {
AutoMLBuildSpec autoMLBuildSpec = new AutoMLBuildSpec();
fr = parse_test_file("./smalldata/logreg/prostate_train.csv");
autoMLBuildSpec.input_spec.training_frame = fr._key;
autoMLBuildSpec.input_spec.response_column = "CAPSULE";
autoMLBuildSpec.build_control.stopping_criteria.set_max_models(1);
autoMLBuildSpec.build_control.stopping_criteria.set_max_runtime_secs(30);
autoMLBuildSpec.build_control.keep_cross_validation_fold_assignment = true;
aml = AutoML.makeAutoML(Key.make(), new Date(), autoMLBuildSpec);
AutoML.startAutoML(aml);
aml.get();
leader = aml.leader();
assertTrue(leader !=null && leader._parms._keep_cross_validation_fold_assignment);
assertNotNull(leader._output._cross_validation_fold_assignment_frame_id);
} finally {
if(aml!=null) aml.delete();
if(fr != null) fr.remove();
}
}
@Test public void KeepCrossValidationFoldAssignmentDisabledTest() {
AutoML aml = null;
Frame fr = null;
Model leader = null;
try {
AutoMLBuildSpec autoMLBuildSpec = new AutoMLBuildSpec();
fr = parse_test_file("./smalldata/airlines/AirlinesTrain.csv");
autoMLBuildSpec.input_spec.training_frame = fr._key;
autoMLBuildSpec.input_spec.response_column = "IsDepDelayed";
autoMLBuildSpec.build_control.stopping_criteria.set_max_models(1);
autoMLBuildSpec.build_control.keep_cross_validation_fold_assignment = false;
aml = AutoML.makeAutoML(Key.make(), new Date(), autoMLBuildSpec);
AutoML.startAutoML(aml);
aml.get();
leader = aml.leader();
assertTrue(leader !=null && !leader._parms._keep_cross_validation_fold_assignment);
assertNull(leader._output._cross_validation_fold_assignment_frame_id);
} finally {
if(aml!=null) aml.delete();
if(fr != null) fr.delete();
}
}
@Test public void testWorkPlanWithoutExploitation() {
AutoML aml = null;
Frame fr=null;
try {
AutoMLBuildSpec autoMLBuildSpec = new AutoMLBuildSpec();
fr = parse_test_file("./smalldata/airlines/allyears2k_headers.zip");
autoMLBuildSpec.input_spec.training_frame = fr._key;
autoMLBuildSpec.input_spec.response_column = "IsDepDelayed";
autoMLBuildSpec.build_models.exploitation_ratio = 0;
aml = new AutoML(Key.make(), new Date(), autoMLBuildSpec);
Map<Algo, Integer> defaultAllocs = new HashMap<Algo, Integer>(){{
put(Algo.DeepLearning, 1*10+3*20); // models+grids
put(Algo.DRF, 2*10);
put(Algo.GBM, 5*10+1*60); // models+grids
put(Algo.GLM, 1*10);
put(Algo.XGBoost, 3*10+1*100); // models+grids
put(Algo.StackedEnsemble, 2*10);
}};
int maxTotalWork = 0;
for (Map.Entry<Algo, Integer> entry : defaultAllocs.entrySet()) {
if (entry.getKey().enabled()) {
maxTotalWork += entry.getValue();
}
}
assertEquals(maxTotalWork, aml._workAllocations.remainingWork());
autoMLBuildSpec.build_models.exclude_algos = aro(Algo.DeepLearning, Algo.DRF);
aml.planWork();
assertEquals(maxTotalWork - defaultAllocs.get(Algo.DeepLearning) - defaultAllocs.get(Algo.DRF), aml._workAllocations.remainingWork());
} finally {
if (aml != null) aml.delete();
if (fr != null) fr.remove();
}
}
@Test public void testWorkPlanWithExploitation() {
AutoML aml = null;
Frame fr=null;
try {
double exploitationRatio = 0.2;
AutoMLBuildSpec autoMLBuildSpec = new AutoMLBuildSpec();
fr = parse_test_file("./smalldata/airlines/allyears2k_headers.zip");
autoMLBuildSpec.input_spec.training_frame = fr._key;
autoMLBuildSpec.input_spec.response_column = "IsDepDelayed";
autoMLBuildSpec.build_models.exploitation_ratio = exploitationRatio;
aml = new AutoML(Key.make(), new Date(), autoMLBuildSpec);
Map<Algo, Integer> explorationAllocs = new HashMap<Algo, Integer>(){{
put(Algo.DeepLearning, 1*10+3*20); // models+grids
put(Algo.DRF, 2*10);
put(Algo.GBM, 5*10+1*60); // models+grids
put(Algo.GLM, 1*10);
put(Algo.XGBoost, 3*10+1*100); // models+grids
put(Algo.StackedEnsemble, 2*10);
}};
Map<Algo, Integer> exploitationAllocs = new HashMap<Algo, Integer>(){{
put(Algo.GBM, 1*10);
put(Algo.XGBoost, 2*20);
}};
int expectedExplorationWork = explorationAllocs.entrySet().stream().filter(algo -> algo.getKey().enabled()).mapToInt(Map.Entry::getValue).sum();
Function<AutoML, Double> computeExploitationRatio = automl -> {
int explorationWork = automl._workAllocations.remainingWork(ModelingStep.isExplorationWork);
int exploitationWork = automl._workAllocations.remainingWork(ModelingStep.isExploitationWork);
return (double)exploitationWork/(explorationWork+exploitationWork);
};
assertEquals(expectedExplorationWork, aml._workAllocations.remainingWork(ModelingStep.isExplorationWork));
assertEquals(expectedExplorationWork, aml._workAllocations.remainingWork() * (1 - exploitationRatio), 1);
assertEquals(exploitationRatio, computeExploitationRatio.apply(aml), 0.1);
autoMLBuildSpec.build_models.exclude_algos = aro(Algo.DeepLearning, Algo.DRF);
aml.planWork();
expectedExplorationWork = expectedExplorationWork - explorationAllocs.get(Algo.DeepLearning) - explorationAllocs.get(Algo.DRF);
assertEquals(expectedExplorationWork, aml._workAllocations.remainingWork(ModelingStep.isExplorationWork));
assertEquals(expectedExplorationWork, aml._workAllocations.remainingWork() * (1 - exploitationRatio), 1);
assertEquals(exploitationRatio, computeExploitationRatio.apply(aml), 0.01);
int totalExploitationWork = exploitationAllocs.entrySet().stream().filter(algo -> algo.getKey().enabled()).mapToInt(Map.Entry::getValue).sum();
double expectedGBMExploitationRatio = (double)exploitationAllocs.get(Algo.GBM) / totalExploitationWork;
double computedGBMExploitationRatio = (double)aml._workAllocations.remainingWork(ModelingStep.isExploitationWork.and(w -> w._algo == Algo.GBM)) / aml._workAllocations.remainingWork(ModelingStep.isExploitationWork);
assertEquals(expectedGBMExploitationRatio, computedGBMExploitationRatio, 0.01);
} finally {
if (aml != null) aml.delete();
if (fr != null) fr.remove();
}
}
@Test public void test_training_plan() {
AutoML aml = null;
Frame fr=null;
try {
AutoMLBuildSpec autoMLBuildSpec = new AutoMLBuildSpec();
fr = parse_test_file("./smalldata/logreg/prostate_train.csv");
autoMLBuildSpec.input_spec.training_frame = fr._key;
autoMLBuildSpec.input_spec.response_column = "CAPSULE";
autoMLBuildSpec.build_models.modeling_plan = new StepDefinition[] {
new StepDefinition(Algo.GBM.name(), new String[]{ "def_1" }), // 1 model
new StepDefinition(Algo.GLM.name(), StepDefinition.Alias.all), // 1 model
new StepDefinition(Algo.DRF.name(), new Step[] { new Step("XRT", 20) }), // 1 model
new StepDefinition(Algo.XGBoost.name(), StepDefinition.Alias.grids), // 1 grid
new StepDefinition(Algo.DeepLearning.name(), StepDefinition.Alias.grids), // 1 grid
new StepDefinition(Algo.StackedEnsemble.name(), StepDefinition.Alias.defaults) // 2 models
};
autoMLBuildSpec.build_models.exclude_algos = new Algo[] {Algo.XGBoost, Algo.DeepLearning};
aml = AutoML.startAutoML(autoMLBuildSpec);
aml.get();
assertEquals(5, aml.leaderboard().getModelCount());
assertEquals(1, Stream.of(aml.leaderboard().getModels()).filter(GBMModel.class::isInstance).count());
assertEquals(1, Stream.of(aml.leaderboard().getModels()).filter(GLMModel.class::isInstance).count());
assertEquals(1, Stream.of(aml.leaderboard().getModels()).filter(DRFModel.class::isInstance).count());
assertEquals(0, Stream.of(aml.leaderboard().getModels()).filter(XGBoostModel.class::isInstance).count());
assertEquals(0, Stream.of(aml.leaderboard().getModels()).filter(DeepLearningModel.class::isInstance).count());
assertEquals(2, Stream.of(aml.leaderboard().getModels()).filter(StackedEnsembleModel.class::isInstance).count());
assertNotNull(aml._actualModelingSteps);
Log.info(Arrays.toString(aml._actualModelingSteps));
assertArrayEquals(new StepDefinition[] {
new StepDefinition(Algo.GBM.name(), new Step[]{
new Step("def_1", ModelingStep.ModelStep.DEFAULT_MODEL_TRAINING_WEIGHT),
}),
new StepDefinition(Algo.GLM.name(), new Step[]{
new Step("def_1", ModelingStep.ModelStep.DEFAULT_MODEL_TRAINING_WEIGHT),
}),
new StepDefinition(Algo.DRF.name(), new Step[]{
new Step("XRT", 20),
}),
new StepDefinition(Algo.StackedEnsemble.name(), new Step[]{
new Step("best", ModelingStep.ModelStep.DEFAULT_MODEL_TRAINING_WEIGHT),
new Step("all", ModelingStep.ModelStep.DEFAULT_MODEL_TRAINING_WEIGHT),
}),
}, aml._actualModelingSteps);
} finally {
if (aml != null) aml.delete();
if (fr != null) fr.remove();
}
}
@Test public void test_training_frame_partition_when_cv_disabled_and_validation_frame_missing() {
AutoML aml = null;
Frame fr = null, test = null;
try {
AutoMLBuildSpec autoMLBuildSpec = new AutoMLBuildSpec();
fr = parse_test_file("./smalldata/logreg/prostate_train.csv");
test = parse_test_file("./smalldata/logreg/prostate_test.csv");
autoMLBuildSpec.input_spec.response_column = "CAPSULE";
autoMLBuildSpec.input_spec.training_frame = fr._key;
autoMLBuildSpec.input_spec.validation_frame = null;
autoMLBuildSpec.input_spec.leaderboard_frame = test._key;
autoMLBuildSpec.build_control.nfolds = 0;
autoMLBuildSpec.build_control.stopping_criteria.set_max_models(1);
autoMLBuildSpec.build_control.stopping_criteria.set_seed(1);
aml = AutoML.startAutoML(autoMLBuildSpec);
aml.get();
double tolerance = 1e-2;
assertEquals(0.9, (double)aml.getTrainingFrame().numRows() / fr.numRows(), tolerance);
assertEquals(0.1, (double)aml.getValidationFrame().numRows() / fr.numRows(), tolerance);
assertEquals(test.numRows(), aml.getLeaderboardFrame().numRows());
} finally {
if (aml != null) aml.delete();
if (fr != null) fr.remove();
if (test != null) test.remove();
}
}
@Test public void test_training_frame_partition_when_cv_disabled_and_leaderboard_frame_missing() {
AutoML aml = null;
Frame fr = null, test = null;
try {
AutoMLBuildSpec autoMLBuildSpec = new AutoMLBuildSpec();
fr = parse_test_file("./smalldata/logreg/prostate_train.csv");
test = parse_test_file("./smalldata/logreg/prostate_test.csv");
autoMLBuildSpec.input_spec.response_column = "CAPSULE";
autoMLBuildSpec.input_spec.training_frame = fr._key;
autoMLBuildSpec.input_spec.validation_frame = test._key;
autoMLBuildSpec.input_spec.leaderboard_frame = null;
autoMLBuildSpec.build_control.nfolds = 0;
autoMLBuildSpec.build_control.stopping_criteria.set_max_models(1);
autoMLBuildSpec.build_control.stopping_criteria.set_seed(1);
aml = AutoML.startAutoML(autoMLBuildSpec);
aml.get();
double tolerance = 1e-2;
assertEquals(0.9, (double)aml.getTrainingFrame().numRows() / fr.numRows(), tolerance);
assertEquals(test.numRows(), aml.getValidationFrame().numRows());
assertEquals(0.1, (double)aml.getLeaderboardFrame().numRows() / fr.numRows(), tolerance);
} finally {
if (aml != null) aml.delete();
if (fr != null) fr.remove();
if (test != null) test.remove();
}
}
@Test public void test_training_frame_partition_when_cv_disabled_and_both_validation_and_leaderboard_frames_missing() {
AutoML aml = null;
Frame fr = null;
try {
AutoMLBuildSpec autoMLBuildSpec = new AutoMLBuildSpec();
fr = parse_test_file("./smalldata/logreg/prostate_train.csv");
autoMLBuildSpec.input_spec.response_column = "CAPSULE";
autoMLBuildSpec.input_spec.training_frame = fr._key;
autoMLBuildSpec.input_spec.validation_frame = null;
autoMLBuildSpec.input_spec.leaderboard_frame = null;
autoMLBuildSpec.build_control.nfolds = 0;
autoMLBuildSpec.build_control.stopping_criteria.set_max_models(1);
autoMLBuildSpec.build_control.stopping_criteria.set_seed(1);
aml = AutoML.startAutoML(autoMLBuildSpec);
aml.get();
double tolerance = 1e-2;
assertEquals(0.8, (double)aml.getTrainingFrame().numRows() / fr.numRows(), tolerance);
assertEquals(0.1, (double)aml.getValidationFrame().numRows() / fr.numRows(), tolerance);
assertEquals(0.1, (double)aml.getLeaderboardFrame().numRows() / fr.numRows(), tolerance);
} finally {
if (aml != null) aml.delete();
if (fr != null) fr.remove();
}
}
@Test public void test_training_frame_not_partitioned_when_cv_enabled() {
AutoML aml = null;
Frame fr = null;
try {
AutoMLBuildSpec autoMLBuildSpec = new AutoMLBuildSpec();
fr = parse_test_file("./smalldata/logreg/prostate_train.csv");
autoMLBuildSpec.input_spec.response_column = "CAPSULE";
autoMLBuildSpec.input_spec.training_frame = fr._key;
autoMLBuildSpec.input_spec.validation_frame = null;
autoMLBuildSpec.input_spec.leaderboard_frame = null;
autoMLBuildSpec.build_control.stopping_criteria.set_max_models(1);
autoMLBuildSpec.build_control.stopping_criteria.set_seed(1);
aml = AutoML.startAutoML(autoMLBuildSpec);
aml.get();
assertEquals(fr.numRows(), aml.getTrainingFrame().numRows());
assertNull(aml.getValidationFrame());
assertNull(aml.getLeaderboardFrame());
} finally {
if (aml != null) aml.delete();
if (fr != null) fr.remove();
}
}
@Test public void testExcludeAlgos() {
AutoML aml = null;
Frame fr=null;
try {
AutoMLBuildSpec autoMLBuildSpec = new AutoMLBuildSpec();
fr = parse_test_file("./smalldata/airlines/allyears2k_headers.zip");
autoMLBuildSpec.input_spec.training_frame = fr._key;
autoMLBuildSpec.input_spec.response_column = "IsDepDelayed";
autoMLBuildSpec.build_models.exclude_algos = new Algo[] {Algo.DeepLearning, Algo.XGBoost, };
aml = new AutoML(Key.make(), new Date(), autoMLBuildSpec);
for (IAlgo algo : autoMLBuildSpec.build_models.exclude_algos) {
assertEquals(0, aml._workAllocations.getAllocations(w -> w._algo == algo).length);
}
for (Algo algo : Algo.values()) {
if (!ArrayUtils.contains(autoMLBuildSpec.build_models.exclude_algos, algo)) {
assertNotEquals(0, aml._workAllocations.getAllocations(w -> w._algo == algo).length);
}
}
} finally {
if (aml != null) aml.delete();
if (fr != null) fr.remove();
}
}
@Test public void testIncludeAlgos() {
AutoML aml = null;
Frame fr=null;
try {
AutoMLBuildSpec autoMLBuildSpec = new AutoMLBuildSpec();
fr = parse_test_file("./smalldata/airlines/allyears2k_headers.zip");
autoMLBuildSpec.input_spec.training_frame = fr._key;
autoMLBuildSpec.input_spec.response_column = "IsDepDelayed";
autoMLBuildSpec.build_models.include_algos = new Algo[] {Algo.DeepLearning, Algo.XGBoost, };
aml = new AutoML(Key.make(), new Date(), autoMLBuildSpec);
for (IAlgo algo : autoMLBuildSpec.build_models.include_algos) {
if (algo.enabled()) {
assertNotEquals(0, aml._workAllocations.getAllocations(w -> w._algo == algo).length);
} else {
assertEquals(0, aml._workAllocations.getAllocations(w -> w._algo == algo).length);
}
}
for (Algo algo : Algo.values()) {
if (!ArrayUtils.contains(autoMLBuildSpec.build_models.include_algos, algo)) {
assertEquals(0, aml._workAllocations.getAllocations(w -> w._algo == algo).length);
}
}
} finally {
if (aml != null) aml.delete();
if (fr != null) fr.remove();
}
}
@Test public void testExcludeIncludeAlgos() {
AutoML aml = null;
Frame fr=null;
try {
AutoMLBuildSpec autoMLBuildSpec = new AutoMLBuildSpec();
fr = parse_test_file("./smalldata/airlines/allyears2k_headers.zip");
autoMLBuildSpec.input_spec.training_frame = fr._key;
autoMLBuildSpec.input_spec.response_column = "IsDepDelayed";
autoMLBuildSpec.build_models.exclude_algos = new Algo[] {Algo.GBM, Algo.GLM, };
autoMLBuildSpec.build_models.include_algos = new Algo[] {Algo.DeepLearning, Algo.XGBoost, };
try {
aml = new AutoML(Key.make(), new Date(), autoMLBuildSpec);
fail("Should have thrown an H2OIllegalArgumentException for providing both include_algos and exclude_algos");
} catch (H2OIllegalArgumentException e) {
assertTrue(e.getMessage().startsWith("Parameters `exclude_algos` and `include_algos` are mutually exclusive"));
}
} finally {
if (aml != null) aml.delete();
if (fr != null) fr.remove();
}
}
@Test public void testAlgosHaveDefaultParametersEnforcingReproducibility() {
AutoML aml=null;
Frame fr=null;
try {
int maxModels = 20; // generating enough models so that we can check every algo x every mode (single model + grid models)
int seed = 0;
int nfolds = 0; //this test currently fails if CV is enabled due to PUBDEV-6385 (the final model gets its `stopping_rounds` param reset to 0)
AutoMLBuildSpec autoMLBuildSpec = new AutoMLBuildSpec();
fr = parse_test_file("./smalldata/logreg/prostate.csv");
autoMLBuildSpec.input_spec.training_frame = fr._key;
autoMLBuildSpec.input_spec.response_column = "CAPSULE";
autoMLBuildSpec.build_control.stopping_criteria.set_max_models(maxModels);
autoMLBuildSpec.build_control.nfolds = nfolds;
autoMLBuildSpec.build_control.stopping_criteria.set_seed(seed);
aml = AutoML.startAutoML(autoMLBuildSpec);
aml.get();
assertEquals(maxModels+(nfolds > 0 ? 2 : 0), aml.leaderboard().getModelCount());
Key[] modelKeys = aml.leaderboard().getModelKeys();
Map<Algo, List<Key<Model>>> keysByAlgo = new HashMap<>();
for (Algo algo : Algo.values()) keysByAlgo.put(algo, new ArrayList<>());
for (Key k : modelKeys) {
if (k.toString().startsWith("XRT")) {
keysByAlgo.get(Algo.DRF).add(k);
} else for (Algo algo: Algo.values()) {
if (k.toString().startsWith(algo.name())) {
keysByAlgo.get(algo).add(k);
break;
}
}
}
// verify that all keys were categorized
int count = 0; for (List<Key<Model>> keys : keysByAlgo.values()) count += keys.size();
assertEquals(aml.leaderboard().getModelCount(), count);
// check parameters constraints that should be set for all models
for (Algo algo: Algo.values()) {
Set<Long> collectedSeeds = new HashSet<>(); // according to AutoML logic, no model for same algo should have the same seed.
List<Key<Model>> keys = keysByAlgo.get(algo);
for (Key<Model> key : keys) {
Model.Parameters parameters = key.get()._parms;
assertTrue(parameters._seed != -1);
assertTrue(key+":"+parameters._seed, Math.abs(parameters._seed - seed) < maxModels);
collectedSeeds.add(parameters._seed);
assertTrue(key+" has `stopping_rounds` param set to "+parameters._stopping_rounds,
parameters._stopping_rounds == 3 || algo == Algo.XGBoost); // currently only enforced to different value for XGB (AutoML hardcoded)
}
assertTrue(collectedSeeds.size() > 1 || keys.size() < 2); // we should have built enough models to guarantee this
}
//check model specific constraints
for (Algo algo : Arrays.asList(Algo.XGBoost)) {
List<Key<Model>> keys = keysByAlgo.get(algo);
for (Key<Model> key : keys) {
XGBoostParameters parameters = (XGBoostParameters)key.get()._parms;
assertEquals(5, parameters._score_tree_interval);
assertEquals(3, parameters._stopping_rounds); //should probably not be left enforced/hardcoded for XGB?
}
}
for (Algo algo : Arrays.asList(Algo.DRF, Algo.GBM)) {
List<Key<Model>> keys = keysByAlgo.get(algo);
for (Key<Model> key : keys) {
SharedTreeParameters parameters = (SharedTreeParameters)key.get()._parms;
assertEquals(5, parameters._score_tree_interval);
}
}
} finally {
// Cleanup
if(aml!=null) aml.delete();
if(fr != null) fr.delete();
}
}
}
|
package com.stuonline;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void aa(){
}
}
|
package org.springframework.roo.addon.mvc.jsp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;
import org.springframework.roo.classpath.details.FieldMetadata;
import org.springframework.roo.classpath.details.annotations.AnnotationAttributeValue;
import org.springframework.roo.classpath.details.annotations.AnnotationMetadata;
import org.springframework.roo.model.JavaSymbolName;
import org.springframework.roo.model.JavaType;
import org.springframework.roo.support.util.XmlUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
*
* This is a helper class which creates SpringJS / Dojo artifacts
* used during jsp generation.
*
* @author Stefan Schmidt
* @since 1.0
*
*/
public class DojoUtils {
public static Element getTitlePaneDojo(Document document, String title) {
addDojoDepenency(document, "dijit.TitlePane");
Element divElement = document.createElement("div");
divElement.setAttribute("dojoType", "dijit.TitlePane");
divElement.setAttribute("title", title);
divElement.setAttribute("style", "width: 100%");
return divElement;
}
public static Element getRequiredDateDojo(Document document, JavaSymbolName fieldName) {
SimpleDateFormat dateFormatLocalized = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.DEFAULT, Locale.getDefault());
addDojoDepenency(document, "dijit.form.DateTextBox");
Element script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setTextContent("Spring.addDecoration(new Spring.ElementDecoration({elementId : '_" + fieldName.getSymbolName().toLowerCase()
+ "', widgetType : 'dijit.form.DateTextBox\", widgetAttrs : {constraints: {datePattern : '" + dateFormatLocalized.toPattern()
+ "', required : true}, datePattern : '" + dateFormatLocalized.toPattern() + "'}})); ");
return script;
}
public static Element getDateDojo(Document document, FieldMetadata field) {
SimpleDateFormat dateFormatLocalized = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.DEFAULT, Locale.getDefault());
addDojoDepenency(document, "dijit.form.DateTextBox");
Element script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setTextContent("Spring.addDecoration(new Spring.ElementDecoration({elementId : '_" + field.getFieldName().getSymbolName()
+ "', widgetType : 'dijit.form.DateTextBox', widgetAttrs : {constraints: {datePattern : '" + dateFormatLocalized.toPattern() + "', required : "
+ (isTypeInAnnotationList(new JavaType("javax.validation.NotNull"), field.getAnnotations()) ? "true" : "false") + "}, datePattern : '" + dateFormatLocalized.toPattern() + "'}})); ");
return script;
}
public static Element getSimpleValidationDojo(Document document, JavaSymbolName field) {
Element script = document.createElement("script");
script.setAttribute("type", "text/javascript");
String message = "Enter " + field.getReadableSymbolName() + " (required)";
script.setTextContent("Spring.addDecoration(new Spring.ElementDecoration({elementId : '_" + field.getSymbolName().toLowerCase()
+ "', widgetType : 'dijit.form.ValidationTextBox', widgetAttrs : {promptMessage: '" + message + "', required : true}})); ");
return script;
}
public static Element getValidationDojo(Document document, FieldMetadata field) {
String regex = "";
String invalid = "";
int min = getMinSize(field);
int max = getMaxSize(field);
boolean isRequired = isTypeInAnnotationList(new JavaType("javax.validation.constraints.NotNull"), field.getAnnotations());
if(field.getFieldType().equals(new JavaType(Integer.class.getName()))) {
if (min != Integer.MIN_VALUE || max != Integer.MAX_VALUE) {
regex = ", regExp: \"-?[0-9]{" + (min == Integer.MIN_VALUE ? "1," : min) + (max == Integer.MAX_VALUE ? "" : max) + "}\"";
} else {
regex = ", regExp: \"-?[0-9]*\"";
}
invalid = "Integer numbers only";
} else if(field.getFieldType().equals(new JavaType(Double.class.getName())) || field.getFieldType().equals(new JavaType(Float.class.getName()))) {
if (min != Integer.MIN_VALUE || max != Integer.MAX_VALUE) {
regex = ", regExp: \"-?[0-9]{" + (min == Integer.MIN_VALUE ? "1," : min) + (max == Integer.MAX_VALUE ? "" : max) + "}(\\.?[0-9]*)?\"";
} else {
regex = ", regExp: \"-?[0-9]*\\.[0-9]*\"";
}
invalid = "Number with '-' or '.' allowed" + (isRequired ? ", required" : "");
} else if (field.getFieldName().getSymbolName().contains("email")) {
regex = ", regExp: \"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\"";
invalid = "Valid email only";
}
Element script = document.createElement("script");
script.setAttribute("type", "text/javascript");
String message = "Enter " + field.getFieldName().getReadableSymbolName() + (isRequired ? " (required)" : "");
script.setTextContent("Spring.addDecoration(new Spring.ElementDecoration({elementId : \"_" + field.getFieldName().getSymbolName()
+ "\", widgetType : \"dijit.form.ValidationTextBox\", widgetAttrs : {promptMessage: \"" + message + "\", invalidMessage: \"" + invalid
+ "\"" + regex + ", required : " + isRequired + "}})); ");
return script;
}
public static Element getTextAreaDojo(Document document, JavaSymbolName fieldName) {
addDojoDepenency(document, "dijit.form.SimpleTextarea");
Element script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setTextContent("Spring.addDecoration(new Spring.ElementDecoration({elementId : \"_" + fieldName.getSymbolName()
+ "\", widgetType: 'dijit.form.SimpleTextarea', widgetAttrs: {}})); ");
return script;
}
public static Element getSelectDojo(Document document, JavaSymbolName fieldName) {
addDojoDepenency(document, "dijit.form.FilteringSelect");
Element script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setTextContent("Spring.addDecoration(new Spring.ElementDecoration({elementId : '_" + fieldName.getSymbolName()
+ "', widgetType: 'dijit.form.FilteringSelect', widgetAttrs : {hasDownArrow : true}})); ");
return script;
}
public static Element getMultiSelectDojo(Document document, JavaSymbolName fieldName) {
addDojoDepenency(document, "dijit.form.MultiSelect");
Element script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setTextContent("Spring.addDecoration(new Spring.ElementDecoration({elementId : '_" + fieldName.getSymbolName()
+ "', widgetType: 'dijit.form.MultiSelect', widgetAttrs: {}})); ");
return script;
}
public static Element getSubmitButtonDojo(Document document, String buttonId) {
Element script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setTextContent("Spring.addDecoration(new Spring.ValidateAllDecoration({elementId:'" + buttonId + "', event:'onclick'}));");
return script;
}
public static void addDojoDepenency(Document document, String require) {
boolean elementFound = true;
Element script = XmlUtils.findFirstElement("//script[starts-with(text(),'dojo.require')]", document.getDocumentElement());
if(script == null) {
elementFound = false;
script = document.createElement("script");
script.setAttribute("type", "text/javascript");
}
if (!script.getTextContent().contains(require)) {
script.setTextContent(script.getTextContent() + "dojo.require(\"" + require + "\");");
}
if (!elementFound) {
document.getDocumentElement().insertBefore(script, XmlUtils.findFirstElement("//directive.include[2]", document.getDocumentElement()).getNextSibling());
}
}
private static boolean isTypeInAnnotationList(JavaType type, List<AnnotationMetadata> annotations) {
for (AnnotationMetadata annotation : annotations) {
if(annotation.getAnnotationType().equals(type)) {
return true;
}
}
return false;
}
private static int getMinSize(FieldMetadata field) {
for(AnnotationMetadata annotation : field.getAnnotations()) {
if (annotation.getAnnotationType().getFullyQualifiedTypeName().equals("javax.validation.constraints.Size")) {
AnnotationAttributeValue<?> minValue = annotation.getAttribute(new JavaSymbolName("min"));
if(minValue != null) {
return (Integer)minValue.getValue();
}
}
}
return Integer.MIN_VALUE;
}
private static int getMaxSize(FieldMetadata field) {
for(AnnotationMetadata annotation : field.getAnnotations()) {
if (annotation.getAnnotationType().getFullyQualifiedTypeName().equals("javax.validation.constraints.Size")) {
AnnotationAttributeValue<?> maxValue = annotation.getAttribute(new JavaSymbolName("max"));
if(maxValue != null) {
return (Integer)maxValue.getValue();
}
}
}
return Integer.MAX_VALUE;
}
}
|
package water.parser;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashSet;
import java.util.zip.*;
import jsr166y.CountedCompleter;
import water.*;
import water.fvec.*;
import water.fvec.Vec.VectorGroup;
import water.nbhm.NonBlockingHashMap;
import water.nbhm.NonBlockingSetInt;
import water.util.ArrayUtils;
import water.util.FrameUtils;
import water.util.PrettyPrint;
import water.util.Log;
public final class ParseDataset2 extends Job<Frame> {
private MultiFileParseTask _mfpt; // Access to partially built vectors for cleanup after parser crash
// Keys are limited to ByteVec Keys and Frames-of-1-ByteVec Keys
public static Frame parse(Key okey, Key... keys) { return parse(okey,keys,true, false,0/*guess header*/); }
// Guess setup from inspecting the first Key only, then parse.
// Suitable for e.g. testing setups, where the data is known to be sane.
// NOT suitable for random user input!
public static Frame parse(Key okey, Key[] keys, boolean delete_on_done, boolean singleQuote, int checkHeader) {
return parse(okey,keys,delete_on_done,setup(keys[0],singleQuote,checkHeader));
}
public static Frame parse(Key okey, Key[] keys, boolean delete_on_done, ParseSetup globalSetup) {
return parse(okey,keys,delete_on_done,globalSetup,true).get();
}
public static ParseDataset2 parse(Key okey, Key[] keys, boolean delete_on_done, ParseSetup globalSetup, boolean blocking) {
ParseDataset2 job = forkParseDataset(okey,keys,globalSetup,delete_on_done);
try { if( blocking ) job.get(); return job; }
catch( Throwable ex ) {
// Took a crash/NPE somewhere in the parser. Attempt cleanup.
Futures fs = new Futures();
if( job != null ) {
Keyed.remove(job._dest,fs);
// Find & remove all partially-built output vecs & chunks
if( job._mfpt != null ) job._mfpt.onExceptionCleanup(fs);
}
// Assume the input is corrupt - or already partially deleted after
// parsing. Nuke it all - no partial Vecs lying around.
for( Key k : keys ) Keyed.remove(k,fs);
fs.blockForPending();
assert DKV.<Job>getGet(job._key).isStopped();
throw ex;
}
}
private static ParseSetup setup(Key k, boolean singleQuote, int checkHeader) {
byte[] bits = ZipUtil.getFirstUnzippedBytes(getByteVec(k));
ParseSetup globalSetup = ParseSetup.guessSetup(bits, singleQuote, checkHeader);
if( globalSetup._ncols <= 0 ) throw new UnsupportedOperationException(globalSetup.toString());
return globalSetup;
}
// Allow both ByteVec keys and Frame-of-1-ByteVec
static ByteVec getByteVec(Key key) {
Iced ice = DKV.get(key).get();
return (ByteVec)(ice instanceof ByteVec ? ice : ((Frame)ice).vecs()[0]);
}
static String [] genericColumnNames(int ncols){
String [] res = new String[ncols];
for(int i = 0; i < res.length; ++i) res[i] = "C" + String.valueOf(i+1);
return res;
}
// Same parse, as a backgroundable Job
public static ParseDataset2 forkParseDataset(final Key dest, final Key[] keys, final ParseSetup setup, boolean delete_on_done) {
HashSet<String> conflictingNames = setup.checkDupColumnNames();
for( String x : conflictingNames )
throw new IllegalArgumentException("Found duplicate column name "+x);
// Some quick sanity checks: no overwriting your input key, and a resource check.
long sum=0;
for( int i=0; i<keys.length; i++ ) {
Key k = keys[i];
if( dest.equals(k) )
throw new IllegalArgumentException("Destination key "+dest+" must be different from all sources");
if( delete_on_done )
for( int j=i+1; j<keys.length; j++ )
if( k==keys[j] )
throw new IllegalArgumentException("Source key "+k+" appears twice, delete_on_done must be false");
sum += getByteVec(k).length(); // Sum of all input filesizes
}
long memsz = H2O.CLOUD.memsz();
if( sum > memsz*4 )
throw new IllegalArgumentException("Total input file size of "+PrettyPrint.bytes(sum)+" is much larger than total cluster memory of "+PrettyPrint.bytes(memsz)+", please use either a larger cluster or smaller data.");
// Fire off the parse
ParseDataset2 job = new ParseDataset2(dest);
new Frame(job.dest(),new String[0],new Vec[0]).delete_and_lock(job._key); // Write-Lock BEFORE returning
for( Key k : keys ) Lockable.read_lock(k,job._key); // Read-Lock BEFORE returning
ParserFJTask fjt = new ParserFJTask(job, keys, setup, delete_on_done); // Fire off background parse
job.start(fjt, sum);
return job;
}
// Setup a private background parse job
private ParseDataset2(Key dest) {
super(dest,"Parse");
}
// Simple internal class doing background parsing, with trackable Job status
public static class ParserFJTask extends water.H2O.H2OCountedCompleter {
final ParseDataset2 _job;
final Key[] _keys;
final ParseSetup _setup;
final boolean _delete_on_done;
public ParserFJTask( ParseDataset2 job, Key[] keys, ParseSetup setup, boolean delete_on_done) {
_job = job;
_keys = keys;
_setup = setup;
_delete_on_done = delete_on_done;
}
@Override public void compute2() {
parse_impl(_job, _keys, _setup, _delete_on_done);
tryComplete();
}
// Took a crash/NPE somewhere in the parser. Attempt cleanup.
@Override public boolean onExceptionalCompletion(Throwable ex, CountedCompleter caller){
if( _job != null ) _job.cancel2(ex);
return true;
}
@Override public void onCompletion(CountedCompleter caller) { _job.done(); }
}
private static class EnumMapping extends Iced {
final int [][] map;
public EnumMapping(int[][] map){this.map = map;}
}
// Top-level parser driver
private static void parse_impl(ParseDataset2 job, Key[] fkeys, ParseSetup setup, boolean delete_on_done) {
assert setup._ncols > 0;
if( fkeys.length == 0) { job.cancel(); return; }
VectorGroup vg = getByteVec(fkeys[0]).group();
MultiFileParseTask mfpt = job._mfpt = new MultiFileParseTask(vg,setup,job._key,fkeys,delete_on_done);
mfpt.doAll(fkeys);
EnumUpdateTask eut = null;
// Calculate enum domain
int n = 0;
int [] ecols = new int[mfpt._dout._nCols];
for( int i = 0; i < ecols.length; ++i )
if(mfpt._dout._vecs[i].shouldBeEnum())
ecols[n++] = i;
ecols = Arrays.copyOf(ecols, n);
if( ecols.length > 0 ) {
EnumFetchTask eft = new EnumFetchTask(mfpt._eKey, ecols).doAllNodes();
Categorical[] enums = eft._gEnums;
ValueString[][] ds = new ValueString[ecols.length][];
EnumMapping [] emaps = new EnumMapping[H2O.CLOUD.size()];
int k = 0;
for( int ei : ecols)
mfpt._dout._vecs[ei].setDomain(ValueString.toString(ds[k++] = enums[ei].computeColumnDomain()));
for(int nodeId = 0; nodeId < H2O.CLOUD.size(); ++nodeId) {
if(eft._lEnums[nodeId] == null)continue;
int[][] emap = new int[ecols.length][];
for (int i = 0; i < ecols.length; ++i) {
final Categorical e = eft._lEnums[nodeId][ecols[i]];
if(e == null) continue;
emap[i] = MemoryManager.malloc4(e.maxId() + 1);
Arrays.fill(emap[i], -1);
for (int j = 0; j < ds[i].length; ++j) {
ValueString vs = ds[i][j];
if (e.containsKey(vs)) {
assert e.getTokenId(vs) <= e.maxId() : "maxIdx = " + e.maxId() + ", got " + e.getTokenId(vs);
emap[i][e.getTokenId(vs)] = j;
}
}
}
emaps[nodeId] = new EnumMapping(emap);
}
eut = new EnumUpdateTask(ds, emaps, mfpt._chunk2Enum);
}
Frame fr = new Frame(job.dest(),setup._columnNames != null?setup._columnNames:genericColumnNames(mfpt._dout._nCols),mfpt._dout.closeVecs());
// SVMLight is sparse format, there may be missing chunks with all 0s, fill them in
new SVFTask(fr).doAllNodes();
// Update enums to the globally agreed numbering
if( eut != null ) {
Vec[] evecs = new Vec[ecols.length];
for( int i = 0; i < evecs.length; ++i ) evecs[i] = fr.vecs()[ecols[i]];
eut.doAll(evecs);
}
// unify any vecs with enums and strings to strings only
new UnifyStrVecTask().doAll(fr);
// Log any errors
if( mfpt._errors != null )
for( String err : mfpt._errors )
Log.warn(err);
logParseResults(job, fr);
// Release the frame for overwriting
fr.unlock(job._key);
// Remove CSV files from H2O memory
if( delete_on_done )
for( Key k : fkeys )
assert DKV.get(k) == null : "Input key "+k+" not deleted during parse";
}
/** Task to update enum (categorical) values to match the global numbering scheme.
* Performs update in place so that values originally numbered using
* node-local unordered numbering will be numbered using global numbering.
* @author tomasnykodym
*/
private static class EnumUpdateTask extends MRTask<EnumUpdateTask> {
private final ValueString [][] _gDomain;
private final EnumMapping [] _emaps;
private final int [] _chunk2Enum;
private EnumUpdateTask(ValueString [][] gDomain, EnumMapping [] emaps, int [] chunk2Enum) {
_gDomain = gDomain; _emaps = emaps; _chunk2Enum = chunk2Enum;
}
private int[][] emap(int nodeId) {return _emaps[nodeId].map;}
@Override public void map(Chunk [] chks){
int[][] emap = emap(_chunk2Enum[chks[0].cidx()]);
final int cidx = chks[0].cidx();
for(int i = 0; i < chks.length; ++i) {
Chunk chk = chks[i];
if(_gDomain[i] == null) // killed, replace with all NAs
DKV.put(chk.vec().chunkKey(chk.cidx()),new C0DChunk(Double.NaN,chk._len));
else if (!(chk instanceof CStrChunk)) {
for( int j = 0; j < chk._len; ++j){
if( chk.isNA0(j) )continue;
long l = chk.at80(j);
if (l < 0 || l >= emap[i].length)
chk.reportBrokenEnum(i, j, l, emap, _gDomain[i].length);
if(emap[i][(int)l] < 0)
throw new RuntimeException(H2O.SELF.toString() + ": missing enum at col:" + i + ", line: " + (chk.start() + j) + ", val = " + l + ", chunk=" + chk.getClass().getSimpleName() + ", map = " + Arrays.toString(emap[i]));
chk.set0(j, emap[i][(int)l]);
}
}
chk.close(cidx, _fs);
}
}
}
private static class EnumFetchTask extends MRTask<EnumFetchTask> {
private final Key _k;
private final int[] _ecols;
private Categorical[] _gEnums; // global enums per column
public Categorical[][] _lEnums; // local enums per node per column
private EnumFetchTask(Key k, int[] ecols){_k = k;_ecols = ecols;}
@Override public void setupLocal() {
_lEnums = new Categorical[H2O.CLOUD.size()][];
if( !MultiFileParseTask._enums.containsKey(_k) ) return;
_lEnums[H2O.SELF.index()] = _gEnums = MultiFileParseTask._enums.get(_k);
// Null out any empty Enum structs; no need to ship these around.
for( int i=0; i<_gEnums.length; i++ )
if( _gEnums[i].size()==0 ) _gEnums[i] = null;
// if we are the original node (i.e. there will be no sending over wire),
// we have to clone the enums not to share the same object (causes
// problems when computing column domain and renumbering maps).
// if( H2O.SELF.index() == _homeNode ) {
// fixme: looks like need to clone even if not on home node in h2o-dev
_gEnums = _gEnums.clone();
for(int i = 0; i < _gEnums.length; ++i)
if( _gEnums[i] != null ) _gEnums[i] = _gEnums[i].deepCopy();
MultiFileParseTask._enums.remove(_k);
}
@Override public void reduce(EnumFetchTask etk) {
if(_gEnums == null) {
_gEnums = etk._gEnums;
_lEnums = etk._lEnums;
} else if (etk._gEnums != null) {
for( int i : _ecols ) {
if( _gEnums[i] == null ) _gEnums[i] = etk._gEnums[i];
else if( etk._gEnums[i] != null ) _gEnums[i].merge(etk._gEnums[i]);
}
for( int i = 0; i < _lEnums.length; ++i )
if( _lEnums[i] == null ) _lEnums[i] = etk._lEnums[i];
else assert etk._lEnums[i] == null;
}
}
}
// Run once on all nodes; fill in missing zero chunks
private static class SVFTask extends MRTask<SVFTask> {
private final Frame _f;
private SVFTask( Frame f ) { _f = f; }
@Override public void map(Key key) {
Vec v0 = _f.anyVec();
for( int i = 0; i < v0.nChunks(); ++i ) {
if( !v0.chunkKey(i).home() ) continue;
// First find the nrows as the # rows of non-missing chunks; done on
// locally-homed chunks only - to keep the data distribution.
int nlines = 0;
for( Vec vec : _f.vecs() ) {
Value val = H2O.get(vec.chunkKey(i)); // Local-get only
if( val != null ) {
nlines = ((Chunk)val.get())._len;
break;
}
}
// Now fill in appropriate-sized zero chunks
for( Vec vec : _f.vecs() ) {
Key k = vec.chunkKey(i);
if( !k.home() ) continue; // Local keys only
Value val = H2O.get(k); // Local-get only
if( val == null ) // Missing? Fill in w/zero chunk
H2O.putIfMatch(k, new Value(k,new C0DChunk(0, nlines)), null);
}
}
}
}
// Run once on all nodes; switch enum chunks over to string chunks
private static class UnifyStrVecTask extends MRTask<UnifyStrVecTask> {
private UnifyStrVecTask() {}
@Override public void map(Chunk[] chunks) {
for (Chunk c : chunks) {
Vec v = c.vec();
if (v.isString() && c instanceof C4Chunk) {
Key k = v.chunkKey(c.cidx());
NewChunk nc = new NewChunk(v, c.cidx());
for (int j = 0; j < c._len; ++j)
if (c.isNA0(j)) nc.addNA();
else nc.addStr(new ValueString(v.domain()[(int) c.at80(j)]));
H2O.putIfMatch(k, new Value(k, nc.new_close()), H2O.get(k));
}
}
}
}
// We want to do a standard MRTask with a collection of file-keys (so the
// files are parsed in parallel across the cluster), but we want to throttle
// the parallelism on each node.
private static class MultiFileParseTask extends MRTask<MultiFileParseTask> {
private final ParseSetup _setup; // The expected column layout
private final VectorGroup _vg; // vector group of the target dataset
private final int _vecIdStart; // Start of available vector keys
// Shared against all concurrent unrelated parses, a map to the node-local
// Enum lists for each concurrent parse.
private static NonBlockingHashMap<Key, Categorical[]> _enums = new NonBlockingHashMap<>();
// The Key used to sort out *this* parse's Categorical[]
private final Key _eKey = Key.make();
// Eagerly delete Big Data
private final boolean _delete_on_done;
// Mapping from Chunk# to cluster-node-number holding the enum mapping.
// It is either self for all the non-parallel parses, or the Chunk-home for parallel parses.
private int[] _chunk2Enum;
// Job Key, to unlock & remove raw parsed data; to report progress
private final Key _job_key;
// A mapping of Key+ByteVec to rolling total Chunk counts.
private final int[] _fileChunkOffsets;
// OUTPUT fields:
FVecDataOut _dout;
String[] _errors;
MultiFileParseTask(VectorGroup vg, ParseSetup setup, Key job_key, Key[] fkeys, boolean delete_on_done ) {
_vg = vg; _setup = setup;
_vecIdStart = _vg.reserveKeys(_setup._pType == ParserType.SVMLight ? 100000000 : setup._ncols);
_delete_on_done = delete_on_done;
_job_key = job_key;
// A mapping of Key+ByteVec to rolling total Chunk counts.
_fileChunkOffsets = new int[fkeys.length];
int len = 0;
for( int i = 0; i < fkeys.length; ++i ) {
_fileChunkOffsets[i] = len;
len += getByteVec(fkeys[i]).nChunks();
}
// Mapping from Chunk# to cluster-node-number
_chunk2Enum = MemoryManager.malloc4(len);
Arrays.fill(_chunk2Enum, -1);
}
// Fetch out the node-local Categorical[] using _eKey and _enums hashtable
private static Categorical[] enums(Key eKey, int ncols) {
Categorical[] enums = _enums.get(eKey);
if( enums != null ) return enums;
enums = new Categorical[ncols];
for( int i = 0; i < enums.length; ++i ) enums[i] = new Categorical();
_enums.putIfAbsent(eKey, enums);
return _enums.get(eKey); // Re-get incase lost insertion race
}
// Flag all chunk enums as being on local (self)
private void chunksAreLocal( Vec vec, int chunkStartIdx, Key key ) {
for(int i = 0; i < vec.nChunks(); ++i)
_chunk2Enum[chunkStartIdx + i] = H2O.SELF.index();
// For Big Data, must delete data as eagerly as possible.
Iced ice = DKV.get(key).get();
if( ice==vec ) {
if( _delete_on_done ) vec.remove();
} else {
Frame fr = (Frame)ice;
if( _delete_on_done ) fr.delete(_job_key,new Futures()).blockForPending();
else if( fr._key != null ) fr.unlock(_job_key);
}
}
// Called once per file
@Override public void map( Key key ) {
// Get parser setup info for this chunk
ByteVec vec = getByteVec(key);
final int chunkStartIdx = _fileChunkOffsets[_lo];
byte[] zips = vec.getFirstBytes();
ZipUtil.Compression cpr = ZipUtil.guessCompressionMethod(zips);
byte[] bits = ZipUtil.unzipBytes(zips,cpr);
ParseSetup localSetup = _setup.guessSetup(bits,0/*guess header in each file*/);
if( !localSetup._isValid ) {
_errors = localSetup._errors;
chunksAreLocal(vec,chunkStartIdx,key);
return;
}
// Parse the file
try {
switch( cpr ) {
case NONE:
if( localSetup._pType._parallelParseSupported ) {
DParse dp = new DParse(_vg, localSetup, _vecIdStart, chunkStartIdx,this,key);
addToPendingCount(1);
dp.setCompleter(this);
dp.asyncExec(vec);
for( int i = 0; i < vec.nChunks(); ++i )
_chunk2Enum[chunkStartIdx + i] = vec.chunkKey(i).home_node().index();
} else {
InputStream bvs = vec.openStream(_job_key);
_dout = streamParse(bvs, localSetup, _vecIdStart, chunkStartIdx, bvs);
chunksAreLocal(vec,chunkStartIdx,key);
}
break;
case ZIP: {
// Zipped file; no parallel decompression;
InputStream bvs = vec.openStream(_job_key);
ZipInputStream zis = new ZipInputStream(bvs);
ZipEntry ze = zis.getNextEntry(); // Get the *FIRST* entry
// There is at least one entry in zip file and it is not a directory.
if( ze != null && !ze.isDirectory() )
_dout = streamParse(zis,localSetup, _vecIdStart, chunkStartIdx, bvs);
else zis.close(); // Confused: which zipped file to decompress
chunksAreLocal(vec,chunkStartIdx,key);
break;
}
case GZIP: {
InputStream bvs = vec.openStream(_job_key);
// Zipped file; no parallel decompression;
_dout = streamParse(new GZIPInputStream(bvs),localSetup,_vecIdStart, chunkStartIdx,bvs);
// set this node as the one which processed all the chunks
chunksAreLocal(vec,chunkStartIdx,key);
break;
}
}
} catch( IOException ioe ) {
throw new RuntimeException(ioe);
}
}
// Reduce: combine errors from across files.
// Roll-up other meta data
@Override public void reduce( MultiFileParseTask mfpt ) {
assert this != mfpt;
// Collect & combine columns across files
if( _dout == null ) _dout = mfpt._dout;
else _dout.reduce(mfpt._dout);
if( _chunk2Enum == null ) _chunk2Enum = mfpt._chunk2Enum;
else if(_chunk2Enum != mfpt._chunk2Enum) { // we're sharing global array!
for( int i = 0; i < _chunk2Enum.length; ++i ) {
if( _chunk2Enum[i] == -1 ) _chunk2Enum[i] = mfpt._chunk2Enum[i];
else assert mfpt._chunk2Enum[i] == -1 : Arrays.toString(_chunk2Enum) + " :: " + Arrays.toString(mfpt._chunk2Enum);
}
}
_errors = ArrayUtils.append(_errors,mfpt._errors);
}
// Zipped file; no parallel decompression; decompress into local chunks,
// parse local chunks; distribute chunks later.
private FVecDataOut streamParse( final InputStream is, final ParseSetup localSetup, int vecIdStart, int chunkStartIdx, InputStream bvs) throws IOException {
// All output into a fresh pile of NewChunks, one per column
FVecDataOut dout = new FVecDataOut(_vg, chunkStartIdx, localSetup._ncols, vecIdStart, enums(_eKey,_setup._ncols), null);
Parser p = localSetup.parser();
// assume 2x inflation rate
if( localSetup._pType._parallelParseSupported ) p.streamParseZip(is, dout, bvs);
else p.streamParse (is, dout);
// Parse all internal "chunks", until we drain the zip-stream dry. Not
// real chunks, just flipping between 32K buffers. Fills up the single
// very large NewChunk.
dout.close(_fs);
return dout;
}
private static class DParse extends MRTask<DParse> {
private final ParseSetup _setup;
private final int _vecIdStart;
private final int _startChunkIdx; // for multifile parse, offset of the first chunk in the final dataset
private final VectorGroup _vg;
private FVecDataOut _dout;
private final Key _eKey; // Parse-local-Enums key
private final Key _job_key;
private transient final MultiFileParseTask _outerMFPT;
private transient final Key _srckey; // Source/text file to delete on done
private transient NonBlockingSetInt _visited;
DParse(VectorGroup vg, ParseSetup setup, int vecIdstart, int startChunkIdx, MultiFileParseTask mfpt, Key srckey) {
super(mfpt);
_vg = vg;
_setup = setup;
_vecIdStart = vecIdstart;
_startChunkIdx = startChunkIdx;
_outerMFPT = mfpt;
_eKey = mfpt._eKey;
_job_key = mfpt._job_key;
_srckey = srckey;
}
@Override public void setupLocal(){
super.setupLocal();
_visited = new NonBlockingSetInt();
}
@Override public void map( Chunk in ) {
Categorical [] enums = enums(_eKey,_setup._ncols);
// Break out the input & output vectors before the parse loop
FVecDataIn din = new FVecDataIn(in);
FVecDataOut dout;
Parser p;
switch(_setup._pType) {
case CSV:
p = new CsvParser(_setup);
dout = new FVecDataOut(_vg,_startChunkIdx + in.cidx(),_setup._ncols,_vecIdStart,enums, null);
break;
case ARFF:
p = new CsvParser(_setup);
dout = new FVecDataOut(_vg,_startChunkIdx + in.cidx(),_setup._ncols,_vecIdStart,enums, _setup._ctypes); //TODO: use _setup._domains instead of enums
break;
case SVMLight:
p = new SVMLightParser(_setup);
dout = new SVMLightFVecDataOut(_vg, _startChunkIdx + in.cidx(), enums);
break;
default:
throw H2O.unimpl();
}
p.parallelParse(in.cidx(),din,dout);
(_dout = dout).close(_fs);
Job.update(in._len,_job_key); // Record bytes parsed
// remove parsed data right away (each chunk is used by 2)
freeMem(in,0);
freeMem(in,1);
}
private void freeMem(Chunk in, int off) {
final int cidx = in.cidx()+off;
if( _visited.add(cidx) ) return; // First visit; expect a 2nd so no freeing yet
Value v = H2O.get(in.vec().chunkKey(cidx));
if( v == null || !v.isPersisted() ) return; // Not found, or not on disk somewhere
v.freePOJO(); // Eagerly toss from memory
v.freeMem();
}
@Override public void reduce(DParse dp) { _dout.reduce(dp._dout); }
@Override public void postGlobal() {
super.postGlobal();
_outerMFPT._dout = _dout;
_dout = null; // Reclaim GC eagerly
// For Big Data, must delete data as eagerly as possible.
Value val = DKV.get(_srckey);
if( val == null ) return;
Iced ice = val.get();
if( ice instanceof ByteVec ) {
if( _outerMFPT._delete_on_done ) ((ByteVec)ice).remove();
} else {
Frame fr = (Frame)ice;
if( _outerMFPT._delete_on_done ) fr.delete(_outerMFPT._job_key,new Futures()).blockForPending();
else if( fr._key != null ) fr.unlock(_outerMFPT._job_key);
}
}
}
// Find & remove all partially built output chunks & vecs
private Futures onExceptionCleanup(Futures fs) {
int nchunks = _chunk2Enum.length;
int ncols = _setup._ncols;
for( int i = 0; i < ncols; ++i ) {
Key vkey = _vg.vecKey(_vecIdStart + i);
Keyed.remove(vkey,fs);
for( int c = 0; c < nchunks; ++c )
DKV.remove(Vec.chunkKey(vkey,c),fs);
}
cancel(true);
return fs;
}
}
/** Parsed data output specialized for fluid vecs.
* @author tomasnykodym
*/
static class FVecDataOut extends Iced implements Parser.StreamDataOut {
protected transient NewChunk [] _nvs;
protected AppendableVec []_vecs;
protected final Categorical [] _enums;
protected transient byte [] _ctypes;
long _nLines;
int _nCols;
int _col = -1;
final int _cidx;
final int _vecIdStart;
boolean _closedVecs = false;
private final VectorGroup _vg;
static final byte UCOL = 0; // unknown col type
static final byte NCOL = 1; // numeric col type
static final byte ECOL = 2; // enum col type
static final byte TCOL = 3; // time col typ
static final byte ICOL = 4; // UUID col typ
static final byte SCOL = 5; // String col typ
private FVecDataOut(VectorGroup vg, int cidx, int ncols, int vecIdStart, Categorical[] enums, byte[] ctypes){
_ctypes = ctypes == null ? MemoryManager.malloc1(ncols) : ctypes;
_vecs = new AppendableVec[ncols];
_nvs = new NewChunk[ncols];
_enums = enums;
_nCols = ncols;
_cidx = cidx;
_vg = vg;
_vecIdStart = vecIdStart;
for(int i = 0; i < ncols; ++i)
_nvs[i] = (_vecs[i] = new AppendableVec(vg.vecKey(vecIdStart + i))).chunkForChunkIdx(_cidx);
}
@Override public FVecDataOut reduce(Parser.StreamDataOut sdout){
FVecDataOut dout = (FVecDataOut)sdout;
if( dout == null ) return this;
_nCols = Math.max(_nCols,dout._nCols);
if(dout._vecs.length > _vecs.length){
AppendableVec [] v = _vecs;
_vecs = dout._vecs;
dout._vecs = v;
}
for(int i = 0; i < dout._vecs.length; ++i) {
// unify string and enum chunks
if (_vecs[i].isString() && !dout._vecs[i].isString())
dout.enumCol2StrCol(i);
else if (!_vecs[i].isString() && dout._vecs[i].isString()) {
enumCol2StrCol(i);
_ctypes[i] = SCOL;
}
_vecs[i].reduce(dout._vecs[i]);
}
return this;
}
@Override public FVecDataOut close(){
Futures fs = new Futures();
close(fs);
fs.blockForPending();
return this;
}
@Override public FVecDataOut close(Futures fs){
if( _nvs == null ) return this; // Might call close twice
for(NewChunk nv:_nvs) nv.close(_cidx, fs);
_nvs = null; // Free for GC
return this;
}
@Override public FVecDataOut nextChunk(){
return new FVecDataOut(_vg, _cidx+1, _nCols, _vecIdStart, _enums, null);
}
private Vec [] closeVecs(){
Futures fs = new Futures();
_closedVecs = true;
Vec [] res = new Vec[_vecs.length];
for(int i = 0; i < _vecs[0]._espc.length; ++i){
int j = 0;
while(j < _vecs.length && _vecs[j]._espc[i] == 0)++j;
if(j == _vecs.length)break;
final long clines = _vecs[j]._espc[i];
for(AppendableVec v:_vecs) {
if(v._espc[i] == 0)v._espc[i] = clines;
else assert v._espc[i] == clines:"incompatible number of lines: " + v._espc[i] + " != " + clines;
}
}
for(int i = 0; i < _vecs.length; ++i)
res[i] = _vecs[i].close(fs);
_vecs = null; // Free for GC
fs.blockForPending();
return res;
}
@Override public void newLine() {
if(_col >= 0){
++_nLines;
for(int i = _col+1; i < _nCols; ++i)
addInvalidCol(i);
}
_col = -1;
}
@Override public void addNumCol(int colIdx, long number, int exp) {
if( colIdx < _nCols ) {
_nvs[_col = colIdx].addNum(number, exp);
if(_ctypes[colIdx] == UCOL ) _ctypes[colIdx] = NCOL;
}
}
@Override public final void addInvalidCol(int colIdx) {
if(colIdx < _nCols) _nvs[_col = colIdx].addNA();
}
@Override public final boolean isString(int colIdx) { return (colIdx < _nCols) && (_ctypes[colIdx]==ECOL || _ctypes[colIdx]==SCOL);}
@Override public final void addStrCol(int colIdx, ValueString str) {
if(colIdx < _nvs.length){
if(_ctypes[colIdx] == NCOL){ // support enforced types
addInvalidCol(colIdx);
return;
}
if(_ctypes[colIdx] == UCOL && ParseTime.attemptTimeParse(str) > 0)
_ctypes[colIdx] = TCOL;
if( _ctypes[colIdx] == UCOL ) { // Attempt UUID parse
int old = str.get_off();
ParseTime.attemptUUIDParse0(str);
ParseTime.attemptUUIDParse1(str);
if( str.get_off() != -1 ) _ctypes[colIdx] = ICOL;
str.setOff(old);
}
if( _ctypes[colIdx] == TCOL ) {
long l = ParseTime.attemptTimeParse(str);
if( l == Long.MIN_VALUE ) addInvalidCol(colIdx);
else {
int time_pat = ParseTime.decodePat(l); // Get time pattern
l = ParseTime.decodeTime(l); // Get time
addNumCol(colIdx, l, 0); // Record time in msec
_nvs[_col]._timCnt[time_pat]++; // Count histo of time parse patterns
}
} else if( _ctypes[colIdx] == ICOL ) { // UUID column? Only allow UUID parses
long lo = ParseTime.attemptUUIDParse0(str);
long hi = ParseTime.attemptUUIDParse1(str);
if( str.get_off() == -1 ) { lo = C16Chunk._LO_NA; hi = C16Chunk._HI_NA; }
if( colIdx < _nCols ) _nvs[_col = colIdx].addUUID(lo, hi);
} else if( _ctypes[colIdx] == SCOL ) {
_nvs[_col = colIdx].addStr(str);
} else {
if(!_enums[colIdx].isMapFull()) {
int id = _enums[_col = colIdx].addKey(str);
if (_ctypes[colIdx] == UCOL && id > 1) _ctypes[colIdx] = ECOL;
_nvs[colIdx].addEnum(id);
} else { // maxed out enum map, convert col to string chunk
_ctypes[_col = colIdx] = SCOL;
enumCol2StrCol(colIdx);
_nvs[colIdx].addStr(str);
}
}
}
}
private void enumCol2StrCol(int colIdx) {
//build local value2key map for enums
Categorical enums = _enums[colIdx].deepCopy();
ValueString emap[] = new ValueString[enums.maxId()+1];
ValueString keys[] = enums._map.keySet().toArray(new ValueString[enums.size()]);
for (ValueString str:keys)
// adjust for enum ids using 1-based indexing
emap[enums._map.get(str)-1] = str;
//swap in string NewChunk in place of enum NewChunk
_nvs[colIdx] = _nvs[colIdx].convertEnum2Str(emap);
//Log.info("enumCol2StrCol");
}
/** Adds double value to the column. */
@Override public void addNumCol(int colIdx, double value) {
if (Double.isNaN(value)) {
addInvalidCol(colIdx);
} else {
double d= value;
int exp = 0;
long number = (long)d;
while (number != d) {
d = d * 10;
--exp;
number = (long)d;
}
addNumCol(colIdx, number, exp);
}
}
@Override public void setColumnNames(String [] names){}
@Override public final void rollbackLine() {}
@Override public void invalidLine(String err) { newLine(); }
}
private static class SVMLightFVecDataOut extends FVecDataOut {
protected final VectorGroup _vg;
private SVMLightFVecDataOut(VectorGroup vg, int cidx, Categorical [] enums){
super(vg,cidx,0,vg.reserveKeys(10000000),enums, null);
_nvs = new NewChunk[0];
_vg = vg;
_col = 0;
}
private void addColumns(int ncols){
if(ncols > _nCols){
_nvs = Arrays.copyOf(_nvs , ncols);
_vecs = Arrays.copyOf(_vecs , ncols);
_ctypes= Arrays.copyOf(_ctypes, ncols);
for(int i = _nCols; i < ncols; ++i){
_vecs[i] = new AppendableVec(_vg.vecKey(_vecIdStart + i + 1));
_nvs[i] = new NewChunk(_vecs[i], _cidx);
for(int j = 0; j < _nLines; ++j)
_nvs[i].addNum(0, 0);
}
_nCols = ncols;
}
}
@Override public void addNumCol(int colIdx, long number, int exp) {
assert colIdx >= _col;
addColumns(colIdx+1);
for(int i = _col; i < colIdx; ++i)
super.addNumCol(i, 0, 0);
super.addNumCol(colIdx, number, exp);
_col = colIdx+1;
}
@Override public void newLine() {
if(_col < _nCols)addNumCol(_nCols-1, 0,0);
super.newLine();
_col = 0;
}
}
/** Parser data in taking data from fluid vec chunk.
* @author tomasnykodym
*/
private static class FVecDataIn implements Parser.DataIn {
final Vec _vec;
Chunk _chk;
int _idx;
final long _firstLine;
public FVecDataIn(Chunk chk){
_chk = chk;
_idx = _chk.cidx();
_firstLine = chk.start();
_vec = chk.vec();
}
@Override public byte[] getChunkData(int cidx) {
if(cidx != _idx)
_chk = cidx < _vec.nChunks()?_vec.chunkForChunkIdx(_idx = cidx):null;
return (_chk == null)?null:_chk.getBytes();
}
@Override public int getChunkDataStart(int cidx) { return -1; }
@Override public void setChunkDataStart(int cidx, int offset) { }
}
// Log information about the dataset we just parsed.
private static void logParseResults(ParseDataset2 job, Frame fr) {
try {
long numRows = fr.anyVec().length();
Log.info("Parse result for " + job.dest() + " (" + Long.toString(numRows) + " rows):");
Futures fs = new Futures();
Vec[] vecArr = fr.vecs();
for(Vec v:vecArr) v.startRollupStats(fs);
fs.blockForPending();
int namelen = 0;
for (String s : fr.names()) namelen = Math.max(namelen, s.length());
String format = " %"+namelen+"s %11s %12s %12s %11s %8s %6s";
Log.info(String.format(format, "ColV2", "type", "min", "max", "NAs", "constant", "numLevels"));
// get all rollups started in parallell, otherwise this takes ages!
for( int i = 0; i < vecArr.length; i++ ) {
Vec v = vecArr[i];
boolean isCategorical = v.isEnum();
boolean isConstant = v.isConst();
boolean isString = v.isString();
String CStr = String.format("%"+namelen+"s:", fr.names()[i]);
String typeStr = String.format("%s", (v.isUUID() ? "UUID" : (isCategorical ? "categorical" : (isString ? "string" : "numeric"))));
String minStr = isString ? "" : String.format("%g", v.min());
String maxStr = isString ? "" : String.format("%g", v.max());
long numNAs = v.naCnt();
String naStr = (numNAs > 0) ? String.format("%d", numNAs) : "";
String isConstantStr = isConstant ? "constant" : "";
String numLevelsStr = isCategorical ? String.format("%d", v.domain().length) : (isString ? String.format("%d", v.nzCnt()) : "");
boolean printLogSeparatorToStdout = false;
boolean printColumnToStdout;
{
// Print information to stdout for this many leading columns.
final int MAX_HEAD_TO_PRINT_ON_STDOUT = 10;
// Print information to stdout for this many trailing columns.
final int MAX_TAIL_TO_PRINT_ON_STDOUT = 10;
if (vecArr.length <= (MAX_HEAD_TO_PRINT_ON_STDOUT + MAX_TAIL_TO_PRINT_ON_STDOUT)) {
// For small numbers of columns, print them all.
printColumnToStdout = true;
} else if (i < MAX_HEAD_TO_PRINT_ON_STDOUT) {
printColumnToStdout = true;
} else if (i == MAX_HEAD_TO_PRINT_ON_STDOUT) {
printLogSeparatorToStdout = true;
printColumnToStdout = false;
} else if ((i + MAX_TAIL_TO_PRINT_ON_STDOUT) < vecArr.length) {
printColumnToStdout = false;
} else {
printColumnToStdout = true;
}
}
if (printLogSeparatorToStdout) {
System.out.println("Additional column information only sent to log file...");
}
String s = String.format(format, CStr, typeStr, minStr, maxStr, naStr, isConstantStr, numLevelsStr);
if( printColumnToStdout ) Log.info (s);
else Log.info_no_stdout(s);
}
Log.info(FrameUtils.chunkSummary(fr).toString());
}
catch(Exception ignore) {} // Don't fail due to logging issues. Just ignore them.
}
}
|
package com.xpn.xwiki.api;
import com.xpn.xwiki.XWiki;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.doc.XWikiAttachment;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.doc.XWikiDocumentArchive;
import com.xpn.xwiki.doc.XWikiLock;
import com.xpn.xwiki.objects.BaseObject;
import com.xpn.xwiki.objects.BaseProperty;
import com.xpn.xwiki.objects.classes.BaseClass;
import com.xpn.xwiki.plugin.fileupload.FileUploadPlugin;
import com.xpn.xwiki.stats.impl.DocumentStats;
import com.xpn.xwiki.util.TOCGenerator;
import com.xpn.xwiki.util.Util;
import org.apache.commons.fileupload.DefaultFileItem;
import org.apache.commons.io.CopyUtils;
import org.suigeneris.jrcs.diff.DifferentiationFailedException;
import org.suigeneris.jrcs.rcs.Version;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import java.io.InputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class Document extends Api {
protected XWikiDocument olddoc;
protected XWikiDocument doc;
protected Object currentObj;
public Document(XWikiDocument doc, XWikiContext context) {
super(context);
this.olddoc = doc;
this.doc = doc;
}
/**
* this function is accessible only if you have the programming rights
* give access to the priviledged API of the Document
* @return
*/
public XWikiDocument getDocument() {
if (checkProgrammingRights())
return doc;
else
return null;
}
protected XWikiDocument getDoc() {
if (doc == olddoc)
doc = (XWikiDocument) doc.clone();
return doc;
}
/**
* return the ID of the document. this ID is uniq accross the wiki.
*
* @return the id of the document
*/
public long getId() {
return doc.getId();
}
/**
* return the name of a document.
*
* for exemple if the fullName of a document is "MySpace.Mydoc", the name is MyDoc
*
* @return the name of the document
*/
public String getName() {
return doc.getName();
}
/**
* return the name of the space of the document
*
* for exemple if the fullName of a document is "MySpace.Mydoc", the name is MySpace
*
* @return the name of the space of the document
*/
public String getSpace() {
return doc.getSpace();
}
/**
* return the name of the space of the document
*
* for exemple if the fullName of a document is "MySpace.Mydoc", the name is MySpace
*
* @deprecated use {@link #getSpace()} instead of this function
* @return
*/
public String getWeb() {
return doc.getWeb();
}
/**
* return the fullName of a doucment
*
* if a document has for name "MyDoc" and space "MySpace", the fullname is "MySpace.MyDoc"
* In a wiki, all the documents have a different fullName.
*
* @return
*/
public String getFullName() {
return doc.getFullName();
}
public Version getRCSVersion() {
return doc.getRCSVersion();
}
/**
* return a String with the version of the document.
* @return
*/
public String getVersion() {
return doc.getVersion();
}
/**
* return the title of a document
* @return
*/
public String getTitle() {
return doc.getTitle();
}
/**
* return the title of the document. If there is no title, return the first title in the document
* @return
*/
public String getDisplayTitle() {
return doc.getDisplayTitle();
}
public String getFormat() {
return doc.getFormat();
}
/**
* return the name of the last author of the document
* @return
*/
public String getAuthor() {
return doc.getAuthor();
}
/**
* return the name of the last author of the content of the document
* @return
*/
public String getContentAuthor() {
return doc.getContentAuthor();
}
/**
* return the modification date
* @return
*/
public Date getDate() {
return doc.getDate();
}
/**
* return the date of the last modification of the content
* @return
*/
public Date getContentUpdateDate() {
return doc.getContentUpdateDate();
}
/**
* return the date of the creation of the document
* @return
*/
public Date getCreationDate() {
return doc.getCreationDate();
}
/**
* return the name of the parent document
* @return
*/
public String getParent() {
return doc.getParent();
}
/**
* return the name of the creator of the document
* @return
*/
public String getCreator() {
return doc.getCreator();
}
/**
* return the content of the document
* @return
*/
public String getContent() {
return doc.getContent();
}
/**
* return the language of the document if it's a traduction, otherwise, it return default
* @return
*/
public String getLanguage() {
return doc.getLanguage();
}
public String getTemplate() {
return doc.getTemplate();
}
/**
* return the real language of the document
* @return
* @throws XWikiException
*/
public String getRealLanguage() throws XWikiException {
return doc.getRealLanguage(context);
}
/**
* return the language of the default document
* @return
*/
public String getDefaultLanguage() {
return doc.getDefaultLanguage();
}
public String getDefaultTemplate() {
return doc.getDefaultTemplate();
}
/**
* return the list of possible traduction for this document
* @return
* @throws XWikiException
*/
public List getTranslationList() throws XWikiException {
return doc.getTranslationList(context);
}
/**
* return the tranlated document's content
* if the wiki is multilingual, the language is first checked in the URL, the cookie, the user profile and finally the wiki configuration
* if not, the language is the one on the wiki configuration
* @return
* @throws XWikiException
*/
public String getTranslatedContent() throws XWikiException {
return doc.getTranslatedContent(context);
}
/**
* return the translated content in the given language
* @param language
* @return
* @throws XWikiException
*/
public String getTranslatedContent(String language) throws XWikiException {
return doc.getTranslatedContent(language, context);
}
/**
* return the translated document in the given document
* @param language
* @return
* @throws XWikiException
*/
public Document getTranslatedDocument(String language) throws XWikiException {
return doc.getTranslatedDocument(language, context).newDocument(context);
}
/**
* return the tranlated Document
* if the wiki is multilingual, the language is first checked in the URL, the cookie, the user profile and finally the wiki configuration
* if not, the language is the one on the wiki configuration
* @return
* @throws XWikiException
*/
public Document getTranslatedDocument() throws XWikiException {
return doc.getTranslatedDocument(context).newDocument(context);
}
/**
* return the content of the document rendererd
* @return
* @throws XWikiException
*/
public String getRenderedContent() throws XWikiException {
return doc.getRenderedContent(context);
}
/**
* return the given text rendered in the context of this document
* @param text
* @return
* @throws XWikiException
*/
public String getRenderedContent(String text) throws XWikiException {
return doc.getRenderedContent(text, context);
}
/**
* return a escaped version of the content of this document
* @return
* @throws XWikiException
*/
public String getEscapedContent() throws XWikiException {
return doc.getEscapedContent(context);
}
/**
* return the archive of the document in a string format
* @return
* @throws XWikiException
*/
public String getArchive() throws XWikiException {
return doc.getDocumentArchive(context).getArchive();
}
/**
* this function is accessible only if you have the programming rights
* return the archive of the document
* @return
* @throws XWikiException
*/
public XWikiDocumentArchive getDocumentArchive() throws XWikiException {
if (checkProgrammingRights())
return doc.getDocumentArchive(context);
return null;
}
/**
* return true if the document is a new one (Has never been saved)
* @return
*/
public boolean isNew() {
return doc.isNew();
}
/**
* return the URL of download for the the given attachment name
* @param filename the name of the attachment
* @return A String with the URL
*/
public String getAttachmentURL(String filename) {
return doc.getAttachmentURL(filename, "download", context);
}
/**
* return the URL of the given action for the the given attachment name
* @param filename
* @param action
* @return A string with the URL
*/
public String getAttachmentURL(String filename, String action) {
return doc.getAttachmentURL(filename, action, context);
}
/**
* return the URL of the given action for the the given attachment name with "queryString" parameters
* @param filename
* @param action
* @param queryString parameters added to the URL
* @return
*/
public String getAttachmentURL(String filename, String action, String queryString) {
return doc.getAttachmentURL(filename, action, queryString, context);
}
/**
* return the URL for accessing to the archive of the attachment "filename" at the version "version"
* @param filename
* @param version
* @return
*/
public String getAttachmentRevisionURL(String filename, String version) {
return doc.getAttachmentRevisionURL(filename, version, context);
}
/**
* return the URL for accessing to the archive of the attachment "filename" at the version "version" and with the given queryString parameters
* @param filename
* @param version
* @param querystring
* @return
*/
public String getAttachmentRevisionURL(String filename, String version, String querystring) {
return doc.getAttachmentRevisionURL(filename, version, querystring, context);
}
/**
* return the URL of this document in view mode
* @return
*/
public String getURL() {
return doc.getURL("view", context);
}
/**
* return thr URL of this document with the given action
* @param action
* @return
*/
public String getURL(String action) {
return doc.getURL(action, context);
}
/**
* return thr URL of this document with the given action and queryString as parameters
* @param action
* @param querystring
* @return
*/
public String getURL(String action, String querystring) {
return doc.getURL(action, querystring, context);
}
/**
* return the full URL of the document
* @return
*/
public String getExternalURL() {
return doc.getExternalURL("view", context);
}
/**
* return the full URL of the document for the given action
* @param action
* @return
*/
public String getExternalURL(String action) {
return doc.getExternalURL(action, context);
}
public String getExternalURL(String action, String querystring) {
return doc.getExternalURL(action, querystring, context);
}
public String getParentURL() throws XWikiException {
return doc.getParentURL(context);
}
public Class getxWikiClass() {
BaseClass bclass = getDoc().getxWikiClass();
if (bclass == null)
return null;
else
return new Class(bclass, context);
}
public Class[] getxWikiClasses() {
List list = getDoc().getxWikiClasses(context);
if (list == null)
return null;
Class[] result = new Class[list.size()];
for (int i = 0; i < list.size(); i++)
result[i] = new Class((BaseClass) list.get(i), context);
return result;
}
public int createNewObject(String classname) throws XWikiException {
return getDoc().createNewObject(classname, context);
}
public Object newObject(String classname) throws XWikiException {
int nb = createNewObject(classname);
return getObject(classname, nb);
}
public boolean isFromCache() {
return doc.isFromCache();
}
public int getObjectNumbers(String classname) {
return getDoc().getObjectNumbers(classname);
}
public Map getxWikiObjects() {
Map map = getDoc().getxWikiObjects();
Map resultmap = new HashMap();
for (Iterator it = map.keySet().iterator(); it.hasNext();) {
String name = (String) it.next();
Vector objects = (Vector) map.get(name);
if (objects != null)
resultmap.put(name, getObjects(objects));
}
return resultmap;
}
protected Vector getObjects(Vector objects) {
Vector result = new Vector();
if (objects == null)
return result;
for (int i = 0; i < objects.size(); i++) {
BaseObject bobj = (BaseObject) objects.get(i);
if (bobj != null) {
result.add(newObjectApi(bobj, context));
}
}
return result;
}
public Vector getObjects(String classname) {
Vector objects = getDoc().getObjects(classname);
return getObjects(objects);
}
public Object getFirstObject(String fieldname) {
try {
BaseObject obj = getDoc().getFirstObject(fieldname, context);
if (obj == null)
return null;
else
return newObjectApi(obj, context);
} catch (Exception e) {
return null;
}
}
public Object getObject(String classname, String key, String value, boolean failover) {
try {
BaseObject obj = getDoc().getObject(classname, key, value, failover);
if (obj == null)
return null;
else
return newObjectApi(obj, context);
} catch (Exception e) {
return null;
}
}
public Object getObject(String classname, String key, String value) {
try {
BaseObject obj = getDoc().getObject(classname, key, value);
if (obj == null)
return null;
else
return newObjectApi(obj, context);
} catch (Exception e) {
return null;
}
}
public Object getObject(String classname) {
return getObject(classname, false);
}
public Object getObject(String classname, boolean create) {
try {
BaseObject obj = getDoc().getObject(classname);
if ((obj == null) && create) {
return newObject(classname);
}
if (obj == null)
return null;
else
return newObjectApi(obj, context);
} catch (Exception e) {
return null;
}
}
public Object getObject(String classname, int nb) {
try {
BaseObject obj = getDoc().getObject(classname, nb);
if (obj == null)
return null;
else
return newObjectApi(obj, context);
} catch (Exception e) {
return null;
}
}
private Object newObjectApi(BaseObject obj, XWikiContext context) {
return obj.newObjectApi(obj, context);
}
public String getXMLContent() throws XWikiException {
String xml = doc.getXMLContent(context);
return context.getUtil().substitute("s/<password>.*?<\\/password>/<password>********<\\/password>/goi", xml);
}
public String toXML() throws XWikiException {
if (checkProgrammingRights())
return doc.toXML(context);
else
return "";
}
public org.dom4j.Document toXMLDocument() throws XWikiException {
if (checkProgrammingRights())
return doc.toXMLDocument(context);
else return null;
}
public Version[] getRevisions() throws XWikiException {
return doc.getRevisions(context);
}
public String[] getRecentRevisions() throws XWikiException {
return doc.getRecentRevisions(5, context);
}
public String[] getRecentRevisions(int nb) throws XWikiException {
return doc.getRecentRevisions(nb, context);
}
public List getAttachmentList() {
List list = getDoc().getAttachmentList();
List list2 = new ArrayList();
for (int i = 0; i < list.size(); i++) {
list2.add(new Attachment(this, (XWikiAttachment) list.get(i), context));
}
return list2;
}
public Vector getComments() {
return getComments(true);
}
public Vector getComments(boolean asc) {
if (asc)
return getObjects("XWiki.XWikiComments");
else {
Vector list = getObjects("XWiki.XWikiComments");
if (list == null)
return list;
Vector newlist = new Vector();
for (int i = list.size() - 1; i >= 0; i
newlist.add(list.get(i));
}
return newlist;
}
}
public void use(Object object) {
currentObj = object;
}
public void use(String className) {
currentObj = getObject(className);
}
public void use(String className, int nb) {
currentObj = getObject(className, nb);
}
public String getActiveClass() {
if (currentObj==null)
return null;
else
return currentObj.getName();
}
public String displayPrettyName(String fieldname) {
if (currentObj == null)
return doc.displayPrettyName(fieldname, context);
else
return doc.displayPrettyName(fieldname, currentObj.getBaseObject(), context);
}
public String displayPrettyName(String fieldname, Object obj) {
if (obj == null)
return "";
return doc.displayPrettyName(fieldname, obj.getBaseObject(), context);
}
public String displayTooltip(String fieldname) {
if (currentObj == null)
return doc.displayTooltip(fieldname, context);
else
return doc.displayTooltip(fieldname, currentObj.getBaseObject(), context);
}
public String displayTooltip(String fieldname, Object obj) {
if (obj == null)
return "";
return doc.displayTooltip(fieldname, obj.getBaseObject(), context);
}
public String display(String fieldname) {
if (currentObj == null)
return doc.display(fieldname, context);
else
return doc.display(fieldname, currentObj.getBaseObject(), context);
}
public String display(String fieldname, String mode) {
if (currentObj == null)
return doc.display(fieldname, mode, context);
else
return doc.display(fieldname, mode, currentObj.getBaseObject(), context);
}
public String display(String fieldname, String mode, String prefix) {
if (currentObj == null)
return doc.display(fieldname, mode, prefix, context);
else
return doc.display(fieldname, mode, prefix, currentObj.getBaseObject(), context);
}
public String display(String fieldname, Object obj) {
if (obj == null)
return "";
return doc.display(fieldname, obj.getBaseObject(), context);
}
public String display(String fieldname, String mode, Object obj) {
if (obj == null)
return "";
return doc.display(fieldname, mode, obj.getBaseObject(), context);
}
public String display(String fieldname, String mode, String prefix, Object obj) {
if (obj == null)
return "";
return doc.display(fieldname, mode, prefix, obj.getBaseObject(), context);
}
public String displayForm(String className, String header, String format) {
return doc.displayForm(className, header, format, context);
}
public String displayForm(String className, String header, String format, boolean linebreak) {
return doc.displayForm(className, header, format, linebreak, context);
}
public String displayForm(String className) {
return doc.displayForm(className, context);
}
public String displayRendered(com.xpn.xwiki.api.PropertyClass pclass, String prefix, Collection object) throws XWikiException {
if ((pclass == null) || (object == null))
return "";
return doc.displayRendered(pclass.getBasePropertyClass(), prefix, object.getCollection(), context);
}
public String displayView(com.xpn.xwiki.api.PropertyClass pclass, String prefix, Collection object) {
if ((pclass == null) || (object == null))
return "";
return doc.displayView(pclass.getBasePropertyClass(), prefix, object.getCollection(), context);
}
public String displayEdit(com.xpn.xwiki.api.PropertyClass pclass, String prefix, Collection object) {
if ((pclass == null) || (object == null))
return "";
return doc.displayEdit(pclass.getBasePropertyClass(), prefix, object.getCollection(), context);
}
public String displayHidden(com.xpn.xwiki.api.PropertyClass pclass, String prefix, Collection object) {
if ((pclass == null) || (object == null))
return "";
return doc.displayHidden(pclass.getBasePropertyClass(), prefix, object.getCollection(), context);
}
public List getIncludedPages() {
return doc.getIncludedPages(context);
}
public List getIncludedMacros() {
return doc.getIncludedMacros(context);
}
public List getLinkedPages() {
return doc.getLinkedPages(context);
}
public Attachment getAttachment(String filename) {
XWikiAttachment attach = getDoc().getAttachment(filename);
if (attach == null)
return null;
else
return new Attachment(this, attach, context);
}
public List getContentDiff(Document origdoc, Document newdoc) throws XWikiException, DifferentiationFailedException {
try {
if ((origdoc == null) && (newdoc == null))
return new ArrayList();
if (origdoc == null)
return doc.getContentDiff(new XWikiDocument(newdoc.getWeb(), newdoc.getName()), newdoc.getDoc(), context);
if (newdoc == null)
return doc.getContentDiff(origdoc.getDoc(), new XWikiDocument(origdoc.getWeb(), origdoc.getName()), context);
return doc.getContentDiff(origdoc.getDoc(), newdoc.getDoc(), context);
} catch (Exception e) {
java.lang.Object[] args = {origdoc.getFullName(), origdoc.getVersion(), newdoc.getVersion()};
List list = new ArrayList();
XWikiException xe = new XWikiException(XWikiException.MODULE_XWIKI_DIFF, XWikiException.ERROR_XWIKI_DIFF_CONTENT_ERROR,
"Error while making content diff of {0} between version {1} and version {2}", e, args);
String errormsg = Util.getHTMLExceptionMessage(xe, context);
list.add(errormsg);
return list;
}
}
public List getXMLDiff(Document origdoc, Document newdoc) throws XWikiException, DifferentiationFailedException {
try {
if ((origdoc == null) && (newdoc == null))
return new ArrayList();
if (origdoc == null)
return doc.getXMLDiff(new XWikiDocument(newdoc.getWeb(), newdoc.getName()), newdoc.getDoc(), context);
if (newdoc == null)
return doc.getXMLDiff(origdoc.getDoc(), new XWikiDocument(origdoc.getWeb(), origdoc.getName()), context);
return doc.getXMLDiff(origdoc.getDoc(), newdoc.getDoc(), context);
} catch (Exception e) {
java.lang.Object[] args = {origdoc.getFullName(), origdoc.getVersion(), newdoc.getVersion()};
List list = new ArrayList();
XWikiException xe = new XWikiException(XWikiException.MODULE_XWIKI_DIFF, XWikiException.ERROR_XWIKI_DIFF_XML_ERROR,
"Error while making xml diff of {0} between version {1} and version {2}", e, args);
String errormsg = Util.getHTMLExceptionMessage(xe, context);
list.add(errormsg);
return list;
}
}
public List getRenderedContentDiff(Document origdoc, Document newdoc) throws XWikiException, DifferentiationFailedException {
try {
if ((origdoc == null) && (newdoc == null))
return new ArrayList();
if (origdoc == null)
return doc.getRenderedContentDiff(new XWikiDocument(newdoc.getWeb(), newdoc.getName()), newdoc.getDoc(), context);
if (newdoc == null)
return doc.getRenderedContentDiff(origdoc.getDoc(), new XWikiDocument(origdoc.getWeb(), origdoc.getName()), context);
return doc.getRenderedContentDiff(origdoc.getDoc(), newdoc.getDoc(), context);
} catch (Exception e) {
java.lang.Object[] args = {origdoc.getFullName(), origdoc.getVersion(), newdoc.getVersion()};
List list = new ArrayList();
XWikiException xe = new XWikiException(XWikiException.MODULE_XWIKI_DIFF, XWikiException.ERROR_XWIKI_DIFF_RENDERED_ERROR,
"Error while making rendered diff of {0} between version {1} and version {2}", e, args);
String errormsg = Util.getHTMLExceptionMessage(xe, context);
list.add(errormsg);
return list;
}
}
public List getMetaDataDiff(Document origdoc, Document newdoc) throws XWikiException {
try {
if ((origdoc == null) && (newdoc == null))
return new ArrayList();
if (origdoc == null)
return doc.getMetaDataDiff(new XWikiDocument(newdoc.getWeb(), newdoc.getName()), newdoc.getDoc(), context);
if (newdoc == null)
return doc.getMetaDataDiff(origdoc.getDoc(), new XWikiDocument(origdoc.getWeb(), origdoc.getName()), context);
return doc.getMetaDataDiff(origdoc.getDoc(), newdoc.getDoc(), context);
} catch (Exception e) {
java.lang.Object[] args = {origdoc.getFullName(), origdoc.getVersion(), newdoc.getVersion()};
List list = new ArrayList();
XWikiException xe = new XWikiException(XWikiException.MODULE_XWIKI_DIFF, XWikiException.ERROR_XWIKI_DIFF_METADATA_ERROR,
"Error while making meta data diff of {0} between version {1} and version {2}", e, args);
String errormsg = Util.getHTMLExceptionMessage(xe, context);
list.add(errormsg);
return list;
}
}
public List getObjectDiff(Document origdoc, Document newdoc) throws XWikiException {
try {
if ((origdoc == null) && (newdoc == null))
return new ArrayList();
if (origdoc == null)
return getDoc().getObjectDiff(new XWikiDocument(newdoc.getWeb(), newdoc.getName()), newdoc.getDoc(), context);
if (newdoc == null)
return getDoc().getObjectDiff(origdoc.getDoc(), new XWikiDocument(origdoc.getWeb(), origdoc.getName()), context);
return getDoc().getObjectDiff(origdoc.getDoc(), newdoc.getDoc(), context);
} catch (Exception e) {
java.lang.Object[] args = {origdoc.getFullName(), origdoc.getVersion(), newdoc.getVersion()};
List list = new ArrayList();
XWikiException xe = new XWikiException(XWikiException.MODULE_XWIKI_DIFF, XWikiException.ERROR_XWIKI_DIFF_OBJECT_ERROR,
"Error while making meta object diff of {0} between version {1} and version {2}", e, args);
String errormsg = Util.getHTMLExceptionMessage(xe, context);
list.add(errormsg);
return list;
}
}
public List getClassDiff(Document origdoc, Document newdoc) throws XWikiException {
try {
if ((origdoc == null) && (newdoc == null))
return new ArrayList();
if (origdoc == null)
return doc.getClassDiff(new XWikiDocument(newdoc.getWeb(), newdoc.getName()), newdoc.getDoc(), context);
if (newdoc == null)
return doc.getClassDiff(origdoc.getDoc(), new XWikiDocument(origdoc.getWeb(), origdoc.getName()), context);
return doc.getClassDiff(origdoc.getDoc(), newdoc.getDoc(), context);
} catch (Exception e) {
java.lang.Object[] args = {origdoc.getFullName(), origdoc.getVersion(), newdoc.getVersion()};
List list = new ArrayList();
XWikiException xe = new XWikiException(XWikiException.MODULE_XWIKI_DIFF, XWikiException.ERROR_XWIKI_DIFF_CLASS_ERROR,
"Error while making class diff of {0} between version {1} and version {2}", e, args);
String errormsg = Util.getHTMLExceptionMessage(xe, context);
list.add(errormsg);
return list;
}
}
public List getLastChanges() throws XWikiException, DifferentiationFailedException {
return doc.getLastChanges(context);
}
public DocumentStats getCurrentMonthPageStats(String action) {
return context.getWiki().getStatsService(context).getDocMonthStats(doc.getFullName(), action, new Date(), context);
}
public DocumentStats getCurrentMonthWebStats(String action) {
return context.getWiki().getStatsService(context).getDocMonthStats(doc.getWeb(), action, new Date(), context);
}
public List getCurrentMonthRefStats() throws XWikiException {
return context.getWiki().getStatsService(context).getRefMonthStats(doc.getFullName(), new Date(), context);
}
public boolean checkAccess(String right) {
try {
return context.getWiki().checkAccess(right, getDoc(), context);
} catch (XWikiException e) {
return false;
}
}
public boolean hasAccessLevel(String level) {
try {
return context.getWiki().getRightService().hasAccessLevel(level, context.getUser(), getDoc().getFullName(), context);
} catch (Exception e) {
return false;
}
}
public boolean hasAccessLevel(String level, String user) {
try {
return context.getWiki().getRightService().hasAccessLevel(level, user, doc.getFullName(), context);
} catch (Exception e) {
return false;
}
}
public boolean getLocked() {
try {
XWikiLock lock = doc.getLock(context);
if (lock != null && !context.getUser().equals(lock.getUserName()))
return true;
else
return false;
} catch (Exception e) {
return false;
}
}
public String getLockingUser() {
try {
XWikiLock lock = doc.getLock(context);
if (lock != null && !context.getUser().equals(lock.getUserName()))
return lock.getUserName();
else
return "";
} catch (XWikiException e) {
return "";
}
}
public Date getLockingDate() {
try {
XWikiLock lock = doc.getLock(context);
if (lock != null && !context.getUser().equals(lock.getUserName()))
return lock.getDate();
else
return null;
} catch (XWikiException e) {
return null;
}
}
public java.lang.Object get(String classOrFieldName) {
if (currentObj != null)
return getDoc().display(classOrFieldName, currentObj.getBaseObject(), context);
BaseObject object = getDoc().getFirstObject(classOrFieldName, context);
if (object != null) {
return getDoc().display(classOrFieldName, object, context);
}
return getDoc().getObject(classOrFieldName);
}
public java.lang.Object getValue(String fieldName) {
Object object;
if (currentObj == null)
object = new Object(getDoc().getFirstObject(fieldName, context), context);
else
object = currentObj;
if (object != null) {
try {
return ((BaseProperty) object.getBaseObject().safeget(fieldName)).getValue();
}
catch(NullPointerException e){
return null;
}
}
return null;
}
public String getTextArea() {
return com.xpn.xwiki.XWiki.getTextArea(doc.getContent(), context);
}
/**
* Returns data needed for a generation of Table of Content for this document.
*
* @param init an intial level where the TOC generation should start at
* @param max maximum level TOC is generated for
* @param numbered if should generate numbering for headings
* @return a map where an heading (title) ID is the key and
* value is another map with two keys: text, level and numbering
*/
public Map getTOC(int init, int max, boolean numbered) {
return TOCGenerator.generateTOC(getContent(), init, max, numbered, context);
}
public void insertText(String text, String marker) throws XWikiException {
if (hasAccessLevel("edit"))
getDoc().insertText(text, marker, context);
}
public boolean equals(java.lang.Object arg0) {
if (!(arg0 instanceof Document)) return false;
Document d = (Document) arg0;
return d.context.equals(context) && doc.equals(d.doc);
}
public List getBacklinks() throws XWikiException {
return doc.getBacklinks(context);
}
public List getLinks() throws XWikiException {
return doc.getLinks(context);
}
public String getDefaultEditURL() throws XWikiException {
return doc.getDefaultEditURL(context);
}
public String getEditURL(String action, String mode) throws XWikiException {
return doc.getEditURL(action, mode, context);
}
public String getEditURL(String action, String mode, String language) {
return doc.getEditURL(action, mode, language, context);
}
public boolean isCurrentUserCreator() {
return doc.isCurrentUserCreator(context);
}
public boolean isCurrentUserPage() {
return doc.isCurrentUserPage(context);
}
public boolean isCurrentLocalUserPage() {
return doc.isCurrentLocalUserPage(context);
}
public boolean isCreator(String username) {
return doc.isCreator(username);
}
public void set(String fieldname, java.lang.Object value) {
Object obj;
if (currentObj != null)
obj = currentObj;
else
obj = getFirstObject(fieldname);
if (obj == null)
return;
obj.set(fieldname, value);
}
public void setTitle(String title) {
getDoc().setTitle(title);
}
public void setCustomClass(String customClass) {
getDoc().setCustomClass(customClass);
}
public void setParent(String parent) {
getDoc().setParent(parent);
}
public void setContent(String content) {
getDoc().setContent(content);
}
public void setDefaultTemplate(String dtemplate) {
getDoc().setDefaultTemplate(dtemplate);
}
public void save() throws XWikiException {
if (hasAccessLevel("edit")){
saveDocument();
}
else {
java.lang.Object[] args = {getDoc().getFullName()};
throw new XWikiException(XWikiException.MODULE_XWIKI_ACCESS, XWikiException.ERROR_XWIKI_ACCESS_DENIED,
"Access denied in edit mode on document {0}", null, args);
}
}
public void saveWithProgrammingRights() throws XWikiException {
if (checkProgrammingRights()){
saveDocument();
}
else {
java.lang.Object[] args = {getDoc().getFullName()};
throw new XWikiException(XWikiException.MODULE_XWIKI_ACCESS, XWikiException.ERROR_XWIKI_ACCESS_DENIED,
"Access denied with no programming rights document {0}", null, args);
}
}
private void saveDocument() throws XWikiException {
context.getWiki().saveDocument(getDoc(), olddoc, context);
olddoc = doc;
}
public com.xpn.xwiki.api.Object addObjectFromRequest() throws XWikiException {
// Call to getDoc() ensures that we are working on a clone()
return new com.xpn.xwiki.api.Object(getDoc().addObjectFromRequest(context), context);
}
public com.xpn.xwiki.api.Object addObjectFromRequest(String className) throws XWikiException {
return new com.xpn.xwiki.api.Object(getDoc().addObjectFromRequest(className, context), context);
}
public List addObjectsFromRequest(String className) throws XWikiException {
return addObjectsFromRequest(className, "");
}
public com.xpn.xwiki.api.Object addObjectFromRequest(String className, String prefix) throws XWikiException {
return new com.xpn.xwiki.api.Object(getDoc().addObjectFromRequest(className, prefix, context), context);
}
public List addObjectsFromRequest(String className, String prefix) throws XWikiException {
List objs = getDoc().addObjectsFromRequest(className, prefix, context);
List wrapped = new ArrayList();
Iterator it = objs.iterator();
while(it.hasNext()){
wrapped.add(new com.xpn.xwiki.api.Object((BaseObject) it.next(), context));
}
return wrapped;
}
public com.xpn.xwiki.api.Object updateObjectFromRequest(String className) throws XWikiException {
return new com.xpn.xwiki.api.Object(getDoc().updateObjectFromRequest(className, context), context);
}
public List updateObjectsFromRequest(String className) throws XWikiException {
return updateObjectsFromRequest(className, "");
}
public com.xpn.xwiki.api.Object updateObjectFromRequest(String className, String prefix) throws XWikiException {
return new com.xpn.xwiki.api.Object(getDoc().updateObjectFromRequest(className, prefix, context), context);
}
public List updateObjectsFromRequest(String className, String prefix) throws XWikiException {
List objs = getDoc().updateObjectsFromRequest(className, prefix, context);
List wrapped = new ArrayList();
Iterator it = objs.iterator();
while(it.hasNext()){
wrapped.add(new com.xpn.xwiki.api.Object((BaseObject) it.next(), context));
}
return wrapped;
}
public boolean isAdvancedContent() {
return doc.isAdvancedContent();
}
public boolean isProgrammaticContent() {
return doc.isProgrammaticContent();
}
public boolean removeObject(Object obj) {
return getDoc().removeObject(obj.getBaseObject());
}
public boolean removeObjects(String className) {
return getDoc().removeObjects(className);
}
public void delete() throws XWikiException {
if (hasAccessLevel("delete"))
context.getWiki().deleteDocument(getDocument(), context);
else {
java.lang.Object[] args = {doc.getFullName()};
throw new XWikiException(XWikiException.MODULE_XWIKI_ACCESS, XWikiException.ERROR_XWIKI_ACCESS_DENIED,
"Access denied in edit mode on document {0}", null, args);
}
}
public void deleteWithProgrammingRights() throws XWikiException {
if (checkProgrammingRights())
context.getWiki().deleteDocument(getDocument(), context);
else {
java.lang.Object[] args = {doc.getFullName()};
throw new XWikiException(XWikiException.MODULE_XWIKI_ACCESS, XWikiException.ERROR_XWIKI_ACCESS_DENIED,
"Access denied with no programming rights document {0}", null, args);
}
}
public String getVersionHashCode() {
return doc.getVersionHashCode(context);
}
public int addAttachments() throws XWikiException {
return addAttachments(null);
}
public int addAttachments(String fieldName) throws XWikiException {
if (!hasAccessLevel("edit")){
java.lang.Object[] args = {getDoc().getFullName()};
throw new XWikiException(XWikiException.MODULE_XWIKI_ACCESS, XWikiException.ERROR_XWIKI_ACCESS_DENIED,
"Access denied in edit mode on document {0}", null, args);
}
XWiki xwiki = context.getWiki();
FileUploadPlugin fileupload = (FileUploadPlugin) xwiki.getPlugin("fileupload", context);
List fileuploadlist = fileupload.getFileItems(context);
List attachments = new ArrayList();
int nb = 0;
if (fileuploadlist == null)
return 0;
Iterator it = fileuploadlist.iterator();
while(it.hasNext()) {
DefaultFileItem item = (DefaultFileItem) it.next();
String name = item.getFieldName();
if (fieldName != null && !fieldName.equals(name))
continue;
if (item.isFormField())
continue;
byte[] data = fileupload.getFileItemData(name, context);
String filename;
String fname = fileupload.getFileName(name, context);
int i = fname.lastIndexOf("\\");
if (i==-1)
i = fname.lastIndexOf("/");
filename = fname.substring(i+1);
filename = filename.replaceAll("\\+"," ");
if ((data != null) && (data.length > 0)){
XWikiAttachment attachment = addAttachment(filename, data);
getDoc().saveAttachmentContent(attachment, context);
getDoc().getAttachmentList().add(attachment);
attachments.add(attachment);
nb++;
}
}
if (nb > 0)
context.getWiki().saveDocument(getDoc(), context);
return nb;
}
protected XWikiAttachment addAttachment(String fileName, InputStream iStream) throws XWikiException, IOException {
ByteArrayOutputStream bAOut = new ByteArrayOutputStream();
CopyUtils.copy(iStream, bAOut);
return addAttachment(fileName, bAOut.toByteArray());
}
protected XWikiAttachment addAttachment(String fileName, byte[] data) throws XWikiException {
int i = fileName.indexOf("\\");
if (i == -1)
i = fileName.indexOf("/");
String filename = fileName.substring(i + 1);
filename = context.getWiki().clearName(filename, context);
XWikiAttachment attachment = getDoc().getAttachment(filename);
if (attachment==null) {
attachment = new XWikiAttachment();
olddoc.getAttachmentList().add(attachment);
}
attachment.setContent(data);
attachment.setFilename(filename);
attachment.setAuthor(context.getUser());
// Add the attachment to the document
attachment.setDoc(getDoc());
return attachment;
}
public boolean validate() throws XWikiException {
return doc.validate(context);
}
}
|
package net.dongliu.apk.parser.io;
import net.dongliu.apk.parser.exception.ParserException;
import net.dongliu.apk.parser.struct.ResValue;
import net.dongliu.apk.parser.struct.StringEncoding;
import net.dongliu.apk.parser.struct.StringPool;
import net.dongliu.apk.parser.struct.StringPoolHeader;
import net.dongliu.apk.parser.struct.resource.*;
import java.io.IOException;
import java.util.List;
/**
* @author dongliu
*/
public class SU {
/**
* read string from input stream. if get EOF before read enough data, throw IOException.
*/
public static String readString(TellableInputStream in, StringEncoding encoding)
throws IOException {
if (encoding == StringEncoding.UTF8) {
// The lengths are encoded in the same way as for the 16-bit format
// but using 8-bit rather than 16-bit integers.
int strLen = readLen(in);
int bytesLen = readLen(in);
byte[] bytes = in.readBytes(bytesLen);
String str = new String(bytes, "UTF-8");
// zero
int trailling = in.readUByte();
return str;
} else {
// The length is encoded as either one or two 16-bit integers as per the commentRef...
int strLen = readLen16(in);
String str = in.readStringUTF16(strLen);
// zero
int trailling = in.readUShort();
return str;
}
}
/**
* read utf-16 encoding str, use zero char to end str.
*
* @param in
* @param strLen
* @return
* @throws IOException
*/
public static String readStringUTF16(TellableInputStream in, int strLen) throws IOException {
String str = in.readStringUTF16(strLen);
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c == 0) {
return str.substring(0, i);
}
}
return str;
}
/**
* read encoding len.
* see Stringpool.cpp ENCODE_LENGTH
*
* @param in
* @return
* @throws IOException
*/
private static int readLen(TellableInputStream in) throws IOException {
int len = 0;
int i = in.read();
if ((i & 0x80) != 0) {
//read one more byte.
len |= (i & 0x7f) << 7;
len += in.read();
} else {
len = i;
}
return len;
}
/**
* read encoding len.
* see Stringpool.cpp ENCODE_LENGTH
*
* @param in
* @return
* @throws IOException
*/
private static int readLen16(TellableInputStream in) throws IOException {
int len = 0;
int i = in.readUShort();
if ((i & 0x8000) != 0) {
len |= (i & 0x7fff) << 15;
len += in.readUByte();
} else {
len = i;
}
return len;
}
/**
* read String pool
*
* @param in
* @param stringPoolHeader
* @return
* @throws IOException
*/
public static StringPool readStringPool(TellableInputStream in,
StringPoolHeader stringPoolHeader) throws IOException {
long beginPos = in.tell();
long[] offsets = new long[(int) stringPoolHeader.stringCount];
// read strings offset
if (stringPoolHeader.stringCount > 0) {
for (int idx = 0; idx < stringPoolHeader.stringCount; idx++) {
offsets[idx] = in.readUInt();
}
}
// read flag
boolean sorted = (stringPoolHeader.flags & StringPoolHeader.SORTED_FLAG) != 0;
StringEncoding stringEncoding = (stringPoolHeader.flags & StringPoolHeader.UTF8_FLAG) != 0 ?
StringEncoding.UTF8 : StringEncoding.UTF16;
// read strings. the head and metas have 28 bytes
long stringPos = beginPos + stringPoolHeader.stringsStart - stringPoolHeader.headerSize;
in.advanceIfNotRearch(stringPos);
StringPool stringPool = new StringPool((int) stringPoolHeader.stringCount);
for (int idx = 0; idx < offsets.length; idx++) {
in.advanceIfNotRearch(stringPos + offsets[idx]);
String str = SU.readString(in, stringEncoding);
stringPool.set(idx, str);
}
// read styles
if (stringPoolHeader.styleCount > 0) {
// now we just skip it
}
in.advanceIfNotRearch(beginPos + stringPoolHeader.chunkSize - stringPoolHeader.headerSize);
return stringPool;
}
/**
* read bytes as c++ chars.
*
* @param in
* @param len
* @return
*/
public static String readChars(TellableInputStream in, int len) throws IOException {
char[] chars = new char[len];
for (int i = 0; i < len; i++) {
chars[i] = (char) in.readUByte();
}
return new String(chars);
}
/**
* method to read resource value RGB/ARGB type.
*
* @return
*/
public static String readRGBs(TellableInputStream in, int strLen)
throws IOException {
long l = in.readUInt();
StringBuilder sb = new StringBuilder();
for (int i = strLen / 2 - 1; i >= 0; i
sb.append(Integer.toHexString((int) ((l >> i * 8) & 0xff)));
}
return sb.toString();
}
/**
* read res value, convert from different types to string.
*
* @param in
* @param stringPool
* @return
* @throws IOException
*/
public static ResValue readResValue(TellableInputStream in, StringPool stringPool,
ResourceTable resourceTable)
throws IOException {
ResValue resValue = new ResValue();
resValue.size = in.readUShort();
resValue.res0 = in.readUByte();
resValue.dataType = in.readUByte();
switch (resValue.dataType) {
case ResValue.ResType.INT_DEC:
resValue.data = String.valueOf(in.readUInt());
break;
case ResValue.ResType.STRING:
int strRef = in.readInt();
if (strRef > 0) {
resValue.data = stringPool.get(strRef);
}
break;
case ResValue.ResType.REFERENCE:
long resourceId = in.readUInt();
resValue.data = getResourceByid(resourceId, resourceTable);
break;
case ResValue.ResType.INT_BOOLEAN:
resValue.data = String.valueOf(in.readInt() != 0);
break;
case ResValue.ResType.INT_HEX:
resValue.data = "0x" + Long.toHexString(in.readUInt());
break;
case ResValue.ResType.NULL:
resValue.data = "";
break;
case ResValue.ResType.INT_COLOR_RGB8:
case ResValue.ResType.INT_COLOR_RGB4:
resValue.data = readRGBs(in, 6);
break;
case ResValue.ResType.INT_COLOR_ARGB8:
case ResValue.ResType.INT_COLOR_ARGB4:
resValue.data = readRGBs(in, 8);
break;
case ResValue.ResType.DIMENSION:
resValue.data = getDemension(in);
break;
case ResValue.ResType.FRACTION:
resValue.data = getFraction(in);
break;
default:
resValue.data = "{" + resValue.dataType + ":" + in.readUInt() + "}";
}
return resValue;
}
private static String getDemension(TellableInputStream in) throws IOException {
long l = in.readUInt();
short unit = (short) (l & 0xff);
String unitStr;
switch (unit) {
case ResValue.ResDataCOMPLEX.UNIT_MM:
unitStr = "mm";
break;
case ResValue.ResDataCOMPLEX.UNIT_PX:
unitStr = "px";
break;
case ResValue.ResDataCOMPLEX.UNIT_DIP:
unitStr = "dp";
break;
case ResValue.ResDataCOMPLEX.UNIT_SP:
unitStr = "sp";
break;
case ResValue.ResDataCOMPLEX.UNIT_PT:
unitStr = "pt";
break;
case ResValue.ResDataCOMPLEX.UNIT_IN:
unitStr = "in";
break;
default:
unitStr = "unknow unit:0x" + Integer.toHexString(unit);
}
return (l >> 8) + unitStr;
}
private static String getFraction(TellableInputStream in) throws IOException {
long l = in.readUInt();
// The low-order 4 bits of the data value specify the type of the fraction
short type = (short) (l & 0xf);
String pstr;
switch (type) {
case ResValue.ResDataCOMPLEX.UNIT_FRACTION:
pstr = "%";
break;
case ResValue.ResDataCOMPLEX.UNIT_FRACTION_PARENT:
pstr = "%p";
break;
default:
pstr = "unknow type:0x" + Integer.toHexString(type);
}
float value = Float.intBitsToFloat((int) (l >> 4));
return value + pstr;
}
public static void checkChunkType(int expected, int real) {
if (expected != real) {
throw new ParserException("Excepct chunk type:" + Integer.toHexString(expected)
+ ", but got:" + Integer.toHexString(real));
}
}
public static String getResourceByid(long resourceId, ResourceTable resourceTable) {
// An Android Resource id is a 32-bit integer. It comprises
// an 8-bit Package id [bits 24-31]
// an 8-bit Type id [bits 16-23]
// a 16-bit Entry index [bits 0-15]
String str = "invalid resource:0x" + Long.toHexString(resourceId);
if (resourceTable == null) {
return str;
}
String ref = "@";
short packageId = (short) (resourceId >> 24 & 0xff);
short typeId = (short) ((resourceId >> 16) & 0xff);
int entryIndex = (int) (resourceId & 0xffff);
ResourcePackage resourcePackage = resourceTable.getPackage(packageId);
if (resourcePackage == null) {
return str;
}
TypeSpec typeSpec = resourcePackage.getTypeSpec(typeId);
List<Type> types = resourcePackage.getTypes(typeId);
if (typeSpec == null || types == null) {
return str;
}
if (!typeSpec.exists(entryIndex)) {
return str;
}
ref += typeSpec.name;
// read from type resource
String result = null;
for (Type type : types) {
ResourceEntry resource = type.getResourceEntry(entryIndex);
if (resource == null) {
continue;
}
ref += "/" + resource.key;
result = resource.toString();
}
if (result == null) {
result = ref;
}
return result;
}
}
|
package org.safehaus.kiskis.mgmt.shared.protocol.settings;
public class Common {
public static final String UNKNOWN_LXC_PARENT_NAME = "UNKNOWN";
public static final String BASE_CONTAINER_NAME = "base-container";
public static final int REFRESH_UI_SEC = 3;
public static final int LXC_AGENT_WAIT_TIMEOUT_SEC = 90;
public static final int AGENT_FRESHNESS_MIN = 5;
public static final int MAX_COMMAND_TIMEOUT_SEC = 100 * 60 * 60; // 100 hours
public static final String IP_MASK = "^10\\.10\\.10\\.([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])$";
public static final String HOSTNAME_REGEX = "^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])(\\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9]))*$";
}
|
package com.yahoo.wildwest;
import java.lang.reflect.Field;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;
import sun.misc.Unsafe;
import sun.misc.VM;
@SuppressWarnings("restriction")
public class MUnsafe {
/**
* The instance of unsafe everyone can use
*/
private static final Unsafe unsafe;
/**
* This is required by unsafe to access a char array, it's the offset
*/
private static final long charArrayBaseOffset;
/**
* This is required by unsafe to access a char array, it's the scale for indexing.
*/
private static final long charArrayIndexScale;
/**
* This is required by unsafe to access a byte array, it's the offset
*/
private static final long byteArrayBaseOffset;
/**
* This is required by unsafe to access a byte array, it's the scale for indexing.
*/
private static final long byteArrayIndexScale;
/**
* For convenience.
*/
private static final byte[] EMPTY_BYTE_ARRAY = new byte[] {};
// public static final long ISA_ADDR_OFFSET;
static {
try {
Field f = Unsafe.class.getDeclaredField("theUnsafe");
f.setAccessible(true);
unsafe = (Unsafe) f.get(null);
charArrayBaseOffset = unsafe.arrayBaseOffset(char[].class);
charArrayIndexScale = unsafe.arrayIndexScale(char[].class);
byteArrayBaseOffset = unsafe.arrayBaseOffset(byte[].class);
byteArrayIndexScale = unsafe.arrayIndexScale(byte[].class);
// ISA_HOLDER_OFFSET =
// unsafe.objectFieldOffset(InetSocketAddress.class.getDeclaredField("holder"));
} catch (ReflectiveOperationException | SecurityException | IllegalArgumentException e) {
throw new Error(e);
}
}
/**
* Access to unsafe
*
* @return Unsafe accessor.
*/
public static Unsafe getUnsafe() {
return unsafe;
}
/**
* Given an index into a char array, return the correct offset to use
*
* @param index index into the array to get.
* @return offset into the array for a specific index.
*/
public static long charArrayOffset(int index) {
return calculateOffset(index, charArrayBaseOffset, charArrayIndexScale);
}
/**
* Given a char array, calculate the correct amount of memory it will take. ??? Doesn't take into account null and
* probably should.
*
* @param from array to use in calculation.
* @return length to allocate.
*/
public static long charArraySize(char[] from) {
return from.length * charArrayIndexScale;
}
/**
* Given an index into a byte array, return the correct offset to use
*
* @param index index into the array to get.
* @return offset into the array for a specific index.
*/
public static long byteArrayOffset(int index) {
return calculateOffset(index, byteArrayBaseOffset, byteArrayIndexScale);
}
/**
* Given a byte array, calculate the correct amount of memory it will take.
*
* @param from array to use in calculation.
* @return length to allocate.
*/
public static long byteArraySize(byte[] from) {
return from.length * byteArrayIndexScale;
}
/**
* The object referred to by o is an array, and the offset is an integer of the form B+N*S, where N is a valid index
* into the array, and B and S are the values obtained by #arrayBaseOffset and #arrayIndexScale (respectively) from
* the array's class. The value referred to is the Nth element of the array.
*
* @param index into the array to find the offset for.
* @param base base from Unsafe to use.
* @param scale scale from Unsafe to use
* @return value usable by copyMemory
**/
public static long calculateOffset(int index, long base, long scale) {
return (base + (index * scale));
}
/**
* Allocate memory from unsafe of cap bytes
*
* @param cap number of bytes to allocate
* @return memory that must be free'd with Unsafe.free memory
*/
// Cribbed from DirectByteBuffer, apparently you need to check if it should
// be page aligned and allocate enough if it is.
public static long allocateMemory(long cap) {
boolean isDirectMemoryPageAligned = VM.isDirectMemoryPageAligned();
int pageSize = unsafe.pageSize();
long size = Math.max(1L, (long) cap + (isDirectMemoryPageAligned ? pageSize : 0));
long base = unsafe.allocateMemory(size);
unsafe.setMemory(base, size, (byte) 0);
long address = 0;
if (isDirectMemoryPageAligned && (base % pageSize != 0)) {
// Round up to page boundary
address = base + pageSize - (base & (pageSize - 1));
} else {
address = base;
}
return address;
}
/**
* Copy the contents of a byte array into native memory
*
* @param destAddress native memory
* @param totalSize amount to copy
* @param from where to copy from
*/
public static void copyMemory(long destAddress, byte[] from) {
copyMemory(destAddress, from.length, from);
}
/**
* Copy the contents of a byte array into native memory
*
* @param destAddress native memory
* @param totalSize amount to copy
* @param from where to copy from
*/
public static void copyMemory(long destAddress, long totalSize, byte[] from) {
if (0 == destAddress || 0 == totalSize || null == from || 0 == from.length) {
return;
}
long bytes = Math.min(from.length, totalSize);
unsafe.copyMemory(from, byteArrayBaseOffset, null, index(destAddress, 0), bytes);
}
/**
* Copy the contents of a byte array into native memory
*
* @param dest where to copy to
* @param srcAddress where to copy from
* @param totalSize amount to copy
*/
public static void copyMemory(byte[] dest, long srcAddress, long totalSize) {
if (0 == srcAddress || 0 == totalSize || null == dest || 0 == dest.length) {
return;
}
long bytes = Math.min(dest.length, totalSize);
unsafe.copyMemory(null, index(srcAddress, 0), dest, byteArrayBaseOffset, bytes);
}
/**
* given an address find it's index
*
* @param address native memory
* @param i index
* @return index
*/
private static long index(long address, int i) {
return address + ((long) i << 0);
}
/**
* Free's native memory
*
* @param address native memory to free
*/
public static void freeMemory(long address) {
if (0 != address) {
unsafe.freeMemory(address);
address = 0;
}
}
/**
* Given a String, encode it into MissingFingers address,length tuple
*
* @param s input
* @return MissingFingers, allocated address + length
*/
public static MissingFingers encodeString(String s) {
if (null == s || 0 == s.length() || s.isEmpty()) {
// null begets null
return new MissingFingers(0, 0);
}
byte[] fromBytes = s.getBytes(StandardCharsets.UTF_8);
// gotta null terminate
long totalSize = byteArraySize(fromBytes) + 1;
long destAddress = unsafe.allocateMemory(totalSize);
copyMemory(destAddress, totalSize, fromBytes);
unsafe.putByte(destAddress + (totalSize - 1), (byte) 0);
return new MissingFingers(destAddress, totalSize);
}
/**
* Given an address into memory, copy the bytes into a new String assuming UTF-8 encoding. Also free the memory upon
* completion using Unsafe.freeMemory If you didn't allocate this via unsafe, things will likely go south. If you
* allocated with malloc, they might not unless you turn on NativeMemoryTracking then they will for sure. haha.
*
* @param srcAddress unsafe allocated address that we can copy from/
* @param len bytes to copy.
* @return String, null on null, 0 on empty string
*/
public static String decodeStringAndFree(long srcAddress, long len) {
try {
return decodeString(srcAddress, len);
} finally {
if (0 != srcAddress) {
freeMemory(srcAddress);
}
}
}
/**
* Given an address into memory, copy the bytes into a new String assuming UTF-8 encoding.
*
* @param srcAddress unsafe allocated address that we can copy from/
* @param len bytes to copy.
* @return String, null on null, 0 on empty string
*/
public static String decodeString(long srcAddress, long len) {
if (0 == srcAddress) {
return null;
}
if (0 == len) {
return "";
}
byte[] toBytes = new byte[(int) len];
copyMemory(toBytes, srcAddress, len);
// strip off null terminator
if (0 == toBytes[(int) len - 1]) {
len -= 1;
}
return new String(toBytes, 0, (int) len, StandardCharsets.UTF_8);
}
/**
* Given an address into memory, copy the bytes into a new String assuming UTF-8 encoding. Also free the memory upon
* completion using Unsafe.freeMemory If you didn't allocate this via unsafe, things will likely go south. If you
* allocated with malloc, they might not unless you turn on NativeMemoryTracking then they will for sure. haha.
*
* @param encodedString unsafe allocated address that we can copy from/
* @return String, null on null, 0 on empty string
*/
public static String decodeString(MissingFingers encodedString) {
if (null == encodedString) {
return null;
}
return decodeString(encodedString.getAddress(), encodedString.getLength());
}
/**
* Given an address into memory, copy the bytes into a new String assuming UTF-8 encoding. Also free the memory upon
* completion using Unsafe.freeMemory If you didn't allocate this via unsafe, things will likely go south. If you
* allocated with malloc, they might not unless you turn on NativeMemoryTracking then they will for sure. haha.
*
* @param encodedString unsafe allocated address that we can copy from/
* @return String, null on null, 0 on empty string
*/
public static String decodeStringAndFree(MissingFingers encodedString) {
try {
if (null == encodedString) {
return null;
}
return decodeString(encodedString.getAddress(), encodedString.getLength());
} finally {
if (null != encodedString) {
encodedString.close();
}
}
}
/**
* Given an address into memory, copy the bytes into a new InetAddress.
*
* @param srcAddress unsafe allocated address that we can copy from/
* @param len length of bytes to copy.
* @return InetAddress, null on null, 0 on empty string
*/
public static InetAddress decodeInetAddress(long srcAddress, long len) {
// TODO: implement
return null;
}
/**
* Given an address into memory, copy the bytes into a new InetAddress. Also free the memory upon completion using
* Unsafe.freeMemory If you didn't allocate this via unsafe, things will likely go south. If you allocated with
* malloc, they might not unless you turn on NativeMemoryTracking then they will for sure. haha.
*
* @param srcAddress unsafe allocated address that we can copy from/
* @param len length of bytes to copy.
* @return InetAddress, null on null, 0 on empty string
*/
public static InetAddress decodeInetAddressAndFree(long srcAddress, long len) {
try {
return decodeInetAddress(srcAddress, len);
} finally {
if (0 != srcAddress) {
freeMemory(srcAddress);
}
}
}
/**
* Given an address into memory, copy the bytes into a new InetAddress. Also free the memory upon completion using
* Unsafe.freeMemory If you didn't allocate this via unsafe, things will likely go south. If you allocated with
* malloc, they might not unless you turn on NativeMemoryTracking then they will for sure. haha.
*
* @param encodedInetAddress unsafe allocated address that we can copy from/
* @return InetAddress, null on null, 0 on empty string
*/
public static InetAddress decodeInetAddressAndFree(MissingFingers encodedInetAddress) {
try {
if (null == encodedInetAddress) {
return null;
}
return decodeInetAddress(encodedInetAddress.getAddress(), encodedInetAddress.getLength());
} finally {
if (null != encodedInetAddress) {
encodedInetAddress.close();
}
}
}
/**
* Given an address into memory, copy the bytes into a new byte array. Also free the memory upon completion using
* Unsafe.freeMemory If you didn't allocate this via unsafe, things will likely go south. If you allocated with
* malloc, they might not unless you turn on NativeMemoryTracking then they will for sure. haha.
*
* @param srcAddress unsafe allocated address that we can copy from/
* @param len length of bytes to copy.
* @return Java ByteArray, null on null, 0 on empty string
*/
public static byte[] decodeByteArrayAndFree(long srcAddress, long len) {
try {
return decodeByteArray(srcAddress, len);
} finally {
if (0 != srcAddress) {
freeMemory(srcAddress);
}
}
}
/**
* Given an address into memory, copy the bytes into a new byte array.
*
* @param srcAddress unsafe allocated address that we can copy from/
* @param len length of bytes to copy.
* @return Java ByteArray, null on null, 0 on empty string
*/
public static byte[] decodeByteArray(long srcAddress, long len) {
if (0 == srcAddress) {
return null;
}
if (0 == len) {
return EMPTY_BYTE_ARRAY;
}
byte[] toBytes = new byte[(int) len];
copyMemory(toBytes, srcAddress, len);
return toBytes;
}
/**
* Given an address into memory, copy the bytes into a new byte array.
*
* @param encodedByteArray unsafe allocated address that we can copy from/
* @return Java ByteArray, null on null, 0 on empty string
*/
public static byte[] decodeByteArray(MissingFingers encodedByteArray) {
if (null == encodedByteArray) {
return null;
}
return decodeByteArray(encodedByteArray.getAddress(), encodedByteArray.getLength());
}
/**
* Given an address into memory, copy the bytes into a new byte array. Also free the memory upon completion using
* Unsafe.freeMemory If you didn't allocate this via unsafe, things will likely go south. If you allocated with
* malloc, they might not unless you turn on NativeMemoryTracking then they will for sure. haha.
*
* @param encodedByteArray unsafe allocated address that we can copy from/
* @return Java ByteArray, null on null, 0 on empty string
*/
public static byte[] decodeByteArrayAndFree(MissingFingers encodedByteArray) {
try {
if (null == encodedByteArray) {
return null;
}
return decodeByteArray(encodedByteArray.getAddress(), encodedByteArray.getLength());
} finally {
if (null != encodedByteArray) {
encodedByteArray.close();
}
}
}
public static long arrayIndexScale(Class<?> arrayClass) {
return unsafe.arrayIndexScale(arrayClass);
}
public static void putLong(long address, long data) {
unsafe.putLong(address, data);
}
public static void putInt(long address, int data) {
unsafe.putInt(address, data);
}
public static void putShort(long address, short data) {
unsafe.putShort(address, data);
}
public static void putByte(long address, byte data) {
unsafe.putByte(address, data);
}
public static void putAddress(long address, long newAddress) {
unsafe.putAddress(address, newAddress);
}
public static byte getByte(long address) {
return unsafe.getByte(address);
}
public static short getShort(long address) {
return unsafe.getShort(address);
}
public static int getInt(long address) {
return unsafe.getInt(address);
}
public static long getLong(long address) {
return unsafe.getLong(address);
}
public static long getAddress(long address) {
return unsafe.getAddress(address);
}
public static int getStringLength(byte[] b) {
if (null == b) {
return 0;
}
for (int i = 0; i < b.length; i++) {
if (0 == b[i]) {
return i;
}
}
return b.length;
}
}
|
package ti.modules.titanium.android;
import org.appcelerator.kroll.KrollDict;
import org.appcelerator.kroll.KrollModule;
import org.appcelerator.kroll.KrollProxy;
import org.appcelerator.kroll.annotations.Kroll;
import org.appcelerator.titanium.TiApplication;
import org.appcelerator.titanium.TiC;
import org.appcelerator.titanium.TiContext;
import org.appcelerator.titanium.proxy.IntentProxy;
import org.appcelerator.titanium.util.TiConvert;
import android.app.PendingIntent;
import android.content.Context;
@Kroll.proxy(creatableInModule=AndroidModule.class, propertyAccessors = {
TiC.PROPERTY_FLAGS,
TiC.PROPERTY_INTENT,
TiC.PROPERTY_UPDATE_CURRENT_INTENT
})
public class PendingIntentProxy extends KrollProxy
{
protected PendingIntent pendingIntent;
protected IntentProxy intent;
protected Context pendingIntentContext;
protected boolean updateCurrentIntent = true;
protected int flags;
public PendingIntentProxy()
{
super();
}
public PendingIntentProxy(TiContext tiContext)
{
this();
}
@Override
public void handleCreationArgs(KrollModule createdInModule, Object[] args)
{
if (args.length >= 1 && args[0] instanceof IntentProxy) {
intent = (IntentProxy) args[0];
if (args.length >= 2) {
flags = TiConvert.toInt(args[1]);
}
}
super.handleCreationArgs(createdInModule, args);
pendingIntentContext = getActivity();
if (pendingIntentContext == null) {
pendingIntentContext = TiApplication.getAppCurrentActivity();
}
if (pendingIntentContext == null) {
pendingIntentContext = TiApplication.getInstance();
}
if (pendingIntentContext == null || intent == null) {
throw new IllegalStateException("Creation arguments must contain intent");
}
switch (intent.getType()) {
case IntentProxy.TYPE_ACTIVITY : {
pendingIntent = PendingIntent.getActivity(
pendingIntentContext, 0, intent.getIntent(), flags);
break;
}
case IntentProxy.TYPE_BROADCAST : {
pendingIntent = PendingIntent.getBroadcast(
pendingIntentContext, 0, intent.getIntent(), flags);
break;
}
case IntentProxy.TYPE_SERVICE : {
pendingIntent = PendingIntent.getService(
pendingIntentContext, 0, intent.getIntent(), flags);
break;
}
}
}
public void handleCreationDict(KrollDict dict)
{
if (dict.containsKey(TiC.PROPERTY_INTENT)) {
intent = (IntentProxy) dict.get(TiC.PROPERTY_INTENT);
}
if (dict.containsKey(TiC.PROPERTY_UPDATE_CURRENT_INTENT)) {
updateCurrentIntent = TiConvert.toBoolean(dict.get(TiC.PROPERTY_UPDATE_CURRENT_INTENT));
}
if (dict.containsKey(TiC.PROPERTY_FLAGS)) {
flags = dict.getInt(TiC.PROPERTY_FLAGS);
}
//Since only 1 flag can be set, if user specifies a flag, use it, otherwise, use default flag
if (flags == 0 && updateCurrentIntent) {
flags = PendingIntent.FLAG_UPDATE_CURRENT;
}
super.handleCreationDict(dict);
}
public PendingIntent getPendingIntent()
{
return pendingIntent;
}
}
|
package org.apache.maven.plugin.executablewar;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import com.google.common.base.Function;
import com.google.common.collect.Maps;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugin.PluginManager;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.archiver.ArchiverException;
import org.codehaus.plexus.archiver.UnArchiver;
import org.codehaus.plexus.archiver.manager.ArchiverManager;
import org.codehaus.plexus.archiver.manager.NoSuchArchiverException;
import org.codehaus.plexus.components.io.fileselectors.FileInfo;
import org.codehaus.plexus.components.io.fileselectors.FileSelector;
import org.codehaus.plexus.util.FileUtils;
/**
* Build an executable WAR file.
*
* @author <a href="from.executable-war@nisgits.net">Stig Kleppe-Jrgensen</a>
* @version $Id: $
* TODO make a JDK v1.4 version too with that maven plugin
* TODO need to check if we are in a war packaging and only run then...or?? What about other war-packaging variants
* TODO improve name of goal
*
* @goal add-exec-resources
* @phase process-resources
*/
public class ExecutableWarMojo extends AbstractMojo {
/**
* The Maven Project Object
*
* @parameter expression="${project}"
* @required
* @readonly
*/
private MavenProject project;
/**
* The Maven Session Object
*
* @parameter expression="${session}"
* @required
* @readonly
*/
private MavenSession session;
/**
* The Maven PluginManager Object
*
* @component
* @required
*/
private PluginManager pluginManager;
/**
* The directory for the generated WAR.
*
* @parameter expression="${project.build.directory}"
* @required
*/
private String buildDirectory;
/**
* To look up Archiver/UnArchiver implementations
*
* @component
*/
private ArchiverManager archiverManager;
/**
* The dependencies declared in your plugin.
*
* @parameter default-value="${plugin.artifacts}"
*/
private List<Artifact> pluginArtifacts;
/**
* The name of the generated WAR.
*
* @parameter expression="${project.build.finalName}"
* @required
*/
private String warName;
/**
* Maps "groupId:artifactId" to the corresponding artifact.
* Built from pluginArtifacts.
*/
private Map<String, Artifact> idToArtifact;
public void execute() throws MojoExecutionException, MojoFailureException {
verifyCorrectPackaging(project.getPackaging());
idToArtifact = mapIdToArtifact();
final File expandedWarDirectory = new File(buildDirectory, warName);
extractExecWarClassesTo(expandedWarDirectory);
copyDependenciesTo(expandedWarDirectory);
}
private void verifyCorrectPackaging(final String packaging) throws MojoFailureException {
if (!packaging.equals("war")) {
throw new MojoFailureException(
"Can only be run within a project with 'war' packaging, that is, when building a web application");
}
}
private Map<String, Artifact> mapIdToArtifact() {
return Maps.uniqueIndex(pluginArtifacts, new Function<Artifact, String>() {
public String apply(Artifact from) {
return from.getGroupId() + ":" + from.getArtifactId();
}
});
}
private void extractExecWarClassesTo(final File expandedWarDirectory) {
final Artifact artifact = idToArtifact.get("org.apache.maven.plugins:maven-executable-war-library");
final File artifactFile = artifact.getFile();
try {
final UnArchiver unArchiver = archiverManager.getUnArchiver(artifactFile);
unArchiver.setSourceFile(artifactFile);
expandedWarDirectory.mkdirs();
unArchiver.setFileSelectors(new FileSelector[]{new IsClassFileSelector()});
unArchiver.setDestDirectory(expandedWarDirectory);
unArchiver.extract();
} catch (NoSuchArchiverException e) {
throw new IllegalStateException("Could not get unarchiver for " + artifactFile, e);
} catch (ArchiverException e) {
throw new IllegalStateException("Could not extract " + artifactFile, e);
}
}
private void copyDependenciesTo(File expandedWarDirectory) throws MojoExecutionException {
copyArtifactByIdToDirectory("net.java.dev.jna:jna", expandedWarDirectory);
copyArtifactByIdToDirectory("com.sun.akuma:akuma", expandedWarDirectory);
copyArtifactByIdToDirectory("net.sourceforge.winstone:winstone", expandedWarDirectory);
}
private void copyArtifactByIdToDirectory(final String id, File expandedWarDirectory) throws MojoExecutionException {
final Artifact artifact = idToArtifact.get(id);
copyArtifactToDirectory(artifact, expandedWarDirectory);
}
private void copyArtifactToDirectory(Artifact artifact, File expandedWarDirectory) throws MojoExecutionException {
try {
FileUtils.copyFile(artifact.getFile(), new File(expandedWarDirectory, artifact.getArtifactId() + ".jar"));
} catch (FileNotFoundException e) {
throw new MojoExecutionException("Could not find file for artifact", e);
} catch (IOException e) {
throw new MojoExecutionException("Problems copying artifact", e);
}
}
/**
* Selects only class files
*/
private static class IsClassFileSelector implements FileSelector {
public boolean isSelected(FileInfo fileInfo) throws IOException {
return fileInfo.isFile() && fileInfo.getName().endsWith(".class");
}
}
}
|
// modified : r.nagel 23.08.2004
// - insert getEntryByKey() methode needed by AuxSubGenerator
package net.sf.jabref;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyVetoException;
import java.beans.VetoableChangeListener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import javax.swing.JOptionPane;
public class BibtexDatabase {
Map<String, BibtexEntry> _entries = new Hashtable<String, BibtexEntry>();
String _preamble = null;
HashMap<String, BibtexString> _strings = new HashMap<String, BibtexString>();
Vector<String> _strings_ = new Vector<String>();
Set<DatabaseChangeListener> changeListeners = new HashSet<DatabaseChangeListener>();
private boolean followCrossrefs = true;
/**
* use a map instead of a set since i need to know how many of each key is
* inthere
*/
private HashMap<String, Integer> allKeys = new HashMap<String, Integer>();
/*
* Entries are stored in a HashMap with the ID as key. What happens if
* someone changes a BibtexEntry's ID after it has been added to this
* BibtexDatabase? The key of that entry would be the old ID, not the new
* one. Use a PropertyChangeListener to identify an ID change and update the
* Map.
*/
private final VetoableChangeListener listener =
new VetoableChangeListener()
{
public void vetoableChange(PropertyChangeEvent pce)
throws PropertyVetoException
{
if (pce.getPropertyName() == null)
fireDatabaseChanged (new DatabaseChangeEvent(BibtexDatabase.this, DatabaseChangeEvent.ChangeType.CHANGING_ENTRY, (BibtexEntry)pce.getSource()));
else if ("id".equals(pce.getPropertyName()))
{
// locate the entry under its old key
BibtexEntry oldEntry =
_entries.remove(pce.getOldValue());
if (oldEntry != pce.getSource())
{
// Something is very wrong!
// The entry under the old key isn't
// the one that sent this event.
// Restore the old state.
_entries.put((String)pce.getOldValue(), oldEntry);
throw new PropertyVetoException("Wrong old ID", pce);
}
if (_entries.get(pce.getNewValue()) != null)
{
_entries.put((String)pce.getOldValue(), oldEntry);
throw new PropertyVetoException
("New ID already in use, please choose another",
pce);
}
// and re-file this entry
_entries.put((String) pce.getNewValue(),
(BibtexEntry) pce.getSource());
} else {
fireDatabaseChanged (new DatabaseChangeEvent(BibtexDatabase.this, DatabaseChangeEvent.ChangeType.CHANGED_ENTRY, (BibtexEntry)pce.getSource()));
//Util.pr(pce.getSource().toString()+"\n"+pce.getPropertyName()
// +"\n"+pce.getNewValue());
}
}
};
/**
* Returns the number of entries.
*/
public synchronized int getEntryCount()
{
return _entries.size();
}
/**
* Returns a Set containing the keys to all entries.
* Use getKeySet().iterator() to iterate over all entries.
*/
public synchronized Set<String> getKeySet()
{
return _entries.keySet();
}
/**
* Returns an EntrySorter with the sorted entries from this base,
* sorted by the given Comparator.
*/
public synchronized EntrySorter getSorter(Comparator<BibtexEntry> comp) {
EntrySorter sorter = new EntrySorter(_entries, comp);
addDatabaseChangeListener(sorter);
return sorter;
}
/**
* Just temporary, for testing purposes....
* @return
*/
public Map<String, BibtexEntry> getEntryMap() { return _entries; }
/**
* Returns the entry with the given ID (-> entry_type + hashcode).
*/
public synchronized BibtexEntry getEntryById(String id)
{
return _entries.get(id);
}
public synchronized Collection<BibtexEntry> getEntries() {
return _entries.values();
}
/**
* Returns the entry with the given bibtex key.
*/
public synchronized BibtexEntry getEntryByKey(String key)
{
BibtexEntry back = null ;
int keyHash = key.hashCode() ; // key hash for better performance
Set<String> keySet = _entries.keySet();
for (String entrieID : keySet) {
BibtexEntry entry = getEntryById(entrieID);
if ((entry != null) && (entry.getCiteKey() != null)) {
String citeKey = entry.getCiteKey();
if (citeKey != null) {
if (keyHash == citeKey.hashCode()) {
back = entry;
}
}
}
}
return back ;
}
public synchronized BibtexEntry[] getEntriesByKey(String key) {
ArrayList<BibtexEntry> entries = new ArrayList<BibtexEntry>();
for (BibtexEntry entry : _entries.values()){
if (key.equals(entry.getCiteKey()))
entries.add(entry);
}
return entries.toArray(new BibtexEntry[entries.size()]);
}
/**
* Inserts the entry, given that its ID is not already in use.
* use Util.createId(...) to make up a unique ID for an entry.
*/
public synchronized boolean insertEntry(BibtexEntry entry)
throws KeyCollisionException
{
String id = entry.getId();
if (getEntryById(id) != null)
{
throw new KeyCollisionException(
"ID is already in use, please choose another");
}
entry.addPropertyChangeListener(listener);
_entries.put(id, entry);
fireDatabaseChanged(new DatabaseChangeEvent(this, DatabaseChangeEvent.ChangeType.ADDED_ENTRY, entry));
return checkForDuplicateKeyAndAdd(null, entry.getCiteKey(), false);
}
/**
* Removes the entry with the given string.
*
* Returns null if not found.
*/
public synchronized BibtexEntry removeEntry(String id)
{
BibtexEntry oldValue = _entries.remove(id);
if (oldValue == null)
return null;
removeKeyFromSet(oldValue.getCiteKey());
oldValue.removePropertyChangeListener(listener);
fireDatabaseChanged(new DatabaseChangeEvent(this, DatabaseChangeEvent.ChangeType.REMOVED_ENTRY, oldValue));
return oldValue;
}
public synchronized boolean setCiteKeyForEntry(String id, String key) {
if (!_entries.containsKey(id)) return false; // Entry doesn't exist!
BibtexEntry entry = getEntryById(id);
String oldKey = entry.getCiteKey();
if (key != null)
entry.setField(BibtexFields.KEY_FIELD, key);
else
entry.clearField(BibtexFields.KEY_FIELD);
return checkForDuplicateKeyAndAdd(oldKey, entry.getCiteKey(), false);
}
/**
* Sets the database's preamble.
*/
public synchronized void setPreamble(String preamble)
{
_preamble = preamble;
}
/**
* Returns the database's preamble.
*/
public synchronized String getPreamble()
{
return _preamble;
}
/**
* Inserts a Bibtex String at the given index.
*/
public synchronized void addString(BibtexString string)
throws KeyCollisionException
{
if (hasStringLabel(string.getName())){
throw new KeyCollisionException(Globals.lang("A string with this label already exists"));
}
if (_strings.containsKey(string.getId()))
throw new KeyCollisionException("Duplicate BibtexString id.");
_strings.put(string.getId(), string);
}
/**
* Removes the string at the given index.
*/
public synchronized void removeString(String id) {
_strings.remove(id);
}
/**
* Returns a Set of keys to all BibtexString objects in the database.
* These are in no sorted order.
*/
public Set<String> getStringKeySet() {
return _strings.keySet();
}
/**
* Returns a Collection of all BibtexString objects in the database.
* These are in no particular order.
*/
public Collection<BibtexString> getStringValues() {
return _strings.values();
}
/**
* Returns the string at the given index.
*/
public synchronized BibtexString getString(String o) {
return _strings.get(o);
}
/**
* Returns the number of strings.
*/
public synchronized int getStringCount() {
return _strings.size();
}
/**
* Returns true if a string with the given label already exists.
*/
public synchronized boolean hasStringLabel(String label) {
for (BibtexString value : _strings.values()){
if (value.getName().equals(label))
return true;
}
return false;
}
/**
* Resolves any references to strings contained in this field content,
* if possible.
*/
public String resolveForStrings(String content) {
if (content == null){
throw new IllegalArgumentException("Content for resolveForStrings must not be null.");
}
return resolveContent(content, new HashSet<String>());
}
/**
* Take the given collection of BibtexEntry and resolve any string
* references.
*
* @param entries
* A collection of BibtexEntries in which all strings of the form
* #xxx# will be resolved against the hash map of string
* references stored in the databasee.
*
* @param inPlace If inPlace is true then the given BibtexEntries will be modified, if false then copies of the BibtexEntries are made before resolving the strings.
*
* @return a list of bibtexentries, with all strings resolved. It is dependent on the value of inPlace whether copies are made or the given BibtexEntries are modified.
*/
public List<BibtexEntry> resolveForStrings(Collection<BibtexEntry> entries, boolean inPlace){
if (entries == null)
throw new NullPointerException();
List<BibtexEntry> results = new ArrayList<BibtexEntry>(entries.size());
for (BibtexEntry entry : entries){
results.add(this.resolveForStrings(entry, inPlace));
}
return results;
}
/**
* Take the given BibtexEntry and resolve any string references.
*
* @param entry
* A BibtexEntry in which all strings of the form #xxx# will be
* resolved against the hash map of string references stored in
* the databasee.
*
* @param inPlace
* If inPlace is true then the given BibtexEntry will be
* modified, if false then a copy is made using close made before
* resolving the strings.
*
* @return a BibtexEntry with all string references resolved. It is
* dependent on the value of inPlace whether a copy is made or the
* given BibtexEntries is modified.
*/
public BibtexEntry resolveForStrings(BibtexEntry entry, boolean inPlace) {
if (!inPlace){
entry = (BibtexEntry)entry.clone();
}
for (Object field : entry.getAllFields()){
entry.setField(field.toString(), this.resolveForStrings(entry.getField(field.toString())));
}
return entry;
}
/**
* If the label represents a string contained in this database, returns
* that string's content. Resolves references to other strings, taking
* care not to follow a circular reference pattern.
* If the string is undefined, returns null.
*/
private String resolveString(String label, HashSet<String> usedIds) {
for (BibtexString string : _strings.values()){
//Util.pr(label+" : "+string.getName());
if (string.getName().toLowerCase().equals(label.toLowerCase())) {
// First check if this string label has been resolved
// earlier in this recursion. If so, we have a
// circular reference, and have to stop to avoid
// infinite recursion.
if (usedIds.contains(string.getId())) {
Util.pr("Stopped due to circular reference in strings: "+label);
return label;
}
// If not, log this string's ID now.
usedIds.add(string.getId());
// Ok, we found the string. Now we must make sure we
// resolve any references to other strings in this one.
String res = string.getContent();
res = resolveContent(res, usedIds);
// Finished with recursing this branch, so we remove our
// ID again:
usedIds.remove(string.getId());
return res;
}
}
// If we get to this point, the string has obviously not been defined locally.
// Check if one of the standard BibTeX month strings has been used:
Object o;
if ((o = Globals.MONTH_STRINGS.get(label.toLowerCase())) != null) {
return (String)o;
}
return null;
}
private String resolveContent(String res, HashSet<String> usedIds) {
//if (res.matches(".*
if (res.matches(".*
StringBuilder newRes = new StringBuilder();
int piv = 0, next = 0;
while ((next=res.indexOf("#", piv)) >= 0) {
// We found the next string ref. Append the text
// up to it.
if (next > 0)
newRes.append(res.substring(piv, next));
int stringEnd = res.indexOf("#", next+1);
if (stringEnd >= 0) {
// We found the boundaries of the string ref,
// now resolve that one.
String refLabel = res.substring(next+1, stringEnd);
String resolved = resolveString(refLabel, usedIds);
if (resolved == null) {
// Could not resolve string. Display the
// characters rather than removing them:
newRes.append(res.substring(next, stringEnd+1));
} else
// The string was resolved, so we display its meaning only,
// stripping the # characters signifying the string label:
newRes.append(resolved);
piv = stringEnd+1;
} else {
// We didn't find the boundaries of the string ref. This
// makes it impossible to interpret it as a string label.
// So we should just append the rest of the text and finish.
newRes.append(res.substring(next));
piv = res.length();
break;
}
}
if (piv < res.length()-1)
newRes.append(res.substring(piv));
res = newRes.toString();
}
return res;
}
//
// usage:
// isDuplicate=checkForDuplicateKeyAndAdd( null, b.getKey() , issueDuplicateWarning);
//
// if the newkey already exists and is not the same as oldkey it will give a warning
// else it will add the newkey to the to set and remove the oldkey
public boolean checkForDuplicateKeyAndAdd(String oldKey, String newKey, boolean issueWarning){
// Globals.logger(" checkForDuplicateKeyAndAdd [oldKey = " + oldKey + "] [newKey = " + newKey + "]");
boolean duplicate=false;
if(oldKey==null){// this is a new entry so don't bother removing oldKey
duplicate= addKeyToSet( newKey);
}else{
if(oldKey.equals(newKey)){// were OK because the user did not change keys
duplicate=false;
}else{// user changed the key
// removed the oldkey
// But what if more than two have the same key?
// this means that user can add another key and would not get a warning!
// consider this: i add a key xxx, then i add another key xxx . I get a warning. I delete the key xxx. JBM
// removes this key from the allKey. then I add another key xxx. I don't get a warning!
// i need a way to count the number of keys of each type
// hashmap=>int (increment each time)
removeKeyFromSet( oldKey);
duplicate = addKeyToSet( newKey );
}
}
if(duplicate && issueWarning){
JOptionPane.showMessageDialog(null, Globals.lang("Warning there is a duplicate key")+":" + newKey ,
Globals.lang("Duplicate Key Warning"),
JOptionPane.WARNING_MESSAGE);//, options);
}
return duplicate;
}
/**
* Returns the number of occurences of the given key in this database.
*/
public int getNumberOfKeyOccurences(String key) {
Object o = allKeys.get(key);
if (o == null)
return 0;
else
return (Integer) o;
}
// keep track of all the keys to warn if there are duplicates
private boolean addKeyToSet(String key){
boolean exists=false;
if((key == null) || key.equals(""))
return false;//don't put empty key
if(allKeys.containsKey(key)){
// warning
exists=true;
allKeys.put( key, allKeys.get(key) + 1);// incrementInteger( allKeys.get(key)));
}else
allKeys.put( key, 1);
return exists;
}
// reduce the number of keys by 1. if this number goes to zero then remove from the set
// note: there is a good reason why we should not use a hashset but use hashmap instead
private void removeKeyFromSet(String key){
if((key == null) || key.equals("")) return;
if(allKeys.containsKey(key)){
Integer tI = allKeys.get(key); // if(allKeys.get(key) instanceof Integer)
if(tI ==1)
allKeys.remove( key);
else
allKeys.put( key, tI - 1);//decrementInteger( tI ));
}
}
public void fireDatabaseChanged(DatabaseChangeEvent e) {
for (DatabaseChangeListener listener : changeListeners){
listener.databaseChanged(e);
}
}
public void addDatabaseChangeListener(DatabaseChangeListener l) {
changeListeners.add(l);
}
public void removeDatabaseChangeListener(DatabaseChangeListener l) {
changeListeners.remove(l);
}
/**
* Returns the text stored in the given field of the given bibtex entry
* which belongs to the given database.
*
* If a database is given, this function will try to resolve any string
* references in the field-value.
* Also, if a database is given, this function will try to find values for
* unset fields in the entry linked by the "crossref" field, if any.
*
* @param field
* The field to return the value of.
* @param bibtex maybenull
* The bibtex entry which contains the field.
* @param database maybenull
* The database of the bibtex entry.
* @return The resolved field value or null if not found.
*/
public static String getResolvedField(String field, BibtexEntry bibtex,
BibtexDatabase database) {
if (field.equals("bibtextype"))
return bibtex.getType().getName();
// TODO: Changed this to also consider alias fields, which is the expected
// behavior for the preview layout and for the check whatever all fields are present.
// But there might be unwanted side-effects?!
Object o = bibtex.getFieldOrAlias(field);
// If this field is not set, and the entry has a crossref, try to look up the
// field in the referred entry: Do not do this for the bibtex key.
if ((o == null) && (database != null) && database.followCrossrefs && !field.equals(BibtexFields.KEY_FIELD)) {
Object crossRef = bibtex.getField("crossref");
if (crossRef != null) {
BibtexEntry referred = database.getEntryByKey((String)crossRef);
if (referred != null) {
// Ok, we found the referred entry. Get the field value from that
// entry. If it is unset there, too, stop looking:
o = referred.getField(field);
}
}
}
return getText((String)o, database);
}
/**
* Returns a text with references resolved according to an optionally given
* database.
* @param toResolve maybenull The text to resolve.
* @param database maybenull The database to use for resolving the text.
* @return The resolved text or the original text if either the text or the database are null
*/
public static String getText(String toResolve, BibtexDatabase database) {
if (toResolve != null && database != null)
return database.resolveForStrings(toResolve);
return toResolve;
}
public void setFollowCrossrefs(boolean followCrossrefs) {
this.followCrossrefs = followCrossrefs;
}
}
|
package org.jboss.forge.addon.maven.projects.facets;
import java.io.File;
import javax.enterprise.context.Dependent;
import javax.enterprise.event.Event;
import javax.inject.Inject;
import org.apache.maven.model.Build;
import org.apache.maven.model.Model;
import org.jboss.forge.addon.environment.Environment;
import org.jboss.forge.addon.facets.AbstractFacet;
import org.jboss.forge.addon.maven.projects.MavenFacet;
import org.jboss.forge.addon.maven.projects.MavenFacetImpl;
import org.jboss.forge.addon.maven.projects.MavenProjectBuilder;
import org.jboss.forge.addon.projects.Project;
import org.jboss.forge.addon.projects.building.ProjectBuilder;
import org.jboss.forge.addon.projects.events.PackagingChanged;
import org.jboss.forge.addon.projects.facets.PackagingFacet;
import org.jboss.forge.addon.resource.Resource;
import org.jboss.forge.addon.resource.ResourceFactory;
import org.jboss.forge.furnace.util.Strings;
/**
* @author <a href="mailto:lincolnbaxter@gmail.com">Lincoln Baxter, III</a>
*/
@Dependent
public class MavenPackagingFacet extends AbstractFacet<Project> implements PackagingFacet
{
@Inject
private Event<PackagingChanged> event;
@Inject
private ResourceFactory factory;
@Inject
private Environment environment;
@Override
public void setOrigin(Project origin)
{
super.setOrigin(origin);
}
@Override
public void setPackagingType(final String type)
{
String oldType = getPackagingType();
if (!oldType.equals(type))
{
MavenFacet mavenFacet = getOrigin().getFacet(MavenFacet.class);
Model pom = mavenFacet.getPOM();
pom.setPackaging(type);
mavenFacet.setPOM(pom);
event.fire(new PackagingChanged(getOrigin(), oldType, type));
}
}
@Override
public String getPackagingType()
{
MavenFacet mavenFacet = getOrigin().getFacet(MavenFacet.class);
Model pom = mavenFacet.getPOM();
return pom.getPackaging();
}
@Override
public boolean isInstalled()
{
return getOrigin().hasFacet(MavenFacet.class);
}
@Override
public boolean install()
{
if (getPackagingType() == null || getPackagingType().isEmpty())
{
setPackagingType("pom");
}
return true;
}
@Override
public Resource<?> getFinalArtifact()
{
MavenFacetImpl mvn = (MavenFacetImpl) getOrigin().getFacet(MavenFacet.class);
String directory = mvn.getProjectBuildingResult().getProject().getBuild().getDirectory();
String finalName = mvn.getProjectBuildingResult().getProject().getBuild().getFinalName();
if (Strings.isNullOrEmpty(directory))
{
throw new IllegalStateException("Project build directory is not configured");
}
if (Strings.isNullOrEmpty(finalName))
{
throw new IllegalStateException("Project final artifact name is not configured");
}
return factory.create(new File(directory.trim() + "/" + finalName + "."
+ getPackagingType().toLowerCase()));
}
@Override
public Resource<?> executeBuild(final String... args)
{
return createBuilder().addArguments(args).build();
}
@Override
public ProjectBuilder createBuilder()
{
return new MavenProjectBuilder(environment, getOrigin());
}
@Override
public String getFinalName()
{
MavenFacet mavenFacet = getOrigin().getFacet(MavenFacet.class);
Model pom = mavenFacet.getPOM();
Build build = pom.getBuild();
return build != null ? build.getFinalName() : getDefaultFinalName();
}
private String getDefaultFinalName()
{
MavenFacet mavenFacet = getOrigin().getFacet(MavenFacet.class);
Model pom = mavenFacet.getPOM();
String version = pom.getVersion();
if (version == null && pom.getParent() != null)
version = pom.getParent().getVersion();
return pom.getArtifactId() + "-" + version;
}
@Override
public void setFinalName(final String finalName)
{
MavenFacet mavenFacet = getOrigin().getFacet(MavenFacet.class);
Model pom = mavenFacet.getPOM();
Build build = pom.getBuild();
if (build == null)
{
build = new Build();
pom.setBuild(build);
}
pom.getBuild().setFinalName(finalName);
mavenFacet.setPOM(pom);
}
}
|
package control;
import java.util.LinkedList;
import data.Camera;
import data.CameraShot;
import data.CameraTimeline;
import data.CameraType;
import data.DirectorTimeline;
import data.ScriptingProject;
import gui.modal.AddCameraModalView;
import gui.modal.AddCameraTypeModalView;
import gui.modal.EditProjectModalView;
import gui.root.RootCenterArea;
import javafx.scene.control.Label;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
public class EditMenuController {
private ControllerManager controllerManager;
private EditProjectModalView editModal;
private AddCameraTypeModalView typeModal;
private AddCameraModalView cameraModal;
/**
* Construct a new EditMenuController.
* @param manager the ControllerManager that controls this EditMenuController
*/
public EditMenuController(ControllerManager manager) {
this.controllerManager = manager;
}
/**
* Start the edit project modal.
*/
public void editProject() {
editModal = new EditProjectModalView(controllerManager.getRootPane());
editModal.getAddCameraButton().setOnMouseClicked(this::addCamera);
editModal.getDeleteCameraButton().setOnMouseClicked(this::deleteCamera);
editModal.getAddCameraTypeButton().setOnMouseClicked(this::addCameraType);
editModal.getDeleteCameraTypeButton().setOnMouseClicked(this::deleteCameraType);
editModal.getCancelButton().setOnMouseClicked(this::cancel);
editModal.getSaveButton().setOnMouseClicked(this::save);
}
/**
* Handler for adding a camera.
* @param event the MouseEvent for this handler
*/
private void addCamera(MouseEvent event) {
cameraModal = new AddCameraModalView(controllerManager.getRootPane(), editModal.getTypes());
cameraModal.getAddCameraButton().setOnMouseClicked(this::cameraAdded);
}
/**
* Handler for when a camera is added.
* @param event the MouseEvent for this handler
*/
private void cameraAdded(MouseEvent event) {
if (validateCameraData()) {
// Hide modal
cameraModal.hideModal();
// Get data
String name = cameraModal.getNameField().getText();
String description = cameraModal.getDescriptionField().getText();
int selectedIndex = cameraModal.getCameraTypes().getSelectionModel().getSelectedIndex();
// Construct objects from data
CameraType type = cameraModal.getCameraTypeList().get(selectedIndex);
Camera camera = new Camera(name, description, type);
// Add camera to camera list
editModal.getCameras().add(camera);
// Add camera to list of cameras that is shown
HBox box = new HBox();
box.getChildren().addAll(new Label(name), new Label(" - "), new Label(description));
editModal.getCameraList().getItems().add(box);
// Add camera timeline to list of timelines
CameraTimeline timeline = new CameraTimeline(name, camera, description, null);
editModal.getTimelines().add(timeline);
}
}
/**
* Validate the entered camera data.
* @return true if the data is legit, false otherwise
*/
private boolean validateCameraData() {
String errorString = "";
String name = cameraModal.getNameField().getText();
String description = cameraModal.getDescriptionField().getText();
int selectedIndex = cameraModal.getCameraTypes().getSelectionModel().getSelectedIndex();
if (selectedIndex == -1) {
errorString = "Please select a camera type\n";
}
if (description.isEmpty()) {
errorString = "Please enter a camera description\n";
}
if (name.isEmpty()) {
errorString = "Please enter a camera name\n";
}
cameraModal.getTitleLabel().setText(errorString);
cameraModal.getTitleLabel().setTextFill(Color.RED);
return errorString.isEmpty();
}
/**
* Handler for deleting a camera.
* @param event the MouseEvent for this handler
*/
private void deleteCamera(MouseEvent event) {
// TODO: Show prompt if there are shots on the timeline.
int selectedIndex = editModal.getCameraList().getSelectionModel().getSelectedIndex();
if (selectedIndex != -1) {
editModal.getCameras().remove(selectedIndex);
editModal.getTimelines().remove(selectedIndex);
editModal.getCameraList().getItems().remove(selectedIndex);
} else {
// TODO: Error message: should select camera
}
}
private void addCameraType(MouseEvent event) {
typeModal = new AddCameraTypeModalView(controllerManager.getRootPane());
typeModal.getAddCameraTypeButton().setOnMouseClicked(this::typeAdded);
}
/**
* Handler for adding a camera type.
* @param event the MouseEvent for this handler
*/
private void typeAdded(MouseEvent event) {
if (validateCameraTypeData()) {
typeModal.hideModal();
String name = typeModal.getNameField().getText();
String description = typeModal.getDescriptionField().getText();
double movementMargin = Double.parseDouble(
typeModal.getMovementMarginField().getText());
CameraType type = new CameraType(name, description, movementMargin);
editModal.getTypes().add(type);
HBox box = new HBox();
box.getChildren().addAll(new Label(name), new Label(" - "), new Label(description));
editModal.getCameraTypeList().getItems().add(box);
}
}
/**
* Validate the data for adding a camera type.
* @return true if the data is legit, false otherwise
*/
private boolean validateCameraTypeData() {
String errorString = "";
String name = typeModal.getNameField().getText();
String description = typeModal.getDescriptionField().getText();
String movementMargin = typeModal.getMovementMarginField().getText();
if (movementMargin.isEmpty()) {
errorString = "Please enter a movement margin\n";
}
if (description.isEmpty()) {
errorString = "Please enter a description\n";
}
if (name.isEmpty()) {
errorString = "Please enter a name\n";
}
typeModal.getTitleLabel().setText(errorString);
typeModal.getTitleLabel().setTextFill(Color.RED);
return errorString.isEmpty();
}
/**
* Handler for deleting a camera type.
* @param event the MouseEvent for this handler
*/
private void deleteCameraType(MouseEvent event) {
int selectedIndex = editModal.getCameraTypeList().getSelectionModel().getSelectedIndex();
if (selectedIndex != -1) {
editModal.getTypes().remove(selectedIndex);
editModal.getCameraTypeList().getItems().remove(selectedIndex);
} else {
// TODO: Error message, select camera type
}
}
/**
* Handler for when the cancel button is pressed.
* @param event the MouseEvent for this handler
*/
private void cancel(MouseEvent event) {
editModal.hideModal();
}
/**
* Handler for when the save button is clicked.
* @param event the MouseEvent for this handler
*/
private void save(MouseEvent event) {
if (validateProjectData()) {
editModal.hideModal();
String name = editModal.getNameField().getText();
String description = editModal.getDescriptionField().getText();
String directorTimelineDescription = editModal.getDirectorDescriptionField().getText();
double secondsPerCount = Double.parseDouble(
editModal.getSecondsPerCountField().getText());
ScriptingProject project = new ScriptingProject(name, description, secondsPerCount);
project.setDirectorTimeline(new DirectorTimeline(directorTimelineDescription, null));
project.setCameraTypes(editModal.getTypes());
project.setCameras(editModal.getCameras());
project.setCameraTimelines(editModal.getTimelines());
project.getDirectorTimeline().setProject(project);
project.setFilePath(editModal.getProject().getFilePath());
for (CameraTimeline timeline : project.getCameraTimelines()) {
timeline.setProject(project);
}
controllerManager.setScriptingProject(project);
controllerManager.updateWindowTitle();
RootCenterArea area = new RootCenterArea(
controllerManager.getRootPane(), editModal.getTimelines().size(), false);
controllerManager.getRootPane().reInitRootCenterArea(area);
for (int i = 0;i < project.getCameraTimelines().size();i++) {
CameraTimeline newLine = project.getCameraTimelines().get(i);
CameraTimeline oldLine = editModal.getProject().getCameraTimelines().get(i);
LinkedList<CameraShot> shots = new LinkedList<CameraShot>();
for (CameraShot shot: oldLine.getShots()) {
shots.add(shot);
}
for (CameraShot shot: shots) {
newLine.addShot(shot);
controllerManager.getTimelineControl().addCameraShot(i, shot);
}
}
}
}
/**
* Validate the data entered for the project.
* @return true if the data is legit, false otherwise
*/
private boolean validateProjectData() {
String errorString = "";
String directorTimelineDescription = editModal.getDirectorDescriptionField().getText();
if (directorTimelineDescription.isEmpty()) {
errorString = "Please enter a director timeline description\n";
}
String secondsPerCount = editModal.getSecondsPerCountField().getText();
if (secondsPerCount.isEmpty()) {
errorString = "Please enter the seconds per count\n";
}
String description = editModal.getDescriptionField().getText();
if (description.isEmpty()) {
errorString = "Please enter a project description\n";
}
String name = editModal.getNameField().getText();
if (name.isEmpty()) {
errorString = "Please enter a project name\n";
}
editModal.getErrorLabel().setText(errorString);
editModal.getErrorLabel().setTextFill(Color.RED);
return errorString.isEmpty();
}
}
|
package control;
import data.CameraShot;
import data.DirectorShot;
import gui.centerarea.CameraShotBlock;
import gui.centerarea.DirectorShotBlock;
import gui.centerarea.ShotBlock;
import gui.headerarea.ToolView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
/**
* Controller that manages the tool menu (e.g. shot creation menu).
*/
public class ToolViewController {
private ControllerManager controllerManager;
private CreationModalViewController creationModalViewController;
private ToolView toolView;
/**
* Constructor.
* @param controllerManager Manager of the controllers.
*/
public ToolViewController(ControllerManager controllerManager) {
this.controllerManager = controllerManager;
this.creationModalViewController = new CreationModalViewController(this.controllerManager);
this.toolView = controllerManager.getRootPane().getRootHeaderArea().getToolView();
initializeTools();
}
/**
* Initialize all tools in the toolbox. Adds the corresponding buttons to the views and sets up
* the event handlers.
*/
private void initializeTools() {
// add handlers to toolbuttons
toolView.getCameraBlockCreationTool().getButton().setOnMouseClicked(
event -> creationModalViewController.showCameraCreationWindow());
toolView.getDirectorBlockCreationTool().getButton().setOnMouseClicked(
event -> creationModalViewController.showDirectorCreationWindow());
toolView.getBlockDeletionTool().getButton().setOnMouseClicked(
event -> deleteActiveCameraShot());
toolView.getShotGenerationTool().getButton().setOnMouseClicked(
event -> generateCameraShots());
toolView.getAllShotGenerationTool().getButton().setOnMouseClicked(
event -> controllerManager.getDirectorTimelineControl().generateAllShots());
// If there is no active ShotBlock, then disable the delete button
if (this.controllerManager.getActiveShotBlock() == null) {
toolView.getBlockDeletionTool().disableButton();
toolView.getShotGenerationTool().disableButton();
}
// Add Delete Key Event Listener for deleting active shot
this.controllerManager.getRootPane().getPrimaryStage()
.getScene().addEventFilter(KeyEvent.KEY_RELEASED, event -> {
if (event.getCode() == KeyCode.DELETE) {
deleteActiveCameraShot();
event.consume();
}
});
}
/**
* Deletes the active camera block.
*/
private void deleteActiveCameraShot() {
ShotBlock currentShot = this.controllerManager.getActiveShotBlock();
if (currentShot instanceof CameraShotBlock) {
CameraShotBlock cameraShotBlock = (CameraShotBlock) currentShot;
this.controllerManager.getTimelineControl().removeCameraShot(cameraShotBlock);
}
if (currentShot instanceof DirectorShotBlock) {
DirectorShotBlock directorShotBlock = (DirectorShotBlock) currentShot;
this.controllerManager.getDirectorTimelineControl().removeShot(directorShotBlock);
}
}
/**
* Create the director shot's corresponding camera shots.
*/
private void generateCameraShots() {
if (this.controllerManager.getActiveShotBlock() instanceof DirectorShotBlock) {
DirectorShotBlock directorShotBlock = (DirectorShotBlock)
this.controllerManager.getActiveShotBlock();
DirectorShot shot = directorShotBlock.getShot();
// Camera shots need to take the director shot's padding into account when making a shot
double cameraStart = shot.getBeginCount() - shot.getFrontShotPadding();
double cameraEnd = shot.getEndCount() + shot.getEndShotPadding();
shot.getTimelineIndices().forEach(index -> {
CameraShot subShot = new CameraShot(shot.getName(), shot.getDescription(),
cameraStart, cameraEnd, shot);
shot.addCameraShot(subShot);
this.controllerManager.getTimelineControl().addCameraShot(index, subShot);
});
}
}
/**
* Called when the active shot selection changed.
* ToolViewController then updates the buttons accordingly.
*/
public void activeBlockChanged() {
if (this.controllerManager.getActiveShotBlock() != null) {
toolView.getBlockDeletionTool().enableButton();
// Only enable the generation of camera shots if it's a director shot w/o camera shots
boolean enableGen = false;
if (this.controllerManager.getActiveShotBlock() instanceof DirectorShotBlock) {
DirectorShotBlock directorShotBlock = (DirectorShotBlock)
this.controllerManager.getActiveShotBlock();
if (directorShotBlock.getShot().getCameraShots().isEmpty()) {
enableGen = true;
}
}
if (enableGen) {
toolView.getShotGenerationTool().enableButton();
} else {
toolView.getShotGenerationTool().disableButton();
}
} else {
toolView.getBlockDeletionTool().disableButton();
toolView.getShotGenerationTool().disableButton();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.