diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/src/uk/co/oliwali/DataLog/util/DataLogAPI.java b/src/uk/co/oliwali/DataLog/util/DataLogAPI.java
index f277bc2..c2a3ee0 100644
--- a/src/uk/co/oliwali/DataLog/util/DataLogAPI.java
+++ b/src/uk/co/oliwali/DataLog/util/DataLogAPI.java
@@ -1,19 +1,17 @@
package uk.co.oliwali.DataLog.util;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import uk.co.oliwali.DataLog.DataManager;
import uk.co.oliwali.DataLog.DataType;
public class DataLogAPI {
public static boolean addEntry(JavaPlugin plugin, String action, Player player, Location loc, String data) {
- if (action.contains(" "))
- return false;
DataManager.addEntry(player, plugin, DataType.OTHER, loc, action + "-" + data);
return true;
}
}
| true | true | public static boolean addEntry(JavaPlugin plugin, String action, Player player, Location loc, String data) {
if (action.contains(" "))
return false;
DataManager.addEntry(player, plugin, DataType.OTHER, loc, action + "-" + data);
return true;
}
| public static boolean addEntry(JavaPlugin plugin, String action, Player player, Location loc, String data) {
DataManager.addEntry(player, plugin, DataType.OTHER, loc, action + "-" + data);
return true;
}
|
diff --git a/OFQAAPI/src/com/openfeint/qa/core/caze/step/definition/BasicStepDefinition.java b/OFQAAPI/src/com/openfeint/qa/core/caze/step/definition/BasicStepDefinition.java
index ae40393..b39da8d 100644
--- a/OFQAAPI/src/com/openfeint/qa/core/caze/step/definition/BasicStepDefinition.java
+++ b/OFQAAPI/src/com/openfeint/qa/core/caze/step/definition/BasicStepDefinition.java
@@ -1,58 +1,61 @@
package com.openfeint.qa.core.caze.step.definition;
import android.util.Log;
import java.util.Hashtable;
import java.util.Observable;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import junit.framework.AssertionFailedError;
public abstract class BasicStepDefinition extends Observable {
protected static Hashtable<String, Object> blockRepo = null;
private final Semaphore inStepSync = new Semaphore(0, true);
protected int TIMEOUT = 5000;
protected static Hashtable<String, Object> getBlockRepo() {
if (null == blockRepo) {
blockRepo = new Hashtable<String, Object>();
}
return blockRepo;
}
protected void setTimeout(int timeout) {
TIMEOUT = timeout;
}
/**
* notifys automation framework that current step is finished
*/
protected void notifyStepPass() {
setChanged();
notifyObservers("update waiting");
}
/**
* keeps waiting until a notifyAsync() call invoked
*
* @throws InterruptedException
*/
protected void waitForAsyncInStep() {
try {
- inStepSync.tryAcquire(1, TIMEOUT, TimeUnit.MILLISECONDS);
- } catch (Exception e) {
+ boolean t = inStepSync.tryAcquire(1, TIMEOUT, TimeUnit.MILLISECONDS);
+ if (!t) {
+ throw new AssertionFailedError();
+ }
+ } catch (InterruptedException e) {
throw new AssertionFailedError();
}
}
/**
* notifys async semaphore that current async call is finished
*/
protected void notifyAsyncInStep() {
inStepSync.release(1);
}
}
| true | true | protected void waitForAsyncInStep() {
try {
inStepSync.tryAcquire(1, TIMEOUT, TimeUnit.MILLISECONDS);
} catch (Exception e) {
throw new AssertionFailedError();
}
}
| protected void waitForAsyncInStep() {
try {
boolean t = inStepSync.tryAcquire(1, TIMEOUT, TimeUnit.MILLISECONDS);
if (!t) {
throw new AssertionFailedError();
}
} catch (InterruptedException e) {
throw new AssertionFailedError();
}
}
|
diff --git a/src/org/apache/fop/image/FopImageFactory.java b/src/org/apache/fop/image/FopImageFactory.java
index 9a2650c07..4e1ea97e6 100644
--- a/src/org/apache/fop/image/FopImageFactory.java
+++ b/src/org/apache/fop/image/FopImageFactory.java
@@ -1,190 +1,196 @@
/*
* $Id$
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources.
*/
package org.apache.fop.image;
// Java
import java.io.IOException;
import java.io.InputStream;
import java.io.File;
import java.net.URL;
import java.net.MalformedURLException;
import java.lang.reflect.Constructor;
import java.util.Hashtable;
// FOP
import org.apache.fop.image.analyser.ImageReaderFactory;
import org.apache.fop.image.analyser.ImageReader;
import org.apache.fop.configuration.Configuration;
/**
* create FopImage objects (with a configuration file - not yet implemented).
* @author Eric SCHAEFFER
*/
public class FopImageFactory {
private static Hashtable m_urlMap = new Hashtable();
/**
* create an FopImage objects.
* @param href image URL as a String
* @return a new FopImage object
* @exception java.net.MalformedURLException bad URL
* @exception FopImageException an error occured during construction
*/
public static FopImage Make(String href)
throws MalformedURLException, FopImageException {
/*
* According to section 5.11 a <uri-specification> is:
* "url(" + URI + ")"
* according to 7.28.7 a <uri-specification> is:
* URI
* So handle both.
*/
// Get the absolute URL
URL absoluteURL = null;
InputStream imgIS = null;
href = href.trim();
if(href.startsWith("url(") && (href.indexOf(")") != -1)) {
href = href.substring(4, href.indexOf(")")).trim();
if(href.startsWith("'") && href.endsWith("'")) {
href = href.substring(1, href.length() - 1);
} else if(href.startsWith("\"") && href.endsWith("\"")) {
href = href.substring(1, href.length() - 1);
}
}
try {
// try url as complete first, this can cause
// a problem with relative uri's if there is an
// image relative to where fop is run and relative
// to the base dir of the document
try {
absoluteURL = new URL(href);
} catch (MalformedURLException mue) {
// if the href contains onl a path then file is assumed
absoluteURL = new URL("file:" + href);
}
imgIS = absoluteURL.openStream();
} catch (MalformedURLException e_context) {
throw new FopImageException("Error with image URL: "
+ e_context.getMessage());
} catch (Exception e) {
// maybe relative
URL context_url = null;
+ String base = Configuration.getStringValue("baseDir");
+ if(base == null) {
+ throw new FopImageException("Error with image URL: "
+ + e.getMessage()
+ + " and no base directory is specified");
+ }
try {
absoluteURL = new URL(Configuration.getStringValue("baseDir")
+ absoluteURL.getFile());
} catch (MalformedURLException e_context) {
// pb context url
throw new FopImageException("Invalid Image URL - error on relative URL : "
+ e_context.getMessage());
}
}
// check if already created
FopImage imageObject = (FopImage)m_urlMap.get(absoluteURL.toString());
if (imageObject != null)
return imageObject;
// If not, check image type
ImageReader imgReader = null;
try {
if (imgIS == null) {
imgIS = absoluteURL.openStream();
}
imgReader = ImageReaderFactory.Make(absoluteURL.toExternalForm(),
imgIS);
} catch (Exception e) {
throw new FopImageException("Error while recovering Image Informations ("
+ absoluteURL.toString() + ") : "
+ e.getMessage());
}
finally {
if (imgIS != null) {
try {
imgIS.close();
} catch (IOException e) {}
}
}
if (imgReader == null)
throw new FopImageException("No ImageReader for this type of image ("
+ absoluteURL.toString() + ")");
// Associate mime-type to FopImage class
String imgMimeType = imgReader.getMimeType();
String imgClassName = null;
if ("image/gif".equals(imgMimeType)) {
imgClassName = "org.apache.fop.image.GifImage";
// imgClassName = "org.apache.fop.image.JAIImage";
} else if ("image/jpeg".equals(imgMimeType)) {
imgClassName = "org.apache.fop.image.JpegImage";
// imgClassName = "org.apache.fop.image.JAIImage";
} else if ("image/bmp".equals(imgMimeType)) {
imgClassName = "org.apache.fop.image.BmpImage";
// imgClassName = "org.apache.fop.image.JAIImage";
} else if ("image/png".equals(imgMimeType)) {
imgClassName = "org.apache.fop.image.JimiImage";
// imgClassName = "org.apache.fop.image.JAIImage";
} else if ("image/tga".equals(imgMimeType)) {
imgClassName = "org.apache.fop.image.JimiImage";
// imgClassName = "org.apache.fop.image.JAIImage";
} else if ("image/tiff".equals(imgMimeType)) {
imgClassName = "org.apache.fop.image.JimiImage";
// imgClassName = "org.apache.fop.image.JAIImage";
} else if ("image/svg+xml".equals(imgMimeType)) {
imgClassName = "org.apache.fop.image.SVGImage";
}
if (imgClassName == null)
throw new FopImageException("Unsupported image type ("
+ absoluteURL.toString() + ") : "
+ imgMimeType);
// load the right image class
// return new <FopImage implementing class>
Object imageInstance = null;
Class imageClass = null;
try {
imageClass = Class.forName(imgClassName);
Class[] imageConstructorParameters = new Class[2];
imageConstructorParameters[0] = Class.forName("java.net.URL");
imageConstructorParameters[1] =
Class.forName("org.apache.fop.image.analyser.ImageReader");
Constructor imageConstructor =
imageClass.getDeclaredConstructor(imageConstructorParameters);
Object[] initArgs = new Object[2];
initArgs[0] = absoluteURL;
initArgs[1] = imgReader;
imageInstance = imageConstructor.newInstance(initArgs);
} catch (java.lang.reflect.InvocationTargetException ex) {
Throwable t = ex.getTargetException();
String msg;
if (t != null) {
msg = t.getMessage();
} else {
msg = ex.getMessage();
}
throw new FopImageException("Error creating FopImage object ("
+ absoluteURL.toString() + ") : "
+ msg);
} catch (Exception ex) {
throw new FopImageException("Error creating FopImage object ("
+ "Error creating FopImage object ("
+ absoluteURL.toString() + ") : "
+ ex.getMessage());
}
if (!(imageInstance instanceof org.apache.fop.image.FopImage)) {
throw new FopImageException("Error creating FopImage object ("
+ absoluteURL.toString() + ") : "
+ "class " + imageClass.getName()
+ " doesn't implement org.apache.fop.image.FopImage interface");
}
m_urlMap.put(absoluteURL.toString(), imageInstance);
return (FopImage)imageInstance;
}
}
| true | true | public static FopImage Make(String href)
throws MalformedURLException, FopImageException {
/*
* According to section 5.11 a <uri-specification> is:
* "url(" + URI + ")"
* according to 7.28.7 a <uri-specification> is:
* URI
* So handle both.
*/
// Get the absolute URL
URL absoluteURL = null;
InputStream imgIS = null;
href = href.trim();
if(href.startsWith("url(") && (href.indexOf(")") != -1)) {
href = href.substring(4, href.indexOf(")")).trim();
if(href.startsWith("'") && href.endsWith("'")) {
href = href.substring(1, href.length() - 1);
} else if(href.startsWith("\"") && href.endsWith("\"")) {
href = href.substring(1, href.length() - 1);
}
}
try {
// try url as complete first, this can cause
// a problem with relative uri's if there is an
// image relative to where fop is run and relative
// to the base dir of the document
try {
absoluteURL = new URL(href);
} catch (MalformedURLException mue) {
// if the href contains onl a path then file is assumed
absoluteURL = new URL("file:" + href);
}
imgIS = absoluteURL.openStream();
} catch (MalformedURLException e_context) {
throw new FopImageException("Error with image URL: "
+ e_context.getMessage());
} catch (Exception e) {
// maybe relative
URL context_url = null;
try {
absoluteURL = new URL(Configuration.getStringValue("baseDir")
+ absoluteURL.getFile());
} catch (MalformedURLException e_context) {
// pb context url
throw new FopImageException("Invalid Image URL - error on relative URL : "
+ e_context.getMessage());
}
}
// check if already created
FopImage imageObject = (FopImage)m_urlMap.get(absoluteURL.toString());
if (imageObject != null)
return imageObject;
// If not, check image type
ImageReader imgReader = null;
try {
if (imgIS == null) {
imgIS = absoluteURL.openStream();
}
imgReader = ImageReaderFactory.Make(absoluteURL.toExternalForm(),
imgIS);
} catch (Exception e) {
throw new FopImageException("Error while recovering Image Informations ("
+ absoluteURL.toString() + ") : "
+ e.getMessage());
}
finally {
if (imgIS != null) {
try {
imgIS.close();
} catch (IOException e) {}
}
}
if (imgReader == null)
throw new FopImageException("No ImageReader for this type of image ("
+ absoluteURL.toString() + ")");
// Associate mime-type to FopImage class
String imgMimeType = imgReader.getMimeType();
String imgClassName = null;
if ("image/gif".equals(imgMimeType)) {
imgClassName = "org.apache.fop.image.GifImage";
// imgClassName = "org.apache.fop.image.JAIImage";
} else if ("image/jpeg".equals(imgMimeType)) {
imgClassName = "org.apache.fop.image.JpegImage";
// imgClassName = "org.apache.fop.image.JAIImage";
} else if ("image/bmp".equals(imgMimeType)) {
imgClassName = "org.apache.fop.image.BmpImage";
// imgClassName = "org.apache.fop.image.JAIImage";
} else if ("image/png".equals(imgMimeType)) {
imgClassName = "org.apache.fop.image.JimiImage";
// imgClassName = "org.apache.fop.image.JAIImage";
} else if ("image/tga".equals(imgMimeType)) {
imgClassName = "org.apache.fop.image.JimiImage";
// imgClassName = "org.apache.fop.image.JAIImage";
} else if ("image/tiff".equals(imgMimeType)) {
imgClassName = "org.apache.fop.image.JimiImage";
// imgClassName = "org.apache.fop.image.JAIImage";
} else if ("image/svg+xml".equals(imgMimeType)) {
imgClassName = "org.apache.fop.image.SVGImage";
}
if (imgClassName == null)
throw new FopImageException("Unsupported image type ("
+ absoluteURL.toString() + ") : "
+ imgMimeType);
// load the right image class
// return new <FopImage implementing class>
Object imageInstance = null;
Class imageClass = null;
try {
imageClass = Class.forName(imgClassName);
Class[] imageConstructorParameters = new Class[2];
imageConstructorParameters[0] = Class.forName("java.net.URL");
imageConstructorParameters[1] =
Class.forName("org.apache.fop.image.analyser.ImageReader");
Constructor imageConstructor =
imageClass.getDeclaredConstructor(imageConstructorParameters);
Object[] initArgs = new Object[2];
initArgs[0] = absoluteURL;
initArgs[1] = imgReader;
imageInstance = imageConstructor.newInstance(initArgs);
} catch (java.lang.reflect.InvocationTargetException ex) {
Throwable t = ex.getTargetException();
String msg;
if (t != null) {
msg = t.getMessage();
} else {
msg = ex.getMessage();
}
throw new FopImageException("Error creating FopImage object ("
+ absoluteURL.toString() + ") : "
+ msg);
} catch (Exception ex) {
throw new FopImageException("Error creating FopImage object ("
+ "Error creating FopImage object ("
+ absoluteURL.toString() + ") : "
+ ex.getMessage());
}
if (!(imageInstance instanceof org.apache.fop.image.FopImage)) {
throw new FopImageException("Error creating FopImage object ("
+ absoluteURL.toString() + ") : "
+ "class " + imageClass.getName()
+ " doesn't implement org.apache.fop.image.FopImage interface");
}
m_urlMap.put(absoluteURL.toString(), imageInstance);
return (FopImage)imageInstance;
}
| public static FopImage Make(String href)
throws MalformedURLException, FopImageException {
/*
* According to section 5.11 a <uri-specification> is:
* "url(" + URI + ")"
* according to 7.28.7 a <uri-specification> is:
* URI
* So handle both.
*/
// Get the absolute URL
URL absoluteURL = null;
InputStream imgIS = null;
href = href.trim();
if(href.startsWith("url(") && (href.indexOf(")") != -1)) {
href = href.substring(4, href.indexOf(")")).trim();
if(href.startsWith("'") && href.endsWith("'")) {
href = href.substring(1, href.length() - 1);
} else if(href.startsWith("\"") && href.endsWith("\"")) {
href = href.substring(1, href.length() - 1);
}
}
try {
// try url as complete first, this can cause
// a problem with relative uri's if there is an
// image relative to where fop is run and relative
// to the base dir of the document
try {
absoluteURL = new URL(href);
} catch (MalformedURLException mue) {
// if the href contains onl a path then file is assumed
absoluteURL = new URL("file:" + href);
}
imgIS = absoluteURL.openStream();
} catch (MalformedURLException e_context) {
throw new FopImageException("Error with image URL: "
+ e_context.getMessage());
} catch (Exception e) {
// maybe relative
URL context_url = null;
String base = Configuration.getStringValue("baseDir");
if(base == null) {
throw new FopImageException("Error with image URL: "
+ e.getMessage()
+ " and no base directory is specified");
}
try {
absoluteURL = new URL(Configuration.getStringValue("baseDir")
+ absoluteURL.getFile());
} catch (MalformedURLException e_context) {
// pb context url
throw new FopImageException("Invalid Image URL - error on relative URL : "
+ e_context.getMessage());
}
}
// check if already created
FopImage imageObject = (FopImage)m_urlMap.get(absoluteURL.toString());
if (imageObject != null)
return imageObject;
// If not, check image type
ImageReader imgReader = null;
try {
if (imgIS == null) {
imgIS = absoluteURL.openStream();
}
imgReader = ImageReaderFactory.Make(absoluteURL.toExternalForm(),
imgIS);
} catch (Exception e) {
throw new FopImageException("Error while recovering Image Informations ("
+ absoluteURL.toString() + ") : "
+ e.getMessage());
}
finally {
if (imgIS != null) {
try {
imgIS.close();
} catch (IOException e) {}
}
}
if (imgReader == null)
throw new FopImageException("No ImageReader for this type of image ("
+ absoluteURL.toString() + ")");
// Associate mime-type to FopImage class
String imgMimeType = imgReader.getMimeType();
String imgClassName = null;
if ("image/gif".equals(imgMimeType)) {
imgClassName = "org.apache.fop.image.GifImage";
// imgClassName = "org.apache.fop.image.JAIImage";
} else if ("image/jpeg".equals(imgMimeType)) {
imgClassName = "org.apache.fop.image.JpegImage";
// imgClassName = "org.apache.fop.image.JAIImage";
} else if ("image/bmp".equals(imgMimeType)) {
imgClassName = "org.apache.fop.image.BmpImage";
// imgClassName = "org.apache.fop.image.JAIImage";
} else if ("image/png".equals(imgMimeType)) {
imgClassName = "org.apache.fop.image.JimiImage";
// imgClassName = "org.apache.fop.image.JAIImage";
} else if ("image/tga".equals(imgMimeType)) {
imgClassName = "org.apache.fop.image.JimiImage";
// imgClassName = "org.apache.fop.image.JAIImage";
} else if ("image/tiff".equals(imgMimeType)) {
imgClassName = "org.apache.fop.image.JimiImage";
// imgClassName = "org.apache.fop.image.JAIImage";
} else if ("image/svg+xml".equals(imgMimeType)) {
imgClassName = "org.apache.fop.image.SVGImage";
}
if (imgClassName == null)
throw new FopImageException("Unsupported image type ("
+ absoluteURL.toString() + ") : "
+ imgMimeType);
// load the right image class
// return new <FopImage implementing class>
Object imageInstance = null;
Class imageClass = null;
try {
imageClass = Class.forName(imgClassName);
Class[] imageConstructorParameters = new Class[2];
imageConstructorParameters[0] = Class.forName("java.net.URL");
imageConstructorParameters[1] =
Class.forName("org.apache.fop.image.analyser.ImageReader");
Constructor imageConstructor =
imageClass.getDeclaredConstructor(imageConstructorParameters);
Object[] initArgs = new Object[2];
initArgs[0] = absoluteURL;
initArgs[1] = imgReader;
imageInstance = imageConstructor.newInstance(initArgs);
} catch (java.lang.reflect.InvocationTargetException ex) {
Throwable t = ex.getTargetException();
String msg;
if (t != null) {
msg = t.getMessage();
} else {
msg = ex.getMessage();
}
throw new FopImageException("Error creating FopImage object ("
+ absoluteURL.toString() + ") : "
+ msg);
} catch (Exception ex) {
throw new FopImageException("Error creating FopImage object ("
+ "Error creating FopImage object ("
+ absoluteURL.toString() + ") : "
+ ex.getMessage());
}
if (!(imageInstance instanceof org.apache.fop.image.FopImage)) {
throw new FopImageException("Error creating FopImage object ("
+ absoluteURL.toString() + ") : "
+ "class " + imageClass.getName()
+ " doesn't implement org.apache.fop.image.FopImage interface");
}
m_urlMap.put(absoluteURL.toString(), imageInstance);
return (FopImage)imageInstance;
}
|
diff --git a/pmd/src/net/sourceforge/pmd/lang/xml/ast/XmlParser.java b/pmd/src/net/sourceforge/pmd/lang/xml/ast/XmlParser.java
index dae9fb462..1d5b2b1b9 100644
--- a/pmd/src/net/sourceforge/pmd/lang/xml/ast/XmlParser.java
+++ b/pmd/src/net/sourceforge/pmd/lang/xml/ast/XmlParser.java
@@ -1,157 +1,157 @@
/**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.xml.ast;
import java.io.IOException;
import java.io.Reader;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import net.sourceforge.pmd.lang.ast.ParseException;
import net.sourceforge.pmd.lang.ast.RootNode;
import net.sourceforge.pmd.lang.ast.xpath.Attribute;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.Text;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class XmlParser {
protected Map<Node, XmlNode> nodeCache = new HashMap<Node, XmlNode>();
protected Document parseDocument(Reader reader) throws ParseException {
nodeCache.clear();
try {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(new InputSource(reader));
return document;
} catch (ParserConfigurationException e) {
throw new ParseException(e);
} catch (SAXException e) {
throw new ParseException(e);
} catch (IOException e) {
throw new ParseException(e);
}
}
public XmlNode parse(Reader reader) {
Document document = parseDocument(reader);
return createProxy(document.getDocumentElement());
}
public XmlNode createProxy(Node node) {
XmlNode proxy = nodeCache.get(node);
if (proxy != null) {
return proxy;
}
// TODO Change Parser interface to take ClassLoader?
LinkedHashSet<Class<?>> interfaces = new LinkedHashSet<Class<?>>();
interfaces.add(XmlNode.class);
if (node.getParentNode() instanceof Document) {
interfaces.add(RootNode.class);
}
addAllInterfaces(interfaces, node.getClass());
proxy = (XmlNode) Proxy.newProxyInstance(XmlParser.class.getClassLoader(), interfaces
.toArray(new Class[interfaces.size()]), new XmlNodeInvocationHandler(node));
nodeCache.put(node, proxy);
return proxy;
}
public void addAllInterfaces(Set<Class<?>> interfaces, Class<?> clazz) {
interfaces.addAll(Arrays.asList((Class<?>[]) clazz.getInterfaces()));
if (clazz.getSuperclass() != null) {
addAllInterfaces(interfaces, clazz.getSuperclass());
}
}
public class XmlNodeInvocationHandler implements InvocationHandler {
private final Node node;
public XmlNodeInvocationHandler(Node node) {
this.node = node;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// XmlNode method?
if (method.getDeclaringClass().isAssignableFrom(XmlNode.class)
&& !"java.lang.Object".equals(method.getDeclaringClass().getName())) {
if ("jjtGetNumChildren".equals(method.getName())) {
return node.hasChildNodes() ? node.getChildNodes().getLength() : 0;
} else if ("jjtGetChild".equals(method.getName())) {
return createProxy(node.getChildNodes().item(((Integer) args[0]).intValue()));
} else if ("getImage".equals(method.getName())) {
if (node instanceof Text) {
return ((Text) node).getData();
} else {
return null;
}
} else if ("jjtGetParent".equals(method.getName())) {
Node parent = node.getParentNode();
if (parent != null && !(parent instanceof Document)) {
return createProxy(parent);
} else {
return null;
}
} else if ("getAttributeIterator".equals(method.getName())) {
final NamedNodeMap attributes = node.getAttributes();
return new Iterator<Attribute>() {
private int index;
public boolean hasNext() {
return attributes != null && index < attributes.getLength();
}
public Attribute next() {
Node attributeNode = attributes.item(index++);
return new Attribute(createProxy(node), attributeNode.getNodeName(), attributeNode
.getNodeValue());
}
public void remove() {
throw new UnsupportedOperationException();
}
};
} else if ("getBeginLine".equals(method.getName())) {
return Integer.valueOf(-1);
} else if ("getBeginColumn".equals(method.getName())) {
return Integer.valueOf(-1);
} else if ("getEndLine".equals(method.getName())) {
return Integer.valueOf(-1);
} else if ("getEndColumn".equals(method.getName())) {
return Integer.valueOf(-1);
} else if ("getNode".equals(method.getName())) {
return node;
}
throw new UnsupportedOperationException("Method not supported for XmlNode: " + method);
}
// Delegate method
else {
if ("toString".equals(method.getName())) {
String s = ((Node) node).getNodeName();
- s = s.replace('#', '');
+ s = s.replace("#", "");
return s;
}
Object result = method.invoke(node, args);
return result;
}
}
}
}
| true | true | public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// XmlNode method?
if (method.getDeclaringClass().isAssignableFrom(XmlNode.class)
&& !"java.lang.Object".equals(method.getDeclaringClass().getName())) {
if ("jjtGetNumChildren".equals(method.getName())) {
return node.hasChildNodes() ? node.getChildNodes().getLength() : 0;
} else if ("jjtGetChild".equals(method.getName())) {
return createProxy(node.getChildNodes().item(((Integer) args[0]).intValue()));
} else if ("getImage".equals(method.getName())) {
if (node instanceof Text) {
return ((Text) node).getData();
} else {
return null;
}
} else if ("jjtGetParent".equals(method.getName())) {
Node parent = node.getParentNode();
if (parent != null && !(parent instanceof Document)) {
return createProxy(parent);
} else {
return null;
}
} else if ("getAttributeIterator".equals(method.getName())) {
final NamedNodeMap attributes = node.getAttributes();
return new Iterator<Attribute>() {
private int index;
public boolean hasNext() {
return attributes != null && index < attributes.getLength();
}
public Attribute next() {
Node attributeNode = attributes.item(index++);
return new Attribute(createProxy(node), attributeNode.getNodeName(), attributeNode
.getNodeValue());
}
public void remove() {
throw new UnsupportedOperationException();
}
};
} else if ("getBeginLine".equals(method.getName())) {
return Integer.valueOf(-1);
} else if ("getBeginColumn".equals(method.getName())) {
return Integer.valueOf(-1);
} else if ("getEndLine".equals(method.getName())) {
return Integer.valueOf(-1);
} else if ("getEndColumn".equals(method.getName())) {
return Integer.valueOf(-1);
} else if ("getNode".equals(method.getName())) {
return node;
}
throw new UnsupportedOperationException("Method not supported for XmlNode: " + method);
}
// Delegate method
else {
if ("toString".equals(method.getName())) {
String s = ((Node) node).getNodeName();
s = s.replace('#', '');
return s;
}
Object result = method.invoke(node, args);
return result;
}
}
| public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// XmlNode method?
if (method.getDeclaringClass().isAssignableFrom(XmlNode.class)
&& !"java.lang.Object".equals(method.getDeclaringClass().getName())) {
if ("jjtGetNumChildren".equals(method.getName())) {
return node.hasChildNodes() ? node.getChildNodes().getLength() : 0;
} else if ("jjtGetChild".equals(method.getName())) {
return createProxy(node.getChildNodes().item(((Integer) args[0]).intValue()));
} else if ("getImage".equals(method.getName())) {
if (node instanceof Text) {
return ((Text) node).getData();
} else {
return null;
}
} else if ("jjtGetParent".equals(method.getName())) {
Node parent = node.getParentNode();
if (parent != null && !(parent instanceof Document)) {
return createProxy(parent);
} else {
return null;
}
} else if ("getAttributeIterator".equals(method.getName())) {
final NamedNodeMap attributes = node.getAttributes();
return new Iterator<Attribute>() {
private int index;
public boolean hasNext() {
return attributes != null && index < attributes.getLength();
}
public Attribute next() {
Node attributeNode = attributes.item(index++);
return new Attribute(createProxy(node), attributeNode.getNodeName(), attributeNode
.getNodeValue());
}
public void remove() {
throw new UnsupportedOperationException();
}
};
} else if ("getBeginLine".equals(method.getName())) {
return Integer.valueOf(-1);
} else if ("getBeginColumn".equals(method.getName())) {
return Integer.valueOf(-1);
} else if ("getEndLine".equals(method.getName())) {
return Integer.valueOf(-1);
} else if ("getEndColumn".equals(method.getName())) {
return Integer.valueOf(-1);
} else if ("getNode".equals(method.getName())) {
return node;
}
throw new UnsupportedOperationException("Method not supported for XmlNode: " + method);
}
// Delegate method
else {
if ("toString".equals(method.getName())) {
String s = ((Node) node).getNodeName();
s = s.replace("#", "");
return s;
}
Object result = method.invoke(node, args);
return result;
}
}
|
diff --git a/src/org/apache/xalan/xsltc/compiler/Predicate.java b/src/org/apache/xalan/xsltc/compiler/Predicate.java
index 9591f4c7..2b80346d 100644
--- a/src/org/apache/xalan/xsltc/compiler/Predicate.java
+++ b/src/org/apache/xalan/xsltc/compiler/Predicate.java
@@ -1,588 +1,590 @@
/*
* @(#)$Id$
*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 2001-2003 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 2001, Sun
* Microsystems., http://www.sun.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* @author Jacek Ambroziak
* @author Santiago Pericas-Geertsen
* @author Morten Jorgensen
*
*/
package org.apache.xalan.xsltc.compiler;
import java.util.ArrayList;
import org.apache.bcel.classfile.Field;
import org.apache.bcel.generic.ASTORE;
import org.apache.bcel.generic.CHECKCAST;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.GETFIELD;
import org.apache.bcel.generic.INVOKESPECIAL;
import org.apache.bcel.generic.InstructionList;
import org.apache.bcel.generic.LocalVariableGen;
import org.apache.bcel.generic.NEW;
import org.apache.bcel.generic.PUSH;
import org.apache.bcel.generic.PUTFIELD;
import org.apache.xalan.xsltc.compiler.util.BooleanType;
import org.apache.xalan.xsltc.compiler.util.ClassGenerator;
import org.apache.xalan.xsltc.compiler.util.FilterGenerator;
import org.apache.xalan.xsltc.compiler.util.IntType;
import org.apache.xalan.xsltc.compiler.util.MethodGenerator;
import org.apache.xalan.xsltc.compiler.util.NumberType;
import org.apache.xalan.xsltc.compiler.util.ReferenceType;
import org.apache.xalan.xsltc.compiler.util.ResultTreeType;
import org.apache.xalan.xsltc.compiler.util.TestGenerator;
import org.apache.xalan.xsltc.compiler.util.Type;
import org.apache.xalan.xsltc.compiler.util.TypeCheckError;
import org.apache.xalan.xsltc.compiler.util.Util;
final class Predicate extends Expression implements Closure {
private Expression _exp = null; // Expression to be compiled inside pred.
private boolean _nthPositionFilter = false;
private boolean _nthDescendant = false;
private boolean _canOptimize = true;
private int _ptype = -1;
private String _className = null;
private ArrayList _closureVars = null;
private Closure _parentClosure = null;
public Predicate(Expression exp) {
(_exp = exp).setParent(this);
}
public void setParser(Parser parser) {
super.setParser(parser);
_exp.setParser(parser);
}
public boolean isNthDescendant() {
return _nthDescendant;
}
public boolean isNthPositionFilter() {
return _nthPositionFilter;
}
public void dontOptimize() {
_canOptimize = false;
}
// -- Begin Closure interface --------------------
/**
* Returns true if this closure is compiled in an inner class (i.e.
* if this is a real closure).
*/
public boolean inInnerClass() {
return (_className != null);
}
/**
* Returns a reference to its parent closure or null if outermost.
*/
public Closure getParentClosure() {
if (_parentClosure == null) {
SyntaxTreeNode node = getParent();
do {
if (node instanceof Closure) {
_parentClosure = (Closure) node;
break;
}
if (node instanceof TopLevelElement) {
break; // way up in the tree
}
node = node.getParent();
} while (node != null);
}
return _parentClosure;
}
/**
* Returns the name of the auxiliary class or null if this predicate
* is compiled inside the Translet.
*/
public String getInnerClassName() {
return _className;
}
/**
* Add new variable to the closure.
*/
public void addVariable(VariableRefBase variableRef) {
if (_closureVars == null) {
_closureVars = new ArrayList();
}
// Only one reference per variable
if (!_closureVars.contains(variableRef)) {
_closureVars.add(variableRef);
// Add variable to parent closure as well
Closure parentClosure = getParentClosure();
if (parentClosure != null) {
parentClosure.addVariable(variableRef);
}
}
}
// -- End Closure interface ----------------------
public int getPosType() {
if (_ptype == -1) {
SyntaxTreeNode parent = getParent();
if (parent instanceof StepPattern) {
_ptype = ((StepPattern)parent).getNodeType();
}
else if (parent instanceof AbsoluteLocationPath) {
AbsoluteLocationPath path = (AbsoluteLocationPath)parent;
Expression exp = path.getPath();
if (exp instanceof Step) {
_ptype = ((Step)exp).getNodeType();
}
}
else if (parent instanceof VariableRefBase) {
final VariableRefBase ref = (VariableRefBase)parent;
final VariableBase var = ref.getVariable();
final Expression exp = var.getExpression();
if (exp instanceof Step) {
_ptype = ((Step)exp).getNodeType();
}
}
else if (parent instanceof Step) {
_ptype = ((Step)parent).getNodeType();
}
}
return _ptype;
}
public boolean parentIsPattern() {
return (getParent() instanceof Pattern);
}
public Expression getExpr() {
return _exp;
}
public String toString() {
if (isNthPositionFilter())
return "pred([" + _exp + "],"+getPosType()+")";
else
return "pred(" + _exp + ')';
}
/**
* Type check a predicate expression. If the type of the expression is
* number convert it to boolean by adding a comparison with position().
* Note that if the expression is a parameter, we cannot distinguish
* at compile time if its type is number or not. Hence, expressions of
* reference type are always converted to booleans.
*/
public Type typeCheck(SymbolTable stable) throws TypeCheckError {
Type texp = _exp.typeCheck(stable);
// We need explicit type information for reference types - no good!
if (texp instanceof ReferenceType) {
_exp = new CastExpr(_exp, texp = Type.Real);
}
// A result tree fragment should not be cast directly to a number type,
// but rather to a boolean value, and then to a numer (0 or 1).
// Ref. section 11.2 of the XSLT 1.0 spec
if (texp instanceof ResultTreeType) {
_exp = new CastExpr(_exp, Type.Boolean);
_exp = new CastExpr(_exp, Type.Real);
texp = _exp.typeCheck(stable);
}
// Numerical types will be converted to a position filter
if (texp instanceof NumberType) {
// Cast any numerical types to an integer
if (texp instanceof IntType == false) {
_exp = new CastExpr(_exp, Type.Int);
}
SyntaxTreeNode parent = getParent();
// Expand [last()] into [position() = last()]
if ((_exp instanceof LastCall) ||
(parent instanceof Pattern) ||
(parent instanceof FilterExpr)) {
if (parent instanceof Pattern && !(_exp instanceof LastCall)) {
_nthPositionFilter = _canOptimize;
}
else if (parent instanceof FilterExpr) {
FilterExpr filter = (FilterExpr)parent;
Expression fexp = filter.getExpr();
if (fexp instanceof KeyCall)
_canOptimize = false;
else if (fexp instanceof VariableRefBase)
_canOptimize = false;
else if (fexp instanceof ParentLocationPath)
_canOptimize = false;
+ else if (fexp instanceof FilterParentPath)
+ _canOptimize = false;
else if (fexp instanceof UnionPathExpr)
_canOptimize = false;
else if (_exp.hasPositionCall() && _exp.hasLastCall())
_canOptimize = false;
else if (filter.getParent() instanceof FilterParentPath)
_canOptimize = false;
if (_canOptimize)
_nthPositionFilter = true;
}
// If this case can be optimized, leave the expression as
// an integer. Otherwise, turn it into a comparison with
// the position() function.
if (_nthPositionFilter) {
return _type = Type.NodeSet;
} else {
final QName position =
getParser().getQNameIgnoreDefaultNs("position");
final PositionCall positionCall =
new PositionCall(position);
positionCall.setParser(getParser());
positionCall.setParent(this);
_exp = new EqualityExpr(EqualityExpr.EQ, positionCall,
_exp);
if (_exp.typeCheck(stable) != Type.Boolean) {
_exp = new CastExpr(_exp, Type.Boolean);
}
return _type = Type.Boolean;
}
}
// Use NthPositionIterator to handle [position()] or [a]
else {
if ((parent != null) && (parent instanceof Step)) {
parent = parent.getParent();
if ((parent != null) &&
(parent instanceof AbsoluteLocationPath)) {
// TODO: Special case for "//*[n]" pattern....
_nthDescendant = true;
return _type = Type.NodeSet;
}
}
_nthPositionFilter = true;
return _type = Type.NodeSet;
}
}
else if (texp instanceof BooleanType) {
if (_exp.hasPositionCall())
_nthPositionFilter = true;
}
// All other types will be handled as boolean values
else {
_exp = new CastExpr(_exp, Type.Boolean);
}
_nthPositionFilter = false;
return _type = Type.Boolean;
}
/**
* Create a new "Filter" class implementing
* <code>CurrentNodeListFilter</code>. Allocate registers for local
* variables and local parameters passed in the closure to test().
* Notice that local variables need to be "unboxed".
*/
private void compileFilter(ClassGenerator classGen,
MethodGenerator methodGen) {
TestGenerator testGen;
LocalVariableGen local;
FilterGenerator filterGen;
_className = getXSLTC().getHelperClassName();
filterGen = new FilterGenerator(_className,
"java.lang.Object",
toString(),
ACC_PUBLIC | ACC_SUPER,
new String[] {
CURRENT_NODE_LIST_FILTER
},
classGen.getStylesheet());
final ConstantPoolGen cpg = filterGen.getConstantPool();
final int length = (_closureVars == null) ? 0 : _closureVars.size();
// Add a new instance variable for each var in closure
for (int i = 0; i < length; i++) {
VariableBase var = ((VariableRefBase) _closureVars.get(i)).getVariable();
filterGen.addField(new Field(ACC_PUBLIC,
cpg.addUtf8(var.getVariable()),
cpg.addUtf8(var.getType().toSignature()),
null, cpg.getConstantPool()));
}
final InstructionList il = new InstructionList();
testGen = new TestGenerator(ACC_PUBLIC | ACC_FINAL,
org.apache.bcel.generic.Type.BOOLEAN,
new org.apache.bcel.generic.Type[] {
org.apache.bcel.generic.Type.INT,
org.apache.bcel.generic.Type.INT,
org.apache.bcel.generic.Type.INT,
org.apache.bcel.generic.Type.INT,
Util.getJCRefType(TRANSLET_SIG),
Util.getJCRefType(NODE_ITERATOR_SIG)
},
new String[] {
"node",
"position",
"last",
"current",
"translet",
"iterator"
},
"test", _className, il, cpg);
// Store the dom in a local variable
local = testGen.addLocalVariable("document",
Util.getJCRefType(DOM_INTF_SIG),
null, null);
final String className = classGen.getClassName();
il.append(filterGen.loadTranslet());
il.append(new CHECKCAST(cpg.addClass(className)));
il.append(new GETFIELD(cpg.addFieldref(className,
DOM_FIELD, DOM_INTF_SIG)));
il.append(new ASTORE(local.getIndex()));
// Store the dom index in the test generator
testGen.setDomIndex(local.getIndex());
_exp.translate(filterGen, testGen);
il.append(IRETURN);
testGen.stripAttributes(true);
testGen.setMaxLocals();
testGen.setMaxStack();
testGen.removeNOPs();
filterGen.addEmptyConstructor(ACC_PUBLIC);
filterGen.addMethod(testGen.getMethod());
getXSLTC().dumpClass(filterGen.getJavaClass());
}
/**
* Returns true if the predicate is a test for the existance of an
* element or attribute. All we have to do is to get the first node
* from the step, check if it is there, and then return true/false.
*/
public boolean isBooleanTest() {
return (_exp instanceof BooleanExpr);
}
/**
* Method to see if we can optimise the predicate by using a specialised
* iterator for expressions like '/foo/bar[@attr = $var]', which are
* very common in many stylesheets
*/
public boolean isNodeValueTest() {
if (!_canOptimize) return false;
return (getStep() != null && getCompareValue() != null);
}
private Expression _value = null;
private Step _step = null;
/**
* Utility method for optimisation. See isNodeValueTest()
*/
public Expression getCompareValue() {
if (_value != null) return _value;
if (_exp == null) return null;
if (_exp instanceof EqualityExpr) {
EqualityExpr exp = (EqualityExpr)_exp;
Expression left = exp.getLeft();
Expression right = exp.getRight();
Type tleft = left.getType();
Type tright = right.getType();
if (left instanceof CastExpr) left = ((CastExpr)left).getExpr();
if (right instanceof CastExpr) right = ((CastExpr)right).getExpr();
try {
if ((tleft == Type.String) && (!(left instanceof Step)))
_value = exp.getLeft();
if (left instanceof VariableRefBase)
_value = new CastExpr(left, Type.String);
if (_value != null) return _value;
}
catch (TypeCheckError e) { }
try {
if ((tright == Type.String) && (!(right instanceof Step)))
_value = exp.getRight();
if (right instanceof VariableRefBase)
_value = new CastExpr(right, Type.String);
if (_value != null) return _value;
}
catch (TypeCheckError e) { }
}
return null;
}
/**
* Utility method for optimisation. See isNodeValueTest()
*/
public Step getStep() {
if (_step != null) return _step;
if (_exp == null) return null;
if (_exp instanceof EqualityExpr) {
EqualityExpr exp = (EqualityExpr)_exp;
Expression left = exp.getLeft();
Expression right = exp.getRight();
if (left instanceof CastExpr) left = ((CastExpr)left).getExpr();
if (left instanceof Step) _step = (Step)left;
if (right instanceof CastExpr) right = ((CastExpr)right).getExpr();
if (right instanceof Step) _step = (Step)right;
}
return _step;
}
/**
* Translate a predicate expression. This translation pushes
* two references on the stack: a reference to a newly created
* filter object and a reference to the predicate's closure.
*/
public void translate(ClassGenerator classGen, MethodGenerator methodGen) {
final ConstantPoolGen cpg = classGen.getConstantPool();
final InstructionList il = methodGen.getInstructionList();
if (_nthPositionFilter || _nthDescendant) {
_exp.translate(classGen, methodGen);
}
else if (isNodeValueTest() && (getParent() instanceof Step)) {
_value.translate(classGen, methodGen);
il.append(new CHECKCAST(cpg.addClass(STRING_CLASS)));
il.append(new PUSH(cpg, ((EqualityExpr)_exp).getOp()));
}
else {
translateFilter(classGen, methodGen);
}
}
/**
* Translate a predicate expression. This translation pushes
* two references on the stack: a reference to a newly created
* filter object and a reference to the predicate's closure.
*/
public void translateFilter(ClassGenerator classGen,
MethodGenerator methodGen)
{
final ConstantPoolGen cpg = classGen.getConstantPool();
final InstructionList il = methodGen.getInstructionList();
// Compile auxiliary class for filter
compileFilter(classGen, methodGen);
// Create new instance of filter
il.append(new NEW(cpg.addClass(_className)));
il.append(DUP);
il.append(new INVOKESPECIAL(cpg.addMethodref(_className,
"<init>", "()V")));
// Initialize closure variables
final int length = (_closureVars == null) ? 0 : _closureVars.size();
for (int i = 0; i < length; i++) {
VariableRefBase varRef = (VariableRefBase) _closureVars.get(i);
VariableBase var = varRef.getVariable();
Type varType = var.getType();
il.append(DUP);
// Find nearest closure implemented as an inner class
Closure variableClosure = _parentClosure;
while (variableClosure != null) {
if (variableClosure.inInnerClass()) break;
variableClosure = variableClosure.getParentClosure();
}
// Use getfield if in an inner class
if (variableClosure != null) {
il.append(ALOAD_0);
il.append(new GETFIELD(
cpg.addFieldref(variableClosure.getInnerClassName(),
var.getVariable(), varType.toSignature())));
}
else {
// Use a load of instruction if in translet class
il.append(var.loadInstruction());
}
// Store variable in new closure
il.append(new PUTFIELD(
cpg.addFieldref(_className, var.getVariable(),
varType.toSignature())));
}
}
}
| true | true | public Type typeCheck(SymbolTable stable) throws TypeCheckError {
Type texp = _exp.typeCheck(stable);
// We need explicit type information for reference types - no good!
if (texp instanceof ReferenceType) {
_exp = new CastExpr(_exp, texp = Type.Real);
}
// A result tree fragment should not be cast directly to a number type,
// but rather to a boolean value, and then to a numer (0 or 1).
// Ref. section 11.2 of the XSLT 1.0 spec
if (texp instanceof ResultTreeType) {
_exp = new CastExpr(_exp, Type.Boolean);
_exp = new CastExpr(_exp, Type.Real);
texp = _exp.typeCheck(stable);
}
// Numerical types will be converted to a position filter
if (texp instanceof NumberType) {
// Cast any numerical types to an integer
if (texp instanceof IntType == false) {
_exp = new CastExpr(_exp, Type.Int);
}
SyntaxTreeNode parent = getParent();
// Expand [last()] into [position() = last()]
if ((_exp instanceof LastCall) ||
(parent instanceof Pattern) ||
(parent instanceof FilterExpr)) {
if (parent instanceof Pattern && !(_exp instanceof LastCall)) {
_nthPositionFilter = _canOptimize;
}
else if (parent instanceof FilterExpr) {
FilterExpr filter = (FilterExpr)parent;
Expression fexp = filter.getExpr();
if (fexp instanceof KeyCall)
_canOptimize = false;
else if (fexp instanceof VariableRefBase)
_canOptimize = false;
else if (fexp instanceof ParentLocationPath)
_canOptimize = false;
else if (fexp instanceof UnionPathExpr)
_canOptimize = false;
else if (_exp.hasPositionCall() && _exp.hasLastCall())
_canOptimize = false;
else if (filter.getParent() instanceof FilterParentPath)
_canOptimize = false;
if (_canOptimize)
_nthPositionFilter = true;
}
// If this case can be optimized, leave the expression as
// an integer. Otherwise, turn it into a comparison with
// the position() function.
if (_nthPositionFilter) {
return _type = Type.NodeSet;
} else {
final QName position =
getParser().getQNameIgnoreDefaultNs("position");
final PositionCall positionCall =
new PositionCall(position);
positionCall.setParser(getParser());
positionCall.setParent(this);
_exp = new EqualityExpr(EqualityExpr.EQ, positionCall,
_exp);
if (_exp.typeCheck(stable) != Type.Boolean) {
_exp = new CastExpr(_exp, Type.Boolean);
}
return _type = Type.Boolean;
}
}
// Use NthPositionIterator to handle [position()] or [a]
else {
if ((parent != null) && (parent instanceof Step)) {
parent = parent.getParent();
if ((parent != null) &&
(parent instanceof AbsoluteLocationPath)) {
// TODO: Special case for "//*[n]" pattern....
_nthDescendant = true;
return _type = Type.NodeSet;
}
}
_nthPositionFilter = true;
return _type = Type.NodeSet;
}
}
else if (texp instanceof BooleanType) {
if (_exp.hasPositionCall())
_nthPositionFilter = true;
}
// All other types will be handled as boolean values
else {
_exp = new CastExpr(_exp, Type.Boolean);
}
_nthPositionFilter = false;
return _type = Type.Boolean;
}
| public Type typeCheck(SymbolTable stable) throws TypeCheckError {
Type texp = _exp.typeCheck(stable);
// We need explicit type information for reference types - no good!
if (texp instanceof ReferenceType) {
_exp = new CastExpr(_exp, texp = Type.Real);
}
// A result tree fragment should not be cast directly to a number type,
// but rather to a boolean value, and then to a numer (0 or 1).
// Ref. section 11.2 of the XSLT 1.0 spec
if (texp instanceof ResultTreeType) {
_exp = new CastExpr(_exp, Type.Boolean);
_exp = new CastExpr(_exp, Type.Real);
texp = _exp.typeCheck(stable);
}
// Numerical types will be converted to a position filter
if (texp instanceof NumberType) {
// Cast any numerical types to an integer
if (texp instanceof IntType == false) {
_exp = new CastExpr(_exp, Type.Int);
}
SyntaxTreeNode parent = getParent();
// Expand [last()] into [position() = last()]
if ((_exp instanceof LastCall) ||
(parent instanceof Pattern) ||
(parent instanceof FilterExpr)) {
if (parent instanceof Pattern && !(_exp instanceof LastCall)) {
_nthPositionFilter = _canOptimize;
}
else if (parent instanceof FilterExpr) {
FilterExpr filter = (FilterExpr)parent;
Expression fexp = filter.getExpr();
if (fexp instanceof KeyCall)
_canOptimize = false;
else if (fexp instanceof VariableRefBase)
_canOptimize = false;
else if (fexp instanceof ParentLocationPath)
_canOptimize = false;
else if (fexp instanceof FilterParentPath)
_canOptimize = false;
else if (fexp instanceof UnionPathExpr)
_canOptimize = false;
else if (_exp.hasPositionCall() && _exp.hasLastCall())
_canOptimize = false;
else if (filter.getParent() instanceof FilterParentPath)
_canOptimize = false;
if (_canOptimize)
_nthPositionFilter = true;
}
// If this case can be optimized, leave the expression as
// an integer. Otherwise, turn it into a comparison with
// the position() function.
if (_nthPositionFilter) {
return _type = Type.NodeSet;
} else {
final QName position =
getParser().getQNameIgnoreDefaultNs("position");
final PositionCall positionCall =
new PositionCall(position);
positionCall.setParser(getParser());
positionCall.setParent(this);
_exp = new EqualityExpr(EqualityExpr.EQ, positionCall,
_exp);
if (_exp.typeCheck(stable) != Type.Boolean) {
_exp = new CastExpr(_exp, Type.Boolean);
}
return _type = Type.Boolean;
}
}
// Use NthPositionIterator to handle [position()] or [a]
else {
if ((parent != null) && (parent instanceof Step)) {
parent = parent.getParent();
if ((parent != null) &&
(parent instanceof AbsoluteLocationPath)) {
// TODO: Special case for "//*[n]" pattern....
_nthDescendant = true;
return _type = Type.NodeSet;
}
}
_nthPositionFilter = true;
return _type = Type.NodeSet;
}
}
else if (texp instanceof BooleanType) {
if (_exp.hasPositionCall())
_nthPositionFilter = true;
}
// All other types will be handled as boolean values
else {
_exp = new CastExpr(_exp, Type.Boolean);
}
_nthPositionFilter = false;
return _type = Type.Boolean;
}
|
diff --git a/src/org/ubergibson/campfireclient/ConsoleClient.java b/src/org/ubergibson/campfireclient/ConsoleClient.java
index 7aebf66..d122bea 100644
--- a/src/org/ubergibson/campfireclient/ConsoleClient.java
+++ b/src/org/ubergibson/campfireclient/ConsoleClient.java
@@ -1,108 +1,108 @@
package org.ubergibson.campfireclient;
import gnu.getopt.Getopt;
import java.io.*;
public class ConsoleClient extends CampfireClient implements MessageHandler {
private static String ccVersion = "0.1dev";
public ConsoleClient(String user, String pass, String sub, boolean ssl) throws Exception {
super(user, pass, sub, ssl);
super.setMessageHandler(this);
}
public void handleMessage(Message newMsg) {
try {
int ASCII_ESCAPE = 27;
System.out.printf("%c[34;47m%s%c[0m: %s\n", ASCII_ESCAPE, newMsg.getFrom().getName(), ASCII_ESCAPE, newMsg.getMessage());
//System.out.println(newMsg.getFrom().getName()+": "+newMsg.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
}
private static void usage() {
System.out.println(
"Usage: java ConsoleClient -u username -p password -s subdomain");
System.exit(1);
}
public static void main(String [] args) throws Exception {
String user;
String pass;
String subdomain;
user = pass = subdomain = "";
boolean useSSL = false;
// parse command line parameters
Getopt g = new Getopt("ConsoleClient", args, "u:p:s:hS");
int c;
while ((c = g.getopt()) != -1) {
switch (c) {
case 'u':
user = String.valueOf(g.getOptarg());
break;
case 'p':
pass = String.valueOf(g.getOptarg());
break;
case 's':
subdomain = String.valueOf(g.getOptarg());
break;
case 'S':
useSSL = true;
break;
case 'h':
// fall through
default:
case '?':
usage();
break;
}
}
if(user == "" || pass == "" || subdomain == "") {
System.out.println("Error: missing required arguments.");
usage();
}
//clear screen
System.out.printf("%c[2J", 27);
System.out.printf("%c[31;40mConsoleClient %s%c[0m\n", 27, ccVersion, 27);
if(useSSL) {
- System.out.println("Using SSL.");
+ System.out.println("> Using SSL.");
} else {
- System.out.println("Not using SSL.");
+ System.out.println("> Not using SSL.");
}
- System.out.println("Connecting...");
+ System.out.println("> Connecting...");
ConsoleClient cc = new ConsoleClient(user, pass, subdomain, useSSL);
- System.out.println("Now connected to \""+subdomain+".campfirenow.com\"");
+ System.out.println("> Now connected to \""+subdomain+".campfirenow.com\"");
showCommands();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String curLine = "";
while((curLine = br.readLine()) != null) {
if(curLine.startsWith("/quit")) {
break;
} else if(curLine.startsWith("/join")) {
- System.out.println("Joining room...");
+ System.out.println("> Joining room...");
cc.joinRoom(curLine.substring(6));
- System.out.println("Now chatting in \""+curLine.substring(6)+"\"");
+ System.out.println("> Now chatting in \""+curLine.substring(6)+"\"");
} else if(curLine.startsWith("/")) {
showCommands();
} else {
cc.sendMessage(curLine);
}
}
cc.leaveCurrentRoom();
cc.logOut();
}
private static void showCommands() {
System.out.println("Available commands: /join <room>, /quit");
}
}
| false | true | public static void main(String [] args) throws Exception {
String user;
String pass;
String subdomain;
user = pass = subdomain = "";
boolean useSSL = false;
// parse command line parameters
Getopt g = new Getopt("ConsoleClient", args, "u:p:s:hS");
int c;
while ((c = g.getopt()) != -1) {
switch (c) {
case 'u':
user = String.valueOf(g.getOptarg());
break;
case 'p':
pass = String.valueOf(g.getOptarg());
break;
case 's':
subdomain = String.valueOf(g.getOptarg());
break;
case 'S':
useSSL = true;
break;
case 'h':
// fall through
default:
case '?':
usage();
break;
}
}
if(user == "" || pass == "" || subdomain == "") {
System.out.println("Error: missing required arguments.");
usage();
}
//clear screen
System.out.printf("%c[2J", 27);
System.out.printf("%c[31;40mConsoleClient %s%c[0m\n", 27, ccVersion, 27);
if(useSSL) {
System.out.println("Using SSL.");
} else {
System.out.println("Not using SSL.");
}
System.out.println("Connecting...");
ConsoleClient cc = new ConsoleClient(user, pass, subdomain, useSSL);
System.out.println("Now connected to \""+subdomain+".campfirenow.com\"");
showCommands();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String curLine = "";
while((curLine = br.readLine()) != null) {
if(curLine.startsWith("/quit")) {
break;
} else if(curLine.startsWith("/join")) {
System.out.println("Joining room...");
cc.joinRoom(curLine.substring(6));
System.out.println("Now chatting in \""+curLine.substring(6)+"\"");
} else if(curLine.startsWith("/")) {
showCommands();
} else {
cc.sendMessage(curLine);
}
}
cc.leaveCurrentRoom();
cc.logOut();
}
| public static void main(String [] args) throws Exception {
String user;
String pass;
String subdomain;
user = pass = subdomain = "";
boolean useSSL = false;
// parse command line parameters
Getopt g = new Getopt("ConsoleClient", args, "u:p:s:hS");
int c;
while ((c = g.getopt()) != -1) {
switch (c) {
case 'u':
user = String.valueOf(g.getOptarg());
break;
case 'p':
pass = String.valueOf(g.getOptarg());
break;
case 's':
subdomain = String.valueOf(g.getOptarg());
break;
case 'S':
useSSL = true;
break;
case 'h':
// fall through
default:
case '?':
usage();
break;
}
}
if(user == "" || pass == "" || subdomain == "") {
System.out.println("Error: missing required arguments.");
usage();
}
//clear screen
System.out.printf("%c[2J", 27);
System.out.printf("%c[31;40mConsoleClient %s%c[0m\n", 27, ccVersion, 27);
if(useSSL) {
System.out.println("> Using SSL.");
} else {
System.out.println("> Not using SSL.");
}
System.out.println("> Connecting...");
ConsoleClient cc = new ConsoleClient(user, pass, subdomain, useSSL);
System.out.println("> Now connected to \""+subdomain+".campfirenow.com\"");
showCommands();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String curLine = "";
while((curLine = br.readLine()) != null) {
if(curLine.startsWith("/quit")) {
break;
} else if(curLine.startsWith("/join")) {
System.out.println("> Joining room...");
cc.joinRoom(curLine.substring(6));
System.out.println("> Now chatting in \""+curLine.substring(6)+"\"");
} else if(curLine.startsWith("/")) {
showCommands();
} else {
cc.sendMessage(curLine);
}
}
cc.leaveCurrentRoom();
cc.logOut();
}
|
diff --git a/src/main/java/com/jcabi/aspects/aj/MethodLogger.java b/src/main/java/com/jcabi/aspects/aj/MethodLogger.java
index 07d641b..498fe0f 100644
--- a/src/main/java/com/jcabi/aspects/aj/MethodLogger.java
+++ b/src/main/java/com/jcabi/aspects/aj/MethodLogger.java
@@ -1,440 +1,441 @@
/**
* Copyright (c) 2012-2013, JCabi.com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met: 1) Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer. 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution. 3) Neither the name of the jcabi.com nor
* the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jcabi.aspects.aj;
import com.jcabi.aspects.Loggable;
import com.jcabi.log.Logger;
import java.lang.reflect.Method;
import java.util.Set;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
/**
* Logs method calls.
*
* <p>It is an AspectJ aspect and you are not supposed to use it directly. It
* is instantiated by AspectJ runtime framework when your code is annotated
* with {@link Loggable} annotation.
*
* @author Yegor Bugayenko ([email protected])
* @version $Id$
* @since 0.7.2
* @checkstyle IllegalThrows (500 lines)
*/
@Aspect
@SuppressWarnings({ "PMD.AvoidCatchingThrowable", "PMD.TooManyMethods" })
public final class MethodLogger {
/**
* Currently running methods.
*/
private final transient Set<MethodLogger.Marker> running =
new ConcurrentSkipListSet<MethodLogger.Marker>();
/**
* Service that monitors all running methods.
*/
private final transient ScheduledExecutorService monitor;
/**
* Public ctor.
*/
@SuppressWarnings("PMD.DoNotUseThreads")
public MethodLogger() {
this.monitor = Executors.newSingleThreadScheduledExecutor(
new NamedThreads(
"loggable",
"watching of @Loggable annotated methods"
)
);
this.monitor.scheduleWithFixedDelay(
new Runnable() {
@Override
public void run() {
for (MethodLogger.Marker marker
: MethodLogger.this.running) {
marker.monitor();
}
}
},
1, 1, TimeUnit.SECONDS
);
}
/**
* Log methods in a class.
*
* <p>Try NOT to change the signature of this method, in order to keep
* it backward compatible.
*
* @param point Joint point
* @return The result of call
* @throws Throwable If something goes wrong inside
*/
@Around(
// @checkstyle StringLiteralsConcatenation (7 lines)
"(execution(public * (@com.jcabi.aspects.Loggable *).*(..))"
+ " || initialization((@com.jcabi.aspects.Loggable *).new(..)))"
+ " && !execution(String *.toString())"
+ " && !execution(int *.hashCode())"
+ " && !execution(boolean *.canEqual(Object))"
+ " && !execution(boolean *.equals(Object))"
+ " && !cflow(call(com.jcabi.aspects.aj.MethodLogger.new()))"
)
public Object wrapClass(final ProceedingJoinPoint point) throws Throwable {
final Method method =
MethodSignature.class.cast(point.getSignature()).getMethod();
Object output;
if (method.isAnnotationPresent(Loggable.class)) {
output = point.proceed();
} else {
output = this.wrap(
point,
method,
method.getDeclaringClass().getAnnotation(Loggable.class)
);
}
return output;
}
/**
* Log individual methods.
*
* <p>Try NOT to change the signature of this method, in order to keep
* it backward compatible.
*
* @param point Joint point
* @return The result of call
* @throws Throwable If something goes wrong inside
*/
@Around(
// @checkstyle StringLiteralsConcatenation (2 lines)
"(execution(* *(..)) || initialization(*.new(..)))"
+ " && @annotation(com.jcabi.aspects.Loggable)"
)
@SuppressWarnings("PMD.AvoidCatchingThrowable")
public Object wrapMethod(final ProceedingJoinPoint point) throws Throwable {
final Method method =
MethodSignature.class.cast(point.getSignature()).getMethod();
return this.wrap(point, method, method.getAnnotation(Loggable.class));
}
/**
* Catch exception and re-call the method.
* @param point Joint point
* @param method The method
* @param annotation The annotation
* @return The result of call
* @throws Throwable If something goes wrong inside
* @checkstyle ExecutableStatementCount (50 lines)
*/
private Object wrap(final ProceedingJoinPoint point, final Method method,
final Loggable annotation) throws Throwable {
if (Thread.interrupted()) {
throw new IllegalStateException("thread interrupted");
}
final long start = System.nanoTime();
final MethodLogger.Marker marker =
new MethodLogger.Marker(point, annotation);
this.running.add(marker);
try {
final Class<?> type = method.getDeclaringClass();
int level = annotation.value();
final int limit = annotation.limit();
if (annotation.prepend()) {
MethodLogger.log(
level,
type,
new StringBuilder(Mnemos.toText(point, annotation.trim()))
.append(": entered").toString()
);
}
final Object result = point.proceed();
final long nano = System.nanoTime() - start;
final boolean over = nano > annotation.unit().toNanos(limit);
if (MethodLogger.enabled(level, type) || over) {
final StringBuilder msg = new StringBuilder();
msg.append(Mnemos.toText(point, annotation.trim()))
.append(':');
if (!method.getReturnType().equals(Void.TYPE)) {
- msg.append(" returned ")
- .append(Mnemos.toText(result, annotation.trim()));
+ msg.append(' ').append(
+ Mnemos.toText(result, annotation.trim())
+ );
}
msg.append(Logger.format(" in %[nano]s", nano));
if (over) {
level = Loggable.WARN;
msg.append(" (too slow!)");
}
MethodLogger.log(
level,
type,
msg.toString()
);
}
return result;
// @checkstyle IllegalCatch (1 line)
} catch (Throwable ex) {
if (!MethodLogger.contains(annotation.ignore(), ex)) {
final StackTraceElement trace = ex.getStackTrace()[0];
MethodLogger.log(
Loggable.ERROR,
method.getDeclaringClass(),
Logger.format(
"%s: thrown %s out of %s#%s[%d] in %[nano]s",
Mnemos.toText(point, annotation.trim()),
Mnemos.toText(ex),
trace.getClassName(),
trace.getMethodName(),
trace.getLineNumber(),
System.nanoTime() - start
)
);
}
throw ex;
} finally {
this.running.remove(marker);
}
}
/**
* Log one line.
* @param level Level of logging
* @param log Destination log
* @param message Message to log
*/
private static void log(final int level, final Class<?> log,
final String message) {
if (level == Loggable.TRACE) {
Logger.trace(log, message);
} else if (level == Loggable.DEBUG) {
Logger.debug(log, message);
} else if (level == Loggable.INFO) {
Logger.info(log, message);
} else if (level == Loggable.WARN) {
Logger.warn(log, message);
} else if (level == Loggable.ERROR) {
Logger.error(log, message);
}
}
/**
* Log level is enabled?
* @param level Level of logging
* @param log Destination log
* @return TRUE if enabled
*/
private static boolean enabled(final int level, final Class<?> log) {
boolean enabled;
if (level == Loggable.TRACE) {
enabled = Logger.isTraceEnabled(log);
} else if (level == Loggable.DEBUG) {
enabled = Logger.isDebugEnabled(log);
} else if (level == Loggable.INFO) {
enabled = Logger.isInfoEnabled(log);
} else if (level == Loggable.WARN) {
enabled = Logger.isWarnEnabled(log);
} else {
enabled = true;
}
return enabled;
}
/**
* Marker of a running method.
*/
private static final class Marker
implements Comparable<MethodLogger.Marker> {
/**
* When the method was started, in milliseconds.
*/
private final transient long started = System.currentTimeMillis();
/**
* Which monitoring cycle was logged recently.
*/
private final transient AtomicInteger logged = new AtomicInteger();
/**
* The thread it's running in.
*/
@SuppressWarnings("PMD.DoNotUseThreads")
private final transient Thread thread = Thread.currentThread();
/**
* Joint point.
*/
private final transient ProceedingJoinPoint point;
/**
* Annotation.
*/
private final transient Loggable annotation;
/**
* Public ctor.
* @param pnt Joint point
* @param annt Annotation
*/
public Marker(final ProceedingJoinPoint pnt, final Loggable annt) {
this.point = pnt;
this.annotation = annt;
}
/**
* Monitor it's status and log the problem, if any.
*/
public void monitor() {
final TimeUnit unit = this.annotation.unit();
final long threshold = this.annotation.limit();
final long age = unit.convert(
System.currentTimeMillis() - this.started, TimeUnit.MILLISECONDS
);
final int cycle = (int) ((age - threshold) / threshold);
if (cycle > this.logged.get()) {
final Method method = MethodSignature.class.cast(
this.point.getSignature()
).getMethod();
Logger.warn(
method.getDeclaringClass(),
"%s: takes more than %[ms]s, %[ms]s already, thread=%s/%s",
Mnemos.toText(this.point, true),
TimeUnit.MILLISECONDS.convert(threshold, unit),
TimeUnit.MILLISECONDS.convert(age, unit),
this.thread.getName(),
this.thread.getState()
);
Logger.debug(
method.getDeclaringClass(),
"%s: thread %s/%s stacktrace: %s",
Mnemos.toText(this.point, true),
this.thread.getName(),
this.thread.getState(),
MethodLogger.textualize(this.thread.getStackTrace())
);
this.logged.set(cycle);
}
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
return this.point.hashCode();
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(final Object obj) {
return obj == this || MethodLogger.Marker.class.cast(obj)
.point.equals(this.point);
}
/**
* {@inheritDoc}
*/
@Override
public int compareTo(final Marker marker) {
int diff;
if (marker.started > this.started) {
diff = 1;
} else if (marker.started < this.started) {
diff = -1;
} else {
diff = 0;
}
return diff;
}
}
/**
* Checks whether array of types contains given type.
* @param array Array of them
* @param exp The exception to find
* @return TRUE if it's there
*/
private static boolean contains(final Class<? extends Throwable>[] array,
final Throwable exp) {
boolean contains = false;
for (Class<? extends Throwable> type : array) {
if (MethodLogger.instanceOf(exp.getClass(), type)) {
contains = true;
break;
}
}
return contains;
}
/**
* The type is an instance of another type?
* @param child The child type
* @param parent Parent type
* @return TRUE if child is really a child of a parent
*/
private static boolean instanceOf(final Class<?> child,
final Class<?> parent) {
boolean instance = child.equals(parent)
|| (child.getSuperclass() != null
&& MethodLogger.instanceOf(child.getSuperclass(), parent));
if (!instance) {
for (Class<?> iface : child.getInterfaces()) {
instance = MethodLogger.instanceOf(iface, parent);
if (instance) {
break;
}
}
}
return instance;
}
/**
* Textualize a stacktrace.
* @param trace Array of stacktrace elements
* @return The text
*/
private static String textualize(final StackTraceElement[] trace) {
final StringBuilder text = new StringBuilder();
for (int pos = 0; pos < trace.length; ++pos) {
if (text.length() > 0) {
text.append(", ");
}
text.append(
String.format(
"%s#%s[%d]",
trace[pos].getClassName(),
trace[pos].getMethodName(),
trace[pos].getLineNumber()
)
);
}
return text.toString();
}
}
| true | true | private Object wrap(final ProceedingJoinPoint point, final Method method,
final Loggable annotation) throws Throwable {
if (Thread.interrupted()) {
throw new IllegalStateException("thread interrupted");
}
final long start = System.nanoTime();
final MethodLogger.Marker marker =
new MethodLogger.Marker(point, annotation);
this.running.add(marker);
try {
final Class<?> type = method.getDeclaringClass();
int level = annotation.value();
final int limit = annotation.limit();
if (annotation.prepend()) {
MethodLogger.log(
level,
type,
new StringBuilder(Mnemos.toText(point, annotation.trim()))
.append(": entered").toString()
);
}
final Object result = point.proceed();
final long nano = System.nanoTime() - start;
final boolean over = nano > annotation.unit().toNanos(limit);
if (MethodLogger.enabled(level, type) || over) {
final StringBuilder msg = new StringBuilder();
msg.append(Mnemos.toText(point, annotation.trim()))
.append(':');
if (!method.getReturnType().equals(Void.TYPE)) {
msg.append(" returned ")
.append(Mnemos.toText(result, annotation.trim()));
}
msg.append(Logger.format(" in %[nano]s", nano));
if (over) {
level = Loggable.WARN;
msg.append(" (too slow!)");
}
MethodLogger.log(
level,
type,
msg.toString()
);
}
return result;
// @checkstyle IllegalCatch (1 line)
} catch (Throwable ex) {
if (!MethodLogger.contains(annotation.ignore(), ex)) {
final StackTraceElement trace = ex.getStackTrace()[0];
MethodLogger.log(
Loggable.ERROR,
method.getDeclaringClass(),
Logger.format(
"%s: thrown %s out of %s#%s[%d] in %[nano]s",
Mnemos.toText(point, annotation.trim()),
Mnemos.toText(ex),
trace.getClassName(),
trace.getMethodName(),
trace.getLineNumber(),
System.nanoTime() - start
)
);
}
throw ex;
} finally {
this.running.remove(marker);
}
}
| private Object wrap(final ProceedingJoinPoint point, final Method method,
final Loggable annotation) throws Throwable {
if (Thread.interrupted()) {
throw new IllegalStateException("thread interrupted");
}
final long start = System.nanoTime();
final MethodLogger.Marker marker =
new MethodLogger.Marker(point, annotation);
this.running.add(marker);
try {
final Class<?> type = method.getDeclaringClass();
int level = annotation.value();
final int limit = annotation.limit();
if (annotation.prepend()) {
MethodLogger.log(
level,
type,
new StringBuilder(Mnemos.toText(point, annotation.trim()))
.append(": entered").toString()
);
}
final Object result = point.proceed();
final long nano = System.nanoTime() - start;
final boolean over = nano > annotation.unit().toNanos(limit);
if (MethodLogger.enabled(level, type) || over) {
final StringBuilder msg = new StringBuilder();
msg.append(Mnemos.toText(point, annotation.trim()))
.append(':');
if (!method.getReturnType().equals(Void.TYPE)) {
msg.append(' ').append(
Mnemos.toText(result, annotation.trim())
);
}
msg.append(Logger.format(" in %[nano]s", nano));
if (over) {
level = Loggable.WARN;
msg.append(" (too slow!)");
}
MethodLogger.log(
level,
type,
msg.toString()
);
}
return result;
// @checkstyle IllegalCatch (1 line)
} catch (Throwable ex) {
if (!MethodLogger.contains(annotation.ignore(), ex)) {
final StackTraceElement trace = ex.getStackTrace()[0];
MethodLogger.log(
Loggable.ERROR,
method.getDeclaringClass(),
Logger.format(
"%s: thrown %s out of %s#%s[%d] in %[nano]s",
Mnemos.toText(point, annotation.trim()),
Mnemos.toText(ex),
trace.getClassName(),
trace.getMethodName(),
trace.getLineNumber(),
System.nanoTime() - start
)
);
}
throw ex;
} finally {
this.running.remove(marker);
}
}
|
diff --git a/src/com/nullprogram/chess/pieces/King.java b/src/com/nullprogram/chess/pieces/King.java
index c5b0de3..9eb95ef 100644
--- a/src/com/nullprogram/chess/pieces/King.java
+++ b/src/com/nullprogram/chess/pieces/King.java
@@ -1,139 +1,139 @@
package com.nullprogram.chess.pieces;
import com.nullprogram.chess.Piece;
import com.nullprogram.chess.Position;
import com.nullprogram.chess.Move;
import com.nullprogram.chess.MoveList;
/**
* The Chess king.
*
* This class describes the movement and capture behavior of the Chess
* king.
*/
public class King extends Piece {
/** List of enemy moves (cahced). */
private MoveList enemy;
/** Cache the check check. */
private Boolean inCheck;
/**
* Create a new king on the given side.
*
* @param side piece owner
*/
public King(final Side side) {
super(side);
}
/** {@inheritDoc} */
public final MoveList getMoves(final boolean check) {
MoveList list = new MoveList(getBoard(), check);
Position pos = getPosition();
for (int y = -1; y <= 1; y++) {
for (int x = -1; x <= 1; x++) {
if (x != 0 || y != 0) {
list.addCapture(new Move(pos, new Position(pos, x, y)));
}
}
}
/* check for castling */
enemy = null;
inCheck = null;
if (check && !moved()) {
Move left = castle(-1);
if (left != null) {
list.add(left);
}
Move right = castle(1);
if (right != null) {
list.add(right);
}
}
return list;
}
/**
* Try to create a castle move in the given direction.
*
* @param dir direction to check
* @return the move, or null
*/
private Move castle(final int dir) {
int dist = getBoard().getWidth() / 2 - 2;
Position pos = getPosition();
int max;
if (dir < 0) {
max = 0;
} else {
max = getBoard().getWidth() - 1;
}
Position rookPos = new Position(max, pos.getY());
Piece rook = getBoard().getPiece(rookPos);
- if (rook != null && rook.moved()) {
+ if (rook == null || rook.moved()) {
return null;
}
if (emptyRow(getPosition(), dir, max) && !inCheck()) {
/* generate the move */
Position kpos = new Position(pos, dir * dist, 0);
Move kingDest = new Move(pos, kpos);
Position rpos = new Position(pos, dir * dist - dir, 0);
Move rookDest = new Move(rookPos, rpos);
kingDest.setNext(rookDest);
return kingDest;
}
return null;
}
/**
* Check for an empty, unthreatened castling row.
*
* @param start the starting position
* @param dir direction to check
* @param max maximum column for the board
* @return true if row is safe
*/
private boolean emptyRow(final Position start, final int dir,
final int max) {
for (int i = start.getX() + dir; i != max; i += dir) {
Position pos = new Position(i, start.getY());
if (getBoard().getPiece(pos) != null
|| enemyMoves().containsDest(pos)) {
return false;
}
}
return true;
}
/**
* Cache of enemy moves.
*
* @return list of enemy moves
*/
private MoveList enemyMoves() {
if (enemy != null) {
return enemy;
}
enemy = getBoard().allMoves(opposite(getSide()), false);
return enemy;
}
/**
* Cache of check check.
*
* @return true if king is in check
*/
private boolean inCheck() {
if (inCheck != null) {
return inCheck;
}
inCheck = getBoard().check(getSide());
return inCheck;
}
}
| true | true | private Move castle(final int dir) {
int dist = getBoard().getWidth() / 2 - 2;
Position pos = getPosition();
int max;
if (dir < 0) {
max = 0;
} else {
max = getBoard().getWidth() - 1;
}
Position rookPos = new Position(max, pos.getY());
Piece rook = getBoard().getPiece(rookPos);
if (rook != null && rook.moved()) {
return null;
}
if (emptyRow(getPosition(), dir, max) && !inCheck()) {
/* generate the move */
Position kpos = new Position(pos, dir * dist, 0);
Move kingDest = new Move(pos, kpos);
Position rpos = new Position(pos, dir * dist - dir, 0);
Move rookDest = new Move(rookPos, rpos);
kingDest.setNext(rookDest);
return kingDest;
}
return null;
}
| private Move castle(final int dir) {
int dist = getBoard().getWidth() / 2 - 2;
Position pos = getPosition();
int max;
if (dir < 0) {
max = 0;
} else {
max = getBoard().getWidth() - 1;
}
Position rookPos = new Position(max, pos.getY());
Piece rook = getBoard().getPiece(rookPos);
if (rook == null || rook.moved()) {
return null;
}
if (emptyRow(getPosition(), dir, max) && !inCheck()) {
/* generate the move */
Position kpos = new Position(pos, dir * dist, 0);
Move kingDest = new Move(pos, kpos);
Position rpos = new Position(pos, dir * dist - dir, 0);
Move rookDest = new Move(rookPos, rpos);
kingDest.setNext(rookDest);
return kingDest;
}
return null;
}
|
diff --git a/src/java/org/jivesoftware/openfire/http/HttpBindManager.java b/src/java/org/jivesoftware/openfire/http/HttpBindManager.java
index 3d17df73..2d864979 100644
--- a/src/java/org/jivesoftware/openfire/http/HttpBindManager.java
+++ b/src/java/org/jivesoftware/openfire/http/HttpBindManager.java
@@ -1,545 +1,545 @@
/**
* $RCSfile$
* $Revision: $
* $Date: $
*
* Copyright (C) 2005-2008 Jive Software. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.openfire.http;
import java.io.File;
import java.security.KeyStore;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.Map;
import org.eclipse.jetty.http.ssl.SslContextFactory;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.server.ssl.SslSelectChannelConnector;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.eclipse.jetty.webapp.WebAppContext;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.net.SSLConfig;
import org.jivesoftware.util.CertificateEventListener;
import org.jivesoftware.util.CertificateManager;
import org.jivesoftware.util.JiveGlobals;
import org.jivesoftware.util.PropertyEventDispatcher;
import org.jivesoftware.util.PropertyEventListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
*/
public final class HttpBindManager {
private static final Logger Log = LoggerFactory.getLogger(HttpBindManager.class);
public static final String HTTP_BIND_ENABLED = "httpbind.enabled";
public static final boolean HTTP_BIND_ENABLED_DEFAULT = true;
public static final String HTTP_BIND_PORT = "httpbind.port.plain";
public static final int HTTP_BIND_PORT_DEFAULT = 7070;
public static final String HTTP_BIND_SECURE_PORT = "httpbind.port.secure";
public static final int HTTP_BIND_SECURE_PORT_DEFAULT = 7443;
private static HttpBindManager instance = new HttpBindManager();
private Server httpBindServer;
private int bindPort;
private int bindSecurePort;
private Connector httpConnector;
private Connector httpsConnector;
private CertificateListener certificateListener;
private HttpSessionManager httpSessionManager;
private ContextHandlerCollection contexts;
public static HttpBindManager getInstance() {
return instance;
}
private HttpBindManager() {
// JSP 2.0 uses commons-logging, so also override that implementation.
System.setProperty("org.apache.commons.logging.LogFactory", "org.jivesoftware.util.log.util.CommonsLogFactory");
PropertyEventDispatcher.addListener(new HttpServerPropertyListener());
this.httpSessionManager = new HttpSessionManager();
contexts = new ContextHandlerCollection();
}
public void start() {
certificateListener = new CertificateListener();
CertificateManager.addListener(certificateListener);
if (!isHttpBindServiceEnabled()) {
return;
}
bindPort = getHttpBindUnsecurePort();
bindSecurePort = getHttpBindSecurePort();
configureHttpBindServer(bindPort, bindSecurePort);
try {
httpBindServer.start();
}
catch (Exception e) {
Log.error("Error starting HTTP bind service", e);
}
}
public void stop() {
CertificateManager.removeListener(certificateListener);
if (httpBindServer != null) {
try {
httpBindServer.stop();
}
catch (Exception e) {
Log.error("Error stoping HTTP bind service", e);
}
}
}
public HttpSessionManager getSessionManager() {
return httpSessionManager;
}
private boolean isHttpBindServiceEnabled() {
return JiveGlobals.getBooleanProperty(HTTP_BIND_ENABLED, HTTP_BIND_ENABLED_DEFAULT);
}
private void createConnector(int port) {
httpConnector = null;
if (port > 0) {
SelectChannelConnector connector = new SelectChannelConnector();
// Listen on a specific network interface if it has been set.
connector.setHost(getBindInterface());
connector.setPort(port);
httpConnector = connector;
}
}
private void createSSLConnector(int securePort) {
httpsConnector = null;
try {
if (securePort > 0 && CertificateManager.isRSACertificate(SSLConfig.getKeyStore(), "*")) {
if (!CertificateManager.isRSACertificate(SSLConfig.getKeyStore(),
XMPPServer.getInstance().getServerInfo().getXMPPDomain())) {
Log.warn("HTTP binding: Using RSA certificates but they are not valid for " +
"the hosted domain");
}
final SslContextFactory sslContextFactory = new SslContextFactory(SSLConfig.getKeystoreLocation());
sslContextFactory.setTrustStorePassword(SSLConfig.getc2sTrustPassword());
sslContextFactory.setTrustStoreType(SSLConfig.getStoreType());
sslContextFactory.setTrustStore(SSLConfig.getc2sTruststoreLocation());
sslContextFactory.setKeyStorePassword(SSLConfig.getKeyPassword());
sslContextFactory.setKeyStoreType(SSLConfig.getStoreType());
// Set policy for checking client certificates
String certPol = JiveGlobals.getProperty("xmpp.client.cert.policy", "disabled");
if(certPol.equals("needed")) {
sslContextFactory.setNeedClientAuth(true);
sslContextFactory.setWantClientAuth(true);
} else if(certPol.equals("wanted")) {
sslContextFactory.setNeedClientAuth(false);
sslContextFactory.setWantClientAuth(true);
} else {
sslContextFactory.setNeedClientAuth(false);
sslContextFactory.setWantClientAuth(false);
}
- final SslSelectChannelConnector sslConnector = new SslSelectChannelConnector();
+ final SslSelectChannelConnector sslConnector = new SslSelectChannelConnector(sslContextFactory);
sslConnector.setHost(getBindInterface());
sslConnector.setPort(securePort);
httpsConnector = sslConnector;
}
}
catch (Exception e) {
Log.error("Error creating SSL connector for Http bind", e);
}
}
private String getBindInterface() {
String interfaceName = JiveGlobals.getXMLProperty("network.interface");
String bindInterface = null;
if (interfaceName != null) {
if (interfaceName.trim().length() > 0) {
bindInterface = interfaceName;
}
}
return bindInterface;
}
/**
* Returns true if the HTTP binding server is currently enabled.
*
* @return true if the HTTP binding server is currently enabled.
*/
public boolean isHttpBindEnabled() {
return httpBindServer != null && httpBindServer.isRunning();
}
/**
* Returns true if a listener on the HTTP binding port is running.
*
* @return true if a listener on the HTTP binding port is running.
*/
public boolean isHttpBindActive() {
return httpConnector != null && httpConnector.isRunning();
}
/**
* Returns true if a listener on the HTTPS binding port is running.
*
* @return true if a listener on the HTTPS binding port is running.
*/
public boolean isHttpsBindActive() {
return httpsConnector != null && httpsConnector.isRunning();
}
public String getHttpBindUnsecureAddress() {
return "http://" + XMPPServer.getInstance().getServerInfo().getXMPPDomain() + ":" +
bindPort + "/http-bind/";
}
public String getHttpBindSecureAddress() {
return "https://" + XMPPServer.getInstance().getServerInfo().getXMPPDomain() + ":" +
bindSecurePort + "/http-bind/";
}
public String getJavaScriptUrl() {
return "http://" + XMPPServer.getInstance().getServerInfo().getXMPPDomain() + ":" +
bindPort + "/scripts/";
}
public void setHttpBindEnabled(boolean isEnabled) {
JiveGlobals.setProperty(HTTP_BIND_ENABLED, String.valueOf(isEnabled));
}
/**
* Set the ports on which the HTTP binding service will be running.
*
* @param unsecurePort the unsecured connection port which clients can connect to.
* @param securePort the secured connection port which clients can connect to.
* @throws Exception when there is an error configuring the HTTP binding ports.
*/
public void setHttpBindPorts(int unsecurePort, int securePort) throws Exception {
changeHttpBindPorts(unsecurePort, securePort);
bindPort = unsecurePort;
bindSecurePort = securePort;
if (unsecurePort != HTTP_BIND_PORT_DEFAULT) {
JiveGlobals.setProperty(HTTP_BIND_PORT, String.valueOf(unsecurePort));
}
else {
JiveGlobals.deleteProperty(HTTP_BIND_PORT);
}
if (securePort != HTTP_BIND_SECURE_PORT_DEFAULT) {
JiveGlobals.setProperty(HTTP_BIND_SECURE_PORT, String.valueOf(securePort));
}
else {
JiveGlobals.deleteProperty(HTTP_BIND_SECURE_PORT);
}
}
private synchronized void changeHttpBindPorts(int unsecurePort, int securePort)
throws Exception {
if (unsecurePort < 0 && securePort < 0) {
throw new IllegalArgumentException("At least one port must be greater than zero.");
}
if (unsecurePort == securePort) {
throw new IllegalArgumentException("Ports must be distinct.");
}
if (httpBindServer != null) {
try {
httpBindServer.stop();
}
catch (Exception e) {
Log.error("Error stopping http bind server", e);
}
}
configureHttpBindServer(unsecurePort, securePort);
httpBindServer.start();
}
/**
* Starts an HTTP Bind server on the specified port and secure port.
*
* @param port the port to start the normal (unsecured) HTTP Bind service on.
* @param securePort the port to start the TLS (secure) HTTP Bind service on.
*/
private synchronized void configureHttpBindServer(int port, int securePort) {
httpBindServer = new Server();
final QueuedThreadPool tp = new QueuedThreadPool(254);
tp.setName("Jetty-QTP-BOSH");
httpBindServer.setThreadPool(tp);
createConnector(port);
createSSLConnector(securePort);
if (httpConnector == null && httpsConnector == null) {
httpBindServer = null;
return;
}
if (httpConnector != null) {
httpBindServer.addConnector(httpConnector);
}
if (httpsConnector != null) {
httpBindServer.addConnector(httpsConnector);
}
createBoshHandler(contexts, "/http-bind");
createCrossDomainHandler(contexts, "/");
loadStaticDirectory(contexts);
HandlerCollection collection = new HandlerCollection();
httpBindServer.setHandler(collection);
collection.setHandlers(new Handler[] { contexts, new DefaultHandler() });
}
private void createBoshHandler(ContextHandlerCollection contexts, String boshPath)
{
ServletContextHandler context = new ServletContextHandler(contexts, boshPath, ServletContextHandler.SESSIONS);
context.addServlet(new ServletHolder(new HttpBindServlet()),"/*");
}
private void createCrossDomainHandler(ContextHandlerCollection contexts, String crossPath)
{
ServletContextHandler context = new ServletContextHandler(contexts, crossPath, ServletContextHandler.SESSIONS);
context.addServlet(new ServletHolder(new HttpBindServlet()),"/crossdomain.xml");
}
private void loadStaticDirectory(ContextHandlerCollection contexts) {
File spankDirectory = new File(JiveGlobals.getHomeDirectory() + File.separator
+ "resources" + File.separator + "spank");
if (spankDirectory.exists()) {
if (spankDirectory.canRead()) {
WebAppContext context = new WebAppContext(contexts, spankDirectory.getPath(), "/");
context.setWelcomeFiles(new String[]{"index.html"});
}
else {
Log.warn("Openfire cannot read the directory: " + spankDirectory);
}
}
}
public ContextHandlerCollection getContexts() {
return contexts;
}
private void doEnableHttpBind(boolean shouldEnable) {
if (shouldEnable && httpBindServer == null) {
try {
changeHttpBindPorts(JiveGlobals.getIntProperty(HTTP_BIND_PORT,
HTTP_BIND_PORT_DEFAULT), JiveGlobals.getIntProperty(HTTP_BIND_SECURE_PORT,
HTTP_BIND_SECURE_PORT_DEFAULT));
}
catch (Exception e) {
Log.error("Error configuring HTTP binding ports", e);
}
}
else if (!shouldEnable && httpBindServer != null) {
try {
httpBindServer.stop();
}
catch (Exception e) {
Log.error("Error stopping HTTP bind service", e);
}
httpBindServer = null;
}
}
/**
* Returns the HTTP binding port which does not use SSL.
*
* @return the HTTP binding port which does not use SSL.
*/
public int getHttpBindUnsecurePort() {
return JiveGlobals.getIntProperty(HTTP_BIND_PORT, HTTP_BIND_PORT_DEFAULT);
}
/**
* Returns the HTTP binding port which uses SSL.
*
* @return the HTTP binding port which uses SSL.
*/
public int getHttpBindSecurePort() {
return JiveGlobals.getIntProperty(HTTP_BIND_SECURE_PORT, HTTP_BIND_SECURE_PORT_DEFAULT);
}
/**
* Returns true if script syntax is enabled. Script syntax allows BOSH to be used in
* environments where clients may be restricted to using a particular server. Instead of using
* standard HTTP Post requests to transmit data, HTTP Get requests are used.
*
* @return true if script syntax is enabled.
* @see <a href="http://www.xmpp.org/extensions/xep-0124.html#script">BOSH: Alternative Script
* Syntax</a>
*/
public boolean isScriptSyntaxEnabled() {
return JiveGlobals.getBooleanProperty("xmpp.httpbind.scriptSyntax.enabled", false);
}
/**
* Enables or disables script syntax.
*
* @param isEnabled true to enable script syntax and false to disable it.
* @see #isScriptSyntaxEnabled()
* @see <a href="http://www.xmpp.org/extensions/xep-0124.html#script">BOSH: Alternative Script
* Syntax</a>
*/
public void setScriptSyntaxEnabled(boolean isEnabled) {
final String property = "xmpp.httpbind.scriptSyntax.enabled";
if(!isEnabled) {
JiveGlobals.deleteProperty(property);
}
else {
JiveGlobals.setProperty(property, String.valueOf(isEnabled));
}
}
private void setUnsecureHttpBindPort(int value) {
if (value == bindPort) {
return;
}
try {
changeHttpBindPorts(value, JiveGlobals.getIntProperty(HTTP_BIND_SECURE_PORT,
HTTP_BIND_SECURE_PORT_DEFAULT));
bindPort = value;
}
catch (Exception ex) {
Log.error("Error setting HTTP bind ports", ex);
}
}
private void setSecureHttpBindPort(int value) {
if (value == bindSecurePort) {
return;
}
try {
changeHttpBindPorts(JiveGlobals.getIntProperty(HTTP_BIND_PORT,
HTTP_BIND_PORT_DEFAULT), value);
bindSecurePort = value;
}
catch (Exception ex) {
Log.error("Error setting HTTP bind ports", ex);
}
}
private synchronized void restartServer() {
if (httpBindServer != null) {
try {
httpBindServer.stop();
}
catch (Exception e) {
Log.error("Error stopping http bind server", e);
}
configureHttpBindServer(getHttpBindUnsecurePort(), getHttpBindSecurePort());
}
}
/** Listens for changes to Jive properties that affect the HTTP server manager. */
private class HttpServerPropertyListener implements PropertyEventListener {
public void propertySet(String property, Map<String, Object> params) {
if (property.equalsIgnoreCase(HTTP_BIND_ENABLED)) {
doEnableHttpBind(Boolean.valueOf(params.get("value").toString()));
}
else if (property.equalsIgnoreCase(HTTP_BIND_PORT)) {
int value;
try {
value = Integer.valueOf(params.get("value").toString());
}
catch (NumberFormatException ne) {
JiveGlobals.deleteProperty(HTTP_BIND_PORT);
return;
}
setUnsecureHttpBindPort(value);
}
else if (property.equalsIgnoreCase(HTTP_BIND_SECURE_PORT)) {
int value;
try {
value = Integer.valueOf(params.get("value").toString());
}
catch (NumberFormatException ne) {
JiveGlobals.deleteProperty(HTTP_BIND_SECURE_PORT);
return;
}
setSecureHttpBindPort(value);
}
}
public void propertyDeleted(String property, Map<String, Object> params) {
if (property.equalsIgnoreCase(HTTP_BIND_ENABLED)) {
doEnableHttpBind(HTTP_BIND_ENABLED_DEFAULT);
}
else if (property.equalsIgnoreCase(HTTP_BIND_PORT)) {
setUnsecureHttpBindPort(HTTP_BIND_PORT_DEFAULT);
}
else if (property.equalsIgnoreCase(HTTP_BIND_SECURE_PORT)) {
setSecureHttpBindPort(HTTP_BIND_SECURE_PORT_DEFAULT);
}
}
public void xmlPropertySet(String property, Map<String, Object> params) {
}
public void xmlPropertyDeleted(String property, Map<String, Object> params) {
}
}
private class CertificateListener implements CertificateEventListener {
public void certificateCreated(KeyStore keyStore, String alias, X509Certificate cert) {
// If new certificate is RSA then (re)start the HTTPS service
if ("RSA".equals(cert.getPublicKey().getAlgorithm())) {
restartServer();
}
}
public void certificateDeleted(KeyStore keyStore, String alias) {
restartServer();
}
public void certificateSigned(KeyStore keyStore, String alias,
List<X509Certificate> certificates) {
// If new certificate is RSA then (re)start the HTTPS service
if ("RSA".equals(certificates.get(0).getPublicKey().getAlgorithm())) {
restartServer();
}
}
}
}
| true | true | private void createSSLConnector(int securePort) {
httpsConnector = null;
try {
if (securePort > 0 && CertificateManager.isRSACertificate(SSLConfig.getKeyStore(), "*")) {
if (!CertificateManager.isRSACertificate(SSLConfig.getKeyStore(),
XMPPServer.getInstance().getServerInfo().getXMPPDomain())) {
Log.warn("HTTP binding: Using RSA certificates but they are not valid for " +
"the hosted domain");
}
final SslContextFactory sslContextFactory = new SslContextFactory(SSLConfig.getKeystoreLocation());
sslContextFactory.setTrustStorePassword(SSLConfig.getc2sTrustPassword());
sslContextFactory.setTrustStoreType(SSLConfig.getStoreType());
sslContextFactory.setTrustStore(SSLConfig.getc2sTruststoreLocation());
sslContextFactory.setKeyStorePassword(SSLConfig.getKeyPassword());
sslContextFactory.setKeyStoreType(SSLConfig.getStoreType());
// Set policy for checking client certificates
String certPol = JiveGlobals.getProperty("xmpp.client.cert.policy", "disabled");
if(certPol.equals("needed")) {
sslContextFactory.setNeedClientAuth(true);
sslContextFactory.setWantClientAuth(true);
} else if(certPol.equals("wanted")) {
sslContextFactory.setNeedClientAuth(false);
sslContextFactory.setWantClientAuth(true);
} else {
sslContextFactory.setNeedClientAuth(false);
sslContextFactory.setWantClientAuth(false);
}
final SslSelectChannelConnector sslConnector = new SslSelectChannelConnector();
sslConnector.setHost(getBindInterface());
sslConnector.setPort(securePort);
httpsConnector = sslConnector;
}
}
catch (Exception e) {
Log.error("Error creating SSL connector for Http bind", e);
}
}
| private void createSSLConnector(int securePort) {
httpsConnector = null;
try {
if (securePort > 0 && CertificateManager.isRSACertificate(SSLConfig.getKeyStore(), "*")) {
if (!CertificateManager.isRSACertificate(SSLConfig.getKeyStore(),
XMPPServer.getInstance().getServerInfo().getXMPPDomain())) {
Log.warn("HTTP binding: Using RSA certificates but they are not valid for " +
"the hosted domain");
}
final SslContextFactory sslContextFactory = new SslContextFactory(SSLConfig.getKeystoreLocation());
sslContextFactory.setTrustStorePassword(SSLConfig.getc2sTrustPassword());
sslContextFactory.setTrustStoreType(SSLConfig.getStoreType());
sslContextFactory.setTrustStore(SSLConfig.getc2sTruststoreLocation());
sslContextFactory.setKeyStorePassword(SSLConfig.getKeyPassword());
sslContextFactory.setKeyStoreType(SSLConfig.getStoreType());
// Set policy for checking client certificates
String certPol = JiveGlobals.getProperty("xmpp.client.cert.policy", "disabled");
if(certPol.equals("needed")) {
sslContextFactory.setNeedClientAuth(true);
sslContextFactory.setWantClientAuth(true);
} else if(certPol.equals("wanted")) {
sslContextFactory.setNeedClientAuth(false);
sslContextFactory.setWantClientAuth(true);
} else {
sslContextFactory.setNeedClientAuth(false);
sslContextFactory.setWantClientAuth(false);
}
final SslSelectChannelConnector sslConnector = new SslSelectChannelConnector(sslContextFactory);
sslConnector.setHost(getBindInterface());
sslConnector.setPort(securePort);
httpsConnector = sslConnector;
}
}
catch (Exception e) {
Log.error("Error creating SSL connector for Http bind", e);
}
}
|
diff --git a/src/main/java/net/sf/plist/defaults/OperatingSystemPath.java b/src/main/java/net/sf/plist/defaults/OperatingSystemPath.java
index 7d9c77a..3698140 100644
--- a/src/main/java/net/sf/plist/defaults/OperatingSystemPath.java
+++ b/src/main/java/net/sf/plist/defaults/OperatingSystemPath.java
@@ -1,181 +1,181 @@
/*
Property List Utility - LGPL 3.0 licensed
Copyright (C) 2012 Yørn de Jong
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
File is part of the Property List project.
Project page on http://plist.sf.net/
*/
package net.sf.plist.defaults;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.net.NetworkInterface;
import java.net.SocketException;
/**
* Helper class for {@link NSDefaults} to provide defaults on multiple operating systems.
*/
abstract class OperatingSystemPath {
/**
* Class for generic (probably *NIX) operating system
*/
static class DefaultSystemPath extends OperatingSystemPath {
@Override
public File getPListPath(final Scope scope) {
switch(scope) {
case USER:
return new File(System.getProperty("user.home")+"/.preferences/");
case USER_BYHOST:
return new File(System.getProperty("user.home")+"/.preferences/ByHost/");
case SYSTEM:
return new File("/etc/preferences/");
}
throw new NullPointerException();
}
@Override
public boolean isLowerCasePreferred() {
return true;
}
}
/**
* Class for the Mac operating system
*/
static class OSXSystemPath extends OperatingSystemPath {
@Override
public File getPListPath(final Scope scope) {
switch(scope) {
case USER:
return new File(System.getProperty("user.home")+"/Library/Preferences/");
case USER_BYHOST:
return new File(System.getProperty("user.home")+"/Library/Preferences/ByHost/");
case SYSTEM:
return new File("/Library/Preferences/");
}
throw new NullPointerException();
}
@Override
public String getMachineUUID() {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
Runtime.getRuntime().exec("system_profiler SPHardwareDataType")
.getInputStream()));
String line = reader.readLine();
while(line != null) {
if (line.trim().startsWith("Hardware UUID: "))
return line.trim().substring("Hardware UUID: ".length());
line = reader.readLine();
}
return super.getMachineUUID();
} catch (Exception e) {
return super.getMachineUUID();
}
}
@Override
public boolean isLowerCasePreferred() {
return false;
}
}
/**
* Class for the Linux operating system
*/
static class LinuxSystemPath extends DefaultSystemPath {
@Override
public String getMachineUUID() {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
Runtime.getRuntime().exec("hal-get-property --udi /org/freedesktop/Hal/devices/computer --key system.hardware.uuid")
.getInputStream()));
return reader.readLine();
} catch (Exception e) {
return super.getMachineUUID();
}
}
}
// UUID Linux: hal-get-property --udi /org/freedesktop/Hal/devices/computer --key system.hardware.uuid
// UUID OS X: system_profiler SPHardwareDataType | awk '/UUID/{sub(/^[ \t]+/, "")}; NR == 17 {print}'
// UUID Windows: reg query "HKLM\SYSTEM\ControlSet001\Control\IDConfigDB\Hardware Profiles\0001" /v HwProfileGuid
/**
* Get the instance for the current operating system
*/
public static OperatingSystemPath getInstance() {
if (System.getProperty("os.name").toLowerCase().contains("mac"))
return new OSXSystemPath();
if (System.getProperty("os.name").toLowerCase().contains("linux"))
return new LinuxSystemPath();
return new DefaultSystemPath();
}
/**
* Get the Property List file for a given domain and scope
*
* @param domain the domain
* @param scope the scope
* @return the property list file
*/
public final File getPListFile(String domain, final Scope scope) {
if (domain == null)
domain = isLowerCasePreferred() ? ".globalpreferences" : ".GlobalPreferences";
if (scope.isByHost())
return new File(getPListPath(scope)+File.separator+domain+"."+getMachineUUID()+".plist");
return new File(getPListPath(scope)+File.separator+domain+".plist");
}
public abstract boolean isLowerCasePreferred();
/**
* Get the path to the directory where defaults are stored for a given scope
*
* @param scope the scope
* @return the directory
*/
public abstract File getPListPath(final Scope scope);
/**
* Get the UUID of the machine running the program
*
* @return the UUID
*/
public String getMachineUUID() {
StringBuilder result = new StringBuilder();
try {
// Basic UUID determination using MAC address,
// when determining using more modern methods fail
// or are not available
for(byte b : NetworkInterface.getNetworkInterfaces().nextElement().getHardwareAddress()) {
- result.append(Integer.toString(b&0xFF, 0xF));
+ result.append(Integer.toString(b&0xFF, 0x10));
}
return result.toString();
} catch (SocketException e) {
// When all else fails
return System.getProperty("user.name")
+ System.getProperty("user.region")
+ System.getProperty("user.language")
+ "-"
+ System.getProperty("os.name")
+ System.getProperty("os.version")
+ System.getProperty("os.arch");
}
}
}
| true | true | public String getMachineUUID() {
StringBuilder result = new StringBuilder();
try {
// Basic UUID determination using MAC address,
// when determining using more modern methods fail
// or are not available
for(byte b : NetworkInterface.getNetworkInterfaces().nextElement().getHardwareAddress()) {
result.append(Integer.toString(b&0xFF, 0xF));
}
return result.toString();
} catch (SocketException e) {
// When all else fails
return System.getProperty("user.name")
+ System.getProperty("user.region")
+ System.getProperty("user.language")
+ "-"
+ System.getProperty("os.name")
+ System.getProperty("os.version")
+ System.getProperty("os.arch");
}
}
| public String getMachineUUID() {
StringBuilder result = new StringBuilder();
try {
// Basic UUID determination using MAC address,
// when determining using more modern methods fail
// or are not available
for(byte b : NetworkInterface.getNetworkInterfaces().nextElement().getHardwareAddress()) {
result.append(Integer.toString(b&0xFF, 0x10));
}
return result.toString();
} catch (SocketException e) {
// When all else fails
return System.getProperty("user.name")
+ System.getProperty("user.region")
+ System.getProperty("user.language")
+ "-"
+ System.getProperty("os.name")
+ System.getProperty("os.version")
+ System.getProperty("os.arch");
}
}
|
diff --git a/flickrvote-web/src/main/java/net/chrissearle/flickrvote/web/admin/CreateChallengeAction.java b/flickrvote-web/src/main/java/net/chrissearle/flickrvote/web/admin/CreateChallengeAction.java
index a1522481..4a0004ab 100644
--- a/flickrvote-web/src/main/java/net/chrissearle/flickrvote/web/admin/CreateChallengeAction.java
+++ b/flickrvote-web/src/main/java/net/chrissearle/flickrvote/web/admin/CreateChallengeAction.java
@@ -1,48 +1,48 @@
package net.chrissearle.flickrvote.web.admin;
import com.opensymphony.xwork2.ActionSupport;
import net.chrissearle.flickrvote.service.ChallengeService;
import net.chrissearle.flickrvote.service.model.ChallengeInfo;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
public class CreateChallengeAction extends ActionSupport {
private ChallengeInfo challenge;
@Autowired
private ChallengeService challengeService;
private static final int START_VOTE_TIME = 18;
private static final int START_CHALLENGE_TIME = 18;
private static final int END_CHALLENGE_TIME = 21;
@Override
public String execute() throws Exception {
DateTime start = new DateTime(challenge.getStartDate()).plusHours(START_CHALLENGE_TIME);
DateTime vote = new DateTime(challenge.getVoteDate()).plusHours(START_VOTE_TIME);
DateTime end = new DateTime(challenge.getEndDate()).plusHours(END_CHALLENGE_TIME);
challengeService.addChallenge(challenge.getTitle(), challenge.getTag(),
- start.toDate(), vote.toDate(), end.toDate());
+ start.toDate(), end.toDate(), vote.toDate());
return SUCCESS;
}
@Override
public void validate() {
if (challenge.getTitle().length() == 0) {
addFieldError("challenge.title", "Title must be filled out");
}
if (challenge.getTag().length() == 0) {
addFieldError("challenge.tag", "Tag must be filled out");
}
}
public ChallengeInfo getChallenge() {
return challenge;
}
public void setChallenge(ChallengeInfo challenge) {
this.challenge = challenge;
}
}
| true | true | public String execute() throws Exception {
DateTime start = new DateTime(challenge.getStartDate()).plusHours(START_CHALLENGE_TIME);
DateTime vote = new DateTime(challenge.getVoteDate()).plusHours(START_VOTE_TIME);
DateTime end = new DateTime(challenge.getEndDate()).plusHours(END_CHALLENGE_TIME);
challengeService.addChallenge(challenge.getTitle(), challenge.getTag(),
start.toDate(), vote.toDate(), end.toDate());
return SUCCESS;
}
| public String execute() throws Exception {
DateTime start = new DateTime(challenge.getStartDate()).plusHours(START_CHALLENGE_TIME);
DateTime vote = new DateTime(challenge.getVoteDate()).plusHours(START_VOTE_TIME);
DateTime end = new DateTime(challenge.getEndDate()).plusHours(END_CHALLENGE_TIME);
challengeService.addChallenge(challenge.getTitle(), challenge.getTag(),
start.toDate(), end.toDate(), vote.toDate());
return SUCCESS;
}
|
diff --git a/src/test/java/eu/margiel/domain/SponsorTypeShould.java b/src/test/java/eu/margiel/domain/SponsorTypeShould.java
index 4ffd1e9..9a320a0 100644
--- a/src/test/java/eu/margiel/domain/SponsorTypeShould.java
+++ b/src/test/java/eu/margiel/domain/SponsorTypeShould.java
@@ -1,16 +1,16 @@
package eu.margiel.domain;
import static org.fest.assertions.Assertions.*;
import java.util.List;
import org.junit.Test;
public class SponsorTypeShould {
@Test
public void getAllShortNames() {
List<String> shortNames = SponsorType.allShortNames();
- assertThat(shortNames).containsExactly("Złoty", "Srebrny", "Brązowy", "Medialny");
+ assertThat(shortNames).containsExactly("Platynowy", "Złoty", "Srebrny", "Medialny");
}
}
| true | true | public void getAllShortNames() {
List<String> shortNames = SponsorType.allShortNames();
assertThat(shortNames).containsExactly("Złoty", "Srebrny", "Brązowy", "Medialny");
}
| public void getAllShortNames() {
List<String> shortNames = SponsorType.allShortNames();
assertThat(shortNames).containsExactly("Platynowy", "Złoty", "Srebrny", "Medialny");
}
|
diff --git a/src/com/turt2live/antishare/client/SimpleNotice.java b/src/com/turt2live/antishare/client/SimpleNotice.java
index f281aab7..19b70f4c 100644
--- a/src/com/turt2live/antishare/client/SimpleNotice.java
+++ b/src/com/turt2live/antishare/client/SimpleNotice.java
@@ -1,34 +1,34 @@
package com.turt2live.antishare.client;
import java.util.logging.Level;
import org.bukkit.entity.Player;
import com.turt2live.antishare.AntiShare;
import com.turt2live.antishare.AntiShare.LogType;
import com.turt2live.antishare.ErrorLog;
public class SimpleNotice {
public void onEnable(){
AntiShare.getInstance().getServer().getMessenger().registerOutgoingPluginChannel(AntiShare.getInstance(), "SimpleNotice");
}
public boolean sendPluginMessage(Player player, String message){
if(player == null || message == null){
return false;
}
if(!player.getListeningPluginChannels().contains("SimpleNotice")){
return false;
}
try{
- player.sendPluginMessage(AntiShare.getInstance(), "SimpleNotice", message.getBytes("UTF-8"));
+ player.sendPluginMessage(AntiShare.getInstance(), "SimpleNotice", message.getBytes());
return true;
}catch(Exception e){
AntiShare.getInstance().getMessenger().log("AntiShare encountered and error. Please report this to turt2live.", Level.SEVERE, LogType.ERROR);
AntiShare.getInstance().getMessenger().log("Please see " + ErrorLog.print(e) + " for the full error.", Level.SEVERE, LogType.ERROR);
return false;
}
}
}
| true | true | public boolean sendPluginMessage(Player player, String message){
if(player == null || message == null){
return false;
}
if(!player.getListeningPluginChannels().contains("SimpleNotice")){
return false;
}
try{
player.sendPluginMessage(AntiShare.getInstance(), "SimpleNotice", message.getBytes("UTF-8"));
return true;
}catch(Exception e){
AntiShare.getInstance().getMessenger().log("AntiShare encountered and error. Please report this to turt2live.", Level.SEVERE, LogType.ERROR);
AntiShare.getInstance().getMessenger().log("Please see " + ErrorLog.print(e) + " for the full error.", Level.SEVERE, LogType.ERROR);
return false;
}
}
| public boolean sendPluginMessage(Player player, String message){
if(player == null || message == null){
return false;
}
if(!player.getListeningPluginChannels().contains("SimpleNotice")){
return false;
}
try{
player.sendPluginMessage(AntiShare.getInstance(), "SimpleNotice", message.getBytes());
return true;
}catch(Exception e){
AntiShare.getInstance().getMessenger().log("AntiShare encountered and error. Please report this to turt2live.", Level.SEVERE, LogType.ERROR);
AntiShare.getInstance().getMessenger().log("Please see " + ErrorLog.print(e) + " for the full error.", Level.SEVERE, LogType.ERROR);
return false;
}
}
|
diff --git a/src/edu/stuy/subsystems/Drivetrain.java b/src/edu/stuy/subsystems/Drivetrain.java
index d038f40..ee6354c 100644
--- a/src/edu/stuy/subsystems/Drivetrain.java
+++ b/src/edu/stuy/subsystems/Drivetrain.java
@@ -1,49 +1,49 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.stuy.subsystems;
import edu.stuy.Devmode;
import edu.stuy.RobotMap;
import edu.stuy.commands.DriveManualJoystickControl;
import edu.wpi.first.wpilibj.AnalogChannel;
import edu.wpi.first.wpilibj.RobotDrive;
import edu.wpi.first.wpilibj.Solenoid;
import edu.wpi.first.wpilibj.command.Subsystem;
/**
*
* @author Kevin Wang
*/
public class Drivetrain extends Subsystem {
RobotDrive drive;
Solenoid gearShift;
AnalogChannel sonar;
// Put methods for controlling this subsystem
// here. Call these from Commands.
public Drivetrain() {
drive = new RobotDrive(RobotMap.FRONT_LEFT_MOTOR, RobotMap.REAR_LEFT_MOTOR, RobotMap.FRONT_RIGHT_MOTOR, RobotMap.REAR_RIGHT_MOTOR);
if (!Devmode.DEV_MODE) {
gearShift = new Solenoid(RobotMap.GEAR_SHIFT);
}
- sonar = new AnalogChannel(SONAR_CHANNEL);
+ sonar = new AnalogChannel(RobotMap.SONAR_CHANNEL);
}
public void initDefaultCommand() {
// Set the default command for a subsystem here.
//setDefaultCommand(new MySpecialCommand());
setDefaultCommand(new DriveManualJoystickControl());
}
public void tankDrive(double leftValue, double rightValue) {
drive.tankDrive(leftValue, rightValue);
}
public void setGear(boolean high) {
gearShift.set(high);
}
}
| true | true | public Drivetrain() {
drive = new RobotDrive(RobotMap.FRONT_LEFT_MOTOR, RobotMap.REAR_LEFT_MOTOR, RobotMap.FRONT_RIGHT_MOTOR, RobotMap.REAR_RIGHT_MOTOR);
if (!Devmode.DEV_MODE) {
gearShift = new Solenoid(RobotMap.GEAR_SHIFT);
}
sonar = new AnalogChannel(SONAR_CHANNEL);
}
| public Drivetrain() {
drive = new RobotDrive(RobotMap.FRONT_LEFT_MOTOR, RobotMap.REAR_LEFT_MOTOR, RobotMap.FRONT_RIGHT_MOTOR, RobotMap.REAR_RIGHT_MOTOR);
if (!Devmode.DEV_MODE) {
gearShift = new Solenoid(RobotMap.GEAR_SHIFT);
}
sonar = new AnalogChannel(RobotMap.SONAR_CHANNEL);
}
|
diff --git a/src/test/java/com/github/signed/mp3/GetStarted.java b/src/test/java/com/github/signed/mp3/GetStarted.java
index ad92554..4d69dc8 100644
--- a/src/test/java/com/github/signed/mp3/GetStarted.java
+++ b/src/test/java/com/github/signed/mp3/GetStarted.java
@@ -1,58 +1,58 @@
package com.github.signed.mp3;
import org.junit.Before;
import org.junit.Test;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;
public class GetStarted {
@Before
public void setUp() throws Exception {
Logger.getLogger("org.jaudiotagger").setLevel(Level.OFF);
}
@Test
public void testName() throws Exception {
- Path path = Paths.get("/home/signed/tmp/candidates/");
+ Path path = Paths.get("/path/to/album");
Mp3Album album = Mp3Album.For(path);
- //album.forEachMp3File(new SetTitleToFileName());
- //album.forEachMp3File(new PrependTrackNumberToTitle());
- //album.forEachMp3File(new SetTrackNumber());
- //album.forEachMp3File(new SetAlbum("Das Rad der Zeit 28 - Die weiße Burg"));
- //album.forEachMp3File(new CheckForMissingArtist());
+ album.forEachMp3File(new SetTitleToFileName());
+ album.forEachMp3File(new PrependTrackNumberToTitle());
+ album.forEachMp3File(new SetTrackNumber());
+ album.forEachMp3File(new SetAlbum("The incredible bunch"));
+ album.forEachMp3File(new CheckForMissingArtist());
album.forEachMp3File(new DumpAllTags());
}
@Test
public void forACollectionOfFiles() throws Exception {
Collection<Path> filePaths = new ArrayList<>();
for (Path filePath : filePaths) {
Mp3Album.Context context = new Mp3Album.Context(1, 1, filePath, Mp3.From(filePath));
//new DumpAllTags().call(context);
new DumpAllTags().call(context);
}
}
@Test
public void forASingleFile() throws Exception {
Path singleMp3 = Paths.get("some.mp3");
Mp3Album.Context context = new Mp3Album.Context(1, 1, singleMp3, Mp3.From(singleMp3));
new DumpAllTags().call(context);
//new SetTrackNumber().call(context);
//new SetTitleToFileName().call(context);
// Path reloaded = Paths.get("/home/signed/tmp/18.Wolken über Ebou Dar/00. Intro.mp3");
// context = new Mp3Album.Context(1, 1, singleMp3, Mp3.From(reloaded));
// new DumpAllTags().call(context);
}
}
| false | true | public void testName() throws Exception {
Path path = Paths.get("/home/signed/tmp/candidates/");
Mp3Album album = Mp3Album.For(path);
//album.forEachMp3File(new SetTitleToFileName());
//album.forEachMp3File(new PrependTrackNumberToTitle());
//album.forEachMp3File(new SetTrackNumber());
//album.forEachMp3File(new SetAlbum("Das Rad der Zeit 28 - Die weiße Burg"));
//album.forEachMp3File(new CheckForMissingArtist());
album.forEachMp3File(new DumpAllTags());
}
| public void testName() throws Exception {
Path path = Paths.get("/path/to/album");
Mp3Album album = Mp3Album.For(path);
album.forEachMp3File(new SetTitleToFileName());
album.forEachMp3File(new PrependTrackNumberToTitle());
album.forEachMp3File(new SetTrackNumber());
album.forEachMp3File(new SetAlbum("The incredible bunch"));
album.forEachMp3File(new CheckForMissingArtist());
album.forEachMp3File(new DumpAllTags());
}
|
diff --git a/sources/code/java/org/opensubsystems/core/util/ModifierClassFactory.java b/sources/code/java/org/opensubsystems/core/util/ModifierClassFactory.java
index eecd7e1..0be84cb 100644
--- a/sources/code/java/org/opensubsystems/core/util/ModifierClassFactory.java
+++ b/sources/code/java/org/opensubsystems/core/util/ModifierClassFactory.java
@@ -1,242 +1,242 @@
/*
* Copyright (C) 2003 - 2012 OpenSubsystems.com/net/org and its owners. All rights reserved.
*
* This file is part of OpenSubsystems.
*
* OpenSubsystems is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opensubsystems.core.util;
import java.util.List;
import org.opensubsystems.core.error.OSSException;
/**
* Class factory responsible for instantiation of classes whose implementation
* depends on some kind of aspect or technology identified by modifier. This
* class factory tries to instantiate the correct class based on what modifier
* is currently used.
*
* Assuming name of the interface aaa.AAA
* 1. try class name aaa.modifier.ModifierAAAImpl
* 2. try class name aaa.modifier.ModifierAAA
* 3. try class name aaa.impl.ModifierAAAImpl
* 4. try class name aaa.ModifierAAAImpl
* 5. try class name aaa.ModifierAAA
* 6. try class name aaa.modifier.AAAImpl
* 7. try class name aaa.modifier.AAA
* 8. try class in the form of aaa.impl.AAAImpl (from base class)
* 9. try aaa.AAAImpl (from base class)
* 10. try directly class aaa.AAA (from base class)
*
* @author bastafidli
*/
public class ModifierClassFactory<T> extends ImplementationClassFactory<T>
{
// Attributes ///////////////////////////////////////////////////////////////
/**
* Modifier used to construct classes.
*/
protected String m_strModifier;
// Constructors /////////////////////////////////////////////////////////////
/**
* Constructor
*
* @param type - type for objects instantiated by this factory
* @param strModifier - modifier that should be used to construct the classes
*/
public ModifierClassFactory(
Class<? extends T> type,
String strModifier
)
{
super(type);
m_strModifier = strModifier;
}
// Helper methods ///////////////////////////////////////////////////////////
/**
* {@inheritDoc}
*/
@Override
protected void createDefaultClassNames(
String strClassIdentifier,
String strModifier,
List<String> lstClassNames
) throws OSSException
{
- int iIndex;
- StringBuffer sbClassName = new StringBuffer();
+ int iIndex;
+ StringBuilder sbClassName = new StringBuilder();
// Assuming name of the interface aaa.AAA
// Find package separator
iIndex = strClassIdentifier.lastIndexOf('.');
// First try class name aaa.modifier.ModifierAAAImpl
if (iIndex != -1)
{
// There is a package
sbClassName.append(strClassIdentifier.substring(0, iIndex + 1));
sbClassName.append(strModifier.toLowerCase());
sbClassName.append(".");
sbClassName.append(strModifier);
sbClassName.append(strClassIdentifier.substring(iIndex + 1,
strClassIdentifier.length()));
}
else
{
sbClassName.append(strModifier.toLowerCase());
sbClassName.append(".");
sbClassName.append(strModifier);
sbClassName.append(strClassIdentifier);
}
sbClassName.append("Impl");
lstClassNames.add(sbClassName.toString());
sbClassName.delete(0, sbClassName.length());
// Then try class name aaa.modifier.ModifierAAA
if (iIndex != -1)
{
// There is a package
sbClassName.append(strClassIdentifier.substring(0, iIndex + 1));
sbClassName.append(strModifier.toLowerCase());
sbClassName.append(".");
sbClassName.append(strModifier);
sbClassName.append(strClassIdentifier.substring(iIndex + 1,
strClassIdentifier.length()));
}
else
{
sbClassName.append(strModifier.toLowerCase());
sbClassName.append(".");
sbClassName.append(strModifier);
sbClassName.append(strClassIdentifier);
}
lstClassNames.add(sbClassName.toString());
sbClassName.delete(0, sbClassName.length());
// Then try class name aaa.impl.ModifierAAAImpl
if (iIndex != -1)
{
// There is a package
sbClassName.append(strClassIdentifier.substring(0, iIndex + 1));
sbClassName.append("impl");
sbClassName.append(".");
sbClassName.append(strModifier);
sbClassName.append(strClassIdentifier.substring(iIndex + 1,
strClassIdentifier.length()));
}
else
{
sbClassName.append("impl");
sbClassName.append(".");
sbClassName.append(strModifier);
sbClassName.append(strClassIdentifier);
}
sbClassName.append("Impl");
lstClassNames.add(sbClassName.toString());
sbClassName.delete(0, sbClassName.length());
// Then try class name aaa.ModifierAAAImpl
if (iIndex != -1)
{
// There is a package
sbClassName.append(strClassIdentifier.substring(0, iIndex + 1));
sbClassName.append(strModifier);
sbClassName.append(strClassIdentifier.substring(iIndex + 1,
strClassIdentifier.length()));
}
else
{
sbClassName.append(strModifier);
sbClassName.append(strClassIdentifier);
}
sbClassName.append("Impl");
lstClassNames.add(sbClassName.toString());
sbClassName.delete(0, sbClassName.length());
// Then try class name aaa.ModifierAAA
if (iIndex != -1)
{
// There is a package
sbClassName.append(strClassIdentifier.substring(0, iIndex + 1));
sbClassName.append(strModifier);
sbClassName.append(strClassIdentifier.substring(iIndex + 1,
strClassIdentifier.length()));
}
else
{
sbClassName.append(strModifier);
sbClassName.append(strClassIdentifier);
}
lstClassNames.add(sbClassName.toString());
sbClassName.delete(0, sbClassName.length());
// Then try class aaa.modifier.AAAImpl
if (iIndex != -1)
{
// There is a package
sbClassName.append(strClassIdentifier.substring(0, iIndex + 1));
sbClassName.append(strModifier.toLowerCase());
sbClassName.append(".");
sbClassName.append(strClassIdentifier.substring(iIndex + 1,
strClassIdentifier.length()));
}
else
{
sbClassName.append(strModifier.toLowerCase());
sbClassName.append(".");
sbClassName.append(strClassIdentifier);
}
sbClassName.append("Impl");
lstClassNames.add(sbClassName.toString());
sbClassName.delete(0, sbClassName.length());
// Then try class aaa.modifier.AAA
if (iIndex != -1)
{
// There is a package
sbClassName.append(strClassIdentifier.substring(0, iIndex + 1));
sbClassName.append(strModifier.toLowerCase());
sbClassName.append(".");
sbClassName.append(strClassIdentifier.substring(iIndex + 1,
strClassIdentifier.length()));
}
else
{
sbClassName.append(strModifier.toLowerCase());
sbClassName.append(".");
sbClassName.append(strClassIdentifier);
}
lstClassNames.add(sbClassName.toString());
super.createDefaultClassNames(strClassIdentifier, strModifier, lstClassNames);
}
/**
* {@inheritDoc}
*/
@Override
protected String getModifier(
) throws OSSException
{
return m_strModifier;
}
}
| true | true | protected void createDefaultClassNames(
String strClassIdentifier,
String strModifier,
List<String> lstClassNames
) throws OSSException
{
int iIndex;
StringBuffer sbClassName = new StringBuffer();
// Assuming name of the interface aaa.AAA
// Find package separator
iIndex = strClassIdentifier.lastIndexOf('.');
// First try class name aaa.modifier.ModifierAAAImpl
if (iIndex != -1)
{
// There is a package
sbClassName.append(strClassIdentifier.substring(0, iIndex + 1));
sbClassName.append(strModifier.toLowerCase());
sbClassName.append(".");
sbClassName.append(strModifier);
sbClassName.append(strClassIdentifier.substring(iIndex + 1,
strClassIdentifier.length()));
}
else
{
sbClassName.append(strModifier.toLowerCase());
sbClassName.append(".");
sbClassName.append(strModifier);
sbClassName.append(strClassIdentifier);
}
sbClassName.append("Impl");
lstClassNames.add(sbClassName.toString());
sbClassName.delete(0, sbClassName.length());
// Then try class name aaa.modifier.ModifierAAA
if (iIndex != -1)
{
// There is a package
sbClassName.append(strClassIdentifier.substring(0, iIndex + 1));
sbClassName.append(strModifier.toLowerCase());
sbClassName.append(".");
sbClassName.append(strModifier);
sbClassName.append(strClassIdentifier.substring(iIndex + 1,
strClassIdentifier.length()));
}
else
{
sbClassName.append(strModifier.toLowerCase());
sbClassName.append(".");
sbClassName.append(strModifier);
sbClassName.append(strClassIdentifier);
}
lstClassNames.add(sbClassName.toString());
sbClassName.delete(0, sbClassName.length());
// Then try class name aaa.impl.ModifierAAAImpl
if (iIndex != -1)
{
// There is a package
sbClassName.append(strClassIdentifier.substring(0, iIndex + 1));
sbClassName.append("impl");
sbClassName.append(".");
sbClassName.append(strModifier);
sbClassName.append(strClassIdentifier.substring(iIndex + 1,
strClassIdentifier.length()));
}
else
{
sbClassName.append("impl");
sbClassName.append(".");
sbClassName.append(strModifier);
sbClassName.append(strClassIdentifier);
}
sbClassName.append("Impl");
lstClassNames.add(sbClassName.toString());
sbClassName.delete(0, sbClassName.length());
// Then try class name aaa.ModifierAAAImpl
if (iIndex != -1)
{
// There is a package
sbClassName.append(strClassIdentifier.substring(0, iIndex + 1));
sbClassName.append(strModifier);
sbClassName.append(strClassIdentifier.substring(iIndex + 1,
strClassIdentifier.length()));
}
else
{
sbClassName.append(strModifier);
sbClassName.append(strClassIdentifier);
}
sbClassName.append("Impl");
lstClassNames.add(sbClassName.toString());
sbClassName.delete(0, sbClassName.length());
// Then try class name aaa.ModifierAAA
if (iIndex != -1)
{
// There is a package
sbClassName.append(strClassIdentifier.substring(0, iIndex + 1));
sbClassName.append(strModifier);
sbClassName.append(strClassIdentifier.substring(iIndex + 1,
strClassIdentifier.length()));
}
else
{
sbClassName.append(strModifier);
sbClassName.append(strClassIdentifier);
}
lstClassNames.add(sbClassName.toString());
sbClassName.delete(0, sbClassName.length());
// Then try class aaa.modifier.AAAImpl
if (iIndex != -1)
{
// There is a package
sbClassName.append(strClassIdentifier.substring(0, iIndex + 1));
sbClassName.append(strModifier.toLowerCase());
sbClassName.append(".");
sbClassName.append(strClassIdentifier.substring(iIndex + 1,
strClassIdentifier.length()));
}
else
{
sbClassName.append(strModifier.toLowerCase());
sbClassName.append(".");
sbClassName.append(strClassIdentifier);
}
sbClassName.append("Impl");
lstClassNames.add(sbClassName.toString());
sbClassName.delete(0, sbClassName.length());
// Then try class aaa.modifier.AAA
if (iIndex != -1)
{
// There is a package
sbClassName.append(strClassIdentifier.substring(0, iIndex + 1));
sbClassName.append(strModifier.toLowerCase());
sbClassName.append(".");
sbClassName.append(strClassIdentifier.substring(iIndex + 1,
strClassIdentifier.length()));
}
else
{
sbClassName.append(strModifier.toLowerCase());
sbClassName.append(".");
sbClassName.append(strClassIdentifier);
}
lstClassNames.add(sbClassName.toString());
super.createDefaultClassNames(strClassIdentifier, strModifier, lstClassNames);
}
| protected void createDefaultClassNames(
String strClassIdentifier,
String strModifier,
List<String> lstClassNames
) throws OSSException
{
int iIndex;
StringBuilder sbClassName = new StringBuilder();
// Assuming name of the interface aaa.AAA
// Find package separator
iIndex = strClassIdentifier.lastIndexOf('.');
// First try class name aaa.modifier.ModifierAAAImpl
if (iIndex != -1)
{
// There is a package
sbClassName.append(strClassIdentifier.substring(0, iIndex + 1));
sbClassName.append(strModifier.toLowerCase());
sbClassName.append(".");
sbClassName.append(strModifier);
sbClassName.append(strClassIdentifier.substring(iIndex + 1,
strClassIdentifier.length()));
}
else
{
sbClassName.append(strModifier.toLowerCase());
sbClassName.append(".");
sbClassName.append(strModifier);
sbClassName.append(strClassIdentifier);
}
sbClassName.append("Impl");
lstClassNames.add(sbClassName.toString());
sbClassName.delete(0, sbClassName.length());
// Then try class name aaa.modifier.ModifierAAA
if (iIndex != -1)
{
// There is a package
sbClassName.append(strClassIdentifier.substring(0, iIndex + 1));
sbClassName.append(strModifier.toLowerCase());
sbClassName.append(".");
sbClassName.append(strModifier);
sbClassName.append(strClassIdentifier.substring(iIndex + 1,
strClassIdentifier.length()));
}
else
{
sbClassName.append(strModifier.toLowerCase());
sbClassName.append(".");
sbClassName.append(strModifier);
sbClassName.append(strClassIdentifier);
}
lstClassNames.add(sbClassName.toString());
sbClassName.delete(0, sbClassName.length());
// Then try class name aaa.impl.ModifierAAAImpl
if (iIndex != -1)
{
// There is a package
sbClassName.append(strClassIdentifier.substring(0, iIndex + 1));
sbClassName.append("impl");
sbClassName.append(".");
sbClassName.append(strModifier);
sbClassName.append(strClassIdentifier.substring(iIndex + 1,
strClassIdentifier.length()));
}
else
{
sbClassName.append("impl");
sbClassName.append(".");
sbClassName.append(strModifier);
sbClassName.append(strClassIdentifier);
}
sbClassName.append("Impl");
lstClassNames.add(sbClassName.toString());
sbClassName.delete(0, sbClassName.length());
// Then try class name aaa.ModifierAAAImpl
if (iIndex != -1)
{
// There is a package
sbClassName.append(strClassIdentifier.substring(0, iIndex + 1));
sbClassName.append(strModifier);
sbClassName.append(strClassIdentifier.substring(iIndex + 1,
strClassIdentifier.length()));
}
else
{
sbClassName.append(strModifier);
sbClassName.append(strClassIdentifier);
}
sbClassName.append("Impl");
lstClassNames.add(sbClassName.toString());
sbClassName.delete(0, sbClassName.length());
// Then try class name aaa.ModifierAAA
if (iIndex != -1)
{
// There is a package
sbClassName.append(strClassIdentifier.substring(0, iIndex + 1));
sbClassName.append(strModifier);
sbClassName.append(strClassIdentifier.substring(iIndex + 1,
strClassIdentifier.length()));
}
else
{
sbClassName.append(strModifier);
sbClassName.append(strClassIdentifier);
}
lstClassNames.add(sbClassName.toString());
sbClassName.delete(0, sbClassName.length());
// Then try class aaa.modifier.AAAImpl
if (iIndex != -1)
{
// There is a package
sbClassName.append(strClassIdentifier.substring(0, iIndex + 1));
sbClassName.append(strModifier.toLowerCase());
sbClassName.append(".");
sbClassName.append(strClassIdentifier.substring(iIndex + 1,
strClassIdentifier.length()));
}
else
{
sbClassName.append(strModifier.toLowerCase());
sbClassName.append(".");
sbClassName.append(strClassIdentifier);
}
sbClassName.append("Impl");
lstClassNames.add(sbClassName.toString());
sbClassName.delete(0, sbClassName.length());
// Then try class aaa.modifier.AAA
if (iIndex != -1)
{
// There is a package
sbClassName.append(strClassIdentifier.substring(0, iIndex + 1));
sbClassName.append(strModifier.toLowerCase());
sbClassName.append(".");
sbClassName.append(strClassIdentifier.substring(iIndex + 1,
strClassIdentifier.length()));
}
else
{
sbClassName.append(strModifier.toLowerCase());
sbClassName.append(".");
sbClassName.append(strClassIdentifier);
}
lstClassNames.add(sbClassName.toString());
super.createDefaultClassNames(strClassIdentifier, strModifier, lstClassNames);
}
|
diff --git a/src/generator/src/main/java/com/smvp4g/generator/generator/AbstractGenerator.java b/src/generator/src/main/java/com/smvp4g/generator/generator/AbstractGenerator.java
index d6c7aba..e6f8e36 100644
--- a/src/generator/src/main/java/com/smvp4g/generator/generator/AbstractGenerator.java
+++ b/src/generator/src/main/java/com/smvp4g/generator/generator/AbstractGenerator.java
@@ -1,110 +1,110 @@
/*
* Copyright (C) 2009 - 2012 SMVP4G.COM
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package com.smvp4g.generator.generator;
import com.google.gwt.core.ext.Generator;
import com.google.gwt.core.ext.GeneratorContext;
import com.google.gwt.core.ext.TreeLogger;
import com.google.gwt.core.ext.UnableToCompleteException;
import com.google.gwt.core.ext.typeinfo.JClassType;
import freemarker.cache.URLTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URL;
import java.util.Map;
/**
* The Class AbstractGenerator.
*
* @author Nguyen Duc Dung
* @since 11/24/11, 12:33 PM
*/
public abstract class AbstractGenerator<M extends AbstractTemplateData> extends Generator {
public static final String DEFAULT_FILE_PREFIX = "Generated";
protected GeneratorContext context;
protected JClassType classType;
@Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName) throws UnableToCompleteException {
try {
this.context = context;
classType = context.getTypeOracle().getType(typeName);
PrintWriter sourceWriter = context.tryCreate(logger, getPackageName(),getClassName());
if (sourceWriter != null) {
StringWriter templateWriter = new StringWriter();
createTemplate().process(scan(), templateWriter);
sourceWriter.print(templateWriter.toString());
context.commit(logger, sourceWriter);
- return getPackageName() + "." + getClassName();
}
+ return getPackageName() + "." + getClassName();
} catch (Exception e) {
logger.log(TreeLogger.Type.ERROR, e.getMessage());
}
return null;
}
protected Template createTemplate() {
Configuration configuration = new Configuration();
configuration.setTemplateLoader(new URLTemplateLoader() {
@Override
protected URL getURL(String name) {
return getResourceClass().getResource(getTemplateFileName());
}
});
try {
return configuration.getTemplate(getTemplateFileName());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected String getPackageName() {
if (classType != null) {
return classType.getPackage().getName();
}
return null;
}
protected String getClassName() {
if (classType != null) {
return classType.getSimpleSourceName() + getFilePrefix();
}
return null;
}
protected String getFilePrefix() {
return DEFAULT_FILE_PREFIX;
}
protected abstract Map<String, M> scan();
protected abstract String getTemplateFileName();
protected abstract Class<?> getResourceClass();
}
| false | true | public String generate(TreeLogger logger, GeneratorContext context, String typeName) throws UnableToCompleteException {
try {
this.context = context;
classType = context.getTypeOracle().getType(typeName);
PrintWriter sourceWriter = context.tryCreate(logger, getPackageName(),getClassName());
if (sourceWriter != null) {
StringWriter templateWriter = new StringWriter();
createTemplate().process(scan(), templateWriter);
sourceWriter.print(templateWriter.toString());
context.commit(logger, sourceWriter);
return getPackageName() + "." + getClassName();
}
} catch (Exception e) {
logger.log(TreeLogger.Type.ERROR, e.getMessage());
}
return null;
}
| public String generate(TreeLogger logger, GeneratorContext context, String typeName) throws UnableToCompleteException {
try {
this.context = context;
classType = context.getTypeOracle().getType(typeName);
PrintWriter sourceWriter = context.tryCreate(logger, getPackageName(),getClassName());
if (sourceWriter != null) {
StringWriter templateWriter = new StringWriter();
createTemplate().process(scan(), templateWriter);
sourceWriter.print(templateWriter.toString());
context.commit(logger, sourceWriter);
}
return getPackageName() + "." + getClassName();
} catch (Exception e) {
logger.log(TreeLogger.Type.ERROR, e.getMessage());
}
return null;
}
|
diff --git a/src/org/jacorb/idl/UnionType.java b/src/org/jacorb/idl/UnionType.java
index 14070453..91e08652 100644
--- a/src/org/jacorb/idl/UnionType.java
+++ b/src/org/jacorb/idl/UnionType.java
@@ -1,1179 +1,1179 @@
package org.jacorb.idl;
/*
* JacORB - a free Java ORB
*
* Copyright (C) 1997-2002 Gerald Brose.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free
* Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintWriter;
import java.util.*;
class UnionType
extends TypeDeclaration
implements Scope
{
/** the union's discriminator's type spec */
TypeSpec switch_type_spec;
SwitchBody switch_body;
boolean written = false;
private ScopeData scopeData;
private boolean allCasesCovered = false;
private boolean switch_is_enum = false;
private boolean switch_is_bool = false;
private boolean switch_is_longlong = false;
private boolean explicit_default_case = false;
private int labels;
public UnionType( int num )
{
super( num );
pack_name = "";
}
public Object clone()
{
UnionType ut = new UnionType( new_num() );
ut.switch_type_spec = this.switch_type_spec;
ut.switch_body = switch_body;
ut.pack_name = this.pack_name;
ut.name = this.name;
ut.written = this.written;
ut.scopeData = this.scopeData;
ut.enclosing_symbol = this.enclosing_symbol;
ut.token = this.token;
return ut;
}
public void setScopeData( ScopeData data )
{
scopeData = data;
}
public ScopeData getScopeData()
{
return scopeData;
}
public TypeDeclaration declaration()
{
return this;
}
public void setEnclosingSymbol( IdlSymbol s )
{
if( enclosing_symbol != null && enclosing_symbol != s )
throw new RuntimeException( "Compiler Error: trying to reassign container for " + name );
enclosing_symbol = s;
if (switch_body != null)
{
switch_body.setEnclosingSymbol( s );
}
}
public String typeName()
{
if( typeName == null )
setPrintPhaseNames();
return typeName;
}
public String className()
{
String fullName = typeName();
if( fullName.indexOf( '.' ) > 0 )
{
return fullName.substring( fullName.lastIndexOf( '.' ) + 1 );
}
else
{
return fullName;
}
}
public String printReadExpression( String Streamname )
{
return typeName() + "Helper.read(" + Streamname + ")";
}
public String printWriteStatement( String var_name, String streamname )
{
return typeName() + "Helper.write(" + streamname + "," + var_name + ");";
}
public String holderName()
{
return typeName() + "Holder";
}
public void set_included( boolean i )
{
included = i;
}
public void setSwitchType( TypeSpec s )
{
switch_type_spec = s;
}
public void setSwitchBody( SwitchBody sb )
{
switch_body = sb;
}
public void setPackage( String s )
{
s = parser.pack_replace( s );
if( pack_name.length() > 0 )
{
pack_name = new String( s + "." + pack_name);
}
else
{
pack_name = s;
}
if (switch_type_spec != null)
{
switch_type_spec.setPackage (s);
}
if (switch_body != null)
{
switch_body.setPackage( s );
}
}
public boolean basic()
{
return false;
}
public void parse()
{
boolean justAnotherOne = false;
escapeName();
ConstrTypeSpec ctspec = new ConstrTypeSpec( new_num() );
try
{
ScopedName.definePseudoScope( full_name() );
ctspec.c_type_spec = this;
NameTable.define( full_name(), "type-union" );
TypeMap.typedef( full_name(), ctspec );
}
catch (NameAlreadyDefined nad)
{
if (parser.get_pending (full_name ()) != null)
{
if (switch_type_spec == null )
{
justAnotherOne = true;
}
// else actual definition
if( !full_name().equals( "org.omg.CORBA.TypeCode" ) && switch_type_spec != null )
{
TypeMap.replaceForwardDeclaration( full_name(), ctspec );
}
}
else
{
Environment.output( 4, nad );
parser.error( "Union " + full_name() + " already defined", token );
}
}
if (switch_type_spec != null)
{
// Resolve scoped names and aliases
TypeSpec ts;
if( switch_type_spec.type_spec instanceof ScopedName )
{
ts = ( (ScopedName)switch_type_spec.type_spec ).resolvedTypeSpec();
while( ts instanceof ScopedName || ts instanceof AliasTypeSpec )
{
if( ts instanceof ScopedName )
{
ts = ( (ScopedName)ts ).resolvedTypeSpec();
}
else
{
ts = ( (AliasTypeSpec)ts ).originalType();
}
}
addImportedName( switch_type_spec.typeName() );
}
else
{
ts = switch_type_spec.type_spec;
}
// Check if we have a valid discriminator type
if
( !(
( ( ts instanceof SwitchTypeSpec ) &&
( ( (SwitchTypeSpec)ts ).isSwitchable() ) )
||
( ( ts instanceof BaseType ) &&
( ( (BaseType)ts ).isSwitchType() ) )
||
( ( ts instanceof ConstrTypeSpec ) &&
( ( (ConstrTypeSpec)ts ).c_type_spec instanceof EnumType ) )
) )
{
parser.error( "Illegal Switch Type: " + ts.typeName(), token );
}
switch_type_spec.parse();
switch_body.setTypeSpec( switch_type_spec );
switch_body.setUnion( this );
ScopedName.addRecursionScope( typeName() );
switch_body.parse();
ScopedName.removeRecursionScope( typeName() );
// Fixup array typing
for( Enumeration e = switch_body.caseListVector.elements(); e.hasMoreElements(); )
{
Case c = (Case)e.nextElement();
c.element_spec.t = getElementType( c.element_spec );
}
NameTable.parsed_interfaces.put( full_name(), "" );
parser.remove_pending( full_name() );
}
else if( !justAnotherOne )
{
// i am forward declared, must set myself as
// pending further parsing
parser.set_pending( full_name() );
}
}
/**
* @returns a string for an expression of type TypeCode that
* describes this type
*/
public String getTypeCodeExpression()
{
return typeName() + "Helper.type()";
}
public String getTypeCodeExpression( Set knownTypes )
{
if( knownTypes.contains( this ) )
{
return this.getRecursiveTypeCodeExpression();
}
else
{
return this.getTypeCodeExpression();
}
}
private void printClassComment( String className, PrintWriter ps )
{
ps.println( "/**" );
ps.println( " *\tGenerated from IDL definition of union " +
"\"" + className + "\"" );
ps.println( " *\t@author JacORB IDL compiler " );
ps.println( " */\n" );
}
public void printUnionClass( String className, PrintWriter pw )
{
if( !pack_name.equals( "" ) )
pw.println( "package " + pack_name + ";" );
printImport( pw );
printClassComment( className, pw );
pw.println( "public" + parser.getFinalString() + " class " + className );
pw.println( "\timplements org.omg.CORBA.portable.IDLEntity" );
pw.println( "{" );
TypeSpec ts = switch_type_spec.typeSpec();
while( ts instanceof ScopedName || ts instanceof AliasTypeSpec )
{
if( ts instanceof ScopedName )
ts = ( (ScopedName)ts ).resolvedTypeSpec();
if( ts instanceof AliasTypeSpec )
ts = ( (AliasTypeSpec)ts ).originalType();
}
pw.println( "\tprivate " + ts.typeName() + " discriminator;" );
/* find a "default" value */
String defaultStr = "";
/* start by concatenating all case label lists into one list
* (this list is used only for finding a default)
*/
int def = 0;
java.util.Vector allCaseLabels = new java.util.Vector();
for( Enumeration e = switch_body.caseListVector.elements(); e.hasMoreElements(); )
{
Case c = (Case)e.nextElement();
for( int i = 0; i < c.case_label_list.v.size(); i++ )
{
labels++; // the overall number of labels is needed in a number of places...
Object ce = c.case_label_list.v.elementAt( i );
if( ce != null )
{
if( ce instanceof ConstExpr )
{
allCaseLabels.addElement( ( (ConstExpr)ce ).value() );
}
else
{
allCaseLabels.addElement( ( (ScopedName)ce ).resolvedName() ); // this is a scoped name
Environment.output( 4, "Adding " + ( (ScopedName)ce ).resolvedName() + " case labels." );
}
}
else
{
def = 1;
explicit_default_case = true;
}
}
}
/* if switch type is an enum, the default is null */
if( ( ts instanceof ConstrTypeSpec &&
( (ConstrTypeSpec)ts ).declaration() instanceof EnumType ) )
{
this.switch_is_enum = true;
EnumType et = (EnumType)( (ConstrTypeSpec)ts ).declaration();
if( allCaseLabels.size() + def > et.size() )
{
lexer.emit_warn( "Too many case labels in definition of union " +
full_name() + ", default cannot apply", token );
}
if( allCaseLabels.size() + def == et.size() )
{
allCasesCovered = true;
}
for( int i = 0; i < et.size(); i++ )
{
String qualifiedCaseLabel =
ts.typeName() + "." + (String)et.enumlist.v.elementAt( i );
if( !( allCaseLabels.contains( qualifiedCaseLabel ) ) )
{
defaultStr = qualifiedCaseLabel;
break;
}
}
}
else
{
if( ts instanceof BaseType )
{
ts = ( (BaseType)ts ).typeSpec();
}
if( ts instanceof BooleanType )
{
this.switch_is_bool = true;
// find a "default" for boolean
if( allCaseLabels.size() + def > 2 )
{
parser.error( "Case label error: too many default labels.", token );
return;
}
else if( allCaseLabels.size() == 1 )
{
if( ( (String)allCaseLabels.elementAt( 0 ) ).equals( "true" ) )
defaultStr = "false";
else
defaultStr = "true";
}
else
{
// labels for both true and false -> no default possible
}
}
else if( ts instanceof CharType )
{
// find a "default" for char
for( short s = 0; s < 256; s++ )
{
if( !( allCaseLabels.contains( new Character( (char)s ).toString() ) ) )
{
defaultStr = "(char)" + s;
break;
}
}
}
else if( ts instanceof IntType )
{
int maxint = 65536; // 2^16, max short
if( ts instanceof LongType )
maxint = 2147483647; // -2^31, max long
for( int i = 0; i < maxint; i++ )
{
if( !( allCaseLabels.contains( String.valueOf( i ) ) ) )
{
defaultStr = Integer.toString( i );
break;
}
}
if( ts instanceof LongLongType )
{
this.switch_is_longlong = true;
}
}
else
{
System.err.println( "Something went wrong in UnionType, "
+ "could not identify switch type "
+ switch_type_spec.type_spec );
}
}
/* print members */
for( Enumeration e = switch_body.caseListVector.elements(); e.hasMoreElements(); )
{
Case c = (Case)e.nextElement();
int caseLabelNum = c.case_label_list.v.size();
String label[] = new String[ caseLabelNum ];
for( int i = 0; i < caseLabelNum; i++ )
{
Object o = c.case_label_list.v.elementAt( i );
if( o == null ) // null means "default"
{
label[ i ] = null;
}
else if( o != null && o instanceof ConstExpr )
{
label[ i ] = ( (ConstExpr)o ).value();
}
else if( o instanceof ScopedName )
{
label[ i ] = ( (ScopedName)o ).typeName();
}
}
pw.println( "\tprivate " + c.element_spec.t.typeName()
+ " " + c.element_spec.d.name() + ";" );
}
/*
* print a constructor for class member initialization
*/
pw.println( "\n\tpublic " + className + " ()" );
pw.println( "\t{" );
pw.println( "\t}\n" );
/*
* print an accessor method for the discriminator
*/
pw.println( "\tpublic " + ts.typeName() + " discriminator ()" );
pw.println( "\t{" );
pw.println( "\t\treturn discriminator;" );
pw.println( "\t}\n" );
/*
* print accessor and modifiers for each case label and branch
*/
for( Enumeration e = switch_body.caseListVector.elements(); e.hasMoreElements(); )
{
Case c = (Case)e.nextElement();
boolean thisCaseIsDefault = false;
int caseLabelNum = c.case_label_list.v.size();
String label[] = new String[ caseLabelNum ];
/* make case labels available as strings */
for( int i = 0; i < caseLabelNum; i++ )
{
Object o = c.case_label_list.v.elementAt( i );
if( o == null ) // null means "default"
{
label[ i ] = null;
thisCaseIsDefault = true;
}
else if( o instanceof ConstExpr )
label[ i ] = ( (ConstExpr)o ).value();
else if( o instanceof ScopedName )
label[ i ] = ( (ScopedName)o ).typeName();
}
// accessors
pw.println( "\tpublic " + c.element_spec.t.typeName()
+ " " + c.element_spec.d.name() + " ()" );
pw.println( "\t{" );
// if( switch_is_enum )
// pw.print("\t\tif( !discriminator.equals( ");
// else
pw.print( "\t\tif( discriminator != " );
for( int i = 0; i < caseLabelNum; i++ )
{
if( label[ i ] == null )
pw.print( defaultStr );
else
pw.print( label[ i ] );
if( i < caseLabelNum - 1 )
{
// if( switch_is_enum )
// pw.print(") && !discriminator.equals( ");
// else
pw.print( " && discriminator != " );
}
}
pw.println( ")\n\t\t\tthrow new org.omg.CORBA.BAD_OPERATION();" );
pw.println( "\t\treturn " + c.element_spec.d.name() + ";" );
pw.println( "\t}\n" );
// modifiers
pw.println( "\tpublic void " + c.element_spec.d.name() +
" (" + c.element_spec.t.typeName() + " _x)" );
pw.println( "\t{" );
pw.print( "\t\tdiscriminator = " );
if( label[ 0 ] == null )
pw.println( defaultStr + ";" );
else
pw.println( label[ 0 ] + ";" );
pw.println( "\t\t" + c.element_spec.d.name() + " = _x;" );
pw.println( "\t}\n" );
if( caseLabelNum > 1 || thisCaseIsDefault )
{
pw.println( "\tpublic void " + c.element_spec.d.name() + "( " +
ts.typeName() + " _discriminator, " +
c.element_spec.t.typeName() + " _x )" );
pw.println( "\t{" );
pw.print( "\t\tif( _discriminator != " );
for( int i = 0; i < caseLabelNum; i++ )
{
if( label[ i ] != null )
pw.print( label[ i ] );
else
pw.print( defaultStr );
if( i < caseLabelNum - 1 )
{
pw.print( " && _discriminator != " );
}
}
pw.println( ")\n\t\t\tthrow new org.omg.CORBA.BAD_OPERATION();" );
pw.println( "\t\tdiscriminator = _discriminator;" );
pw.println( "\t\t" + c.element_spec.d.name() + " = _x;" );
pw.println( "\t}\n" );
}
}
/* if there is no default case and case labels do not cover
* all discriminator values, we have to generate __defaultmethods
*/
if( def == 0 && defaultStr.length() > 0 )
{
pw.println( "\tpublic void __default ()" );
pw.println( "\t{" );
pw.println( "\t\tdiscriminator = " + defaultStr + ";" );
pw.println( "\t}" );
pw.println( "\tpublic void __default (" + ts.typeName() + " _discriminator)" );
pw.println( "\t{" );
pw.println( "\t\tdiscriminator = _discriminator;" );
pw.println( "\t}" );
}
pw.println( "}" );
}
public void printHolderClass( String className, PrintWriter ps )
{
if( !pack_name.equals( "" ) )
ps.println( "package " + pack_name + ";" );
printClassComment( className, ps );
ps.println( "public" + parser.getFinalString() + " class " + className + "Holder" );
ps.println( "\timplements org.omg.CORBA.portable.Streamable" );
ps.println( "{" );
ps.println( "\tpublic " + className + " value;\n" );
ps.println( "\tpublic " + className + "Holder ()" );
ps.println( "\t{" );
ps.println( "\t}" );
ps.println( "\tpublic " + className + "Holder (final " + className + " initial)" );
ps.println( "\t{" );
ps.println( "\t\tvalue = initial;" );
ps.println( "\t}" );
ps.println( "\tpublic org.omg.CORBA.TypeCode _type ()" );
ps.println( "\t{" );
ps.println( "\t\treturn " + className + "Helper.type ();" );
ps.println( "\t}" );
ps.println( "\tpublic void _read (final org.omg.CORBA.portable.InputStream in)" );
ps.println( "\t{" );
ps.println( "\t\tvalue = " + className + "Helper.read (in);" );
ps.println( "\t}" );
ps.println( "\tpublic void _write (final org.omg.CORBA.portable.OutputStream out)" );
ps.println( "\t{" );
ps.println( "\t\t" + className + "Helper.write (out, value);" );
ps.println( "\t}" );
ps.println( "}" );
}
private void printHelperClass( String className, PrintWriter ps )
{
if( !pack_name.equals( "" ) )
ps.println( "package " + pack_name + ";" );
printImport( ps );
printClassComment( className, ps );
ps.println( "public" + parser.getFinalString() + " class " + className + "Helper" );
ps.println( "{" );
ps.println( "\tprivate static org.omg.CORBA.TypeCode _type;" );
String _type = typeName();
TypeSpec.printInsertExtractMethods( ps, typeName() );
printIdMethod( ps );
/** read method */
ps.println( "\tpublic static " + className + " read (org.omg.CORBA.portable.InputStream in)" );
ps.println( "\t{" );
ps.println( "\t\t" + className + " result = new " + className + " ();" );
TypeSpec switch_ts_resolved = switch_type_spec;
if( switch_type_spec.type_spec instanceof ScopedName )
{
switch_ts_resolved = ( (ScopedName)switch_type_spec.type_spec ).resolvedTypeSpec();
}
String indent1 = "\t\t\t";
String indent2 = "\t\t\t\t";
if( switch_is_longlong )
{
indent1 = "\t\t";
indent2 = "\t\t\t";
}
String case_str = "case ";
String colon_str = ":";
String default_str = "default:";
if( switch_is_enum )
{
ps.println( "\t\t" + switch_ts_resolved.toString() + " disc = " +
switch_ts_resolved.toString() + ".from_int(in.read_long());" );
ps.println( "\t\tswitch (disc.value ())" );
ps.println( "\t\t{" );
}
else
{
ps.println( "\t\t" + switch_ts_resolved.toString() + " "
+ switch_ts_resolved.printReadStatement( "disc", "in" ) );
if( switch_is_bool )
{
/* special case: boolean is not a switch type in java */
case_str = "if (disc == ";
colon_str = ")";
default_str = "else";
}
else if( switch_is_longlong )
{
/* special case: long is not a switch type in java */
case_str = "if (disc == ";
colon_str = ")";
default_str = "else";
}
else
{
ps.println( "\t\tswitch (disc)" );
ps.println( "\t\t{" );
}
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
PrintWriter defaultWriter = new PrintWriter( bos );
PrintWriter alt = null;
for( Enumeration e = switch_body.caseListVector.elements(); e.hasMoreElements(); )
{
Case c = (Case)e.nextElement();
TypeSpec t = c.element_spec.t;
Declarator d = c.element_spec.d;
int caseLabelNum = c.case_label_list.v.size();
boolean was_default = false;
for( int i = 0; i < caseLabelNum; i++ )
{
Object o = c.case_label_list.v.elementAt( i );
if( o == null )
{
// null means "default"
defaultWriter.println( indent1 + default_str );
was_default = true;
}
else if( o instanceof ConstExpr )
{
ps.println( indent1 + case_str + ( (ConstExpr)o ).value() + colon_str );
}
else if( o instanceof ScopedName )
{
String _t = ( (ScopedName)o ).typeName();
if( switch_is_enum )
ps.println( indent1 + case_str + _t.substring( 0, _t.lastIndexOf( '.' ) + 1 )
+ "_" + _t.substring( _t.lastIndexOf( '.' ) + 1 ) + colon_str );
else
ps.println( indent1 + case_str + _t + colon_str );
}
if( i == caseLabelNum - 1 )
{
if( o == null )
{
alt = ps;
ps = defaultWriter;
}
ps.println( indent1 + "{" );
if( t instanceof ScopedName )
{
t = ( (ScopedName)t ).resolvedTypeSpec();
}
t = t.typeSpec();
String varname = "_var";
ps.println( indent2 + t.typeName() + " " + varname + ";" );
ps.println( indent2 + t.printReadStatement( varname, "in" ) );
ps.print( indent2 + "result." + d.name() + " (" );
if( caseLabelNum > 1 )
{
ps.print( "disc," );
}
ps.println( varname + ");" );
// no "break" written for default case or for "if" construct
if( o != null && !switch_is_bool && !switch_is_longlong )
{
ps.println( indent2 + "break;" );
}
if( switch_is_longlong )
{
ps.println( indent2 + "return result;" );
}
ps.println( indent1 + "}" );
if( o == null )
{
ps = alt;
}
}
}
if( switch_is_bool && !was_default )
{
case_str = "else " + case_str;
}
}
if( !explicit_default_case && !switch_is_bool && !switch_is_longlong && !allCasesCovered )
{
defaultWriter.println( "\t\t\tdefault: result.__default (disc);" );
}
if( !explicit_default_case && switch_is_longlong )
{
defaultWriter.println( "\t\tresult.__default (disc);" );
defaultWriter.println( "\t\treturn result;" );
}
defaultWriter.close();
if( bos.size() > 0 )
{
ps.print( bos.toString() );
}
if( !switch_is_bool && !switch_is_longlong )
{
ps.println( "\t\t}" ); // close switch statement
}
if( !switch_is_longlong )
{
ps.println( "\t\treturn result;" );
}
ps.println( "\t}" );
/** write method */
ps.println( "\tpublic static void write (org.omg.CORBA.portable.OutputStream out, " + className + " s)" );
ps.println( "\t{" );
if( switch_is_enum )
{
ps.println( "\t\tout.write_long(s.discriminator().value());" );
ps.println( "\t\tswitch(s.discriminator().value())" );
ps.println( "\t\t{" );
}
else
{
ps.println( "\t\t" + switch_type_spec.typeSpec().printWriteStatement( "s.discriminator ()", "out" ) + ";" );
if( switch_is_bool )
{
/* special case: booleans are no switch type in java */
case_str = "if(s.discriminator()==";
// colon_str and default_str are already set correctly
}
else if( switch_is_longlong )
{
ps.println( "\t\tlong disc = s.discriminator ();" );
}
else
{
ps.println( "\t\tswitch (s.discriminator ())" );
ps.println( "\t\t{" );
}
}
bos = new ByteArrayOutputStream();
defaultWriter = new PrintWriter( bos );
alt = null;
for( Enumeration e = switch_body.caseListVector.elements(); e.hasMoreElements(); )
{
Case c = (Case)e.nextElement();
TypeSpec t = c.element_spec.t;
Declarator d = c.element_spec.d;
int caseLabelNum = c.case_label_list.v.size();
boolean was_default = false;
for( int i = 0; i < caseLabelNum; i++ )
{
Object o = c.case_label_list.v.elementAt( i );
if( o == null )
{
// null means "default"
defaultWriter.println( indent1 + default_str );
was_default = true;
}
else if( o != null && o instanceof ConstExpr )
{
ps.println( indent1 + case_str + ( (ConstExpr)o ).value() + colon_str );
}
else if( o instanceof ScopedName )
{
String _t = ( (ScopedName)o ).typeName();
if( switch_is_enum )
ps.println( indent1 + case_str + _t.substring( 0, _t.lastIndexOf( '.' ) + 1 )
+ "_" + _t.substring( _t.lastIndexOf( '.' ) + 1 ) + colon_str );
else
ps.println( indent1 + case_str + _t + colon_str );
}
if( i == caseLabelNum - 1 )
{
if( o == null )
{
alt = ps;
ps = defaultWriter;
}
ps.println( indent1 + "{" );
if( t instanceof ScopedName )
t = ( (ScopedName)t ).resolvedTypeSpec();
t = t.typeSpec();
ps.println( indent2 + t.printWriteStatement( "s." + d.name() + " ()", "out" ) );
// no "break" written for default case
if( o != null && !switch_is_bool && !switch_is_longlong )
{
ps.println( indent2 + "break;" );
}
if( switch_is_longlong )
{
ps.println( indent2 + "return;" );
}
ps.println( indent1 + "}" );
if( o == null )
{
ps = alt;
}
}
}
if( switch_is_bool && !was_default )
{
case_str = "else " + case_str;
}
}
defaultWriter.close();
if( bos.size() > 0 )
{
ps.print( bos.toString() );
}
/* close switch statement */
if( !switch_is_bool && !switch_is_longlong )
{
ps.println( "\t\t}" );
}
ps.println( "\t}" );
/** type() */
ps.println( "\tpublic static org.omg.CORBA.TypeCode type ()" );
ps.println( "\t{" );
ps.println( "\t\tif (_type == null)" );
ps.println( "\t\t{" );
ps.println( "\t\t\torg.omg.CORBA.UnionMember[] members = new org.omg.CORBA.UnionMember[" + labels + "];" );
ps.println( "\t\t\torg.omg.CORBA.Any label_any;" );
- int mi = 0;
TypeSpec label_t = switch_type_spec.typeSpec();
while( label_t instanceof ScopedName || label_t instanceof AliasTypeSpec )
{
if( label_t instanceof ScopedName )
label_t = ( (ScopedName)label_t ).resolvedTypeSpec();
if( label_t instanceof AliasTypeSpec )
label_t = ( (AliasTypeSpec)label_t ).originalType();
}
label_t = label_t.typeSpec();
+ int mi = switch_body.caseListVector.size () - 1;
for( Enumeration e = switch_body.caseListVector.elements(); e.hasMoreElements(); )
{
Case c = (Case)e.nextElement();
TypeSpec t = c.element_spec.t;
while( t instanceof ScopedName || t instanceof AliasTypeSpec )
{
if( t instanceof ScopedName )
t = ( (ScopedName)t ).resolvedTypeSpec();
if( t instanceof AliasTypeSpec )
t = ( (AliasTypeSpec)t ).originalType();
}
t = t.typeSpec();
Declarator d = c.element_spec.d;
int caseLabelNum = c.case_label_list.v.size();
for( int i = 0; i < caseLabelNum; i++ )
{
Object o = c.case_label_list.v.elementAt( i );
ps.println( "\t\t\tlabel_any = org.omg.CORBA.ORB.init().create_any ();" );
if( o == null )
{
ps.println( "\t\t\tlabel_any.insert_octet ((byte)0);" );
}
else if( label_t instanceof BaseType )
{
if( ( label_t instanceof CharType ) ||
( label_t instanceof BooleanType ) ||
( label_t instanceof LongType ) ||
( label_t instanceof LongLongType ) )
{
ps.print( "\t\t\tlabel_any." + label_t.printInsertExpression() + " (" );
}
else if( label_t instanceof ShortType )
{
ps.print( "\t\t\tlabel_any." + label_t.printInsertExpression() + " ((short)" );
}
else
{
throw new RuntimeException( "Compiler error: unrecognized BaseType: "
+ label_t.typeName() + ":" + label_t + ": " + label_t.typeSpec()
+ ": " + label_t.getClass().getName() );
}
ps.println( ( (ConstExpr)o ).value() + ");" );
}
else if( switch_is_enum )
{
String _t = ( (ScopedName)o ).typeName();
ps.println( "\t\t\t" + _t.substring( 0, _t.lastIndexOf( '.' ) )
+ "Helper.insert( label_any, " + _t + " );" );
}
else
{
throw new Error( "Compiler error: unrecognized label type: " + label_t.typeName() );
}
- ps.print( "\t\t\tmembers[" + ( mi++ ) + "] = new org.omg.CORBA.UnionMember (\"" + d.deEscapeName() + "\", label_any, " );
+ ps.print( "\t\t\tmembers[" + ( mi-- ) + "] = new org.omg.CORBA.UnionMember (\"" + d.deEscapeName() + "\", label_any, " );
if( t instanceof ConstrTypeSpec )
{
ps.print( t.typeSpec().toString() + "Helper.type()," );
}
else
{
ps.print( t.typeSpec().getTypeCodeExpression() + "," );
}
ps.println( "null);" );
}
}
ps.print( "\t\t\t _type = org.omg.CORBA.ORB.init().create_union_tc(id(),\"" + className() + "\"," );
ps.println( switch_type_spec.typeSpec().getTypeCodeExpression() + ", members);" );
ps.println( "\t\t}" );
ps.println( "\t\treturn _type;" );
ps.println( "\t}" );
ps.println( "}" ); // end of helper class
}
/** generate required classes */
public void print( PrintWriter ps )
{
setPrintPhaseNames();
/** no code generation for included definitions */
if( included && !generateIncluded() )
return;
/** only write once */
if( written )
{
return;
}
// Forward declaration
if (switch_type_spec != null)
{
try
{
switch_body.print( ps );
String className = className();
String path = parser.out_dir + fileSeparator +
pack_name.replace( '.', fileSeparator );
File dir = new File( path );
if( !dir.exists() )
if( !dir.mkdirs() )
{
org.jacorb.idl.parser.fatal_error( "Unable to create " + path, null );
}
/** print the mapped java class */
String fname = className + ".java";
PrintWriter decl_ps = new PrintWriter( new java.io.FileWriter( new File( dir, fname ) ) );
printUnionClass( className, decl_ps );
decl_ps.close();
/** print the holder class */
fname = className + "Holder.java";
decl_ps = new PrintWriter( new java.io.FileWriter( new File( dir, fname ) ) );
printHolderClass( className, decl_ps );
decl_ps.close();
/** print the helper class */
fname = className + "Helper.java";
decl_ps = new PrintWriter( new java.io.FileWriter( new File( dir, fname ) ) );
printHelperClass( className, decl_ps );
decl_ps.close();
written = true;
}
catch( java.io.IOException i )
{
System.err.println( "File IO error" );
i.printStackTrace();
}
}
}
private TypeSpec getElementType( ElementSpec element )
{
TypeSpec tspec = element.t;
// Arrays are handled as a special case. Parser generates
// an ArrayDeclarator for an array, need to spot this and
// create appropriate type information with an ArrayTypeSpec.
if( element.d.d instanceof ArrayDeclarator )
{
tspec = new ArrayTypeSpec( new_num(), tspec,
(ArrayDeclarator)element.d.d, pack_name );
tspec.parse();
}
return tspec;
}
}
| false | true | private void printHelperClass( String className, PrintWriter ps )
{
if( !pack_name.equals( "" ) )
ps.println( "package " + pack_name + ";" );
printImport( ps );
printClassComment( className, ps );
ps.println( "public" + parser.getFinalString() + " class " + className + "Helper" );
ps.println( "{" );
ps.println( "\tprivate static org.omg.CORBA.TypeCode _type;" );
String _type = typeName();
TypeSpec.printInsertExtractMethods( ps, typeName() );
printIdMethod( ps );
/** read method */
ps.println( "\tpublic static " + className + " read (org.omg.CORBA.portable.InputStream in)" );
ps.println( "\t{" );
ps.println( "\t\t" + className + " result = new " + className + " ();" );
TypeSpec switch_ts_resolved = switch_type_spec;
if( switch_type_spec.type_spec instanceof ScopedName )
{
switch_ts_resolved = ( (ScopedName)switch_type_spec.type_spec ).resolvedTypeSpec();
}
String indent1 = "\t\t\t";
String indent2 = "\t\t\t\t";
if( switch_is_longlong )
{
indent1 = "\t\t";
indent2 = "\t\t\t";
}
String case_str = "case ";
String colon_str = ":";
String default_str = "default:";
if( switch_is_enum )
{
ps.println( "\t\t" + switch_ts_resolved.toString() + " disc = " +
switch_ts_resolved.toString() + ".from_int(in.read_long());" );
ps.println( "\t\tswitch (disc.value ())" );
ps.println( "\t\t{" );
}
else
{
ps.println( "\t\t" + switch_ts_resolved.toString() + " "
+ switch_ts_resolved.printReadStatement( "disc", "in" ) );
if( switch_is_bool )
{
/* special case: boolean is not a switch type in java */
case_str = "if (disc == ";
colon_str = ")";
default_str = "else";
}
else if( switch_is_longlong )
{
/* special case: long is not a switch type in java */
case_str = "if (disc == ";
colon_str = ")";
default_str = "else";
}
else
{
ps.println( "\t\tswitch (disc)" );
ps.println( "\t\t{" );
}
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
PrintWriter defaultWriter = new PrintWriter( bos );
PrintWriter alt = null;
for( Enumeration e = switch_body.caseListVector.elements(); e.hasMoreElements(); )
{
Case c = (Case)e.nextElement();
TypeSpec t = c.element_spec.t;
Declarator d = c.element_spec.d;
int caseLabelNum = c.case_label_list.v.size();
boolean was_default = false;
for( int i = 0; i < caseLabelNum; i++ )
{
Object o = c.case_label_list.v.elementAt( i );
if( o == null )
{
// null means "default"
defaultWriter.println( indent1 + default_str );
was_default = true;
}
else if( o instanceof ConstExpr )
{
ps.println( indent1 + case_str + ( (ConstExpr)o ).value() + colon_str );
}
else if( o instanceof ScopedName )
{
String _t = ( (ScopedName)o ).typeName();
if( switch_is_enum )
ps.println( indent1 + case_str + _t.substring( 0, _t.lastIndexOf( '.' ) + 1 )
+ "_" + _t.substring( _t.lastIndexOf( '.' ) + 1 ) + colon_str );
else
ps.println( indent1 + case_str + _t + colon_str );
}
if( i == caseLabelNum - 1 )
{
if( o == null )
{
alt = ps;
ps = defaultWriter;
}
ps.println( indent1 + "{" );
if( t instanceof ScopedName )
{
t = ( (ScopedName)t ).resolvedTypeSpec();
}
t = t.typeSpec();
String varname = "_var";
ps.println( indent2 + t.typeName() + " " + varname + ";" );
ps.println( indent2 + t.printReadStatement( varname, "in" ) );
ps.print( indent2 + "result." + d.name() + " (" );
if( caseLabelNum > 1 )
{
ps.print( "disc," );
}
ps.println( varname + ");" );
// no "break" written for default case or for "if" construct
if( o != null && !switch_is_bool && !switch_is_longlong )
{
ps.println( indent2 + "break;" );
}
if( switch_is_longlong )
{
ps.println( indent2 + "return result;" );
}
ps.println( indent1 + "}" );
if( o == null )
{
ps = alt;
}
}
}
if( switch_is_bool && !was_default )
{
case_str = "else " + case_str;
}
}
if( !explicit_default_case && !switch_is_bool && !switch_is_longlong && !allCasesCovered )
{
defaultWriter.println( "\t\t\tdefault: result.__default (disc);" );
}
if( !explicit_default_case && switch_is_longlong )
{
defaultWriter.println( "\t\tresult.__default (disc);" );
defaultWriter.println( "\t\treturn result;" );
}
defaultWriter.close();
if( bos.size() > 0 )
{
ps.print( bos.toString() );
}
if( !switch_is_bool && !switch_is_longlong )
{
ps.println( "\t\t}" ); // close switch statement
}
if( !switch_is_longlong )
{
ps.println( "\t\treturn result;" );
}
ps.println( "\t}" );
/** write method */
ps.println( "\tpublic static void write (org.omg.CORBA.portable.OutputStream out, " + className + " s)" );
ps.println( "\t{" );
if( switch_is_enum )
{
ps.println( "\t\tout.write_long(s.discriminator().value());" );
ps.println( "\t\tswitch(s.discriminator().value())" );
ps.println( "\t\t{" );
}
else
{
ps.println( "\t\t" + switch_type_spec.typeSpec().printWriteStatement( "s.discriminator ()", "out" ) + ";" );
if( switch_is_bool )
{
/* special case: booleans are no switch type in java */
case_str = "if(s.discriminator()==";
// colon_str and default_str are already set correctly
}
else if( switch_is_longlong )
{
ps.println( "\t\tlong disc = s.discriminator ();" );
}
else
{
ps.println( "\t\tswitch (s.discriminator ())" );
ps.println( "\t\t{" );
}
}
bos = new ByteArrayOutputStream();
defaultWriter = new PrintWriter( bos );
alt = null;
for( Enumeration e = switch_body.caseListVector.elements(); e.hasMoreElements(); )
{
Case c = (Case)e.nextElement();
TypeSpec t = c.element_spec.t;
Declarator d = c.element_spec.d;
int caseLabelNum = c.case_label_list.v.size();
boolean was_default = false;
for( int i = 0; i < caseLabelNum; i++ )
{
Object o = c.case_label_list.v.elementAt( i );
if( o == null )
{
// null means "default"
defaultWriter.println( indent1 + default_str );
was_default = true;
}
else if( o != null && o instanceof ConstExpr )
{
ps.println( indent1 + case_str + ( (ConstExpr)o ).value() + colon_str );
}
else if( o instanceof ScopedName )
{
String _t = ( (ScopedName)o ).typeName();
if( switch_is_enum )
ps.println( indent1 + case_str + _t.substring( 0, _t.lastIndexOf( '.' ) + 1 )
+ "_" + _t.substring( _t.lastIndexOf( '.' ) + 1 ) + colon_str );
else
ps.println( indent1 + case_str + _t + colon_str );
}
if( i == caseLabelNum - 1 )
{
if( o == null )
{
alt = ps;
ps = defaultWriter;
}
ps.println( indent1 + "{" );
if( t instanceof ScopedName )
t = ( (ScopedName)t ).resolvedTypeSpec();
t = t.typeSpec();
ps.println( indent2 + t.printWriteStatement( "s." + d.name() + " ()", "out" ) );
// no "break" written for default case
if( o != null && !switch_is_bool && !switch_is_longlong )
{
ps.println( indent2 + "break;" );
}
if( switch_is_longlong )
{
ps.println( indent2 + "return;" );
}
ps.println( indent1 + "}" );
if( o == null )
{
ps = alt;
}
}
}
if( switch_is_bool && !was_default )
{
case_str = "else " + case_str;
}
}
defaultWriter.close();
if( bos.size() > 0 )
{
ps.print( bos.toString() );
}
/* close switch statement */
if( !switch_is_bool && !switch_is_longlong )
{
ps.println( "\t\t}" );
}
ps.println( "\t}" );
/** type() */
ps.println( "\tpublic static org.omg.CORBA.TypeCode type ()" );
ps.println( "\t{" );
ps.println( "\t\tif (_type == null)" );
ps.println( "\t\t{" );
ps.println( "\t\t\torg.omg.CORBA.UnionMember[] members = new org.omg.CORBA.UnionMember[" + labels + "];" );
ps.println( "\t\t\torg.omg.CORBA.Any label_any;" );
int mi = 0;
TypeSpec label_t = switch_type_spec.typeSpec();
while( label_t instanceof ScopedName || label_t instanceof AliasTypeSpec )
{
if( label_t instanceof ScopedName )
label_t = ( (ScopedName)label_t ).resolvedTypeSpec();
if( label_t instanceof AliasTypeSpec )
label_t = ( (AliasTypeSpec)label_t ).originalType();
}
label_t = label_t.typeSpec();
for( Enumeration e = switch_body.caseListVector.elements(); e.hasMoreElements(); )
{
Case c = (Case)e.nextElement();
TypeSpec t = c.element_spec.t;
while( t instanceof ScopedName || t instanceof AliasTypeSpec )
{
if( t instanceof ScopedName )
t = ( (ScopedName)t ).resolvedTypeSpec();
if( t instanceof AliasTypeSpec )
t = ( (AliasTypeSpec)t ).originalType();
}
t = t.typeSpec();
Declarator d = c.element_spec.d;
int caseLabelNum = c.case_label_list.v.size();
for( int i = 0; i < caseLabelNum; i++ )
{
Object o = c.case_label_list.v.elementAt( i );
ps.println( "\t\t\tlabel_any = org.omg.CORBA.ORB.init().create_any ();" );
if( o == null )
{
ps.println( "\t\t\tlabel_any.insert_octet ((byte)0);" );
}
else if( label_t instanceof BaseType )
{
if( ( label_t instanceof CharType ) ||
( label_t instanceof BooleanType ) ||
( label_t instanceof LongType ) ||
( label_t instanceof LongLongType ) )
{
ps.print( "\t\t\tlabel_any." + label_t.printInsertExpression() + " (" );
}
else if( label_t instanceof ShortType )
{
ps.print( "\t\t\tlabel_any." + label_t.printInsertExpression() + " ((short)" );
}
else
{
throw new RuntimeException( "Compiler error: unrecognized BaseType: "
+ label_t.typeName() + ":" + label_t + ": " + label_t.typeSpec()
+ ": " + label_t.getClass().getName() );
}
ps.println( ( (ConstExpr)o ).value() + ");" );
}
else if( switch_is_enum )
{
String _t = ( (ScopedName)o ).typeName();
ps.println( "\t\t\t" + _t.substring( 0, _t.lastIndexOf( '.' ) )
+ "Helper.insert( label_any, " + _t + " );" );
}
else
{
throw new Error( "Compiler error: unrecognized label type: " + label_t.typeName() );
}
ps.print( "\t\t\tmembers[" + ( mi++ ) + "] = new org.omg.CORBA.UnionMember (\"" + d.deEscapeName() + "\", label_any, " );
if( t instanceof ConstrTypeSpec )
{
ps.print( t.typeSpec().toString() + "Helper.type()," );
}
else
{
ps.print( t.typeSpec().getTypeCodeExpression() + "," );
}
ps.println( "null);" );
}
}
ps.print( "\t\t\t _type = org.omg.CORBA.ORB.init().create_union_tc(id(),\"" + className() + "\"," );
ps.println( switch_type_spec.typeSpec().getTypeCodeExpression() + ", members);" );
ps.println( "\t\t}" );
ps.println( "\t\treturn _type;" );
ps.println( "\t}" );
ps.println( "}" ); // end of helper class
}
| private void printHelperClass( String className, PrintWriter ps )
{
if( !pack_name.equals( "" ) )
ps.println( "package " + pack_name + ";" );
printImport( ps );
printClassComment( className, ps );
ps.println( "public" + parser.getFinalString() + " class " + className + "Helper" );
ps.println( "{" );
ps.println( "\tprivate static org.omg.CORBA.TypeCode _type;" );
String _type = typeName();
TypeSpec.printInsertExtractMethods( ps, typeName() );
printIdMethod( ps );
/** read method */
ps.println( "\tpublic static " + className + " read (org.omg.CORBA.portable.InputStream in)" );
ps.println( "\t{" );
ps.println( "\t\t" + className + " result = new " + className + " ();" );
TypeSpec switch_ts_resolved = switch_type_spec;
if( switch_type_spec.type_spec instanceof ScopedName )
{
switch_ts_resolved = ( (ScopedName)switch_type_spec.type_spec ).resolvedTypeSpec();
}
String indent1 = "\t\t\t";
String indent2 = "\t\t\t\t";
if( switch_is_longlong )
{
indent1 = "\t\t";
indent2 = "\t\t\t";
}
String case_str = "case ";
String colon_str = ":";
String default_str = "default:";
if( switch_is_enum )
{
ps.println( "\t\t" + switch_ts_resolved.toString() + " disc = " +
switch_ts_resolved.toString() + ".from_int(in.read_long());" );
ps.println( "\t\tswitch (disc.value ())" );
ps.println( "\t\t{" );
}
else
{
ps.println( "\t\t" + switch_ts_resolved.toString() + " "
+ switch_ts_resolved.printReadStatement( "disc", "in" ) );
if( switch_is_bool )
{
/* special case: boolean is not a switch type in java */
case_str = "if (disc == ";
colon_str = ")";
default_str = "else";
}
else if( switch_is_longlong )
{
/* special case: long is not a switch type in java */
case_str = "if (disc == ";
colon_str = ")";
default_str = "else";
}
else
{
ps.println( "\t\tswitch (disc)" );
ps.println( "\t\t{" );
}
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
PrintWriter defaultWriter = new PrintWriter( bos );
PrintWriter alt = null;
for( Enumeration e = switch_body.caseListVector.elements(); e.hasMoreElements(); )
{
Case c = (Case)e.nextElement();
TypeSpec t = c.element_spec.t;
Declarator d = c.element_spec.d;
int caseLabelNum = c.case_label_list.v.size();
boolean was_default = false;
for( int i = 0; i < caseLabelNum; i++ )
{
Object o = c.case_label_list.v.elementAt( i );
if( o == null )
{
// null means "default"
defaultWriter.println( indent1 + default_str );
was_default = true;
}
else if( o instanceof ConstExpr )
{
ps.println( indent1 + case_str + ( (ConstExpr)o ).value() + colon_str );
}
else if( o instanceof ScopedName )
{
String _t = ( (ScopedName)o ).typeName();
if( switch_is_enum )
ps.println( indent1 + case_str + _t.substring( 0, _t.lastIndexOf( '.' ) + 1 )
+ "_" + _t.substring( _t.lastIndexOf( '.' ) + 1 ) + colon_str );
else
ps.println( indent1 + case_str + _t + colon_str );
}
if( i == caseLabelNum - 1 )
{
if( o == null )
{
alt = ps;
ps = defaultWriter;
}
ps.println( indent1 + "{" );
if( t instanceof ScopedName )
{
t = ( (ScopedName)t ).resolvedTypeSpec();
}
t = t.typeSpec();
String varname = "_var";
ps.println( indent2 + t.typeName() + " " + varname + ";" );
ps.println( indent2 + t.printReadStatement( varname, "in" ) );
ps.print( indent2 + "result." + d.name() + " (" );
if( caseLabelNum > 1 )
{
ps.print( "disc," );
}
ps.println( varname + ");" );
// no "break" written for default case or for "if" construct
if( o != null && !switch_is_bool && !switch_is_longlong )
{
ps.println( indent2 + "break;" );
}
if( switch_is_longlong )
{
ps.println( indent2 + "return result;" );
}
ps.println( indent1 + "}" );
if( o == null )
{
ps = alt;
}
}
}
if( switch_is_bool && !was_default )
{
case_str = "else " + case_str;
}
}
if( !explicit_default_case && !switch_is_bool && !switch_is_longlong && !allCasesCovered )
{
defaultWriter.println( "\t\t\tdefault: result.__default (disc);" );
}
if( !explicit_default_case && switch_is_longlong )
{
defaultWriter.println( "\t\tresult.__default (disc);" );
defaultWriter.println( "\t\treturn result;" );
}
defaultWriter.close();
if( bos.size() > 0 )
{
ps.print( bos.toString() );
}
if( !switch_is_bool && !switch_is_longlong )
{
ps.println( "\t\t}" ); // close switch statement
}
if( !switch_is_longlong )
{
ps.println( "\t\treturn result;" );
}
ps.println( "\t}" );
/** write method */
ps.println( "\tpublic static void write (org.omg.CORBA.portable.OutputStream out, " + className + " s)" );
ps.println( "\t{" );
if( switch_is_enum )
{
ps.println( "\t\tout.write_long(s.discriminator().value());" );
ps.println( "\t\tswitch(s.discriminator().value())" );
ps.println( "\t\t{" );
}
else
{
ps.println( "\t\t" + switch_type_spec.typeSpec().printWriteStatement( "s.discriminator ()", "out" ) + ";" );
if( switch_is_bool )
{
/* special case: booleans are no switch type in java */
case_str = "if(s.discriminator()==";
// colon_str and default_str are already set correctly
}
else if( switch_is_longlong )
{
ps.println( "\t\tlong disc = s.discriminator ();" );
}
else
{
ps.println( "\t\tswitch (s.discriminator ())" );
ps.println( "\t\t{" );
}
}
bos = new ByteArrayOutputStream();
defaultWriter = new PrintWriter( bos );
alt = null;
for( Enumeration e = switch_body.caseListVector.elements(); e.hasMoreElements(); )
{
Case c = (Case)e.nextElement();
TypeSpec t = c.element_spec.t;
Declarator d = c.element_spec.d;
int caseLabelNum = c.case_label_list.v.size();
boolean was_default = false;
for( int i = 0; i < caseLabelNum; i++ )
{
Object o = c.case_label_list.v.elementAt( i );
if( o == null )
{
// null means "default"
defaultWriter.println( indent1 + default_str );
was_default = true;
}
else if( o != null && o instanceof ConstExpr )
{
ps.println( indent1 + case_str + ( (ConstExpr)o ).value() + colon_str );
}
else if( o instanceof ScopedName )
{
String _t = ( (ScopedName)o ).typeName();
if( switch_is_enum )
ps.println( indent1 + case_str + _t.substring( 0, _t.lastIndexOf( '.' ) + 1 )
+ "_" + _t.substring( _t.lastIndexOf( '.' ) + 1 ) + colon_str );
else
ps.println( indent1 + case_str + _t + colon_str );
}
if( i == caseLabelNum - 1 )
{
if( o == null )
{
alt = ps;
ps = defaultWriter;
}
ps.println( indent1 + "{" );
if( t instanceof ScopedName )
t = ( (ScopedName)t ).resolvedTypeSpec();
t = t.typeSpec();
ps.println( indent2 + t.printWriteStatement( "s." + d.name() + " ()", "out" ) );
// no "break" written for default case
if( o != null && !switch_is_bool && !switch_is_longlong )
{
ps.println( indent2 + "break;" );
}
if( switch_is_longlong )
{
ps.println( indent2 + "return;" );
}
ps.println( indent1 + "}" );
if( o == null )
{
ps = alt;
}
}
}
if( switch_is_bool && !was_default )
{
case_str = "else " + case_str;
}
}
defaultWriter.close();
if( bos.size() > 0 )
{
ps.print( bos.toString() );
}
/* close switch statement */
if( !switch_is_bool && !switch_is_longlong )
{
ps.println( "\t\t}" );
}
ps.println( "\t}" );
/** type() */
ps.println( "\tpublic static org.omg.CORBA.TypeCode type ()" );
ps.println( "\t{" );
ps.println( "\t\tif (_type == null)" );
ps.println( "\t\t{" );
ps.println( "\t\t\torg.omg.CORBA.UnionMember[] members = new org.omg.CORBA.UnionMember[" + labels + "];" );
ps.println( "\t\t\torg.omg.CORBA.Any label_any;" );
TypeSpec label_t = switch_type_spec.typeSpec();
while( label_t instanceof ScopedName || label_t instanceof AliasTypeSpec )
{
if( label_t instanceof ScopedName )
label_t = ( (ScopedName)label_t ).resolvedTypeSpec();
if( label_t instanceof AliasTypeSpec )
label_t = ( (AliasTypeSpec)label_t ).originalType();
}
label_t = label_t.typeSpec();
int mi = switch_body.caseListVector.size () - 1;
for( Enumeration e = switch_body.caseListVector.elements(); e.hasMoreElements(); )
{
Case c = (Case)e.nextElement();
TypeSpec t = c.element_spec.t;
while( t instanceof ScopedName || t instanceof AliasTypeSpec )
{
if( t instanceof ScopedName )
t = ( (ScopedName)t ).resolvedTypeSpec();
if( t instanceof AliasTypeSpec )
t = ( (AliasTypeSpec)t ).originalType();
}
t = t.typeSpec();
Declarator d = c.element_spec.d;
int caseLabelNum = c.case_label_list.v.size();
for( int i = 0; i < caseLabelNum; i++ )
{
Object o = c.case_label_list.v.elementAt( i );
ps.println( "\t\t\tlabel_any = org.omg.CORBA.ORB.init().create_any ();" );
if( o == null )
{
ps.println( "\t\t\tlabel_any.insert_octet ((byte)0);" );
}
else if( label_t instanceof BaseType )
{
if( ( label_t instanceof CharType ) ||
( label_t instanceof BooleanType ) ||
( label_t instanceof LongType ) ||
( label_t instanceof LongLongType ) )
{
ps.print( "\t\t\tlabel_any." + label_t.printInsertExpression() + " (" );
}
else if( label_t instanceof ShortType )
{
ps.print( "\t\t\tlabel_any." + label_t.printInsertExpression() + " ((short)" );
}
else
{
throw new RuntimeException( "Compiler error: unrecognized BaseType: "
+ label_t.typeName() + ":" + label_t + ": " + label_t.typeSpec()
+ ": " + label_t.getClass().getName() );
}
ps.println( ( (ConstExpr)o ).value() + ");" );
}
else if( switch_is_enum )
{
String _t = ( (ScopedName)o ).typeName();
ps.println( "\t\t\t" + _t.substring( 0, _t.lastIndexOf( '.' ) )
+ "Helper.insert( label_any, " + _t + " );" );
}
else
{
throw new Error( "Compiler error: unrecognized label type: " + label_t.typeName() );
}
ps.print( "\t\t\tmembers[" + ( mi-- ) + "] = new org.omg.CORBA.UnionMember (\"" + d.deEscapeName() + "\", label_any, " );
if( t instanceof ConstrTypeSpec )
{
ps.print( t.typeSpec().toString() + "Helper.type()," );
}
else
{
ps.print( t.typeSpec().getTypeCodeExpression() + "," );
}
ps.println( "null);" );
}
}
ps.print( "\t\t\t _type = org.omg.CORBA.ORB.init().create_union_tc(id(),\"" + className() + "\"," );
ps.println( switch_type_spec.typeSpec().getTypeCodeExpression() + ", members);" );
ps.println( "\t\t}" );
ps.println( "\t\treturn _type;" );
ps.println( "\t}" );
ps.println( "}" ); // end of helper class
}
|
diff --git a/src/ClassAdminFrontEnd/FrmTable.java b/src/ClassAdminFrontEnd/FrmTable.java
index 1d7570c..8d47063 100644
--- a/src/ClassAdminFrontEnd/FrmTable.java
+++ b/src/ClassAdminFrontEnd/FrmTable.java
@@ -1,595 +1,595 @@
package ClassAdminFrontEnd;
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.util.LinkedList;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JColorChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import org.jdesktop.swingx.JXTable;
import ClassAdminBackEnd.BetweenFormat;
import ClassAdminBackEnd.BorderCase;
import ClassAdminBackEnd.EntityType;
import ClassAdminBackEnd.Format;
import ClassAdminBackEnd.LeafMarkEntity;
import ClassAdminBackEnd.LeafStringEntity;
import ClassAdminBackEnd.Project;
import ClassAdminBackEnd.SuperEntity;
import ClassAdminBackEnd.SuperEntityPointer;
import ClassAdminBackEnd.TableCellListener;
import ClassAdminBackEnd.GreaterThanFormat;
import ClassAdminBackEnd.LessThanFormat;
public class FrmTable extends JPanel {
private JXTable table;
private JButton btnAdd;
private JTextField txtField1;
private JTextField txtField2;
public String[] headers;
public LinkedList<LinkedList<Boolean>> filters = new LinkedList<LinkedList<Boolean>>();
public Boolean[] dataFilter;
public LinkedList<LinkedList<SuperEntity>> data;
public LinkedList<SuperEntity> headersList;
public LinkedList<Integer> headPoints;
public JComboBox cbheaders;
public JComboBox cbFormatting;
public String[] numberHeads;
public DefaultTableModel tableModel;
public Project project;
private LinkedList<Integer> selected = new LinkedList<Integer>();
/**
* redraws the entire table
*/
public void redraw() {
this.data = project.getHead().getDataLinkedList();
this.headers = project.getHead().getHeaders();
tableModel.setColumnCount(0);
tableModel.setRowCount(0);
for (int x = 0; x < data.size(); x++) {
LinkedList<Boolean> temp = new LinkedList<Boolean>();
for (int y = 0; y < data.get(0).size(); y++) {
temp.add(false);
}
filters.add(temp);
}
dataFilter = new Boolean[data.size()];
for (int x = 0; x < dataFilter.length; x++)
dataFilter[x] = true;
for (int x = 0; x < headers.length; x++) {
tableModel.addColumn(headers[x]);
}
Object[] temp = new Object[data.get(0).size()];
for (int x = 0; x < data.size(); x++) {
for (int y = 0; y < data.get(0).size(); y++) {
temp[y] = data.get(x).get(y).getValue();
}
tableModel.addRow(temp);
}
}
public SuperEntity[] getFirstSelectedStudent() {
if (table.getSelectedRow() != -1) {
SuperEntity[] tempForReturn = new SuperEntity[data.get(0).size()];
int selected = table.getSelectedRow();
for (int x = 0; x < data.get(0).size(); x++) {
tempForReturn[x] = data.get(selected).get(x);
}
return tempForReturn;
} else {
return null;
}
}
public String getFirstSelectedStudentNr() {
return (data.get(table.getSelectedRow()).get(0).getValue());
}
public void filterTable() {
// boolean filtered = false;
LinkedList<Integer> removes = new LinkedList<Integer>();
// --------------------------------------
// adds all the rows to tha table again
Object[][] temp = new Object[data.size()][data.get(0).size()];
for (int x = 0; x < data.size(); x++) {
for (int y = 0; y < data.get(0).size(); y++) {
temp[x][y] = data.get(x).get(y).getValue();
}
}
int rows = tableModel.getRowCount();
for (int x = 0; x < rows; x++) {
tableModel.removeRow(0);
}
for (int x = 0; x < data.size(); x++) {
tableModel.addRow(temp[x]);
}
// --------------------------------------------------
for (int x = 0; x < filters.size(); x++) {
for (int y = 0; y < filters.get(0).size(); y++) {
if (filters.get(x).get(y)) {
removes.add(x);
y = filters.get(0).size();
}
}
}
for (int x = removes.size() - 1; x >= 0; x--) {
tableModel.removeRow(removes.get(x));
}
}
public FrmTable(String[] headers, LinkedList<LinkedList<SuperEntity>> data,
Project project) {
this.data = data;
this.project = project;
this.headers = headers;
project.getTables().add(this);
createGUI();
}
/**
* Used to create the table and draw all of it
*/
private void createGUI() {
// -------------------------------------------------------------------------------------------------------
// create the filters array with everything false
for (int x = 0; x < data.size(); x++) {
LinkedList<Boolean> temp = new LinkedList<Boolean>();
for (int y = 0; y < data.get(0).size(); y++) {
temp.add(false);
}
filters.add(temp);
}
// ---------------------------------------------------------------------------------------------------------------
dataFilter = new Boolean[data.size()];
for (int x = 0; x < dataFilter.length; x++)
dataFilter[x] = true;
setLayout(new BorderLayout());
JScrollPane pane = new JScrollPane();
Action action = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
TableCellListener tcl = (TableCellListener) e.getSource();
if (tcl.getOldValue() != tcl.getNewValue()) {
if (data.get(tcl.getRow()).get(tcl.getColumn())
.getDetails().getType().getIsTextField()) {
data.get(tcl.getRow()).get(tcl.getColumn())
.getDetails()
.setValue((String) tcl.getNewValue());
} else {
try {
if (Double.parseDouble((String) tcl.getNewValue()) >= 0
&& data.get(tcl.getRow())
.get(tcl.getColumn()).getType()
.getMaxValue() >= Double
.parseDouble((String) tcl
.getNewValue())) {
data.get(tcl.getRow())
.get(tcl.getColumn())
.setMark(
(Double.parseDouble((String) tcl
.getNewValue())));
for (int x = 0; x < data.get(0).size(); x++) {
table.getModel().setValueAt(
data.get(tcl.getRow()).get(x)
.getValue(), tcl.getRow(),
x);
}
tableModel.fireTableDataChanged();
table.repaint();
} else {
table.getModel().setValueAt(tcl.getOldValue(),
tcl.getRow(), tcl.getColumn());
}
} catch (Exception ex) {
table.getModel().setValueAt(tcl.getOldValue(),
tcl.getRow(), tcl.getColumn());
}
}
}
}
};
Object[][] temp = new Object[data.size()][data.get(0).size()];
for (int x = 0; x < data.size(); x++) {
for (int y = 0; y < data.get(0).size(); y++) {
temp[x][y] = data.get(x).get(y).getValue();
}
}
table = new JXTable() {
public Component prepareRenderer(TableCellRenderer renderer,
int Index_row, int Index_col) {
- Component comp = super.prepareRenderer(renderer, Index_row,
- Index_col);
+ Component comp = super.prepareRenderer(renderer, convertRowIndexToModel(Index_row),
+ convertColumnIndexToModel(Index_col));
// even index, selected or not selected
try {
LinkedList<Color> backgroundColors = new LinkedList<Color>();
LinkedList<Color> textColors = new LinkedList<Color>();
LinkedList<Format> format = data
.get(table.getRowSorter().convertRowIndexToModel(
Index_row)).get(convertColumnIndexToModel(Index_col)).getType()
.getFormatting();
if (project.getSelected().contains(
data.get(
table.getRowSorter()
.convertRowIndexToModel(Index_row))
.get(convertColumnIndexToModel(Index_col)))) {
int[] intTest = table.getSelectedRows();
boolean temp = false;
for (int x = 0; x < intTest.length; x++) {
if (intTest[x] == convertRowIndexToModel(Index_row)) {
temp = true;
}
}
if (intTest.length > 0) {
if (!temp) {
project.getSelected()
.remove(data
.get(table
.getRowSorter()
.convertRowIndexToModel(
Index_row))
.get(convertColumnIndexToModel(Index_col)));
comp.setBackground(Color.white);
}
} else {
backgroundColors.add(Color.orange);
comp.setBackground(Color.orange);
}
} else {
comp.setBackground(Color.white);
}
- if (isCellSelected(Index_row, Index_col)) {
+ if (isCellSelected(convertRowIndexToModel(Index_row), Index_col)) {
backgroundColors.add(Color.orange);
comp.setBackground(Color.orange);
if (convertColumnIndexToModel(Index_col) == 0)
if (!project.getSelected().contains(
data.get(
table.getRowSorter()
.convertRowIndexToModel(
Index_row)).get(
convertColumnIndexToModel(Index_col)))) {
if (table.getSelectedRowCount() > 1) {
// Clear selection if only one is selected
if (table.getSelectedRow() == table
.convertRowIndexToModel(Index_row))
project.clearselected();
// Set the selected in the back-end
project.setSelected(table
.convertRowIndexToModel(Index_row),
false);
} else {
project.clearselected();
project.setSelected(table
.convertRowIndexToModel(Index_row),
false);
}
}
comp.setForeground(Color.black);
// table.repaint();
}
for (int x = 0; x < format.size(); x++) {
if (format.get(x).evaluate(data.get(table.getRowSorter().convertRowIndexToModel(Index_row)).get(convertColumnIndexToModel(Index_col)).getMark())) {
if (format.get(x).getHighlightColor() != null) {
backgroundColors.add(format.get(x)
.getHighlightColor());
} else if (format.get(x).getTextColor() != null) {
textColors.add(format.get(x).getTextColor());
}
}
int r = 0;
int g = 0;
int b = 0;
for (int y = 0; y < backgroundColors.size(); y++) {
r += backgroundColors.get(y).getRed();
g += backgroundColors.get(y).getGreen();
b += backgroundColors.get(y).getBlue();
}
if (backgroundColors.size() > 0) {
r = r / backgroundColors.size();
g = g / backgroundColors.size();
b = b / backgroundColors.size();
}
if (r != 0 || g != 0 || b != 0) {
comp.setBackground(new Color(r, g, b));
}
r = 0;
g = 0;
b = 0;
for (int y = 0; y < textColors.size(); y++) {
r += textColors.get(y).getRed();
g += textColors.get(y).getGreen();
b += textColors.get(y).getBlue();
}
if (textColors.size() > 0) {
r = r / textColors.size();
g = g / textColors.size();
b = b / textColors.size();
}
if (r != 0 || g != 0 || b != 0) {
comp.setForeground(new Color(r, g, b));
}
}
LinkedList<BorderCase> bordercases = data.get(table.getRowSorter().convertRowIndexToModel(Index_row)).get(convertColumnIndexToModel(Index_col)).getType().getBorderCasing();
for (int x = 0; x < bordercases.size(); x++) {
if (bordercases.get(x).isBorderCase(data.get(table.getRowSorter().convertRowIndexToModel(Index_row)).get(convertColumnIndexToModel(Index_col)))) {
comp.setBackground(Color.cyan);
}
}
return comp;
} catch (Exception e) {
// TODO: handle exception
return null;
}
}
};
// ---------------------------------------------------------------------------------------------------
// tooltip when hovering
table.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseMoved(MouseEvent e) {
Point p = e.getPoint();
int row = table.rowAtPoint(p);
int col = table.columnAtPoint(p);
String toolTip = "";
try {
LinkedList<Format> format = data
.get(table.getRowSorter().convertRowIndexToModel(
row)).get(col).getType().getFormatting();
for (int x = 0; x < format.size(); x++) {
if (format.get(x).evaluate(
data.get(
table.getRowSorter()
.convertRowIndexToModel(row))
.get(col).getMark())) {
if (format.get(x).getHighlightColor() != null) {
toolTip += " Background Color due to "
+ format.get(x).getDescription();
toolTip += "\t";
} else if (format.get(x).getTextColor() != null) {
toolTip += " Text Color due to "
+ format.get(x).getDescription();
toolTip += "\t";
}
}
}
table.setToolTipText(toolTip);
} catch (Exception ex) {
// TODO: handle exception
}
}// end MouseMoved
}); // end MouseMotionAdapter
// =---------------------------------------------------------------------------------------------
table.setAutoCreateRowSorter(true);
TableCellListener tcl = new TableCellListener(table, action);
table.addPropertyChangeListener(tcl);
// --------------------------------------------------------------------------------------------
table.getSelectionModel().addListSelectionListener(
new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent arg0) {
int viewRow = table.getSelectedRow();
if (viewRow < 0) {
} else {
int modelRow = table
.convertRowIndexToModel(viewRow);
}
}
});
// --------------------------------------------------------------------------------------
headPoints = new LinkedList<Integer>();
numberHeads = project.getHead().getNumberHeaders();
for (int x = 0; x < headers.length; x++) {
if (!data.get(0).get(x).getType().getIsTextField()) {
headPoints.add(x);
numberHeads[headPoints.size() - 1] = headers[x];
}
}
pane.setViewportView(table);
JPanel eastPanel = new JPanel();
JPanel border = new JPanel();
JButton bordercase = new JButton("Add bordercase");
border.add(bordercase);
cbheaders = new JComboBox(numberHeads);
headersList = project.getHead().getHeadersLinkedList();
border.add(cbheaders);
// =--------------------------------------------------------------------------------------------------------------
eastPanel.setLayout(new GridLayout(0, 1));
JPanel northPanel = new JPanel();
add(northPanel, BorderLayout.NORTH);
// add(eastPanel, BorderLayout.EAST);
add(pane, BorderLayout.CENTER);
table.setColumnControlVisible(true);
table.setHorizontalScrollEnabled(true);
tableModel = new DefaultTableModel(temp, (Object[]) headers);
table.setModel(tableModel);
// =--------------------------------------------------------------------------------------------------------------
}
// =--------------------------------------------------------------------------------------------------------------
/**
* @param entType
* @param parent
* Creates a new entity entType with its parent
*/
public void createEntities(EntityType entType, SuperEntityPointer parent) {
LinkedList<EntityType> list = entType.getSubEntityType();
if (entType.getIsTextField()) {
LeafStringEntity head = new LeafStringEntity(entType,
parent.getTarget(), "");
SuperEntityPointer headPointer = new SuperEntityPointer(head);
for (int x = 0; x < list.size(); x++) {
createEntities(list.get(x), headPointer);
}
} else {
LeafMarkEntity head = new LeafMarkEntity(entType,
parent.getTarget(), 0);
SuperEntityPointer headPointer = new SuperEntityPointer(head);
for (int x = 0; x < list.size(); x++) {
createEntities(list.get(x), headPointer);
}
}
}
// =--------------------------------------------------------------------------------------------------------------
/**
* implements the tableModelListener and adds to the tableChanged function
*
*/
public class InteractiveTableModelListener implements TableModelListener {
public void tableChanged(TableModelEvent evt) {
if (evt.getType() == TableModelEvent.UPDATE) {
int column = evt.getColumn();
int row = evt.getFirstRow();
table.setColumnSelectionInterval(column + 1, column + 1);
table.setRowSelectionInterval(row, row);
table.repaint();
}
}
}
/**
* @return returns the table
*/
public JTable getTable() {
return table;
}
/**
* @return returns the data linkedlist
*/
public LinkedList<LinkedList<SuperEntity>> getData() {
return data;
}
/**
* @param text
* if you type in the search box it looks for a matching cell and
* selects its row
*/
public void search(String text) {
boolean temp = false;
if (text.compareTo("") != 0) {
project.getSelected().clear();
project.clearselected();
for (int x = 0; x < data.size(); x++) {
for (int y = 0; y < data.get(0).size(); y++) {
if ((data.get(x).get(y).getValue().toLowerCase())
.contains(text.toLowerCase())) {
temp = true;
if (!project.getSelected().contains(data.get(x).get(0)))
;
for (int z = 0; z < data.get(x).size(); z++) {
project.getSelected().add(data.get(x).get(z));
project.setSelected(x, false);
}
tableModel.fireTableDataChanged();
}
}
}
if (!temp) {
project.getSelected().clear();
tableModel.fireTableDataChanged();
}
}
}
}
| false | true | private void createGUI() {
// -------------------------------------------------------------------------------------------------------
// create the filters array with everything false
for (int x = 0; x < data.size(); x++) {
LinkedList<Boolean> temp = new LinkedList<Boolean>();
for (int y = 0; y < data.get(0).size(); y++) {
temp.add(false);
}
filters.add(temp);
}
// ---------------------------------------------------------------------------------------------------------------
dataFilter = new Boolean[data.size()];
for (int x = 0; x < dataFilter.length; x++)
dataFilter[x] = true;
setLayout(new BorderLayout());
JScrollPane pane = new JScrollPane();
Action action = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
TableCellListener tcl = (TableCellListener) e.getSource();
if (tcl.getOldValue() != tcl.getNewValue()) {
if (data.get(tcl.getRow()).get(tcl.getColumn())
.getDetails().getType().getIsTextField()) {
data.get(tcl.getRow()).get(tcl.getColumn())
.getDetails()
.setValue((String) tcl.getNewValue());
} else {
try {
if (Double.parseDouble((String) tcl.getNewValue()) >= 0
&& data.get(tcl.getRow())
.get(tcl.getColumn()).getType()
.getMaxValue() >= Double
.parseDouble((String) tcl
.getNewValue())) {
data.get(tcl.getRow())
.get(tcl.getColumn())
.setMark(
(Double.parseDouble((String) tcl
.getNewValue())));
for (int x = 0; x < data.get(0).size(); x++) {
table.getModel().setValueAt(
data.get(tcl.getRow()).get(x)
.getValue(), tcl.getRow(),
x);
}
tableModel.fireTableDataChanged();
table.repaint();
} else {
table.getModel().setValueAt(tcl.getOldValue(),
tcl.getRow(), tcl.getColumn());
}
} catch (Exception ex) {
table.getModel().setValueAt(tcl.getOldValue(),
tcl.getRow(), tcl.getColumn());
}
}
}
}
};
Object[][] temp = new Object[data.size()][data.get(0).size()];
for (int x = 0; x < data.size(); x++) {
for (int y = 0; y < data.get(0).size(); y++) {
temp[x][y] = data.get(x).get(y).getValue();
}
}
table = new JXTable() {
public Component prepareRenderer(TableCellRenderer renderer,
int Index_row, int Index_col) {
Component comp = super.prepareRenderer(renderer, Index_row,
Index_col);
// even index, selected or not selected
try {
LinkedList<Color> backgroundColors = new LinkedList<Color>();
LinkedList<Color> textColors = new LinkedList<Color>();
LinkedList<Format> format = data
.get(table.getRowSorter().convertRowIndexToModel(
Index_row)).get(convertColumnIndexToModel(Index_col)).getType()
.getFormatting();
if (project.getSelected().contains(
data.get(
table.getRowSorter()
.convertRowIndexToModel(Index_row))
.get(convertColumnIndexToModel(Index_col)))) {
int[] intTest = table.getSelectedRows();
boolean temp = false;
for (int x = 0; x < intTest.length; x++) {
if (intTest[x] == convertRowIndexToModel(Index_row)) {
temp = true;
}
}
if (intTest.length > 0) {
if (!temp) {
project.getSelected()
.remove(data
.get(table
.getRowSorter()
.convertRowIndexToModel(
Index_row))
.get(convertColumnIndexToModel(Index_col)));
comp.setBackground(Color.white);
}
} else {
backgroundColors.add(Color.orange);
comp.setBackground(Color.orange);
}
} else {
comp.setBackground(Color.white);
}
if (isCellSelected(Index_row, Index_col)) {
backgroundColors.add(Color.orange);
comp.setBackground(Color.orange);
if (convertColumnIndexToModel(Index_col) == 0)
if (!project.getSelected().contains(
data.get(
table.getRowSorter()
.convertRowIndexToModel(
Index_row)).get(
convertColumnIndexToModel(Index_col)))) {
if (table.getSelectedRowCount() > 1) {
// Clear selection if only one is selected
if (table.getSelectedRow() == table
.convertRowIndexToModel(Index_row))
project.clearselected();
// Set the selected in the back-end
project.setSelected(table
.convertRowIndexToModel(Index_row),
false);
} else {
project.clearselected();
project.setSelected(table
.convertRowIndexToModel(Index_row),
false);
}
}
comp.setForeground(Color.black);
// table.repaint();
}
for (int x = 0; x < format.size(); x++) {
if (format.get(x).evaluate(data.get(table.getRowSorter().convertRowIndexToModel(Index_row)).get(convertColumnIndexToModel(Index_col)).getMark())) {
if (format.get(x).getHighlightColor() != null) {
backgroundColors.add(format.get(x)
.getHighlightColor());
} else if (format.get(x).getTextColor() != null) {
textColors.add(format.get(x).getTextColor());
}
}
int r = 0;
int g = 0;
int b = 0;
for (int y = 0; y < backgroundColors.size(); y++) {
r += backgroundColors.get(y).getRed();
g += backgroundColors.get(y).getGreen();
b += backgroundColors.get(y).getBlue();
}
if (backgroundColors.size() > 0) {
r = r / backgroundColors.size();
g = g / backgroundColors.size();
b = b / backgroundColors.size();
}
if (r != 0 || g != 0 || b != 0) {
comp.setBackground(new Color(r, g, b));
}
r = 0;
g = 0;
b = 0;
for (int y = 0; y < textColors.size(); y++) {
r += textColors.get(y).getRed();
g += textColors.get(y).getGreen();
b += textColors.get(y).getBlue();
}
if (textColors.size() > 0) {
r = r / textColors.size();
g = g / textColors.size();
b = b / textColors.size();
}
if (r != 0 || g != 0 || b != 0) {
comp.setForeground(new Color(r, g, b));
}
}
LinkedList<BorderCase> bordercases = data.get(table.getRowSorter().convertRowIndexToModel(Index_row)).get(convertColumnIndexToModel(Index_col)).getType().getBorderCasing();
for (int x = 0; x < bordercases.size(); x++) {
if (bordercases.get(x).isBorderCase(data.get(table.getRowSorter().convertRowIndexToModel(Index_row)).get(convertColumnIndexToModel(Index_col)))) {
comp.setBackground(Color.cyan);
}
}
return comp;
} catch (Exception e) {
// TODO: handle exception
return null;
}
}
};
// ---------------------------------------------------------------------------------------------------
// tooltip when hovering
table.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseMoved(MouseEvent e) {
Point p = e.getPoint();
int row = table.rowAtPoint(p);
int col = table.columnAtPoint(p);
String toolTip = "";
try {
LinkedList<Format> format = data
.get(table.getRowSorter().convertRowIndexToModel(
row)).get(col).getType().getFormatting();
for (int x = 0; x < format.size(); x++) {
if (format.get(x).evaluate(
data.get(
table.getRowSorter()
.convertRowIndexToModel(row))
.get(col).getMark())) {
if (format.get(x).getHighlightColor() != null) {
toolTip += " Background Color due to "
+ format.get(x).getDescription();
toolTip += "\t";
} else if (format.get(x).getTextColor() != null) {
toolTip += " Text Color due to "
+ format.get(x).getDescription();
toolTip += "\t";
}
}
}
table.setToolTipText(toolTip);
} catch (Exception ex) {
// TODO: handle exception
}
}// end MouseMoved
}); // end MouseMotionAdapter
// =---------------------------------------------------------------------------------------------
table.setAutoCreateRowSorter(true);
TableCellListener tcl = new TableCellListener(table, action);
table.addPropertyChangeListener(tcl);
// --------------------------------------------------------------------------------------------
table.getSelectionModel().addListSelectionListener(
new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent arg0) {
int viewRow = table.getSelectedRow();
if (viewRow < 0) {
} else {
int modelRow = table
.convertRowIndexToModel(viewRow);
}
}
});
// --------------------------------------------------------------------------------------
headPoints = new LinkedList<Integer>();
numberHeads = project.getHead().getNumberHeaders();
for (int x = 0; x < headers.length; x++) {
if (!data.get(0).get(x).getType().getIsTextField()) {
headPoints.add(x);
numberHeads[headPoints.size() - 1] = headers[x];
}
}
pane.setViewportView(table);
JPanel eastPanel = new JPanel();
JPanel border = new JPanel();
JButton bordercase = new JButton("Add bordercase");
border.add(bordercase);
cbheaders = new JComboBox(numberHeads);
headersList = project.getHead().getHeadersLinkedList();
border.add(cbheaders);
// =--------------------------------------------------------------------------------------------------------------
eastPanel.setLayout(new GridLayout(0, 1));
JPanel northPanel = new JPanel();
add(northPanel, BorderLayout.NORTH);
// add(eastPanel, BorderLayout.EAST);
add(pane, BorderLayout.CENTER);
table.setColumnControlVisible(true);
table.setHorizontalScrollEnabled(true);
tableModel = new DefaultTableModel(temp, (Object[]) headers);
table.setModel(tableModel);
// =--------------------------------------------------------------------------------------------------------------
}
| private void createGUI() {
// -------------------------------------------------------------------------------------------------------
// create the filters array with everything false
for (int x = 0; x < data.size(); x++) {
LinkedList<Boolean> temp = new LinkedList<Boolean>();
for (int y = 0; y < data.get(0).size(); y++) {
temp.add(false);
}
filters.add(temp);
}
// ---------------------------------------------------------------------------------------------------------------
dataFilter = new Boolean[data.size()];
for (int x = 0; x < dataFilter.length; x++)
dataFilter[x] = true;
setLayout(new BorderLayout());
JScrollPane pane = new JScrollPane();
Action action = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
TableCellListener tcl = (TableCellListener) e.getSource();
if (tcl.getOldValue() != tcl.getNewValue()) {
if (data.get(tcl.getRow()).get(tcl.getColumn())
.getDetails().getType().getIsTextField()) {
data.get(tcl.getRow()).get(tcl.getColumn())
.getDetails()
.setValue((String) tcl.getNewValue());
} else {
try {
if (Double.parseDouble((String) tcl.getNewValue()) >= 0
&& data.get(tcl.getRow())
.get(tcl.getColumn()).getType()
.getMaxValue() >= Double
.parseDouble((String) tcl
.getNewValue())) {
data.get(tcl.getRow())
.get(tcl.getColumn())
.setMark(
(Double.parseDouble((String) tcl
.getNewValue())));
for (int x = 0; x < data.get(0).size(); x++) {
table.getModel().setValueAt(
data.get(tcl.getRow()).get(x)
.getValue(), tcl.getRow(),
x);
}
tableModel.fireTableDataChanged();
table.repaint();
} else {
table.getModel().setValueAt(tcl.getOldValue(),
tcl.getRow(), tcl.getColumn());
}
} catch (Exception ex) {
table.getModel().setValueAt(tcl.getOldValue(),
tcl.getRow(), tcl.getColumn());
}
}
}
}
};
Object[][] temp = new Object[data.size()][data.get(0).size()];
for (int x = 0; x < data.size(); x++) {
for (int y = 0; y < data.get(0).size(); y++) {
temp[x][y] = data.get(x).get(y).getValue();
}
}
table = new JXTable() {
public Component prepareRenderer(TableCellRenderer renderer,
int Index_row, int Index_col) {
Component comp = super.prepareRenderer(renderer, convertRowIndexToModel(Index_row),
convertColumnIndexToModel(Index_col));
// even index, selected or not selected
try {
LinkedList<Color> backgroundColors = new LinkedList<Color>();
LinkedList<Color> textColors = new LinkedList<Color>();
LinkedList<Format> format = data
.get(table.getRowSorter().convertRowIndexToModel(
Index_row)).get(convertColumnIndexToModel(Index_col)).getType()
.getFormatting();
if (project.getSelected().contains(
data.get(
table.getRowSorter()
.convertRowIndexToModel(Index_row))
.get(convertColumnIndexToModel(Index_col)))) {
int[] intTest = table.getSelectedRows();
boolean temp = false;
for (int x = 0; x < intTest.length; x++) {
if (intTest[x] == convertRowIndexToModel(Index_row)) {
temp = true;
}
}
if (intTest.length > 0) {
if (!temp) {
project.getSelected()
.remove(data
.get(table
.getRowSorter()
.convertRowIndexToModel(
Index_row))
.get(convertColumnIndexToModel(Index_col)));
comp.setBackground(Color.white);
}
} else {
backgroundColors.add(Color.orange);
comp.setBackground(Color.orange);
}
} else {
comp.setBackground(Color.white);
}
if (isCellSelected(convertRowIndexToModel(Index_row), Index_col)) {
backgroundColors.add(Color.orange);
comp.setBackground(Color.orange);
if (convertColumnIndexToModel(Index_col) == 0)
if (!project.getSelected().contains(
data.get(
table.getRowSorter()
.convertRowIndexToModel(
Index_row)).get(
convertColumnIndexToModel(Index_col)))) {
if (table.getSelectedRowCount() > 1) {
// Clear selection if only one is selected
if (table.getSelectedRow() == table
.convertRowIndexToModel(Index_row))
project.clearselected();
// Set the selected in the back-end
project.setSelected(table
.convertRowIndexToModel(Index_row),
false);
} else {
project.clearselected();
project.setSelected(table
.convertRowIndexToModel(Index_row),
false);
}
}
comp.setForeground(Color.black);
// table.repaint();
}
for (int x = 0; x < format.size(); x++) {
if (format.get(x).evaluate(data.get(table.getRowSorter().convertRowIndexToModel(Index_row)).get(convertColumnIndexToModel(Index_col)).getMark())) {
if (format.get(x).getHighlightColor() != null) {
backgroundColors.add(format.get(x)
.getHighlightColor());
} else if (format.get(x).getTextColor() != null) {
textColors.add(format.get(x).getTextColor());
}
}
int r = 0;
int g = 0;
int b = 0;
for (int y = 0; y < backgroundColors.size(); y++) {
r += backgroundColors.get(y).getRed();
g += backgroundColors.get(y).getGreen();
b += backgroundColors.get(y).getBlue();
}
if (backgroundColors.size() > 0) {
r = r / backgroundColors.size();
g = g / backgroundColors.size();
b = b / backgroundColors.size();
}
if (r != 0 || g != 0 || b != 0) {
comp.setBackground(new Color(r, g, b));
}
r = 0;
g = 0;
b = 0;
for (int y = 0; y < textColors.size(); y++) {
r += textColors.get(y).getRed();
g += textColors.get(y).getGreen();
b += textColors.get(y).getBlue();
}
if (textColors.size() > 0) {
r = r / textColors.size();
g = g / textColors.size();
b = b / textColors.size();
}
if (r != 0 || g != 0 || b != 0) {
comp.setForeground(new Color(r, g, b));
}
}
LinkedList<BorderCase> bordercases = data.get(table.getRowSorter().convertRowIndexToModel(Index_row)).get(convertColumnIndexToModel(Index_col)).getType().getBorderCasing();
for (int x = 0; x < bordercases.size(); x++) {
if (bordercases.get(x).isBorderCase(data.get(table.getRowSorter().convertRowIndexToModel(Index_row)).get(convertColumnIndexToModel(Index_col)))) {
comp.setBackground(Color.cyan);
}
}
return comp;
} catch (Exception e) {
// TODO: handle exception
return null;
}
}
};
// ---------------------------------------------------------------------------------------------------
// tooltip when hovering
table.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseMoved(MouseEvent e) {
Point p = e.getPoint();
int row = table.rowAtPoint(p);
int col = table.columnAtPoint(p);
String toolTip = "";
try {
LinkedList<Format> format = data
.get(table.getRowSorter().convertRowIndexToModel(
row)).get(col).getType().getFormatting();
for (int x = 0; x < format.size(); x++) {
if (format.get(x).evaluate(
data.get(
table.getRowSorter()
.convertRowIndexToModel(row))
.get(col).getMark())) {
if (format.get(x).getHighlightColor() != null) {
toolTip += " Background Color due to "
+ format.get(x).getDescription();
toolTip += "\t";
} else if (format.get(x).getTextColor() != null) {
toolTip += " Text Color due to "
+ format.get(x).getDescription();
toolTip += "\t";
}
}
}
table.setToolTipText(toolTip);
} catch (Exception ex) {
// TODO: handle exception
}
}// end MouseMoved
}); // end MouseMotionAdapter
// =---------------------------------------------------------------------------------------------
table.setAutoCreateRowSorter(true);
TableCellListener tcl = new TableCellListener(table, action);
table.addPropertyChangeListener(tcl);
// --------------------------------------------------------------------------------------------
table.getSelectionModel().addListSelectionListener(
new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent arg0) {
int viewRow = table.getSelectedRow();
if (viewRow < 0) {
} else {
int modelRow = table
.convertRowIndexToModel(viewRow);
}
}
});
// --------------------------------------------------------------------------------------
headPoints = new LinkedList<Integer>();
numberHeads = project.getHead().getNumberHeaders();
for (int x = 0; x < headers.length; x++) {
if (!data.get(0).get(x).getType().getIsTextField()) {
headPoints.add(x);
numberHeads[headPoints.size() - 1] = headers[x];
}
}
pane.setViewportView(table);
JPanel eastPanel = new JPanel();
JPanel border = new JPanel();
JButton bordercase = new JButton("Add bordercase");
border.add(bordercase);
cbheaders = new JComboBox(numberHeads);
headersList = project.getHead().getHeadersLinkedList();
border.add(cbheaders);
// =--------------------------------------------------------------------------------------------------------------
eastPanel.setLayout(new GridLayout(0, 1));
JPanel northPanel = new JPanel();
add(northPanel, BorderLayout.NORTH);
// add(eastPanel, BorderLayout.EAST);
add(pane, BorderLayout.CENTER);
table.setColumnControlVisible(true);
table.setHorizontalScrollEnabled(true);
tableModel = new DefaultTableModel(temp, (Object[]) headers);
table.setModel(tableModel);
// =--------------------------------------------------------------------------------------------------------------
}
|
diff --git a/Tupl/src/main/java/org/cojen/tupl/Database.java b/Tupl/src/main/java/org/cojen/tupl/Database.java
index c22aba76..f6cd63c2 100644
--- a/Tupl/src/main/java/org/cojen/tupl/Database.java
+++ b/Tupl/src/main/java/org/cojen/tupl/Database.java
@@ -1,2214 +1,2214 @@
/*
* Copyright 2011-2012 Brian S O'Neill
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cojen.tupl;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import static org.cojen.tupl.Node.*;
import static org.cojen.tupl.Utils.*;
/**
* Main database class, containing a collection of transactional indexes. Call
* {@link #open open} to obtain a Database instance. Examples:
*
* <p>Open a non-durable database, limited to a max size of 100MB:
*
* <pre>
* DatabaseConfig config = new DatabaseConfig().maxCacheSize(100_000_000);
* Database db = Database.open(config);
* </pre>
*
* <p>Open a regular database, setting the minimum cache size to ensure enough
* memory is initially available. A weak {@link DurabilityMode durability mode}
* offers the best transactional commit performance.
*
* <pre>
* DatabaseConfig config = new DatabaseConfig()
* .baseFilePath("/var/lib/tupl")
* .minCacheSize(100_000_000)
* .durabilityMode(DurabilityMode.NO_FLUSH);
*
* Database db = Database.open(config);
* </pre>
*
* <p>The following files are created by the above example:
*
* <ul>
* <li><code>/var/lib/tupl.db</code> – primary data file
* <li><code>/var/lib/tupl.info</code> – text file describing the database configuration
* <li><code>/var/lib/tupl.lock</code> – lock file to ensure that at most one process can have the database open
* <li><code>/var/lib/tupl.redo.0</code> – first redo log file
* </ul>
*
* @author Brian S O'Neill
* @see DatabaseConfig
*/
public final class Database extends CauseCloseable {
private static final int DEFAULT_CACHED_NODES = 1000;
// +2 for registry and key map root nodes, +1 for one user index, and +2
// for usage list to function correctly. It always assumes that the least
// recently used node points to a valid, more recently used node.
private static final int MIN_CACHED_NODES = 5;
// Approximate byte overhead per node. Influenced by many factors,
// including pointer size and child node references. This estimate assumes
// 32-bit pointers.
private static final int NODE_OVERHEAD = 100;
private static int nodeCountFromBytes(long bytes, int pageSize) {
if (bytes <= 0) {
return 0;
}
pageSize += NODE_OVERHEAD;
bytes += pageSize - 1;
if (bytes <= 0) {
// Overflow.
return Integer.MAX_VALUE;
}
long count = bytes / pageSize;
return count <= Integer.MAX_VALUE ? (int) count : Integer.MAX_VALUE;
}
private static long byteCountFromNodes(int nodes, int pageSize) {
return nodes * (long) (pageSize + NODE_OVERHEAD);
}
private static final int ENCODING_VERSION = 20120630;
private static final int I_ENCODING_VERSION = 0;
private static final int I_ROOT_PAGE_ID = I_ENCODING_VERSION + 4;
private static final int I_MASTER_UNDO_LOG_PAGE_ID = I_ROOT_PAGE_ID + 8;
private static final int I_TRANSACTION_ID = I_MASTER_UNDO_LOG_PAGE_ID + 8;
private static final int I_REDO_LOG_ID = I_TRANSACTION_ID + 8;
private static final int HEADER_SIZE = I_REDO_LOG_ID + 8;
static final byte KEY_TYPE_INDEX_NAME = 0;
static final byte KEY_TYPE_INDEX_ID = 1;
private static final int DEFAULT_PAGE_SIZE = 4096;
private static final int MINIMUM_PAGE_SIZE = 512;
private static final int MAXIMUM_PAGE_SIZE = 65536;
private final EventListener mEventListener;
private final LockedFile mLockFile;
final DurabilityMode mDurabilityMode;
final long mDefaultLockTimeoutNanos;
final LockManager mLockManager;
final RedoLog mRedoLog;
final PageDb mPageDb;
private final BufferPool mSpareBufferPool;
private final Latch mUsageLatch;
private int mMaxNodeCount;
private int mNodeCount;
private Node mMostRecentlyUsed;
private Node mLeastRecentlyUsed;
private final Lock mSharedCommitLock;
// Is either CACHED_DIRTY_0 or CACHED_DIRTY_1. Access is guarded by commit lock.
private byte mCommitState;
// Typically opposite of mCommitState, or negative if checkpoint is not in
// progress. Indicates which nodes are being flushed by the checkpoint.
private volatile int mCheckpointFlushState = CHECKPOINT_NOT_FLUSHING;
private static int CHECKPOINT_FLUSH_PREPARE = -2, CHECKPOINT_NOT_FLUSHING = -1;
// The root tree, which maps tree ids to other tree root node ids.
private final Tree mRegistry;
// Maps tree name keys to ids.
private final Tree mRegistryKeyMap;
// Maps tree names to open trees.
private final Map<byte[], Tree> mOpenTrees;
private final LHashTable.Obj<Tree> mOpenTreesById;
private final OrderedPageAllocator mAllocator;
private final FragmentCache mFragmentCache;
final int mMaxFragmentedEntrySize;
// Fragmented values which are transactionally deleted go here.
private volatile FragmentedTrash mFragmentedTrash;
private final Object mTxnIdLock = new Object();
// The following fields are guarded by mTxnIdLock.
private long mTxnId;
private UndoLog mTopUndoLog;
private int mUndoLogCount;
private final Object mCheckpointLock = new Object();
private volatile Checkpointer mCheckpointer;
private final TempFileManager mTempFileManager;
volatile boolean mClosed;
volatile Throwable mClosedCause;
/**
* Open a database, creating it if necessary.
*/
public static Database open(DatabaseConfig config) throws IOException {
config = config.clone();
Database db = new Database(config, false);
db.startCheckpointer(config);
return db;
}
/**
* Delete the contents of an existing database, and replace it with an
* empty one. When using a raw block device for the data file, this method
* must be used to format it.
*/
public static Database destroy(DatabaseConfig config) throws IOException {
config = config.clone();
if (config.mReadOnly) {
throw new IllegalArgumentException("Cannot destroy read-only database");
}
Database db = new Database(config, true);
db.startCheckpointer(config);
return db;
}
/**
* @param config cloned config
*/
private Database(DatabaseConfig config, boolean destroy) throws IOException {
mEventListener = SafeEventListener.makeSafe(config.mEventListener);
File baseFile = config.mBaseFile;
File[] dataFiles = config.dataFiles();
int pageSize = config.mPageSize;
if (pageSize <= 0) {
config.pageSize(pageSize = DEFAULT_PAGE_SIZE);
} else if (pageSize < MINIMUM_PAGE_SIZE) {
throw new IllegalArgumentException
("Page size is too small: " + pageSize + " < " + MINIMUM_PAGE_SIZE);
} else if (pageSize > MAXIMUM_PAGE_SIZE) {
throw new IllegalArgumentException
("Page size is too large: " + pageSize + " > " + MAXIMUM_PAGE_SIZE);
}
int minCache, maxCache;
cacheSize: {
long minCachedBytes = Math.max(0, config.mMinCachedBytes);
long maxCachedBytes = Math.max(0, config.mMaxCachedBytes);
if (maxCachedBytes == 0) {
maxCachedBytes = minCachedBytes;
if (maxCachedBytes == 0) {
minCache = maxCache = DEFAULT_CACHED_NODES;
break cacheSize;
}
}
if (minCachedBytes > maxCachedBytes) {
throw new IllegalArgumentException
("Minimum cache size exceeds maximum: " +
minCachedBytes + " > " + maxCachedBytes);
}
minCache = nodeCountFromBytes(minCachedBytes, pageSize);
maxCache = nodeCountFromBytes(maxCachedBytes, pageSize);
minCache = Math.max(MIN_CACHED_NODES, minCache);
maxCache = Math.max(MIN_CACHED_NODES, maxCache);
}
// Update config such that info file is correct.
config.mMinCachedBytes = byteCountFromNodes(minCache, pageSize);
config.mMaxCachedBytes = byteCountFromNodes(maxCache, pageSize);
mUsageLatch = new Latch();
mMaxNodeCount = maxCache;
mDurabilityMode = config.mDurabilityMode;
mDefaultLockTimeoutNanos = config.mLockTimeoutNanos;
mLockManager = new LockManager(mDefaultLockTimeoutNanos);
if (baseFile != null && !config.mReadOnly && config.mMkdirs) {
baseFile.getParentFile().mkdirs();
for (File f : dataFiles) {
f.getParentFile().mkdirs();
}
}
// Create lock file and write info file of properties.
if (baseFile == null) {
mLockFile = null;
} else {
mLockFile = new LockedFile(new File(baseFile.getPath() + ".lock"), config.mReadOnly);
if (!config.mReadOnly) {
File infoFile = new File(baseFile.getPath() + ".info");
Writer w = new BufferedWriter
(new OutputStreamWriter(new FileOutputStream(infoFile), "UTF-8"));
try {
config.writeInfo(w);
} finally {
w.close();
}
}
}
EnumSet<OpenOption> options = config.createOpenOptions();
if (baseFile != null && destroy) {
// Delete old redo log files.
deleteNumberedFiles(baseFile, ".redo.");
}
if (dataFiles == null) {
mPageDb = new NonPageDb(pageSize);
} else {
mPageDb = new DurablePageDb(pageSize, dataFiles, options, destroy);
}
mSharedCommitLock = mPageDb.sharedCommitLock();
try {
// Pre-allocate nodes. They are automatically added to the usage
// list, and so nothing special needs to be done to allow them to
// get used. Since the initial state is clean, evicting these
// nodes does nothing.
long cacheInitStart = 0;
if (mEventListener != null) {
mEventListener.notify(EventType.CACHE_INIT_BEGIN,
"Initializing %1$d cached nodes", minCache);
cacheInitStart = System.nanoTime();
}
try {
for (int i=minCache; --i>=0; ) {
allocLatchedNode(true).releaseExclusive();
}
} catch (OutOfMemoryError e) {
mMostRecentlyUsed = null;
mLeastRecentlyUsed = null;
throw new OutOfMemoryError
("Unable to allocate the minimum required number of cached nodes: " +
minCache);
}
if (mEventListener != null) {
double duration = (System.nanoTime() - cacheInitStart) / 1000000000.0;
- mEventListener.notify(EventType.CHECKPOINT_BEGIN,
+ mEventListener.notify(EventType.CACHE_INIT_COMPLETE,
"Cache initialization completed in %1$1.3f seconds",
duration, TimeUnit.SECONDS);
}
int spareBufferCount = Runtime.getRuntime().availableProcessors();
mSpareBufferPool = new BufferPool(mPageDb.pageSize(), spareBufferCount);
mSharedCommitLock.lock();
try {
mCommitState = CACHED_DIRTY_0;
} finally {
mSharedCommitLock.unlock();
}
byte[] header = new byte[HEADER_SIZE];
mPageDb.readExtraCommitData(header);
mRegistry = new Tree(this, Tree.REGISTRY_ID, null, null, loadRegistryRoot(header));
mOpenTrees = new TreeMap<byte[], Tree>(KeyComparator.THE);
mOpenTreesById = new LHashTable.Obj<Tree>(16);
synchronized (mTxnIdLock) {
mTxnId = readLongLE(header, I_TRANSACTION_ID);
}
long redoLogId = readLongLE(header, I_REDO_LOG_ID);
// Initialized, but not open yet.
mRedoLog = baseFile == null ? null : new RedoLog(baseFile, redoLogId);
mRegistryKeyMap = openInternalTree(Tree.REGISTRY_KEY_MAP_ID, true);
mAllocator = new OrderedPageAllocator
(mPageDb, null /*openInternalTree(Tree.PAGE_ALLOCATOR_ID, true)*/);
if (baseFile == null) {
// Non-durable database never evicts anything.
mFragmentCache = new FragmentMap();
} else {
// Regular database evicts automatically.
mFragmentCache = new FragmentCache(this, mMaxNodeCount);
}
{
Tree tree = openInternalTree(Tree.FRAGMENTED_TRASH_ID, false);
if (tree != null) {
mFragmentedTrash = new FragmentedTrash(tree);
}
}
// Limit maximum fragmented entry size to guarantee that 2 entries
// fit. Each also requires 2 bytes for pointer and up to 3 bytes
// for value length field.
mMaxFragmentedEntrySize = (pageSize - Node.TN_HEADER_SIZE - (2 + 3 + 2 + 3)) >> 1;
long recoveryStart = 0;
if (mRedoLog != null) {
// Perform recovery by examining redo and undo logs.
if (mEventListener != null) {
mEventListener.notify(EventType.RECOVERY_BEGIN, "Database recovery begin");
recoveryStart = System.nanoTime();
}
UndoLog masterUndoLog;
LHashTable.Obj<UndoLog> undoLogs;
{
long nodeId = readLongLE(header, I_MASTER_UNDO_LOG_PAGE_ID);
if (nodeId == 0) {
masterUndoLog = null;
undoLogs = null;
} else {
if (mEventListener != null) {
mEventListener.notify
(EventType.RECOVERY_LOAD_UNDO_LOGS, "Loading undo logs");
}
masterUndoLog = UndoLog.recoverMasterUndoLog(this, nodeId);
undoLogs = masterUndoLog.recoverLogs();
}
}
// List of all replayed redo log files which should be deleted
// after the recovery checkpoint.
ArrayList<Long> redosToDelete = new ArrayList<Long>(2);
if (redoReplay(undoLogs)) {
// Make sure old redo logs are deleted. Process might have
// exited before last checkpoint could delete them.
for (int i=1; i<=2; i++) {
mRedoLog.deleteOldFile(redoLogId - i);
}
redosToDelete.add(mRedoLog.openNewFile());
while (mRedoLog.isReplayMode()) {
// Last checkpoint was interrupted, so apply next log file too.
redoReplay(undoLogs);
redosToDelete.add(mRedoLog.openNewFile());
}
}
boolean doCheckpoint = false;
if (masterUndoLog != null) {
// Rollback or truncate all remaining undo logs. They were
// never explicitly rolled back, or they were committed but
// not cleaned up. This also deletes the master undo log.
if (mEventListener != null) {
mEventListener.notify
(EventType.RECOVERY_PROCESS_REMAINING,
"Processing remaining transactions");
}
if (masterUndoLog.processRemaining(undoLogs)) {
// Checkpoint ensures that undo logs don't get
// re-applied following a restart.
doCheckpoint = true;
}
}
if (doCheckpoint || !redosToDelete.isEmpty()) {
// The one and only recovery checkpoint.
checkpoint(true);
// Only delete redo logs after successful checkpoint.
for (long id : redosToDelete) {
mRedoLog.deleteOldFile(id);
}
}
}
// Delete lingering fragmented values after undo logs have been
// processed, ensuring deletes were committed.
if (mFragmentedTrash != null) {
if (mEventListener != null) {
mEventListener.notify(EventType.RECOVERY_DELETE_FRAGMENTS,
"Deleting unused large fragments");
}
if (mFragmentedTrash.emptyAllTrash()) {
checkpoint(true);
}
}
mTempFileManager = baseFile == null ? null : new TempFileManager(baseFile);
if (mRedoLog != null && mEventListener != null) {
double duration = (System.nanoTime() - recoveryStart) / 1000000000.0;
mEventListener.notify(EventType.RECOVERY_COMPLETE,
"Recovery completed in %1$1.3f seconds",
duration, TimeUnit.SECONDS);
}
} catch (Throwable e) {
closeQuietly(null, this, e);
throw rethrow(e);
}
}
private void startCheckpointer(DatabaseConfig config) {
if (mRedoLog == null && mTempFileManager == null) {
// Nothing is durable and nothing to ever clean up
return;
}
mCheckpointer = new Checkpointer(this, config.mCheckpointRateNanos);
// Register objects to automatically shutdown.
mCheckpointer.register(mRedoLog);
mCheckpointer.register(mTempFileManager);
mCheckpointer.start();
}
/*
void trace() throws IOException {
java.util.BitSet pages = mPageDb.tracePages();
mRegistry.mRoot.tracePages(this, pages);
mRegistryKeyMap.mRoot.tracePages(this, pages);
synchronized (mOpenTrees) {
for (Tree tree : mOpenTrees.values()) {
tree.mRoot.tracePages(this, pages);
}
}
System.out.println(pages);
System.out.println("lost: " + pages.cardinality());
System.out.println(mPageDb.stats());
}
*/
private boolean redoReplay(LHashTable.Obj<UndoLog> undoLogs) throws IOException {
RedoLogTxnScanner scanner = new RedoLogTxnScanner();
if (mEventListener != null) {
mEventListener.notify
(EventType.RECOVERY_SCAN_REDO_LOG, "Scanning redo log: %1$d", mRedoLog.logId());
}
if (!mRedoLog.replay(scanner)) {
return false;
}
if (mEventListener != null) {
mEventListener.notify
(EventType.RECOVERY_APPLY_REDO_LOG, "Applying redo log: %1$d", mRedoLog.logId());
}
if (!mRedoLog.replay(new RedoLogApplier(this, scanner, undoLogs))) {
return false;
}
long redoTxnId = scanner.highestTxnId();
if (redoTxnId != 0) synchronized (mTxnIdLock) {
// Subtract for modulo comparison.
if (mTxnId == 0 || (redoTxnId - mTxnId) > 0) {
mTxnId = redoTxnId;
}
}
return true;
}
/**
* Returns the given named index, returning null if not found.
*
* @return shared Index instance; null if not found
*/
public Index findIndex(byte[] name) throws IOException {
return openIndex(name.clone(), false);
}
/**
* Returns the given named index, returning null if not found. Name is UTF-8
* encoded.
*
* @return shared Index instance; null if not found
*/
public Index findIndex(String name) throws IOException {
return openIndex(name.getBytes("UTF-8"), false);
}
/**
* Returns the given named index, creating it if necessary.
*
* @return shared Index instance
*/
public Index openIndex(byte[] name) throws IOException {
return openIndex(name.clone(), true);
}
/**
* Returns the given named index, creating it if necessary. Name is UTF-8
* encoded.
*
* @return shared Index instance
*/
public Index openIndex(String name) throws IOException {
return openIndex(name.getBytes("UTF-8"), true);
}
/**
* Returns an index by its identifier, returning null if not found.
*
* @throws IllegalArgumentException if id is reserved
*/
public Index indexById(long id) throws IOException {
if (Tree.isInternal(id)) {
throw new IllegalArgumentException("Invalid id: " + id);
}
Index index;
final Lock commitLock = sharedCommitLock();
commitLock.lock();
try {
synchronized (mOpenTrees) {
LHashTable.ObjEntry<Tree> entry = mOpenTreesById.get(id);
if (entry != null) {
return entry.value;
}
}
byte[] idKey = new byte[9];
idKey[0] = KEY_TYPE_INDEX_ID;
writeLongBE(idKey, 1, id);
byte[] name = mRegistryKeyMap.load(null, idKey);
if (name == null) {
return null;
}
index = openIndex(name, false);
} catch (Throwable e) {
throw closeOnFailure(this, e);
} finally {
commitLock.unlock();
}
if (index == null) {
// Registry needs to be repaired to fix this.
throw new DatabaseException("Unable to find index in registry");
}
return index;
}
/**
* Returns an index by its identifier, returning null if not found.
*
* @param id big-endian encoded long integer
* @throws IllegalArgumentException if id is malformed or reserved
*/
public Index indexById(byte[] id) throws IOException {
if (id.length != 8) {
throw new IllegalArgumentException("Expected 8 byte identifier: " + id.length);
}
return indexById(readLongBE(id, 0));
}
/**
* Allows access to internal indexes which can use the redo log.
*/
Index anyIndexById(long id) throws IOException {
if (id == Tree.REGISTRY_KEY_MAP_ID) {
return mRegistryKeyMap;
} else if (id == Tree.FRAGMENTED_TRASH_ID) {
return fragmentedTrash().mTrash;
}
return indexById(id);
}
/**
* Returns a Cursor which maps all available index names to
* identifiers. Identifiers are long integers, big-endian encoded.
* Attempting to store anything into the Cursor causes an {@link
* UnmodifiableViewException} to be thrown.
*/
public Cursor allIndexes() throws IOException {
return new IndexesCursor(mRegistryKeyMap.newCursor(null));
}
/**
* Returns a new Transaction with the {@link DatabaseConfig#durabilityMode default}
* durability mode.
*/
public Transaction newTransaction() {
return doNewTransaction(mDurabilityMode);
}
/**
* Returns a new Transaction with the given durability mode. If null, the
* {@link DatabaseConfig#durabilityMode default} is used.
*/
public Transaction newTransaction(DurabilityMode durabilityMode) {
return doNewTransaction(durabilityMode == null ? mDurabilityMode : durabilityMode);
}
private Transaction doNewTransaction(DurabilityMode durabilityMode) {
return new Transaction
(this, durabilityMode, LockMode.UPGRADABLE_READ, mDefaultLockTimeoutNanos);
}
/**
* Convenience method which returns a transaction intended for locking, and
* not for making modifications.
*/
Transaction newLockTransaction() {
return new Transaction(this, DurabilityMode.NO_LOG, LockMode.UPGRADABLE_READ, -1);
}
/**
* Caller must hold commit lock. This ensures that highest transaction id
* is persisted correctly by checkpoint.
*
* @param txnId pass zero to select a transaction id
* @return non-zero transaction id
*/
long register(UndoLog undo, long txnId) {
synchronized (mTxnIdLock) {
UndoLog top = mTopUndoLog;
if (top != null) {
undo.mPrev = top;
top.mNext = undo;
}
mTopUndoLog = undo;
mUndoLogCount++;
while (txnId == 0) {
txnId = ++mTxnId;
}
return txnId;
}
}
/**
* Caller must hold commit lock. This ensures that highest transaction id
* is persisted correctly by checkpoint.
*
* @return non-zero transaction id
*/
long nextTransactionId() {
long txnId;
do {
synchronized (mTxnIdLock) {
txnId = ++mTxnId;
}
} while (txnId == 0);
return txnId;
}
/**
* Called only by UndoLog.
*/
void unregister(UndoLog log) {
synchronized (mTxnIdLock) {
UndoLog prev = log.mPrev;
UndoLog next = log.mNext;
if (prev != null) {
prev.mNext = next;
log.mPrev = null;
}
if (next != null) {
next.mPrev = prev;
log.mNext = null;
} else if (log == mTopUndoLog) {
mTopUndoLog = prev;
}
mUndoLogCount--;
}
}
/**
* Preallocates pages for immediate use.
*/
public void preallocate(long bytes) throws IOException {
int pageSize = pageSize();
long pageCount = (bytes + pageSize - 1) / pageSize;
if (pageCount > 0) {
mPageDb.allocatePages(pageCount);
checkpoint(true);
}
}
/**
* Support for capturing a snapshot (hot backup) of the database, while
* still allowing concurrent modifications. The snapshot contains all data
* up to the last checkpoint. Call {@link #restoreFromSnapshot restoreFromSnapshot}
* to recreate a Database from the snapshot.
*
* @param out snapshot destination; does not require extra buffering; not auto-closed
* @return a snapshot control object, which must be closed when no longer needed
*/
public Snapshot beginSnapshot(OutputStream out) throws IOException {
if (!(mPageDb instanceof DurablePageDb)) {
throw new UnsupportedOperationException("Snapshot only allowed for durable databases");
}
DurablePageDb pageDb = (DurablePageDb) mPageDb;
int cluster = Math.max(1, 65536 / pageSize());
return pageDb.beginSnapshot(mTempFileManager, cluster, out);
}
/**
* @param in snapshot source; does not require extra buffering; not auto-closed
*/
public static Database restoreFromSnapshot(DatabaseConfig config, InputStream in)
throws IOException
{
File[] dataFiles = config.dataFiles();
if (dataFiles == null) {
throw new UnsupportedOperationException("Restore only allowed for durable databases");
}
if (!config.mReadOnly && config.mMkdirs) {
for (File f : dataFiles) {
f.getParentFile().mkdirs();
}
}
EnumSet<OpenOption> options = config.createOpenOptions();
// Delete old redo log files.
deleteNumberedFiles(config.mBaseFile, ".redo.");
DurablePageDb.restoreFromSnapshot(dataFiles, options, in).close();
return Database.open(config);
}
/**
* Flushes, but does not sync, all non-flushed transactions. Transactions
* committed with {@link DurabilityMode#NO_FLUSH no-flush} effectively
* become {@link DurabilityMode#NO_SYNC no-sync} durable.
*/
public void flush() throws IOException {
if (!mClosed && mRedoLog != null) {
mRedoLog.flush();
}
}
/**
* Persists all non-flushed and non-sync'd transactions. Transactions
* committed with {@link DurabilityMode#NO_FLUSH no-flush} and {@link
* DurabilityMode#NO_SYNC no-sync} effectively become {@link
* DurabilityMode#SYNC sync} durable.
*/
public void sync() throws IOException {
if (!mClosed && mRedoLog != null) {
mRedoLog.sync();
}
}
/**
* Durably sync and checkpoint all changes to the database. In addition to
* ensuring that all transactions are durable, checkpointing ensures that
* non-transactional modifications are durable.
*/
public void checkpoint() throws IOException {
if (!mClosed && mRedoLog != null) {
checkpoint(false);
}
}
/**
* Closes the database, ensuring durability of committed transactions. No
* checkpoint is performed by this method, and so non-transactional
* modifications can be lost.
*/
@Override
public void close() throws IOException {
close(null);
}
@Override
void close(Throwable cause) throws IOException {
if (cause != null) {
if (mClosedCause == null && mEventListener != null) {
mEventListener.notify(EventType.PANIC_UNHANDLED_EXCEPTION,
"Closing database due to unhandled exception: %1$s",
rootCause(cause));
}
mClosedCause = cause;
}
mClosed = true;
Checkpointer c = mCheckpointer;
if (c != null) {
c.close();
c = null;
}
if (mOpenTrees != null) {
synchronized (mOpenTrees) {
mOpenTrees.clear();
mOpenTreesById.clear(0);
}
}
mSharedCommitLock.lock();
try {
closeNodeCache();
if (mAllocator != null) {
mAllocator.clearDirtyNodes();
}
IOException ex = null;
ex = closeQuietly(ex, mRedoLog, cause);
ex = closeQuietly(ex, mPageDb, cause);
ex = closeQuietly(ex, mLockFile, cause);
mLockManager.close();
if (ex != null) {
throw ex;
}
} finally {
mSharedCommitLock.unlock();
}
}
void checkClosed() throws DatabaseException {
if (mClosed) {
String message = "Closed";
Throwable cause = mClosedCause;
if (cause != null) {
message += "; " + rootCause(cause);
}
throw new DatabaseException(message, cause);
}
}
/**
* @param rootId pass zero to create
* @return unlatched and unevictable root node
*/
private Node loadTreeRoot(long rootId) throws IOException {
Node rootNode = allocLatchedNode(false);
try {
if (rootId == 0) {
rootNode.asEmptyRoot();
} else {
try {
rootNode.read(this, rootId);
} catch (IOException e) {
makeEvictable(rootNode);
throw e;
}
}
} finally {
rootNode.releaseExclusive();
}
return rootNode;
}
/**
* Loads the root registry node, or creates one if store is new. Root node
* is not eligible for eviction.
*/
private Node loadRegistryRoot(byte[] header) throws IOException {
int version = readIntLE(header, I_ENCODING_VERSION);
long rootId;
if (version == 0) {
rootId = 0;
} else {
if (version != ENCODING_VERSION) {
throw new CorruptDatabaseException("Unknown encoding version: " + version);
}
rootId = readLongLE(header, I_ROOT_PAGE_ID);
}
return loadTreeRoot(rootId);
}
private Tree openInternalTree(long treeId, boolean create) throws IOException {
final Lock commitLock = sharedCommitLock();
commitLock.lock();
try {
byte[] treeIdBytes = new byte[8];
writeLongBE(treeIdBytes, 0, treeId);
byte[] rootIdBytes = mRegistry.load(Transaction.BOGUS, treeIdBytes);
long rootId;
if (rootIdBytes != null) {
rootId = readLongLE(rootIdBytes, 0);
} else {
if (!create) {
return null;
}
rootId = 0;
}
return new Tree(this, treeId, treeIdBytes, null, loadTreeRoot(rootId));
} finally {
commitLock.unlock();
}
}
private Index openIndex(byte[] name, boolean create) throws IOException {
checkClosed();
final Lock commitLock = sharedCommitLock();
commitLock.lock();
try {
synchronized (mOpenTrees) {
Tree tree = mOpenTrees.get(name);
if (tree != null) {
return tree;
}
}
byte[] nameKey = newKey(KEY_TYPE_INDEX_NAME, name);
byte[] treeIdBytes = mRegistryKeyMap.load(null, nameKey);
long treeId;
if (treeIdBytes != null) {
treeId = readLongBE(treeIdBytes, 0);
} else if (!create) {
return null;
} else synchronized (mOpenTrees) {
treeIdBytes = mRegistryKeyMap.load(null, nameKey);
if (treeIdBytes != null) {
treeId = readLongBE(treeIdBytes, 0);
} else {
treeIdBytes = new byte[8];
try {
do {
treeId = Tree.randomId();
writeLongBE(treeIdBytes, 0, treeId);
} while (!mRegistry.insert(Transaction.BOGUS, treeIdBytes, EMPTY_BYTES));
if (!mRegistryKeyMap.insert(null, nameKey, treeIdBytes)) {
mRegistry.delete(Transaction.BOGUS, treeIdBytes);
throw new DatabaseException("Unable to insert index name");
}
byte[] idKey = newKey(KEY_TYPE_INDEX_ID, treeIdBytes);
if (!mRegistryKeyMap.insert(null, idKey, name)) {
mRegistryKeyMap.delete(null, nameKey);
mRegistry.delete(Transaction.BOGUS, treeIdBytes);
throw new DatabaseException("Unable to insert index id");
}
} catch (IOException e) {
throw closeOnFailure(this, e);
}
}
}
// Use a transaction to ensure that only one thread loads the
// requested index. Nothing is written into it.
Transaction txn = newLockTransaction();
try {
// Pass the transaction to acquire the lock.
byte[] rootIdBytes = mRegistry.load(txn, treeIdBytes);
synchronized (mOpenTrees) {
Tree tree = mOpenTrees.get(name);
if (tree != null) {
// Another thread got the lock first and loaded the index.
return tree;
}
}
long rootId = (rootIdBytes == null || rootIdBytes.length == 0) ? 0
: readLongLE(rootIdBytes, 0);
Tree tree = new Tree(this, treeId, treeIdBytes, name, loadTreeRoot(rootId));
synchronized (mOpenTrees) {
mOpenTrees.put(name, tree);
mOpenTreesById.insert(treeId).value = tree;
}
return tree;
} finally {
txn.reset();
}
} finally {
commitLock.unlock();
}
}
private static byte[] newKey(byte type, byte[] payload) {
byte[] key = new byte[1 + payload.length];
key[0] = type;
System.arraycopy(payload, 0, key, 1, payload.length);
return key;
}
/**
* Returns the fixed size of all pages in the store, in bytes.
*/
int pageSize() {
return mPageDb.pageSize();
}
/**
* Access the shared commit lock, which prevents commits while held.
*/
Lock sharedCommitLock() {
return mSharedCommitLock;
}
/**
* Returns a new or recycled Node instance, latched exclusively, with an id
* of zero and a clean state.
*/
Node allocLatchedNode() throws IOException {
return allocLatchedNode(true);
}
/**
* Returns a new or recycled Node instance, latched exclusively, with an id
* of zero and a clean state.
*
* @param evictable true if allocated node can be automatically evicted
*/
Node allocLatchedNode(boolean evictable) throws IOException {
final Latch usageLatch = mUsageLatch;
usageLatch.acquireExclusive();
alloc: try {
int max = mMaxNodeCount;
if (max == 0) {
break alloc;
}
if (mNodeCount < max) {
checkClosed();
Node node = new Node(pageSize());
node.acquireExclusive();
mNodeCount++;
if (evictable) {
if ((node.mLessUsed = mMostRecentlyUsed) == null) {
mLeastRecentlyUsed = node;
} else {
mMostRecentlyUsed.mMoreUsed = node;
}
mMostRecentlyUsed = node;
}
return node;
}
if (!evictable && mLeastRecentlyUsed.mMoreUsed == mMostRecentlyUsed) {
// Cannot allow list to shrink to less than two elements.
break alloc;
}
do {
Node node = mLeastRecentlyUsed;
(mLeastRecentlyUsed = node.mMoreUsed).mLessUsed = null;
node.mMoreUsed = null;
(node.mLessUsed = mMostRecentlyUsed).mMoreUsed = node;
mMostRecentlyUsed = node;
if (node.tryAcquireExclusive() && (node = Node.evict(node, this)) != null) {
if (!evictable) {
// Detach from linked list.
(mMostRecentlyUsed = node.mLessUsed).mMoreUsed = null;
node.mLessUsed = null;
}
// Return with latch still held.
return node;
}
} while (--max > 0);
} finally {
usageLatch.releaseExclusive();
}
checkClosed();
// TODO: Try all nodes again, but with stronger latch request before
// giving up.
throw new CacheExhaustedException();
}
/**
* Unlinks all nodes from each other in usage list, and prevents new nodes
* from being allocated.
*/
private void closeNodeCache() {
final Latch usageLatch = mUsageLatch;
usageLatch.acquireExclusive();
try {
// Prevent new allocations.
mMaxNodeCount = 0;
Node node = mLeastRecentlyUsed;
mLeastRecentlyUsed = null;
mMostRecentlyUsed = null;
while (node != null) {
Node next = node.mMoreUsed;
node.mLessUsed = null;
node.mMoreUsed = null;
// Make node appear to be evicted.
node.mId = 0;
// Attempt to unlink child nodes, making them appear to be evicted.
if (node.tryAcquireExclusive()) {
Node[] childNodes = node.mChildNodes;
if (childNodes != null) {
Arrays.fill(childNodes, null);
}
node.releaseExclusive();
}
node = next;
}
} finally {
usageLatch.releaseExclusive();
}
}
/**
* Returns a new or recycled Node instance, latched exclusively and marked
* dirty. Caller must hold commit lock.
*
* @param forTree tree which is allocating the node
*/
Node allocDirtyNode(Tree forTree) throws IOException {
Node node = allocLatchedNode(true);
try {
dirty(node, mAllocator.allocPage(forTree, node));
return node;
} catch (IOException e) {
node.releaseExclusive();
throw e;
}
}
/**
* Returns a new or recycled Node instance, latched exclusively, marked
* dirty and unevictable. Caller must hold commit lock.
*
* @param forTree tree which is allocating the node
*/
Node allocUnevictableNode(Tree forTree) throws IOException {
Node node = allocLatchedNode(false);
try {
dirty(node, mAllocator.allocPage(forTree, node));
return node;
} catch (IOException e) {
makeEvictable(node);
node.releaseExclusive();
throw e;
}
}
/**
* Allow a Node which was allocated as unevictable to be evictable,
* starting off as the most recently used.
*/
void makeEvictable(Node node) {
final Latch usageLatch = mUsageLatch;
usageLatch.acquireExclusive();
try {
if (mMaxNodeCount == 0) {
// Closed.
return;
}
if (node.mMoreUsed != null || node.mLessUsed != null) {
throw new IllegalStateException();
}
(node.mLessUsed = mMostRecentlyUsed).mMoreUsed = node;
mMostRecentlyUsed = node;
} finally {
usageLatch.releaseExclusive();
}
}
/**
* Allow a Node which was allocated as evictable to be unevictable.
*/
void makeUnevictable(Node node) {
final Latch usageLatch = mUsageLatch;
usageLatch.acquireExclusive();
try {
if (mMaxNodeCount == 0) {
// Closed.
return;
}
Node lessUsed = node.mLessUsed;
Node moreUsed = node.mMoreUsed;
if (lessUsed == null) {
(mLeastRecentlyUsed = moreUsed).mLessUsed = null;
} else if (moreUsed == null) {
(mMostRecentlyUsed = lessUsed).mMoreUsed = null;
} else {
node.mLessUsed.mMoreUsed = moreUsed;
node.mMoreUsed.mLessUsed = lessUsed;
}
node.mMoreUsed = null;
node.mLessUsed = null;
} finally {
usageLatch.releaseExclusive();
}
}
/**
* Caller must hold commit lock and any latch on node.
*/
boolean shouldMarkDirty(Node node) {
return node.mCachedState != mCommitState && node.mId != Node.STUB_ID;
}
/**
* Caller must hold commit lock and exclusive latch on node. Method does
* nothing if node is already dirty. Latch is never released by this method,
* even if an exception is thrown.
*
* @return true if just made dirty and id changed
*/
boolean markDirty(Tree tree, Node node) throws IOException {
if (node.mCachedState == mCommitState || node.mId == Node.STUB_ID) {
return false;
} else {
doMarkDirty(tree, node);
return true;
}
}
/**
* Caller must hold commit lock and exclusive latch on node. Method does
* nothing if node is already dirty. Latch is never released by this method,
* even if an exception is thrown.
*/
void markUndoLogDirty(Node node) throws IOException {
if (node.mCachedState != mCommitState) {
long oldId = node.mId;
long newId = mAllocator.allocPage(null, node);
mPageDb.deletePage(oldId);
node.write(this);
dirty(node, newId);
}
}
/**
* Caller must hold commit lock and exclusive latch on node. Method must
* not be called if node is already dirty. Latch is never released by this
* method, even if an exception is thrown.
*/
void doMarkDirty(Tree tree, Node node) throws IOException {
long oldId = node.mId;
long newId = mAllocator.allocPage(tree, node);
if (oldId != 0) {
mPageDb.deletePage(oldId);
}
if (node.mCachedState != CACHED_CLEAN) {
node.write(this);
}
if (node == tree.mRoot && tree.mIdBytes != null) {
byte[] newEncodedId = new byte[8];
writeLongLE(newEncodedId, 0, newId);
mRegistry.store(Transaction.BOGUS, tree.mIdBytes, newEncodedId);
}
dirty(node, newId);
}
/**
* Caller must hold commit lock and exclusive latch on node.
*/
private void dirty(Node node, long newId) {
node.mId = newId;
node.mCachedState = mCommitState;
}
/**
* Caller must hold commit lock and exclusive latch on node. This method
* should only be called for nodes whose existing data is not needed.
*/
void redirty(Node node) {
node.mCachedState = mCommitState;
mAllocator.dirty(node);
}
/**
* Similar to markDirty method except no new page is reserved, and old page
* is not immediately deleted. Caller must hold commit lock and exclusive
* latch on node. Latch is never released by this method, unless an
* exception is thrown.
*/
void prepareToDelete(Node node) throws IOException {
// Hello. My name is Inigo Montoya. You killed my father. Prepare to die.
if (node.mCachedState == mCheckpointFlushState) {
// Node must be committed with the current checkpoint, and so
// it must be written out before it can be deleted.
try {
node.write(this);
} catch (Throwable e) {
node.releaseExclusive();
throw rethrow(e);
}
}
}
/**
* Caller must hold commit lock and exclusive latch on node. The
* prepareToDelete method must have been called first. Latch is always
* released by this method, even if an exception is thrown.
*/
void deleteNode(Tree fromTree, Node node) throws IOException {
try {
deletePage(fromTree, node.mId, node.mCachedState);
node.mId = 0;
// TODO: child node array should be recycled
node.mChildNodes = null;
// When node is re-allocated, it will be evicted. Ensure that eviction
// doesn't write anything.
node.mCachedState = CACHED_CLEAN;
} finally {
node.releaseExclusive();
}
// Indicate that node is least recently used, allowing it to be
// re-allocated immediately without evicting another node. Node must be
// unlatched at this point, to prevent it from being immediately
// promoted to most recently used by allocLatchedNode.
final Latch usageLatch = mUsageLatch;
usageLatch.acquireExclusive();
try {
if (mMaxNodeCount == 0) {
// Closed.
return;
}
Node lessUsed = node.mLessUsed;
if (lessUsed == null) {
// Node might already be least...
if (node.mMoreUsed != null) {
// ...confirmed.
return;
}
// ...Node isn't in the usage list at all.
} else {
Node moreUsed = node.mMoreUsed;
if ((lessUsed.mMoreUsed = moreUsed) == null) {
mMostRecentlyUsed = lessUsed;
} else {
moreUsed.mLessUsed = lessUsed;
}
node.mLessUsed = null;
}
(node.mMoreUsed = mLeastRecentlyUsed).mLessUsed = node;
mLeastRecentlyUsed = node;
} finally {
usageLatch.releaseExclusive();
}
}
/**
* Caller must hold commit lock.
*/
void deletePage(Tree fromTree, long id, int cachedState) throws IOException {
if (id != 0) {
if (cachedState == mCommitState) {
// Newly reserved page was never used, so recycle it.
mAllocator.recyclePage(fromTree, id);
} else {
// Old data must survive until after checkpoint.
mPageDb.deletePage(id);
}
}
}
/**
* Indicate that non-root node is most recently used. Root node is not
* managed in usage list and cannot be evicted. Caller must hold any latch
* on node. Latch is never released by this method, even if an exception is
* thrown.
*/
void used(Node node) {
// Node latch is only required for this check. Dirty nodes are evicted
// in FIFO order, which helps spread out the write workload.
if (node.mCachedState != CACHED_CLEAN) {
return;
}
// Because this method can be a bottleneck, don't wait for exclusive
// latch. If node is popular, it will get more chances to be identified
// as most recently used. This strategy works well enough because cache
// eviction is always a best-guess approach.
final Latch usageLatch = mUsageLatch;
if (usageLatch.tryAcquireExclusive()) {
Node moreUsed = node.mMoreUsed;
if (moreUsed != null) {
Node lessUsed = node.mLessUsed;
if ((moreUsed.mLessUsed = lessUsed) == null) {
mLeastRecentlyUsed = moreUsed;
} else {
lessUsed.mMoreUsed = moreUsed;
}
node.mMoreUsed = null;
(node.mLessUsed = mMostRecentlyUsed).mMoreUsed = node;
mMostRecentlyUsed = node;
}
usageLatch.releaseExclusive();
}
}
/**
* Breakup a large value into separate pages, returning a new value which
* encodes the page references. Caller must hold commit lock.
*
* Returned value begins with a one byte header:
*
* 0b0000_ffip
*
* The leading 4 bits define the encoding type, which must be 0. The 'f'
* bits define the full value length field size: 2, 4, 6, or 8 bytes. The
* array is limited to a 4 byte length, and so only the 2 and 4 byte forms
* apply. The 'i' bit defines the inline content length field size: 0 or 2
* bytes. The 'p' bit is clear if direct pointers are used, and set for
* indirect pointers. Pointers are always 6 bytes.
*
* @param caller optional tree node which is latched and calling this method
* @param forTree tree which is storing large value
* @param max maximum allowed size for returned byte array; must not be
* less than 11 (can be 9 if full value length is < 65536)
* @return null if max is too small
*/
byte[] fragment(Node caller, Tree forTree, byte[] value, int max) throws IOException {
int pageSize = pageSize();
int pageCount = value.length / pageSize;
int remainder = value.length % pageSize;
if (value.length >= 65536) {
// Subtract header size, full length field size, and size of one pointer.
max -= (1 + 4 + 6);
} else if (pageCount == 0 && remainder <= (max - (1 + 2 + 2))) {
// Entire value fits inline. It didn't really need to be
// encoded this way, but do as we're told.
byte[] newValue = new byte[(1 + 2 + 2) + value.length];
newValue[0] = 0x02; // ff=0, i=1, p=0
writeShortLE(newValue, 1, value.length); // full length
writeShortLE(newValue, 1 + 2, value.length); // inline length
System.arraycopy(value, 0, newValue, (1 + 2 + 2), value.length);
return newValue;
} else {
// Subtract header size, full length field size, and size of one pointer.
max -= (1 + 2 + 6);
}
if (max < 0) {
return null;
}
int pointerSpace = pageCount * 6;
byte[] newValue;
if (remainder <= max && remainder < 65536
&& (pointerSpace <= (max + (6 - 2) - remainder)))
{
// Remainder fits inline, minimizing internal fragmentation. All
// extra pages will be full. All pointers fit too; encode direct.
byte header;
int offset;
if (value.length >= 65536) {
header = 0x06; // ff = 1, i=1
offset = 1 + 4;
} else {
header = 0x02; // ff = 0, i=1
offset = 1 + 2;
}
int poffset = offset + 2 + remainder;
newValue = new byte[poffset + pointerSpace];
if (pageCount > 0) {
int voffset = remainder;
while (true) {
Node node = allocDirtyNode(forTree);
try {
mFragmentCache.put(caller, node);
writeInt48LE(newValue, poffset, node.mId);
System.arraycopy(value, voffset, node.mPage, 0, pageSize);
if (pageCount == 1) {
break;
}
} finally {
node.releaseExclusive();
}
pageCount--;
poffset += 6;
voffset += pageSize;
}
}
newValue[0] = header;
writeShortLE(newValue, offset, remainder); // inline length
System.arraycopy(value, 0, newValue, offset + 2, remainder);
} else {
// Remainder doesn't fit inline, so don't encode any inline
// content. Last extra page will not be full.
pageCount++;
pointerSpace += 6;
byte header;
int offset;
if (value.length >= 65536) {
header = 0x04; // ff = 1, i=0
offset = 1 + 4;
} else {
header = 0x00; // ff = 0, i=0
offset = 1 + 2;
}
if (pointerSpace <= (max + 6)) {
// All pointers fit, so encode as direct.
newValue = new byte[offset + pointerSpace];
if (pageCount > 0) {
int voffset = 0;
while (true) {
Node node = allocDirtyNode(forTree);
try {
mFragmentCache.put(caller, node);
writeInt48LE(newValue, offset, node.mId);
if (pageCount > 1) {
System.arraycopy(value, voffset, node.mPage, 0, pageSize);
} else {
System.arraycopy(value, voffset, node.mPage, 0, remainder);
break;
}
} finally {
node.releaseExclusive();
}
pageCount--;
offset += 6;
voffset += pageSize;
}
}
} else {
// Use indirect pointers.
header |= 0x01;
newValue = new byte[offset + 6];
int levels = calculateInodeLevels(value.length, pageSize);
Node inode = allocDirtyNode(forTree);
writeInt48LE(newValue, offset, inode.mId);
writeMultilevelFragments
(caller, forTree, levels, inode, value, 0, value.length);
}
newValue[0] = header;
}
// Encode full length field.
if (value.length >= 65536) {
writeIntLE(newValue, 1, value.length);
} else {
writeShortLE(newValue, 1, value.length);
}
return newValue;
}
private static int calculateInodeLevels(long valueLength, int pageSize) {
int levels = 0;
if (valueLength >= 0 && valueLength < (Long.MAX_VALUE / 2)) {
long len = (valueLength + (pageSize - 1)) / pageSize;
if (len > 1) {
int ptrCount = pageSize / 6;
do {
levels++;
} while ((len = (len + (ptrCount - 1)) / ptrCount) > 1);
}
} else {
BigInteger bPageSize = BigInteger.valueOf(pageSize);
BigInteger bLen = (valueOfUnsigned(valueLength)
.add(bPageSize.subtract(BigInteger.ONE))).divide(bPageSize);
if (bLen.compareTo(BigInteger.ONE) > 0) {
BigInteger bPtrCount = bPageSize.divide(BigInteger.valueOf(6));
BigInteger bPtrCountM1 = bPtrCount.subtract(BigInteger.ONE);
do {
levels++;
} while ((bLen = (bLen.add(bPtrCountM1)).divide(bPtrCount))
.compareTo(BigInteger.ONE) > 0);
}
}
return levels;
}
/**
* @param level inode level; at least 1
* @param inode exclusive latched parent inode; always released by this method
* @param value slice of complete value being fragmented
*/
private void writeMultilevelFragments(Node caller, Tree forTree,
int level, Node inode,
byte[] value, int voffset, int vlength)
throws IOException
{
long levelCap;
long[] childNodeIds;
Node[] childNodes;
try {
byte[] page = inode.mPage;
level--;
levelCap = levelCap(page.length, level);
// Pre-allocate and reference the required child nodes in order for
// parent node latch to be released early. FragmentCache can then
// safely evict the parent node if necessary.
int childNodeCount = (int) ((vlength + (levelCap - 1)) / levelCap);
childNodeIds = new long[childNodeCount];
childNodes = new Node[childNodeCount];
try {
for (int poffset = 0, i=0; i<childNodeCount; poffset += 6, i++) {
Node childNode = allocDirtyNode(forTree);
writeInt48LE(page, poffset, childNodeIds[i] = childNode.mId);
childNodes[i] = childNode;
// Allow node to be evicted, but don't write anything yet.
childNode.mCachedState = CACHED_CLEAN;
childNode.releaseExclusive();
}
} catch (Throwable e) {
for (Node childNode : childNodes) {
if (childNode != null) {
childNode.acquireExclusive();
deleteNode(null, childNode);
}
}
throw rethrow(e);
}
mFragmentCache.put(caller, inode);
} finally {
inode.releaseExclusive();
}
for (int i=0; i<childNodeIds.length; i++) {
long childNodeId = childNodeIds[i];
Node childNode = childNodes[i];
latchChild: {
if (childNodeId == childNode.mId) {
childNode.acquireExclusive();
if (childNodeId == childNode.mId) {
// Since commit lock is held, only need to switch the
// state. Calling redirty is unnecessary and it would
// screw up the dirty list order for no good reason.
childNode.mCachedState = mCommitState;
break latchChild;
}
}
// Child node was evicted, although it was clean.
childNode = allocLatchedNode();
childNode.mId = childNodeId;
redirty(childNode);
}
int len = (int) Math.min(levelCap, vlength);
if (level <= 0) {
System.arraycopy(value, voffset, childNode.mPage, 0, len);
mFragmentCache.put(caller, childNode);
childNode.releaseExclusive();
} else {
writeMultilevelFragments
(caller, forTree, level, childNode, value, voffset, len);
}
vlength -= len;
voffset += len;
}
}
/**
* Reconstruct a fragmented value.
*
* @param caller optional tree node which is latched and calling this method
*/
byte[] reconstruct(Node caller, byte[] fragmented, int off, int len) throws IOException {
int header = fragmented[off++];
len--;
int vLen;
switch ((header >> 2) & 0x03) {
default:
vLen = readUnsignedShortLE(fragmented, off);
break;
case 1:
vLen = readIntLE(fragmented, off);
if (vLen < 0) {
throw new LargeValueException(vLen & 0xffffffffL);
}
break;
case 2:
long vLenL = readUnsignedInt48LE(fragmented, off);
if (vLenL > Integer.MAX_VALUE) {
throw new LargeValueException(vLenL);
}
vLen = (int) vLenL;
break;
case 3:
vLenL = readLongLE(fragmented, off);
if (vLenL < 0 || vLenL > Integer.MAX_VALUE) {
throw new LargeValueException(vLenL);
}
vLen = (int) vLenL;
break;
}
{
int vLenFieldSize = 2 + ((header >> 1) & 0x06);
off += vLenFieldSize;
len -= vLenFieldSize;
}
byte[] value;
try {
value = new byte[vLen];
} catch (OutOfMemoryError e) {
throw new LargeValueException(vLen, e);
}
int vOff = 0;
if ((header & 0x02) != 0) {
// Inline content.
int inLen = readUnsignedShortLE(fragmented, off);
off += 2;
len -= 2;
System.arraycopy(fragmented, off, value, vOff, inLen);
off += inLen;
len -= inLen;
vOff += inLen;
vLen -= inLen;
}
if ((header & 0x01) == 0) {
// Direct pointers.
while (len >= 6) {
long nodeId = readUnsignedInt48LE(fragmented, off);
off += 6;
len -= 6;
Node node = mFragmentCache.get(caller, nodeId);
try {
byte[] page = node.mPage;
int pLen = Math.min(vLen, page.length);
System.arraycopy(page, 0, value, vOff, pLen);
vOff += pLen;
vLen -= pLen;
} finally {
node.releaseShared();
}
}
} else {
// Indirect pointers.
int levels = calculateInodeLevels(vLen, pageSize());
long nodeId = readUnsignedInt48LE(fragmented, off);
Node inode = mFragmentCache.get(caller, nodeId);
readMultilevelFragments(caller, levels, inode, value, 0, vLen);
}
return value;
}
/**
* @param level inode level; at least 1
* @param inode shared latched parent inode; always released by this method
* @param value slice of complete value being reconstructed
*/
private void readMultilevelFragments(Node caller,
int level, Node inode,
byte[] value, int voffset, int vlength)
throws IOException
{
byte[] page = inode.mPage;
level--;
long levelCap = levelCap(page.length, level);
// Copy all child node ids and release parent latch early.
// FragmentCache can then safely evict the parent node if necessary.
int childNodeCount = (int) ((vlength + (levelCap - 1)) / levelCap);
long[] childNodeIds = new long[childNodeCount];
for (int poffset = 0, i=0; i<childNodeCount; poffset += 6, i++) {
childNodeIds[i] = readUnsignedInt48LE(page, poffset);
}
inode.releaseShared();
for (long childNodeId : childNodeIds) {
Node childNode = mFragmentCache.get(caller, childNodeId);
int len = (int) Math.min(levelCap, vlength);
if (level <= 0) {
System.arraycopy(childNode.mPage, 0, value, voffset, len);
childNode.releaseShared();
} else {
readMultilevelFragments(caller, level, childNode, value, voffset, len);
}
vlength -= len;
voffset += len;
}
}
/**
* Delete the extra pages of a fragmented value. Caller must hold commit
* lock.
*
* @param caller optional tree node which is latched and calling this method
* @param fromTree tree which is deleting the large value
*/
void deleteFragments(Node caller, Tree fromTree, byte[] fragmented, int off, int len)
throws IOException
{
int header = fragmented[off++];
len--;
long vLen;
if ((header & 0x01) == 0) {
// Don't need to read the value length when deleting direct pointers.
vLen = 0;
} else {
switch ((header >> 2) & 0x03) {
default:
vLen = readUnsignedShortLE(fragmented, off);
break;
case 1:
vLen = readIntLE(fragmented, off) & 0xffffffffL;
break;
case 2:
vLen = readUnsignedInt48LE(fragmented, off);
break;
case 3:
vLen = readLongLE(fragmented, off);
break;
}
}
{
int vLenFieldSize = 2 + ((header >> 1) & 0x06);
off += vLenFieldSize;
len -= vLenFieldSize;
}
if ((header & 0x02) != 0) {
// Skip inline content.
int inLen = 2 + readUnsignedShortLE(fragmented, off);
off += inLen;
len -= inLen;
}
if ((header & 0x01) == 0) {
// Direct pointers.
while (len >= 6) {
long nodeId = readUnsignedInt48LE(fragmented, off);
off += 6;
len -= 6;
deleteFragment(caller, fromTree, nodeId);
}
} else {
// Indirect pointers.
int levels = calculateInodeLevels(vLen, pageSize());
long nodeId = readUnsignedInt48LE(fragmented, off);
Node inode = removeInode(caller, nodeId);
deleteMultilevelFragments(caller, fromTree, levels, inode, vLen);
}
}
/**
* @param level inode level; at least 1
* @param inode exclusive latched parent inode; always released by this method
*/
private void deleteMultilevelFragments(Node caller, Tree fromTree,
int level, Node inode, long vlength)
throws IOException
{
byte[] page = inode.mPage;
level--;
long levelCap = levelCap(page.length, level);
// Copy all child node ids and release parent latch early.
int childNodeCount = (int) ((vlength + (levelCap - 1)) / levelCap);
long[] childNodeIds = new long[childNodeCount];
for (int poffset = 0, i=0; i<childNodeCount; poffset += 6, i++) {
childNodeIds[i] = readUnsignedInt48LE(page, poffset);
}
deleteNode(fromTree, inode);
if (level <= 0) for (long childNodeId : childNodeIds) {
deleteFragment(caller, fromTree, childNodeId);
} else for (long childNodeId : childNodeIds) {
Node childNode = removeInode(caller, childNodeId);
long len = Math.min(levelCap, vlength);
deleteMultilevelFragments(caller, fromTree, level, childNode, len);
vlength -= len;
}
}
/**
* @return non-null Node with exclusive latch held
*/
private Node removeInode(Node caller, long nodeId) throws IOException {
Node node = mFragmentCache.remove(caller, nodeId);
if (node == null) {
node = allocLatchedNode(false);
node.mId = nodeId;
node.mType = TYPE_FRAGMENT;
readPage(nodeId, node.mPage);
}
return node;
}
private void deleteFragment(Node caller, Tree fromTree, long nodeId) throws IOException {
Node node = mFragmentCache.remove(caller, nodeId);
if (node != null) {
deleteNode(fromTree, node);
} else {
// Page is clean if not in a Node, and so it must survive until
// after the next checkpoint.
mPageDb.deletePage(nodeId);
}
}
private static long levelCap(int pageLength, int level) {
return pageLength * (long) Math.pow(pageLength / 6, level);
}
/**
* Obtain the trash for transactionally deleting fragmented values.
*/
FragmentedTrash fragmentedTrash() throws IOException {
FragmentedTrash trash = mFragmentedTrash;
if (trash != null) {
return trash;
}
synchronized (mOpenTrees) {
if ((trash = mFragmentedTrash) != null) {
return trash;
}
Tree tree = openInternalTree(Tree.FRAGMENTED_TRASH_ID, true);
return mFragmentedTrash = new FragmentedTrash(tree);
}
}
byte[] removeSpareBuffer() throws InterruptedIOException {
return mSpareBufferPool.remove();
}
void addSpareBuffer(byte[] buffer) {
mSpareBufferPool.add(buffer);
}
void readPage(long id, byte[] page) throws IOException {
mPageDb.readPage(id, page);
}
void writePage(long id, byte[] page) throws IOException {
mPageDb.writePage(id, page);
}
private void checkpoint(boolean force) throws IOException {
// Checkpoint lock ensures consistent state between page store and logs.
synchronized (mCheckpointLock) {
final Node root = mRegistry.mRoot;
if (!force) {
root.acquireShared();
if (root.mCachedState == CACHED_CLEAN) {
// Root is clean, so nothing to do.
root.releaseShared();
return;
}
root.releaseShared();
}
long start = 0;
if (mEventListener != null) {
mEventListener.notify(EventType.CHECKPOINT_BEGIN,
"Checkpoint begin: %1$d", mRedoLog.logId());
start = System.nanoTime();
}
final long redoLogId = mRedoLog.openNewFile();
// Exclusive commit lock must be acquired before root latch, to
// prevent deadlock.
// If the commit lock cannot be immediately obtained, it's due to a
// shared lock being held for a long time. While waiting for the
// exclusive lock, all other shared requests are queued. By waiting
// a timed amount and giving up, the exclusive lock request is
// effectively de-prioritized. For each retry, the timeout is
// doubled, to ensure that the checkpoint request is not starved.
try {
Lock commitLock = mPageDb.exclusiveCommitLock();
long timeoutMillis = 1;
while (!commitLock.tryLock(timeoutMillis, TimeUnit.MILLISECONDS)) {
timeoutMillis <<= 1;
}
} catch (InterruptedException e) {
throw new InterruptedIOException();
}
root.acquireShared();
mCheckpointFlushState = CHECKPOINT_FLUSH_PREPARE;
final UndoLog masterUndoLog;
try {
// TODO: I don't like all this activity with exclusive commit
// lock held. UndoLog can be refactored to store into a special
// Tree, but this requires more features to be added to Tree
// first. Specifically, large values and appending to them.
final long masterUndoLogId;
synchronized (mTxnIdLock) {
int count = mUndoLogCount;
if (count == 0) {
masterUndoLog = null;
masterUndoLogId = 0;
} else {
masterUndoLog = UndoLog.newMasterUndoLog(this);
byte[] workspace = null;
for (UndoLog log = mTopUndoLog; log != null; log = log.mPrev) {
workspace = log.writeToMaster(masterUndoLog, workspace);
}
masterUndoLogId = masterUndoLog.topNodeId();
}
}
mPageDb.commit(new PageDb.CommitCallback() {
@Override
public byte[] prepare() throws IOException {
return flush(redoLogId, masterUndoLogId);
}
});
} catch (IOException e) {
if (mCheckpointFlushState == CHECKPOINT_FLUSH_PREPARE) {
// Exception was thrown with locks still held.
mCheckpointFlushState = CHECKPOINT_NOT_FLUSHING;
root.releaseShared();
mPageDb.exclusiveCommitLock().unlock();
}
throw e;
}
if (masterUndoLog != null) {
// Delete the master undo log, which won't take effect until
// the next checkpoint.
masterUndoLog.truncate(false);
}
// Note: The delete step can get skipped if process exits at this
// point. File is deleted again when database is re-opened.
mRedoLog.deleteOldFile(redoLogId);
// Deleted pages are now available for new allocations.
mAllocator.fill();
if (mEventListener != null) {
double duration = (System.nanoTime() - start) / 1000000000.0;
mEventListener.notify(EventType.CHECKPOINT_BEGIN,
"Checkpoint completed in %1$1.3f seconds",
duration, TimeUnit.SECONDS);
}
}
}
/**
* Method is invoked with exclusive commit lock and shared root node latch
* held. Both are released by this method.
*/
private byte[] flush(final long redoLogId, final long masterUndoLogId) throws IOException {
final long txnId;
synchronized (mTxnIdLock) {
txnId = mTxnId;
}
final Node root = mRegistry.mRoot;
final long rootId = root.mId;
final int stateToFlush = mCommitState;
mCheckpointFlushState = stateToFlush;
mCommitState = (byte) (stateToFlush ^ 1);
root.releaseShared();
mPageDb.exclusiveCommitLock().unlock();
if (mEventListener != null) {
mEventListener.notify(EventType.CHECKPOINT_FLUSH, "Flushing all dirty nodes");
}
try {
mAllocator.beginDirtyIteration();
Node node;
while ((node = mAllocator.removeNextDirtyNode(stateToFlush)) != null) {
node.downgrade();
try {
node.write(this);
// Clean state must be set after write completes. Although
// latch has been downgraded to shared, modifying the state
// is safe because no other thread could have changed it.
// Be extra paranoid and perform a volatile read first,
// ensuring that the write operation happens before. If the
// cache state becomes clean before the write, then node
// eviction logic gets confused. It can cause a node to get
// reloaded before it's previous write begins, which is
// clearly incorrect behavior.
if (mCheckpointFlushState != stateToFlush) {
throw new AssertionError();
}
node.mCachedState = CACHED_CLEAN;
} finally {
node.releaseShared();
}
}
} finally {
mCheckpointFlushState = CHECKPOINT_NOT_FLUSHING;
}
byte[] header = new byte[HEADER_SIZE];
writeIntLE(header, I_ENCODING_VERSION, ENCODING_VERSION);
writeLongLE(header, I_ROOT_PAGE_ID, rootId);
writeLongLE(header, I_MASTER_UNDO_LOG_PAGE_ID, masterUndoLogId);
writeLongLE(header, I_TRANSACTION_ID, txnId);
// Add one to redoLogId, indicating the active log id.
writeLongLE(header, I_REDO_LOG_ID, redoLogId + 1);
return header;
}
}
| true | true | private Database(DatabaseConfig config, boolean destroy) throws IOException {
mEventListener = SafeEventListener.makeSafe(config.mEventListener);
File baseFile = config.mBaseFile;
File[] dataFiles = config.dataFiles();
int pageSize = config.mPageSize;
if (pageSize <= 0) {
config.pageSize(pageSize = DEFAULT_PAGE_SIZE);
} else if (pageSize < MINIMUM_PAGE_SIZE) {
throw new IllegalArgumentException
("Page size is too small: " + pageSize + " < " + MINIMUM_PAGE_SIZE);
} else if (pageSize > MAXIMUM_PAGE_SIZE) {
throw new IllegalArgumentException
("Page size is too large: " + pageSize + " > " + MAXIMUM_PAGE_SIZE);
}
int minCache, maxCache;
cacheSize: {
long minCachedBytes = Math.max(0, config.mMinCachedBytes);
long maxCachedBytes = Math.max(0, config.mMaxCachedBytes);
if (maxCachedBytes == 0) {
maxCachedBytes = minCachedBytes;
if (maxCachedBytes == 0) {
minCache = maxCache = DEFAULT_CACHED_NODES;
break cacheSize;
}
}
if (minCachedBytes > maxCachedBytes) {
throw new IllegalArgumentException
("Minimum cache size exceeds maximum: " +
minCachedBytes + " > " + maxCachedBytes);
}
minCache = nodeCountFromBytes(minCachedBytes, pageSize);
maxCache = nodeCountFromBytes(maxCachedBytes, pageSize);
minCache = Math.max(MIN_CACHED_NODES, minCache);
maxCache = Math.max(MIN_CACHED_NODES, maxCache);
}
// Update config such that info file is correct.
config.mMinCachedBytes = byteCountFromNodes(minCache, pageSize);
config.mMaxCachedBytes = byteCountFromNodes(maxCache, pageSize);
mUsageLatch = new Latch();
mMaxNodeCount = maxCache;
mDurabilityMode = config.mDurabilityMode;
mDefaultLockTimeoutNanos = config.mLockTimeoutNanos;
mLockManager = new LockManager(mDefaultLockTimeoutNanos);
if (baseFile != null && !config.mReadOnly && config.mMkdirs) {
baseFile.getParentFile().mkdirs();
for (File f : dataFiles) {
f.getParentFile().mkdirs();
}
}
// Create lock file and write info file of properties.
if (baseFile == null) {
mLockFile = null;
} else {
mLockFile = new LockedFile(new File(baseFile.getPath() + ".lock"), config.mReadOnly);
if (!config.mReadOnly) {
File infoFile = new File(baseFile.getPath() + ".info");
Writer w = new BufferedWriter
(new OutputStreamWriter(new FileOutputStream(infoFile), "UTF-8"));
try {
config.writeInfo(w);
} finally {
w.close();
}
}
}
EnumSet<OpenOption> options = config.createOpenOptions();
if (baseFile != null && destroy) {
// Delete old redo log files.
deleteNumberedFiles(baseFile, ".redo.");
}
if (dataFiles == null) {
mPageDb = new NonPageDb(pageSize);
} else {
mPageDb = new DurablePageDb(pageSize, dataFiles, options, destroy);
}
mSharedCommitLock = mPageDb.sharedCommitLock();
try {
// Pre-allocate nodes. They are automatically added to the usage
// list, and so nothing special needs to be done to allow them to
// get used. Since the initial state is clean, evicting these
// nodes does nothing.
long cacheInitStart = 0;
if (mEventListener != null) {
mEventListener.notify(EventType.CACHE_INIT_BEGIN,
"Initializing %1$d cached nodes", minCache);
cacheInitStart = System.nanoTime();
}
try {
for (int i=minCache; --i>=0; ) {
allocLatchedNode(true).releaseExclusive();
}
} catch (OutOfMemoryError e) {
mMostRecentlyUsed = null;
mLeastRecentlyUsed = null;
throw new OutOfMemoryError
("Unable to allocate the minimum required number of cached nodes: " +
minCache);
}
if (mEventListener != null) {
double duration = (System.nanoTime() - cacheInitStart) / 1000000000.0;
mEventListener.notify(EventType.CHECKPOINT_BEGIN,
"Cache initialization completed in %1$1.3f seconds",
duration, TimeUnit.SECONDS);
}
int spareBufferCount = Runtime.getRuntime().availableProcessors();
mSpareBufferPool = new BufferPool(mPageDb.pageSize(), spareBufferCount);
mSharedCommitLock.lock();
try {
mCommitState = CACHED_DIRTY_0;
} finally {
mSharedCommitLock.unlock();
}
byte[] header = new byte[HEADER_SIZE];
mPageDb.readExtraCommitData(header);
mRegistry = new Tree(this, Tree.REGISTRY_ID, null, null, loadRegistryRoot(header));
mOpenTrees = new TreeMap<byte[], Tree>(KeyComparator.THE);
mOpenTreesById = new LHashTable.Obj<Tree>(16);
synchronized (mTxnIdLock) {
mTxnId = readLongLE(header, I_TRANSACTION_ID);
}
long redoLogId = readLongLE(header, I_REDO_LOG_ID);
// Initialized, but not open yet.
mRedoLog = baseFile == null ? null : new RedoLog(baseFile, redoLogId);
mRegistryKeyMap = openInternalTree(Tree.REGISTRY_KEY_MAP_ID, true);
mAllocator = new OrderedPageAllocator
(mPageDb, null /*openInternalTree(Tree.PAGE_ALLOCATOR_ID, true)*/);
if (baseFile == null) {
// Non-durable database never evicts anything.
mFragmentCache = new FragmentMap();
} else {
// Regular database evicts automatically.
mFragmentCache = new FragmentCache(this, mMaxNodeCount);
}
{
Tree tree = openInternalTree(Tree.FRAGMENTED_TRASH_ID, false);
if (tree != null) {
mFragmentedTrash = new FragmentedTrash(tree);
}
}
// Limit maximum fragmented entry size to guarantee that 2 entries
// fit. Each also requires 2 bytes for pointer and up to 3 bytes
// for value length field.
mMaxFragmentedEntrySize = (pageSize - Node.TN_HEADER_SIZE - (2 + 3 + 2 + 3)) >> 1;
long recoveryStart = 0;
if (mRedoLog != null) {
// Perform recovery by examining redo and undo logs.
if (mEventListener != null) {
mEventListener.notify(EventType.RECOVERY_BEGIN, "Database recovery begin");
recoveryStart = System.nanoTime();
}
UndoLog masterUndoLog;
LHashTable.Obj<UndoLog> undoLogs;
{
long nodeId = readLongLE(header, I_MASTER_UNDO_LOG_PAGE_ID);
if (nodeId == 0) {
masterUndoLog = null;
undoLogs = null;
} else {
if (mEventListener != null) {
mEventListener.notify
(EventType.RECOVERY_LOAD_UNDO_LOGS, "Loading undo logs");
}
masterUndoLog = UndoLog.recoverMasterUndoLog(this, nodeId);
undoLogs = masterUndoLog.recoverLogs();
}
}
// List of all replayed redo log files which should be deleted
// after the recovery checkpoint.
ArrayList<Long> redosToDelete = new ArrayList<Long>(2);
if (redoReplay(undoLogs)) {
// Make sure old redo logs are deleted. Process might have
// exited before last checkpoint could delete them.
for (int i=1; i<=2; i++) {
mRedoLog.deleteOldFile(redoLogId - i);
}
redosToDelete.add(mRedoLog.openNewFile());
while (mRedoLog.isReplayMode()) {
// Last checkpoint was interrupted, so apply next log file too.
redoReplay(undoLogs);
redosToDelete.add(mRedoLog.openNewFile());
}
}
boolean doCheckpoint = false;
if (masterUndoLog != null) {
// Rollback or truncate all remaining undo logs. They were
// never explicitly rolled back, or they were committed but
// not cleaned up. This also deletes the master undo log.
if (mEventListener != null) {
mEventListener.notify
(EventType.RECOVERY_PROCESS_REMAINING,
"Processing remaining transactions");
}
if (masterUndoLog.processRemaining(undoLogs)) {
// Checkpoint ensures that undo logs don't get
// re-applied following a restart.
doCheckpoint = true;
}
}
if (doCheckpoint || !redosToDelete.isEmpty()) {
// The one and only recovery checkpoint.
checkpoint(true);
// Only delete redo logs after successful checkpoint.
for (long id : redosToDelete) {
mRedoLog.deleteOldFile(id);
}
}
}
// Delete lingering fragmented values after undo logs have been
// processed, ensuring deletes were committed.
if (mFragmentedTrash != null) {
if (mEventListener != null) {
mEventListener.notify(EventType.RECOVERY_DELETE_FRAGMENTS,
"Deleting unused large fragments");
}
if (mFragmentedTrash.emptyAllTrash()) {
checkpoint(true);
}
}
mTempFileManager = baseFile == null ? null : new TempFileManager(baseFile);
if (mRedoLog != null && mEventListener != null) {
double duration = (System.nanoTime() - recoveryStart) / 1000000000.0;
mEventListener.notify(EventType.RECOVERY_COMPLETE,
"Recovery completed in %1$1.3f seconds",
duration, TimeUnit.SECONDS);
}
} catch (Throwable e) {
closeQuietly(null, this, e);
throw rethrow(e);
}
}
| private Database(DatabaseConfig config, boolean destroy) throws IOException {
mEventListener = SafeEventListener.makeSafe(config.mEventListener);
File baseFile = config.mBaseFile;
File[] dataFiles = config.dataFiles();
int pageSize = config.mPageSize;
if (pageSize <= 0) {
config.pageSize(pageSize = DEFAULT_PAGE_SIZE);
} else if (pageSize < MINIMUM_PAGE_SIZE) {
throw new IllegalArgumentException
("Page size is too small: " + pageSize + " < " + MINIMUM_PAGE_SIZE);
} else if (pageSize > MAXIMUM_PAGE_SIZE) {
throw new IllegalArgumentException
("Page size is too large: " + pageSize + " > " + MAXIMUM_PAGE_SIZE);
}
int minCache, maxCache;
cacheSize: {
long minCachedBytes = Math.max(0, config.mMinCachedBytes);
long maxCachedBytes = Math.max(0, config.mMaxCachedBytes);
if (maxCachedBytes == 0) {
maxCachedBytes = minCachedBytes;
if (maxCachedBytes == 0) {
minCache = maxCache = DEFAULT_CACHED_NODES;
break cacheSize;
}
}
if (minCachedBytes > maxCachedBytes) {
throw new IllegalArgumentException
("Minimum cache size exceeds maximum: " +
minCachedBytes + " > " + maxCachedBytes);
}
minCache = nodeCountFromBytes(minCachedBytes, pageSize);
maxCache = nodeCountFromBytes(maxCachedBytes, pageSize);
minCache = Math.max(MIN_CACHED_NODES, minCache);
maxCache = Math.max(MIN_CACHED_NODES, maxCache);
}
// Update config such that info file is correct.
config.mMinCachedBytes = byteCountFromNodes(minCache, pageSize);
config.mMaxCachedBytes = byteCountFromNodes(maxCache, pageSize);
mUsageLatch = new Latch();
mMaxNodeCount = maxCache;
mDurabilityMode = config.mDurabilityMode;
mDefaultLockTimeoutNanos = config.mLockTimeoutNanos;
mLockManager = new LockManager(mDefaultLockTimeoutNanos);
if (baseFile != null && !config.mReadOnly && config.mMkdirs) {
baseFile.getParentFile().mkdirs();
for (File f : dataFiles) {
f.getParentFile().mkdirs();
}
}
// Create lock file and write info file of properties.
if (baseFile == null) {
mLockFile = null;
} else {
mLockFile = new LockedFile(new File(baseFile.getPath() + ".lock"), config.mReadOnly);
if (!config.mReadOnly) {
File infoFile = new File(baseFile.getPath() + ".info");
Writer w = new BufferedWriter
(new OutputStreamWriter(new FileOutputStream(infoFile), "UTF-8"));
try {
config.writeInfo(w);
} finally {
w.close();
}
}
}
EnumSet<OpenOption> options = config.createOpenOptions();
if (baseFile != null && destroy) {
// Delete old redo log files.
deleteNumberedFiles(baseFile, ".redo.");
}
if (dataFiles == null) {
mPageDb = new NonPageDb(pageSize);
} else {
mPageDb = new DurablePageDb(pageSize, dataFiles, options, destroy);
}
mSharedCommitLock = mPageDb.sharedCommitLock();
try {
// Pre-allocate nodes. They are automatically added to the usage
// list, and so nothing special needs to be done to allow them to
// get used. Since the initial state is clean, evicting these
// nodes does nothing.
long cacheInitStart = 0;
if (mEventListener != null) {
mEventListener.notify(EventType.CACHE_INIT_BEGIN,
"Initializing %1$d cached nodes", minCache);
cacheInitStart = System.nanoTime();
}
try {
for (int i=minCache; --i>=0; ) {
allocLatchedNode(true).releaseExclusive();
}
} catch (OutOfMemoryError e) {
mMostRecentlyUsed = null;
mLeastRecentlyUsed = null;
throw new OutOfMemoryError
("Unable to allocate the minimum required number of cached nodes: " +
minCache);
}
if (mEventListener != null) {
double duration = (System.nanoTime() - cacheInitStart) / 1000000000.0;
mEventListener.notify(EventType.CACHE_INIT_COMPLETE,
"Cache initialization completed in %1$1.3f seconds",
duration, TimeUnit.SECONDS);
}
int spareBufferCount = Runtime.getRuntime().availableProcessors();
mSpareBufferPool = new BufferPool(mPageDb.pageSize(), spareBufferCount);
mSharedCommitLock.lock();
try {
mCommitState = CACHED_DIRTY_0;
} finally {
mSharedCommitLock.unlock();
}
byte[] header = new byte[HEADER_SIZE];
mPageDb.readExtraCommitData(header);
mRegistry = new Tree(this, Tree.REGISTRY_ID, null, null, loadRegistryRoot(header));
mOpenTrees = new TreeMap<byte[], Tree>(KeyComparator.THE);
mOpenTreesById = new LHashTable.Obj<Tree>(16);
synchronized (mTxnIdLock) {
mTxnId = readLongLE(header, I_TRANSACTION_ID);
}
long redoLogId = readLongLE(header, I_REDO_LOG_ID);
// Initialized, but not open yet.
mRedoLog = baseFile == null ? null : new RedoLog(baseFile, redoLogId);
mRegistryKeyMap = openInternalTree(Tree.REGISTRY_KEY_MAP_ID, true);
mAllocator = new OrderedPageAllocator
(mPageDb, null /*openInternalTree(Tree.PAGE_ALLOCATOR_ID, true)*/);
if (baseFile == null) {
// Non-durable database never evicts anything.
mFragmentCache = new FragmentMap();
} else {
// Regular database evicts automatically.
mFragmentCache = new FragmentCache(this, mMaxNodeCount);
}
{
Tree tree = openInternalTree(Tree.FRAGMENTED_TRASH_ID, false);
if (tree != null) {
mFragmentedTrash = new FragmentedTrash(tree);
}
}
// Limit maximum fragmented entry size to guarantee that 2 entries
// fit. Each also requires 2 bytes for pointer and up to 3 bytes
// for value length field.
mMaxFragmentedEntrySize = (pageSize - Node.TN_HEADER_SIZE - (2 + 3 + 2 + 3)) >> 1;
long recoveryStart = 0;
if (mRedoLog != null) {
// Perform recovery by examining redo and undo logs.
if (mEventListener != null) {
mEventListener.notify(EventType.RECOVERY_BEGIN, "Database recovery begin");
recoveryStart = System.nanoTime();
}
UndoLog masterUndoLog;
LHashTable.Obj<UndoLog> undoLogs;
{
long nodeId = readLongLE(header, I_MASTER_UNDO_LOG_PAGE_ID);
if (nodeId == 0) {
masterUndoLog = null;
undoLogs = null;
} else {
if (mEventListener != null) {
mEventListener.notify
(EventType.RECOVERY_LOAD_UNDO_LOGS, "Loading undo logs");
}
masterUndoLog = UndoLog.recoverMasterUndoLog(this, nodeId);
undoLogs = masterUndoLog.recoverLogs();
}
}
// List of all replayed redo log files which should be deleted
// after the recovery checkpoint.
ArrayList<Long> redosToDelete = new ArrayList<Long>(2);
if (redoReplay(undoLogs)) {
// Make sure old redo logs are deleted. Process might have
// exited before last checkpoint could delete them.
for (int i=1; i<=2; i++) {
mRedoLog.deleteOldFile(redoLogId - i);
}
redosToDelete.add(mRedoLog.openNewFile());
while (mRedoLog.isReplayMode()) {
// Last checkpoint was interrupted, so apply next log file too.
redoReplay(undoLogs);
redosToDelete.add(mRedoLog.openNewFile());
}
}
boolean doCheckpoint = false;
if (masterUndoLog != null) {
// Rollback or truncate all remaining undo logs. They were
// never explicitly rolled back, or they were committed but
// not cleaned up. This also deletes the master undo log.
if (mEventListener != null) {
mEventListener.notify
(EventType.RECOVERY_PROCESS_REMAINING,
"Processing remaining transactions");
}
if (masterUndoLog.processRemaining(undoLogs)) {
// Checkpoint ensures that undo logs don't get
// re-applied following a restart.
doCheckpoint = true;
}
}
if (doCheckpoint || !redosToDelete.isEmpty()) {
// The one and only recovery checkpoint.
checkpoint(true);
// Only delete redo logs after successful checkpoint.
for (long id : redosToDelete) {
mRedoLog.deleteOldFile(id);
}
}
}
// Delete lingering fragmented values after undo logs have been
// processed, ensuring deletes were committed.
if (mFragmentedTrash != null) {
if (mEventListener != null) {
mEventListener.notify(EventType.RECOVERY_DELETE_FRAGMENTS,
"Deleting unused large fragments");
}
if (mFragmentedTrash.emptyAllTrash()) {
checkpoint(true);
}
}
mTempFileManager = baseFile == null ? null : new TempFileManager(baseFile);
if (mRedoLog != null && mEventListener != null) {
double duration = (System.nanoTime() - recoveryStart) / 1000000000.0;
mEventListener.notify(EventType.RECOVERY_COMPLETE,
"Recovery completed in %1$1.3f seconds",
duration, TimeUnit.SECONDS);
}
} catch (Throwable e) {
closeQuietly(null, this, e);
throw rethrow(e);
}
}
|
diff --git a/kernel/src/tests/org/jboss/test/kernel/deployment/support/container/BeanPool.java b/kernel/src/tests/org/jboss/test/kernel/deployment/support/container/BeanPool.java
index 1bca3e8f..f22c8835 100644
--- a/kernel/src/tests/org/jboss/test/kernel/deployment/support/container/BeanPool.java
+++ b/kernel/src/tests/org/jboss/test/kernel/deployment/support/container/BeanPool.java
@@ -1,70 +1,71 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.test.kernel.deployment.support.container;
import java.util.concurrent.ArrayBlockingQueue;
import org.jboss.beans.metadata.spi.factory.BeanFactory;
/**
*
* @param <T> the type
* @author [email protected]
* @version $Revision$
*/
public class BeanPool<T>
{
/** The pooling policy */
private ArrayBlockingQueue<T> pool = new ArrayBlockingQueue<T>(2);
private BeanFactory factory;
public BeanFactory getFactory()
{
return factory;
}
public void setFactory(BeanFactory factory)
{
this.factory = factory;
}
@SuppressWarnings("unchecked")
public synchronized T createBean()
throws Throwable
{
if(pool.size() == 0)
{
+ int capacity = pool.remainingCapacity();
// Fill the pool
- for(int n = 0; n < pool.remainingCapacity(); n ++)
+ for(int n = 0; n < capacity; n ++)
{
T bean = (T) factory.createBean();
pool.put(bean);
}
}
return pool.take();
}
public void destroyBean(T bean)
throws Throwable
{
pool.put(bean);
}
}
| false | true | public synchronized T createBean()
throws Throwable
{
if(pool.size() == 0)
{
// Fill the pool
for(int n = 0; n < pool.remainingCapacity(); n ++)
{
T bean = (T) factory.createBean();
pool.put(bean);
}
}
return pool.take();
}
| public synchronized T createBean()
throws Throwable
{
if(pool.size() == 0)
{
int capacity = pool.remainingCapacity();
// Fill the pool
for(int n = 0; n < capacity; n ++)
{
T bean = (T) factory.createBean();
pool.put(bean);
}
}
return pool.take();
}
|
diff --git a/orcid-utils/src/main/java/org/orcid/utils/OrcidWebUtils.java b/orcid-utils/src/main/java/org/orcid/utils/OrcidWebUtils.java
index 9d6fceeb07..e350e99cdf 100644
--- a/orcid-utils/src/main/java/org/orcid/utils/OrcidWebUtils.java
+++ b/orcid-utils/src/main/java/org/orcid/utils/OrcidWebUtils.java
@@ -1,65 +1,66 @@
/**
* =============================================================================
*
* ORCID (R) Open Source
* http://orcid.org
*
* Copyright (c) 2012-2013 ORCID, Inc.
* Licensed under an MIT-Style License (MIT)
* http://orcid.org/open-source-license
*
* This copyright and license information (including a link to the full license)
* shall be included in its entirety in all copies or substantial portion of
* the software.
*
* =============================================================================
*/
package org.orcid.utils;
import javax.servlet.http.HttpServletRequest;
import java.net.URI;
import java.net.URISyntaxException;
/**
* 2011-2012 ORCID
*
* @author Declan Newman (declan) Date: 29/03/2012
*/
public class OrcidWebUtils {
public static URI getServerUriWithContextPath(HttpServletRequest request) {
try {
return new URI(getServerStringWithContextPath(request));
} catch (URISyntaxException e) {
throw new IllegalArgumentException("Cannot create a URI from request");
}
}
public static URI getServerUri(HttpServletRequest request) {
try {
return new URI(getServerString(request));
} catch (URISyntaxException e) {
throw new IllegalArgumentException("Cannot create a URI from request");
}
}
public static String getServerStringWithContextPath(HttpServletRequest request) {
String contextPath = request.getContextPath();
String serverString = getServerString(request);
return contextPath == null ? serverString : serverString + contextPath;
}
public static String getServerString(HttpServletRequest request) {
- String scheme = request.getScheme();
+ String forwardedProto = request.getHeader("X-Forwarded-Proto");
+ String scheme = forwardedProto != null ? forwardedProto : request.getScheme();
int serverPort = request.getServerPort();
String serverName = request.getServerName();
StringBuilder sb = new StringBuilder();
sb.append(scheme);
sb.append("://");
sb.append(serverName);
sb.append((("https".equalsIgnoreCase(scheme) && serverPort == 443) || ("http".equalsIgnoreCase(scheme) && serverPort == 80)) ? "" : ":" + serverPort);
return sb.toString();
}
}
| true | true | public static String getServerString(HttpServletRequest request) {
String scheme = request.getScheme();
int serverPort = request.getServerPort();
String serverName = request.getServerName();
StringBuilder sb = new StringBuilder();
sb.append(scheme);
sb.append("://");
sb.append(serverName);
sb.append((("https".equalsIgnoreCase(scheme) && serverPort == 443) || ("http".equalsIgnoreCase(scheme) && serverPort == 80)) ? "" : ":" + serverPort);
return sb.toString();
}
| public static String getServerString(HttpServletRequest request) {
String forwardedProto = request.getHeader("X-Forwarded-Proto");
String scheme = forwardedProto != null ? forwardedProto : request.getScheme();
int serverPort = request.getServerPort();
String serverName = request.getServerName();
StringBuilder sb = new StringBuilder();
sb.append(scheme);
sb.append("://");
sb.append(serverName);
sb.append((("https".equalsIgnoreCase(scheme) && serverPort == 443) || ("http".equalsIgnoreCase(scheme) && serverPort == 80)) ? "" : ":" + serverPort);
return sb.toString();
}
|
diff --git a/portalobjects/binding/src/test/java/org/gatein/management/portalobjects/binding/impl/AbstractMarshallerTest.java b/portalobjects/binding/src/test/java/org/gatein/management/portalobjects/binding/impl/AbstractMarshallerTest.java
index 774c317..45150f5 100644
--- a/portalobjects/binding/src/test/java/org/gatein/management/portalobjects/binding/impl/AbstractMarshallerTest.java
+++ b/portalobjects/binding/src/test/java/org/gatein/management/portalobjects/binding/impl/AbstractMarshallerTest.java
@@ -1,161 +1,161 @@
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.gatein.management.portalobjects.binding.impl;
import org.exoplatform.portal.config.model.ApplicationState;
import org.exoplatform.portal.config.model.TransientApplicationState;
import org.exoplatform.portal.pom.data.ApplicationData;
import org.exoplatform.portal.pom.data.BodyData;
import org.exoplatform.portal.pom.data.ComponentData;
import org.exoplatform.portal.pom.data.ContainerData;
import org.exoplatform.portal.pom.spi.portlet.Portlet;
import org.exoplatform.portal.pom.spi.portlet.Preference;
import java.util.List;
import static org.junit.Assert.*;
/**
* @author <a href="mailto:[email protected]">Nick Scavelli</a>
* @version $Revision$
*/
public abstract class AbstractMarshallerTest
{
protected void compareComponents(List<ComponentData> expectedComponents, List<ComponentData> actualComponents)
{
assertEquals(expectedComponents.size(), actualComponents.size());
for (int i=0; i<expectedComponents.size(); i++)
{
ComponentData expected = expectedComponents.get(i);
ComponentData actual = actualComponents.get(i);
assertEquals(expected.getClass(), actual.getClass());
if (expected instanceof ApplicationData)
{
compareApplicationData((ApplicationData) expected, (ApplicationData) actual);
}
else if (expected instanceof BodyData)
{
compareBodyData((BodyData) expected, (BodyData) actual);
}
else if (expected instanceof ContainerData)
{
compareContainerData((ContainerData) expected, (ContainerData) actual);
}
}
}
protected void compareContainerData(ContainerData expected, ContainerData actual)
{
assertNull(actual.getStorageId());
assertNull(actual.getStorageName());
assertNull(actual.getId());
assertEquals(expected.getName(), actual.getName());
assertEquals(expected.getIcon(), actual.getIcon());
assertEquals(expected.getTemplate(), actual.getTemplate());
assertEquals(expected.getFactoryId(), actual.getFactoryId());
assertEquals(expected.getTitle(), actual.getTitle());
assertEquals(expected.getDescription(), actual.getDescription());
assertEquals(expected.getWidth(), actual.getWidth());
assertEquals(expected.getHeight(), actual.getHeight());
assertEquals(expected.getAccessPermissions(), actual.getAccessPermissions());
compareComponents(expected.getChildren(), actual.getChildren());
}
protected void compareApplicationData(ApplicationData expected, ApplicationData actual)
{
assertNull(actual.getStorageId());
assertNull(actual.getStorageName());
assertEquals(expected.getType(), actual.getType());
if (expected.getState() == null)
{
assertNull(actual.getState());
}
else
{
assertNotNull(actual.getState());
- compareApplicationState(actual.getState(), expected.getState());
+ compareApplicationState(expected.getState(), actual.getState());
}
assertNull(actual.getStorageId());
assertNull(actual.getStorageName());
assertNull(actual.getId());
assertEquals(expected.getTitle(), actual.getTitle());
assertEquals(expected.getIcon(), actual.getIcon());
assertEquals(expected.getDescription(), actual.getDescription());
assertEquals(expected.isShowInfoBar(), actual.isShowInfoBar());
assertEquals(expected.isShowApplicationState(), actual.isShowApplicationState());
assertEquals(expected.isShowApplicationMode(), actual.isShowApplicationMode());
assertEquals(expected.getTheme(), actual.getTheme());
assertEquals(expected.getWidth(), actual.getWidth());
assertEquals(expected.getHeight(), actual.getHeight());
assertEquals(expected.getProperties(), actual.getProperties());
assertEquals(expected.getAccessPermissions(), actual.getAccessPermissions());
}
protected void compareApplicationState(ApplicationState expected, ApplicationState actual)
{
assertEquals(expected.getClass(), actual.getClass());
if (expected instanceof TransientApplicationState)
{
TransientApplicationState expectedTas = (TransientApplicationState) expected;
TransientApplicationState actualTas = (TransientApplicationState) actual;
assertEquals(expectedTas.getContentId(), actualTas.getContentId());
assertNull(actualTas.getOwnerType());
assertNull(actualTas.getOwnerId());
assertNull(actualTas.getUniqueId());
if (expectedTas.getContentState() == null)
{
assertNull(actualTas.getContentState());
}
else
{
assertEquals(expectedTas.getContentState().getClass(), actualTas.getContentState().getClass());
if (expectedTas.getContentState() instanceof Portlet)
{
comparePortlet((Portlet) expectedTas.getContentState(), (Portlet) actualTas.getContentState());
}
}
}
}
protected void comparePortlet(Portlet expected, Portlet actual)
{
for (Preference expectedPref : expected)
{
Preference actualPref = actual.getPreference(expectedPref.getName());
assertNotNull(actualPref);
assertEquals(expectedPref.getName(), actualPref.getName());
assertEquals(expectedPref.getValues(), actualPref.getValues());
assertEquals(expectedPref.isReadOnly(), actualPref.isReadOnly());
}
}
protected void compareBodyData(BodyData expected, BodyData actual)
{
assertNull(actual.getStorageId());
assertNull(actual.getStorageName());
assertEquals(expected.getType(), actual.getType());
}
}
| true | true | protected void compareApplicationData(ApplicationData expected, ApplicationData actual)
{
assertNull(actual.getStorageId());
assertNull(actual.getStorageName());
assertEquals(expected.getType(), actual.getType());
if (expected.getState() == null)
{
assertNull(actual.getState());
}
else
{
assertNotNull(actual.getState());
compareApplicationState(actual.getState(), expected.getState());
}
assertNull(actual.getStorageId());
assertNull(actual.getStorageName());
assertNull(actual.getId());
assertEquals(expected.getTitle(), actual.getTitle());
assertEquals(expected.getIcon(), actual.getIcon());
assertEquals(expected.getDescription(), actual.getDescription());
assertEquals(expected.isShowInfoBar(), actual.isShowInfoBar());
assertEquals(expected.isShowApplicationState(), actual.isShowApplicationState());
assertEquals(expected.isShowApplicationMode(), actual.isShowApplicationMode());
assertEquals(expected.getTheme(), actual.getTheme());
assertEquals(expected.getWidth(), actual.getWidth());
assertEquals(expected.getHeight(), actual.getHeight());
assertEquals(expected.getProperties(), actual.getProperties());
assertEquals(expected.getAccessPermissions(), actual.getAccessPermissions());
}
| protected void compareApplicationData(ApplicationData expected, ApplicationData actual)
{
assertNull(actual.getStorageId());
assertNull(actual.getStorageName());
assertEquals(expected.getType(), actual.getType());
if (expected.getState() == null)
{
assertNull(actual.getState());
}
else
{
assertNotNull(actual.getState());
compareApplicationState(expected.getState(), actual.getState());
}
assertNull(actual.getStorageId());
assertNull(actual.getStorageName());
assertNull(actual.getId());
assertEquals(expected.getTitle(), actual.getTitle());
assertEquals(expected.getIcon(), actual.getIcon());
assertEquals(expected.getDescription(), actual.getDescription());
assertEquals(expected.isShowInfoBar(), actual.isShowInfoBar());
assertEquals(expected.isShowApplicationState(), actual.isShowApplicationState());
assertEquals(expected.isShowApplicationMode(), actual.isShowApplicationMode());
assertEquals(expected.getTheme(), actual.getTheme());
assertEquals(expected.getWidth(), actual.getWidth());
assertEquals(expected.getHeight(), actual.getHeight());
assertEquals(expected.getProperties(), actual.getProperties());
assertEquals(expected.getAccessPermissions(), actual.getAccessPermissions());
}
|
diff --git a/panc/src/main/java/org/quattor/pan/dml/functions/Replace.java b/panc/src/main/java/org/quattor/pan/dml/functions/Replace.java
index 8bb23c5..279fbf8 100644
--- a/panc/src/main/java/org/quattor/pan/dml/functions/Replace.java
+++ b/panc/src/main/java/org/quattor/pan/dml/functions/Replace.java
@@ -1,110 +1,116 @@
/*
Copyright (c) 2006 Charles A. Loomis, Jr, Cedric Duprilot, and
Centre National de la Recherche Scientifique (CNRS).
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
$HeadURL: https://svn.lal.in2p3.fr/LCG/QWG/panc/trunk/src/org/quattor/pan/dml/functions/Substr.java $
$Id: Substr.java 2618 2007-12-08 16:32:02Z loomis $
*/
package org.quattor.pan.dml.functions;
import static org.quattor.pan.utils.MessageUtils.MSG_3_ARGS_REQ;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import org.quattor.pan.dml.Operation;
import org.quattor.pan.dml.data.Element;
import org.quattor.pan.dml.data.StringProperty;
import org.quattor.pan.exceptions.EvaluationException;
import org.quattor.pan.exceptions.SyntaxException;
import org.quattor.pan.template.Context;
import org.quattor.pan.template.SourceRange;
/**
* Replace occurrences of a regular expression with a given string.
*
* @author loomis
*
*/
final public class Replace extends BuiltInFunction {
private Replace(SourceRange sourceRange, Operation... operations)
throws SyntaxException {
super("replace", sourceRange, operations);
}
public static Operation getInstance(SourceRange sourceRange,
Operation... operations) throws SyntaxException {
// There must be three arguments.
if (operations.length != 3) {
throw SyntaxException
.create(sourceRange, MSG_3_ARGS_REQ, "replace");
}
return new Replace(sourceRange, operations);
}
@Override
public Element execute(Context context) {
assert (ops.length == 3);
// Extract the first argument. This must be a string value and also a
// valid regular expression.
Pattern regex = null;
try {
String re = ((StringProperty) ops[0].execute(context)).getValue();
regex = Pattern.compile(re);
} catch (ClassCastException cce) {
throw new EvaluationException(
"first argument to replace() must be a regular expression string",
getSourceRange(), context);
} catch (PatternSyntaxException pse) {
throw new EvaluationException("invalid regular expression: "
+ pse.getLocalizedMessage(), getSourceRange(), context);
}
// Extract the second argument, the replacement string.
String repl = null;
try {
repl = ((StringProperty) ops[1].execute(context)).getValue();
} catch (ClassCastException cce) {
throw new EvaluationException(
"second argument to replace() must be a replacement string",
getSourceRange(), context);
}
// Finally get the target string.
String target = null;
try {
target = ((StringProperty) ops[2].execute(context)).getValue();
} catch (ClassCastException cce) {
throw new EvaluationException(
"third argument to replace() must be a string",
getSourceRange(), context);
}
- String result = regex.matcher(target).replaceAll(repl);
- return StringProperty.getInstance(result);
+ try {
+ String result = regex.matcher(target).replaceAll(repl);
+ return StringProperty.getInstance(result);
+ } catch (IllegalArgumentException e) {
+ throw new EvaluationException(
+ "invalid replacement string; check '$' and '\\' characters",
+ getSourceRange(), context);
+ }
}
}
| true | true | public Element execute(Context context) {
assert (ops.length == 3);
// Extract the first argument. This must be a string value and also a
// valid regular expression.
Pattern regex = null;
try {
String re = ((StringProperty) ops[0].execute(context)).getValue();
regex = Pattern.compile(re);
} catch (ClassCastException cce) {
throw new EvaluationException(
"first argument to replace() must be a regular expression string",
getSourceRange(), context);
} catch (PatternSyntaxException pse) {
throw new EvaluationException("invalid regular expression: "
+ pse.getLocalizedMessage(), getSourceRange(), context);
}
// Extract the second argument, the replacement string.
String repl = null;
try {
repl = ((StringProperty) ops[1].execute(context)).getValue();
} catch (ClassCastException cce) {
throw new EvaluationException(
"second argument to replace() must be a replacement string",
getSourceRange(), context);
}
// Finally get the target string.
String target = null;
try {
target = ((StringProperty) ops[2].execute(context)).getValue();
} catch (ClassCastException cce) {
throw new EvaluationException(
"third argument to replace() must be a string",
getSourceRange(), context);
}
String result = regex.matcher(target).replaceAll(repl);
return StringProperty.getInstance(result);
}
| public Element execute(Context context) {
assert (ops.length == 3);
// Extract the first argument. This must be a string value and also a
// valid regular expression.
Pattern regex = null;
try {
String re = ((StringProperty) ops[0].execute(context)).getValue();
regex = Pattern.compile(re);
} catch (ClassCastException cce) {
throw new EvaluationException(
"first argument to replace() must be a regular expression string",
getSourceRange(), context);
} catch (PatternSyntaxException pse) {
throw new EvaluationException("invalid regular expression: "
+ pse.getLocalizedMessage(), getSourceRange(), context);
}
// Extract the second argument, the replacement string.
String repl = null;
try {
repl = ((StringProperty) ops[1].execute(context)).getValue();
} catch (ClassCastException cce) {
throw new EvaluationException(
"second argument to replace() must be a replacement string",
getSourceRange(), context);
}
// Finally get the target string.
String target = null;
try {
target = ((StringProperty) ops[2].execute(context)).getValue();
} catch (ClassCastException cce) {
throw new EvaluationException(
"third argument to replace() must be a string",
getSourceRange(), context);
}
try {
String result = regex.matcher(target).replaceAll(repl);
return StringProperty.getInstance(result);
} catch (IllegalArgumentException e) {
throw new EvaluationException(
"invalid replacement string; check '$' and '\\' characters",
getSourceRange(), context);
}
}
|
diff --git a/nanoscrollpanel-demo/src/main/java/org/vaadin/hhe/nanoscrollpanel/demo/NanoScrollPanelDemoUI.java b/nanoscrollpanel-demo/src/main/java/org/vaadin/hhe/nanoscrollpanel/demo/NanoScrollPanelDemoUI.java
index bad5e5c..285b4e8 100644
--- a/nanoscrollpanel-demo/src/main/java/org/vaadin/hhe/nanoscrollpanel/demo/NanoScrollPanelDemoUI.java
+++ b/nanoscrollpanel-demo/src/main/java/org/vaadin/hhe/nanoscrollpanel/demo/NanoScrollPanelDemoUI.java
@@ -1,164 +1,161 @@
package org.vaadin.hhe.nanoscrollpanel.demo;
import org.vaadin.hhe.nanoscrollpanel.NanoScrollPanel;
import org.vaadin.hhe.nanoscrollpanel.NanoScrollPanel.NanoScrollEvent;
import org.vaadin.hhe.nanoscrollpanel.NanoScrollPanel.NanoScrollPanelListener;
import com.vaadin.server.VaadinRequest;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.Component;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.Notification;
import com.vaadin.ui.Panel;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
public class NanoScrollPanelDemoUI extends UI {
private static final long serialVersionUID = 7992657815796718844L;
private Component scrollToTarget = null;
@SuppressWarnings("serial")
@Override
protected void init(VaadinRequest request) {
final NanoScrollPanel nPanel = new NanoScrollPanel();
nPanel.setWidth("400px");
nPanel.setHeight("400px");
// flash user there are more content
nPanel.flashScrollbar();
nPanel.setPreventPageScrolling(true);
nPanel.addNanoScrollListener(new NanoScrollPanelListener() {
@Override
public void onScroll(NanoScrollEvent event) {
Notification.show("NanoScrollEvent catched",
"Event type is "+event.getType(),
Notification.Type.HUMANIZED_MESSAGE);
}
});
nPanel.addClickListener(new com.vaadin.event.MouseEvents.ClickListener() {
@Override
public void click(com.vaadin.event.MouseEvents.ClickEvent event) {
if(event.isDoubleClick()) {
Notification.show("NanoScrollPanel was double clicked", "Event",
Notification.Type.HUMANIZED_MESSAGE);
} else {
Notification.show("NanoScrollPanel was clicked", "Event",
Notification.Type.HUMANIZED_MESSAGE);
}
}
});
final VerticalLayout vLayout = new VerticalLayout();
for(int i=0; i<50; ++i) {
Label l = new Label("This is a example of NanoScrollPanel "+i+".");
l.setId("Label"+i);
if(i==25) scrollToTarget = l;
vLayout.addComponent(l);
}
Button btn = new Button("Add more");
vLayout.addComponent(btn);
btn.addClickListener(new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
vLayout.addComponent(new Label("This is more and more test."));
}
});
Button btn2 = new Button("Remove one");
vLayout.addComponent(btn2);
btn2.addClickListener(new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
if(vLayout.getComponentCount()>54)
vLayout.removeComponent(vLayout.getComponent(vLayout.getComponentCount()-1));
}
});
Button btn3 = new Button("Shrink");
vLayout.addComponent(btn3);
btn3.addClickListener(new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
nPanel.setHeight(nPanel.getHeight()*0.8f, nPanel.getHeightUnits());
}
});
Button btn4 = new Button("Expand");
vLayout.addComponent(btn4);
btn4.addClickListener(new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
nPanel.setHeight(nPanel.getHeight()/0.8f, nPanel.getHeightUnits());
}
});
nPanel.setContent(vLayout);
VerticalLayout nanoScrollLayout = new VerticalLayout();
nanoScrollLayout.addComponent(nPanel);
Button flashBtn = new Button("Flash Scrollbar");
flashBtn.addClickListener(new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
nPanel.flashScrollbar();
}
});
nanoScrollLayout.addComponent(flashBtn);
Button scrollTopBtn = new Button("Scroll To Top");
scrollTopBtn.addClickListener(new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
nPanel.flashScrollbar();
nPanel.scrollToTop();
}
});
nanoScrollLayout.addComponent(scrollTopBtn);
Button scrollBottomBtn = new Button("Scroll To Bottom");
scrollBottomBtn.addClickListener(new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
nPanel.flashScrollbar();
nPanel.scrollToBottom();
}
});
nanoScrollLayout.addComponent(scrollBottomBtn);
Button scrollToBtn = new Button("Scroll To 25");
scrollToBtn.addClickListener(new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
nPanel.flashScrollbar();
nPanel.scrollTo(scrollToTarget);
}
});
nanoScrollLayout.addComponent(scrollToBtn);
HorizontalLayout hLayout = new HorizontalLayout();
hLayout.addComponent(nanoScrollLayout);
Panel normalPanel = new Panel();
normalPanel.setWidth("400px");
normalPanel.setHeight("400px");
final VerticalLayout normalPanelContentLayout = new VerticalLayout();
normalPanelContentLayout.setMargin(true);
for(int i=0; i<50; ++i) {
- Label l = new Label("This is a example of Normal Panel "+i+".");
- l.setId("Label"+i);
- if(i==25) scrollToTarget = l;
- normalPanelContentLayout.addComponent(l);
+ normalPanelContentLayout.addComponent(new Label("This is a example of Normal Panel "+i+"."));
}
normalPanel.setContent(normalPanelContentLayout);
hLayout.addComponent(normalPanel);
setContent(hLayout);
}
}
| true | true | protected void init(VaadinRequest request) {
final NanoScrollPanel nPanel = new NanoScrollPanel();
nPanel.setWidth("400px");
nPanel.setHeight("400px");
// flash user there are more content
nPanel.flashScrollbar();
nPanel.setPreventPageScrolling(true);
nPanel.addNanoScrollListener(new NanoScrollPanelListener() {
@Override
public void onScroll(NanoScrollEvent event) {
Notification.show("NanoScrollEvent catched",
"Event type is "+event.getType(),
Notification.Type.HUMANIZED_MESSAGE);
}
});
nPanel.addClickListener(new com.vaadin.event.MouseEvents.ClickListener() {
@Override
public void click(com.vaadin.event.MouseEvents.ClickEvent event) {
if(event.isDoubleClick()) {
Notification.show("NanoScrollPanel was double clicked", "Event",
Notification.Type.HUMANIZED_MESSAGE);
} else {
Notification.show("NanoScrollPanel was clicked", "Event",
Notification.Type.HUMANIZED_MESSAGE);
}
}
});
final VerticalLayout vLayout = new VerticalLayout();
for(int i=0; i<50; ++i) {
Label l = new Label("This is a example of NanoScrollPanel "+i+".");
l.setId("Label"+i);
if(i==25) scrollToTarget = l;
vLayout.addComponent(l);
}
Button btn = new Button("Add more");
vLayout.addComponent(btn);
btn.addClickListener(new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
vLayout.addComponent(new Label("This is more and more test."));
}
});
Button btn2 = new Button("Remove one");
vLayout.addComponent(btn2);
btn2.addClickListener(new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
if(vLayout.getComponentCount()>54)
vLayout.removeComponent(vLayout.getComponent(vLayout.getComponentCount()-1));
}
});
Button btn3 = new Button("Shrink");
vLayout.addComponent(btn3);
btn3.addClickListener(new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
nPanel.setHeight(nPanel.getHeight()*0.8f, nPanel.getHeightUnits());
}
});
Button btn4 = new Button("Expand");
vLayout.addComponent(btn4);
btn4.addClickListener(new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
nPanel.setHeight(nPanel.getHeight()/0.8f, nPanel.getHeightUnits());
}
});
nPanel.setContent(vLayout);
VerticalLayout nanoScrollLayout = new VerticalLayout();
nanoScrollLayout.addComponent(nPanel);
Button flashBtn = new Button("Flash Scrollbar");
flashBtn.addClickListener(new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
nPanel.flashScrollbar();
}
});
nanoScrollLayout.addComponent(flashBtn);
Button scrollTopBtn = new Button("Scroll To Top");
scrollTopBtn.addClickListener(new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
nPanel.flashScrollbar();
nPanel.scrollToTop();
}
});
nanoScrollLayout.addComponent(scrollTopBtn);
Button scrollBottomBtn = new Button("Scroll To Bottom");
scrollBottomBtn.addClickListener(new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
nPanel.flashScrollbar();
nPanel.scrollToBottom();
}
});
nanoScrollLayout.addComponent(scrollBottomBtn);
Button scrollToBtn = new Button("Scroll To 25");
scrollToBtn.addClickListener(new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
nPanel.flashScrollbar();
nPanel.scrollTo(scrollToTarget);
}
});
nanoScrollLayout.addComponent(scrollToBtn);
HorizontalLayout hLayout = new HorizontalLayout();
hLayout.addComponent(nanoScrollLayout);
Panel normalPanel = new Panel();
normalPanel.setWidth("400px");
normalPanel.setHeight("400px");
final VerticalLayout normalPanelContentLayout = new VerticalLayout();
normalPanelContentLayout.setMargin(true);
for(int i=0; i<50; ++i) {
Label l = new Label("This is a example of Normal Panel "+i+".");
l.setId("Label"+i);
if(i==25) scrollToTarget = l;
normalPanelContentLayout.addComponent(l);
}
normalPanel.setContent(normalPanelContentLayout);
hLayout.addComponent(normalPanel);
setContent(hLayout);
}
| protected void init(VaadinRequest request) {
final NanoScrollPanel nPanel = new NanoScrollPanel();
nPanel.setWidth("400px");
nPanel.setHeight("400px");
// flash user there are more content
nPanel.flashScrollbar();
nPanel.setPreventPageScrolling(true);
nPanel.addNanoScrollListener(new NanoScrollPanelListener() {
@Override
public void onScroll(NanoScrollEvent event) {
Notification.show("NanoScrollEvent catched",
"Event type is "+event.getType(),
Notification.Type.HUMANIZED_MESSAGE);
}
});
nPanel.addClickListener(new com.vaadin.event.MouseEvents.ClickListener() {
@Override
public void click(com.vaadin.event.MouseEvents.ClickEvent event) {
if(event.isDoubleClick()) {
Notification.show("NanoScrollPanel was double clicked", "Event",
Notification.Type.HUMANIZED_MESSAGE);
} else {
Notification.show("NanoScrollPanel was clicked", "Event",
Notification.Type.HUMANIZED_MESSAGE);
}
}
});
final VerticalLayout vLayout = new VerticalLayout();
for(int i=0; i<50; ++i) {
Label l = new Label("This is a example of NanoScrollPanel "+i+".");
l.setId("Label"+i);
if(i==25) scrollToTarget = l;
vLayout.addComponent(l);
}
Button btn = new Button("Add more");
vLayout.addComponent(btn);
btn.addClickListener(new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
vLayout.addComponent(new Label("This is more and more test."));
}
});
Button btn2 = new Button("Remove one");
vLayout.addComponent(btn2);
btn2.addClickListener(new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
if(vLayout.getComponentCount()>54)
vLayout.removeComponent(vLayout.getComponent(vLayout.getComponentCount()-1));
}
});
Button btn3 = new Button("Shrink");
vLayout.addComponent(btn3);
btn3.addClickListener(new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
nPanel.setHeight(nPanel.getHeight()*0.8f, nPanel.getHeightUnits());
}
});
Button btn4 = new Button("Expand");
vLayout.addComponent(btn4);
btn4.addClickListener(new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
nPanel.setHeight(nPanel.getHeight()/0.8f, nPanel.getHeightUnits());
}
});
nPanel.setContent(vLayout);
VerticalLayout nanoScrollLayout = new VerticalLayout();
nanoScrollLayout.addComponent(nPanel);
Button flashBtn = new Button("Flash Scrollbar");
flashBtn.addClickListener(new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
nPanel.flashScrollbar();
}
});
nanoScrollLayout.addComponent(flashBtn);
Button scrollTopBtn = new Button("Scroll To Top");
scrollTopBtn.addClickListener(new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
nPanel.flashScrollbar();
nPanel.scrollToTop();
}
});
nanoScrollLayout.addComponent(scrollTopBtn);
Button scrollBottomBtn = new Button("Scroll To Bottom");
scrollBottomBtn.addClickListener(new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
nPanel.flashScrollbar();
nPanel.scrollToBottom();
}
});
nanoScrollLayout.addComponent(scrollBottomBtn);
Button scrollToBtn = new Button("Scroll To 25");
scrollToBtn.addClickListener(new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
nPanel.flashScrollbar();
nPanel.scrollTo(scrollToTarget);
}
});
nanoScrollLayout.addComponent(scrollToBtn);
HorizontalLayout hLayout = new HorizontalLayout();
hLayout.addComponent(nanoScrollLayout);
Panel normalPanel = new Panel();
normalPanel.setWidth("400px");
normalPanel.setHeight("400px");
final VerticalLayout normalPanelContentLayout = new VerticalLayout();
normalPanelContentLayout.setMargin(true);
for(int i=0; i<50; ++i) {
normalPanelContentLayout.addComponent(new Label("This is a example of Normal Panel "+i+"."));
}
normalPanel.setContent(normalPanelContentLayout);
hLayout.addComponent(normalPanel);
setContent(hLayout);
}
|
diff --git a/src/SEG_Airport/src/Model/SaveToXMLFile.java b/src/SEG_Airport/src/Model/SaveToXMLFile.java
index fef31b4..0fd9dd6 100644
--- a/src/SEG_Airport/src/Model/SaveToXMLFile.java
+++ b/src/SEG_Airport/src/Model/SaveToXMLFile.java
@@ -1,305 +1,305 @@
package Model;
import java.io.*;
import java.util.ArrayList;
import javax.swing.JFileChooser;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import org.w3c.dom.*;
/**This class, when instantiated and passed an airport; takes the airports runways and their
* values and creates an XML file with them. It provides a JFileChooser window to select where
* to save the file and how to name it. It also works with obstacles.
* @author Oscar
*/
public class SaveToXMLFile {
private File file;
private DocumentBuilderFactory documentBuilderFactory;
private DocumentBuilder documentBuilder;
private Document document;
private Element rootElement;
/**
* Constructor for Airport
* @param airport The airport to save
* @throws Exception Relating to writing files or generating xml
* TODO: Throw only relevant exceptions.
*/
public SaveToXMLFile(Airport airport) throws Exception {
String root = "Airport";
this.createDocBuilderFactory(root);
//First element, the airport's name
Element airportName = document.createElement("Airport_Name");
airportName.appendChild(document.createTextNode(airport.getName()));
rootElement.appendChild(airportName);
this.addNodesAndElements(airport);
//Creating JFileChooser object and storing its return value
this.createFChooserAndStore();
}
/**
* Constructor for obstacle
* @param obstacle The obstacle to save
* @throws Exception Relating to reading files or generating xml
*/
public SaveToXMLFile(Obstacle obstacle) throws Exception{
String root = "Obstacle";
this.createDocBuilderFactory(root);
//First element, the obstacle's name
Element obstacleName = document.createElement("Obstacle_Name");
obstacleName.appendChild(document.createTextNode(obstacle.getName()));
rootElement.appendChild(obstacleName);
this.addNodesAndElementsObstacle(obstacle);
//Creating JFileChooser object and storing its return value
this.createFChooserAndStore();
}
/**
* Constructor for contacts
* @param contacts The list of contacts to save
* @throws Exception Relating to reading files or generating xml
*/
public SaveToXMLFile(ArrayList<Contact> contacts) throws Exception{
String root = "Contacts";
this.createDocBuilderFactory(root);
this.addNodesAndElementsContacts(contacts);
//Creating JFileChooser object and storing its return value
this.createFChooserAndStore();
}
/**
* Creates DocumentBuilderFactory using string for root element
* @param root The root element
* @throws ParserConfigurationException
*/
public void createDocBuilderFactory(String root) throws ParserConfigurationException{
documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilder = documentBuilderFactory.newDocumentBuilder();
document = documentBuilder.newDocument();
rootElement = document.createElement(root);
document.appendChild(rootElement);
}
/**
* Adds the nodes and elements to the xml
* @param contacts The list of contacts to be saved
*/
public void addNodesAndElementsContacts(ArrayList<Contact> contactList) {
//int numberOfRunways = airport.runways().size(); //number of physical runways
//for (PhysicalRunway runway: airport.runways()) {
/*Element physicalRunway = document.createElement("PhysicalRunway");
String namePhysicalRunwayString = runway.getId();
// physicalRunway.appendChild(document.createTextNode(nam));
Element physicalRunwayName = document.createElement("Name");
physicalRunwayName.appendChild(document.createTextNode(namePhysicalRunwayString));
physicalRunway.appendChild(physicalRunwayName);*/
for (int i = 0; i < contactList.size(); i++) { // looping through each contact
Contact thisContact = contactList.get(i);// grabbing a contact
// Creating contact element and appending to root element
Element element = document.createElement("Contact");
// Creating each of the contact's elements and appending to the contact element
Element firstName = document.createElement("First_Name");
firstName.appendChild(document.createTextNode(thisContact.getFirstName()));
element.appendChild(firstName);
Element lastName = document.createElement("Last_Name");
lastName.appendChild(document.createTextNode(thisContact.getLastName()));
element.appendChild(lastName);
Element email = document.createElement("Email_Address");
email.appendChild(document.createTextNode(thisContact.getEmail()));
element.appendChild(email);
rootElement.appendChild(element);
// rootElement.appendChild(em);
}
}
/**
* Adds the nodes and elements to the xml
* @param airport The airport to be saved
*/
public void addNodesAndElements(Airport airport) {
//int numberOfRunways = airport.runways().size(); //number of physical runways
for (PhysicalRunway runway: airport.getPhysicalRunways()) { // looping through all physical runways
Element physicalRunway = document.createElement("PhysicalRunway");
String namePhysicalRunwayString = runway.getId();
// physicalRunway.appendChild(document.createTextNode(nam));
Element physicalRunwayName = document.createElement("Name");
physicalRunwayName.appendChild(document.createTextNode(namePhysicalRunwayString));
physicalRunway.appendChild(physicalRunwayName);
Element resa = document.createElement("RESA");
- String resaString = Double.toString(runway.getRESA(0));
+ String resaString = Double.toString(runway.getResa()/*.getRESA()*/);
resa.appendChild(document.createTextNode(resaString));
physicalRunway.appendChild(resa);
Element stopway = document.createElement("Stopway");
- String stopwayString = Double.toString(runway.getStopway(0));
+ String stopwayString = Double.toString(runway.getStopway());
stopway.appendChild(document.createTextNode(stopwayString));
physicalRunway.appendChild(stopway);
Element blastAllowance = document.createElement("Blast_Allowance");
- String blastString = Double.toString(runway.getBlastAllowance(0));
+ String blastString = Double.toString(runway.getBlastAllowance());
blastAllowance.appendChild(document.createTextNode(blastString));
physicalRunway.appendChild(blastAllowance);
Element runwayStripWidth = document.createElement("Runway_Strip_Width");
String runwayWidthString = Double.toString(runway.getRunwayStripWidth());
runwayStripWidth.appendChild(document.createTextNode(runwayWidthString));
physicalRunway.appendChild(runwayStripWidth);
Element clearAndGradedWidth = document.createElement("Clear_And_Graded_Width");
String clearWidthString = Double.toString(runway.getClearedAndGradedWidth());
clearAndGradedWidth.appendChild(document.createTextNode(clearWidthString));
physicalRunway.appendChild(clearAndGradedWidth);
Element distanceAwayFromThreshold = document.createElement("Distance_Away_From_Threshold");
String distanceFromThresString = Double.toString(runway.getDistanceAwayFromThreshold());
distanceAwayFromThreshold.appendChild(document.createTextNode(distanceFromThresString));
physicalRunway.appendChild(distanceAwayFromThreshold);
Element distanceAwayFromCenterline = document.createElement("Distance_Away_From_Centerline");
String distanceFromCenterString = Double.toString(runway.getDistanceAwayFromCenterLine());
distanceAwayFromCenterline.appendChild(document.createTextNode(distanceFromCenterString));
physicalRunway.appendChild(distanceAwayFromCenterline);
Element angleOfSlope = document.createElement("Angle_Of_Slope");
- String angleString = Double.toString(runway.getAngleOfSlope(0));
+ String angleString = Double.toString(runway.getAngleOfSlope());
angleOfSlope.appendChild(document.createTextNode(angleString));
physicalRunway.appendChild(angleOfSlope);
for (int i = 0; i < 2; i++) { // looping through each actual runway (2)
Runway runwayObject = runway.getRunway(i);// getting a runway
// Creating runway element and appending to root element
Element element = document.createElement("Runway");
// Creating each of the runway's elements and appending to the runway element
Element name = document.createElement("RunwayName");
name.appendChild(document.createTextNode(runwayObject.getName()));
element.appendChild(name);
Element tora = document.createElement("TORA");
String toraString = Double.toString(runwayObject.getTORA(1));// getting the tora value that can be modified
tora.appendChild(document.createTextNode(toraString));
element.appendChild(tora);
Element asda = document.createElement("ASDA");
String asdaString = Double.toString(runwayObject.getASDA(1));
asda.appendChild(document.createTextNode(asdaString));
element.appendChild(asda);
Element toda = document.createElement("TODA");
String todaString = Double.toString(runwayObject.getTODA(1));
toda.appendChild(document.createTextNode(todaString));
element.appendChild(toda);
Element lda = document.createElement("LDA");
String ldaString = Double.toString(runwayObject.getLDA(1));
lda.appendChild(document.createTextNode(ldaString));
element.appendChild(lda);
Element displacedThreshold = document
.createElement("DisplacedThreshold");
String displacedThresholdString = Double.toString(runwayObject.getDisplacedThreshold(1));
displacedThreshold.appendChild(document.createTextNode(displacedThresholdString));
element.appendChild(displacedThreshold);
physicalRunway.appendChild(element);
// rootElement.appendChild(em);
}
rootElement.appendChild(physicalRunway);
}
}
/**
* Adds the nodes and elements to the xml
* @param obstacle The obstacle to be saved
*/
public void addNodesAndElementsObstacle(Obstacle obstacle) {
Element height = document.createElement("Height");
String heightString = Double.toString(obstacle.getHeight());
height.appendChild(document.createTextNode(heightString));
rootElement.appendChild(height);
Element width = document.createElement("Width");
String widthString = Double.toString(obstacle.getWidth());
width.appendChild(document.createTextNode(widthString));
rootElement.appendChild(width);
Element length = document.createElement("Length");
String lengthString = Double.toString(obstacle.getLength());
length.appendChild(document.createTextNode(lengthString));
rootElement.appendChild(length);
}
/**
* Creates File chooser and saves XML to given file
* @throws IOException
* @throws TransformerException
*/
public void createFChooserAndStore() throws IOException, TransformerException {
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showSaveDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
file = fileChooser.getSelectedFile();
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StreamResult result = new StreamResult(file);
file.createNewFile();
DOMSource source = new DOMSource(document);
transformer.transform(source, result);
} else {
System.out.println("Save command cancelled by user.");
}
}
}
| false | true | public void addNodesAndElements(Airport airport) {
//int numberOfRunways = airport.runways().size(); //number of physical runways
for (PhysicalRunway runway: airport.getPhysicalRunways()) { // looping through all physical runways
Element physicalRunway = document.createElement("PhysicalRunway");
String namePhysicalRunwayString = runway.getId();
// physicalRunway.appendChild(document.createTextNode(nam));
Element physicalRunwayName = document.createElement("Name");
physicalRunwayName.appendChild(document.createTextNode(namePhysicalRunwayString));
physicalRunway.appendChild(physicalRunwayName);
Element resa = document.createElement("RESA");
String resaString = Double.toString(runway.getRESA(0));
resa.appendChild(document.createTextNode(resaString));
physicalRunway.appendChild(resa);
Element stopway = document.createElement("Stopway");
String stopwayString = Double.toString(runway.getStopway(0));
stopway.appendChild(document.createTextNode(stopwayString));
physicalRunway.appendChild(stopway);
Element blastAllowance = document.createElement("Blast_Allowance");
String blastString = Double.toString(runway.getBlastAllowance(0));
blastAllowance.appendChild(document.createTextNode(blastString));
physicalRunway.appendChild(blastAllowance);
Element runwayStripWidth = document.createElement("Runway_Strip_Width");
String runwayWidthString = Double.toString(runway.getRunwayStripWidth());
runwayStripWidth.appendChild(document.createTextNode(runwayWidthString));
physicalRunway.appendChild(runwayStripWidth);
Element clearAndGradedWidth = document.createElement("Clear_And_Graded_Width");
String clearWidthString = Double.toString(runway.getClearedAndGradedWidth());
clearAndGradedWidth.appendChild(document.createTextNode(clearWidthString));
physicalRunway.appendChild(clearAndGradedWidth);
Element distanceAwayFromThreshold = document.createElement("Distance_Away_From_Threshold");
String distanceFromThresString = Double.toString(runway.getDistanceAwayFromThreshold());
distanceAwayFromThreshold.appendChild(document.createTextNode(distanceFromThresString));
physicalRunway.appendChild(distanceAwayFromThreshold);
Element distanceAwayFromCenterline = document.createElement("Distance_Away_From_Centerline");
String distanceFromCenterString = Double.toString(runway.getDistanceAwayFromCenterLine());
distanceAwayFromCenterline.appendChild(document.createTextNode(distanceFromCenterString));
physicalRunway.appendChild(distanceAwayFromCenterline);
Element angleOfSlope = document.createElement("Angle_Of_Slope");
String angleString = Double.toString(runway.getAngleOfSlope(0));
angleOfSlope.appendChild(document.createTextNode(angleString));
physicalRunway.appendChild(angleOfSlope);
for (int i = 0; i < 2; i++) { // looping through each actual runway (2)
Runway runwayObject = runway.getRunway(i);// getting a runway
// Creating runway element and appending to root element
Element element = document.createElement("Runway");
// Creating each of the runway's elements and appending to the runway element
Element name = document.createElement("RunwayName");
name.appendChild(document.createTextNode(runwayObject.getName()));
element.appendChild(name);
Element tora = document.createElement("TORA");
String toraString = Double.toString(runwayObject.getTORA(1));// getting the tora value that can be modified
tora.appendChild(document.createTextNode(toraString));
element.appendChild(tora);
Element asda = document.createElement("ASDA");
String asdaString = Double.toString(runwayObject.getASDA(1));
asda.appendChild(document.createTextNode(asdaString));
element.appendChild(asda);
Element toda = document.createElement("TODA");
String todaString = Double.toString(runwayObject.getTODA(1));
toda.appendChild(document.createTextNode(todaString));
element.appendChild(toda);
Element lda = document.createElement("LDA");
String ldaString = Double.toString(runwayObject.getLDA(1));
lda.appendChild(document.createTextNode(ldaString));
element.appendChild(lda);
Element displacedThreshold = document
.createElement("DisplacedThreshold");
String displacedThresholdString = Double.toString(runwayObject.getDisplacedThreshold(1));
displacedThreshold.appendChild(document.createTextNode(displacedThresholdString));
element.appendChild(displacedThreshold);
physicalRunway.appendChild(element);
// rootElement.appendChild(em);
}
rootElement.appendChild(physicalRunway);
}
}
| public void addNodesAndElements(Airport airport) {
//int numberOfRunways = airport.runways().size(); //number of physical runways
for (PhysicalRunway runway: airport.getPhysicalRunways()) { // looping through all physical runways
Element physicalRunway = document.createElement("PhysicalRunway");
String namePhysicalRunwayString = runway.getId();
// physicalRunway.appendChild(document.createTextNode(nam));
Element physicalRunwayName = document.createElement("Name");
physicalRunwayName.appendChild(document.createTextNode(namePhysicalRunwayString));
physicalRunway.appendChild(physicalRunwayName);
Element resa = document.createElement("RESA");
String resaString = Double.toString(runway.getResa()/*.getRESA()*/);
resa.appendChild(document.createTextNode(resaString));
physicalRunway.appendChild(resa);
Element stopway = document.createElement("Stopway");
String stopwayString = Double.toString(runway.getStopway());
stopway.appendChild(document.createTextNode(stopwayString));
physicalRunway.appendChild(stopway);
Element blastAllowance = document.createElement("Blast_Allowance");
String blastString = Double.toString(runway.getBlastAllowance());
blastAllowance.appendChild(document.createTextNode(blastString));
physicalRunway.appendChild(blastAllowance);
Element runwayStripWidth = document.createElement("Runway_Strip_Width");
String runwayWidthString = Double.toString(runway.getRunwayStripWidth());
runwayStripWidth.appendChild(document.createTextNode(runwayWidthString));
physicalRunway.appendChild(runwayStripWidth);
Element clearAndGradedWidth = document.createElement("Clear_And_Graded_Width");
String clearWidthString = Double.toString(runway.getClearedAndGradedWidth());
clearAndGradedWidth.appendChild(document.createTextNode(clearWidthString));
physicalRunway.appendChild(clearAndGradedWidth);
Element distanceAwayFromThreshold = document.createElement("Distance_Away_From_Threshold");
String distanceFromThresString = Double.toString(runway.getDistanceAwayFromThreshold());
distanceAwayFromThreshold.appendChild(document.createTextNode(distanceFromThresString));
physicalRunway.appendChild(distanceAwayFromThreshold);
Element distanceAwayFromCenterline = document.createElement("Distance_Away_From_Centerline");
String distanceFromCenterString = Double.toString(runway.getDistanceAwayFromCenterLine());
distanceAwayFromCenterline.appendChild(document.createTextNode(distanceFromCenterString));
physicalRunway.appendChild(distanceAwayFromCenterline);
Element angleOfSlope = document.createElement("Angle_Of_Slope");
String angleString = Double.toString(runway.getAngleOfSlope());
angleOfSlope.appendChild(document.createTextNode(angleString));
physicalRunway.appendChild(angleOfSlope);
for (int i = 0; i < 2; i++) { // looping through each actual runway (2)
Runway runwayObject = runway.getRunway(i);// getting a runway
// Creating runway element and appending to root element
Element element = document.createElement("Runway");
// Creating each of the runway's elements and appending to the runway element
Element name = document.createElement("RunwayName");
name.appendChild(document.createTextNode(runwayObject.getName()));
element.appendChild(name);
Element tora = document.createElement("TORA");
String toraString = Double.toString(runwayObject.getTORA(1));// getting the tora value that can be modified
tora.appendChild(document.createTextNode(toraString));
element.appendChild(tora);
Element asda = document.createElement("ASDA");
String asdaString = Double.toString(runwayObject.getASDA(1));
asda.appendChild(document.createTextNode(asdaString));
element.appendChild(asda);
Element toda = document.createElement("TODA");
String todaString = Double.toString(runwayObject.getTODA(1));
toda.appendChild(document.createTextNode(todaString));
element.appendChild(toda);
Element lda = document.createElement("LDA");
String ldaString = Double.toString(runwayObject.getLDA(1));
lda.appendChild(document.createTextNode(ldaString));
element.appendChild(lda);
Element displacedThreshold = document
.createElement("DisplacedThreshold");
String displacedThresholdString = Double.toString(runwayObject.getDisplacedThreshold(1));
displacedThreshold.appendChild(document.createTextNode(displacedThresholdString));
element.appendChild(displacedThreshold);
physicalRunway.appendChild(element);
// rootElement.appendChild(em);
}
rootElement.appendChild(physicalRunway);
}
}
|
diff --git a/src/edu/cmu/cs/diamond/opendiamond/ConnectionSet.java b/src/edu/cmu/cs/diamond/opendiamond/ConnectionSet.java
index 4bf392b..a3e42d2 100644
--- a/src/edu/cmu/cs/diamond/opendiamond/ConnectionSet.java
+++ b/src/edu/cmu/cs/diamond/opendiamond/ConnectionSet.java
@@ -1,134 +1,140 @@
/*
* The OpenDiamond Platform for Interactive Search
*
* Copyright (c) 2009 Carnegie Mellon University
* All rights reserved.
*
* This software is distributed under the terms of the Eclipse Public
* License, Version 1.0 which can be found in the file named LICENSE.
* ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS SOFTWARE CONSTITUTES
* RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT
*/
package edu.cmu.cs.diamond.opendiamond;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.*;
class ConnectionSet {
private final Set<Connection> connections;
private final BlastQueue blastQueue = new BlastQueue(20);
private final ExecutorService executor;
private final List<Future<?>> blastFutures = new ArrayList<Future<?>>();
private final Future<?> connectionSetFuture;
private volatile boolean closing;
ConnectionSet(ExecutorService executor, Set<Connection> connections) {
this.executor = executor;
this.connections = new HashSet<Connection>(connections);
// create tasks for getting blast messages
final CompletionService<Object> blastTasks = new ExecutorCompletionService<Object>(
executor);
for (Connection c : connections) {
blastFutures.add(blastTasks.submit(new BlastGetter(c, c
.getHostname(), blastQueue, 10)));
}
final int tasksCount = blastFutures.size();
// wait for things to finish
connectionSetFuture = executor.submit(new Callable<Object>() {
public Object call() {
try {
for (int i = 0; i < tasksCount; i++) {
blastTasks.take().get();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (ExecutionException e) {
cancelAllBlastTasks();
Throwable cause = e.getCause();
- if ((cause instanceof IOException) && !closing) {
- IOException e2 = (IOException) cause;
+ if (!closing) {
+ IOException e2;
+ if (cause instanceof IOException) {
+ e2 = (IOException) cause;
+ } else {
+ e2 = new IOException("couldn't read blast channel",
+ cause);
+ }
// inject into blast queue, only if we are not closing
try {
blastQueue.put(new BlastChannelObject(null, null,
e2));
} catch (InterruptedException e1) {
Thread.currentThread().interrupt();
}
}
} finally {
// all tasks done, shut down queue
blastQueue.shutdown();
}
return null;
}
});
}
public void close() throws InterruptedException {
closing = true;
// cancel all blast tasks
cancelAllBlastTasks();
// close all connections
for (Connection c : connections) {
c.close();
}
// wait for cancellations and shutdown
try {
connectionSetFuture.get();
} catch (ExecutionException e) {
// ignore
}
}
private void cancelAllBlastTasks() {
for (Future<?> f : blastFutures) {
f.cancel(true);
}
}
public BlastChannelObject getNextBlastChannelObject()
throws InterruptedException {
return blastQueue.take();
}
public <T> CompletionService<T> runOnAllServers(ConnectionFunction<T> cf) {
CompletionService<T> cs = new ExecutorCompletionService<T>(executor);
for (Connection c : connections) {
cs.submit(cf.createCallable(c));
}
return cs;
}
public CompletionService<MiniRPCReply> sendToAllControlChannels(
final int cmd, final byte[] data) {
return runOnAllServers(new ConnectionFunction<MiniRPCReply>() {
public Callable<MiniRPCReply> createCallable(Connection c) {
return new RPC(c, c.getHostname(), cmd, data);
}
});
}
public int size() {
return connections.size();
}
}
| true | true | ConnectionSet(ExecutorService executor, Set<Connection> connections) {
this.executor = executor;
this.connections = new HashSet<Connection>(connections);
// create tasks for getting blast messages
final CompletionService<Object> blastTasks = new ExecutorCompletionService<Object>(
executor);
for (Connection c : connections) {
blastFutures.add(blastTasks.submit(new BlastGetter(c, c
.getHostname(), blastQueue, 10)));
}
final int tasksCount = blastFutures.size();
// wait for things to finish
connectionSetFuture = executor.submit(new Callable<Object>() {
public Object call() {
try {
for (int i = 0; i < tasksCount; i++) {
blastTasks.take().get();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (ExecutionException e) {
cancelAllBlastTasks();
Throwable cause = e.getCause();
if ((cause instanceof IOException) && !closing) {
IOException e2 = (IOException) cause;
// inject into blast queue, only if we are not closing
try {
blastQueue.put(new BlastChannelObject(null, null,
e2));
} catch (InterruptedException e1) {
Thread.currentThread().interrupt();
}
}
} finally {
// all tasks done, shut down queue
blastQueue.shutdown();
}
return null;
}
});
}
| ConnectionSet(ExecutorService executor, Set<Connection> connections) {
this.executor = executor;
this.connections = new HashSet<Connection>(connections);
// create tasks for getting blast messages
final CompletionService<Object> blastTasks = new ExecutorCompletionService<Object>(
executor);
for (Connection c : connections) {
blastFutures.add(blastTasks.submit(new BlastGetter(c, c
.getHostname(), blastQueue, 10)));
}
final int tasksCount = blastFutures.size();
// wait for things to finish
connectionSetFuture = executor.submit(new Callable<Object>() {
public Object call() {
try {
for (int i = 0; i < tasksCount; i++) {
blastTasks.take().get();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (ExecutionException e) {
cancelAllBlastTasks();
Throwable cause = e.getCause();
if (!closing) {
IOException e2;
if (cause instanceof IOException) {
e2 = (IOException) cause;
} else {
e2 = new IOException("couldn't read blast channel",
cause);
}
// inject into blast queue, only if we are not closing
try {
blastQueue.put(new BlastChannelObject(null, null,
e2));
} catch (InterruptedException e1) {
Thread.currentThread().interrupt();
}
}
} finally {
// all tasks done, shut down queue
blastQueue.shutdown();
}
return null;
}
});
}
|
diff --git a/bundles/org.eclipse.equinox.frameworkadmin/src/org/eclipse/equinox/internal/frameworkadmin/utils/Utils.java b/bundles/org.eclipse.equinox.frameworkadmin/src/org/eclipse/equinox/internal/frameworkadmin/utils/Utils.java
index 54bf68cec..a498dcbf5 100644
--- a/bundles/org.eclipse.equinox.frameworkadmin/src/org/eclipse/equinox/internal/frameworkadmin/utils/Utils.java
+++ b/bundles/org.eclipse.equinox.frameworkadmin/src/org/eclipse/equinox/internal/frameworkadmin/utils/Utils.java
@@ -1,571 +1,568 @@
/*******************************************************************************
* Copyright (c) 2007 IBM Corporation and others. All rights reserved. This
* program and the accompanying materials are made available under the terms of
* the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors: IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.equinox.internal.frameworkadmin.utils;
import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.jar.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.eclipse.equinox.frameworkadmin.BundleInfo;
public class Utils {
private final static String PATH_SEP = "/";
private static final String[] EMPTY_STRING_ARRAY = new String[] {};
/**
* Overwrite all properties of from to the properties of to. Return the result of to.
*
* @param to Properties whose keys and values of other Properties will be appended to.
* @param from Properties whose keys and values will be set to the other properties.
* @return Properties as a result of this method.
*/
public static Properties appendProperties(Properties to, Properties from) {
if (from != null) {
if (to == null)
to = new Properties();
// printoutProperties(System.out, "to", to);
// printoutProperties(System.out, "from", from);
for (Enumeration enumeration = from.keys(); enumeration.hasMoreElements();) {
String key = (String) enumeration.nextElement();
to.setProperty(key, from.getProperty(key));
}
}
// printoutProperties(System.out, "to", to);
return to;
}
//Return a dictionary representing a manifest. The data may result from plugin.xml conversion
private static Dictionary basicLoadManifest(File bundleLocation) {
InputStream manifestStream = null;
ZipFile jarFile = null;
try {
String fileExtention = bundleLocation.getName();
fileExtention = fileExtention.substring(fileExtention.lastIndexOf('.') + 1);
if ("jar".equalsIgnoreCase(fileExtention) && bundleLocation.isFile()) { //$NON-NLS-1$
jarFile = new ZipFile(bundleLocation, ZipFile.OPEN_READ);
ZipEntry manifestEntry = jarFile.getEntry(JarFile.MANIFEST_NAME);
if (manifestEntry != null) {
manifestStream = jarFile.getInputStream(manifestEntry);
}
} else {
manifestStream = new BufferedInputStream(new FileInputStream(new File(bundleLocation, JarFile.MANIFEST_NAME)));
}
} catch (IOException e) {
//ignore
}
Dictionary manifest = null;
//It is not a manifest, but a plugin or a fragment
if (manifestStream != null) {
try {
Manifest m = new Manifest(manifestStream);
manifest = manifestToProperties(m.getMainAttributes());
} catch (IOException ioe) {
return null;
} finally {
try {
manifestStream.close();
} catch (IOException e1) {
//Ignore
}
try {
if (jarFile != null)
jarFile.close();
} catch (IOException e2) {
//Ignore
}
}
}
return manifest;
}
public static void checkAbsoluteDir(File file, String dirName) throws IllegalArgumentException {
if (file == null)
throw new IllegalArgumentException(dirName + " is null");
if (!file.isAbsolute())
throw new IllegalArgumentException(dirName + " is not absolute path. file=" + file.getAbsolutePath());
if (!file.isDirectory())
throw new IllegalArgumentException(dirName + " is not directory. file=" + file.getAbsolutePath());
}
public static void checkAbsoluteFile(File file, String dirName) {//throws ManipulatorException {
if (file == null)
throw new IllegalArgumentException(dirName + " is null");
if (!file.isAbsolute())
throw new IllegalArgumentException(dirName + " is not absolute path. file=" + file.getAbsolutePath());
if (file.isDirectory())
throw new IllegalArgumentException(dirName + " is not file but directory");
}
public static URL checkFullUrl(URL url, String urlName) throws IllegalArgumentException {//throws ManipulatorException {
if (url == null)
throw new IllegalArgumentException(urlName + " is null");
if (!url.getProtocol().endsWith("file"))
return url;
File file = new File(url.getFile());
if (!file.isAbsolute())
throw new IllegalArgumentException(urlName + "(" + url + ") does not have absolute path");
if (file.getAbsolutePath().startsWith(PATH_SEP))
return url;
try {
return getUrl("file", null, PATH_SEP + file.getAbsolutePath());
} catch (MalformedURLException e) {
throw new IllegalArgumentException(urlName + "(" + "file:" + PATH_SEP + file.getAbsolutePath() + ") is not fully quallified");
}
}
public static void createParentDir(File file) throws IOException {
File parent = file.getParentFile();
if (parent == null)
return;
parent.mkdirs();
}
/**
* Deletes the given file recursively, adding failure info to
* the provided status object. The filePath is passed as a parameter
* to optimize java.io.File object creation.
*/
// Implementation taken from the Eclipse File sytem bundle class LocalFile.
// TODO consider putting back the progress and cancelation support.
private static boolean internalDelete(File target, String pathToDelete) {
//first try to delete - this should succeed for files and symbolic links to directories
if (target.delete() || !target.exists())
return true;
if (target.isDirectory()) {
String[] list = target.list();
if (list == null)
list = EMPTY_STRING_ARRAY;
int parentLength = pathToDelete.length();
boolean failedRecursive = false;
for (int i = 0, imax = list.length; i < imax; i++) {
//optimized creation of child path object
StringBuffer childBuffer = new StringBuffer(parentLength + list[i].length() + 1);
childBuffer.append(pathToDelete);
childBuffer.append(File.separatorChar);
childBuffer.append(list[i]);
String childName = childBuffer.toString();
// try best effort on all children so put logical OR at end
failedRecursive = !internalDelete(new java.io.File(childName), childName) || failedRecursive;
}
try {
// don't try to delete the root if one of the children failed
if (!failedRecursive && target.delete())
return true;
} catch (Exception e) {
// we caught a runtime exception so log it
return false;
}
}
// message = NLS.bind(Messages.couldnotDelete, target.getAbsolutePath());
return false;
}
public static void deleteDir(File target) throws IOException {
internalDelete(target, target.getAbsolutePath());
throw new IOException("Fail to delete Dir(" + target.getAbsolutePath() + ")");
}
/**
* First, it replaces File.seperator of relativePath to "/".
* If relativePath is in URL format, return its URL.
* Otherwise, create absolute URL based on the baseUrl.
*
* @param relativePath
* @param baseUrl
* @return URL
* @throws MalformedURLException
*/
public static URL formatUrl(String relativePath, URL baseUrl) throws MalformedURLException {//throws ManipulatorException {
relativePath = Utils.replaceAll(relativePath, File.separator, "/");
URL url = null;
try {
url = new URL(relativePath);
if (url.getProtocol().equals("file"))
if (!(new File(url.getFile())).isAbsolute())
url = getUrlInFull(relativePath, baseUrl);
return url;
} catch (MalformedURLException e) {
return getUrlInFull(relativePath, baseUrl);
}
}
public static BundleInfo[] getBundleInfosFromList(List list) {
if (list == null)
return new BundleInfo[0];
BundleInfo[] ret = new BundleInfo[list.size()];
list.toArray(ret);
return ret;
}
public static String[] getClauses(String header) {
StringTokenizer token = new StringTokenizer(header, ",");
List list = new LinkedList();
while (token.hasMoreTokens()) {
list.add(token.nextToken());
}
String[] ret = new String[list.size()];
list.toArray(ret);
return ret;
}
public static String[] getClausesManifestMainAttributes(String location, String name) {
return getClauses(getManifestMainAttributes(location, name));
}
public static String getManifestMainAttributes(String location, String name) {
Dictionary manifest = Utils.getOSGiManifest(location);
if (manifest == null)
throw new RuntimeException("Unable to locate bundle manifest: " + location);
return (String) manifest.get(name);
}
public static Dictionary getOSGiManifest(String location) {
if (location.startsWith("file:") && !location.endsWith(".jar"))
return basicLoadManifest(new File(location.substring("file:".length())));
try {
URL url = new URL("jar:" + location + "!/");
JarURLConnection jarConnection = (JarURLConnection) url.openConnection();
Manifest manifest = jarConnection.getManifest();
Attributes attributes = manifest.getMainAttributes();
// Set set = attributes.keySet();
Hashtable table = new Hashtable();
for (java.util.Iterator ite = attributes.keySet().iterator(); ite.hasNext();) {
// Object obj = ite.next();
//System.out.println(obj.getClass().getName());
String key = (String) ite.next().toString();
// While table contains non OSGiManifest, it doesn't matter.
table.put(key, attributes.getValue(key));
// System.out.println("key=" + key + " value=" + value);
}
// System.out.println("");
try {
jarConnection.getJarFile().close();
} catch (IOException e) {
//Ignore
}
return table;
- } catch (MalformedURLException e1) {
- // TODO log
- System.err.println("location=" + location);
- e1.printStackTrace();
} catch (IOException e) {
- // TODO log
- System.err.println("location=" + location);
- e.printStackTrace();
+ if (System.getProperty("osgi.debug") != null) {
+ System.err.println("location=" + location);
+ e.printStackTrace();
+ }
}
return null;
}
public static String getPathFromClause(String clause) {
if (clause == null)
return null;
if (clause.indexOf(";") != -1)
clause = clause.substring(0, clause.indexOf(";"));
return clause.trim();
}
public static String getRelativePath(File target, File from) {
String targetPath = Utils.replaceAll(target.getAbsolutePath(), File.separator, PATH_SEP);
String fromPath = Utils.replaceAll(from.getAbsolutePath(), File.separator, PATH_SEP);
String[] targetTokens = Utils.getTokens(targetPath, PATH_SEP);
String[] fromTokens = Utils.getTokens(fromPath, PATH_SEP);
int index = -1;
for (int i = 0; i < fromTokens.length; i++)
if (fromTokens[i].equals(targetTokens[i]))
index = i;
else
break;
StringBuffer sb = new StringBuffer();
for (int i = index + 1; i < fromTokens.length; i++)
sb.append(".." + PATH_SEP);
for (int i = index + 1; i < targetTokens.length; i++)
if (i != targetTokens.length - 1)
sb.append(targetTokens[i] + PATH_SEP);
else
sb.append(targetTokens[i]);
return sb.toString();
}
public static String getRelativePath(URL target, URL from) throws IllegalArgumentException {
if (!target.getProtocol().equals(from.getProtocol()))
throw new IllegalArgumentException("Protocols of target(=" + target + ") and from(=" + from + ") does NOT equal");
if (target.getHost() != null && target.getHost().length() != 0) {
//System.out.println("target.getHost()=" + target.getHost());
if (from.getHost() != null && from.getHost().length() != 0) {
if (!target.getHost().equals(from.getHost()))
throw new IllegalArgumentException("Hosts of target(=" + target + ") and from(=" + from + ") does NOT equal");
if (target.getPort() != (from.getPort()))
throw new IllegalArgumentException("Ports of target(=" + target + ") and from(=" + from + ") does NOT equal");
} else
throw new IllegalArgumentException("While Host of target(=" + target + ") is set, Host of from is null.target.getHost()=" + target.getHost());
} else if (from.getHost() != null && from.getHost().length() != 0)
throw new IllegalArgumentException("While Host of from(=" + from + ") is set, Host of target is null");
String targetPath = target.getFile();
String fromPath = from.getFile();
String[] targetTokens = Utils.getTokens(targetPath, PATH_SEP);
String[] fromTokens = Utils.getTokens(fromPath, PATH_SEP);
int index = -1;
for (int i = 0; i < fromTokens.length; i++)
if (fromTokens[i].equals(targetTokens[i]))
index = i;
else
break;
StringBuffer sb = new StringBuffer();
for (int i = index + 1; i < fromTokens.length; i++)
sb.append(".." + PATH_SEP);
for (int i = index + 1; i < targetTokens.length; i++)
if (i != targetTokens.length - 1)
sb.append(targetTokens[i] + PATH_SEP);
else
sb.append(targetTokens[i]);
return sb.toString();
}
// public static URL getAbsoluteUrl(String relativePath, URL baseUrl) throws FwLauncherException {
// relativePath = Utils.replaceAll(relativePath, File.separator, "/");
// try {
// return new URL(baseUrl, relativePath);
// } catch (MalformedURLException e) {
// throw new FwLauncherException("Absolute URL cannot be created. \nrelativePath=" + relativePath + ",baseUrl=" + baseUrl, e, FwLauncherException.URL_FORMAT_ERROR);
// }
// }
// public static void setProperties(Properties to, Properties from, String key) {
// if (from != null) {
// String value = from.getProperty(key);
// if (value != null) {
// if (to != null)
// to = new Properties();
// to.setProperty(key, value);
// }
// }
// }
// public static int getIntProperties(Properties props, String key) {//throws ManipulatorException {
// if (props == null)
// throw new IllegalArgumentException("props == null");
// String value = null;
// try {
// value = props.getProperty(key);
// return Integer.parseInt(value);
// } catch (NumberFormatException nfe) {
// throw new ManipulatorException("key=" + key + ",value=" + value, nfe, ManipulatorException.OTHERS);
// }
// }
/**
* This method will be called for create a backup file.
*
* @param file target file
* @return File backup file whose filename consists of "hogehoge.yyyyMMddHHmmss.ext" or
* "hogehoge.yyyyMMddHHmmss".
*/
public static File getSimpleDataFormattedFile(File file) {
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String date = df.format(new Date());
String filename = file.getName();
int index = filename.lastIndexOf(".");
if (index != -1)
filename = filename.substring(0, index) + "." + date + "." + filename.substring(index + 1);
else
filename = filename + "." + date;
File dest = new File(file.getParentFile(), filename);
return dest;
}
public static String[] getTokens(String msg, String delim) {
return getTokens(msg, delim, false);
}
public static String[] getTokens(String msg, String delim, boolean returnDelims) {
StringTokenizer targetST = new StringTokenizer(msg, delim, returnDelims);
String[] tokens = new String[targetST.countTokens()];
ArrayList list = new ArrayList(targetST.countTokens());
while (targetST.hasMoreTokens()) {
list.add(targetST.nextToken());
}
list.toArray(tokens);
return tokens;
}
public static URL getUrl(String protocol, String host, String file) throws MalformedURLException {// throws ManipulatorException {
file = Utils.replaceAll(file, File.separator, "/");
return new URL(protocol, host, file);
}
public static URL getUrlInFull(String path, URL from) throws MalformedURLException {//throws ManipulatorException {
Utils.checkFullUrl(from, "from");
path = Utils.replaceAll(path, File.separator, "/");
//System.out.println("from.toExternalForm()=" + from.toExternalForm());
String fromSt = Utils.removeLastCh(from.toExternalForm(), '/');
//System.out.println("fromSt=" + fromSt);
if (path.startsWith("/")) {
String fileSt = from.getFile();
return new URL(fromSt.substring(0, fromSt.lastIndexOf(fileSt) - 1) + path);
}
return new URL(fromSt + "/" + path);
}
private static Properties manifestToProperties(Attributes d) {
Iterator iter = d.keySet().iterator();
Properties result = new Properties();
while (iter.hasNext()) {
Attributes.Name key = (Attributes.Name) iter.next();
result.put(key.toString(), d.get(key));
}
return result;
}
/**
* Just used for debug.
*
* @param ps printstream
* @param name name of properties
* @param props properties whose keys and values will be printed out.
*/
public static void printoutProperties(PrintStream ps, String name, Properties props) {
if (props == null || props.size() == 0) {
ps.println("Props(" + name + ") is empty");
return;
}
ps.println("Props(" + name + ")=");
for (Enumeration enumeration = props.keys(); enumeration.hasMoreElements();) {
String key = (String) enumeration.nextElement();
ps.print("\tkey=" + key);
ps.println("\tvalue=" + props.getProperty(key));
}
}
public static String removeLastCh(String target, char ch) {
while (target.charAt(target.length() - 1) == ch) {
target = target.substring(0, target.length() - 1);
}
return target;
}
public static String replaceAll(String st, String oldSt, String newSt) {
if (oldSt.equals(newSt))
return st;
int index = -1;
while ((index = st.indexOf(oldSt)) != -1) {
st = st.substring(0, index) + newSt + st.substring(index + oldSt.length());
}
return st;
}
public static String shrinkPath(String target) {
String targetPath = Utils.replaceAll(target, File.separator, PATH_SEP);
String[] targetTokens = Utils.getTokens(targetPath, PATH_SEP);
//String[] fromTokens = Utils.getTokens(fromPath, PATH_SEP);
for (int i = 0; i < targetTokens.length; i++)
if (targetTokens[i].equals("")) {
targetTokens[i] = null;
} else if (targetTokens[i].equals(".")) {
targetTokens[i] = null;
} else if (targetTokens[i].equals("..")) {
int id = i - 1;
while (targetTokens[id] == null) {
id--;
}
targetTokens[id] = null;
}
StringBuffer sb = new StringBuffer();
if (targetPath.startsWith(PATH_SEP))
sb.append(PATH_SEP);
for (int i = 0; i < targetTokens.length; i++)
if (targetTokens[i] != null)
sb.append(targetTokens[i] + PATH_SEP);
String ret = sb.toString();
if (!targetPath.endsWith(PATH_SEP))
ret = ret.substring(0, ret.lastIndexOf(PATH_SEP));
return ret;
}
/**
* Sort by increasing order of startlevels.
*
* @param bInfos array of BundleInfos to be sorted.
* @param initialBSL initial bundle start level to be used.
* @return sorted array of BundleInfos
*/
public static BundleInfo[] sortBundleInfos(BundleInfo[] bInfos, int initialBSL) {
SortedMap bslToList = new TreeMap();
for (int i = 0; i < bInfos.length; i++) {
Integer sL = new Integer(bInfos[i].getStartLevel());
if (sL.intValue() == BundleInfo.NO_LEVEL)
sL = new Integer(initialBSL);
List list = (List) bslToList.get(sL);
if (list == null) {
list = new LinkedList();
bslToList.put(sL, list);
}
list.add(bInfos[i]);
}
// bslToList is sorted by the key (StartLevel).
List bundleInfoList = new LinkedList();
for (Iterator ite = bslToList.keySet().iterator(); ite.hasNext();) {
Integer sL = (Integer) ite.next();
List list = (List) bslToList.get(sL);
for (Iterator ite2 = list.iterator(); ite2.hasNext();) {
BundleInfo bInfo = (BundleInfo) ite2.next();
bundleInfoList.add(bInfo);
}
}
return getBundleInfosFromList(bundleInfoList);
}
/**
* get String representing the given properties.
*
* @param name name of properties
* @param props properties whose keys and values will be printed out.
*/
public static String toStringProperties(String name, Properties props) {
if (props == null || props.size() == 0) {
return "Props(" + name + ") is empty\n";
}
StringBuffer sb = new StringBuffer();
sb.append("Props(" + name + ") is \n");
for (Enumeration enumeration = props.keys(); enumeration.hasMoreElements();) {
String key = (String) enumeration.nextElement();
sb.append("\tkey=" + key + "\tvalue=" + props.getProperty(key) + "\n");
}
return sb.toString();
}
public static void validateUrl(URL url) {//throws ManipulatorException {
try {//test
URLConnection connection = url.openConnection();
connection.connect();
} catch (IOException e) {
throw new IllegalArgumentException("URL(" + url + ") cannot be connected.");
}
}
}
| false | true | public static void checkAbsoluteFile(File file, String dirName) {//throws ManipulatorException {
if (file == null)
throw new IllegalArgumentException(dirName + " is null");
if (!file.isAbsolute())
throw new IllegalArgumentException(dirName + " is not absolute path. file=" + file.getAbsolutePath());
if (file.isDirectory())
throw new IllegalArgumentException(dirName + " is not file but directory");
}
public static URL checkFullUrl(URL url, String urlName) throws IllegalArgumentException {//throws ManipulatorException {
if (url == null)
throw new IllegalArgumentException(urlName + " is null");
if (!url.getProtocol().endsWith("file"))
return url;
File file = new File(url.getFile());
if (!file.isAbsolute())
throw new IllegalArgumentException(urlName + "(" + url + ") does not have absolute path");
if (file.getAbsolutePath().startsWith(PATH_SEP))
return url;
try {
return getUrl("file", null, PATH_SEP + file.getAbsolutePath());
} catch (MalformedURLException e) {
throw new IllegalArgumentException(urlName + "(" + "file:" + PATH_SEP + file.getAbsolutePath() + ") is not fully quallified");
}
}
public static void createParentDir(File file) throws IOException {
File parent = file.getParentFile();
if (parent == null)
return;
parent.mkdirs();
}
/**
* Deletes the given file recursively, adding failure info to
* the provided status object. The filePath is passed as a parameter
* to optimize java.io.File object creation.
*/
// Implementation taken from the Eclipse File sytem bundle class LocalFile.
// TODO consider putting back the progress and cancelation support.
private static boolean internalDelete(File target, String pathToDelete) {
//first try to delete - this should succeed for files and symbolic links to directories
if (target.delete() || !target.exists())
return true;
if (target.isDirectory()) {
String[] list = target.list();
if (list == null)
list = EMPTY_STRING_ARRAY;
int parentLength = pathToDelete.length();
boolean failedRecursive = false;
for (int i = 0, imax = list.length; i < imax; i++) {
//optimized creation of child path object
StringBuffer childBuffer = new StringBuffer(parentLength + list[i].length() + 1);
childBuffer.append(pathToDelete);
childBuffer.append(File.separatorChar);
childBuffer.append(list[i]);
String childName = childBuffer.toString();
// try best effort on all children so put logical OR at end
failedRecursive = !internalDelete(new java.io.File(childName), childName) || failedRecursive;
}
try {
// don't try to delete the root if one of the children failed
if (!failedRecursive && target.delete())
return true;
} catch (Exception e) {
// we caught a runtime exception so log it
return false;
}
}
// message = NLS.bind(Messages.couldnotDelete, target.getAbsolutePath());
return false;
}
public static void deleteDir(File target) throws IOException {
internalDelete(target, target.getAbsolutePath());
throw new IOException("Fail to delete Dir(" + target.getAbsolutePath() + ")");
}
/**
* First, it replaces File.seperator of relativePath to "/".
* If relativePath is in URL format, return its URL.
* Otherwise, create absolute URL based on the baseUrl.
*
* @param relativePath
* @param baseUrl
* @return URL
* @throws MalformedURLException
*/
public static URL formatUrl(String relativePath, URL baseUrl) throws MalformedURLException {//throws ManipulatorException {
relativePath = Utils.replaceAll(relativePath, File.separator, "/");
URL url = null;
try {
url = new URL(relativePath);
if (url.getProtocol().equals("file"))
if (!(new File(url.getFile())).isAbsolute())
url = getUrlInFull(relativePath, baseUrl);
return url;
} catch (MalformedURLException e) {
return getUrlInFull(relativePath, baseUrl);
}
}
public static BundleInfo[] getBundleInfosFromList(List list) {
if (list == null)
return new BundleInfo[0];
BundleInfo[] ret = new BundleInfo[list.size()];
list.toArray(ret);
return ret;
}
public static String[] getClauses(String header) {
StringTokenizer token = new StringTokenizer(header, ",");
List list = new LinkedList();
while (token.hasMoreTokens()) {
list.add(token.nextToken());
}
String[] ret = new String[list.size()];
list.toArray(ret);
return ret;
}
public static String[] getClausesManifestMainAttributes(String location, String name) {
return getClauses(getManifestMainAttributes(location, name));
}
public static String getManifestMainAttributes(String location, String name) {
Dictionary manifest = Utils.getOSGiManifest(location);
if (manifest == null)
throw new RuntimeException("Unable to locate bundle manifest: " + location);
return (String) manifest.get(name);
}
public static Dictionary getOSGiManifest(String location) {
if (location.startsWith("file:") && !location.endsWith(".jar"))
return basicLoadManifest(new File(location.substring("file:".length())));
try {
URL url = new URL("jar:" + location + "!/");
JarURLConnection jarConnection = (JarURLConnection) url.openConnection();
Manifest manifest = jarConnection.getManifest();
Attributes attributes = manifest.getMainAttributes();
// Set set = attributes.keySet();
Hashtable table = new Hashtable();
for (java.util.Iterator ite = attributes.keySet().iterator(); ite.hasNext();) {
// Object obj = ite.next();
//System.out.println(obj.getClass().getName());
String key = (String) ite.next().toString();
// While table contains non OSGiManifest, it doesn't matter.
table.put(key, attributes.getValue(key));
// System.out.println("key=" + key + " value=" + value);
}
// System.out.println("");
try {
jarConnection.getJarFile().close();
} catch (IOException e) {
//Ignore
}
return table;
} catch (MalformedURLException e1) {
// TODO log
System.err.println("location=" + location);
e1.printStackTrace();
} catch (IOException e) {
// TODO log
System.err.println("location=" + location);
e.printStackTrace();
}
return null;
}
public static String getPathFromClause(String clause) {
if (clause == null)
return null;
if (clause.indexOf(";") != -1)
clause = clause.substring(0, clause.indexOf(";"));
return clause.trim();
}
public static String getRelativePath(File target, File from) {
String targetPath = Utils.replaceAll(target.getAbsolutePath(), File.separator, PATH_SEP);
String fromPath = Utils.replaceAll(from.getAbsolutePath(), File.separator, PATH_SEP);
String[] targetTokens = Utils.getTokens(targetPath, PATH_SEP);
String[] fromTokens = Utils.getTokens(fromPath, PATH_SEP);
int index = -1;
for (int i = 0; i < fromTokens.length; i++)
if (fromTokens[i].equals(targetTokens[i]))
index = i;
else
break;
StringBuffer sb = new StringBuffer();
for (int i = index + 1; i < fromTokens.length; i++)
sb.append(".." + PATH_SEP);
for (int i = index + 1; i < targetTokens.length; i++)
if (i != targetTokens.length - 1)
sb.append(targetTokens[i] + PATH_SEP);
else
sb.append(targetTokens[i]);
return sb.toString();
}
public static String getRelativePath(URL target, URL from) throws IllegalArgumentException {
if (!target.getProtocol().equals(from.getProtocol()))
throw new IllegalArgumentException("Protocols of target(=" + target + ") and from(=" + from + ") does NOT equal");
if (target.getHost() != null && target.getHost().length() != 0) {
//System.out.println("target.getHost()=" + target.getHost());
if (from.getHost() != null && from.getHost().length() != 0) {
if (!target.getHost().equals(from.getHost()))
throw new IllegalArgumentException("Hosts of target(=" + target + ") and from(=" + from + ") does NOT equal");
if (target.getPort() != (from.getPort()))
throw new IllegalArgumentException("Ports of target(=" + target + ") and from(=" + from + ") does NOT equal");
} else
throw new IllegalArgumentException("While Host of target(=" + target + ") is set, Host of from is null.target.getHost()=" + target.getHost());
} else if (from.getHost() != null && from.getHost().length() != 0)
throw new IllegalArgumentException("While Host of from(=" + from + ") is set, Host of target is null");
String targetPath = target.getFile();
String fromPath = from.getFile();
String[] targetTokens = Utils.getTokens(targetPath, PATH_SEP);
String[] fromTokens = Utils.getTokens(fromPath, PATH_SEP);
int index = -1;
for (int i = 0; i < fromTokens.length; i++)
if (fromTokens[i].equals(targetTokens[i]))
index = i;
else
break;
StringBuffer sb = new StringBuffer();
for (int i = index + 1; i < fromTokens.length; i++)
sb.append(".." + PATH_SEP);
for (int i = index + 1; i < targetTokens.length; i++)
if (i != targetTokens.length - 1)
sb.append(targetTokens[i] + PATH_SEP);
else
sb.append(targetTokens[i]);
return sb.toString();
}
// public static URL getAbsoluteUrl(String relativePath, URL baseUrl) throws FwLauncherException {
// relativePath = Utils.replaceAll(relativePath, File.separator, "/");
// try {
// return new URL(baseUrl, relativePath);
// } catch (MalformedURLException e) {
// throw new FwLauncherException("Absolute URL cannot be created. \nrelativePath=" + relativePath + ",baseUrl=" + baseUrl, e, FwLauncherException.URL_FORMAT_ERROR);
// }
// }
// public static void setProperties(Properties to, Properties from, String key) {
// if (from != null) {
// String value = from.getProperty(key);
// if (value != null) {
// if (to != null)
// to = new Properties();
// to.setProperty(key, value);
// }
// }
// }
// public static int getIntProperties(Properties props, String key) {//throws ManipulatorException {
// if (props == null)
// throw new IllegalArgumentException("props == null");
// String value = null;
// try {
// value = props.getProperty(key);
// return Integer.parseInt(value);
// } catch (NumberFormatException nfe) {
// throw new ManipulatorException("key=" + key + ",value=" + value, nfe, ManipulatorException.OTHERS);
// }
// }
/**
* This method will be called for create a backup file.
*
* @param file target file
* @return File backup file whose filename consists of "hogehoge.yyyyMMddHHmmss.ext" or
* "hogehoge.yyyyMMddHHmmss".
*/
public static File getSimpleDataFormattedFile(File file) {
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String date = df.format(new Date());
String filename = file.getName();
int index = filename.lastIndexOf(".");
if (index != -1)
filename = filename.substring(0, index) + "." + date + "." + filename.substring(index + 1);
else
filename = filename + "." + date;
File dest = new File(file.getParentFile(), filename);
return dest;
}
public static String[] getTokens(String msg, String delim) {
return getTokens(msg, delim, false);
}
public static String[] getTokens(String msg, String delim, boolean returnDelims) {
StringTokenizer targetST = new StringTokenizer(msg, delim, returnDelims);
String[] tokens = new String[targetST.countTokens()];
ArrayList list = new ArrayList(targetST.countTokens());
while (targetST.hasMoreTokens()) {
list.add(targetST.nextToken());
}
list.toArray(tokens);
return tokens;
}
public static URL getUrl(String protocol, String host, String file) throws MalformedURLException {// throws ManipulatorException {
file = Utils.replaceAll(file, File.separator, "/");
return new URL(protocol, host, file);
}
public static URL getUrlInFull(String path, URL from) throws MalformedURLException {//throws ManipulatorException {
Utils.checkFullUrl(from, "from");
path = Utils.replaceAll(path, File.separator, "/");
//System.out.println("from.toExternalForm()=" + from.toExternalForm());
String fromSt = Utils.removeLastCh(from.toExternalForm(), '/');
//System.out.println("fromSt=" + fromSt);
if (path.startsWith("/")) {
String fileSt = from.getFile();
return new URL(fromSt.substring(0, fromSt.lastIndexOf(fileSt) - 1) + path);
}
return new URL(fromSt + "/" + path);
}
private static Properties manifestToProperties(Attributes d) {
Iterator iter = d.keySet().iterator();
Properties result = new Properties();
while (iter.hasNext()) {
Attributes.Name key = (Attributes.Name) iter.next();
result.put(key.toString(), d.get(key));
}
return result;
}
/**
* Just used for debug.
*
* @param ps printstream
* @param name name of properties
* @param props properties whose keys and values will be printed out.
*/
public static void printoutProperties(PrintStream ps, String name, Properties props) {
if (props == null || props.size() == 0) {
ps.println("Props(" + name + ") is empty");
return;
}
ps.println("Props(" + name + ")=");
for (Enumeration enumeration = props.keys(); enumeration.hasMoreElements();) {
String key = (String) enumeration.nextElement();
ps.print("\tkey=" + key);
ps.println("\tvalue=" + props.getProperty(key));
}
}
public static String removeLastCh(String target, char ch) {
while (target.charAt(target.length() - 1) == ch) {
target = target.substring(0, target.length() - 1);
}
return target;
}
public static String replaceAll(String st, String oldSt, String newSt) {
if (oldSt.equals(newSt))
return st;
int index = -1;
while ((index = st.indexOf(oldSt)) != -1) {
st = st.substring(0, index) + newSt + st.substring(index + oldSt.length());
}
return st;
}
public static String shrinkPath(String target) {
String targetPath = Utils.replaceAll(target, File.separator, PATH_SEP);
String[] targetTokens = Utils.getTokens(targetPath, PATH_SEP);
//String[] fromTokens = Utils.getTokens(fromPath, PATH_SEP);
for (int i = 0; i < targetTokens.length; i++)
if (targetTokens[i].equals("")) {
targetTokens[i] = null;
} else if (targetTokens[i].equals(".")) {
targetTokens[i] = null;
} else if (targetTokens[i].equals("..")) {
int id = i - 1;
while (targetTokens[id] == null) {
id--;
}
targetTokens[id] = null;
}
StringBuffer sb = new StringBuffer();
if (targetPath.startsWith(PATH_SEP))
sb.append(PATH_SEP);
for (int i = 0; i < targetTokens.length; i++)
if (targetTokens[i] != null)
sb.append(targetTokens[i] + PATH_SEP);
String ret = sb.toString();
if (!targetPath.endsWith(PATH_SEP))
ret = ret.substring(0, ret.lastIndexOf(PATH_SEP));
return ret;
}
/**
* Sort by increasing order of startlevels.
*
* @param bInfos array of BundleInfos to be sorted.
* @param initialBSL initial bundle start level to be used.
* @return sorted array of BundleInfos
*/
public static BundleInfo[] sortBundleInfos(BundleInfo[] bInfos, int initialBSL) {
SortedMap bslToList = new TreeMap();
for (int i = 0; i < bInfos.length; i++) {
Integer sL = new Integer(bInfos[i].getStartLevel());
if (sL.intValue() == BundleInfo.NO_LEVEL)
sL = new Integer(initialBSL);
List list = (List) bslToList.get(sL);
if (list == null) {
list = new LinkedList();
bslToList.put(sL, list);
}
list.add(bInfos[i]);
}
// bslToList is sorted by the key (StartLevel).
List bundleInfoList = new LinkedList();
for (Iterator ite = bslToList.keySet().iterator(); ite.hasNext();) {
Integer sL = (Integer) ite.next();
List list = (List) bslToList.get(sL);
for (Iterator ite2 = list.iterator(); ite2.hasNext();) {
BundleInfo bInfo = (BundleInfo) ite2.next();
bundleInfoList.add(bInfo);
}
}
return getBundleInfosFromList(bundleInfoList);
}
/**
* get String representing the given properties.
*
* @param name name of properties
* @param props properties whose keys and values will be printed out.
*/
public static String toStringProperties(String name, Properties props) {
if (props == null || props.size() == 0) {
return "Props(" + name + ") is empty\n";
}
StringBuffer sb = new StringBuffer();
sb.append("Props(" + name + ") is \n");
for (Enumeration enumeration = props.keys(); enumeration.hasMoreElements();) {
String key = (String) enumeration.nextElement();
sb.append("\tkey=" + key + "\tvalue=" + props.getProperty(key) + "\n");
}
return sb.toString();
}
public static void validateUrl(URL url) {//throws ManipulatorException {
try {//test
URLConnection connection = url.openConnection();
connection.connect();
} catch (IOException e) {
throw new IllegalArgumentException("URL(" + url + ") cannot be connected.");
}
}
}
| public static void checkAbsoluteFile(File file, String dirName) {//throws ManipulatorException {
if (file == null)
throw new IllegalArgumentException(dirName + " is null");
if (!file.isAbsolute())
throw new IllegalArgumentException(dirName + " is not absolute path. file=" + file.getAbsolutePath());
if (file.isDirectory())
throw new IllegalArgumentException(dirName + " is not file but directory");
}
public static URL checkFullUrl(URL url, String urlName) throws IllegalArgumentException {//throws ManipulatorException {
if (url == null)
throw new IllegalArgumentException(urlName + " is null");
if (!url.getProtocol().endsWith("file"))
return url;
File file = new File(url.getFile());
if (!file.isAbsolute())
throw new IllegalArgumentException(urlName + "(" + url + ") does not have absolute path");
if (file.getAbsolutePath().startsWith(PATH_SEP))
return url;
try {
return getUrl("file", null, PATH_SEP + file.getAbsolutePath());
} catch (MalformedURLException e) {
throw new IllegalArgumentException(urlName + "(" + "file:" + PATH_SEP + file.getAbsolutePath() + ") is not fully quallified");
}
}
public static void createParentDir(File file) throws IOException {
File parent = file.getParentFile();
if (parent == null)
return;
parent.mkdirs();
}
/**
* Deletes the given file recursively, adding failure info to
* the provided status object. The filePath is passed as a parameter
* to optimize java.io.File object creation.
*/
// Implementation taken from the Eclipse File sytem bundle class LocalFile.
// TODO consider putting back the progress and cancelation support.
private static boolean internalDelete(File target, String pathToDelete) {
//first try to delete - this should succeed for files and symbolic links to directories
if (target.delete() || !target.exists())
return true;
if (target.isDirectory()) {
String[] list = target.list();
if (list == null)
list = EMPTY_STRING_ARRAY;
int parentLength = pathToDelete.length();
boolean failedRecursive = false;
for (int i = 0, imax = list.length; i < imax; i++) {
//optimized creation of child path object
StringBuffer childBuffer = new StringBuffer(parentLength + list[i].length() + 1);
childBuffer.append(pathToDelete);
childBuffer.append(File.separatorChar);
childBuffer.append(list[i]);
String childName = childBuffer.toString();
// try best effort on all children so put logical OR at end
failedRecursive = !internalDelete(new java.io.File(childName), childName) || failedRecursive;
}
try {
// don't try to delete the root if one of the children failed
if (!failedRecursive && target.delete())
return true;
} catch (Exception e) {
// we caught a runtime exception so log it
return false;
}
}
// message = NLS.bind(Messages.couldnotDelete, target.getAbsolutePath());
return false;
}
public static void deleteDir(File target) throws IOException {
internalDelete(target, target.getAbsolutePath());
throw new IOException("Fail to delete Dir(" + target.getAbsolutePath() + ")");
}
/**
* First, it replaces File.seperator of relativePath to "/".
* If relativePath is in URL format, return its URL.
* Otherwise, create absolute URL based on the baseUrl.
*
* @param relativePath
* @param baseUrl
* @return URL
* @throws MalformedURLException
*/
public static URL formatUrl(String relativePath, URL baseUrl) throws MalformedURLException {//throws ManipulatorException {
relativePath = Utils.replaceAll(relativePath, File.separator, "/");
URL url = null;
try {
url = new URL(relativePath);
if (url.getProtocol().equals("file"))
if (!(new File(url.getFile())).isAbsolute())
url = getUrlInFull(relativePath, baseUrl);
return url;
} catch (MalformedURLException e) {
return getUrlInFull(relativePath, baseUrl);
}
}
public static BundleInfo[] getBundleInfosFromList(List list) {
if (list == null)
return new BundleInfo[0];
BundleInfo[] ret = new BundleInfo[list.size()];
list.toArray(ret);
return ret;
}
public static String[] getClauses(String header) {
StringTokenizer token = new StringTokenizer(header, ",");
List list = new LinkedList();
while (token.hasMoreTokens()) {
list.add(token.nextToken());
}
String[] ret = new String[list.size()];
list.toArray(ret);
return ret;
}
public static String[] getClausesManifestMainAttributes(String location, String name) {
return getClauses(getManifestMainAttributes(location, name));
}
public static String getManifestMainAttributes(String location, String name) {
Dictionary manifest = Utils.getOSGiManifest(location);
if (manifest == null)
throw new RuntimeException("Unable to locate bundle manifest: " + location);
return (String) manifest.get(name);
}
public static Dictionary getOSGiManifest(String location) {
if (location.startsWith("file:") && !location.endsWith(".jar"))
return basicLoadManifest(new File(location.substring("file:".length())));
try {
URL url = new URL("jar:" + location + "!/");
JarURLConnection jarConnection = (JarURLConnection) url.openConnection();
Manifest manifest = jarConnection.getManifest();
Attributes attributes = manifest.getMainAttributes();
// Set set = attributes.keySet();
Hashtable table = new Hashtable();
for (java.util.Iterator ite = attributes.keySet().iterator(); ite.hasNext();) {
// Object obj = ite.next();
//System.out.println(obj.getClass().getName());
String key = (String) ite.next().toString();
// While table contains non OSGiManifest, it doesn't matter.
table.put(key, attributes.getValue(key));
// System.out.println("key=" + key + " value=" + value);
}
// System.out.println("");
try {
jarConnection.getJarFile().close();
} catch (IOException e) {
//Ignore
}
return table;
} catch (IOException e) {
if (System.getProperty("osgi.debug") != null) {
System.err.println("location=" + location);
e.printStackTrace();
}
}
return null;
}
public static String getPathFromClause(String clause) {
if (clause == null)
return null;
if (clause.indexOf(";") != -1)
clause = clause.substring(0, clause.indexOf(";"));
return clause.trim();
}
public static String getRelativePath(File target, File from) {
String targetPath = Utils.replaceAll(target.getAbsolutePath(), File.separator, PATH_SEP);
String fromPath = Utils.replaceAll(from.getAbsolutePath(), File.separator, PATH_SEP);
String[] targetTokens = Utils.getTokens(targetPath, PATH_SEP);
String[] fromTokens = Utils.getTokens(fromPath, PATH_SEP);
int index = -1;
for (int i = 0; i < fromTokens.length; i++)
if (fromTokens[i].equals(targetTokens[i]))
index = i;
else
break;
StringBuffer sb = new StringBuffer();
for (int i = index + 1; i < fromTokens.length; i++)
sb.append(".." + PATH_SEP);
for (int i = index + 1; i < targetTokens.length; i++)
if (i != targetTokens.length - 1)
sb.append(targetTokens[i] + PATH_SEP);
else
sb.append(targetTokens[i]);
return sb.toString();
}
public static String getRelativePath(URL target, URL from) throws IllegalArgumentException {
if (!target.getProtocol().equals(from.getProtocol()))
throw new IllegalArgumentException("Protocols of target(=" + target + ") and from(=" + from + ") does NOT equal");
if (target.getHost() != null && target.getHost().length() != 0) {
//System.out.println("target.getHost()=" + target.getHost());
if (from.getHost() != null && from.getHost().length() != 0) {
if (!target.getHost().equals(from.getHost()))
throw new IllegalArgumentException("Hosts of target(=" + target + ") and from(=" + from + ") does NOT equal");
if (target.getPort() != (from.getPort()))
throw new IllegalArgumentException("Ports of target(=" + target + ") and from(=" + from + ") does NOT equal");
} else
throw new IllegalArgumentException("While Host of target(=" + target + ") is set, Host of from is null.target.getHost()=" + target.getHost());
} else if (from.getHost() != null && from.getHost().length() != 0)
throw new IllegalArgumentException("While Host of from(=" + from + ") is set, Host of target is null");
String targetPath = target.getFile();
String fromPath = from.getFile();
String[] targetTokens = Utils.getTokens(targetPath, PATH_SEP);
String[] fromTokens = Utils.getTokens(fromPath, PATH_SEP);
int index = -1;
for (int i = 0; i < fromTokens.length; i++)
if (fromTokens[i].equals(targetTokens[i]))
index = i;
else
break;
StringBuffer sb = new StringBuffer();
for (int i = index + 1; i < fromTokens.length; i++)
sb.append(".." + PATH_SEP);
for (int i = index + 1; i < targetTokens.length; i++)
if (i != targetTokens.length - 1)
sb.append(targetTokens[i] + PATH_SEP);
else
sb.append(targetTokens[i]);
return sb.toString();
}
// public static URL getAbsoluteUrl(String relativePath, URL baseUrl) throws FwLauncherException {
// relativePath = Utils.replaceAll(relativePath, File.separator, "/");
// try {
// return new URL(baseUrl, relativePath);
// } catch (MalformedURLException e) {
// throw new FwLauncherException("Absolute URL cannot be created. \nrelativePath=" + relativePath + ",baseUrl=" + baseUrl, e, FwLauncherException.URL_FORMAT_ERROR);
// }
// }
// public static void setProperties(Properties to, Properties from, String key) {
// if (from != null) {
// String value = from.getProperty(key);
// if (value != null) {
// if (to != null)
// to = new Properties();
// to.setProperty(key, value);
// }
// }
// }
// public static int getIntProperties(Properties props, String key) {//throws ManipulatorException {
// if (props == null)
// throw new IllegalArgumentException("props == null");
// String value = null;
// try {
// value = props.getProperty(key);
// return Integer.parseInt(value);
// } catch (NumberFormatException nfe) {
// throw new ManipulatorException("key=" + key + ",value=" + value, nfe, ManipulatorException.OTHERS);
// }
// }
/**
* This method will be called for create a backup file.
*
* @param file target file
* @return File backup file whose filename consists of "hogehoge.yyyyMMddHHmmss.ext" or
* "hogehoge.yyyyMMddHHmmss".
*/
public static File getSimpleDataFormattedFile(File file) {
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String date = df.format(new Date());
String filename = file.getName();
int index = filename.lastIndexOf(".");
if (index != -1)
filename = filename.substring(0, index) + "." + date + "." + filename.substring(index + 1);
else
filename = filename + "." + date;
File dest = new File(file.getParentFile(), filename);
return dest;
}
public static String[] getTokens(String msg, String delim) {
return getTokens(msg, delim, false);
}
public static String[] getTokens(String msg, String delim, boolean returnDelims) {
StringTokenizer targetST = new StringTokenizer(msg, delim, returnDelims);
String[] tokens = new String[targetST.countTokens()];
ArrayList list = new ArrayList(targetST.countTokens());
while (targetST.hasMoreTokens()) {
list.add(targetST.nextToken());
}
list.toArray(tokens);
return tokens;
}
public static URL getUrl(String protocol, String host, String file) throws MalformedURLException {// throws ManipulatorException {
file = Utils.replaceAll(file, File.separator, "/");
return new URL(protocol, host, file);
}
public static URL getUrlInFull(String path, URL from) throws MalformedURLException {//throws ManipulatorException {
Utils.checkFullUrl(from, "from");
path = Utils.replaceAll(path, File.separator, "/");
//System.out.println("from.toExternalForm()=" + from.toExternalForm());
String fromSt = Utils.removeLastCh(from.toExternalForm(), '/');
//System.out.println("fromSt=" + fromSt);
if (path.startsWith("/")) {
String fileSt = from.getFile();
return new URL(fromSt.substring(0, fromSt.lastIndexOf(fileSt) - 1) + path);
}
return new URL(fromSt + "/" + path);
}
private static Properties manifestToProperties(Attributes d) {
Iterator iter = d.keySet().iterator();
Properties result = new Properties();
while (iter.hasNext()) {
Attributes.Name key = (Attributes.Name) iter.next();
result.put(key.toString(), d.get(key));
}
return result;
}
/**
* Just used for debug.
*
* @param ps printstream
* @param name name of properties
* @param props properties whose keys and values will be printed out.
*/
public static void printoutProperties(PrintStream ps, String name, Properties props) {
if (props == null || props.size() == 0) {
ps.println("Props(" + name + ") is empty");
return;
}
ps.println("Props(" + name + ")=");
for (Enumeration enumeration = props.keys(); enumeration.hasMoreElements();) {
String key = (String) enumeration.nextElement();
ps.print("\tkey=" + key);
ps.println("\tvalue=" + props.getProperty(key));
}
}
public static String removeLastCh(String target, char ch) {
while (target.charAt(target.length() - 1) == ch) {
target = target.substring(0, target.length() - 1);
}
return target;
}
public static String replaceAll(String st, String oldSt, String newSt) {
if (oldSt.equals(newSt))
return st;
int index = -1;
while ((index = st.indexOf(oldSt)) != -1) {
st = st.substring(0, index) + newSt + st.substring(index + oldSt.length());
}
return st;
}
public static String shrinkPath(String target) {
String targetPath = Utils.replaceAll(target, File.separator, PATH_SEP);
String[] targetTokens = Utils.getTokens(targetPath, PATH_SEP);
//String[] fromTokens = Utils.getTokens(fromPath, PATH_SEP);
for (int i = 0; i < targetTokens.length; i++)
if (targetTokens[i].equals("")) {
targetTokens[i] = null;
} else if (targetTokens[i].equals(".")) {
targetTokens[i] = null;
} else if (targetTokens[i].equals("..")) {
int id = i - 1;
while (targetTokens[id] == null) {
id--;
}
targetTokens[id] = null;
}
StringBuffer sb = new StringBuffer();
if (targetPath.startsWith(PATH_SEP))
sb.append(PATH_SEP);
for (int i = 0; i < targetTokens.length; i++)
if (targetTokens[i] != null)
sb.append(targetTokens[i] + PATH_SEP);
String ret = sb.toString();
if (!targetPath.endsWith(PATH_SEP))
ret = ret.substring(0, ret.lastIndexOf(PATH_SEP));
return ret;
}
/**
* Sort by increasing order of startlevels.
*
* @param bInfos array of BundleInfos to be sorted.
* @param initialBSL initial bundle start level to be used.
* @return sorted array of BundleInfos
*/
public static BundleInfo[] sortBundleInfos(BundleInfo[] bInfos, int initialBSL) {
SortedMap bslToList = new TreeMap();
for (int i = 0; i < bInfos.length; i++) {
Integer sL = new Integer(bInfos[i].getStartLevel());
if (sL.intValue() == BundleInfo.NO_LEVEL)
sL = new Integer(initialBSL);
List list = (List) bslToList.get(sL);
if (list == null) {
list = new LinkedList();
bslToList.put(sL, list);
}
list.add(bInfos[i]);
}
// bslToList is sorted by the key (StartLevel).
List bundleInfoList = new LinkedList();
for (Iterator ite = bslToList.keySet().iterator(); ite.hasNext();) {
Integer sL = (Integer) ite.next();
List list = (List) bslToList.get(sL);
for (Iterator ite2 = list.iterator(); ite2.hasNext();) {
BundleInfo bInfo = (BundleInfo) ite2.next();
bundleInfoList.add(bInfo);
}
}
return getBundleInfosFromList(bundleInfoList);
}
/**
* get String representing the given properties.
*
* @param name name of properties
* @param props properties whose keys and values will be printed out.
*/
public static String toStringProperties(String name, Properties props) {
if (props == null || props.size() == 0) {
return "Props(" + name + ") is empty\n";
}
StringBuffer sb = new StringBuffer();
sb.append("Props(" + name + ") is \n");
for (Enumeration enumeration = props.keys(); enumeration.hasMoreElements();) {
String key = (String) enumeration.nextElement();
sb.append("\tkey=" + key + "\tvalue=" + props.getProperty(key) + "\n");
}
return sb.toString();
}
public static void validateUrl(URL url) {//throws ManipulatorException {
try {//test
URLConnection connection = url.openConnection();
connection.connect();
} catch (IOException e) {
throw new IllegalArgumentException("URL(" + url + ") cannot be connected.");
}
}
}
|
diff --git a/editor/src/main/java/com/nebula2d/editor/ui/ComponentsDialog.java b/editor/src/main/java/com/nebula2d/editor/ui/ComponentsDialog.java
index 21ec64e..e8f9a95 100644
--- a/editor/src/main/java/com/nebula2d/editor/ui/ComponentsDialog.java
+++ b/editor/src/main/java/com/nebula2d/editor/ui/ComponentsDialog.java
@@ -1,141 +1,144 @@
/*
* Nebula2D is a cross-platform, 2D game engine for PC, Mac, & Linux
* Copyright (c) 2014 Jon Bonazza
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nebula2d.editor.ui;
import com.nebula2d.editor.framework.GameObject;
import com.nebula2d.editor.framework.components.Component;
import com.nebula2d.editor.ui.controls.N2DLabel;
import com.nebula2d.editor.ui.controls.N2DList;
import com.nebula2d.editor.ui.controls.N2DPanel;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* Dialog for manipulating GameObject components
*/
public class ComponentsDialog extends JDialog {
private N2DPanel rightPanel;
private GameObject gameObject;
private N2DPanel mainPanel;
private N2DList<Component> componentList;
public ComponentsDialog(GameObject gameObject) {
this.gameObject = gameObject;
N2DPanel componentListPanel = forgeComponentsListPanel();
rightPanel = forgeEmptyPanel();
mainPanel = new N2DPanel(new BorderLayout());
mainPanel.add(componentListPanel, BorderLayout.WEST);
mainPanel.add(rightPanel);
add(mainPanel);
setSize(new Dimension(800, 600));
setResizable(false);
setLocationRelativeTo(null);
setVisible(true);
}
public N2DList<Component> getComponentList() {
return componentList;
}
private N2DPanel forgeEmptyPanel() {
N2DPanel panel = new N2DPanel();
N2DLabel emptyLbl = new N2DLabel("No component currently selected.");
panel.add(emptyLbl);
return panel;
}
private N2DPanel forgeComponentsListPanel() {
componentList = new N2DList<Component>();
final DefaultListModel<Component> model = new DefaultListModel<Component>();
componentList.setModel(model);
populateComponentList(componentList);
JScrollPane sp = new JScrollPane(componentList);
sp.setPreferredSize(new Dimension(200, 400));
final JButton addButton = new JButton("Add");
addButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new NewComponentPopup(gameObject, componentList).show(addButton, -1, addButton.getHeight());
}
});
final JButton removeButton = new JButton("Remove");
removeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Component selectedComponent = componentList.getSelectedValue();
gameObject.removeComponent(selectedComponent);
((DefaultListModel<Component>) componentList.getModel()).removeElement(selectedComponent);
mainPanel.remove(rightPanel);
- mainPanel.add(forgeEmptyPanel());
- revalidate();
+ rightPanel = forgeEmptyPanel();
+ mainPanel.add(rightPanel);
+ mainPanel.validate();
+ mainPanel.repaint();
}
});
removeButton.setEnabled(false);
N2DPanel buttonPanel = new N2DPanel();
buttonPanel.add(addButton);
buttonPanel.add(removeButton);
componentList.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting())
return;
Component component = componentList.getSelectedValue();
removeButton.setEnabled(component != null);
if (component != null) {
mainPanel.remove(rightPanel);
rightPanel = component.forgeComponentContentPanel(ComponentsDialog.this);
mainPanel.add(rightPanel);
- revalidate();
+ mainPanel.validate();
+ mainPanel.repaint();
}
}
});
N2DPanel mainPanel = new N2DPanel(new BorderLayout());
mainPanel.add(buttonPanel, BorderLayout.NORTH);
mainPanel.add(sp);
return mainPanel;
}
private void populateComponentList(N2DList<Component> listBox) {
DefaultListModel<Component> model = (DefaultListModel<Component>) listBox.getModel();
for (Component component : gameObject.getComponents()) {
model.addElement(component);
}
}
}
| false | true | private N2DPanel forgeComponentsListPanel() {
componentList = new N2DList<Component>();
final DefaultListModel<Component> model = new DefaultListModel<Component>();
componentList.setModel(model);
populateComponentList(componentList);
JScrollPane sp = new JScrollPane(componentList);
sp.setPreferredSize(new Dimension(200, 400));
final JButton addButton = new JButton("Add");
addButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new NewComponentPopup(gameObject, componentList).show(addButton, -1, addButton.getHeight());
}
});
final JButton removeButton = new JButton("Remove");
removeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Component selectedComponent = componentList.getSelectedValue();
gameObject.removeComponent(selectedComponent);
((DefaultListModel<Component>) componentList.getModel()).removeElement(selectedComponent);
mainPanel.remove(rightPanel);
mainPanel.add(forgeEmptyPanel());
revalidate();
}
});
removeButton.setEnabled(false);
N2DPanel buttonPanel = new N2DPanel();
buttonPanel.add(addButton);
buttonPanel.add(removeButton);
componentList.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting())
return;
Component component = componentList.getSelectedValue();
removeButton.setEnabled(component != null);
if (component != null) {
mainPanel.remove(rightPanel);
rightPanel = component.forgeComponentContentPanel(ComponentsDialog.this);
mainPanel.add(rightPanel);
revalidate();
}
}
});
N2DPanel mainPanel = new N2DPanel(new BorderLayout());
mainPanel.add(buttonPanel, BorderLayout.NORTH);
mainPanel.add(sp);
return mainPanel;
}
| private N2DPanel forgeComponentsListPanel() {
componentList = new N2DList<Component>();
final DefaultListModel<Component> model = new DefaultListModel<Component>();
componentList.setModel(model);
populateComponentList(componentList);
JScrollPane sp = new JScrollPane(componentList);
sp.setPreferredSize(new Dimension(200, 400));
final JButton addButton = new JButton("Add");
addButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new NewComponentPopup(gameObject, componentList).show(addButton, -1, addButton.getHeight());
}
});
final JButton removeButton = new JButton("Remove");
removeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Component selectedComponent = componentList.getSelectedValue();
gameObject.removeComponent(selectedComponent);
((DefaultListModel<Component>) componentList.getModel()).removeElement(selectedComponent);
mainPanel.remove(rightPanel);
rightPanel = forgeEmptyPanel();
mainPanel.add(rightPanel);
mainPanel.validate();
mainPanel.repaint();
}
});
removeButton.setEnabled(false);
N2DPanel buttonPanel = new N2DPanel();
buttonPanel.add(addButton);
buttonPanel.add(removeButton);
componentList.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting())
return;
Component component = componentList.getSelectedValue();
removeButton.setEnabled(component != null);
if (component != null) {
mainPanel.remove(rightPanel);
rightPanel = component.forgeComponentContentPanel(ComponentsDialog.this);
mainPanel.add(rightPanel);
mainPanel.validate();
mainPanel.repaint();
}
}
});
N2DPanel mainPanel = new N2DPanel(new BorderLayout());
mainPanel.add(buttonPanel, BorderLayout.NORTH);
mainPanel.add(sp);
return mainPanel;
}
|
diff --git a/sql12/app/src/net/sourceforge/squirrel_sql/client/session/CancelStatementThread.java b/sql12/app/src/net/sourceforge/squirrel_sql/client/session/CancelStatementThread.java
index 4375f8562..06154f806 100644
--- a/sql12/app/src/net/sourceforge/squirrel_sql/client/session/CancelStatementThread.java
+++ b/sql12/app/src/net/sourceforge/squirrel_sql/client/session/CancelStatementThread.java
@@ -1,118 +1,122 @@
package net.sourceforge.squirrel_sql.client.session;
import net.sourceforge.squirrel_sql.fw.util.IMessageHandler;
import net.sourceforge.squirrel_sql.fw.util.StringManager;
import net.sourceforge.squirrel_sql.fw.util.StringManagerFactory;
import net.sourceforge.squirrel_sql.fw.util.log.ILogger;
import net.sourceforge.squirrel_sql.fw.util.log.LoggerController;
import java.sql.Statement;
public class CancelStatementThread extends Thread
{
private static final StringManager s_stringMgr =
StringManagerFactory.getStringManager(CancelStatementThread.class);
private static final ILogger s_log = LoggerController.createLogger(CancelStatementThread.class);
private Statement _stmt;
private IMessageHandler _messageHandler;
private boolean _threadFinished;
private boolean _joinReturned;
public CancelStatementThread(Statement stmt, IMessageHandler messageHandler)
{
_stmt = stmt;
_messageHandler = messageHandler;
}
public void tryCancel()
{
try
{
start();
join(1500);
synchronized (this)
{
_joinReturned = true;
if(false == _threadFinished)
{
// i18n[CancelStatementThread.cancelTimedOut=Failed to cancel statement within one second. Perhaps your driver/database does not support cancelling statements. If cancelling succeeds later you'll get a further messages.]
String msg = s_stringMgr.getString("CancelStatementThread.cancelTimedOut");
_messageHandler.showErrorMessage(msg);
s_log.error(msg);
}
}
}
catch (InterruptedException e)
{
throw new RuntimeException(e);
}
}
public void run()
{
String msg;
boolean cancelSucceeded = false;
boolean closeSucceeded = false;
try
{
- _stmt.cancel();
+ if (_stmt != null) {
+ _stmt.cancel();
+ }
cancelSucceeded = true;
}
catch (Throwable t)
{
// i18n[CancelStatementThread.cancelFailed=Failed to cancel statement. Perhaps the driver/RDDBMS does not support cancelling statements. See logs for further details ({0})]
msg = s_stringMgr.getString("CancelStatementThread.cancelFailed", t);
_messageHandler.showErrorMessage(msg);
s_log.error(msg, t);
}
try
{
// give the ResultSetReader some time to realize that the user requested
// cancel and stop fetching results. This allows us to stop the query
// processing gracefully.
Thread.sleep(500);
- _stmt.close();
+ if (_stmt != null) {
+ _stmt.close();
+ }
closeSucceeded = true;
}
catch (Throwable t)
{
// i18n[CancelStatementThread.closeFailed=Failed to close statement. Propably the driver/RDDBMS does not support canceling statements. See logs for further details ({0})]
msg = s_stringMgr.getString("CancelStatementThread.closeFailed", t);
_messageHandler.showErrorMessage(msg);
s_log.error(msg, t);
}
synchronized (this)
{
if (cancelSucceeded && closeSucceeded)
{
if (_joinReturned)
{
// i18n[CancelStatementThread.cancelSucceededLate=Canceling statement succeeded now. But took longer than one second.]
msg = s_stringMgr.getString("CancelStatementThread.cancelSucceededLate");
_messageHandler.showMessage(msg);
}
else
{
// i18n[CancelStatementThread.cancelSucceeded=The database has been asked to cancel the statment.]
msg = s_stringMgr.getString("CancelStatementThread.cancelSucceeded");
_messageHandler.showMessage(msg);
}
}
_threadFinished = true;
}
}
}
| false | true | public void run()
{
String msg;
boolean cancelSucceeded = false;
boolean closeSucceeded = false;
try
{
_stmt.cancel();
cancelSucceeded = true;
}
catch (Throwable t)
{
// i18n[CancelStatementThread.cancelFailed=Failed to cancel statement. Perhaps the driver/RDDBMS does not support cancelling statements. See logs for further details ({0})]
msg = s_stringMgr.getString("CancelStatementThread.cancelFailed", t);
_messageHandler.showErrorMessage(msg);
s_log.error(msg, t);
}
try
{
// give the ResultSetReader some time to realize that the user requested
// cancel and stop fetching results. This allows us to stop the query
// processing gracefully.
Thread.sleep(500);
_stmt.close();
closeSucceeded = true;
}
catch (Throwable t)
{
// i18n[CancelStatementThread.closeFailed=Failed to close statement. Propably the driver/RDDBMS does not support canceling statements. See logs for further details ({0})]
msg = s_stringMgr.getString("CancelStatementThread.closeFailed", t);
_messageHandler.showErrorMessage(msg);
s_log.error(msg, t);
}
synchronized (this)
{
if (cancelSucceeded && closeSucceeded)
{
if (_joinReturned)
{
// i18n[CancelStatementThread.cancelSucceededLate=Canceling statement succeeded now. But took longer than one second.]
msg = s_stringMgr.getString("CancelStatementThread.cancelSucceededLate");
_messageHandler.showMessage(msg);
}
else
{
// i18n[CancelStatementThread.cancelSucceeded=The database has been asked to cancel the statment.]
msg = s_stringMgr.getString("CancelStatementThread.cancelSucceeded");
_messageHandler.showMessage(msg);
}
}
_threadFinished = true;
}
}
| public void run()
{
String msg;
boolean cancelSucceeded = false;
boolean closeSucceeded = false;
try
{
if (_stmt != null) {
_stmt.cancel();
}
cancelSucceeded = true;
}
catch (Throwable t)
{
// i18n[CancelStatementThread.cancelFailed=Failed to cancel statement. Perhaps the driver/RDDBMS does not support cancelling statements. See logs for further details ({0})]
msg = s_stringMgr.getString("CancelStatementThread.cancelFailed", t);
_messageHandler.showErrorMessage(msg);
s_log.error(msg, t);
}
try
{
// give the ResultSetReader some time to realize that the user requested
// cancel and stop fetching results. This allows us to stop the query
// processing gracefully.
Thread.sleep(500);
if (_stmt != null) {
_stmt.close();
}
closeSucceeded = true;
}
catch (Throwable t)
{
// i18n[CancelStatementThread.closeFailed=Failed to close statement. Propably the driver/RDDBMS does not support canceling statements. See logs for further details ({0})]
msg = s_stringMgr.getString("CancelStatementThread.closeFailed", t);
_messageHandler.showErrorMessage(msg);
s_log.error(msg, t);
}
synchronized (this)
{
if (cancelSucceeded && closeSucceeded)
{
if (_joinReturned)
{
// i18n[CancelStatementThread.cancelSucceededLate=Canceling statement succeeded now. But took longer than one second.]
msg = s_stringMgr.getString("CancelStatementThread.cancelSucceededLate");
_messageHandler.showMessage(msg);
}
else
{
// i18n[CancelStatementThread.cancelSucceeded=The database has been asked to cancel the statment.]
msg = s_stringMgr.getString("CancelStatementThread.cancelSucceeded");
_messageHandler.showMessage(msg);
}
}
_threadFinished = true;
}
}
|
diff --git a/src/main/java/net/visualillusionsent/fruittrees/canary/CanaryFruitTreesListener.java b/src/main/java/net/visualillusionsent/fruittrees/canary/CanaryFruitTreesListener.java
index 220e55c..c7ac36b 100644
--- a/src/main/java/net/visualillusionsent/fruittrees/canary/CanaryFruitTreesListener.java
+++ b/src/main/java/net/visualillusionsent/fruittrees/canary/CanaryFruitTreesListener.java
@@ -1,394 +1,394 @@
/*
* This file is part of FruitTrees.
*
* Copyright © 2013 Visual Illusions Entertainment
*
* FruitTrees is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* FruitTrees is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with FruitTrees.
* If not, see http://www.gnu.org/licenses/gpl.html.
*/
package net.visualillusionsent.fruittrees.canary;
import net.canarymod.Canary;
import net.canarymod.api.GameMode;
import net.canarymod.api.entity.living.humanoid.Player;
import net.canarymod.api.inventory.Item;
import net.canarymod.api.inventory.ItemType;
import net.canarymod.api.world.blocks.Block;
import net.canarymod.api.world.blocks.BlockType;
import net.canarymod.hook.HookHandler;
import net.canarymod.hook.player.BlockDestroyHook;
import net.canarymod.hook.player.BlockRightClickHook;
import net.canarymod.hook.player.CraftHook;
import net.canarymod.hook.system.LoadWorldHook;
import net.canarymod.hook.system.UnloadWorldHook;
import net.canarymod.hook.world.BlockUpdateHook;
import net.canarymod.hook.world.TreeGrowHook;
import net.canarymod.plugin.PluginListener;
import net.canarymod.plugin.Priority;
import net.visualillusionsent.fruittrees.TreeTracker;
import net.visualillusionsent.fruittrees.TreeType;
import net.visualillusionsent.fruittrees.TreeWorld;
import net.visualillusionsent.fruittrees.trees.AppleTree;
import net.visualillusionsent.fruittrees.trees.CoalTree;
import net.visualillusionsent.fruittrees.trees.DiamondTree;
import net.visualillusionsent.fruittrees.trees.DyeTree;
import net.visualillusionsent.fruittrees.trees.EmeraldTree;
import net.visualillusionsent.fruittrees.trees.FruitTree;
import net.visualillusionsent.fruittrees.trees.GoldTree;
import net.visualillusionsent.fruittrees.trees.GoldenAppleTree;
import net.visualillusionsent.fruittrees.trees.IronTree;
import net.visualillusionsent.fruittrees.trees.RecordTree;
import net.visualillusionsent.fruittrees.trees.RedstoneTree;
import net.visualillusionsent.fruittrees.trees.SpongeTree;
public class CanaryFruitTreesListener implements PluginListener {
public CanaryFruitTreesListener(CanaryFruitTrees cft) {
Canary.hooks().registerListener(this, cft);
}
@HookHandler(priority = Priority.LOW)
public final void craftSeeds(CraftHook hook) {
if (!CanaryFruitTrees.instance().getFruitTreesConfig().requirePermissions()) {
return;
}
if (SeedGen.recipes.contains(hook.getMatchingRecipe())) {
String type = hook.getRecipeResult().getMetaTag().getCompoundTag("FruitTrees").getString("TreeType");
if (!hook.getPlayer().hasPermission("fruittrees.craft.".concat(type.toLowerCase().replace("seeds", "")))) {
hook.setCanceled();
return;
}
}
}
@HookHandler(priority = Priority.LOW)
public final void plantSeeds(BlockRightClickHook hook) {
if (hook.getBlockClicked().getType() == BlockType.Soil) {
Item seeds = hook.getPlayer().getItemHeld();
Block block = hook.getBlockClicked();
- if (seeds.getMetaTag().containsKey("FruitTrees")) {
+ if (seeds.hasMetaTag() && seeds.getMetaTag().containsKey("FruitTrees")) {
String type = seeds.getMetaTag().getCompoundTag("FruitTrees").getString("TreeType");
if (seeds.getType() == ItemType.MelonSeeds) {
if (type.equals("AppleSeeds")) {
if (CanaryFruitTrees.instance().getFruitTreesConfig().checkEnabled(TreeType.APPLE)) {
block.getWorld().setBlockAt(block.getPosition(), (short)3);
block.getWorld().setBlockAt(block.getX(), block.getY() + 1, block.getZ(), (short)6, TreeType.APPLE.getLogData());
FruitTree tree = new AppleTree(CanaryFruitTrees.instance(), block.getX(), block.getY() + 1, block.getZ(), CanaryFruitTrees.instance().getWorldForName(block.getWorld().getFqName()));
tree.save();
decreaseStack(hook.getPlayer());
hook.setCanceled();
}
}
else if (type.equals("GoldenAppleSeeds")) {
if (CanaryFruitTrees.instance().getFruitTreesConfig().checkEnabled(TreeType.GOLDEN_APPLE)) {
block.getWorld().setBlockAt(block.getPosition(), (short)3);
block.getWorld().setBlockAt(block.getX(), block.getY() + 1, block.getZ(), (short)6, TreeType.GOLDEN_APPLE.getLogData());
FruitTree tree = new GoldenAppleTree(CanaryFruitTrees.instance(), block.getX(), block.getY() + 1, block.getZ(), CanaryFruitTrees.instance().getWorldForName(block.getWorld().getFqName()));
tree.save();
decreaseStack(hook.getPlayer());
hook.setCanceled();
}
}
else if (type.equals("CoalSeeds")) {
if (CanaryFruitTrees.instance().getFruitTreesConfig().checkEnabled(TreeType.COAL)) {
block.getWorld().setBlockAt(block.getPosition(), (short)3);
block.getWorld().setBlockAt(block.getX(), block.getY() + 1, block.getZ(), (short)6, TreeType.COAL.getLogData());
FruitTree tree = new CoalTree(CanaryFruitTrees.instance(), block.getX(), block.getY() + 1, block.getZ(), CanaryFruitTrees.instance().getWorldForName(block.getWorld().getFqName()));
tree.save();
decreaseStack(hook.getPlayer());
hook.setCanceled();
}
}
}
else if (seeds.getType() == ItemType.PumpkinSeeds) {
if (type.equals("RecordSeeds")) {
block.getWorld().setBlockAt(block.getPosition(), (short)3);
block.getWorld().setBlockAt(block.getX(), block.getY() + 1, block.getZ(), (short)6, TreeType.RECORD.getLogData());
FruitTree tree = new RecordTree(CanaryFruitTrees.instance(), block.getX(), block.getY() + 1, block.getZ(), CanaryFruitTrees.instance().getWorldForName(block.getWorld().getFqName()));
tree.save();
decreaseStack(hook.getPlayer());
hook.setCanceled();
}
else if (type.equals("SpongeSeeds")) {
block.getWorld().setBlockAt(block.getPosition(), (short)3);
block.getWorld().setBlockAt(block.getX(), block.getY() + 1, block.getZ(), (short)6, TreeType.SPONGE.getLogData());
FruitTree tree = new SpongeTree(CanaryFruitTrees.instance(), block.getX(), block.getY() + 1, block.getZ(), CanaryFruitTrees.instance().getWorldForName(block.getWorld().getFqName()));
tree.save();
decreaseStack(hook.getPlayer());
hook.setCanceled();
}
}
else if (seeds.getType() == ItemType.Seeds) {
if (type.endsWith("DyeSeeds")) {
block.getWorld().setBlockAt(block.getPosition(), (short)3);
block.getWorld().setBlockAt(block.getX(), block.getY() + 1, block.getZ(), (short)6, TreeType.DYE_BLACK.getLogData());
FruitTree tree = new DyeTree(CanaryFruitTrees.instance(), block.getX(), block.getY() + 1, block.getZ(), CanaryFruitTrees.instance().getWorldForName(block.getWorld().getFqName()), seeds.getMetaTag().getCompoundTag("FruitTrees").getByte("DyeColor"));
tree.save();
decreaseStack(hook.getPlayer());
hook.setCanceled();
}
else if (type.equals("RedstoneSeeds")) {
block.getWorld().setBlockAt(block.getPosition(), (short)3);
block.getWorld().setBlockAt(block.getX(), block.getY() + 1, block.getZ(), (short)6, TreeType.REDSTONE.getLogData());
FruitTree tree = new RedstoneTree(CanaryFruitTrees.instance(), block.getX(), block.getY() + 1, block.getZ(), CanaryFruitTrees.instance().getWorldForName(block.getWorld().getFqName()));
tree.save();
decreaseStack(hook.getPlayer());
hook.setCanceled();
}
else if (type.equals("IronSeeds")) {
block.getWorld().setBlockAt(block.getPosition(), (short)3);
block.getWorld().setBlockAt(block.getX(), block.getY() + 1, block.getZ(), (short)6, TreeType.IRON.getLogData());
FruitTree tree = new IronTree(CanaryFruitTrees.instance(), block.getX(), block.getY() + 1, block.getZ(), CanaryFruitTrees.instance().getWorldForName(block.getWorld().getFqName()));
tree.save();
decreaseStack(hook.getPlayer());
hook.setCanceled();
}
else if (type.equals("GoldSeeds")) {
block.getWorld().setBlockAt(block.getPosition(), (short)3);
block.getWorld().setBlockAt(block.getX(), block.getY() + 1, block.getZ(), (short)6, TreeType.GOLD.getLogData());
FruitTree tree = new GoldTree(CanaryFruitTrees.instance(), block.getX(), block.getY() + 1, block.getZ(), CanaryFruitTrees.instance().getWorldForName(block.getWorld().getFqName()));
tree.save();
decreaseStack(hook.getPlayer());
hook.setCanceled();
}
else if (type.equals("DiamondSeeds")) {
block.getWorld().setBlockAt(block.getPosition(), (short)3);
block.getWorld().setBlockAt(block.getX(), block.getY() + 1, block.getZ(), (short)6, TreeType.GOLD.getLogData());
FruitTree tree = new DiamondTree(CanaryFruitTrees.instance(), block.getX(), block.getY() + 1, block.getZ(), CanaryFruitTrees.instance().getWorldForName(block.getWorld().getFqName()));
tree.save();
decreaseStack(hook.getPlayer());
hook.setCanceled();
}
else if (type.equals("EmeraldSeeds")) {
block.getWorld().setBlockAt(block.getPosition(), (short)3);
block.getWorld().setBlockAt(block.getX(), block.getY() + 1, block.getZ(), (short)6, TreeType.GOLD.getLogData());
FruitTree tree = new EmeraldTree(CanaryFruitTrees.instance(), block.getX(), block.getY() + 1, block.getZ(), CanaryFruitTrees.instance().getWorldForName(block.getWorld().getFqName()));
tree.save();
decreaseStack(hook.getPlayer());
hook.setCanceled();
}
else if (type.equals("CoalSeeds")) {
block.getWorld().setBlockAt(block.getPosition(), (short)3);
block.getWorld().setBlockAt(block.getX(), block.getY() + 1, block.getZ(), (short)6, TreeType.GOLD.getLogData());
FruitTree tree = new CoalTree(CanaryFruitTrees.instance(), block.getX(), block.getY() + 1, block.getZ(), CanaryFruitTrees.instance().getWorldForName(block.getWorld().getFqName()));
tree.save();
decreaseStack(hook.getPlayer());
hook.setCanceled();
}
}
}
}
}
@HookHandler(priority = Priority.LOW)
public final void killTree(BlockDestroyHook hook) {
if (BlockType.fromId(hook.getBlock().getTypeId()) == BlockType.OakSapling) {
Block block = hook.getBlock();
FruitTree tree = TreeTracker.getTreeAt(block.getX(), block.getY(), block.getZ(), CanaryFruitTrees.instance().getWorldForName(block.getWorld().getFqName()));
if (tree != null) {
if (hook.getPlayer().getMode() != GameMode.CREATIVE) { //If creative, no need to drop stuff
hook.setCanceled();
switch (tree.getType()) {
case APPLE:
block.getWorld().dropItem(block.getPosition(), SeedGen.seeds[0].clone());
break;
case GOLDEN_APPLE:
block.getWorld().dropItem(block.getPosition(), SeedGen.seeds[1].clone());
break;
case SPONGE:
block.getWorld().dropItem(block.getPosition(), SeedGen.seeds[2].clone());
break;
case RECORD:
block.getWorld().dropItem(block.getPosition(), SeedGen.seeds[3].clone());
break;
case DYE_BLACK:
block.getWorld().dropItem(block.getPosition(), SeedGen.seeds[4].clone());
break;
case DYE_RED:
block.getWorld().dropItem(block.getPosition(), SeedGen.seeds[5].clone());
break;
case DYE_GREEN:
block.getWorld().dropItem(block.getPosition(), SeedGen.seeds[6].clone());
break;
case DYE_BROWN:
block.getWorld().dropItem(block.getPosition(), SeedGen.seeds[7].clone());
break;
case DYE_BLUE:
block.getWorld().dropItem(block.getPosition(), SeedGen.seeds[8].clone());
break;
case DYE_PURPLE:
block.getWorld().dropItem(block.getPosition(), SeedGen.seeds[9].clone());
break;
case DYE_CYAN:
block.getWorld().dropItem(block.getPosition(), SeedGen.seeds[10].clone());
break;
case DYE_LIGHT_GRAY:
block.getWorld().dropItem(block.getPosition(), SeedGen.seeds[11].clone());
break;
case DYE_GRAY:
block.getWorld().dropItem(block.getPosition(), SeedGen.seeds[12].clone());
break;
case DYE_PINK:
block.getWorld().dropItem(block.getPosition(), SeedGen.seeds[13].clone());
break;
case DYE_LIME:
block.getWorld().dropItem(block.getPosition(), SeedGen.seeds[14].clone());
break;
case DYE_YELLOW:
block.getWorld().dropItem(block.getPosition(), SeedGen.seeds[15].clone());
break;
case DYE_LIGHT_BLUE:
block.getWorld().dropItem(block.getPosition(), SeedGen.seeds[16].clone());
break;
case DYE_MAGENTA:
block.getWorld().dropItem(block.getPosition(), SeedGen.seeds[17].clone());
break;
case DYE_ORANGE:
block.getWorld().dropItem(block.getPosition(), SeedGen.seeds[18].clone());
break;
case DYE_WHITE:
block.getWorld().dropItem(block.getPosition(), SeedGen.seeds[19].clone());
break;
case REDSTONE:
block.getWorld().dropItem(block.getPosition(), SeedGen.seeds[20].clone());
break;
case IRON:
block.getWorld().dropItem(block.getPosition(), SeedGen.seeds[21].clone());
break;
case GOLD:
block.getWorld().dropItem(block.getPosition(), SeedGen.seeds[22].clone());
break;
case DIAMOND:
block.getWorld().dropItem(block.getPosition(), SeedGen.seeds[23].clone());
break;
case EMERALD:
block.getWorld().dropItem(block.getPosition(), SeedGen.seeds[24].clone());
break;
case COAL:
block.getWorld().dropItem(block.getPosition(), SeedGen.seeds[25].clone());
break;
default:
break;
}
block.setTypeId((short)0);
block.getWorld().setBlock(block);
}
tree.killTree();
}
}
}
@HookHandler(priority = Priority.LOW)
public final void killTreeArea(BlockUpdateHook hook) { //BlockUpdate a little more reliable with tracking Tree destruction (Especially if editting out a tree)
Block block = hook.getBlock();
if (block.getTypeId() == BlockType.OakLog.getId()) {
FruitTree tree = TreeTracker.isTreeArea(block.getX(), block.getY(), block.getZ(), block.getTypeId(), block.getData(), CanaryFruitTrees.instance().getWorldForName(block.getWorld().getFqName()));
if (tree != null) {
tree.killTree();
}
}
else if (block.getTypeId() == BlockType.OakLeaves.getId()) {
FruitTree tree = TreeTracker.isTreeArea(block.getX(), block.getY(), block.getZ(), block.getTypeId(), block.getData(), CanaryFruitTrees.instance().getWorldForName(block.getWorld().getFqName()));
if (tree != null) {
tree.killTree();
}
}
else if (block.getType() == BlockType.Sponge) {
FruitTree tree = TreeTracker.isTreeArea(block.getX(), block.getY(), block.getZ(), block.getTypeId(), block.getData(), CanaryFruitTrees.instance().getWorldForName(block.getWorld().getFqName()));
if (tree != null) {
tree.killTree();
}
}
else if (block.getTypeId() == BlockType.WoolWhite.getId()) {
FruitTree tree = TreeTracker.isTreeArea(block.getX(), block.getY(), block.getZ(), block.getTypeId(), block.getData(), CanaryFruitTrees.instance().getWorldForName(block.getWorld().getFqName()));
if (tree != null) {
tree.killTree();
}
}
else if (block.getType() == BlockType.RedstoneBlock) {
FruitTree tree = TreeTracker.isTreeArea(block.getX(), block.getY(), block.getZ(), block.getTypeId(), block.getData(), CanaryFruitTrees.instance().getWorldForName(block.getWorld().getFqName()));
if (tree != null) {
tree.killTree();
}
}
else if (block.getType() == BlockType.NoteBlock) {
FruitTree tree = TreeTracker.isTreeArea(block.getX(), block.getY(), block.getZ(), block.getTypeId(), block.getData(), CanaryFruitTrees.instance().getWorldForName(block.getWorld().getFqName()));
if (tree != null) {
tree.killTree();
}
}
else if (block.getType() == BlockType.IronBlock) {
FruitTree tree = TreeTracker.isTreeArea(block.getX(), block.getY(), block.getZ(), block.getTypeId(), block.getData(), CanaryFruitTrees.instance().getWorldForName(block.getWorld().getFqName()));
if (tree != null) {
tree.killTree();
}
}
else if (block.getType() == BlockType.GoldBlock) {
FruitTree tree = TreeTracker.isTreeArea(block.getX(), block.getY(), block.getZ(), block.getTypeId(), block.getData(), CanaryFruitTrees.instance().getWorldForName(block.getWorld().getFqName()));
if (tree != null) {
tree.killTree();
}
}
else if (block.getType() == BlockType.DiamondBlock) {
FruitTree tree = TreeTracker.isTreeArea(block.getX(), block.getY(), block.getZ(), block.getTypeId(), block.getData(), CanaryFruitTrees.instance().getWorldForName(block.getWorld().getFqName()));
if (tree != null) {
tree.killTree();
}
}
else if (block.getType() == BlockType.EmeraldBlock) {
FruitTree tree = TreeTracker.isTreeArea(block.getX(), block.getY(), block.getZ(), block.getTypeId(), block.getData(), CanaryFruitTrees.instance().getWorldForName(block.getWorld().getFqName()));
if (tree != null) {
tree.killTree();
}
}
else if (block.getType() == BlockType.CoalBlock) {
FruitTree tree = TreeTracker.isTreeArea(block.getX(), block.getY(), block.getZ(), block.getTypeId(), block.getData(), CanaryFruitTrees.instance().getWorldForName(block.getWorld().getFqName()));
if (tree != null) {
tree.killTree();
}
}
}
@HookHandler(priority = Priority.HIGH)
public final void treeGrow(TreeGrowHook hook) {
Block sapling = hook.getSapling();
FruitTree tree = TreeTracker.getTreeAt(sapling.getX(), sapling.getY(), sapling.getZ(), CanaryFruitTrees.instance().getWorldForName(sapling.getWorld().getFqName()));
if (tree != null) {
tree.growTree();
hook.setCanceled();
}
}
@HookHandler
public final void worldLoad(LoadWorldHook hook) {
CanaryFruitTrees.instance().addLoadedWorld(hook.getWorld());
}
@HookHandler
public final void worldunload(UnloadWorldHook hook) {
TreeWorld tree_world = CanaryFruitTrees.instance().getWorldForName(hook.getWorld().getFqName());
if (tree_world != null) {
CanaryFruitTrees.instance().debug("World Unloaded: " + tree_world);
tree_world.unloadWorld();
}
}
private final void decreaseStack(Player player) {
if (player.getMode() != GameMode.CREATIVE) {
Item held = player.getItemHeld();
held.setAmount(held.getAmount() - 1);
if (held.getAmount() <= 0) {
player.getInventory().setSlot(held.getSlot(), null);
}
}
}
}
| true | true | public final void plantSeeds(BlockRightClickHook hook) {
if (hook.getBlockClicked().getType() == BlockType.Soil) {
Item seeds = hook.getPlayer().getItemHeld();
Block block = hook.getBlockClicked();
if (seeds.getMetaTag().containsKey("FruitTrees")) {
String type = seeds.getMetaTag().getCompoundTag("FruitTrees").getString("TreeType");
if (seeds.getType() == ItemType.MelonSeeds) {
if (type.equals("AppleSeeds")) {
if (CanaryFruitTrees.instance().getFruitTreesConfig().checkEnabled(TreeType.APPLE)) {
block.getWorld().setBlockAt(block.getPosition(), (short)3);
block.getWorld().setBlockAt(block.getX(), block.getY() + 1, block.getZ(), (short)6, TreeType.APPLE.getLogData());
FruitTree tree = new AppleTree(CanaryFruitTrees.instance(), block.getX(), block.getY() + 1, block.getZ(), CanaryFruitTrees.instance().getWorldForName(block.getWorld().getFqName()));
tree.save();
decreaseStack(hook.getPlayer());
hook.setCanceled();
}
}
else if (type.equals("GoldenAppleSeeds")) {
if (CanaryFruitTrees.instance().getFruitTreesConfig().checkEnabled(TreeType.GOLDEN_APPLE)) {
block.getWorld().setBlockAt(block.getPosition(), (short)3);
block.getWorld().setBlockAt(block.getX(), block.getY() + 1, block.getZ(), (short)6, TreeType.GOLDEN_APPLE.getLogData());
FruitTree tree = new GoldenAppleTree(CanaryFruitTrees.instance(), block.getX(), block.getY() + 1, block.getZ(), CanaryFruitTrees.instance().getWorldForName(block.getWorld().getFqName()));
tree.save();
decreaseStack(hook.getPlayer());
hook.setCanceled();
}
}
else if (type.equals("CoalSeeds")) {
if (CanaryFruitTrees.instance().getFruitTreesConfig().checkEnabled(TreeType.COAL)) {
block.getWorld().setBlockAt(block.getPosition(), (short)3);
block.getWorld().setBlockAt(block.getX(), block.getY() + 1, block.getZ(), (short)6, TreeType.COAL.getLogData());
FruitTree tree = new CoalTree(CanaryFruitTrees.instance(), block.getX(), block.getY() + 1, block.getZ(), CanaryFruitTrees.instance().getWorldForName(block.getWorld().getFqName()));
tree.save();
decreaseStack(hook.getPlayer());
hook.setCanceled();
}
}
}
else if (seeds.getType() == ItemType.PumpkinSeeds) {
if (type.equals("RecordSeeds")) {
block.getWorld().setBlockAt(block.getPosition(), (short)3);
block.getWorld().setBlockAt(block.getX(), block.getY() + 1, block.getZ(), (short)6, TreeType.RECORD.getLogData());
FruitTree tree = new RecordTree(CanaryFruitTrees.instance(), block.getX(), block.getY() + 1, block.getZ(), CanaryFruitTrees.instance().getWorldForName(block.getWorld().getFqName()));
tree.save();
decreaseStack(hook.getPlayer());
hook.setCanceled();
}
else if (type.equals("SpongeSeeds")) {
block.getWorld().setBlockAt(block.getPosition(), (short)3);
block.getWorld().setBlockAt(block.getX(), block.getY() + 1, block.getZ(), (short)6, TreeType.SPONGE.getLogData());
FruitTree tree = new SpongeTree(CanaryFruitTrees.instance(), block.getX(), block.getY() + 1, block.getZ(), CanaryFruitTrees.instance().getWorldForName(block.getWorld().getFqName()));
tree.save();
decreaseStack(hook.getPlayer());
hook.setCanceled();
}
}
else if (seeds.getType() == ItemType.Seeds) {
if (type.endsWith("DyeSeeds")) {
block.getWorld().setBlockAt(block.getPosition(), (short)3);
block.getWorld().setBlockAt(block.getX(), block.getY() + 1, block.getZ(), (short)6, TreeType.DYE_BLACK.getLogData());
FruitTree tree = new DyeTree(CanaryFruitTrees.instance(), block.getX(), block.getY() + 1, block.getZ(), CanaryFruitTrees.instance().getWorldForName(block.getWorld().getFqName()), seeds.getMetaTag().getCompoundTag("FruitTrees").getByte("DyeColor"));
tree.save();
decreaseStack(hook.getPlayer());
hook.setCanceled();
}
else if (type.equals("RedstoneSeeds")) {
block.getWorld().setBlockAt(block.getPosition(), (short)3);
block.getWorld().setBlockAt(block.getX(), block.getY() + 1, block.getZ(), (short)6, TreeType.REDSTONE.getLogData());
FruitTree tree = new RedstoneTree(CanaryFruitTrees.instance(), block.getX(), block.getY() + 1, block.getZ(), CanaryFruitTrees.instance().getWorldForName(block.getWorld().getFqName()));
tree.save();
decreaseStack(hook.getPlayer());
hook.setCanceled();
}
else if (type.equals("IronSeeds")) {
block.getWorld().setBlockAt(block.getPosition(), (short)3);
block.getWorld().setBlockAt(block.getX(), block.getY() + 1, block.getZ(), (short)6, TreeType.IRON.getLogData());
FruitTree tree = new IronTree(CanaryFruitTrees.instance(), block.getX(), block.getY() + 1, block.getZ(), CanaryFruitTrees.instance().getWorldForName(block.getWorld().getFqName()));
tree.save();
decreaseStack(hook.getPlayer());
hook.setCanceled();
}
else if (type.equals("GoldSeeds")) {
block.getWorld().setBlockAt(block.getPosition(), (short)3);
block.getWorld().setBlockAt(block.getX(), block.getY() + 1, block.getZ(), (short)6, TreeType.GOLD.getLogData());
FruitTree tree = new GoldTree(CanaryFruitTrees.instance(), block.getX(), block.getY() + 1, block.getZ(), CanaryFruitTrees.instance().getWorldForName(block.getWorld().getFqName()));
tree.save();
decreaseStack(hook.getPlayer());
hook.setCanceled();
}
else if (type.equals("DiamondSeeds")) {
block.getWorld().setBlockAt(block.getPosition(), (short)3);
block.getWorld().setBlockAt(block.getX(), block.getY() + 1, block.getZ(), (short)6, TreeType.GOLD.getLogData());
FruitTree tree = new DiamondTree(CanaryFruitTrees.instance(), block.getX(), block.getY() + 1, block.getZ(), CanaryFruitTrees.instance().getWorldForName(block.getWorld().getFqName()));
tree.save();
decreaseStack(hook.getPlayer());
hook.setCanceled();
}
else if (type.equals("EmeraldSeeds")) {
block.getWorld().setBlockAt(block.getPosition(), (short)3);
block.getWorld().setBlockAt(block.getX(), block.getY() + 1, block.getZ(), (short)6, TreeType.GOLD.getLogData());
FruitTree tree = new EmeraldTree(CanaryFruitTrees.instance(), block.getX(), block.getY() + 1, block.getZ(), CanaryFruitTrees.instance().getWorldForName(block.getWorld().getFqName()));
tree.save();
decreaseStack(hook.getPlayer());
hook.setCanceled();
}
else if (type.equals("CoalSeeds")) {
block.getWorld().setBlockAt(block.getPosition(), (short)3);
block.getWorld().setBlockAt(block.getX(), block.getY() + 1, block.getZ(), (short)6, TreeType.GOLD.getLogData());
FruitTree tree = new CoalTree(CanaryFruitTrees.instance(), block.getX(), block.getY() + 1, block.getZ(), CanaryFruitTrees.instance().getWorldForName(block.getWorld().getFqName()));
tree.save();
decreaseStack(hook.getPlayer());
hook.setCanceled();
}
}
}
}
}
| public final void plantSeeds(BlockRightClickHook hook) {
if (hook.getBlockClicked().getType() == BlockType.Soil) {
Item seeds = hook.getPlayer().getItemHeld();
Block block = hook.getBlockClicked();
if (seeds.hasMetaTag() && seeds.getMetaTag().containsKey("FruitTrees")) {
String type = seeds.getMetaTag().getCompoundTag("FruitTrees").getString("TreeType");
if (seeds.getType() == ItemType.MelonSeeds) {
if (type.equals("AppleSeeds")) {
if (CanaryFruitTrees.instance().getFruitTreesConfig().checkEnabled(TreeType.APPLE)) {
block.getWorld().setBlockAt(block.getPosition(), (short)3);
block.getWorld().setBlockAt(block.getX(), block.getY() + 1, block.getZ(), (short)6, TreeType.APPLE.getLogData());
FruitTree tree = new AppleTree(CanaryFruitTrees.instance(), block.getX(), block.getY() + 1, block.getZ(), CanaryFruitTrees.instance().getWorldForName(block.getWorld().getFqName()));
tree.save();
decreaseStack(hook.getPlayer());
hook.setCanceled();
}
}
else if (type.equals("GoldenAppleSeeds")) {
if (CanaryFruitTrees.instance().getFruitTreesConfig().checkEnabled(TreeType.GOLDEN_APPLE)) {
block.getWorld().setBlockAt(block.getPosition(), (short)3);
block.getWorld().setBlockAt(block.getX(), block.getY() + 1, block.getZ(), (short)6, TreeType.GOLDEN_APPLE.getLogData());
FruitTree tree = new GoldenAppleTree(CanaryFruitTrees.instance(), block.getX(), block.getY() + 1, block.getZ(), CanaryFruitTrees.instance().getWorldForName(block.getWorld().getFqName()));
tree.save();
decreaseStack(hook.getPlayer());
hook.setCanceled();
}
}
else if (type.equals("CoalSeeds")) {
if (CanaryFruitTrees.instance().getFruitTreesConfig().checkEnabled(TreeType.COAL)) {
block.getWorld().setBlockAt(block.getPosition(), (short)3);
block.getWorld().setBlockAt(block.getX(), block.getY() + 1, block.getZ(), (short)6, TreeType.COAL.getLogData());
FruitTree tree = new CoalTree(CanaryFruitTrees.instance(), block.getX(), block.getY() + 1, block.getZ(), CanaryFruitTrees.instance().getWorldForName(block.getWorld().getFqName()));
tree.save();
decreaseStack(hook.getPlayer());
hook.setCanceled();
}
}
}
else if (seeds.getType() == ItemType.PumpkinSeeds) {
if (type.equals("RecordSeeds")) {
block.getWorld().setBlockAt(block.getPosition(), (short)3);
block.getWorld().setBlockAt(block.getX(), block.getY() + 1, block.getZ(), (short)6, TreeType.RECORD.getLogData());
FruitTree tree = new RecordTree(CanaryFruitTrees.instance(), block.getX(), block.getY() + 1, block.getZ(), CanaryFruitTrees.instance().getWorldForName(block.getWorld().getFqName()));
tree.save();
decreaseStack(hook.getPlayer());
hook.setCanceled();
}
else if (type.equals("SpongeSeeds")) {
block.getWorld().setBlockAt(block.getPosition(), (short)3);
block.getWorld().setBlockAt(block.getX(), block.getY() + 1, block.getZ(), (short)6, TreeType.SPONGE.getLogData());
FruitTree tree = new SpongeTree(CanaryFruitTrees.instance(), block.getX(), block.getY() + 1, block.getZ(), CanaryFruitTrees.instance().getWorldForName(block.getWorld().getFqName()));
tree.save();
decreaseStack(hook.getPlayer());
hook.setCanceled();
}
}
else if (seeds.getType() == ItemType.Seeds) {
if (type.endsWith("DyeSeeds")) {
block.getWorld().setBlockAt(block.getPosition(), (short)3);
block.getWorld().setBlockAt(block.getX(), block.getY() + 1, block.getZ(), (short)6, TreeType.DYE_BLACK.getLogData());
FruitTree tree = new DyeTree(CanaryFruitTrees.instance(), block.getX(), block.getY() + 1, block.getZ(), CanaryFruitTrees.instance().getWorldForName(block.getWorld().getFqName()), seeds.getMetaTag().getCompoundTag("FruitTrees").getByte("DyeColor"));
tree.save();
decreaseStack(hook.getPlayer());
hook.setCanceled();
}
else if (type.equals("RedstoneSeeds")) {
block.getWorld().setBlockAt(block.getPosition(), (short)3);
block.getWorld().setBlockAt(block.getX(), block.getY() + 1, block.getZ(), (short)6, TreeType.REDSTONE.getLogData());
FruitTree tree = new RedstoneTree(CanaryFruitTrees.instance(), block.getX(), block.getY() + 1, block.getZ(), CanaryFruitTrees.instance().getWorldForName(block.getWorld().getFqName()));
tree.save();
decreaseStack(hook.getPlayer());
hook.setCanceled();
}
else if (type.equals("IronSeeds")) {
block.getWorld().setBlockAt(block.getPosition(), (short)3);
block.getWorld().setBlockAt(block.getX(), block.getY() + 1, block.getZ(), (short)6, TreeType.IRON.getLogData());
FruitTree tree = new IronTree(CanaryFruitTrees.instance(), block.getX(), block.getY() + 1, block.getZ(), CanaryFruitTrees.instance().getWorldForName(block.getWorld().getFqName()));
tree.save();
decreaseStack(hook.getPlayer());
hook.setCanceled();
}
else if (type.equals("GoldSeeds")) {
block.getWorld().setBlockAt(block.getPosition(), (short)3);
block.getWorld().setBlockAt(block.getX(), block.getY() + 1, block.getZ(), (short)6, TreeType.GOLD.getLogData());
FruitTree tree = new GoldTree(CanaryFruitTrees.instance(), block.getX(), block.getY() + 1, block.getZ(), CanaryFruitTrees.instance().getWorldForName(block.getWorld().getFqName()));
tree.save();
decreaseStack(hook.getPlayer());
hook.setCanceled();
}
else if (type.equals("DiamondSeeds")) {
block.getWorld().setBlockAt(block.getPosition(), (short)3);
block.getWorld().setBlockAt(block.getX(), block.getY() + 1, block.getZ(), (short)6, TreeType.GOLD.getLogData());
FruitTree tree = new DiamondTree(CanaryFruitTrees.instance(), block.getX(), block.getY() + 1, block.getZ(), CanaryFruitTrees.instance().getWorldForName(block.getWorld().getFqName()));
tree.save();
decreaseStack(hook.getPlayer());
hook.setCanceled();
}
else if (type.equals("EmeraldSeeds")) {
block.getWorld().setBlockAt(block.getPosition(), (short)3);
block.getWorld().setBlockAt(block.getX(), block.getY() + 1, block.getZ(), (short)6, TreeType.GOLD.getLogData());
FruitTree tree = new EmeraldTree(CanaryFruitTrees.instance(), block.getX(), block.getY() + 1, block.getZ(), CanaryFruitTrees.instance().getWorldForName(block.getWorld().getFqName()));
tree.save();
decreaseStack(hook.getPlayer());
hook.setCanceled();
}
else if (type.equals("CoalSeeds")) {
block.getWorld().setBlockAt(block.getPosition(), (short)3);
block.getWorld().setBlockAt(block.getX(), block.getY() + 1, block.getZ(), (short)6, TreeType.GOLD.getLogData());
FruitTree tree = new CoalTree(CanaryFruitTrees.instance(), block.getX(), block.getY() + 1, block.getZ(), CanaryFruitTrees.instance().getWorldForName(block.getWorld().getFqName()));
tree.save();
decreaseStack(hook.getPlayer());
hook.setCanceled();
}
}
}
}
}
|
diff --git a/src/com/vloxlands/util/RenderAssistant.java b/src/com/vloxlands/util/RenderAssistant.java
index 4f007bb..83cb5cf 100644
--- a/src/com/vloxlands/util/RenderAssistant.java
+++ b/src/com/vloxlands/util/RenderAssistant.java
@@ -1,395 +1,396 @@
package com.vloxlands.util;
import static org.lwjgl.opengl.GL11.*;
import java.awt.Font;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.nio.FloatBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.NoSuchElementException;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.ARBShaderObjects;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL20;
import org.lwjgl.util.vector.Vector2f;
import org.lwjgl.util.vector.Vector3f;
import org.newdawn.slick.Color;
import org.newdawn.slick.TrueTypeFont;
import org.newdawn.slick.opengl.Texture;
import org.newdawn.slick.opengl.TextureImpl;
import org.newdawn.slick.opengl.TextureLoader;
import com.vloxlands.render.util.ShaderLoader;
import com.vloxlands.settings.CFG;
//import render.Model;
//import util.math.MathHelper;
public class RenderAssistant
{
public static HashMap<String, Texture> textures = new HashMap<>();
private static HashMap<TextureRegion, Texture> textureRegions = new HashMap<>();
private static HashMap<String, TextureAtlas> textureAtlases = new HashMap<>();
private static HashMap<Integer, HashMap<String, Integer>> uniformPosition = new HashMap<>();
// public static HashMap<String, Model> models = new HashMap<>();
public static void storeTexture(String path)
{
Texture t = loadTexture(path);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
textures.put(path, t);
}
public static void bindTextureRegion(String path, int x, int y, int width, int height)
{
TextureRegion tr = new TextureRegion(path, x, y, width, height);
Texture t = textureRegions.get(tr);
if (t != null)
{
t.bind();
}
else
{
Texture tex = tr.loadTexture();
textureRegions.put(tr, tex);
tex.bind();
}
}
public static void storeTextureAtlas(String path, int cw, int ch)
{
if (!textureAtlases.containsKey(path)) textureAtlases.put(path, new TextureAtlas(path, cw, ch));
}
public static void bindTextureAtlasTile(String path, int x, int y)
{
if (!textureAtlases.containsKey(path)) throw new NoSuchElementException(" texture atlas " + path);
else textureAtlases.get(path).getTile(x, y).bind();
}
public static void bindTexture(String path)
{
if (path == null) return;
Texture t = textures.get(path);
if (t != null) t.bind();// glBindTexture(GL_TEXTURE_2D, t.getTextureID());
else
{
t = loadTexture(path);
t.bind();// glBindTexture(GL_TEXTURE_2D, t.getTextureID());
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
textures.put(path, t);
}
}
// /**
// * Returns a model. If it doesn't exist the method will try to load it
// * @param path The path to the model file
// * @return The model / null if the model could not be loaded
// */
// public static Model getModel(String path)
// {
// Model m = models.get(path);
// if(m == null)
// {
// models.put(path, ModelLoader.loadModel(path));
// m = models.get(path);
// }
// return m;
// }
// /**
// * Renders a model at the GL-coordinate-origin. If it doesn't exist the
// method will try to load the model
// * @param path The path to the model file
// */
// public static void renderModel(String path)
// {
// getModel(path).renderModel();
// }
private static Texture loadTexture(String path)
{
try
{
return TextureLoader.getTexture(".png", RenderAssistant.class.getResourceAsStream(path));
}
catch (Exception e)
{
CFG.p(path);
e.printStackTrace();
}
return null;
}
public static void renderRect(float posX, float posY, float sizeX, float sizeY)
{
renderRect(posX, posY, sizeX, sizeY, 1, 1);
}
public static void renderRect(float posX, float posY, float sizeX, float sizeY, float texSizeX, float texSizeY)
{
renderRect(posX, posY, sizeX, sizeY, 0, 0, texSizeX, texSizeY);
}
public static void renderRect(float posX, float posY, float sizeX, float sizeY, float texPosX, float texPosY, float texSizeX, float texSizeY)
{
glPushMatrix();
{
glDisable(GL_CULL_FACE);
GL11.glBegin(GL11.GL_QUADS);
{
GL11.glTexCoord2d(texPosX, texPosY + texSizeY);
GL11.glVertex2f(posX, posY + sizeY);
GL11.glTexCoord2d(texPosX + texSizeX, texPosY + texSizeY);
GL11.glVertex2f(posX + sizeX, posY + sizeY);
GL11.glTexCoord2d(texPosX + texSizeX, texPosY);
GL11.glVertex2f(posX + sizeX, posY);
GL11.glTexCoord2d(texPosX, texPosY);
GL11.glVertex2f(posX, posY);
}
GL11.glEnd();
}
glPopMatrix();
}
public static void renderText(float x, float y, String text, Font f)
{
TextureImpl.bindNone();
glEnable(GL_BLEND);
FloatBuffer fb = BufferUtils.createFloatBuffer(16);
glGetFloat(GL_CURRENT_COLOR, fb);
FontAssistant.getFont(f).drawString(x, y, text, new Color(fb));
glDisable(GL_BLEND);
}
public static void set2DRenderMode(boolean t)
{
if (t)
{
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glOrtho(0.0, Display.getWidth(), Display.getHeight(), 0.0, -1.0, 10.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glClear(GL_DEPTH_BUFFER_BIT);
glDisable(GL_TEXTURE_2D);
glShadeModel(GL_SMOOTH);
glDisable(GL_DEPTH_TEST);
}
else
{
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
}
}
public static void glColorHex(String hex, float alpha)
{
glColor4f(Integer.parseInt(hex.substring(0, 2), 16) / 255f, Integer.parseInt(hex.substring(2, 4), 16) / 255f, Integer.parseInt(hex.substring(4, 6), 16) / 255f, alpha);
}
public static void enable(int key)
{
if (key == GL_LIGHTING)
{
int location = GL20.glGetUniformLocation(ShaderLoader.getCurrentProgram(), "lighting");
ARBShaderObjects.glUniform1fARB(location, 1);
}
}
public static void disable(int key)
{
if (key == GL_LIGHTING)
{
int location = GL20.glGetUniformLocation(ShaderLoader.getCurrentProgram(), "lighting");
ARBShaderObjects.glUniform1fARB(location, 0);
}
}
public static int getUniformLocation(String name)
{
CFG.p(ShaderLoader.getCurrentProgram());
HashMap<String, Integer> h = uniformPosition.get(ShaderLoader.getCurrentProgram());
if (h == null) h = new HashMap<>();
if (h.get(name) == null) h.put(name, GL20.glGetUniformLocation(ShaderLoader.getCurrentProgram(), name));
return h.get(name);
}
public static void setUniform1f(String name, float value)
{
ARBShaderObjects.glUniform1fARB(getUniformLocation(name), value);
}
public static void setUniform2f(String name, Vector2f v)
{
setUniform2f(name, v.x, v.y);
}
public static void setUniform2f(String name, float a, float b)
{
ARBShaderObjects.glUniform2fARB(getUniformLocation(name), a, b);
}
public static void setUniform3f(String name, Vector3f v)
{
setUniform3f(name, v.x, v.y, v.z);
}
public static void setUniform3f(String name, float a, float b, float c)
{
ARBShaderObjects.glUniform3fARB(getUniformLocation(name), a, b, c);
}
public static BufferedImage toBufferedImage(Image img)
{
BufferedImage image = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
image.getGraphics().drawImage(img, 0, 0, null);
return image;
}
// -- 2D GUI Helper functions -- //
public static void renderOutline(int x, int y, int width, int height, boolean doubled)
{
glEnable(GL_BLEND);
bindTexture("/graphics/textures/ui/gui.png");
int cornerSize = (doubled) ? 24 : 19;
int lineThickness = (doubled) ? 17 : 12;
int lineHeight = (doubled) ? 55 : 59;
int lineWidth = (doubled) ? 73 : 74;
// x1 y1 y2 x2
int[] c = (doubled) ? new int[] { 856, 189, 294, 978 } : new int[] { 865, 398, 498, 982 };
int[] m = (doubled) ? new int[] { 893, 227, 301, 985 } : new int[] { 899, 428, 505, 989 };
renderRect(x, y, cornerSize, cornerSize, c[0] / 1024f, c[1] / 1024f, cornerSize / 1024f, cornerSize / 1024f); // lt
for (int i = 0; i < (width - cornerSize * 2) / lineWidth; i++)
renderRect(x + cornerSize + i * lineWidth, y, lineWidth, lineThickness, m[0] / 1024f, c[1] / 1024f, lineWidth / 1024f, lineThickness / 1024f); // mt
renderRect(x + cornerSize + (width - cornerSize * 2) / lineWidth * lineWidth, y, (width - cornerSize * 2) % lineWidth, lineThickness, m[0] / 1024.0f, c[1] / 1024.0f, ((width - cornerSize * 2) % lineWidth) / 1024.0f, lineThickness / 1024.0f);
renderRect(x + width - cornerSize, y, cornerSize, cornerSize, c[3] / 1024f, c[1] / 1024f, cornerSize / 1024f, cornerSize / 1024f); // rt
for (int i = 0; i < (height - cornerSize * 2) / lineHeight; i++)
renderRect(x, y + cornerSize + i * lineHeight, lineThickness, lineHeight, c[0] / 1024f, m[1] / 1024f, lineThickness / 1024f, lineHeight / 1024f); // ml
renderRect(x, y + cornerSize + (height - cornerSize * 2) / lineHeight * lineHeight, lineThickness, (height - cornerSize * 2) % lineHeight, c[0] / 1024.0f, m[1] / 1024.0f, lineThickness / 1024.0f, ((height - cornerSize * 2) % lineHeight) / 1024.0f);
for (int i = 0; i < (height - cornerSize * 2) / lineHeight; i++)
renderRect(x + width - lineThickness, y + cornerSize + i * lineHeight, lineThickness, lineHeight, m[3] / 1024f, m[1] / 1024f, lineThickness / 1024f, lineHeight / 1024f); // mr
renderRect(x + width - lineThickness, y + cornerSize + (height - cornerSize * 2) / lineHeight * lineHeight, lineThickness, (height - cornerSize * 2) % lineHeight, m[3] / 1024.0f, m[1] / 1024.0f, lineThickness / 1024.0f, ((height - cornerSize * 2) % lineHeight) / 1024.0f);
renderRect(x, y + height - cornerSize, cornerSize, cornerSize, c[0] / 1024f, c[2] / 1024f, cornerSize / 1024f, cornerSize / 1024f); // lb
for (int i = 0; i < (width - cornerSize * 2) / lineWidth; i++)
renderRect(x + cornerSize + i * lineWidth, y + height - lineThickness, lineWidth, lineThickness, m[0] / 1024f, m[2] / 1024f, lineWidth / 1024f, lineThickness / 1024f); // mb
renderRect(x + cornerSize + (width - cornerSize * 2) / lineWidth * lineWidth, y + height - lineThickness, (width - cornerSize * 2) % lineWidth, lineThickness, m[0] / 1024.0f, m[2] / 1024.0f, ((width - cornerSize * 2) % lineWidth) / 1024.0f, lineThickness / 1024.0f);
renderRect(x + width - cornerSize, y + height - cornerSize, cornerSize, cornerSize, c[3] / 1024f, c[2] / 1024f, cornerSize / 1024f, cornerSize / 1024f); // rb
glDisable(GL_BLEND);
}
public static void renderContainer(int x, int y, int width, int height, boolean doubled)
{
glPushMatrix();
{
glEnable(GL_BLEND);
glColor4f(0.4f, 0.4f, 0.4f, 0.6f);
glBindTexture(GL_TEXTURE_2D, 0);
TextureImpl.unbind();
TextureImpl.bindNone();
RenderAssistant.renderRect(x + 5, y + 5, width - 10, height - 10);
glColor4f(1, 1, 1, 1);
bindTexture("/graphics/textures/ui/gui.png");
RenderAssistant.renderOutline(x, y, width, height, doubled);
glDisable(GL_BLEND);
}
glPopMatrix();
}
public static void renderLine(int x, int y, int length, boolean horizontal, boolean doubled)
{
glEnable(GL_BLEND);
bindTexture("/graphics/textures/ui/gui.png");
int height = (doubled) ? 17 : 12;
int width = length;
int lineLength = (doubled) ? 73 : 74;
// if (!horizontal)
// {
// width = height;
// height = length;
// }
// x1 y1 x2
// x3 y2 x4
int[] c = (doubled) ? new int[] { 849, 155, 897 } : new int[] { 845, 363, 887 };
// x1 y1
// x2 y2
int[] m = (doubled) ? new int[] { 893, 189 } : new int[] { 899, 398 };
if (!horizontal)
{
glTranslatef(x, y, 0);
glRotatef(90, 0, 0, 1);
glTranslatef(-x, -y, 0);
}
renderRect(x, y, 15, height, c[0] / 1024f, c[1] / 1024f, 15 / 1024f, height / 1024f);
for (int i = 0; i < width / lineLength; i++)
renderRect(x + i * lineLength + 15, y, lineLength, height, m[0] / 1024f, m[1] / 1024f, lineLength / 1024f, height / 1024f);
renderRect(x + 15 + ((width - 30) / lineLength * lineLength), y, (width - 30) % lineLength, height, m[0] / 1024f, m[1] / 1024f, ((width - 30) % lineLength) / 1024f, height / 1024f);
renderRect(x + width - 15, y, 15, height, c[2] / 1024f, c[1] / 1024f, 15 / 1024f, height / 1024f);
- // }
- // else
- // {
- //
- // }
+ if (!horizontal)
+ {
+ glTranslatef(x, y, 0);
+ glRotatef(-90, 0, 0, 1);
+ glTranslatef(-x, -y, 0);
+ }
glDisable(GL_BLEND);
}
public static String[] wrap(String raw, Font f, int width)
{
ArrayList<String> lines = new ArrayList<>();
TrueTypeFont ttf = FontAssistant.getFont(f);
String cpy = raw;
while (cpy.length() > 0)
{
int length = 0;
for (int i = 0; i < cpy.length(); i++)
{
int wdth = ttf.getWidth(cpy.substring(0, i));
if (wdth < width) length++;
else break;
}
String line = cpy.substring(0, length);
lines.add(line);
cpy = cpy.substring(length);
}
return lines.toArray(new String[] {});
}
}
| true | true | public static void renderLine(int x, int y, int length, boolean horizontal, boolean doubled)
{
glEnable(GL_BLEND);
bindTexture("/graphics/textures/ui/gui.png");
int height = (doubled) ? 17 : 12;
int width = length;
int lineLength = (doubled) ? 73 : 74;
// if (!horizontal)
// {
// width = height;
// height = length;
// }
// x1 y1 x2
// x3 y2 x4
int[] c = (doubled) ? new int[] { 849, 155, 897 } : new int[] { 845, 363, 887 };
// x1 y1
// x2 y2
int[] m = (doubled) ? new int[] { 893, 189 } : new int[] { 899, 398 };
if (!horizontal)
{
glTranslatef(x, y, 0);
glRotatef(90, 0, 0, 1);
glTranslatef(-x, -y, 0);
}
renderRect(x, y, 15, height, c[0] / 1024f, c[1] / 1024f, 15 / 1024f, height / 1024f);
for (int i = 0; i < width / lineLength; i++)
renderRect(x + i * lineLength + 15, y, lineLength, height, m[0] / 1024f, m[1] / 1024f, lineLength / 1024f, height / 1024f);
renderRect(x + 15 + ((width - 30) / lineLength * lineLength), y, (width - 30) % lineLength, height, m[0] / 1024f, m[1] / 1024f, ((width - 30) % lineLength) / 1024f, height / 1024f);
renderRect(x + width - 15, y, 15, height, c[2] / 1024f, c[1] / 1024f, 15 / 1024f, height / 1024f);
// }
// else
// {
//
// }
glDisable(GL_BLEND);
}
| public static void renderLine(int x, int y, int length, boolean horizontal, boolean doubled)
{
glEnable(GL_BLEND);
bindTexture("/graphics/textures/ui/gui.png");
int height = (doubled) ? 17 : 12;
int width = length;
int lineLength = (doubled) ? 73 : 74;
// if (!horizontal)
// {
// width = height;
// height = length;
// }
// x1 y1 x2
// x3 y2 x4
int[] c = (doubled) ? new int[] { 849, 155, 897 } : new int[] { 845, 363, 887 };
// x1 y1
// x2 y2
int[] m = (doubled) ? new int[] { 893, 189 } : new int[] { 899, 398 };
if (!horizontal)
{
glTranslatef(x, y, 0);
glRotatef(90, 0, 0, 1);
glTranslatef(-x, -y, 0);
}
renderRect(x, y, 15, height, c[0] / 1024f, c[1] / 1024f, 15 / 1024f, height / 1024f);
for (int i = 0; i < width / lineLength; i++)
renderRect(x + i * lineLength + 15, y, lineLength, height, m[0] / 1024f, m[1] / 1024f, lineLength / 1024f, height / 1024f);
renderRect(x + 15 + ((width - 30) / lineLength * lineLength), y, (width - 30) % lineLength, height, m[0] / 1024f, m[1] / 1024f, ((width - 30) % lineLength) / 1024f, height / 1024f);
renderRect(x + width - 15, y, 15, height, c[2] / 1024f, c[1] / 1024f, 15 / 1024f, height / 1024f);
if (!horizontal)
{
glTranslatef(x, y, 0);
glRotatef(-90, 0, 0, 1);
glTranslatef(-x, -y, 0);
}
glDisable(GL_BLEND);
}
|
diff --git a/test/siver/agents/BoatHouseTest.java b/test/siver/agents/BoatHouseTest.java
index ad5e2ec..c8c48b3 100644
--- a/test/siver/agents/BoatHouseTest.java
+++ b/test/siver/agents/BoatHouseTest.java
@@ -1,87 +1,88 @@
package siver.agents;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;
import org.easymock.EasyMock;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import repast.simphony.context.Context;
import repast.simphony.space.continuous.ContinuousSpace;
import repast.simphony.space.continuous.NdPoint;
import siver.LanedTest;
import siver.agents.boat.BoatAgent;
import siver.agents.boat.BoatCorner;
import siver.agents.boat.CoxAgent;
import siver.river.River;
import siver.river.lane.Lane.UnstartedLaneException;
public class BoatHouseTest extends LanedTest {
private static River r;
private Context<Object> mockContext;
private ContinuousSpace<Object> mockSpace;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
createLanes();
r = new River(up, mid, down);
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Before
public void setUp() throws Exception {
mockContext = EasyMock.createMock(Context.class);
mockSpace = EasyMock.createMock(ContinuousSpace.class);
}
@After
public void tearDown() throws Exception {
}
@Test
public void testBoatHouse() {
replay(mockContext);
replay(mockSpace);
new BoatHouse(r, mockContext, mockSpace);
verify(mockContext);
verify(mockSpace);
}
@Test
public void testLaunchBoat() {
expect(mockContext.add(anyObject(BoatAgent.class))).andReturn(true).times(1);
expect(mockContext.add(anyObject(CoxAgent.class))).andReturn(true).times(1);
expect(mockContext.add(anyObject(BoatCorner.class))).andReturn(true).times(4);
expect(mockSpace.moveTo(anyObject(BoatAgent.class), eq(0.0), eq(10.0))).andReturn(true).times(1);
- expect(mockSpace.getLocation(anyObject(BoatAgent.class))).andReturn(new NdPoint(0,10)).times(1);
+ expect(mockSpace.getLocation(anyObject(BoatAgent.class))).andReturn(new NdPoint(0,10)).times(3);
expect(mockSpace.getDisplacement(new NdPoint(0,10), new NdPoint(20,10))).andReturn(new double[]{20,0}).times(1);
+ expect(mockSpace.moveByVector(anyObject(BoatAgent.class), eq(0.0), eq(0.0), eq(0.0))).andReturn(new NdPoint(0,10)).once();
replay(mockContext);
replay(mockSpace);
BoatHouse bh = new BoatHouse(r, mockContext, mockSpace);
bh.launchBoat();
verify(mockContext);
verify(mockSpace);
}
@Test
public void testGetLaunchLane() throws UnstartedLaneException {
replay(mockContext);
replay(mockSpace);
BoatHouse bh = new BoatHouse(r, mockContext, mockSpace);
assertEquals(down, bh.getLaunchLane());
verify(mockContext);
verify(mockSpace);
}
}
| false | true | public void testLaunchBoat() {
expect(mockContext.add(anyObject(BoatAgent.class))).andReturn(true).times(1);
expect(mockContext.add(anyObject(CoxAgent.class))).andReturn(true).times(1);
expect(mockContext.add(anyObject(BoatCorner.class))).andReturn(true).times(4);
expect(mockSpace.moveTo(anyObject(BoatAgent.class), eq(0.0), eq(10.0))).andReturn(true).times(1);
expect(mockSpace.getLocation(anyObject(BoatAgent.class))).andReturn(new NdPoint(0,10)).times(1);
expect(mockSpace.getDisplacement(new NdPoint(0,10), new NdPoint(20,10))).andReturn(new double[]{20,0}).times(1);
replay(mockContext);
replay(mockSpace);
BoatHouse bh = new BoatHouse(r, mockContext, mockSpace);
bh.launchBoat();
verify(mockContext);
verify(mockSpace);
}
| public void testLaunchBoat() {
expect(mockContext.add(anyObject(BoatAgent.class))).andReturn(true).times(1);
expect(mockContext.add(anyObject(CoxAgent.class))).andReturn(true).times(1);
expect(mockContext.add(anyObject(BoatCorner.class))).andReturn(true).times(4);
expect(mockSpace.moveTo(anyObject(BoatAgent.class), eq(0.0), eq(10.0))).andReturn(true).times(1);
expect(mockSpace.getLocation(anyObject(BoatAgent.class))).andReturn(new NdPoint(0,10)).times(3);
expect(mockSpace.getDisplacement(new NdPoint(0,10), new NdPoint(20,10))).andReturn(new double[]{20,0}).times(1);
expect(mockSpace.moveByVector(anyObject(BoatAgent.class), eq(0.0), eq(0.0), eq(0.0))).andReturn(new NdPoint(0,10)).once();
replay(mockContext);
replay(mockSpace);
BoatHouse bh = new BoatHouse(r, mockContext, mockSpace);
bh.launchBoat();
verify(mockContext);
verify(mockSpace);
}
|
diff --git a/core/src/main/java/org/jclouds/http/handlers/BackoffLimitedRetryHandler.java b/core/src/main/java/org/jclouds/http/handlers/BackoffLimitedRetryHandler.java
index 73fbbd2c00..5915de99b7 100644
--- a/core/src/main/java/org/jclouds/http/handlers/BackoffLimitedRetryHandler.java
+++ b/core/src/main/java/org/jclouds/http/handlers/BackoffLimitedRetryHandler.java
@@ -1,141 +1,141 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jclouds.http.handlers;
import static org.jclouds.http.HttpUtils.releasePayload;
import java.io.IOException;
import javax.annotation.Resource;
import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.Constants;
import org.jclouds.http.HttpCommand;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.HttpRetryHandler;
import org.jclouds.http.IOExceptionRetryHandler;
import org.jclouds.http.TransformingHttpCommand;
import org.jclouds.logging.Logger;
import com.google.common.base.Throwables;
import com.google.inject.Inject;
/**
* Allow replayable request to be retried a limited number of times, and impose an exponential
* back-off delay before returning.
* <p>
* The back-off delay grows rapidly according to the formula
* <code>50 * (<i>{@link TransformingHttpCommand#getFailureCount()}</i> ^ 2)</code>. For example:
* <table>
* <tr>
* <th>Number of Attempts</th>
* <th>Delay in milliseconds</th>
* </tr>
* <tr>
* <td>1</td>
* <td>50</td>
* </tr>
* <tr>
* <td>2</td>
* <td>200</td>
* </tr>
* <tr>
* <td>3</td>
* <td>450</td>
* </tr>
* <tr>
* <td>4</td>
* <td>800</td>
* </tr>
* <tr>
* <td>5</td>
* <td>1250</td>
* </tr>
* </table>
* <p>
* This implementation has two side-effects. It increments the command's failure count with
* {@link TransformingHttpCommand#incrementFailureCount()}, because this failure count value is used
* to determine how many times the command has already been tried. It also closes the response's
* content input stream to ensure connections are cleaned up.
*
* @author James Murty
*/
@Singleton
public class BackoffLimitedRetryHandler implements HttpRetryHandler, IOExceptionRetryHandler {
public static BackoffLimitedRetryHandler INSTANCE = new BackoffLimitedRetryHandler();
@Inject(optional = true)
@Named(Constants.PROPERTY_MAX_RETRIES)
private int retryCountLimit = 5;
@Inject(optional = true)
@Named(Constants.PROPERTY_RETRY_DELAY_START)
private long delayStart = 50L;
@Resource
protected Logger logger = Logger.NULL;
public boolean shouldRetryRequest(HttpCommand command, IOException error) {
return ifReplayableBackoffAndReturnTrue(command);
}
public boolean shouldRetryRequest(HttpCommand command, HttpResponse response) {
releasePayload(response);
return ifReplayableBackoffAndReturnTrue(command);
}
private boolean ifReplayableBackoffAndReturnTrue(HttpCommand command) {
command.incrementFailureCount();
if (!command.isReplayable()) {
- logger.warn("Cannot retry after server error, command is not replayable: %1$s", command);
+ logger.error("Cannot retry after server error, command is not replayable: %1$s", command);
return false;
} else if (command.getFailureCount() > retryCountLimit) {
- logger.warn("Cannot retry after server error, command has exceeded retry limit %1$d: %2$s", retryCountLimit,
+ logger.error("Cannot retry after server error, command has exceeded retry limit %1$d: %2$s", retryCountLimit,
command);
return false;
} else {
imposeBackoffExponentialDelay(command.getFailureCount(), "server error: " + command.toString());
return true;
}
}
public void imposeBackoffExponentialDelay(int failureCount, String commandDescription) {
imposeBackoffExponentialDelay(delayStart, 2, failureCount, retryCountLimit, commandDescription);
}
public void imposeBackoffExponentialDelay(long period, int pow, int failureCount, int max, String commandDescription) {
imposeBackoffExponentialDelay(period, period * 10l, pow, failureCount, max, commandDescription);
}
public void imposeBackoffExponentialDelay(long period, long maxPeriod, int pow, int failureCount, int max,
String commandDescription) {
long delayMs = (long) (period * Math.pow(failureCount, pow));
delayMs = delayMs > maxPeriod ? maxPeriod : delayMs;
logger.debug("Retry %d/%d: delaying for %d ms: %s", failureCount, max, delayMs, commandDescription);
try {
Thread.sleep(delayMs);
} catch (InterruptedException e) {
Throwables.propagate(e);
}
}
}
| false | true | private boolean ifReplayableBackoffAndReturnTrue(HttpCommand command) {
command.incrementFailureCount();
if (!command.isReplayable()) {
logger.warn("Cannot retry after server error, command is not replayable: %1$s", command);
return false;
} else if (command.getFailureCount() > retryCountLimit) {
logger.warn("Cannot retry after server error, command has exceeded retry limit %1$d: %2$s", retryCountLimit,
command);
return false;
} else {
imposeBackoffExponentialDelay(command.getFailureCount(), "server error: " + command.toString());
return true;
}
}
| private boolean ifReplayableBackoffAndReturnTrue(HttpCommand command) {
command.incrementFailureCount();
if (!command.isReplayable()) {
logger.error("Cannot retry after server error, command is not replayable: %1$s", command);
return false;
} else if (command.getFailureCount() > retryCountLimit) {
logger.error("Cannot retry after server error, command has exceeded retry limit %1$d: %2$s", retryCountLimit,
command);
return false;
} else {
imposeBackoffExponentialDelay(command.getFailureCount(), "server error: " + command.toString());
return true;
}
}
|
diff --git a/Code/src/no/ntnu/fp/gui/WeekSheetAdapter.java b/Code/src/no/ntnu/fp/gui/WeekSheetAdapter.java
index 3fcb89b..9e0b8d8 100644
--- a/Code/src/no/ntnu/fp/gui/WeekSheetAdapter.java
+++ b/Code/src/no/ntnu/fp/gui/WeekSheetAdapter.java
@@ -1,157 +1,157 @@
package no.ntnu.fp.gui;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import no.ntnu.fp.gui.timepicker.DateModel;
import no.ntnu.fp.model.Appointment;
import no.ntnu.fp.model.Calendar;
import no.ntnu.fp.model.CalendarEntry;
import no.ntnu.fp.model.Meeting;
import no.ntnu.fp.model.User;
import no.ntnu.fp.model.Meeting.State;
import no.ntnu.fp.net.network.client.CommunicationController;
import no.ntnu.fp.util.Log;
public class WeekSheetAdapter implements Iterable<CalendarEntryView>, PropertyChangeListener {
private Calendar calendar;
private PropertyChangeSupport pcs = new PropertyChangeSupport(this);
List<Calendar> calendars = new ArrayList<Calendar>();
DateModel dateModel;
public WeekSheetAdapter(DateModel dateModel, Calendar calendar) {
this.dateModel = dateModel;
this.calendar = calendar;
calendar.addPropertyChangeListener(this);
}
public void addCalendar(Calendar calendar) {
calendars.add(calendar);
calendar.addPropertyChangeListener(this);
}
public void removeCalendar(Calendar calendar) {
calendars.remove(calendar);
calendar.removePropertyChangeListener(this);
}
public List<CalendarEntryView> getEntryViews(){
//TODO bgcolor entryviews equal to entryviews from the same calendar
List<CalendarEntryView> entries = new ArrayList<CalendarEntryView>();
for(CalendarEntry calendarEntry: calendar){
if((calendarEntry.getYear()+1900) == dateModel.getYear() && calendarEntry.getWeek() == dateModel.getWeek()){
if (calendarEntry instanceof Meeting) {
Meeting m = (Meeting) calendarEntry;
User user = CommunicationController.getInstance().getUser();
if (m.getOwner().equals(user) || m.getState(user) == State.Accepted) {
CalendarEntryView view = new CalendarEntryView(calendarEntry);
view.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
super.mouseClicked(e);
CalendarEntry ce = ((CalendarEntryView)e.getSource()).getModel();
Meeting m = (Meeting) ce;
- if (m.getOwner() == CommunicationController.getInstance().getUser()) {
+ if (m.getOwner().equals(CommunicationController.getInstance().getUser())) {
new MeetingFrame(m);
} else {
new MeetingInviteFrame(m);
}
}
});
entries.add(view);
}
}
if (calendarEntry instanceof Appointment) {
CalendarEntryView view = new CalendarEntryView(calendarEntry);
view.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
super.mouseClicked(e);
CalendarEntry ce = ((CalendarEntryView)e.getSource()).getModel();
new AppointmentPanel((Appointment) ce);
}
});
entries.add(view);
}
}
}
/*for(Calendar calendar: calendars){
for(CalendarEntry calendarEntry: calendar){
if((calendarEntry.getYear()+1900) == dateModel.getYear() && calendarEntry.getWeek() == dateModel.getWeek()){
CalendarEntryView view = new CalendarEntryView(calendarEntry);
view.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
super.mouseClicked(e);
CalendarEntry ce = ((CalendarEntryView)e.getSource()).getModel();
if (ce instanceof Meeting) {
new MeetingFrame((Meeting) ce);
}
if (ce instanceof Appointment) {
new AppointmentPanel((Appointment) ce);
}
}
});
entries.add(view);
}
}
}*/
return entries;
}
@Override
public Iterator<CalendarEntryView> iterator() {
return new Iterator<CalendarEntryView>() {
List<CalendarEntryView> entries = getEntryViews();
int i = 0;
@Override
public boolean hasNext() {
return i<entries.size();
}
@Override
public CalendarEntryView next() {
return entries.get(i++);
}
@Override
public void remove() {
entries.remove(i);
}
};
}
public void addPropertyChangeListener(PropertyChangeListener l) {
pcs.addPropertyChangeListener(l);
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
pcs.firePropertyChange(evt);
}
}
| true | true | public List<CalendarEntryView> getEntryViews(){
//TODO bgcolor entryviews equal to entryviews from the same calendar
List<CalendarEntryView> entries = new ArrayList<CalendarEntryView>();
for(CalendarEntry calendarEntry: calendar){
if((calendarEntry.getYear()+1900) == dateModel.getYear() && calendarEntry.getWeek() == dateModel.getWeek()){
if (calendarEntry instanceof Meeting) {
Meeting m = (Meeting) calendarEntry;
User user = CommunicationController.getInstance().getUser();
if (m.getOwner().equals(user) || m.getState(user) == State.Accepted) {
CalendarEntryView view = new CalendarEntryView(calendarEntry);
view.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
super.mouseClicked(e);
CalendarEntry ce = ((CalendarEntryView)e.getSource()).getModel();
Meeting m = (Meeting) ce;
if (m.getOwner() == CommunicationController.getInstance().getUser()) {
new MeetingFrame(m);
} else {
new MeetingInviteFrame(m);
}
}
});
entries.add(view);
}
}
if (calendarEntry instanceof Appointment) {
CalendarEntryView view = new CalendarEntryView(calendarEntry);
view.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
super.mouseClicked(e);
CalendarEntry ce = ((CalendarEntryView)e.getSource()).getModel();
new AppointmentPanel((Appointment) ce);
}
});
entries.add(view);
}
}
}
/*for(Calendar calendar: calendars){
for(CalendarEntry calendarEntry: calendar){
if((calendarEntry.getYear()+1900) == dateModel.getYear() && calendarEntry.getWeek() == dateModel.getWeek()){
CalendarEntryView view = new CalendarEntryView(calendarEntry);
view.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
super.mouseClicked(e);
CalendarEntry ce = ((CalendarEntryView)e.getSource()).getModel();
if (ce instanceof Meeting) {
new MeetingFrame((Meeting) ce);
}
if (ce instanceof Appointment) {
new AppointmentPanel((Appointment) ce);
}
}
});
entries.add(view);
}
}
}*/
| public List<CalendarEntryView> getEntryViews(){
//TODO bgcolor entryviews equal to entryviews from the same calendar
List<CalendarEntryView> entries = new ArrayList<CalendarEntryView>();
for(CalendarEntry calendarEntry: calendar){
if((calendarEntry.getYear()+1900) == dateModel.getYear() && calendarEntry.getWeek() == dateModel.getWeek()){
if (calendarEntry instanceof Meeting) {
Meeting m = (Meeting) calendarEntry;
User user = CommunicationController.getInstance().getUser();
if (m.getOwner().equals(user) || m.getState(user) == State.Accepted) {
CalendarEntryView view = new CalendarEntryView(calendarEntry);
view.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
super.mouseClicked(e);
CalendarEntry ce = ((CalendarEntryView)e.getSource()).getModel();
Meeting m = (Meeting) ce;
if (m.getOwner().equals(CommunicationController.getInstance().getUser())) {
new MeetingFrame(m);
} else {
new MeetingInviteFrame(m);
}
}
});
entries.add(view);
}
}
if (calendarEntry instanceof Appointment) {
CalendarEntryView view = new CalendarEntryView(calendarEntry);
view.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
super.mouseClicked(e);
CalendarEntry ce = ((CalendarEntryView)e.getSource()).getModel();
new AppointmentPanel((Appointment) ce);
}
});
entries.add(view);
}
}
}
/*for(Calendar calendar: calendars){
for(CalendarEntry calendarEntry: calendar){
if((calendarEntry.getYear()+1900) == dateModel.getYear() && calendarEntry.getWeek() == dateModel.getWeek()){
CalendarEntryView view = new CalendarEntryView(calendarEntry);
view.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
super.mouseClicked(e);
CalendarEntry ce = ((CalendarEntryView)e.getSource()).getModel();
if (ce instanceof Meeting) {
new MeetingFrame((Meeting) ce);
}
if (ce instanceof Appointment) {
new AppointmentPanel((Appointment) ce);
}
}
});
entries.add(view);
}
}
}*/
|
diff --git a/weaver/src/org/aspectj/weaver/patterns/WithinCodeAnnotationPointcut.java b/weaver/src/org/aspectj/weaver/patterns/WithinCodeAnnotationPointcut.java
index 7d6ab0ebb..bb0b3bb65 100644
--- a/weaver/src/org/aspectj/weaver/patterns/WithinCodeAnnotationPointcut.java
+++ b/weaver/src/org/aspectj/weaver/patterns/WithinCodeAnnotationPointcut.java
@@ -1,224 +1,225 @@
/* *******************************************************************
* Copyright (c) 2004 IBM Corporation.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* ******************************************************************/
package org.aspectj.weaver.patterns;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.util.FuzzyBoolean;
import org.aspectj.weaver.AnnotatedElement;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.NameMangler;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.ShadowMunger;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.VersionedDataInputStream;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.ast.Literal;
import org.aspectj.weaver.ast.Test;
import org.aspectj.weaver.ast.Var;
/**
* @author colyer
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class WithinCodeAnnotationPointcut extends NameBindingPointcut {
private ExactAnnotationTypePattern annotationTypePattern;
private ShadowMunger munger = null; // only set after concretization
private String declarationText;
private static final int matchedShadowKinds;
static {
int flags = Shadow.ALL_SHADOW_KINDS_BITS;
for (int i = 0; i < Shadow.SHADOW_KINDS.length; i++) {
if (Shadow.SHADOW_KINDS[i].isEnclosingKind())
flags -= Shadow.SHADOW_KINDS[i].bit;
}
matchedShadowKinds=flags;
}
public WithinCodeAnnotationPointcut(ExactAnnotationTypePattern type) {
super();
this.annotationTypePattern = type;
this.pointcutKind = Pointcut.ATWITHINCODE;
buildDeclarationText();
}
public WithinCodeAnnotationPointcut(ExactAnnotationTypePattern type, ShadowMunger munger) {
this(type);
this.munger = munger;
this.pointcutKind = Pointcut.ATWITHINCODE;
}
public ExactAnnotationTypePattern getAnnotationTypePattern() {
return annotationTypePattern;
}
public int couldMatchKinds() {
return matchedShadowKinds;
}
public Pointcut parameterizeWith(Map typeVariableMap) {
WithinCodeAnnotationPointcut ret = new WithinCodeAnnotationPointcut((ExactAnnotationTypePattern)this.annotationTypePattern.parameterizeWith(typeVariableMap));
ret.copyLocationFrom(this);
return ret;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.Pointcut#fastMatch(org.aspectj.weaver.patterns.FastMatchInfo)
*/
public FuzzyBoolean fastMatch(FastMatchInfo info) {
return FuzzyBoolean.MAYBE;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.Pointcut#match(org.aspectj.weaver.Shadow)
*/
protected FuzzyBoolean matchInternal(Shadow shadow) {
AnnotatedElement toMatchAgainst = null;
Member member = shadow.getEnclosingCodeSignature();
ResolvedMember rMember = member.resolve(shadow.getIWorld());
if (rMember == null) {
if (member.getName().startsWith(NameMangler.PREFIX)) {
return FuzzyBoolean.NO;
}
shadow.getIWorld().getLint().unresolvableMember.signal(member.toString(), getSourceLocation());
return FuzzyBoolean.NO;
}
annotationTypePattern.resolve(shadow.getIWorld());
return annotationTypePattern.matches(rMember);
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.Pointcut#resolveBindings(org.aspectj.weaver.patterns.IScope, org.aspectj.weaver.patterns.Bindings)
*/
protected void resolveBindings(IScope scope, Bindings bindings) {
if (!scope.getWorld().isInJava5Mode()) {
scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.ATWITHINCODE_ONLY_SUPPORTED_AT_JAVA5_LEVEL),
getSourceLocation()));
return;
}
annotationTypePattern = (ExactAnnotationTypePattern) annotationTypePattern.resolveBindings(scope,bindings,true);
// must be either a Var, or an annotation type pattern
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.Pointcut#concretize1(org.aspectj.weaver.ResolvedType, org.aspectj.weaver.IntMap)
*/
protected Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) {
ExactAnnotationTypePattern newType = (ExactAnnotationTypePattern) annotationTypePattern.remapAdviceFormals(bindings);
Pointcut ret = new WithinCodeAnnotationPointcut(newType, bindings.getEnclosingAdvice());
ret.copyLocationFrom(this);
return ret;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.Pointcut#findResidue(org.aspectj.weaver.Shadow, org.aspectj.weaver.patterns.ExposedState)
*/
protected Test findResidueInternal(Shadow shadow, ExposedState state) {
if (annotationTypePattern instanceof BindingAnnotationTypePattern) {
BindingAnnotationTypePattern btp = (BindingAnnotationTypePattern)annotationTypePattern;
UnresolvedType annotationType = btp.annotationType;
Var var = shadow.getWithinCodeAnnotationVar(annotationType);
// This should not happen, we shouldn't have gotten this far
// if we weren't going to find the annotation
if (var == null)
throw new BCException("Impossible! annotation=["+annotationType+
"] shadow=["+shadow+" at "+shadow.getSourceLocation()+
"] pointcut is at ["+getSourceLocation()+"]");
state.set(btp.getFormalIndex(),var);
}
- if (matchInternal(shadow).alwaysTrue())
- return Literal.TRUE;
- else
- return Literal.FALSE;
+ return Literal.TRUE;
+// if (matchInternal(shadow).alwaysTrue())
+// return Literal.TRUE;
+// else
+// return Literal.FALSE;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingAnnotationTypePatterns()
*/
public List getBindingAnnotationTypePatterns() {
if (annotationTypePattern instanceof BindingAnnotationTypePattern) {
List l = new ArrayList();
l.add(annotationTypePattern);
return l;
} else return Collections.EMPTY_LIST;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingTypePatterns()
*/
public List getBindingTypePatterns() {
return Collections.EMPTY_LIST;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.PatternNode#write(java.io.DataOutputStream)
*/
public void write(DataOutputStream s) throws IOException {
s.writeByte(Pointcut.ATWITHINCODE);
annotationTypePattern.write(s);
writeLocation(s);
}
public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException {
AnnotationTypePattern type = AnnotationTypePattern.read(s, context);
WithinCodeAnnotationPointcut ret = new WithinCodeAnnotationPointcut((ExactAnnotationTypePattern)type);
ret.readLocation(context, s);
return ret;
}
public boolean equals(Object other) {
if (!(other instanceof WithinCodeAnnotationPointcut)) return false;
WithinCodeAnnotationPointcut o = (WithinCodeAnnotationPointcut)other;
return o.annotationTypePattern.equals(this.annotationTypePattern);
}
public int hashCode() {
int result = 17;
result = 23*result + annotationTypePattern.hashCode();
return result;
}
private void buildDeclarationText() {
StringBuffer buf = new StringBuffer();
buf.append("@withincode(");
String annPatt = annotationTypePattern.toString();
buf.append(annPatt.startsWith("@") ? annPatt.substring(1) : annPatt);
buf.append(")");
this.declarationText = buf.toString();
}
public String toString() { return this.declarationText; }
public Object accept(PatternNodeVisitor visitor, Object data) {
return visitor.visit(this, data);
}
}
| true | true | protected Test findResidueInternal(Shadow shadow, ExposedState state) {
if (annotationTypePattern instanceof BindingAnnotationTypePattern) {
BindingAnnotationTypePattern btp = (BindingAnnotationTypePattern)annotationTypePattern;
UnresolvedType annotationType = btp.annotationType;
Var var = shadow.getWithinCodeAnnotationVar(annotationType);
// This should not happen, we shouldn't have gotten this far
// if we weren't going to find the annotation
if (var == null)
throw new BCException("Impossible! annotation=["+annotationType+
"] shadow=["+shadow+" at "+shadow.getSourceLocation()+
"] pointcut is at ["+getSourceLocation()+"]");
state.set(btp.getFormalIndex(),var);
}
if (matchInternal(shadow).alwaysTrue())
return Literal.TRUE;
else
return Literal.FALSE;
}
| protected Test findResidueInternal(Shadow shadow, ExposedState state) {
if (annotationTypePattern instanceof BindingAnnotationTypePattern) {
BindingAnnotationTypePattern btp = (BindingAnnotationTypePattern)annotationTypePattern;
UnresolvedType annotationType = btp.annotationType;
Var var = shadow.getWithinCodeAnnotationVar(annotationType);
// This should not happen, we shouldn't have gotten this far
// if we weren't going to find the annotation
if (var == null)
throw new BCException("Impossible! annotation=["+annotationType+
"] shadow=["+shadow+" at "+shadow.getSourceLocation()+
"] pointcut is at ["+getSourceLocation()+"]");
state.set(btp.getFormalIndex(),var);
}
return Literal.TRUE;
// if (matchInternal(shadow).alwaysTrue())
// return Literal.TRUE;
// else
// return Literal.FALSE;
}
|
diff --git a/src/se/chalmers/segway/scenes/SceneManager.java b/src/se/chalmers/segway/scenes/SceneManager.java
index f0d2747..cf47596 100644
--- a/src/se/chalmers/segway/scenes/SceneManager.java
+++ b/src/se/chalmers/segway/scenes/SceneManager.java
@@ -1,231 +1,231 @@
package se.chalmers.segway.scenes;
import org.andengine.engine.Engine;
import org.andengine.engine.handler.timer.ITimerCallback;
import org.andengine.engine.handler.timer.TimerHandler;
import org.andengine.ui.IGameInterface.OnCreateSceneCallback;
import android.app.Activity;
import android.content.Context;
import se.chalmers.segway.game.PlayerData;
import se.chalmers.segway.game.SaveManager;
import se.chalmers.segway.game.Upgrades;
import se.chalmers.segway.resources.ResourcesManager;
public class SceneManager {
// ---------------------------------------------
// SCENES
// ---------------------------------------------
private BaseScene splashScene;
private BaseScene menuScene;
private BaseScene gameScene;
private BaseScene loadingScene;
private BaseScene selectionScene;
private BaseScene shopScene;
private static boolean isCreated = false;
private PlayerData playerData;
// ---------------------------------------------
// VARIABLES
// ---------------------------------------------
private static SceneManager INSTANCE = new SceneManager();
private SceneType currentSceneType = SceneType.SCENE_SPLASH;
private BaseScene currentScene;
private Engine engine = ResourcesManager.getInstance().engine;
public enum SceneType {
SCENE_SPLASH, SCENE_MENU, SCENE_GAME, SCENE_LOADING, SCENE_SELECTION, SHOP_SCENE
}
// ---------------------------------------------
// CREATION AND DISPOSAL
// ---------------------------------------------
public void createSplashScene(OnCreateSceneCallback pOnCreateSceneCallback) {
ResourcesManager.getInstance().loadSplashScreen();
splashScene = new SplashScene();
currentScene = splashScene;
pOnCreateSceneCallback.onCreateSceneFinished(splashScene);
}
private void disposeSplashScene() {
ResourcesManager.getInstance().unloadSplashScreen();
splashScene.disposeScene();
splashScene = null;
}
public void createMenuScene() {
ResourcesManager.getInstance().loadMenuResources();
menuScene = new MainMenuScene();
loadingScene = new LoadingScene();
shopScene = new ShopScene();
((MainMenuScene) menuScene).setPlayerData(playerData);
((MainMenuScene) menuScene).updateHUD();
setScene(menuScene);
disposeSplashScene();
}
// ---------------------------------------------
// CLASS LOGIC
// ---------------------------------------------
public void setScene(BaseScene scene) {
engine.setScene(scene);
currentScene = scene;
currentSceneType = scene.getSceneType();
}
public void setScene(SceneType sceneType) {
switch (sceneType) {
case SCENE_MENU:
setScene(menuScene);
break;
case SCENE_GAME:
setScene(gameScene);
break;
case SCENE_SPLASH:
setScene(splashScene);
break;
case SCENE_LOADING:
setScene(loadingScene);
break;
case SCENE_SELECTION:
setScene(selectionScene);
break;
case SHOP_SCENE:
setScene(shopScene);
break;
default:
break;
}
}
// TODO: Unfinished
public void loadSelectionScene(final Engine mEngine) {
if (currentScene == gameScene) {
gameScene.disposeScene();
ResourcesManager.getInstance().unloadGameTextures();
} else if (currentScene == menuScene) {
ResourcesManager.getInstance().unloadMenuTextures();
}
setScene(loadingScene);
mEngine.registerUpdateHandler(new TimerHandler(0.1f,
new ITimerCallback() {
public void onTimePassed(final TimerHandler pTimerHandler) {
mEngine.unregisterUpdateHandler(pTimerHandler);
ResourcesManager.getInstance().loadSelectionResources();
selectionScene = new LevelSelectionScene();
((LevelSelectionScene) selectionScene)
.setUnlockedLevels(playerData
.getHighestLevelCleared());
((LevelSelectionScene) selectionScene).updateScene();
setScene(selectionScene);
}
}));
}
public void loadGameScene(final Engine mEngine, final int level) {
setScene(loadingScene);
ResourcesManager.getInstance().unloadSelectionTextures();
mEngine.registerUpdateHandler(new TimerHandler(0.1f,
new ITimerCallback() {
public void onTimePassed(final TimerHandler pTimerHandler) {
mEngine.unregisterUpdateHandler(pTimerHandler);
ResourcesManager.getInstance().loadGameResources();
gameScene = new GameScene();
((GameScene) gameScene).setPlayerData(playerData);
((GameScene) gameScene).loadLevel(level);
setScene(gameScene);
if (ResourcesManager.getInstance().musicManager
.getMasterVolume() == 1) {
ResourcesManager.getInstance().music.pause();
if (level == 4) {
ResourcesManager.getInstance().music2.play();
- } else if (level == 5) {
+ } else if (level == 3) {
ResourcesManager.getInstance().music3.play();
} else {
ResourcesManager.getInstance().music.resume();
}
}
}
}));
}
public void loadMenuScene(final Engine mEngine) {
if (currentScene == gameScene) {
gameScene.disposeScene();
ResourcesManager.getInstance().unloadGameTextures();
if (ResourcesManager.getInstance().musicManager.getMasterVolume() == 1) {
ResourcesManager.getInstance().music.resume();
if (ResourcesManager.getInstance().music2.isPlaying()) {
ResourcesManager.getInstance().music2.pause();
} else if (ResourcesManager.getInstance().music3.isPlaying()) {
ResourcesManager.getInstance().music3.pause();
}
}
}
setScene(loadingScene);
mEngine.registerUpdateHandler(new TimerHandler(0.1f,
new ITimerCallback() {
public void onTimePassed(final TimerHandler pTimerHandler) {
mEngine.unregisterUpdateHandler(pTimerHandler);
ResourcesManager.getInstance().loadMenuTextures();
((MainMenuScene) menuScene).setPlayerData(playerData);
((MainMenuScene) menuScene).updateHUD();
setScene(menuScene);
}
}));
}
private void initPlayerData() {
playerData = SaveManager.loadPlayerData();
if (playerData == null) {
playerData = new PlayerData("Plebian " + Math.random() * 1000);
}
}
public void loadShopScene(final Engine mEngine) {
if (currentScene == gameScene) {
gameScene.disposeScene();
ResourcesManager.getInstance().unloadGameTextures();
}
setScene(shopScene);
mEngine.registerUpdateHandler(new TimerHandler(0.1f,
new ITimerCallback() {
public void onTimePassed(final TimerHandler pTimerHandler) {
mEngine.unregisterUpdateHandler(pTimerHandler);
ResourcesManager.getInstance().loadMenuTextures();
setScene(shopScene);
}
}));
}
// ---------------------------------------------
// GETTERS AND SETTERS
// ---------------------------------------------
public static synchronized SceneManager getInstance() {
if (!isCreated) {
SaveManager.loadUpgrades();
isCreated = true;
INSTANCE = new SceneManager();
INSTANCE.initPlayerData();
}
return INSTANCE;
}
public SceneType getCurrentSceneType() {
return currentSceneType;
}
public BaseScene getCurrentScene() {
return currentScene;
}
}
| true | true | public void loadGameScene(final Engine mEngine, final int level) {
setScene(loadingScene);
ResourcesManager.getInstance().unloadSelectionTextures();
mEngine.registerUpdateHandler(new TimerHandler(0.1f,
new ITimerCallback() {
public void onTimePassed(final TimerHandler pTimerHandler) {
mEngine.unregisterUpdateHandler(pTimerHandler);
ResourcesManager.getInstance().loadGameResources();
gameScene = new GameScene();
((GameScene) gameScene).setPlayerData(playerData);
((GameScene) gameScene).loadLevel(level);
setScene(gameScene);
if (ResourcesManager.getInstance().musicManager
.getMasterVolume() == 1) {
ResourcesManager.getInstance().music.pause();
if (level == 4) {
ResourcesManager.getInstance().music2.play();
} else if (level == 5) {
ResourcesManager.getInstance().music3.play();
} else {
ResourcesManager.getInstance().music.resume();
}
}
}
}));
}
| public void loadGameScene(final Engine mEngine, final int level) {
setScene(loadingScene);
ResourcesManager.getInstance().unloadSelectionTextures();
mEngine.registerUpdateHandler(new TimerHandler(0.1f,
new ITimerCallback() {
public void onTimePassed(final TimerHandler pTimerHandler) {
mEngine.unregisterUpdateHandler(pTimerHandler);
ResourcesManager.getInstance().loadGameResources();
gameScene = new GameScene();
((GameScene) gameScene).setPlayerData(playerData);
((GameScene) gameScene).loadLevel(level);
setScene(gameScene);
if (ResourcesManager.getInstance().musicManager
.getMasterVolume() == 1) {
ResourcesManager.getInstance().music.pause();
if (level == 4) {
ResourcesManager.getInstance().music2.play();
} else if (level == 3) {
ResourcesManager.getInstance().music3.play();
} else {
ResourcesManager.getInstance().music.resume();
}
}
}
}));
}
|
diff --git a/tests/org.eclipse.gmf.tests/src/org/eclipse/gmf/tests/setup/RTSetup.java b/tests/org.eclipse.gmf.tests/src/org/eclipse/gmf/tests/setup/RTSetup.java
index ed58f5fe3..1f0e92845 100644
--- a/tests/org.eclipse.gmf.tests/src/org/eclipse/gmf/tests/setup/RTSetup.java
+++ b/tests/org.eclipse.gmf.tests/src/org/eclipse/gmf/tests/setup/RTSetup.java
@@ -1,271 +1,273 @@
/*
* Copyright (c) 2005 Borland Software Corporation
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Artem Tikhomirov (Borland) - initial API and implementation
*/
package org.eclipse.gmf.tests.setup;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collection;
import junit.framework.Assert;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.operations.OperationHistoryFactory;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Status;
import org.eclipse.emf.codegen.ecore.genmodel.GenClass;
import org.eclipse.emf.codegen.ecore.genmodel.GenFeature;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.transaction.TransactionalEditingDomain;
import org.eclipse.emf.workspace.AbstractEMFOperation;
import org.eclipse.gmf.codegen.gmfgen.GenNode;
import org.eclipse.gmf.codegen.gmfgen.TypeLinkModelFacet;
import org.eclipse.gmf.runtime.diagram.core.DiagramEditingDomainFactory;
import org.eclipse.gmf.runtime.notation.Bounds;
import org.eclipse.gmf.runtime.notation.Diagram;
import org.eclipse.gmf.runtime.notation.Edge;
import org.eclipse.gmf.runtime.notation.Node;
import org.eclipse.gmf.runtime.notation.NotationFactory;
import org.osgi.framework.Bundle;
/**
* TODO DomainModelInstanceSource to separate instantiation from diagram creation and
* to facilitate testing of domain model instance - not to miss containments and other
* potential problems in DomainModelSource
* Simple implementation that creates simple diagram with few elements
* @author artem
*/
public class RTSetup implements RTSource {
private Diagram myCanvas;
private Node myNodeA;
private Node myNodeB;
private Edge myLink;
private EObject myDiagramElement;
public RTSetup() {
}
public final RTSetup init(Bundle b, DiaGenSource genSource) {
initDiagramFileContents(new CoolDomainInstanceProducer(b), genSource);
saveDiagramFile(genSource.getGenDiagram().getEditingDomainID());
return this;
}
public final RTSetup init(DiaGenSource genSource) {
initDiagramFileContents(new NaiveDomainInstanceProducer(), genSource);
saveDiagramFile(genSource.getGenDiagram().getEditingDomainID());
return this;
}
/**
* @return <code>this</code> for convenience
*/
protected void initDiagramFileContents(DomainInstanceProducer instanceProducer, DiaGenSource genSource) {
myCanvas = NotationFactory.eINSTANCE.createDiagram();
myDiagramElement = instanceProducer.createInstance(genSource.getGenDiagram().getDomainDiagramElement());
myCanvas.setElement(myDiagramElement);
myCanvas.setType(genSource.getGenDiagram().getEditorGen().getModelID());
myNodeA = setupNotationNode(genSource.getNodeA(), instanceProducer);
myNodeB = setupNotationNode(genSource.getNodeB(), instanceProducer);
myLink = NotationFactory.eINSTANCE.createEdge();
myCanvas.getPersistedEdges().add(myLink);
//myNode.setVisualID(genSource.getGenNode().getVisualID());
TypeLinkModelFacet mf = (TypeLinkModelFacet) genSource.getLinkC().getModelFacet();
EObject linkElement = instanceProducer.createInstance(mf.getMetaClass());
+ instanceProducer.setFeatureValue(myNodeA.getElement(), linkElement, mf.getContainmentMetaFeature());
+ instanceProducer.setFeatureValue(linkElement, myNodeB.getElement(), mf.getTargetMetaFeature());
myLink.setElement(linkElement);
myLink.setType(String.valueOf(genSource.getLinkC().getVisualID()));
myLink.setSource(myNodeA);
myLink.setTarget(myNodeB);
myLink.setBendpoints(NotationFactory.eINSTANCE.createRelativeBendpoints());
//myLink.setVisualID(genSource.getGenLink().getVisualID());
myCanvas.setType(genSource.getGenDiagram().getEditorGen().getDomainGenModel().getModelName());
/*
Object nc = diagramElement.eGet(genSource.getGenNode().getContainmentMetaFeature().getEcoreFeature());
assert nc instanceof EList;
((EList) nc).add(nodeElement);
Object lc = nodeElement.eGet(genSource.getGenLink().getContainmentMetaFeature().getEcoreFeature());
if (lc instanceof EList) {
((EList) lc).add(linkElement);
} else {
nodeElement.eSet(genSource.getGenLink().getContainmentMetaFeature().getEcoreFeature(), linkElement);
}
*/
}
private Node setupNotationNode(GenNode genNode, DomainInstanceProducer instanceProducer){
Node result = NotationFactory.eINSTANCE.createNode();
myCanvas.getPersistedChildren().add(result);
EObject nodeElement = instanceProducer.createInstance(genNode.getDomainMetaClass());
instanceProducer.setFeatureValue(myDiagramElement, nodeElement, genNode.getModelFacet().getContainmentMetaFeature());
result.setElement(nodeElement);
result.setType(String.valueOf(genNode.getVisualID()));
result.getStyles().add(NotationFactory.eINSTANCE.createShapeStyle());
Bounds b = NotationFactory.eINSTANCE.createBounds();
b.setWidth(0);
b.setHeight(0);
result.setLayoutConstraint(b);
return result;
}
private void saveDiagramFile(String editingDomainId){
TransactionalEditingDomain ted = DiagramEditingDomainFactory.getInstance().createEditingDomain();
ted.setID(editingDomainId);
ResourceSet rs = ted.getResourceSet();
URI uri = URI.createURI("uri://fake/z"); //$NON-NLS-1$
Resource r = rs.getResource(uri, false);
if (r == null) {
r = rs.createResource(uri);
}
final Resource diagramFile = r;
AbstractEMFOperation operation = new AbstractEMFOperation(ted, "") { //$NON-NLS-1$
protected IStatus doExecute(IProgressMonitor monitor, IAdaptable info) throws ExecutionException {
diagramFile.getContents().clear();
diagramFile.getContents().add(getCanvas());
diagramFile.getContents().add(getDiagramElement());
return Status.OK_STATUS;
};
};
try {
OperationHistoryFactory.getOperationHistory().execute(operation,
new NullProgressMonitor(), null);
} catch (ExecutionException e) {
e.printStackTrace();
Assert.fail("Failed to set diagram resource contents"); //$NON-NLS-1$
}
}
public final Diagram getCanvas() {
return myCanvas;
}
public final Node getNodeA() {
return myNodeA;
}
public final Node getNodeB() {
return myNodeB;
}
public Edge getLink() {
return myLink;
}
protected EObject getDiagramElement(){
return myDiagramElement;
}
protected interface DomainInstanceProducer {
EObject createInstance(GenClass genClass);
void setFeatureValue(EObject src, EObject value, GenFeature genFeature);
}
private static class NaiveDomainInstanceProducer implements DomainInstanceProducer {
public EObject createInstance(GenClass genClass) {
return createInstance(genClass.getEcoreClass());
}
public void setFeatureValue(EObject src, EObject value, GenFeature genFeature) {
EStructuralFeature feature = genFeature.getEcoreFeature();
if (genFeature.isListType()) {
Collection result = (Collection) src.eGet(feature);
result.add(value);
} else {
src.eSet(feature, value);
}
}
public EObject createInstance(EClass eClass) {
return eClass.getEPackage().getEFactoryInstance().create(eClass);
}
}
private static class CoolDomainInstanceProducer implements DomainInstanceProducer {
private final Bundle bundle;
public EObject createInstance(GenClass genClass) {
try {
Class factoryClass = getFactoryClass(genClass);
Method m = factoryClass.getMethod("create" + genClass.getName(), new Class[0]);
return (EObject) m.invoke(getInstance(factoryClass), new Object[0]);
} catch (NoSuchFieldException ex) {
Assert.fail(ex.getMessage());
} catch (NoSuchMethodException ex) {
Assert.fail(ex.getMessage());
} catch (InvocationTargetException ex) {
Assert.fail(ex.getMessage());
} catch (IllegalAccessException ex) {
Assert.fail(ex.getMessage());
} catch (ClassNotFoundException ex) {
Assert.fail(ex.getMessage());
}
Assert.fail();
return null;
}
public void setFeatureValue(EObject src, EObject value, GenFeature genFeature) {
try {
Class packageClass = getPackageClass(genFeature);
Method featureAccessor = packageClass.getMethod("get" + genFeature.getFeatureAccessorName(), new Class[0]);
EStructuralFeature feature = (EStructuralFeature) featureAccessor.invoke(getInstance(packageClass), new Object[0]);
if (genFeature.isListType()) {
Collection result = (Collection) src.eGet(feature);
result.add(value);
} else {
src.eSet(feature, value);
}
} catch (ClassNotFoundException ex) {
Assert.fail(ex.getMessage());
} catch (SecurityException ex) {
Assert.fail(ex.getMessage());
} catch (NoSuchMethodException ex) {
Assert.fail(ex.getMessage());
} catch (IllegalArgumentException ex) {
Assert.fail(ex.getMessage());
} catch (IllegalAccessException ex) {
Assert.fail(ex.getMessage());
} catch (InvocationTargetException ex) {
Assert.fail(ex.getMessage());
} catch (NoSuchFieldException ex) {
Assert.fail(ex.getMessage());
}
}
private Class getFactoryClass(GenClass genClass) throws ClassNotFoundException {
return bundle.loadClass(genClass.getGenPackage().getQualifiedFactoryInterfaceName());
}
private Object getInstance(Class interfaceClass) throws NoSuchFieldException, IllegalAccessException {
return interfaceClass.getField("eINSTANCE").get(null);
}
private Class getPackageClass(GenFeature genFeature) throws ClassNotFoundException {
return bundle.loadClass(genFeature.getGenPackage().getQualifiedPackageInterfaceName());
}
public CoolDomainInstanceProducer(Bundle b) {
bundle = b;
}
}
}
| true | true | protected void initDiagramFileContents(DomainInstanceProducer instanceProducer, DiaGenSource genSource) {
myCanvas = NotationFactory.eINSTANCE.createDiagram();
myDiagramElement = instanceProducer.createInstance(genSource.getGenDiagram().getDomainDiagramElement());
myCanvas.setElement(myDiagramElement);
myCanvas.setType(genSource.getGenDiagram().getEditorGen().getModelID());
myNodeA = setupNotationNode(genSource.getNodeA(), instanceProducer);
myNodeB = setupNotationNode(genSource.getNodeB(), instanceProducer);
myLink = NotationFactory.eINSTANCE.createEdge();
myCanvas.getPersistedEdges().add(myLink);
//myNode.setVisualID(genSource.getGenNode().getVisualID());
TypeLinkModelFacet mf = (TypeLinkModelFacet) genSource.getLinkC().getModelFacet();
EObject linkElement = instanceProducer.createInstance(mf.getMetaClass());
myLink.setElement(linkElement);
myLink.setType(String.valueOf(genSource.getLinkC().getVisualID()));
myLink.setSource(myNodeA);
myLink.setTarget(myNodeB);
myLink.setBendpoints(NotationFactory.eINSTANCE.createRelativeBendpoints());
//myLink.setVisualID(genSource.getGenLink().getVisualID());
myCanvas.setType(genSource.getGenDiagram().getEditorGen().getDomainGenModel().getModelName());
/*
Object nc = diagramElement.eGet(genSource.getGenNode().getContainmentMetaFeature().getEcoreFeature());
assert nc instanceof EList;
((EList) nc).add(nodeElement);
Object lc = nodeElement.eGet(genSource.getGenLink().getContainmentMetaFeature().getEcoreFeature());
if (lc instanceof EList) {
((EList) lc).add(linkElement);
} else {
nodeElement.eSet(genSource.getGenLink().getContainmentMetaFeature().getEcoreFeature(), linkElement);
}
*/
}
| protected void initDiagramFileContents(DomainInstanceProducer instanceProducer, DiaGenSource genSource) {
myCanvas = NotationFactory.eINSTANCE.createDiagram();
myDiagramElement = instanceProducer.createInstance(genSource.getGenDiagram().getDomainDiagramElement());
myCanvas.setElement(myDiagramElement);
myCanvas.setType(genSource.getGenDiagram().getEditorGen().getModelID());
myNodeA = setupNotationNode(genSource.getNodeA(), instanceProducer);
myNodeB = setupNotationNode(genSource.getNodeB(), instanceProducer);
myLink = NotationFactory.eINSTANCE.createEdge();
myCanvas.getPersistedEdges().add(myLink);
//myNode.setVisualID(genSource.getGenNode().getVisualID());
TypeLinkModelFacet mf = (TypeLinkModelFacet) genSource.getLinkC().getModelFacet();
EObject linkElement = instanceProducer.createInstance(mf.getMetaClass());
instanceProducer.setFeatureValue(myNodeA.getElement(), linkElement, mf.getContainmentMetaFeature());
instanceProducer.setFeatureValue(linkElement, myNodeB.getElement(), mf.getTargetMetaFeature());
myLink.setElement(linkElement);
myLink.setType(String.valueOf(genSource.getLinkC().getVisualID()));
myLink.setSource(myNodeA);
myLink.setTarget(myNodeB);
myLink.setBendpoints(NotationFactory.eINSTANCE.createRelativeBendpoints());
//myLink.setVisualID(genSource.getGenLink().getVisualID());
myCanvas.setType(genSource.getGenDiagram().getEditorGen().getDomainGenModel().getModelName());
/*
Object nc = diagramElement.eGet(genSource.getGenNode().getContainmentMetaFeature().getEcoreFeature());
assert nc instanceof EList;
((EList) nc).add(nodeElement);
Object lc = nodeElement.eGet(genSource.getGenLink().getContainmentMetaFeature().getEcoreFeature());
if (lc instanceof EList) {
((EList) lc).add(linkElement);
} else {
nodeElement.eSet(genSource.getGenLink().getContainmentMetaFeature().getEcoreFeature(), linkElement);
}
*/
}
|
diff --git a/v4/java/android/support/v4/view/ViewPager.java b/v4/java/android/support/v4/view/ViewPager.java
index f014b99..42304a3 100644
--- a/v4/java/android/support/v4/view/ViewPager.java
+++ b/v4/java/android/support/v4/view/ViewPager.java
@@ -1,2869 +1,2870 @@
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.support.v4.view;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.database.DataSetObserver;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.SystemClock;
import android.support.v4.os.ParcelableCompat;
import android.support.v4.os.ParcelableCompatCreatorCallbacks;
import android.support.v4.view.accessibility.AccessibilityEventCompat;
import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat;
import android.support.v4.view.accessibility.AccessibilityRecordCompat;
import android.support.v4.widget.EdgeEffectCompat;
import android.util.AttributeSet;
import android.util.Log;
import android.view.FocusFinder;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SoundEffectConstants;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.accessibility.AccessibilityEvent;
import android.view.animation.Interpolator;
import android.widget.Scroller;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
/**
* Layout manager that allows the user to flip left and right
* through pages of data. You supply an implementation of a
* {@link PagerAdapter} to generate the pages that the view shows.
*
* <p>Note this class is currently under early design and
* development. The API will likely change in later updates of
* the compatibility library, requiring changes to the source code
* of apps when they are compiled against the newer version.</p>
*
* <p>ViewPager is most often used in conjunction with {@link android.app.Fragment},
* which is a convenient way to supply and manage the lifecycle of each page.
* There are standard adapters implemented for using fragments with the ViewPager,
* which cover the most common use cases. These are
* {@link android.support.v4.app.FragmentPagerAdapter} and
* {@link android.support.v4.app.FragmentStatePagerAdapter}; each of these
* classes have simple code showing how to build a full user interface
* with them.
*
* <p>Here is a more complicated example of ViewPager, using it in conjuction
* with {@link android.app.ActionBar} tabs. You can find other examples of using
* ViewPager in the API 4+ Support Demos and API 13+ Support Demos sample code.
*
* {@sample development/samples/Support13Demos/src/com/example/android/supportv13/app/ActionBarTabsPager.java
* complete}
*/
public class ViewPager extends ViewGroup {
private static final String TAG = "ViewPager";
private static final boolean DEBUG = false;
private static final boolean USE_CACHE = false;
private static final int DEFAULT_OFFSCREEN_PAGES = 1;
private static final int MAX_SETTLE_DURATION = 600; // ms
private static final int MIN_DISTANCE_FOR_FLING = 25; // dips
private static final int DEFAULT_GUTTER_SIZE = 16; // dips
private static final int MIN_FLING_VELOCITY = 400; // dips
private static final int[] LAYOUT_ATTRS = new int[] {
android.R.attr.layout_gravity
};
/**
* Used to track what the expected number of items in the adapter should be.
* If the app changes this when we don't expect it, we'll throw a big obnoxious exception.
*/
private int mExpectedAdapterCount;
static class ItemInfo {
Object object;
int position;
boolean scrolling;
float widthFactor;
float offset;
}
private static final Comparator<ItemInfo> COMPARATOR = new Comparator<ItemInfo>(){
@Override
public int compare(ItemInfo lhs, ItemInfo rhs) {
return lhs.position - rhs.position;
}
};
private static final Interpolator sInterpolator = new Interpolator() {
public float getInterpolation(float t) {
t -= 1.0f;
return t * t * t * t * t + 1.0f;
}
};
private final ArrayList<ItemInfo> mItems = new ArrayList<ItemInfo>();
private final ItemInfo mTempItem = new ItemInfo();
private final Rect mTempRect = new Rect();
private PagerAdapter mAdapter;
private int mCurItem; // Index of currently displayed page.
private int mRestoredCurItem = -1;
private Parcelable mRestoredAdapterState = null;
private ClassLoader mRestoredClassLoader = null;
private Scroller mScroller;
private PagerObserver mObserver;
private int mPageMargin;
private Drawable mMarginDrawable;
private int mTopPageBounds;
private int mBottomPageBounds;
// Offsets of the first and last items, if known.
// Set during population, used to determine if we are at the beginning
// or end of the pager data set during touch scrolling.
private float mFirstOffset = -Float.MAX_VALUE;
private float mLastOffset = Float.MAX_VALUE;
private int mChildWidthMeasureSpec;
private int mChildHeightMeasureSpec;
private boolean mInLayout;
private boolean mScrollingCacheEnabled;
private boolean mPopulatePending;
private int mOffscreenPageLimit = DEFAULT_OFFSCREEN_PAGES;
private boolean mIsBeingDragged;
private boolean mIsUnableToDrag;
private boolean mIgnoreGutter;
private int mDefaultGutterSize;
private int mGutterSize;
private int mTouchSlop;
/**
* Position of the last motion event.
*/
private float mLastMotionX;
private float mLastMotionY;
private float mInitialMotionX;
private float mInitialMotionY;
/**
* ID of the active pointer. This is used to retain consistency during
* drags/flings if multiple pointers are used.
*/
private int mActivePointerId = INVALID_POINTER;
/**
* Sentinel value for no current active pointer.
* Used by {@link #mActivePointerId}.
*/
private static final int INVALID_POINTER = -1;
/**
* Determines speed during touch scrolling
*/
private VelocityTracker mVelocityTracker;
private int mMinimumVelocity;
private int mMaximumVelocity;
private int mFlingDistance;
private int mCloseEnough;
// If the pager is at least this close to its final position, complete the scroll
// on touch down and let the user interact with the content inside instead of
// "catching" the flinging pager.
private static final int CLOSE_ENOUGH = 2; // dp
private boolean mFakeDragging;
private long mFakeDragBeginTime;
private EdgeEffectCompat mLeftEdge;
private EdgeEffectCompat mRightEdge;
private boolean mFirstLayout = true;
private boolean mNeedCalculatePageOffsets = false;
private boolean mCalledSuper;
private int mDecorChildCount;
private OnPageChangeListener mOnPageChangeListener;
private OnPageChangeListener mInternalPageChangeListener;
private OnAdapterChangeListener mAdapterChangeListener;
private PageTransformer mPageTransformer;
private Method mSetChildrenDrawingOrderEnabled;
private static final int DRAW_ORDER_DEFAULT = 0;
private static final int DRAW_ORDER_FORWARD = 1;
private static final int DRAW_ORDER_REVERSE = 2;
private int mDrawingOrder;
private ArrayList<View> mDrawingOrderedChildren;
private static final ViewPositionComparator sPositionComparator = new ViewPositionComparator();
/**
* Indicates that the pager is in an idle, settled state. The current page
* is fully in view and no animation is in progress.
*/
public static final int SCROLL_STATE_IDLE = 0;
/**
* Indicates that the pager is currently being dragged by the user.
*/
public static final int SCROLL_STATE_DRAGGING = 1;
/**
* Indicates that the pager is in the process of settling to a final position.
*/
public static final int SCROLL_STATE_SETTLING = 2;
private final Runnable mEndScrollRunnable = new Runnable() {
public void run() {
setScrollState(SCROLL_STATE_IDLE);
populate();
}
};
private int mScrollState = SCROLL_STATE_IDLE;
/**
* Callback interface for responding to changing state of the selected page.
*/
public interface OnPageChangeListener {
/**
* This method will be invoked when the current page is scrolled, either as part
* of a programmatically initiated smooth scroll or a user initiated touch scroll.
*
* @param position Position index of the first page currently being displayed.
* Page position+1 will be visible if positionOffset is nonzero.
* @param positionOffset Value from [0, 1) indicating the offset from the page at position.
* @param positionOffsetPixels Value in pixels indicating the offset from position.
*/
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels);
/**
* This method will be invoked when a new page becomes selected. Animation is not
* necessarily complete.
*
* @param position Position index of the new selected page.
*/
public void onPageSelected(int position);
/**
* Called when the scroll state changes. Useful for discovering when the user
* begins dragging, when the pager is automatically settling to the current page,
* or when it is fully stopped/idle.
*
* @param state The new scroll state.
* @see ViewPager#SCROLL_STATE_IDLE
* @see ViewPager#SCROLL_STATE_DRAGGING
* @see ViewPager#SCROLL_STATE_SETTLING
*/
public void onPageScrollStateChanged(int state);
}
/**
* Simple implementation of the {@link OnPageChangeListener} interface with stub
* implementations of each method. Extend this if you do not intend to override
* every method of {@link OnPageChangeListener}.
*/
public static class SimpleOnPageChangeListener implements OnPageChangeListener {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
// This space for rent
}
@Override
public void onPageSelected(int position) {
// This space for rent
}
@Override
public void onPageScrollStateChanged(int state) {
// This space for rent
}
}
/**
* A PageTransformer is invoked whenever a visible/attached page is scrolled.
* This offers an opportunity for the application to apply a custom transformation
* to the page views using animation properties.
*
* <p>As property animation is only supported as of Android 3.0 and forward,
* setting a PageTransformer on a ViewPager on earlier platform versions will
* be ignored.</p>
*/
public interface PageTransformer {
/**
* Apply a property transformation to the given page.
*
* @param page Apply the transformation to this page
* @param position Position of page relative to the current front-and-center
* position of the pager. 0 is front and center. 1 is one full
* page position to the right, and -1 is one page position to the left.
*/
public void transformPage(View page, float position);
}
/**
* Used internally to monitor when adapters are switched.
*/
interface OnAdapterChangeListener {
public void onAdapterChanged(PagerAdapter oldAdapter, PagerAdapter newAdapter);
}
/**
* Used internally to tag special types of child views that should be added as
* pager decorations by default.
*/
interface Decor {}
public ViewPager(Context context) {
super(context);
initViewPager();
}
public ViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
initViewPager();
}
void initViewPager() {
setWillNotDraw(false);
setDescendantFocusability(FOCUS_AFTER_DESCENDANTS);
setFocusable(true);
final Context context = getContext();
mScroller = new Scroller(context, sInterpolator);
final ViewConfiguration configuration = ViewConfiguration.get(context);
final float density = context.getResources().getDisplayMetrics().density;
mTouchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(configuration);
mMinimumVelocity = (int) (MIN_FLING_VELOCITY * density);
mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
mLeftEdge = new EdgeEffectCompat(context);
mRightEdge = new EdgeEffectCompat(context);
mFlingDistance = (int) (MIN_DISTANCE_FOR_FLING * density);
mCloseEnough = (int) (CLOSE_ENOUGH * density);
mDefaultGutterSize = (int) (DEFAULT_GUTTER_SIZE * density);
ViewCompat.setAccessibilityDelegate(this, new MyAccessibilityDelegate());
if (ViewCompat.getImportantForAccessibility(this)
== ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
ViewCompat.setImportantForAccessibility(this,
ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES);
}
}
@Override
protected void onDetachedFromWindow() {
removeCallbacks(mEndScrollRunnable);
super.onDetachedFromWindow();
}
private void setScrollState(int newState) {
if (mScrollState == newState) {
return;
}
mScrollState = newState;
if (mPageTransformer != null) {
// PageTransformers can do complex things that benefit from hardware layers.
enableLayers(newState != SCROLL_STATE_IDLE);
}
if (mOnPageChangeListener != null) {
mOnPageChangeListener.onPageScrollStateChanged(newState);
}
}
/**
* Set a PagerAdapter that will supply views for this pager as needed.
*
* @param adapter Adapter to use
*/
public void setAdapter(PagerAdapter adapter) {
if (mAdapter != null) {
mAdapter.unregisterDataSetObserver(mObserver);
mAdapter.startUpdate(this);
for (int i = 0; i < mItems.size(); i++) {
final ItemInfo ii = mItems.get(i);
mAdapter.destroyItem(this, ii.position, ii.object);
}
mAdapter.finishUpdate(this);
mItems.clear();
removeNonDecorViews();
mCurItem = 0;
scrollTo(0, 0);
}
final PagerAdapter oldAdapter = mAdapter;
mAdapter = adapter;
mExpectedAdapterCount = 0;
if (mAdapter != null) {
if (mObserver == null) {
mObserver = new PagerObserver();
}
mAdapter.registerDataSetObserver(mObserver);
mPopulatePending = false;
final boolean wasFirstLayout = mFirstLayout;
mFirstLayout = true;
mExpectedAdapterCount = mAdapter.getCount();
if (mRestoredCurItem >= 0) {
mAdapter.restoreState(mRestoredAdapterState, mRestoredClassLoader);
setCurrentItemInternal(mRestoredCurItem, false, true);
mRestoredCurItem = -1;
mRestoredAdapterState = null;
mRestoredClassLoader = null;
} else if (!wasFirstLayout) {
populate();
} else {
requestLayout();
}
}
if (mAdapterChangeListener != null && oldAdapter != adapter) {
mAdapterChangeListener.onAdapterChanged(oldAdapter, adapter);
}
}
private void removeNonDecorViews() {
for (int i = 0; i < getChildCount(); i++) {
final View child = getChildAt(i);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (!lp.isDecor) {
removeViewAt(i);
i--;
}
}
}
/**
* Retrieve the current adapter supplying pages.
*
* @return The currently registered PagerAdapter
*/
public PagerAdapter getAdapter() {
return mAdapter;
}
void setOnAdapterChangeListener(OnAdapterChangeListener listener) {
mAdapterChangeListener = listener;
}
private int getClientWidth() {
return getMeasuredWidth() - getPaddingLeft() - getPaddingRight();
}
/**
* Set the currently selected page. If the ViewPager has already been through its first
* layout with its current adapter there will be a smooth animated transition between
* the current item and the specified item.
*
* @param item Item index to select
*/
public void setCurrentItem(int item) {
mPopulatePending = false;
setCurrentItemInternal(item, !mFirstLayout, false);
}
/**
* Set the currently selected page.
*
* @param item Item index to select
* @param smoothScroll True to smoothly scroll to the new item, false to transition immediately
*/
public void setCurrentItem(int item, boolean smoothScroll) {
mPopulatePending = false;
setCurrentItemInternal(item, smoothScroll, false);
}
public int getCurrentItem() {
return mCurItem;
}
void setCurrentItemInternal(int item, boolean smoothScroll, boolean always) {
setCurrentItemInternal(item, smoothScroll, always, 0);
}
void setCurrentItemInternal(int item, boolean smoothScroll, boolean always, int velocity) {
if (mAdapter == null || mAdapter.getCount() <= 0) {
setScrollingCacheEnabled(false);
return;
}
if (!always && mCurItem == item && mItems.size() != 0) {
setScrollingCacheEnabled(false);
return;
}
if (item < 0) {
item = 0;
} else if (item >= mAdapter.getCount()) {
item = mAdapter.getCount() - 1;
}
final int pageLimit = mOffscreenPageLimit;
if (item > (mCurItem + pageLimit) || item < (mCurItem - pageLimit)) {
// We are doing a jump by more than one page. To avoid
// glitches, we want to keep all current pages in the view
// until the scroll ends.
for (int i=0; i<mItems.size(); i++) {
mItems.get(i).scrolling = true;
}
}
final boolean dispatchSelected = mCurItem != item;
if (mFirstLayout) {
// We don't have any idea how big we are yet and shouldn't have any pages either.
// Just set things up and let the pending layout handle things.
mCurItem = item;
if (dispatchSelected && mOnPageChangeListener != null) {
mOnPageChangeListener.onPageSelected(item);
}
if (dispatchSelected && mInternalPageChangeListener != null) {
mInternalPageChangeListener.onPageSelected(item);
}
requestLayout();
} else {
populate(item);
scrollToItem(item, smoothScroll, velocity, dispatchSelected);
}
}
private void scrollToItem(int item, boolean smoothScroll, int velocity,
boolean dispatchSelected) {
final ItemInfo curInfo = infoForPosition(item);
int destX = 0;
if (curInfo != null) {
final int width = getClientWidth();
destX = (int) (width * Math.max(mFirstOffset,
Math.min(curInfo.offset, mLastOffset)));
}
if (smoothScroll) {
smoothScrollTo(destX, 0, velocity);
if (dispatchSelected && mOnPageChangeListener != null) {
mOnPageChangeListener.onPageSelected(item);
}
if (dispatchSelected && mInternalPageChangeListener != null) {
mInternalPageChangeListener.onPageSelected(item);
}
} else {
if (dispatchSelected && mOnPageChangeListener != null) {
mOnPageChangeListener.onPageSelected(item);
}
if (dispatchSelected && mInternalPageChangeListener != null) {
mInternalPageChangeListener.onPageSelected(item);
}
completeScroll(false);
scrollTo(destX, 0);
}
}
/**
* Set a listener that will be invoked whenever the page changes or is incrementally
* scrolled. See {@link OnPageChangeListener}.
*
* @param listener Listener to set
*/
public void setOnPageChangeListener(OnPageChangeListener listener) {
mOnPageChangeListener = listener;
}
/**
* Set a {@link PageTransformer} that will be called for each attached page whenever
* the scroll position is changed. This allows the application to apply custom property
* transformations to each page, overriding the default sliding look and feel.
*
* <p><em>Note:</em> Prior to Android 3.0 the property animation APIs did not exist.
* As a result, setting a PageTransformer prior to Android 3.0 (API 11) will have no effect.</p>
*
* @param reverseDrawingOrder true if the supplied PageTransformer requires page views
* to be drawn from last to first instead of first to last.
* @param transformer PageTransformer that will modify each page's animation properties
*/
public void setPageTransformer(boolean reverseDrawingOrder, PageTransformer transformer) {
if (Build.VERSION.SDK_INT >= 11) {
final boolean hasTransformer = transformer != null;
final boolean needsPopulate = hasTransformer != (mPageTransformer != null);
mPageTransformer = transformer;
setChildrenDrawingOrderEnabledCompat(hasTransformer);
if (hasTransformer) {
mDrawingOrder = reverseDrawingOrder ? DRAW_ORDER_REVERSE : DRAW_ORDER_FORWARD;
} else {
mDrawingOrder = DRAW_ORDER_DEFAULT;
}
if (needsPopulate) populate();
}
}
void setChildrenDrawingOrderEnabledCompat(boolean enable) {
if (Build.VERSION.SDK_INT >= 7) {
if (mSetChildrenDrawingOrderEnabled == null) {
try {
mSetChildrenDrawingOrderEnabled = ViewGroup.class.getDeclaredMethod(
"setChildrenDrawingOrderEnabled", new Class[] { Boolean.TYPE });
} catch (NoSuchMethodException e) {
Log.e(TAG, "Can't find setChildrenDrawingOrderEnabled", e);
}
}
try {
mSetChildrenDrawingOrderEnabled.invoke(this, enable);
} catch (Exception e) {
Log.e(TAG, "Error changing children drawing order", e);
}
}
}
@Override
protected int getChildDrawingOrder(int childCount, int i) {
final int index = mDrawingOrder == DRAW_ORDER_REVERSE ? childCount - 1 - i : i;
final int result = ((LayoutParams) mDrawingOrderedChildren.get(index).getLayoutParams()).childIndex;
return result;
}
/**
* Set a separate OnPageChangeListener for internal use by the support library.
*
* @param listener Listener to set
* @return The old listener that was set, if any.
*/
OnPageChangeListener setInternalPageChangeListener(OnPageChangeListener listener) {
OnPageChangeListener oldListener = mInternalPageChangeListener;
mInternalPageChangeListener = listener;
return oldListener;
}
/**
* Returns the number of pages that will be retained to either side of the
* current page in the view hierarchy in an idle state. Defaults to 1.
*
* @return How many pages will be kept offscreen on either side
* @see #setOffscreenPageLimit(int)
*/
public int getOffscreenPageLimit() {
return mOffscreenPageLimit;
}
/**
* Set the number of pages that should be retained to either side of the
* current page in the view hierarchy in an idle state. Pages beyond this
* limit will be recreated from the adapter when needed.
*
* <p>This is offered as an optimization. If you know in advance the number
* of pages you will need to support or have lazy-loading mechanisms in place
* on your pages, tweaking this setting can have benefits in perceived smoothness
* of paging animations and interaction. If you have a small number of pages (3-4)
* that you can keep active all at once, less time will be spent in layout for
* newly created view subtrees as the user pages back and forth.</p>
*
* <p>You should keep this limit low, especially if your pages have complex layouts.
* This setting defaults to 1.</p>
*
* @param limit How many pages will be kept offscreen in an idle state.
*/
public void setOffscreenPageLimit(int limit) {
if (limit < DEFAULT_OFFSCREEN_PAGES) {
Log.w(TAG, "Requested offscreen page limit " + limit + " too small; defaulting to " +
DEFAULT_OFFSCREEN_PAGES);
limit = DEFAULT_OFFSCREEN_PAGES;
}
if (limit != mOffscreenPageLimit) {
mOffscreenPageLimit = limit;
populate();
}
}
/**
* Set the margin between pages.
*
* @param marginPixels Distance between adjacent pages in pixels
* @see #getPageMargin()
* @see #setPageMarginDrawable(Drawable)
* @see #setPageMarginDrawable(int)
*/
public void setPageMargin(int marginPixels) {
final int oldMargin = mPageMargin;
mPageMargin = marginPixels;
final int width = getWidth();
recomputeScrollPosition(width, width, marginPixels, oldMargin);
requestLayout();
}
/**
* Return the margin between pages.
*
* @return The size of the margin in pixels
*/
public int getPageMargin() {
return mPageMargin;
}
/**
* Set a drawable that will be used to fill the margin between pages.
*
* @param d Drawable to display between pages
*/
public void setPageMarginDrawable(Drawable d) {
mMarginDrawable = d;
if (d != null) refreshDrawableState();
setWillNotDraw(d == null);
invalidate();
}
/**
* Set a drawable that will be used to fill the margin between pages.
*
* @param resId Resource ID of a drawable to display between pages
*/
public void setPageMarginDrawable(int resId) {
setPageMarginDrawable(getContext().getResources().getDrawable(resId));
}
@Override
protected boolean verifyDrawable(Drawable who) {
return super.verifyDrawable(who) || who == mMarginDrawable;
}
@Override
protected void drawableStateChanged() {
super.drawableStateChanged();
final Drawable d = mMarginDrawable;
if (d != null && d.isStateful()) {
d.setState(getDrawableState());
}
}
// We want the duration of the page snap animation to be influenced by the distance that
// the screen has to travel, however, we don't want this duration to be effected in a
// purely linear fashion. Instead, we use this method to moderate the effect that the distance
// of travel has on the overall snap duration.
float distanceInfluenceForSnapDuration(float f) {
f -= 0.5f; // center the values about 0.
f *= 0.3f * Math.PI / 2.0f;
return (float) Math.sin(f);
}
/**
* Like {@link View#scrollBy}, but scroll smoothly instead of immediately.
*
* @param x the number of pixels to scroll by on the X axis
* @param y the number of pixels to scroll by on the Y axis
*/
void smoothScrollTo(int x, int y) {
smoothScrollTo(x, y, 0);
}
/**
* Like {@link View#scrollBy}, but scroll smoothly instead of immediately.
*
* @param x the number of pixels to scroll by on the X axis
* @param y the number of pixels to scroll by on the Y axis
* @param velocity the velocity associated with a fling, if applicable. (0 otherwise)
*/
void smoothScrollTo(int x, int y, int velocity) {
if (getChildCount() == 0) {
// Nothing to do.
setScrollingCacheEnabled(false);
return;
}
int sx = getScrollX();
int sy = getScrollY();
int dx = x - sx;
int dy = y - sy;
if (dx == 0 && dy == 0) {
completeScroll(false);
populate();
setScrollState(SCROLL_STATE_IDLE);
return;
}
setScrollingCacheEnabled(true);
setScrollState(SCROLL_STATE_SETTLING);
final int width = getClientWidth();
final int halfWidth = width / 2;
final float distanceRatio = Math.min(1f, 1.0f * Math.abs(dx) / width);
final float distance = halfWidth + halfWidth *
distanceInfluenceForSnapDuration(distanceRatio);
int duration = 0;
velocity = Math.abs(velocity);
if (velocity > 0) {
duration = 4 * Math.round(1000 * Math.abs(distance / velocity));
} else {
final float pageWidth = width * mAdapter.getPageWidth(mCurItem);
final float pageDelta = (float) Math.abs(dx) / (pageWidth + mPageMargin);
duration = (int) ((pageDelta + 1) * 100);
}
duration = Math.min(duration, MAX_SETTLE_DURATION);
mScroller.startScroll(sx, sy, dx, dy, duration);
ViewCompat.postInvalidateOnAnimation(this);
}
ItemInfo addNewItem(int position, int index) {
ItemInfo ii = new ItemInfo();
ii.position = position;
ii.object = mAdapter.instantiateItem(this, position);
ii.widthFactor = mAdapter.getPageWidth(position);
if (index < 0 || index >= mItems.size()) {
mItems.add(ii);
} else {
mItems.add(index, ii);
}
return ii;
}
void dataSetChanged() {
// This method only gets called if our observer is attached, so mAdapter is non-null.
final int adapterCount = mAdapter.getCount();
mExpectedAdapterCount = adapterCount;
boolean needPopulate = mItems.size() < mOffscreenPageLimit * 2 + 1 &&
mItems.size() < adapterCount;
int newCurrItem = mCurItem;
boolean isUpdating = false;
for (int i = 0; i < mItems.size(); i++) {
final ItemInfo ii = mItems.get(i);
final int newPos = mAdapter.getItemPosition(ii.object);
if (newPos == PagerAdapter.POSITION_UNCHANGED) {
continue;
}
if (newPos == PagerAdapter.POSITION_NONE) {
mItems.remove(i);
i--;
if (!isUpdating) {
mAdapter.startUpdate(this);
isUpdating = true;
}
mAdapter.destroyItem(this, ii.position, ii.object);
needPopulate = true;
if (mCurItem == ii.position) {
// Keep the current item in the valid range
newCurrItem = Math.max(0, Math.min(mCurItem, adapterCount - 1));
needPopulate = true;
}
continue;
}
if (ii.position != newPos) {
if (ii.position == mCurItem) {
// Our current item changed position. Follow it.
newCurrItem = newPos;
}
ii.position = newPos;
needPopulate = true;
}
}
if (isUpdating) {
mAdapter.finishUpdate(this);
}
Collections.sort(mItems, COMPARATOR);
if (needPopulate) {
// Reset our known page widths; populate will recompute them.
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (!lp.isDecor) {
lp.widthFactor = 0.f;
}
}
setCurrentItemInternal(newCurrItem, false, true);
requestLayout();
}
}
void populate() {
populate(mCurItem);
}
void populate(int newCurrentItem) {
ItemInfo oldCurInfo = null;
int focusDirection = View.FOCUS_FORWARD;
if (mCurItem != newCurrentItem) {
focusDirection = mCurItem < newCurrentItem ? View.FOCUS_RIGHT : View.FOCUS_LEFT;
oldCurInfo = infoForPosition(mCurItem);
mCurItem = newCurrentItem;
}
if (mAdapter == null) {
sortChildDrawingOrder();
return;
}
// Bail now if we are waiting to populate. This is to hold off
// on creating views from the time the user releases their finger to
// fling to a new position until we have finished the scroll to
// that position, avoiding glitches from happening at that point.
if (mPopulatePending) {
if (DEBUG) Log.i(TAG, "populate is pending, skipping for now...");
sortChildDrawingOrder();
return;
}
// Also, don't populate until we are attached to a window. This is to
// avoid trying to populate before we have restored our view hierarchy
// state and conflicting with what is restored.
if (getWindowToken() == null) {
return;
}
mAdapter.startUpdate(this);
final int pageLimit = mOffscreenPageLimit;
final int startPos = Math.max(0, mCurItem - pageLimit);
final int N = mAdapter.getCount();
final int endPos = Math.min(N-1, mCurItem + pageLimit);
if (N != mExpectedAdapterCount) {
String resName;
try {
resName = getResources().getResourceName(getId());
} catch (Resources.NotFoundException e) {
resName = Integer.toHexString(getId());
}
throw new IllegalStateException("The application's PagerAdapter changed the adapter's" +
" contents without calling PagerAdapter#notifyDataSetChanged!" +
" Expected adapter item count: " + mExpectedAdapterCount + ", found: " + N +
" Pager id: " + resName +
" Pager class: " + getClass() +
" Problematic adapter: " + mAdapter.getClass());
}
// Locate the currently focused item or add it if needed.
int curIndex = -1;
ItemInfo curItem = null;
for (curIndex = 0; curIndex < mItems.size(); curIndex++) {
final ItemInfo ii = mItems.get(curIndex);
if (ii.position >= mCurItem) {
if (ii.position == mCurItem) curItem = ii;
break;
}
}
if (curItem == null && N > 0) {
curItem = addNewItem(mCurItem, curIndex);
}
// Fill 3x the available width or up to the number of offscreen
// pages requested to either side, whichever is larger.
// If we have no current item we have no work to do.
if (curItem != null) {
float extraWidthLeft = 0.f;
int itemIndex = curIndex - 1;
ItemInfo ii = itemIndex >= 0 ? mItems.get(itemIndex) : null;
- final float leftWidthNeeded = 2.f - curItem.widthFactor +
- (float) getPaddingLeft() / (float) getClientWidth();
+ final int clientWidth = getClientWidth();
+ final float leftWidthNeeded = clientWidth <= 0 ? 0 :
+ 2.f - curItem.widthFactor + (float) getPaddingLeft() / (float) clientWidth;
for (int pos = mCurItem - 1; pos >= 0; pos--) {
if (extraWidthLeft >= leftWidthNeeded && pos < startPos) {
if (ii == null) {
break;
}
if (pos == ii.position && !ii.scrolling) {
mItems.remove(itemIndex);
mAdapter.destroyItem(this, pos, ii.object);
if (DEBUG) {
Log.i(TAG, "populate() - destroyItem() with pos: " + pos +
" view: " + ((View) ii.object));
}
itemIndex--;
curIndex--;
ii = itemIndex >= 0 ? mItems.get(itemIndex) : null;
}
} else if (ii != null && pos == ii.position) {
extraWidthLeft += ii.widthFactor;
itemIndex--;
ii = itemIndex >= 0 ? mItems.get(itemIndex) : null;
} else {
ii = addNewItem(pos, itemIndex + 1);
extraWidthLeft += ii.widthFactor;
curIndex++;
ii = itemIndex >= 0 ? mItems.get(itemIndex) : null;
}
}
float extraWidthRight = curItem.widthFactor;
itemIndex = curIndex + 1;
if (extraWidthRight < 2.f) {
ii = itemIndex < mItems.size() ? mItems.get(itemIndex) : null;
- final float rightWidthNeeded = (float) getPaddingRight() / (float) getClientWidth()
- + 2.f;
+ final float rightWidthNeeded = clientWidth <= 0 ? 0 :
+ (float) getPaddingRight() / (float) clientWidth + 2.f;
for (int pos = mCurItem + 1; pos < N; pos++) {
if (extraWidthRight >= rightWidthNeeded && pos > endPos) {
if (ii == null) {
break;
}
if (pos == ii.position && !ii.scrolling) {
mItems.remove(itemIndex);
mAdapter.destroyItem(this, pos, ii.object);
if (DEBUG) {
Log.i(TAG, "populate() - destroyItem() with pos: " + pos +
" view: " + ((View) ii.object));
}
ii = itemIndex < mItems.size() ? mItems.get(itemIndex) : null;
}
} else if (ii != null && pos == ii.position) {
extraWidthRight += ii.widthFactor;
itemIndex++;
ii = itemIndex < mItems.size() ? mItems.get(itemIndex) : null;
} else {
ii = addNewItem(pos, itemIndex);
itemIndex++;
extraWidthRight += ii.widthFactor;
ii = itemIndex < mItems.size() ? mItems.get(itemIndex) : null;
}
}
}
calculatePageOffsets(curItem, curIndex, oldCurInfo);
}
if (DEBUG) {
Log.i(TAG, "Current page list:");
for (int i=0; i<mItems.size(); i++) {
Log.i(TAG, "#" + i + ": page " + mItems.get(i).position);
}
}
mAdapter.setPrimaryItem(this, mCurItem, curItem != null ? curItem.object : null);
mAdapter.finishUpdate(this);
// Check width measurement of current pages and drawing sort order.
// Update LayoutParams as needed.
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
lp.childIndex = i;
if (!lp.isDecor && lp.widthFactor == 0.f) {
// 0 means requery the adapter for this, it doesn't have a valid width.
final ItemInfo ii = infoForChild(child);
if (ii != null) {
lp.widthFactor = ii.widthFactor;
lp.position = ii.position;
}
}
}
sortChildDrawingOrder();
if (hasFocus()) {
View currentFocused = findFocus();
ItemInfo ii = currentFocused != null ? infoForAnyChild(currentFocused) : null;
if (ii == null || ii.position != mCurItem) {
for (int i=0; i<getChildCount(); i++) {
View child = getChildAt(i);
ii = infoForChild(child);
if (ii != null && ii.position == mCurItem) {
if (child.requestFocus(focusDirection)) {
break;
}
}
}
}
}
}
private void sortChildDrawingOrder() {
if (mDrawingOrder != DRAW_ORDER_DEFAULT) {
if (mDrawingOrderedChildren == null) {
mDrawingOrderedChildren = new ArrayList<View>();
} else {
mDrawingOrderedChildren.clear();
}
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
mDrawingOrderedChildren.add(child);
}
Collections.sort(mDrawingOrderedChildren, sPositionComparator);
}
}
private void calculatePageOffsets(ItemInfo curItem, int curIndex, ItemInfo oldCurInfo) {
final int N = mAdapter.getCount();
final int width = getClientWidth();
final float marginOffset = width > 0 ? (float) mPageMargin / width : 0;
// Fix up offsets for later layout.
if (oldCurInfo != null) {
final int oldCurPosition = oldCurInfo.position;
// Base offsets off of oldCurInfo.
if (oldCurPosition < curItem.position) {
int itemIndex = 0;
ItemInfo ii = null;
float offset = oldCurInfo.offset + oldCurInfo.widthFactor + marginOffset;
for (int pos = oldCurPosition + 1;
pos <= curItem.position && itemIndex < mItems.size(); pos++) {
ii = mItems.get(itemIndex);
while (pos > ii.position && itemIndex < mItems.size() - 1) {
itemIndex++;
ii = mItems.get(itemIndex);
}
while (pos < ii.position) {
// We don't have an item populated for this,
// ask the adapter for an offset.
offset += mAdapter.getPageWidth(pos) + marginOffset;
pos++;
}
ii.offset = offset;
offset += ii.widthFactor + marginOffset;
}
} else if (oldCurPosition > curItem.position) {
int itemIndex = mItems.size() - 1;
ItemInfo ii = null;
float offset = oldCurInfo.offset;
for (int pos = oldCurPosition - 1;
pos >= curItem.position && itemIndex >= 0; pos--) {
ii = mItems.get(itemIndex);
while (pos < ii.position && itemIndex > 0) {
itemIndex--;
ii = mItems.get(itemIndex);
}
while (pos > ii.position) {
// We don't have an item populated for this,
// ask the adapter for an offset.
offset -= mAdapter.getPageWidth(pos) + marginOffset;
pos--;
}
offset -= ii.widthFactor + marginOffset;
ii.offset = offset;
}
}
}
// Base all offsets off of curItem.
final int itemCount = mItems.size();
float offset = curItem.offset;
int pos = curItem.position - 1;
mFirstOffset = curItem.position == 0 ? curItem.offset : -Float.MAX_VALUE;
mLastOffset = curItem.position == N - 1 ?
curItem.offset + curItem.widthFactor - 1 : Float.MAX_VALUE;
// Previous pages
for (int i = curIndex - 1; i >= 0; i--, pos--) {
final ItemInfo ii = mItems.get(i);
while (pos > ii.position) {
offset -= mAdapter.getPageWidth(pos--) + marginOffset;
}
offset -= ii.widthFactor + marginOffset;
ii.offset = offset;
if (ii.position == 0) mFirstOffset = offset;
}
offset = curItem.offset + curItem.widthFactor + marginOffset;
pos = curItem.position + 1;
// Next pages
for (int i = curIndex + 1; i < itemCount; i++, pos++) {
final ItemInfo ii = mItems.get(i);
while (pos < ii.position) {
offset += mAdapter.getPageWidth(pos++) + marginOffset;
}
if (ii.position == N - 1) {
mLastOffset = offset + ii.widthFactor - 1;
}
ii.offset = offset;
offset += ii.widthFactor + marginOffset;
}
mNeedCalculatePageOffsets = false;
}
/**
* This is the persistent state that is saved by ViewPager. Only needed
* if you are creating a sublass of ViewPager that must save its own
* state, in which case it should implement a subclass of this which
* contains that state.
*/
public static class SavedState extends BaseSavedState {
int position;
Parcelable adapterState;
ClassLoader loader;
public SavedState(Parcelable superState) {
super(superState);
}
@Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeInt(position);
out.writeParcelable(adapterState, flags);
}
@Override
public String toString() {
return "FragmentPager.SavedState{"
+ Integer.toHexString(System.identityHashCode(this))
+ " position=" + position + "}";
}
public static final Parcelable.Creator<SavedState> CREATOR
= ParcelableCompat.newCreator(new ParcelableCompatCreatorCallbacks<SavedState>() {
@Override
public SavedState createFromParcel(Parcel in, ClassLoader loader) {
return new SavedState(in, loader);
}
@Override
public SavedState[] newArray(int size) {
return new SavedState[size];
}
});
SavedState(Parcel in, ClassLoader loader) {
super(in);
if (loader == null) {
loader = getClass().getClassLoader();
}
position = in.readInt();
adapterState = in.readParcelable(loader);
this.loader = loader;
}
}
@Override
public Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
SavedState ss = new SavedState(superState);
ss.position = mCurItem;
if (mAdapter != null) {
ss.adapterState = mAdapter.saveState();
}
return ss;
}
@Override
public void onRestoreInstanceState(Parcelable state) {
if (!(state instanceof SavedState)) {
super.onRestoreInstanceState(state);
return;
}
SavedState ss = (SavedState)state;
super.onRestoreInstanceState(ss.getSuperState());
if (mAdapter != null) {
mAdapter.restoreState(ss.adapterState, ss.loader);
setCurrentItemInternal(ss.position, false, true);
} else {
mRestoredCurItem = ss.position;
mRestoredAdapterState = ss.adapterState;
mRestoredClassLoader = ss.loader;
}
}
@Override
public void addView(View child, int index, ViewGroup.LayoutParams params) {
if (!checkLayoutParams(params)) {
params = generateLayoutParams(params);
}
final LayoutParams lp = (LayoutParams) params;
lp.isDecor |= child instanceof Decor;
if (mInLayout) {
if (lp != null && lp.isDecor) {
throw new IllegalStateException("Cannot add pager decor view during layout");
}
lp.needsMeasure = true;
addViewInLayout(child, index, params);
} else {
super.addView(child, index, params);
}
if (USE_CACHE) {
if (child.getVisibility() != GONE) {
child.setDrawingCacheEnabled(mScrollingCacheEnabled);
} else {
child.setDrawingCacheEnabled(false);
}
}
}
@Override
public void removeView(View view) {
if (mInLayout) {
removeViewInLayout(view);
} else {
super.removeView(view);
}
}
ItemInfo infoForChild(View child) {
for (int i=0; i<mItems.size(); i++) {
ItemInfo ii = mItems.get(i);
if (mAdapter.isViewFromObject(child, ii.object)) {
return ii;
}
}
return null;
}
ItemInfo infoForAnyChild(View child) {
ViewParent parent;
while ((parent=child.getParent()) != this) {
if (parent == null || !(parent instanceof View)) {
return null;
}
child = (View)parent;
}
return infoForChild(child);
}
ItemInfo infoForPosition(int position) {
for (int i = 0; i < mItems.size(); i++) {
ItemInfo ii = mItems.get(i);
if (ii.position == position) {
return ii;
}
}
return null;
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
mFirstLayout = true;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// For simple implementation, our internal size is always 0.
// We depend on the container to specify the layout size of
// our view. We can't really know what it is since we will be
// adding and removing different arbitrary views and do not
// want the layout to change as this happens.
setMeasuredDimension(getDefaultSize(0, widthMeasureSpec),
getDefaultSize(0, heightMeasureSpec));
final int measuredWidth = getMeasuredWidth();
final int maxGutterSize = measuredWidth / 10;
mGutterSize = Math.min(maxGutterSize, mDefaultGutterSize);
// Children are just made to fill our space.
int childWidthSize = measuredWidth - getPaddingLeft() - getPaddingRight();
int childHeightSize = getMeasuredHeight() - getPaddingTop() - getPaddingBottom();
/*
* Make sure all children have been properly measured. Decor views first.
* Right now we cheat and make this less complicated by assuming decor
* views won't intersect. We will pin to edges based on gravity.
*/
int size = getChildCount();
for (int i = 0; i < size; ++i) {
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (lp != null && lp.isDecor) {
final int hgrav = lp.gravity & Gravity.HORIZONTAL_GRAVITY_MASK;
final int vgrav = lp.gravity & Gravity.VERTICAL_GRAVITY_MASK;
int widthMode = MeasureSpec.AT_MOST;
int heightMode = MeasureSpec.AT_MOST;
boolean consumeVertical = vgrav == Gravity.TOP || vgrav == Gravity.BOTTOM;
boolean consumeHorizontal = hgrav == Gravity.LEFT || hgrav == Gravity.RIGHT;
if (consumeVertical) {
widthMode = MeasureSpec.EXACTLY;
} else if (consumeHorizontal) {
heightMode = MeasureSpec.EXACTLY;
}
int widthSize = childWidthSize;
int heightSize = childHeightSize;
if (lp.width != LayoutParams.WRAP_CONTENT) {
widthMode = MeasureSpec.EXACTLY;
if (lp.width != LayoutParams.FILL_PARENT) {
widthSize = lp.width;
}
}
if (lp.height != LayoutParams.WRAP_CONTENT) {
heightMode = MeasureSpec.EXACTLY;
if (lp.height != LayoutParams.FILL_PARENT) {
heightSize = lp.height;
}
}
final int widthSpec = MeasureSpec.makeMeasureSpec(widthSize, widthMode);
final int heightSpec = MeasureSpec.makeMeasureSpec(heightSize, heightMode);
child.measure(widthSpec, heightSpec);
if (consumeVertical) {
childHeightSize -= child.getMeasuredHeight();
} else if (consumeHorizontal) {
childWidthSize -= child.getMeasuredWidth();
}
}
}
}
mChildWidthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidthSize, MeasureSpec.EXACTLY);
mChildHeightMeasureSpec = MeasureSpec.makeMeasureSpec(childHeightSize, MeasureSpec.EXACTLY);
// Make sure we have created all fragments that we need to have shown.
mInLayout = true;
populate();
mInLayout = false;
// Page views next.
size = getChildCount();
for (int i = 0; i < size; ++i) {
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {
if (DEBUG) Log.v(TAG, "Measuring #" + i + " " + child
+ ": " + mChildWidthMeasureSpec);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (lp == null || !lp.isDecor) {
final int widthSpec = MeasureSpec.makeMeasureSpec(
(int) (childWidthSize * lp.widthFactor), MeasureSpec.EXACTLY);
child.measure(widthSpec, mChildHeightMeasureSpec);
}
}
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
// Make sure scroll position is set correctly.
if (w != oldw) {
recomputeScrollPosition(w, oldw, mPageMargin, mPageMargin);
}
}
private void recomputeScrollPosition(int width, int oldWidth, int margin, int oldMargin) {
if (oldWidth > 0 && !mItems.isEmpty()) {
final int widthWithMargin = width - getPaddingLeft() - getPaddingRight() + margin;
final int oldWidthWithMargin = oldWidth - getPaddingLeft() - getPaddingRight()
+ oldMargin;
final int xpos = getScrollX();
final float pageOffset = (float) xpos / oldWidthWithMargin;
final int newOffsetPixels = (int) (pageOffset * widthWithMargin);
scrollTo(newOffsetPixels, getScrollY());
if (!mScroller.isFinished()) {
// We now return to your regularly scheduled scroll, already in progress.
final int newDuration = mScroller.getDuration() - mScroller.timePassed();
ItemInfo targetInfo = infoForPosition(mCurItem);
mScroller.startScroll(newOffsetPixels, 0,
(int) (targetInfo.offset * width), 0, newDuration);
}
} else {
final ItemInfo ii = infoForPosition(mCurItem);
final float scrollOffset = ii != null ? Math.min(ii.offset, mLastOffset) : 0;
final int scrollPos = (int) (scrollOffset *
(width - getPaddingLeft() - getPaddingRight()));
if (scrollPos != getScrollX()) {
completeScroll(false);
scrollTo(scrollPos, getScrollY());
}
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
final int count = getChildCount();
int width = r - l;
int height = b - t;
int paddingLeft = getPaddingLeft();
int paddingTop = getPaddingTop();
int paddingRight = getPaddingRight();
int paddingBottom = getPaddingBottom();
final int scrollX = getScrollX();
int decorCount = 0;
// First pass - decor views. We need to do this in two passes so that
// we have the proper offsets for non-decor views later.
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
int childLeft = 0;
int childTop = 0;
if (lp.isDecor) {
final int hgrav = lp.gravity & Gravity.HORIZONTAL_GRAVITY_MASK;
final int vgrav = lp.gravity & Gravity.VERTICAL_GRAVITY_MASK;
switch (hgrav) {
default:
childLeft = paddingLeft;
break;
case Gravity.LEFT:
childLeft = paddingLeft;
paddingLeft += child.getMeasuredWidth();
break;
case Gravity.CENTER_HORIZONTAL:
childLeft = Math.max((width - child.getMeasuredWidth()) / 2,
paddingLeft);
break;
case Gravity.RIGHT:
childLeft = width - paddingRight - child.getMeasuredWidth();
paddingRight += child.getMeasuredWidth();
break;
}
switch (vgrav) {
default:
childTop = paddingTop;
break;
case Gravity.TOP:
childTop = paddingTop;
paddingTop += child.getMeasuredHeight();
break;
case Gravity.CENTER_VERTICAL:
childTop = Math.max((height - child.getMeasuredHeight()) / 2,
paddingTop);
break;
case Gravity.BOTTOM:
childTop = height - paddingBottom - child.getMeasuredHeight();
paddingBottom += child.getMeasuredHeight();
break;
}
childLeft += scrollX;
child.layout(childLeft, childTop,
childLeft + child.getMeasuredWidth(),
childTop + child.getMeasuredHeight());
decorCount++;
}
}
}
final int childWidth = width - paddingLeft - paddingRight;
// Page views. Do this once we have the right padding offsets from above.
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
ItemInfo ii;
if (!lp.isDecor && (ii = infoForChild(child)) != null) {
int loff = (int) (childWidth * ii.offset);
int childLeft = paddingLeft + loff;
int childTop = paddingTop;
if (lp.needsMeasure) {
// This was added during layout and needs measurement.
// Do it now that we know what we're working with.
lp.needsMeasure = false;
final int widthSpec = MeasureSpec.makeMeasureSpec(
(int) (childWidth * lp.widthFactor),
MeasureSpec.EXACTLY);
final int heightSpec = MeasureSpec.makeMeasureSpec(
(int) (height - paddingTop - paddingBottom),
MeasureSpec.EXACTLY);
child.measure(widthSpec, heightSpec);
}
if (DEBUG) Log.v(TAG, "Positioning #" + i + " " + child + " f=" + ii.object
+ ":" + childLeft + "," + childTop + " " + child.getMeasuredWidth()
+ "x" + child.getMeasuredHeight());
child.layout(childLeft, childTop,
childLeft + child.getMeasuredWidth(),
childTop + child.getMeasuredHeight());
}
}
}
mTopPageBounds = paddingTop;
mBottomPageBounds = height - paddingBottom;
mDecorChildCount = decorCount;
if (mFirstLayout) {
scrollToItem(mCurItem, false, 0, false);
}
mFirstLayout = false;
}
@Override
public void computeScroll() {
if (!mScroller.isFinished() && mScroller.computeScrollOffset()) {
int oldX = getScrollX();
int oldY = getScrollY();
int x = mScroller.getCurrX();
int y = mScroller.getCurrY();
if (oldX != x || oldY != y) {
scrollTo(x, y);
if (!pageScrolled(x)) {
mScroller.abortAnimation();
scrollTo(0, y);
}
}
// Keep on drawing until the animation has finished.
ViewCompat.postInvalidateOnAnimation(this);
return;
}
// Done with scroll, clean up state.
completeScroll(true);
}
private boolean pageScrolled(int xpos) {
if (mItems.size() == 0) {
mCalledSuper = false;
onPageScrolled(0, 0, 0);
if (!mCalledSuper) {
throw new IllegalStateException(
"onPageScrolled did not call superclass implementation");
}
return false;
}
final ItemInfo ii = infoForCurrentScrollPosition();
final int width = getClientWidth();
final int widthWithMargin = width + mPageMargin;
final float marginOffset = (float) mPageMargin / width;
final int currentPage = ii.position;
final float pageOffset = (((float) xpos / width) - ii.offset) /
(ii.widthFactor + marginOffset);
final int offsetPixels = (int) (pageOffset * widthWithMargin);
mCalledSuper = false;
onPageScrolled(currentPage, pageOffset, offsetPixels);
if (!mCalledSuper) {
throw new IllegalStateException(
"onPageScrolled did not call superclass implementation");
}
return true;
}
/**
* This method will be invoked when the current page is scrolled, either as part
* of a programmatically initiated smooth scroll or a user initiated touch scroll.
* If you override this method you must call through to the superclass implementation
* (e.g. super.onPageScrolled(position, offset, offsetPixels)) before onPageScrolled
* returns.
*
* @param position Position index of the first page currently being displayed.
* Page position+1 will be visible if positionOffset is nonzero.
* @param offset Value from [0, 1) indicating the offset from the page at position.
* @param offsetPixels Value in pixels indicating the offset from position.
*/
protected void onPageScrolled(int position, float offset, int offsetPixels) {
// Offset any decor views if needed - keep them on-screen at all times.
if (mDecorChildCount > 0) {
final int scrollX = getScrollX();
int paddingLeft = getPaddingLeft();
int paddingRight = getPaddingRight();
final int width = getWidth();
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (!lp.isDecor) continue;
final int hgrav = lp.gravity & Gravity.HORIZONTAL_GRAVITY_MASK;
int childLeft = 0;
switch (hgrav) {
default:
childLeft = paddingLeft;
break;
case Gravity.LEFT:
childLeft = paddingLeft;
paddingLeft += child.getWidth();
break;
case Gravity.CENTER_HORIZONTAL:
childLeft = Math.max((width - child.getMeasuredWidth()) / 2,
paddingLeft);
break;
case Gravity.RIGHT:
childLeft = width - paddingRight - child.getMeasuredWidth();
paddingRight += child.getMeasuredWidth();
break;
}
childLeft += scrollX;
final int childOffset = childLeft - child.getLeft();
if (childOffset != 0) {
child.offsetLeftAndRight(childOffset);
}
}
}
if (mOnPageChangeListener != null) {
mOnPageChangeListener.onPageScrolled(position, offset, offsetPixels);
}
if (mInternalPageChangeListener != null) {
mInternalPageChangeListener.onPageScrolled(position, offset, offsetPixels);
}
if (mPageTransformer != null) {
final int scrollX = getScrollX();
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (lp.isDecor) continue;
final float transformPos = (float) (child.getLeft() - scrollX) / getClientWidth();
mPageTransformer.transformPage(child, transformPos);
}
}
mCalledSuper = true;
}
private void completeScroll(boolean postEvents) {
boolean needPopulate = mScrollState == SCROLL_STATE_SETTLING;
if (needPopulate) {
// Done with scroll, no longer want to cache view drawing.
setScrollingCacheEnabled(false);
mScroller.abortAnimation();
int oldX = getScrollX();
int oldY = getScrollY();
int x = mScroller.getCurrX();
int y = mScroller.getCurrY();
if (oldX != x || oldY != y) {
scrollTo(x, y);
}
}
mPopulatePending = false;
for (int i=0; i<mItems.size(); i++) {
ItemInfo ii = mItems.get(i);
if (ii.scrolling) {
needPopulate = true;
ii.scrolling = false;
}
}
if (needPopulate) {
if (postEvents) {
ViewCompat.postOnAnimation(this, mEndScrollRunnable);
} else {
mEndScrollRunnable.run();
}
}
}
private boolean isGutterDrag(float x, float dx) {
return (x < mGutterSize && dx > 0) || (x > getWidth() - mGutterSize && dx < 0);
}
private void enableLayers(boolean enable) {
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final int layerType = enable ?
ViewCompat.LAYER_TYPE_HARDWARE : ViewCompat.LAYER_TYPE_NONE;
ViewCompat.setLayerType(getChildAt(i), layerType, null);
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
/*
* This method JUST determines whether we want to intercept the motion.
* If we return true, onMotionEvent will be called and we do the actual
* scrolling there.
*/
final int action = ev.getAction() & MotionEventCompat.ACTION_MASK;
// Always take care of the touch gesture being complete.
if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) {
// Release the drag.
if (DEBUG) Log.v(TAG, "Intercept done!");
mIsBeingDragged = false;
mIsUnableToDrag = false;
mActivePointerId = INVALID_POINTER;
if (mVelocityTracker != null) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
return false;
}
// Nothing more to do here if we have decided whether or not we
// are dragging.
if (action != MotionEvent.ACTION_DOWN) {
if (mIsBeingDragged) {
if (DEBUG) Log.v(TAG, "Intercept returning true!");
return true;
}
if (mIsUnableToDrag) {
if (DEBUG) Log.v(TAG, "Intercept returning false!");
return false;
}
}
switch (action) {
case MotionEvent.ACTION_MOVE: {
/*
* mIsBeingDragged == false, otherwise the shortcut would have caught it. Check
* whether the user has moved far enough from his original down touch.
*/
/*
* Locally do absolute value. mLastMotionY is set to the y value
* of the down event.
*/
final int activePointerId = mActivePointerId;
if (activePointerId == INVALID_POINTER) {
// If we don't have a valid id, the touch down wasn't on content.
break;
}
final int pointerIndex = MotionEventCompat.findPointerIndex(ev, activePointerId);
final float x = MotionEventCompat.getX(ev, pointerIndex);
final float dx = x - mLastMotionX;
final float xDiff = Math.abs(dx);
final float y = MotionEventCompat.getY(ev, pointerIndex);
final float yDiff = Math.abs(y - mInitialMotionY);
if (DEBUG) Log.v(TAG, "Moved x to " + x + "," + y + " diff=" + xDiff + "," + yDiff);
if (dx != 0 && !isGutterDrag(mLastMotionX, dx) &&
canScroll(this, false, (int) dx, (int) x, (int) y)) {
// Nested view has scrollable area under this point. Let it be handled there.
mLastMotionX = x;
mLastMotionY = y;
mIsUnableToDrag = true;
return false;
}
if (xDiff > mTouchSlop && xDiff * 0.5f > yDiff) {
if (DEBUG) Log.v(TAG, "Starting drag!");
mIsBeingDragged = true;
setScrollState(SCROLL_STATE_DRAGGING);
mLastMotionX = dx > 0 ? mInitialMotionX + mTouchSlop :
mInitialMotionX - mTouchSlop;
mLastMotionY = y;
setScrollingCacheEnabled(true);
} else if (yDiff > mTouchSlop) {
// The finger has moved enough in the vertical
// direction to be counted as a drag... abort
// any attempt to drag horizontally, to work correctly
// with children that have scrolling containers.
if (DEBUG) Log.v(TAG, "Starting unable to drag!");
mIsUnableToDrag = true;
}
if (mIsBeingDragged) {
// Scroll to follow the motion event
if (performDrag(x)) {
ViewCompat.postInvalidateOnAnimation(this);
}
}
break;
}
case MotionEvent.ACTION_DOWN: {
/*
* Remember location of down touch.
* ACTION_DOWN always refers to pointer index 0.
*/
mLastMotionX = mInitialMotionX = ev.getX();
mLastMotionY = mInitialMotionY = ev.getY();
mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
mIsUnableToDrag = false;
mScroller.computeScrollOffset();
if (mScrollState == SCROLL_STATE_SETTLING &&
Math.abs(mScroller.getFinalX() - mScroller.getCurrX()) > mCloseEnough) {
// Let the user 'catch' the pager as it animates.
mScroller.abortAnimation();
mPopulatePending = false;
populate();
mIsBeingDragged = true;
setScrollState(SCROLL_STATE_DRAGGING);
} else {
completeScroll(false);
mIsBeingDragged = false;
}
if (DEBUG) Log.v(TAG, "Down at " + mLastMotionX + "," + mLastMotionY
+ " mIsBeingDragged=" + mIsBeingDragged
+ "mIsUnableToDrag=" + mIsUnableToDrag);
break;
}
case MotionEventCompat.ACTION_POINTER_UP:
onSecondaryPointerUp(ev);
break;
}
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(ev);
/*
* The only time we want to intercept motion events is if we are in the
* drag mode.
*/
return mIsBeingDragged;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (mFakeDragging) {
// A fake drag is in progress already, ignore this real one
// but still eat the touch events.
// (It is likely that the user is multi-touching the screen.)
return true;
}
if (ev.getAction() == MotionEvent.ACTION_DOWN && ev.getEdgeFlags() != 0) {
// Don't handle edge touches immediately -- they may actually belong to one of our
// descendants.
return false;
}
if (mAdapter == null || mAdapter.getCount() == 0) {
// Nothing to present or scroll; nothing to touch.
return false;
}
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(ev);
final int action = ev.getAction();
boolean needsInvalidate = false;
switch (action & MotionEventCompat.ACTION_MASK) {
case MotionEvent.ACTION_DOWN: {
mScroller.abortAnimation();
mPopulatePending = false;
populate();
// Remember where the motion event started
mLastMotionX = mInitialMotionX = ev.getX();
mLastMotionY = mInitialMotionY = ev.getY();
mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
break;
}
case MotionEvent.ACTION_MOVE:
if (!mIsBeingDragged) {
final int pointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
final float x = MotionEventCompat.getX(ev, pointerIndex);
final float xDiff = Math.abs(x - mLastMotionX);
final float y = MotionEventCompat.getY(ev, pointerIndex);
final float yDiff = Math.abs(y - mLastMotionY);
if (DEBUG) Log.v(TAG, "Moved x to " + x + "," + y + " diff=" + xDiff + "," + yDiff);
if (xDiff > mTouchSlop && xDiff > yDiff) {
if (DEBUG) Log.v(TAG, "Starting drag!");
mIsBeingDragged = true;
mLastMotionX = x - mInitialMotionX > 0 ? mInitialMotionX + mTouchSlop :
mInitialMotionX - mTouchSlop;
mLastMotionY = y;
setScrollState(SCROLL_STATE_DRAGGING);
setScrollingCacheEnabled(true);
// Disallow Parent Intercept, just in case
ViewParent parent = getParent();
if (parent != null) {
parent.requestDisallowInterceptTouchEvent(true);
}
}
}
// Not else! Note that mIsBeingDragged can be set above.
if (mIsBeingDragged) {
// Scroll to follow the motion event
final int activePointerIndex = MotionEventCompat.findPointerIndex(
ev, mActivePointerId);
final float x = MotionEventCompat.getX(ev, activePointerIndex);
needsInvalidate |= performDrag(x);
}
break;
case MotionEvent.ACTION_UP:
if (mIsBeingDragged) {
final VelocityTracker velocityTracker = mVelocityTracker;
velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
int initialVelocity = (int) VelocityTrackerCompat.getXVelocity(
velocityTracker, mActivePointerId);
mPopulatePending = true;
final int width = getClientWidth();
final int scrollX = getScrollX();
final ItemInfo ii = infoForCurrentScrollPosition();
final int currentPage = ii.position;
final float pageOffset = (((float) scrollX / width) - ii.offset) / ii.widthFactor;
final int activePointerIndex =
MotionEventCompat.findPointerIndex(ev, mActivePointerId);
final float x = MotionEventCompat.getX(ev, activePointerIndex);
final int totalDelta = (int) (x - mInitialMotionX);
int nextPage = determineTargetPage(currentPage, pageOffset, initialVelocity,
totalDelta);
setCurrentItemInternal(nextPage, true, true, initialVelocity);
mActivePointerId = INVALID_POINTER;
endDrag();
needsInvalidate = mLeftEdge.onRelease() | mRightEdge.onRelease();
}
break;
case MotionEvent.ACTION_CANCEL:
if (mIsBeingDragged) {
scrollToItem(mCurItem, true, 0, false);
mActivePointerId = INVALID_POINTER;
endDrag();
needsInvalidate = mLeftEdge.onRelease() | mRightEdge.onRelease();
}
break;
case MotionEventCompat.ACTION_POINTER_DOWN: {
final int index = MotionEventCompat.getActionIndex(ev);
final float x = MotionEventCompat.getX(ev, index);
mLastMotionX = x;
mActivePointerId = MotionEventCompat.getPointerId(ev, index);
break;
}
case MotionEventCompat.ACTION_POINTER_UP:
onSecondaryPointerUp(ev);
mLastMotionX = MotionEventCompat.getX(ev,
MotionEventCompat.findPointerIndex(ev, mActivePointerId));
break;
}
if (needsInvalidate) {
ViewCompat.postInvalidateOnAnimation(this);
}
return true;
}
private boolean performDrag(float x) {
boolean needsInvalidate = false;
final float deltaX = mLastMotionX - x;
mLastMotionX = x;
float oldScrollX = getScrollX();
float scrollX = oldScrollX + deltaX;
final int width = getClientWidth();
float leftBound = width * mFirstOffset;
float rightBound = width * mLastOffset;
boolean leftAbsolute = true;
boolean rightAbsolute = true;
final ItemInfo firstItem = mItems.get(0);
final ItemInfo lastItem = mItems.get(mItems.size() - 1);
if (firstItem.position != 0) {
leftAbsolute = false;
leftBound = firstItem.offset * width;
}
if (lastItem.position != mAdapter.getCount() - 1) {
rightAbsolute = false;
rightBound = lastItem.offset * width;
}
if (scrollX < leftBound) {
if (leftAbsolute) {
float over = leftBound - scrollX;
needsInvalidate = mLeftEdge.onPull(Math.abs(over) / width);
}
scrollX = leftBound;
} else if (scrollX > rightBound) {
if (rightAbsolute) {
float over = scrollX - rightBound;
needsInvalidate = mRightEdge.onPull(Math.abs(over) / width);
}
scrollX = rightBound;
}
// Don't lose the rounded component
mLastMotionX += scrollX - (int) scrollX;
scrollTo((int) scrollX, getScrollY());
pageScrolled((int) scrollX);
return needsInvalidate;
}
/**
* @return Info about the page at the current scroll position.
* This can be synthetic for a missing middle page; the 'object' field can be null.
*/
private ItemInfo infoForCurrentScrollPosition() {
final int width = getClientWidth();
final float scrollOffset = width > 0 ? (float) getScrollX() / width : 0;
final float marginOffset = width > 0 ? (float) mPageMargin / width : 0;
int lastPos = -1;
float lastOffset = 0.f;
float lastWidth = 0.f;
boolean first = true;
ItemInfo lastItem = null;
for (int i = 0; i < mItems.size(); i++) {
ItemInfo ii = mItems.get(i);
float offset;
if (!first && ii.position != lastPos + 1) {
// Create a synthetic item for a missing page.
ii = mTempItem;
ii.offset = lastOffset + lastWidth + marginOffset;
ii.position = lastPos + 1;
ii.widthFactor = mAdapter.getPageWidth(ii.position);
i--;
}
offset = ii.offset;
final float leftBound = offset;
final float rightBound = offset + ii.widthFactor + marginOffset;
if (first || scrollOffset >= leftBound) {
if (scrollOffset < rightBound || i == mItems.size() - 1) {
return ii;
}
} else {
return lastItem;
}
first = false;
lastPos = ii.position;
lastOffset = offset;
lastWidth = ii.widthFactor;
lastItem = ii;
}
return lastItem;
}
private int determineTargetPage(int currentPage, float pageOffset, int velocity, int deltaX) {
int targetPage;
if (Math.abs(deltaX) > mFlingDistance && Math.abs(velocity) > mMinimumVelocity) {
targetPage = velocity > 0 ? currentPage : currentPage + 1;
} else {
final float truncator = currentPage >= mCurItem ? 0.4f : 0.6f;
targetPage = (int) (currentPage + pageOffset + truncator);
}
if (mItems.size() > 0) {
final ItemInfo firstItem = mItems.get(0);
final ItemInfo lastItem = mItems.get(mItems.size() - 1);
// Only let the user target pages we have items for
targetPage = Math.max(firstItem.position, Math.min(targetPage, lastItem.position));
}
return targetPage;
}
@Override
public void draw(Canvas canvas) {
super.draw(canvas);
boolean needsInvalidate = false;
final int overScrollMode = ViewCompat.getOverScrollMode(this);
if (overScrollMode == ViewCompat.OVER_SCROLL_ALWAYS ||
(overScrollMode == ViewCompat.OVER_SCROLL_IF_CONTENT_SCROLLS &&
mAdapter != null && mAdapter.getCount() > 1)) {
if (!mLeftEdge.isFinished()) {
final int restoreCount = canvas.save();
final int height = getHeight() - getPaddingTop() - getPaddingBottom();
final int width = getWidth();
canvas.rotate(270);
canvas.translate(-height + getPaddingTop(), mFirstOffset * width);
mLeftEdge.setSize(height, width);
needsInvalidate |= mLeftEdge.draw(canvas);
canvas.restoreToCount(restoreCount);
}
if (!mRightEdge.isFinished()) {
final int restoreCount = canvas.save();
final int width = getWidth();
final int height = getHeight() - getPaddingTop() - getPaddingBottom();
canvas.rotate(90);
canvas.translate(-getPaddingTop(), -(mLastOffset + 1) * width);
mRightEdge.setSize(height, width);
needsInvalidate |= mRightEdge.draw(canvas);
canvas.restoreToCount(restoreCount);
}
} else {
mLeftEdge.finish();
mRightEdge.finish();
}
if (needsInvalidate) {
// Keep animating
ViewCompat.postInvalidateOnAnimation(this);
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Draw the margin drawable between pages if needed.
if (mPageMargin > 0 && mMarginDrawable != null && mItems.size() > 0 && mAdapter != null) {
final int scrollX = getScrollX();
final int width = getWidth();
final float marginOffset = (float) mPageMargin / width;
int itemIndex = 0;
ItemInfo ii = mItems.get(0);
float offset = ii.offset;
final int itemCount = mItems.size();
final int firstPos = ii.position;
final int lastPos = mItems.get(itemCount - 1).position;
for (int pos = firstPos; pos < lastPos; pos++) {
while (pos > ii.position && itemIndex < itemCount) {
ii = mItems.get(++itemIndex);
}
float drawAt;
if (pos == ii.position) {
drawAt = (ii.offset + ii.widthFactor) * width;
offset = ii.offset + ii.widthFactor + marginOffset;
} else {
float widthFactor = mAdapter.getPageWidth(pos);
drawAt = (offset + widthFactor) * width;
offset += widthFactor + marginOffset;
}
if (drawAt + mPageMargin > scrollX) {
mMarginDrawable.setBounds((int) drawAt, mTopPageBounds,
(int) (drawAt + mPageMargin + 0.5f), mBottomPageBounds);
mMarginDrawable.draw(canvas);
}
if (drawAt > scrollX + width) {
break; // No more visible, no sense in continuing
}
}
}
}
/**
* Start a fake drag of the pager.
*
* <p>A fake drag can be useful if you want to synchronize the motion of the ViewPager
* with the touch scrolling of another view, while still letting the ViewPager
* control the snapping motion and fling behavior. (e.g. parallax-scrolling tabs.)
* Call {@link #fakeDragBy(float)} to simulate the actual drag motion. Call
* {@link #endFakeDrag()} to complete the fake drag and fling as necessary.
*
* <p>During a fake drag the ViewPager will ignore all touch events. If a real drag
* is already in progress, this method will return false.
*
* @return true if the fake drag began successfully, false if it could not be started.
*
* @see #fakeDragBy(float)
* @see #endFakeDrag()
*/
public boolean beginFakeDrag() {
if (mIsBeingDragged) {
return false;
}
mFakeDragging = true;
setScrollState(SCROLL_STATE_DRAGGING);
mInitialMotionX = mLastMotionX = 0;
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
} else {
mVelocityTracker.clear();
}
final long time = SystemClock.uptimeMillis();
final MotionEvent ev = MotionEvent.obtain(time, time, MotionEvent.ACTION_DOWN, 0, 0, 0);
mVelocityTracker.addMovement(ev);
ev.recycle();
mFakeDragBeginTime = time;
return true;
}
/**
* End a fake drag of the pager.
*
* @see #beginFakeDrag()
* @see #fakeDragBy(float)
*/
public void endFakeDrag() {
if (!mFakeDragging) {
throw new IllegalStateException("No fake drag in progress. Call beginFakeDrag first.");
}
final VelocityTracker velocityTracker = mVelocityTracker;
velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
int initialVelocity = (int) VelocityTrackerCompat.getXVelocity(
velocityTracker, mActivePointerId);
mPopulatePending = true;
final int width = getClientWidth();
final int scrollX = getScrollX();
final ItemInfo ii = infoForCurrentScrollPosition();
final int currentPage = ii.position;
final float pageOffset = (((float) scrollX / width) - ii.offset) / ii.widthFactor;
final int totalDelta = (int) (mLastMotionX - mInitialMotionX);
int nextPage = determineTargetPage(currentPage, pageOffset, initialVelocity,
totalDelta);
setCurrentItemInternal(nextPage, true, true, initialVelocity);
endDrag();
mFakeDragging = false;
}
/**
* Fake drag by an offset in pixels. You must have called {@link #beginFakeDrag()} first.
*
* @param xOffset Offset in pixels to drag by.
* @see #beginFakeDrag()
* @see #endFakeDrag()
*/
public void fakeDragBy(float xOffset) {
if (!mFakeDragging) {
throw new IllegalStateException("No fake drag in progress. Call beginFakeDrag first.");
}
mLastMotionX += xOffset;
float oldScrollX = getScrollX();
float scrollX = oldScrollX - xOffset;
final int width = getClientWidth();
float leftBound = width * mFirstOffset;
float rightBound = width * mLastOffset;
final ItemInfo firstItem = mItems.get(0);
final ItemInfo lastItem = mItems.get(mItems.size() - 1);
if (firstItem.position != 0) {
leftBound = firstItem.offset * width;
}
if (lastItem.position != mAdapter.getCount() - 1) {
rightBound = lastItem.offset * width;
}
if (scrollX < leftBound) {
scrollX = leftBound;
} else if (scrollX > rightBound) {
scrollX = rightBound;
}
// Don't lose the rounded component
mLastMotionX += scrollX - (int) scrollX;
scrollTo((int) scrollX, getScrollY());
pageScrolled((int) scrollX);
// Synthesize an event for the VelocityTracker.
final long time = SystemClock.uptimeMillis();
final MotionEvent ev = MotionEvent.obtain(mFakeDragBeginTime, time, MotionEvent.ACTION_MOVE,
mLastMotionX, 0, 0);
mVelocityTracker.addMovement(ev);
ev.recycle();
}
/**
* Returns true if a fake drag is in progress.
*
* @return true if currently in a fake drag, false otherwise.
*
* @see #beginFakeDrag()
* @see #fakeDragBy(float)
* @see #endFakeDrag()
*/
public boolean isFakeDragging() {
return mFakeDragging;
}
private void onSecondaryPointerUp(MotionEvent ev) {
final int pointerIndex = MotionEventCompat.getActionIndex(ev);
final int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex);
if (pointerId == mActivePointerId) {
// This was our active pointer going up. Choose a new
// active pointer and adjust accordingly.
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
mLastMotionX = MotionEventCompat.getX(ev, newPointerIndex);
mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex);
if (mVelocityTracker != null) {
mVelocityTracker.clear();
}
}
}
private void endDrag() {
mIsBeingDragged = false;
mIsUnableToDrag = false;
if (mVelocityTracker != null) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
}
private void setScrollingCacheEnabled(boolean enabled) {
if (mScrollingCacheEnabled != enabled) {
mScrollingCacheEnabled = enabled;
if (USE_CACHE) {
final int size = getChildCount();
for (int i = 0; i < size; ++i) {
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {
child.setDrawingCacheEnabled(enabled);
}
}
}
}
}
/**
* Tests scrollability within child views of v given a delta of dx.
*
* @param v View to test for horizontal scrollability
* @param checkV Whether the view v passed should itself be checked for scrollability (true),
* or just its children (false).
* @param dx Delta scrolled in pixels
* @param x X coordinate of the active touch point
* @param y Y coordinate of the active touch point
* @return true if child views of v can be scrolled by delta of dx.
*/
protected boolean canScroll(View v, boolean checkV, int dx, int x, int y) {
if (v instanceof ViewGroup) {
final ViewGroup group = (ViewGroup) v;
final int scrollX = v.getScrollX();
final int scrollY = v.getScrollY();
final int count = group.getChildCount();
// Count backwards - let topmost views consume scroll distance first.
for (int i = count - 1; i >= 0; i--) {
// TODO: Add versioned support here for transformed views.
// This will not work for transformed views in Honeycomb+
final View child = group.getChildAt(i);
if (x + scrollX >= child.getLeft() && x + scrollX < child.getRight() &&
y + scrollY >= child.getTop() && y + scrollY < child.getBottom() &&
canScroll(child, true, dx, x + scrollX - child.getLeft(),
y + scrollY - child.getTop())) {
return true;
}
}
}
return checkV && ViewCompat.canScrollHorizontally(v, -dx);
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
// Let the focused view and/or our descendants get the key first
return super.dispatchKeyEvent(event) || executeKeyEvent(event);
}
/**
* You can call this function yourself to have the scroll view perform
* scrolling from a key event, just as if the event had been dispatched to
* it by the view hierarchy.
*
* @param event The key event to execute.
* @return Return true if the event was handled, else false.
*/
public boolean executeKeyEvent(KeyEvent event) {
boolean handled = false;
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_DPAD_LEFT:
handled = arrowScroll(FOCUS_LEFT);
break;
case KeyEvent.KEYCODE_DPAD_RIGHT:
handled = arrowScroll(FOCUS_RIGHT);
break;
case KeyEvent.KEYCODE_TAB:
if (Build.VERSION.SDK_INT >= 11) {
// The focus finder had a bug handling FOCUS_FORWARD and FOCUS_BACKWARD
// before Android 3.0. Ignore the tab key on those devices.
if (KeyEventCompat.hasNoModifiers(event)) {
handled = arrowScroll(FOCUS_FORWARD);
} else if (KeyEventCompat.hasModifiers(event, KeyEvent.META_SHIFT_ON)) {
handled = arrowScroll(FOCUS_BACKWARD);
}
}
break;
}
}
return handled;
}
public boolean arrowScroll(int direction) {
View currentFocused = findFocus();
if (currentFocused == this) {
currentFocused = null;
} else if (currentFocused != null) {
boolean isChild = false;
for (ViewParent parent = currentFocused.getParent(); parent instanceof ViewGroup;
parent = parent.getParent()) {
if (parent == this) {
isChild = true;
break;
}
}
if (!isChild) {
// This would cause the focus search down below to fail in fun ways.
final StringBuilder sb = new StringBuilder();
sb.append(currentFocused.getClass().getSimpleName());
for (ViewParent parent = currentFocused.getParent(); parent instanceof ViewGroup;
parent = parent.getParent()) {
sb.append(" => ").append(parent.getClass().getSimpleName());
}
Log.e(TAG, "arrowScroll tried to find focus based on non-child " +
"current focused view " + sb.toString());
currentFocused = null;
}
}
boolean handled = false;
View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused,
direction);
if (nextFocused != null && nextFocused != currentFocused) {
if (direction == View.FOCUS_LEFT) {
// If there is nothing to the left, or this is causing us to
// jump to the right, then what we really want to do is page left.
final int nextLeft = getChildRectInPagerCoordinates(mTempRect, nextFocused).left;
final int currLeft = getChildRectInPagerCoordinates(mTempRect, currentFocused).left;
if (currentFocused != null && nextLeft >= currLeft) {
handled = pageLeft();
} else {
handled = nextFocused.requestFocus();
}
} else if (direction == View.FOCUS_RIGHT) {
// If there is nothing to the right, or this is causing us to
// jump to the left, then what we really want to do is page right.
final int nextLeft = getChildRectInPagerCoordinates(mTempRect, nextFocused).left;
final int currLeft = getChildRectInPagerCoordinates(mTempRect, currentFocused).left;
if (currentFocused != null && nextLeft <= currLeft) {
handled = pageRight();
} else {
handled = nextFocused.requestFocus();
}
}
} else if (direction == FOCUS_LEFT || direction == FOCUS_BACKWARD) {
// Trying to move left and nothing there; try to page.
handled = pageLeft();
} else if (direction == FOCUS_RIGHT || direction == FOCUS_FORWARD) {
// Trying to move right and nothing there; try to page.
handled = pageRight();
}
if (handled) {
playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction));
}
return handled;
}
private Rect getChildRectInPagerCoordinates(Rect outRect, View child) {
if (outRect == null) {
outRect = new Rect();
}
if (child == null) {
outRect.set(0, 0, 0, 0);
return outRect;
}
outRect.left = child.getLeft();
outRect.right = child.getRight();
outRect.top = child.getTop();
outRect.bottom = child.getBottom();
ViewParent parent = child.getParent();
while (parent instanceof ViewGroup && parent != this) {
final ViewGroup group = (ViewGroup) parent;
outRect.left += group.getLeft();
outRect.right += group.getRight();
outRect.top += group.getTop();
outRect.bottom += group.getBottom();
parent = group.getParent();
}
return outRect;
}
boolean pageLeft() {
if (mCurItem > 0) {
setCurrentItem(mCurItem-1, true);
return true;
}
return false;
}
boolean pageRight() {
if (mAdapter != null && mCurItem < (mAdapter.getCount()-1)) {
setCurrentItem(mCurItem+1, true);
return true;
}
return false;
}
/**
* We only want the current page that is being shown to be focusable.
*/
@Override
public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
final int focusableCount = views.size();
final int descendantFocusability = getDescendantFocusability();
if (descendantFocusability != FOCUS_BLOCK_DESCENDANTS) {
for (int i = 0; i < getChildCount(); i++) {
final View child = getChildAt(i);
if (child.getVisibility() == VISIBLE) {
ItemInfo ii = infoForChild(child);
if (ii != null && ii.position == mCurItem) {
child.addFocusables(views, direction, focusableMode);
}
}
}
}
// we add ourselves (if focusable) in all cases except for when we are
// FOCUS_AFTER_DESCENDANTS and there are some descendants focusable. this is
// to avoid the focus search finding layouts when a more precise search
// among the focusable children would be more interesting.
if (
descendantFocusability != FOCUS_AFTER_DESCENDANTS ||
// No focusable descendants
(focusableCount == views.size())) {
// Note that we can't call the superclass here, because it will
// add all views in. So we need to do the same thing View does.
if (!isFocusable()) {
return;
}
if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE &&
isInTouchMode() && !isFocusableInTouchMode()) {
return;
}
if (views != null) {
views.add(this);
}
}
}
/**
* We only want the current page that is being shown to be touchable.
*/
@Override
public void addTouchables(ArrayList<View> views) {
// Note that we don't call super.addTouchables(), which means that
// we don't call View.addTouchables(). This is okay because a ViewPager
// is itself not touchable.
for (int i = 0; i < getChildCount(); i++) {
final View child = getChildAt(i);
if (child.getVisibility() == VISIBLE) {
ItemInfo ii = infoForChild(child);
if (ii != null && ii.position == mCurItem) {
child.addTouchables(views);
}
}
}
}
/**
* We only want the current page that is being shown to be focusable.
*/
@Override
protected boolean onRequestFocusInDescendants(int direction,
Rect previouslyFocusedRect) {
int index;
int increment;
int end;
int count = getChildCount();
if ((direction & FOCUS_FORWARD) != 0) {
index = 0;
increment = 1;
end = count;
} else {
index = count - 1;
increment = -1;
end = -1;
}
for (int i = index; i != end; i += increment) {
View child = getChildAt(i);
if (child.getVisibility() == VISIBLE) {
ItemInfo ii = infoForChild(child);
if (ii != null && ii.position == mCurItem) {
if (child.requestFocus(direction, previouslyFocusedRect)) {
return true;
}
}
}
}
return false;
}
@Override
public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
// Dispatch scroll events from this ViewPager.
if (event.getEventType() == AccessibilityEventCompat.TYPE_VIEW_SCROLLED) {
return super.dispatchPopulateAccessibilityEvent(event);
}
// Dispatch all other accessibility events from the current page.
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
if (child.getVisibility() == VISIBLE) {
final ItemInfo ii = infoForChild(child);
if (ii != null && ii.position == mCurItem &&
child.dispatchPopulateAccessibilityEvent(event)) {
return true;
}
}
}
return false;
}
@Override
protected ViewGroup.LayoutParams generateDefaultLayoutParams() {
return new LayoutParams();
}
@Override
protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
return generateDefaultLayoutParams();
}
@Override
protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
return p instanceof LayoutParams && super.checkLayoutParams(p);
}
@Override
public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
return new LayoutParams(getContext(), attrs);
}
class MyAccessibilityDelegate extends AccessibilityDelegateCompat {
@Override
public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
super.onInitializeAccessibilityEvent(host, event);
event.setClassName(ViewPager.class.getName());
final AccessibilityRecordCompat recordCompat = AccessibilityRecordCompat.obtain();
recordCompat.setScrollable(canScroll());
if (event.getEventType() == AccessibilityEventCompat.TYPE_VIEW_SCROLLED) {
recordCompat.setItemCount(mAdapter.getCount());
recordCompat.setFromIndex(mCurItem);
recordCompat.setToIndex(mCurItem);
}
}
@Override
public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfoCompat info) {
super.onInitializeAccessibilityNodeInfo(host, info);
info.setClassName(ViewPager.class.getName());
info.setScrollable(canScroll());
if (canScrollForward()) {
info.addAction(AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD);
}
if (canScrollBackward()) {
info.addAction(AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD);
}
}
@Override
public boolean performAccessibilityAction(View host, int action, Bundle args) {
if (super.performAccessibilityAction(host, action, args)) {
return true;
}
switch (action) {
case AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD: {
if (canScrollForward()) {
setCurrentItem(mCurItem + 1);
return true;
}
} return false;
case AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD: {
if (canScrollBackward()) {
setCurrentItem(mCurItem - 1);
return true;
}
} return false;
}
return false;
}
private boolean canScroll() {
return (mAdapter != null) && (mAdapter.getCount() > 1);
}
private boolean canScrollForward() {
return (mAdapter != null) && (mCurItem >= 0) && (mCurItem < (mAdapter.getCount() - 1));
}
private boolean canScrollBackward() {
return (mAdapter != null) && (mCurItem > 0) && (mCurItem < mAdapter.getCount());
}
}
private class PagerObserver extends DataSetObserver {
@Override
public void onChanged() {
dataSetChanged();
}
@Override
public void onInvalidated() {
dataSetChanged();
}
}
/**
* Layout parameters that should be supplied for views added to a
* ViewPager.
*/
public static class LayoutParams extends ViewGroup.LayoutParams {
/**
* true if this view is a decoration on the pager itself and not
* a view supplied by the adapter.
*/
public boolean isDecor;
/**
* Gravity setting for use on decor views only:
* Where to position the view page within the overall ViewPager
* container; constants are defined in {@link android.view.Gravity}.
*/
public int gravity;
/**
* Width as a 0-1 multiplier of the measured pager width
*/
float widthFactor = 0.f;
/**
* true if this view was added during layout and needs to be measured
* before being positioned.
*/
boolean needsMeasure;
/**
* Adapter position this view is for if !isDecor
*/
int position;
/**
* Current child index within the ViewPager that this view occupies
*/
int childIndex;
public LayoutParams() {
super(FILL_PARENT, FILL_PARENT);
}
public LayoutParams(Context context, AttributeSet attrs) {
super(context, attrs);
final TypedArray a = context.obtainStyledAttributes(attrs, LAYOUT_ATTRS);
gravity = a.getInteger(0, Gravity.TOP);
a.recycle();
}
}
static class ViewPositionComparator implements Comparator<View> {
@Override
public int compare(View lhs, View rhs) {
final LayoutParams llp = (LayoutParams) lhs.getLayoutParams();
final LayoutParams rlp = (LayoutParams) rhs.getLayoutParams();
if (llp.isDecor != rlp.isDecor) {
return llp.isDecor ? 1 : -1;
}
return llp.position - rlp.position;
}
}
}
| false | true | void populate(int newCurrentItem) {
ItemInfo oldCurInfo = null;
int focusDirection = View.FOCUS_FORWARD;
if (mCurItem != newCurrentItem) {
focusDirection = mCurItem < newCurrentItem ? View.FOCUS_RIGHT : View.FOCUS_LEFT;
oldCurInfo = infoForPosition(mCurItem);
mCurItem = newCurrentItem;
}
if (mAdapter == null) {
sortChildDrawingOrder();
return;
}
// Bail now if we are waiting to populate. This is to hold off
// on creating views from the time the user releases their finger to
// fling to a new position until we have finished the scroll to
// that position, avoiding glitches from happening at that point.
if (mPopulatePending) {
if (DEBUG) Log.i(TAG, "populate is pending, skipping for now...");
sortChildDrawingOrder();
return;
}
// Also, don't populate until we are attached to a window. This is to
// avoid trying to populate before we have restored our view hierarchy
// state and conflicting with what is restored.
if (getWindowToken() == null) {
return;
}
mAdapter.startUpdate(this);
final int pageLimit = mOffscreenPageLimit;
final int startPos = Math.max(0, mCurItem - pageLimit);
final int N = mAdapter.getCount();
final int endPos = Math.min(N-1, mCurItem + pageLimit);
if (N != mExpectedAdapterCount) {
String resName;
try {
resName = getResources().getResourceName(getId());
} catch (Resources.NotFoundException e) {
resName = Integer.toHexString(getId());
}
throw new IllegalStateException("The application's PagerAdapter changed the adapter's" +
" contents without calling PagerAdapter#notifyDataSetChanged!" +
" Expected adapter item count: " + mExpectedAdapterCount + ", found: " + N +
" Pager id: " + resName +
" Pager class: " + getClass() +
" Problematic adapter: " + mAdapter.getClass());
}
// Locate the currently focused item or add it if needed.
int curIndex = -1;
ItemInfo curItem = null;
for (curIndex = 0; curIndex < mItems.size(); curIndex++) {
final ItemInfo ii = mItems.get(curIndex);
if (ii.position >= mCurItem) {
if (ii.position == mCurItem) curItem = ii;
break;
}
}
if (curItem == null && N > 0) {
curItem = addNewItem(mCurItem, curIndex);
}
// Fill 3x the available width or up to the number of offscreen
// pages requested to either side, whichever is larger.
// If we have no current item we have no work to do.
if (curItem != null) {
float extraWidthLeft = 0.f;
int itemIndex = curIndex - 1;
ItemInfo ii = itemIndex >= 0 ? mItems.get(itemIndex) : null;
final float leftWidthNeeded = 2.f - curItem.widthFactor +
(float) getPaddingLeft() / (float) getClientWidth();
for (int pos = mCurItem - 1; pos >= 0; pos--) {
if (extraWidthLeft >= leftWidthNeeded && pos < startPos) {
if (ii == null) {
break;
}
if (pos == ii.position && !ii.scrolling) {
mItems.remove(itemIndex);
mAdapter.destroyItem(this, pos, ii.object);
if (DEBUG) {
Log.i(TAG, "populate() - destroyItem() with pos: " + pos +
" view: " + ((View) ii.object));
}
itemIndex--;
curIndex--;
ii = itemIndex >= 0 ? mItems.get(itemIndex) : null;
}
} else if (ii != null && pos == ii.position) {
extraWidthLeft += ii.widthFactor;
itemIndex--;
ii = itemIndex >= 0 ? mItems.get(itemIndex) : null;
} else {
ii = addNewItem(pos, itemIndex + 1);
extraWidthLeft += ii.widthFactor;
curIndex++;
ii = itemIndex >= 0 ? mItems.get(itemIndex) : null;
}
}
float extraWidthRight = curItem.widthFactor;
itemIndex = curIndex + 1;
if (extraWidthRight < 2.f) {
ii = itemIndex < mItems.size() ? mItems.get(itemIndex) : null;
final float rightWidthNeeded = (float) getPaddingRight() / (float) getClientWidth()
+ 2.f;
for (int pos = mCurItem + 1; pos < N; pos++) {
if (extraWidthRight >= rightWidthNeeded && pos > endPos) {
if (ii == null) {
break;
}
if (pos == ii.position && !ii.scrolling) {
mItems.remove(itemIndex);
mAdapter.destroyItem(this, pos, ii.object);
if (DEBUG) {
Log.i(TAG, "populate() - destroyItem() with pos: " + pos +
" view: " + ((View) ii.object));
}
ii = itemIndex < mItems.size() ? mItems.get(itemIndex) : null;
}
} else if (ii != null && pos == ii.position) {
extraWidthRight += ii.widthFactor;
itemIndex++;
ii = itemIndex < mItems.size() ? mItems.get(itemIndex) : null;
} else {
ii = addNewItem(pos, itemIndex);
itemIndex++;
extraWidthRight += ii.widthFactor;
ii = itemIndex < mItems.size() ? mItems.get(itemIndex) : null;
}
}
}
calculatePageOffsets(curItem, curIndex, oldCurInfo);
}
if (DEBUG) {
Log.i(TAG, "Current page list:");
for (int i=0; i<mItems.size(); i++) {
Log.i(TAG, "#" + i + ": page " + mItems.get(i).position);
}
}
mAdapter.setPrimaryItem(this, mCurItem, curItem != null ? curItem.object : null);
mAdapter.finishUpdate(this);
// Check width measurement of current pages and drawing sort order.
// Update LayoutParams as needed.
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
lp.childIndex = i;
if (!lp.isDecor && lp.widthFactor == 0.f) {
// 0 means requery the adapter for this, it doesn't have a valid width.
final ItemInfo ii = infoForChild(child);
if (ii != null) {
lp.widthFactor = ii.widthFactor;
lp.position = ii.position;
}
}
}
sortChildDrawingOrder();
if (hasFocus()) {
View currentFocused = findFocus();
ItemInfo ii = currentFocused != null ? infoForAnyChild(currentFocused) : null;
if (ii == null || ii.position != mCurItem) {
for (int i=0; i<getChildCount(); i++) {
View child = getChildAt(i);
ii = infoForChild(child);
if (ii != null && ii.position == mCurItem) {
if (child.requestFocus(focusDirection)) {
break;
}
}
}
}
}
}
| void populate(int newCurrentItem) {
ItemInfo oldCurInfo = null;
int focusDirection = View.FOCUS_FORWARD;
if (mCurItem != newCurrentItem) {
focusDirection = mCurItem < newCurrentItem ? View.FOCUS_RIGHT : View.FOCUS_LEFT;
oldCurInfo = infoForPosition(mCurItem);
mCurItem = newCurrentItem;
}
if (mAdapter == null) {
sortChildDrawingOrder();
return;
}
// Bail now if we are waiting to populate. This is to hold off
// on creating views from the time the user releases their finger to
// fling to a new position until we have finished the scroll to
// that position, avoiding glitches from happening at that point.
if (mPopulatePending) {
if (DEBUG) Log.i(TAG, "populate is pending, skipping for now...");
sortChildDrawingOrder();
return;
}
// Also, don't populate until we are attached to a window. This is to
// avoid trying to populate before we have restored our view hierarchy
// state and conflicting with what is restored.
if (getWindowToken() == null) {
return;
}
mAdapter.startUpdate(this);
final int pageLimit = mOffscreenPageLimit;
final int startPos = Math.max(0, mCurItem - pageLimit);
final int N = mAdapter.getCount();
final int endPos = Math.min(N-1, mCurItem + pageLimit);
if (N != mExpectedAdapterCount) {
String resName;
try {
resName = getResources().getResourceName(getId());
} catch (Resources.NotFoundException e) {
resName = Integer.toHexString(getId());
}
throw new IllegalStateException("The application's PagerAdapter changed the adapter's" +
" contents without calling PagerAdapter#notifyDataSetChanged!" +
" Expected adapter item count: " + mExpectedAdapterCount + ", found: " + N +
" Pager id: " + resName +
" Pager class: " + getClass() +
" Problematic adapter: " + mAdapter.getClass());
}
// Locate the currently focused item or add it if needed.
int curIndex = -1;
ItemInfo curItem = null;
for (curIndex = 0; curIndex < mItems.size(); curIndex++) {
final ItemInfo ii = mItems.get(curIndex);
if (ii.position >= mCurItem) {
if (ii.position == mCurItem) curItem = ii;
break;
}
}
if (curItem == null && N > 0) {
curItem = addNewItem(mCurItem, curIndex);
}
// Fill 3x the available width or up to the number of offscreen
// pages requested to either side, whichever is larger.
// If we have no current item we have no work to do.
if (curItem != null) {
float extraWidthLeft = 0.f;
int itemIndex = curIndex - 1;
ItemInfo ii = itemIndex >= 0 ? mItems.get(itemIndex) : null;
final int clientWidth = getClientWidth();
final float leftWidthNeeded = clientWidth <= 0 ? 0 :
2.f - curItem.widthFactor + (float) getPaddingLeft() / (float) clientWidth;
for (int pos = mCurItem - 1; pos >= 0; pos--) {
if (extraWidthLeft >= leftWidthNeeded && pos < startPos) {
if (ii == null) {
break;
}
if (pos == ii.position && !ii.scrolling) {
mItems.remove(itemIndex);
mAdapter.destroyItem(this, pos, ii.object);
if (DEBUG) {
Log.i(TAG, "populate() - destroyItem() with pos: " + pos +
" view: " + ((View) ii.object));
}
itemIndex--;
curIndex--;
ii = itemIndex >= 0 ? mItems.get(itemIndex) : null;
}
} else if (ii != null && pos == ii.position) {
extraWidthLeft += ii.widthFactor;
itemIndex--;
ii = itemIndex >= 0 ? mItems.get(itemIndex) : null;
} else {
ii = addNewItem(pos, itemIndex + 1);
extraWidthLeft += ii.widthFactor;
curIndex++;
ii = itemIndex >= 0 ? mItems.get(itemIndex) : null;
}
}
float extraWidthRight = curItem.widthFactor;
itemIndex = curIndex + 1;
if (extraWidthRight < 2.f) {
ii = itemIndex < mItems.size() ? mItems.get(itemIndex) : null;
final float rightWidthNeeded = clientWidth <= 0 ? 0 :
(float) getPaddingRight() / (float) clientWidth + 2.f;
for (int pos = mCurItem + 1; pos < N; pos++) {
if (extraWidthRight >= rightWidthNeeded && pos > endPos) {
if (ii == null) {
break;
}
if (pos == ii.position && !ii.scrolling) {
mItems.remove(itemIndex);
mAdapter.destroyItem(this, pos, ii.object);
if (DEBUG) {
Log.i(TAG, "populate() - destroyItem() with pos: " + pos +
" view: " + ((View) ii.object));
}
ii = itemIndex < mItems.size() ? mItems.get(itemIndex) : null;
}
} else if (ii != null && pos == ii.position) {
extraWidthRight += ii.widthFactor;
itemIndex++;
ii = itemIndex < mItems.size() ? mItems.get(itemIndex) : null;
} else {
ii = addNewItem(pos, itemIndex);
itemIndex++;
extraWidthRight += ii.widthFactor;
ii = itemIndex < mItems.size() ? mItems.get(itemIndex) : null;
}
}
}
calculatePageOffsets(curItem, curIndex, oldCurInfo);
}
if (DEBUG) {
Log.i(TAG, "Current page list:");
for (int i=0; i<mItems.size(); i++) {
Log.i(TAG, "#" + i + ": page " + mItems.get(i).position);
}
}
mAdapter.setPrimaryItem(this, mCurItem, curItem != null ? curItem.object : null);
mAdapter.finishUpdate(this);
// Check width measurement of current pages and drawing sort order.
// Update LayoutParams as needed.
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
lp.childIndex = i;
if (!lp.isDecor && lp.widthFactor == 0.f) {
// 0 means requery the adapter for this, it doesn't have a valid width.
final ItemInfo ii = infoForChild(child);
if (ii != null) {
lp.widthFactor = ii.widthFactor;
lp.position = ii.position;
}
}
}
sortChildDrawingOrder();
if (hasFocus()) {
View currentFocused = findFocus();
ItemInfo ii = currentFocused != null ? infoForAnyChild(currentFocused) : null;
if (ii == null || ii.position != mCurItem) {
for (int i=0; i<getChildCount(); i++) {
View child = getChildAt(i);
ii = infoForChild(child);
if (ii != null && ii.position == mCurItem) {
if (child.requestFocus(focusDirection)) {
break;
}
}
}
}
}
}
|
diff --git a/framework/src/java/org/apache/tapestry/ajax/AjaxShellDelegate.java b/framework/src/java/org/apache/tapestry/ajax/AjaxShellDelegate.java
index 433a87ade..6cbde3612 100644
--- a/framework/src/java/org/apache/tapestry/ajax/AjaxShellDelegate.java
+++ b/framework/src/java/org/apache/tapestry/ajax/AjaxShellDelegate.java
@@ -1,73 +1,73 @@
// Copyright 2004, 2005 The Apache Software Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.apache.tapestry.ajax;
import org.apache.tapestry.IAsset;
import org.apache.tapestry.IMarkupWriter;
import org.apache.tapestry.IRender;
import org.apache.tapestry.IRequestCycle;
import org.apache.tapestry.engine.IEngineService;
/**
* The default rendering delegate responseible for include the
* dojo sources into the {@link Shell} component.
*
* @author jkuhnert
*/
public class AjaxShellDelegate implements IRender
{
protected IAsset _dojoSource;
protected IEngineService _assetService;
/**
* {@inheritDoc}
*/
public void render(IMarkupWriter writer, IRequestCycle cycle)
{
//first configure dojo, has to happen before package include
StringBuffer str = new StringBuffer("<script type=\"text/javascript\">");
str.append("djConfig = { isDebug: false,")
.append(" baseRelativePath:\"").append(_dojoSource.getResourceLocation().getPath())
- .append("\", preventBackButtonFix: false };")
+ .append("\", preventBackButtonFix: false, parseWidgets: false };")
.append(" </script>\n\n ");
//include the js package
str.append("<script type=\"text/javascript\" src=\"")
.append(_assetService.getLink(true,
_dojoSource.getResourceLocation()
.getPath()).getAbsoluteURL()).append("\"></script>");
writer.printRaw(str.toString());
}
/**
* Sets a valid path to the base dojo javascript installation
* directory.
* @param dojoSource
*/
public void setDojoSource(IAsset dojoSource)
{
_dojoSource = dojoSource;
}
/**
* Injected asset service.
* @param service
*/
public void setAssetService(IEngineService service)
{
_assetService = service;
}
}
| true | true | public void render(IMarkupWriter writer, IRequestCycle cycle)
{
//first configure dojo, has to happen before package include
StringBuffer str = new StringBuffer("<script type=\"text/javascript\">");
str.append("djConfig = { isDebug: false,")
.append(" baseRelativePath:\"").append(_dojoSource.getResourceLocation().getPath())
.append("\", preventBackButtonFix: false };")
.append(" </script>\n\n ");
//include the js package
str.append("<script type=\"text/javascript\" src=\"")
.append(_assetService.getLink(true,
_dojoSource.getResourceLocation()
.getPath()).getAbsoluteURL()).append("\"></script>");
writer.printRaw(str.toString());
}
| public void render(IMarkupWriter writer, IRequestCycle cycle)
{
//first configure dojo, has to happen before package include
StringBuffer str = new StringBuffer("<script type=\"text/javascript\">");
str.append("djConfig = { isDebug: false,")
.append(" baseRelativePath:\"").append(_dojoSource.getResourceLocation().getPath())
.append("\", preventBackButtonFix: false, parseWidgets: false };")
.append(" </script>\n\n ");
//include the js package
str.append("<script type=\"text/javascript\" src=\"")
.append(_assetService.getLink(true,
_dojoSource.getResourceLocation()
.getPath()).getAbsoluteURL()).append("\"></script>");
writer.printRaw(str.toString());
}
|
diff --git a/OpTalk/OpTalk/src/be/infogroep/optalk/ItemShare.java b/OpTalk/OpTalk/src/be/infogroep/optalk/ItemShare.java
index 938df38..f402eeb 100644
--- a/OpTalk/OpTalk/src/be/infogroep/optalk/ItemShare.java
+++ b/OpTalk/OpTalk/src/be/infogroep/optalk/ItemShare.java
@@ -1,131 +1,131 @@
package be.infogroep.optalk;
//import java.util.Map;
import java.util.*;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.*;
import org.bukkit.inventory.*;
import org.bukkit.inventory.meta.*;
import org.bukkit.potion.*;
public class ItemShare {
private int header = 5;
private boolean potion = false;
private Player receiver_ = null;
private Player sender_;
private ItemStack item_;
private ItemMeta meta_;
private String itemName_;
ItemShare(CommandSender sender, String[] msg) {
Bukkit.getLogger().info("ItemShare");
if (msg.length > 0) {
String name = msg[0];
receiver_ = Bukkit.getServer().getPlayer(name);
}
sender_ = (Player) sender;
item_ = sender_.getItemInHand();
meta_ = item_.getItemMeta();
if (meta_ != null) {
if (meta_.hasDisplayName())
itemName_ = meta_.getDisplayName();
else
itemName_ = item_.getType().name();
} else
itemName_ = // item_.getType().name();
item_.getData().getClass().getName();
Map<Enchantment, Integer> enchants = /* item_.getEnchantments(); */
item_.getEnchantments();
Collection<PotionEffect> effects = null;
Material material_ = item_.getType();
if (material_.getId() == 387) {// special case book
BookMeta BM = (BookMeta) meta_;
itemName_ = BM.getTitle() + " - " + BM.getAuthor();
}
if (material_.getId() == 403) {// special case enchanted book
EnchantmentStorageMeta ESM = (EnchantmentStorageMeta) meta_;
enchants = ESM.getStoredEnchants();
}
if (material_.getId() == 373) {// special case potions
potion = true;
PotionMeta PM = (PotionMeta) meta_;
if (PM.hasDisplayName())
itemName_ = PM.getDisplayName();
effects = PM.getCustomEffects();
}
// Recipe R = ShapedRecipe(item_);
int EnchantsSize = enchants.size();
- int EnchantsHeaderSize = 1;
+ int EnchantsHeaderSize = 0;
if (EnchantsSize > 0)
EnchantsHeaderSize = EnchantsSize;
else if (effects != null) {
if (effects.size() != 0)
EnchantsHeaderSize = effects.size();
}
String[] message = new String[header + EnchantsHeaderSize];
message[0] = "§5" + sender.getName() + ": §6shared an item";
message[1] = "§aItem name: §b" + itemName_;
message[2] = "§aType: §b"
+ material_.name().replace("_", " ").toLowerCase();
if (potion)
message[3] = "§aEffect: ";
else
message[3] = "§aEnchanments: ";
int index = 4;
if (EnchantsSize > 0) {
for (Map.Entry<Enchantment, Integer> current : enchants.entrySet()) {
message[index] = current.getKey().getName() + " Level: "
+ current.getValue();
index = index + 1;
}
} else if (effects != null)
if (!effects.isEmpty()) {
for (PotionEffect P : effects) {
message[index] = P.getType().getName() + ": "
+ P.getDuration();
}
} else {
message[index] = "None";
index = index + 1;
}
message[index] = "§a-------------------";
if (null == receiver_) {
if (msg.length == 0) {
Bukkit.getServer().broadcastMessage("§a§nPublicly shared item");
for (String s : message) {
Bukkit.getServer().broadcastMessage(s);
}
} else {
sender.sendMessage("§ccould not find player: " + msg[0]);
}
} else {
receiver_.sendMessage(message);
sender.sendMessage("§asuccesfully shared your item with " + msg[0]);
}
}
}
| true | true | ItemShare(CommandSender sender, String[] msg) {
Bukkit.getLogger().info("ItemShare");
if (msg.length > 0) {
String name = msg[0];
receiver_ = Bukkit.getServer().getPlayer(name);
}
sender_ = (Player) sender;
item_ = sender_.getItemInHand();
meta_ = item_.getItemMeta();
if (meta_ != null) {
if (meta_.hasDisplayName())
itemName_ = meta_.getDisplayName();
else
itemName_ = item_.getType().name();
} else
itemName_ = // item_.getType().name();
item_.getData().getClass().getName();
Map<Enchantment, Integer> enchants = /* item_.getEnchantments(); */
item_.getEnchantments();
Collection<PotionEffect> effects = null;
Material material_ = item_.getType();
if (material_.getId() == 387) {// special case book
BookMeta BM = (BookMeta) meta_;
itemName_ = BM.getTitle() + " - " + BM.getAuthor();
}
if (material_.getId() == 403) {// special case enchanted book
EnchantmentStorageMeta ESM = (EnchantmentStorageMeta) meta_;
enchants = ESM.getStoredEnchants();
}
if (material_.getId() == 373) {// special case potions
potion = true;
PotionMeta PM = (PotionMeta) meta_;
if (PM.hasDisplayName())
itemName_ = PM.getDisplayName();
effects = PM.getCustomEffects();
}
// Recipe R = ShapedRecipe(item_);
int EnchantsSize = enchants.size();
int EnchantsHeaderSize = 1;
if (EnchantsSize > 0)
EnchantsHeaderSize = EnchantsSize;
else if (effects != null) {
if (effects.size() != 0)
EnchantsHeaderSize = effects.size();
}
String[] message = new String[header + EnchantsHeaderSize];
message[0] = "§5" + sender.getName() + ": §6shared an item";
message[1] = "§aItem name: §b" + itemName_;
message[2] = "§aType: §b"
+ material_.name().replace("_", " ").toLowerCase();
if (potion)
message[3] = "§aEffect: ";
else
message[3] = "§aEnchanments: ";
int index = 4;
if (EnchantsSize > 0) {
for (Map.Entry<Enchantment, Integer> current : enchants.entrySet()) {
message[index] = current.getKey().getName() + " Level: "
+ current.getValue();
index = index + 1;
}
} else if (effects != null)
if (!effects.isEmpty()) {
for (PotionEffect P : effects) {
message[index] = P.getType().getName() + ": "
+ P.getDuration();
}
} else {
message[index] = "None";
index = index + 1;
}
message[index] = "§a-------------------";
if (null == receiver_) {
if (msg.length == 0) {
Bukkit.getServer().broadcastMessage("§a§nPublicly shared item");
for (String s : message) {
Bukkit.getServer().broadcastMessage(s);
}
} else {
sender.sendMessage("§ccould not find player: " + msg[0]);
}
} else {
receiver_.sendMessage(message);
sender.sendMessage("§asuccesfully shared your item with " + msg[0]);
}
}
| ItemShare(CommandSender sender, String[] msg) {
Bukkit.getLogger().info("ItemShare");
if (msg.length > 0) {
String name = msg[0];
receiver_ = Bukkit.getServer().getPlayer(name);
}
sender_ = (Player) sender;
item_ = sender_.getItemInHand();
meta_ = item_.getItemMeta();
if (meta_ != null) {
if (meta_.hasDisplayName())
itemName_ = meta_.getDisplayName();
else
itemName_ = item_.getType().name();
} else
itemName_ = // item_.getType().name();
item_.getData().getClass().getName();
Map<Enchantment, Integer> enchants = /* item_.getEnchantments(); */
item_.getEnchantments();
Collection<PotionEffect> effects = null;
Material material_ = item_.getType();
if (material_.getId() == 387) {// special case book
BookMeta BM = (BookMeta) meta_;
itemName_ = BM.getTitle() + " - " + BM.getAuthor();
}
if (material_.getId() == 403) {// special case enchanted book
EnchantmentStorageMeta ESM = (EnchantmentStorageMeta) meta_;
enchants = ESM.getStoredEnchants();
}
if (material_.getId() == 373) {// special case potions
potion = true;
PotionMeta PM = (PotionMeta) meta_;
if (PM.hasDisplayName())
itemName_ = PM.getDisplayName();
effects = PM.getCustomEffects();
}
// Recipe R = ShapedRecipe(item_);
int EnchantsSize = enchants.size();
int EnchantsHeaderSize = 0;
if (EnchantsSize > 0)
EnchantsHeaderSize = EnchantsSize;
else if (effects != null) {
if (effects.size() != 0)
EnchantsHeaderSize = effects.size();
}
String[] message = new String[header + EnchantsHeaderSize];
message[0] = "§5" + sender.getName() + ": §6shared an item";
message[1] = "§aItem name: §b" + itemName_;
message[2] = "§aType: §b"
+ material_.name().replace("_", " ").toLowerCase();
if (potion)
message[3] = "§aEffect: ";
else
message[3] = "§aEnchanments: ";
int index = 4;
if (EnchantsSize > 0) {
for (Map.Entry<Enchantment, Integer> current : enchants.entrySet()) {
message[index] = current.getKey().getName() + " Level: "
+ current.getValue();
index = index + 1;
}
} else if (effects != null)
if (!effects.isEmpty()) {
for (PotionEffect P : effects) {
message[index] = P.getType().getName() + ": "
+ P.getDuration();
}
} else {
message[index] = "None";
index = index + 1;
}
message[index] = "§a-------------------";
if (null == receiver_) {
if (msg.length == 0) {
Bukkit.getServer().broadcastMessage("§a§nPublicly shared item");
for (String s : message) {
Bukkit.getServer().broadcastMessage(s);
}
} else {
sender.sendMessage("§ccould not find player: " + msg[0]);
}
} else {
receiver_.sendMessage(message);
sender.sendMessage("§asuccesfully shared your item with " + msg[0]);
}
}
|
diff --git a/src/java/org/infoglue/deliver/taglib/management/PrincipalPropertyTag.java b/src/java/org/infoglue/deliver/taglib/management/PrincipalPropertyTag.java
index ed12ecdec..955fbefa8 100755
--- a/src/java/org/infoglue/deliver/taglib/management/PrincipalPropertyTag.java
+++ b/src/java/org/infoglue/deliver/taglib/management/PrincipalPropertyTag.java
@@ -1,156 +1,152 @@
/* ===============================================================================
*
* Part of the InfoGlue Content Management Platform (www.infoglue.org)
*
* ===============================================================================
*
* Copyright (C)
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2, as published by the
* Free Software Foundation. See the file LICENSE.html for more information.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY, including the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc. / 59 Temple
* Place, Suite 330 / Boston, MA 02111-1307 / USA.
*
* ===============================================================================
*/
package org.infoglue.deliver.taglib.management;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.jsp.JspException;
import org.apache.log4j.Logger;
import org.infoglue.cms.entities.management.impl.simple.GroupPropertiesImpl;
import org.infoglue.cms.entities.management.impl.simple.RolePropertiesImpl;
import org.infoglue.cms.entities.management.impl.simple.UserPropertiesImpl;
import org.infoglue.cms.security.InfoGluePrincipal;
import org.infoglue.cms.util.CmsPropertyHandler;
import org.infoglue.deliver.taglib.TemplateControllerTag;
public class PrincipalPropertyTag extends TemplateControllerTag
{
private final static Logger logger = Logger.getLogger(PrincipalPropertyTag.class.getName());
private static final long serialVersionUID = 4050206323348354355L;
private String userName;
private InfoGluePrincipal principal;
private String attributeName;
private Integer languageId = null;
private boolean defeatCaches = false;
private boolean allowAnonymousProperty = false;
private boolean includeRoles = true;
private boolean includeGroups = true;
public PrincipalPropertyTag()
{
super();
}
public int doEndTag() throws JspException
{
if(languageId == null)
languageId = getController().getLanguageId();
//Here we store the defeat caches setting for later reset
boolean previousDefeatCaches = getController().getDeliveryContext().getDefeatCaches();
try
{
- Map<Class, List<Object>> entities = new HashMap<Class, List<Object>>();
- entities.put(UserPropertiesImpl.class, Collections.EMPTY_LIST);
- entities.put(GroupPropertiesImpl.class, Collections.EMPTY_LIST);
- entities.put(RolePropertiesImpl.class, Collections.EMPTY_LIST);
- getController().getDeliveryContext().setDefeatCaches(defeatCaches, entities);
+ getController().getDeliveryContext().setDefeatCaches(defeatCaches, null/* entities*/);
if(userName != null && !userName.equals(""))
{
if(!allowAnonymousProperty && userName.equalsIgnoreCase(CmsPropertyHandler.getAnonymousUser()))
{
setResultAttribute("Anonymous not allowed to have properties");
logger.warn("Anonymous not allowed to have properties unless stated. URL:" + this.getController().getOriginalFullURL() + "\nComponentName:" + this.getController().getComponentLogic().getInfoGlueComponent().getName());
}
else
setResultAttribute(this.getController().getPrincipalPropertyValue(getController().getPrincipal(userName), attributeName, languageId));
}
else if(principal != null)
{
if(!allowAnonymousProperty && principal.getName().equalsIgnoreCase(CmsPropertyHandler.getAnonymousUser()))
{
setResultAttribute("");
logger.warn("Anonymous not allowed to have properties unless stated. URL:" + this.getController().getOriginalFullURL() + "\nComponentName:" + this.getController().getComponentLogic().getInfoGlueComponent().getName());
}
else
setResultAttribute(getController().getPrincipalPropertyValue(principal, attributeName, languageId));
}
else
{
setResultAttribute(getController().getPrincipalPropertyValue(attributeName, languageId));
}
}
finally
{
//Resetting the defeatcaches setting
getController().getDeliveryContext().setDefeatCaches(previousDefeatCaches, new HashMap<Class, List<Object>>());
languageId = null;
userName = null;
principal = null;
defeatCaches = false;
allowAnonymousProperty = false;
includeRoles = false;
includeGroups = false;
}
return EVAL_PAGE;
}
public void setUserName(final String userName) throws JspException
{
this.userName = evaluateString("principal", "userName", userName);
}
public void setPrincipal(final String principalString) throws JspException
{
this.principal = (InfoGluePrincipal)evaluate("principal", "principal", principalString, InfoGluePrincipal.class);
}
public void setAttributeName(final String attributeName) throws JspException
{
this.attributeName = evaluateString("principal", "attributeName", attributeName);
}
public void setLanguageId(final String languageIdString) throws JspException
{
this.languageId = this.evaluateInteger("principal", "languageId", languageIdString);
}
public void setIncludeRoles(final String includeRoles) throws JspException
{
this.includeRoles = (Boolean)evaluate("principal", "includeRoles", includeRoles, Boolean.class);
}
public void setIncludeGroups(final String includeGroups) throws JspException
{
this.includeGroups = (Boolean)evaluate("principal", "includeGroups", includeGroups, Boolean.class);
}
public void setAllowAnonymousProperty(final String allowAnonymousProperty) throws JspException
{
this.allowAnonymousProperty = (Boolean)evaluate("principal", "allowAnonymousProperty", allowAnonymousProperty, Boolean.class);
}
public void setDefeatCaches(final String defeatCaches) throws JspException
{
this.defeatCaches = (Boolean)evaluate("principal", "defeatCaches", defeatCaches, Boolean.class);
}
}
| true | true | public int doEndTag() throws JspException
{
if(languageId == null)
languageId = getController().getLanguageId();
//Here we store the defeat caches setting for later reset
boolean previousDefeatCaches = getController().getDeliveryContext().getDefeatCaches();
try
{
Map<Class, List<Object>> entities = new HashMap<Class, List<Object>>();
entities.put(UserPropertiesImpl.class, Collections.EMPTY_LIST);
entities.put(GroupPropertiesImpl.class, Collections.EMPTY_LIST);
entities.put(RolePropertiesImpl.class, Collections.EMPTY_LIST);
getController().getDeliveryContext().setDefeatCaches(defeatCaches, entities);
if(userName != null && !userName.equals(""))
{
if(!allowAnonymousProperty && userName.equalsIgnoreCase(CmsPropertyHandler.getAnonymousUser()))
{
setResultAttribute("Anonymous not allowed to have properties");
logger.warn("Anonymous not allowed to have properties unless stated. URL:" + this.getController().getOriginalFullURL() + "\nComponentName:" + this.getController().getComponentLogic().getInfoGlueComponent().getName());
}
else
setResultAttribute(this.getController().getPrincipalPropertyValue(getController().getPrincipal(userName), attributeName, languageId));
}
else if(principal != null)
{
if(!allowAnonymousProperty && principal.getName().equalsIgnoreCase(CmsPropertyHandler.getAnonymousUser()))
{
setResultAttribute("");
logger.warn("Anonymous not allowed to have properties unless stated. URL:" + this.getController().getOriginalFullURL() + "\nComponentName:" + this.getController().getComponentLogic().getInfoGlueComponent().getName());
}
else
setResultAttribute(getController().getPrincipalPropertyValue(principal, attributeName, languageId));
}
else
{
setResultAttribute(getController().getPrincipalPropertyValue(attributeName, languageId));
}
}
finally
{
//Resetting the defeatcaches setting
getController().getDeliveryContext().setDefeatCaches(previousDefeatCaches, new HashMap<Class, List<Object>>());
languageId = null;
userName = null;
principal = null;
defeatCaches = false;
allowAnonymousProperty = false;
includeRoles = false;
includeGroups = false;
}
return EVAL_PAGE;
}
| public int doEndTag() throws JspException
{
if(languageId == null)
languageId = getController().getLanguageId();
//Here we store the defeat caches setting for later reset
boolean previousDefeatCaches = getController().getDeliveryContext().getDefeatCaches();
try
{
getController().getDeliveryContext().setDefeatCaches(defeatCaches, null/* entities*/);
if(userName != null && !userName.equals(""))
{
if(!allowAnonymousProperty && userName.equalsIgnoreCase(CmsPropertyHandler.getAnonymousUser()))
{
setResultAttribute("Anonymous not allowed to have properties");
logger.warn("Anonymous not allowed to have properties unless stated. URL:" + this.getController().getOriginalFullURL() + "\nComponentName:" + this.getController().getComponentLogic().getInfoGlueComponent().getName());
}
else
setResultAttribute(this.getController().getPrincipalPropertyValue(getController().getPrincipal(userName), attributeName, languageId));
}
else if(principal != null)
{
if(!allowAnonymousProperty && principal.getName().equalsIgnoreCase(CmsPropertyHandler.getAnonymousUser()))
{
setResultAttribute("");
logger.warn("Anonymous not allowed to have properties unless stated. URL:" + this.getController().getOriginalFullURL() + "\nComponentName:" + this.getController().getComponentLogic().getInfoGlueComponent().getName());
}
else
setResultAttribute(getController().getPrincipalPropertyValue(principal, attributeName, languageId));
}
else
{
setResultAttribute(getController().getPrincipalPropertyValue(attributeName, languageId));
}
}
finally
{
//Resetting the defeatcaches setting
getController().getDeliveryContext().setDefeatCaches(previousDefeatCaches, new HashMap<Class, List<Object>>());
languageId = null;
userName = null;
principal = null;
defeatCaches = false;
allowAnonymousProperty = false;
includeRoles = false;
includeGroups = false;
}
return EVAL_PAGE;
}
|
diff --git a/deployers-core/src/main/org/jboss/deployers/plugins/structure/StructureMetaDataImpl.java b/deployers-core/src/main/org/jboss/deployers/plugins/structure/StructureMetaDataImpl.java
index 087036da..369e4b83 100644
--- a/deployers-core/src/main/org/jboss/deployers/plugins/structure/StructureMetaDataImpl.java
+++ b/deployers-core/src/main/org/jboss/deployers/plugins/structure/StructureMetaDataImpl.java
@@ -1,162 +1,162 @@
/*
* JBoss, Home of Professional Open Source.
* Copyright 2007, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.deployers.plugins.structure;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import org.jboss.deployers.spi.structure.ContextInfo;
import org.jboss.deployers.spi.structure.StructureMetaData;
/**
* StructureMetaDataImpl.
*
* @author <a href="[email protected]">Adrian Brock</a>
* @version $Revision: 1.1 $
*/
public class StructureMetaDataImpl implements StructureMetaData, Externalizable
{
/** The serialVersionUID */
private static final long serialVersionUID = 2341637762171510800L;
/** The contexts */
private List<ContextInfo> contexts = new CopyOnWriteArrayList<ContextInfo>();
public void addContext(ContextInfo context)
{
if (context == null)
throw new IllegalArgumentException("Null context");
String path = context.getPath();
if (path == null)
throw new IllegalArgumentException("Context has no path");
for (ContextInfo other : contexts)
{
if (path.equals(other.getPath()))
- throw new IllegalStateException("Context alread exists with path '" + path + "' contexts=" + getContexts());
+ throw new IllegalStateException("Context already exists with path '" + path + "' contexts=" + getContexts());
}
contexts.add(context);
}
public ContextInfo getContext(String path)
{
if (path == null)
throw new IllegalArgumentException("Null path");
for (ContextInfo context : contexts)
{
if (path.equals(context.getPath()))
return context;
}
return null;
}
public void removeContext(ContextInfo context)
{
if (context == null)
throw new IllegalArgumentException("Null context");
contexts.remove(context);
}
public void removeContext(String path)
{
if (path == null)
throw new IllegalArgumentException("Null path");
for (ContextInfo context : contexts)
{
if (path.equals(context.getPath()))
contexts.remove(context);
}
}
public List<ContextInfo> getContexts()
{
return contexts;
}
@Override
public String toString()
{
StringBuilder builder = new StringBuilder();
builder.append(getClass().getSimpleName());
builder.append("{");
toString(builder);
builder.append("}");
return builder.toString();
}
/**
* For subclasses to override toString()
*
* @param builder the builder
*/
protected void toString(StringBuilder builder)
{
builder.append("contexts=").append(contexts);
}
@Override
public boolean equals(Object obj)
{
if (obj == this)
return true;
if (obj == null || obj instanceof StructureMetaData == false)
return false;
StructureMetaData other = (StructureMetaData) obj;
List<ContextInfo> thisContexts = getContexts();
List<ContextInfo> otherContexts = other.getContexts();
if (thisContexts == null)
return otherContexts == null;
return thisContexts.equals(otherContexts);
}
@Override
public int hashCode()
{
List<ContextInfo> contexts = getContexts();
if (contexts == null)
return 0;
return contexts.hashCode();
}
@SuppressWarnings("unchecked")
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
{
contexts = (List) in.readObject();
}
/**
* @serialData context from {@link #getContexts()}
* @param out the output
* @throws IOException for any error
*/
public void writeExternal(ObjectOutput out) throws IOException
{
out.writeObject(getContexts());
}
}
| true | true | public void addContext(ContextInfo context)
{
if (context == null)
throw new IllegalArgumentException("Null context");
String path = context.getPath();
if (path == null)
throw new IllegalArgumentException("Context has no path");
for (ContextInfo other : contexts)
{
if (path.equals(other.getPath()))
throw new IllegalStateException("Context alread exists with path '" + path + "' contexts=" + getContexts());
}
contexts.add(context);
}
| public void addContext(ContextInfo context)
{
if (context == null)
throw new IllegalArgumentException("Null context");
String path = context.getPath();
if (path == null)
throw new IllegalArgumentException("Context has no path");
for (ContextInfo other : contexts)
{
if (path.equals(other.getPath()))
throw new IllegalStateException("Context already exists with path '" + path + "' contexts=" + getContexts());
}
contexts.add(context);
}
|
diff --git a/model/org/eclipse/cdt/internal/core/settings/model/AbstractCExtensionProxy.java b/model/org/eclipse/cdt/internal/core/settings/model/AbstractCExtensionProxy.java
index 5e56471b5..61b39f3bf 100644
--- a/model/org/eclipse/cdt/internal/core/settings/model/AbstractCExtensionProxy.java
+++ b/model/org/eclipse/cdt/internal/core/settings/model/AbstractCExtensionProxy.java
@@ -1,173 +1,173 @@
/*******************************************************************************
* Copyright (c) 2007, 2010 Intel Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Intel Corporation - Initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.settings.model;
import org.eclipse.cdt.core.ICExtensionReference;
import org.eclipse.cdt.core.settings.model.CProjectDescriptionEvent;
import org.eclipse.cdt.core.settings.model.ICConfigurationDescription;
import org.eclipse.cdt.core.settings.model.ICProjectDescription;
import org.eclipse.cdt.core.settings.model.ICProjectDescriptionListener;
import org.eclipse.cdt.internal.core.CConfigBasedDescriptor;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
public abstract class AbstractCExtensionProxy implements ICProjectDescriptionListener{
private IProject fProject;
private String fExtId;
private boolean fIsNewStyle;
private boolean fInited;
private String fExtPointId;
private Object fProvider;
public AbstractCExtensionProxy(IProject project, String extPointId) {
fProject = project;
fExtPointId = extPointId;
CProjectDescriptionManager.getInstance().addCProjectDescriptionListener(this, CProjectDescriptionEvent.LOADED | CProjectDescriptionEvent.APPLIED);
}
protected final void providerRequested(){
if(!fInited)
checkUpdateProvider(CProjectDescriptionManager.getInstance().getProjectDescription(fProject, false), false, false);
}
public void updateProject(IProject project){
IProject oldProj = fProject;
fProject = project;
if(oldProj == null || !oldProj.equals(fProject))
fInited = false;
}
private ICExtensionReference getRef(ICConfigurationDescription cfg, boolean update){
if(fExtPointId != null){
try {
CConfigBasedDescriptor dr = new CConfigBasedDescriptor(cfg, false);
ICExtensionReference[] cextensions = dr.get(fExtPointId, update);
if (cextensions.length > 0) {
return cextensions[0];
}
} catch (CoreException e) {
}
}
return null;
}
protected IProject getProject(){
return fProject;
}
private boolean checkUpdateProvider(ICProjectDescription des, boolean recreate, boolean rescan){
Object newProvider = null;
Object oldProvider = null;
synchronized(this){
if(recreate || rescan || !fInited){
ICExtensionReference ref = null;
- boolean newStile = true;
+ boolean newStyle = true;
ICConfigurationDescription cfg = null;
if(des != null){
cfg = des.getDefaultSettingConfiguration();
if(cfg != null){
ref = getRef(cfg, false);
- newStile = CProjectDescriptionManager.getInstance().isNewStyleCfg(cfg);
+ newStyle = CProjectDescriptionManager.getInstance().isNewStyleCfg(cfg);
}
}
if(ref != null){
if(recreate || !ref.getID().equals(fExtId)){
try {
newProvider = ref.createExtension();
if(!isValidProvider(newProvider))
newProvider = null;
} catch (CoreException e) {
}
}
}
if(newProvider == null){
- if(recreate || fProvider == null || newStile != fIsNewStyle){
- newStile = isNewStyleCfg(cfg);
- newProvider = createDefaultProvider(cfg, newStile);
+ if(recreate || fProvider == null || newStyle != fIsNewStyle){
+ newStyle = isNewStyleCfg(cfg);
+ newProvider = createDefaultProvider(cfg, newStyle);
}
}
if(newProvider != null){
if(fProvider != null){
deinitializeProvider(fProvider);
oldProvider = fProvider;
}
fProvider = newProvider;
if(ref != null)
fExtId = ref.getID();
- fIsNewStyle = newStile;
+ fIsNewStyle = newStyle;
initializeProvider(fProvider);
}
fInited = true;
}
}
if(newProvider != null){
postProcessProviderChange(newProvider, oldProvider);
return true;
}
return false;
}
protected boolean isNewStyleCfg(ICConfigurationDescription des){
return CProjectDescriptionManager.getInstance().isNewStyleCfg(des);
}
protected abstract boolean isValidProvider(Object o);
protected abstract void initializeProvider(Object o);
protected abstract void deinitializeProvider(Object o);
protected abstract Object createDefaultProvider(ICConfigurationDescription cfgDes, boolean newStile);
protected void postProcessProviderChange(Object newProvider, Object oldProvider){
}
public void close(){
CProjectDescriptionManager.getInstance().removeCProjectDescriptionListener(this);
if(fProvider != null){
deinitializeProvider(fProvider);
}
}
public void handleEvent(CProjectDescriptionEvent event) {
if(!fProject.equals(event.getProject()))
return;
doHandleEvent(event);
}
protected boolean doHandleEvent(CProjectDescriptionEvent event){
boolean force = false;
switch(event.getEventType()){
case CProjectDescriptionEvent.LOADED:
force = true;
//$FALL-THROUGH$
case CProjectDescriptionEvent.APPLIED:
ICProjectDescription des = event.getNewCProjectDescription();
if(des != null){
updateProject(des.getProject());
return checkUpdateProvider(des, force, true);
}
break;
}
return false;
}
}
| false | true | private boolean checkUpdateProvider(ICProjectDescription des, boolean recreate, boolean rescan){
Object newProvider = null;
Object oldProvider = null;
synchronized(this){
if(recreate || rescan || !fInited){
ICExtensionReference ref = null;
boolean newStile = true;
ICConfigurationDescription cfg = null;
if(des != null){
cfg = des.getDefaultSettingConfiguration();
if(cfg != null){
ref = getRef(cfg, false);
newStile = CProjectDescriptionManager.getInstance().isNewStyleCfg(cfg);
}
}
if(ref != null){
if(recreate || !ref.getID().equals(fExtId)){
try {
newProvider = ref.createExtension();
if(!isValidProvider(newProvider))
newProvider = null;
} catch (CoreException e) {
}
}
}
if(newProvider == null){
if(recreate || fProvider == null || newStile != fIsNewStyle){
newStile = isNewStyleCfg(cfg);
newProvider = createDefaultProvider(cfg, newStile);
}
}
if(newProvider != null){
if(fProvider != null){
deinitializeProvider(fProvider);
oldProvider = fProvider;
}
fProvider = newProvider;
if(ref != null)
fExtId = ref.getID();
fIsNewStyle = newStile;
initializeProvider(fProvider);
}
fInited = true;
}
}
if(newProvider != null){
postProcessProviderChange(newProvider, oldProvider);
return true;
}
return false;
}
| private boolean checkUpdateProvider(ICProjectDescription des, boolean recreate, boolean rescan){
Object newProvider = null;
Object oldProvider = null;
synchronized(this){
if(recreate || rescan || !fInited){
ICExtensionReference ref = null;
boolean newStyle = true;
ICConfigurationDescription cfg = null;
if(des != null){
cfg = des.getDefaultSettingConfiguration();
if(cfg != null){
ref = getRef(cfg, false);
newStyle = CProjectDescriptionManager.getInstance().isNewStyleCfg(cfg);
}
}
if(ref != null){
if(recreate || !ref.getID().equals(fExtId)){
try {
newProvider = ref.createExtension();
if(!isValidProvider(newProvider))
newProvider = null;
} catch (CoreException e) {
}
}
}
if(newProvider == null){
if(recreate || fProvider == null || newStyle != fIsNewStyle){
newStyle = isNewStyleCfg(cfg);
newProvider = createDefaultProvider(cfg, newStyle);
}
}
if(newProvider != null){
if(fProvider != null){
deinitializeProvider(fProvider);
oldProvider = fProvider;
}
fProvider = newProvider;
if(ref != null)
fExtId = ref.getID();
fIsNewStyle = newStyle;
initializeProvider(fProvider);
}
fInited = true;
}
}
if(newProvider != null){
postProcessProviderChange(newProvider, oldProvider);
return true;
}
return false;
}
|
diff --git a/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/ui/wizards/JoinSessionWizard.java b/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/ui/wizards/JoinSessionWizard.java
index 6c202cef5..1fd9ff884 100644
--- a/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/ui/wizards/JoinSessionWizard.java
+++ b/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/ui/wizards/JoinSessionWizard.java
@@ -1,460 +1,461 @@
/*
* DPP - Serious Distributed Pair Programming
* (c) Freie Universitaet Berlin - Fachbereich Mathematik und Informatik - 2006
* (c) Riad Djemili - 2006
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 1, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package de.fu_berlin.inf.dpp.ui.wizards;
import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.Callable;
import org.apache.log4j.Logger;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubMonitor;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IPageChangingListener;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.PageChangingEvent;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Shell;
import de.fu_berlin.inf.dpp.FileList;
import de.fu_berlin.inf.dpp.FileListDiff;
import de.fu_berlin.inf.dpp.Saros;
import de.fu_berlin.inf.dpp.exceptions.LocalCancellationException;
import de.fu_berlin.inf.dpp.exceptions.RemoteCancellationException;
import de.fu_berlin.inf.dpp.exceptions.SarosCancellationException;
import de.fu_berlin.inf.dpp.invitation.IncomingInvitationProcess;
import de.fu_berlin.inf.dpp.invitation.InvitationProcess.CancelLocation;
import de.fu_berlin.inf.dpp.invitation.InvitationProcess.CancelOption;
import de.fu_berlin.inf.dpp.net.JID;
import de.fu_berlin.inf.dpp.net.internal.DataTransferManager;
import de.fu_berlin.inf.dpp.preferences.PreferenceUtils;
import de.fu_berlin.inf.dpp.util.EclipseUtils;
import de.fu_berlin.inf.dpp.util.Util;
import de.fu_berlin.inf.dpp.util.VersionManager;
/**
* A wizard that guides the user through an incoming invitation process.
*
* TODO Automatically switch to follow mode
*
* TODO Suggest if the project is a CVS project that the user checks it out and
* offers an option to transfer the settings
*
* TODO Create a separate Wizard class with the following concerns implemented
* more nicely: Long-Running Operation after each step, cancellation by a remote
* party, auto-advance.
*
* @author rdjemili
*/
public class JoinSessionWizard extends Wizard {
private static final Logger log = Logger.getLogger(JoinSessionWizard.class);
protected ShowDescriptionPage descriptionPage;
protected EnterProjectNamePage namePage;
protected WizardDialogAccessable wizardDialog;
protected IncomingInvitationProcess process;
protected boolean requested = false;
protected String updateProjectName;
protected boolean updateSelected;
protected DataTransferManager dataTransferManager;
protected PreferenceUtils preferenceUtils;
protected VersionManager manager;
public JoinSessionWizard(IncomingInvitationProcess process,
DataTransferManager dataTransferManager,
PreferenceUtils preferenceUtils, VersionManager manager) {
this.process = process;
this.dataTransferManager = dataTransferManager;
this.preferenceUtils = preferenceUtils;
this.manager = manager;
process.setInvitationUI(this);
setWindowTitle("Session Invitation");
setHelpAvailable(false);
setNeedsProgressMonitor(true);
}
public PreferenceUtils getPreferenceUtils() {
return preferenceUtils;
}
@Override
public IWizardPage getNextPage(IWizardPage page) {
if (page.equals(descriptionPage) && !requested) {
/*
* Increment pages for auto-next, because the request will block too
* long
*/
pageChanges++;
if (!requestHostFileList()) {
getShell().forceActive();
return null;
}
getShell().forceActive();
}
return super.getNextPage(page);
}
public boolean requestHostFileList() {
requested = true;
/* wait for getting project file list. */
try {
getContainer().run(true, true, new IRunnableWithProgress() {
public void run(IProgressMonitor monitor)
throws InterruptedException, InvocationTargetException {
try {
process.requestRemoteFileList(SubMonitor
.convert(monitor));
} catch (SarosCancellationException e) {
throw new InvocationTargetException(e);
}
}
});
} catch (InvocationTargetException e) {
processException(e.getCause());
return false;
} catch (InterruptedException e) {
log.error("Not designed to be interrupted.");
processException(e);
return false;
}
if (process.getRemoteFileList() == null) {
// Remote side canceled...
getShell().close();
return false;
}
if (preferenceUtils.isAutoReuseExisting()
&& JoinSessionWizardUtils.existsProjects(process.getProjectName())) {
updateSelected = true;
updateProjectName = process.getProjectName();
} else {
updateSelected = false;
updateProjectName = "";
}
return true;
}
@Override
public void createPageControls(Composite pageContainer) {
this.descriptionPage.createControl(pageContainer);
// create namePage lazily
}
@Override
public void addPages() {
descriptionPage = new ShowDescriptionPage(this, manager, process);
namePage = new EnterProjectNamePage(this, dataTransferManager,
preferenceUtils);
addPage(descriptionPage);
addPage(namePage);
}
@Override
public boolean performFinish() {
final IProject source = namePage.getSourceProject();
final String target = namePage.getTargetProjectName();
final boolean skip = namePage.isSyncSkippingSelected();
/*
* Ask the user whether to overwrite local resources only if resources
* are supposed to be overwritten based on the synchronization options
* and if there are differences between the remote and local project.
*/
- if (namePage.overwriteProjectResources()) {
+ if (namePage.overwriteProjectResources()
+ && !preferenceUtils.isAutoReuseExisting()) {
FileListDiff diff;
if (!source.isOpen()) {
try {
source.open(null);
} catch (CoreException e1) {
log.debug("An error occur while opening the source file",
e1);
}
}
try {
diff = FileListDiff.diff(new FileList(source),
process.getRemoteFileList());
} catch (CoreException e) {
MessageDialog.openError(getShell(), "Error computing FileList",
"Could not compute local FileList: " + e.getMessage());
return false;
}
if (diff.getRemovedPaths().size() > 0
|| diff.getAlteredPaths().size() > 0)
if (!confirmOverwritingProjectResources(source.getName(), diff))
return false;
}
try {
getContainer().run(true, true, new IRunnableWithProgress() {
public void run(IProgressMonitor monitor)
throws InvocationTargetException, InterruptedException {
try {
JoinSessionWizard.this.process.accept(source, target,
skip, SubMonitor.convert(monitor));
} catch (Exception e) {
throw new InvocationTargetException(e);
}
}
});
} catch (InvocationTargetException e) {
processException(e.getCause());
return false;
} catch (InterruptedException e) {
log.error("Code not designed to be interrupted.", e);
processException(e);
return false;
}
getShell().forceActive();
return true;
}
public static class OverwriteErrorDialog extends ErrorDialog {
public OverwriteErrorDialog(Shell parentShell, String dialogTitle,
String dialogMessage, IStatus status) {
super(parentShell, dialogTitle, dialogMessage, status, IStatus.OK
| IStatus.INFO | IStatus.WARNING | IStatus.ERROR);
}
@Override
protected void createButtonsForButtonBar(Composite parent) {
super.createButtonsForButtonBar(parent);
Button ok = getButton(IDialogConstants.OK_ID);
ok.setText("Yes");
Button no = createButton(parent, IDialogConstants.CANCEL_ID, "No",
true);
no.moveBelow(ok);
no.setFocus();
}
}
public boolean confirmOverwritingProjectResources(final String projectName,
final FileListDiff diff) {
try {
return Util.runSWTSync(new Callable<Boolean>() {
public Boolean call() {
String message = "The selected project '"
+ projectName
+ "' will be used as a target project to carry out the synchronization.\n\n"
+ "All local changes in the project will be overwritten using the host's project and additional files will be deleted!\n\n"
+ "Press No and select 'Create copy...' in the invitation dialog if you are unsure.\n\n"
+ "Do you want to proceed?";
String PID = Saros.SAROS;
MultiStatus info = new MultiStatus(PID, 1, message, null);
for (IPath path : diff.getRemovedPaths()) {
info.add(new Status(IStatus.WARNING, PID, 1,
"File will be removed: " + path.toOSString(), null));
}
for (IPath path : diff.getAlteredPaths()) {
info.add(new Status(IStatus.WARNING, PID, 1,
"File will be overwritten: " + path.toOSString(),
null));
}
for (IPath path : diff.getAddedPaths()) {
info.add(new Status(IStatus.INFO, PID, 1,
"File will be added: " + path.toOSString(), null));
}
return new OverwriteErrorDialog(getShell(),
"Warning: Local changes will be deleted", null, info)
.open() == IDialogConstants.OK_ID;
}
});
} catch (Exception e) {
log.error(
"An error ocurred while trying to open the confirm dialog.", e);
return false;
}
}
@Override
public boolean performCancel() {
Util.runSafeAsync(log, new Runnable() {
public void run() {
process.localCancel(null, CancelOption.NOTIFY_PEER);
}
});
return true;
}
public void setWizardDlg(WizardDialogAccessable wd) {
this.wizardDialog = wd;
/**
* Listen to page changes so we can cancel our automatic clicking the
* next button
*/
this.wizardDialog.addPageChangingListener(new IPageChangingListener() {
public void handlePageChanging(PageChangingEvent event) {
pageChanges++;
}
});
}
/**
* Variable is only used to count how many times pageChanges were registered
* so we only press the next button if no page changes occurred.
*
* The only place this is needed is below in the pressWizardButton, if you
* want to know the number of page changes, count them yourself.
*/
private int pageChanges = 0;
protected boolean disposed = false;
/**
* Will wait one second and then press the next button, if the dialog is
* still on the given page (i.e. if the user presses next then this will not
* call next again).
*/
public void pressWizardButton(final int buttonID) {
final int pageChangesAtStart = pageChanges;
Util.runSafeAsync(log, new Runnable() {
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
log.error("Code not designed to be interruptable", e);
Thread.currentThread().interrupt();
return;
}
Util.runSafeSWTAsync(log, new Runnable() {
public void run() {
// User clicked next in the meantime
if (pageChangesAtStart != pageChanges)
return;
// Dialog already closed
if (disposed)
return;
// Button not enabled
if (!wizardDialog.getWizardButton(buttonID).isEnabled())
return;
wizardDialog.buttonPressed(buttonID);
}
});
}
});
}
@Override
public void dispose() {
disposed = true;
super.dispose();
}
public String getUpdateProject() {
return updateProjectName;
}
public boolean isUpdateSelected() {
return updateSelected;
}
public void cancelWizard(final JID jid, final String errorMsg,
final CancelLocation cancelLocation) {
Util.runSafeSWTAsync(log, new Runnable() {
public void run() {
wizardDialog.close();
}
});
Util.runSafeSWTAsync(log, new Runnable() {
public void run() {
showCancelMessage(jid, errorMsg, cancelLocation);
}
});
}
public void showCancelMessage(JID jid, String errorMsg,
CancelLocation cancelLocation) {
String peer = jid.getBase();
if (errorMsg != null) {
switch (cancelLocation) {
case LOCAL:
EclipseUtils.openErrorMessageDialog(getShell(),
"Invitation Cancelled",
"Your invitation has been cancelled "
+ "locally because of an error:\n\n" + errorMsg);
break;
case REMOTE:
EclipseUtils.openErrorMessageDialog(getShell(),
"Invitation Cancelled",
"Your invitation has been cancelled " + "remotely by "
+ peer + " because of an error:\n\n" + errorMsg);
}
} else {
switch (cancelLocation) {
case LOCAL:
break;
case REMOTE:
EclipseUtils.openInformationMessageDialog(getShell(),
"Invitation Cancelled",
"Your invitation has been cancelled remotely by " + peer
+ "!");
}
}
}
protected void processException(Throwable t) {
if (t instanceof LocalCancellationException) {
cancelWizard(process.getPeer(), t.getMessage(),
CancelLocation.LOCAL);
} else if (t instanceof RemoteCancellationException) {
cancelWizard(process.getPeer(), t.getMessage(),
CancelLocation.REMOTE);
} else {
log.error("This type of exception is not expected here: ", t);
cancelWizard(process.getPeer(), "Unkown error: " + t.getMessage(),
CancelLocation.REMOTE);
}
}
}
| true | true | public boolean performFinish() {
final IProject source = namePage.getSourceProject();
final String target = namePage.getTargetProjectName();
final boolean skip = namePage.isSyncSkippingSelected();
/*
* Ask the user whether to overwrite local resources only if resources
* are supposed to be overwritten based on the synchronization options
* and if there are differences between the remote and local project.
*/
if (namePage.overwriteProjectResources()) {
FileListDiff diff;
if (!source.isOpen()) {
try {
source.open(null);
} catch (CoreException e1) {
log.debug("An error occur while opening the source file",
e1);
}
}
try {
diff = FileListDiff.diff(new FileList(source),
process.getRemoteFileList());
} catch (CoreException e) {
MessageDialog.openError(getShell(), "Error computing FileList",
"Could not compute local FileList: " + e.getMessage());
return false;
}
if (diff.getRemovedPaths().size() > 0
|| diff.getAlteredPaths().size() > 0)
if (!confirmOverwritingProjectResources(source.getName(), diff))
return false;
}
try {
getContainer().run(true, true, new IRunnableWithProgress() {
public void run(IProgressMonitor monitor)
throws InvocationTargetException, InterruptedException {
try {
JoinSessionWizard.this.process.accept(source, target,
skip, SubMonitor.convert(monitor));
} catch (Exception e) {
throw new InvocationTargetException(e);
}
}
});
} catch (InvocationTargetException e) {
processException(e.getCause());
return false;
} catch (InterruptedException e) {
log.error("Code not designed to be interrupted.", e);
processException(e);
return false;
}
getShell().forceActive();
return true;
}
| public boolean performFinish() {
final IProject source = namePage.getSourceProject();
final String target = namePage.getTargetProjectName();
final boolean skip = namePage.isSyncSkippingSelected();
/*
* Ask the user whether to overwrite local resources only if resources
* are supposed to be overwritten based on the synchronization options
* and if there are differences between the remote and local project.
*/
if (namePage.overwriteProjectResources()
&& !preferenceUtils.isAutoReuseExisting()) {
FileListDiff diff;
if (!source.isOpen()) {
try {
source.open(null);
} catch (CoreException e1) {
log.debug("An error occur while opening the source file",
e1);
}
}
try {
diff = FileListDiff.diff(new FileList(source),
process.getRemoteFileList());
} catch (CoreException e) {
MessageDialog.openError(getShell(), "Error computing FileList",
"Could not compute local FileList: " + e.getMessage());
return false;
}
if (diff.getRemovedPaths().size() > 0
|| diff.getAlteredPaths().size() > 0)
if (!confirmOverwritingProjectResources(source.getName(), diff))
return false;
}
try {
getContainer().run(true, true, new IRunnableWithProgress() {
public void run(IProgressMonitor monitor)
throws InvocationTargetException, InterruptedException {
try {
JoinSessionWizard.this.process.accept(source, target,
skip, SubMonitor.convert(monitor));
} catch (Exception e) {
throw new InvocationTargetException(e);
}
}
});
} catch (InvocationTargetException e) {
processException(e.getCause());
return false;
} catch (InterruptedException e) {
log.error("Code not designed to be interrupted.", e);
processException(e);
return false;
}
getShell().forceActive();
return true;
}
|
diff --git a/java/uk/ltd/getahead/dwr/convert/EnumConverter.java b/java/uk/ltd/getahead/dwr/convert/EnumConverter.java
index 726a9a54..72d3008b 100644
--- a/java/uk/ltd/getahead/dwr/convert/EnumConverter.java
+++ b/java/uk/ltd/getahead/dwr/convert/EnumConverter.java
@@ -1,65 +1,64 @@
package uk.ltd.getahead.dwr.convert;
import java.lang.reflect.Method;
import uk.ltd.getahead.dwr.ConversionException;
import uk.ltd.getahead.dwr.Converter;
import uk.ltd.getahead.dwr.InboundContext;
import uk.ltd.getahead.dwr.InboundVariable;
import uk.ltd.getahead.dwr.Messages;
import uk.ltd.getahead.dwr.OutboundContext;
import uk.ltd.getahead.dwr.OutboundVariable;
import uk.ltd.getahead.dwr.compat.BaseV20Converter;
import uk.ltd.getahead.dwr.util.LocalUtil;
/**
* Converter for all primitive types
* @author Joe Walker [joe at getahead dot ltd dot uk]
*/
public class EnumConverter extends BaseV20Converter implements Converter
{
/* (non-Javadoc)
* @see uk.ltd.getahead.dwr.Converter#convertInbound(java.lang.Class, java.util.List, uk.ltd.getahead.dwr.InboundVariable, uk.ltd.getahead.dwr.InboundContext)
*/
public Object convertInbound(Class paramType, InboundVariable iv, InboundContext inctx) throws ConversionException
{
String value = LocalUtil.decode(iv.getValue());
- // Object[] values = paramType.getEnumConstants();
Object[] values = null;
try
{
- Method getter = paramType.getMethod("getEnumConstants", null); //$NON-NLS-1$
+ Method getter = paramType.getMethod("values", new Class[0]); //$NON-NLS-1$
values = (Object[]) getter.invoke(paramType, null);
}
catch (NoSuchMethodException ex)
{
// We would like to have done: if (!paramType.isEnum())
// But this catch block has the same effect
throw new ConversionException(Messages.getString("EnumConverter.TypeNotEnum", paramType)); //$NON-NLS-1$
}
catch (Exception ex)
{
throw new ConversionException(Messages.getString("EnumConverter.ReflectionError", paramType), ex); //$NON-NLS-1$
}
for (int i = 0; i < values.length; i++)
{
Object en = values[i];
if (value.equals(en.toString()))
{
return en;
}
}
throw new ConversionException(Messages.getString("EnumConverter.NoMatch", value, paramType)); //$NON-NLS-1$
}
/* (non-Javadoc)
* @see uk.ltd.getahead.dwr.Converter#convertOutbound(java.lang.Object, uk.ltd.getahead.dwr.OutboundContext)
*/
public OutboundVariable convertOutbound(Object object, OutboundContext outctx)
{
return new OutboundVariable("", '\'' + object.toString() + '\''); //$NON-NLS-1$
}
}
| false | true | public Object convertInbound(Class paramType, InboundVariable iv, InboundContext inctx) throws ConversionException
{
String value = LocalUtil.decode(iv.getValue());
// Object[] values = paramType.getEnumConstants();
Object[] values = null;
try
{
Method getter = paramType.getMethod("getEnumConstants", null); //$NON-NLS-1$
values = (Object[]) getter.invoke(paramType, null);
}
catch (NoSuchMethodException ex)
{
// We would like to have done: if (!paramType.isEnum())
// But this catch block has the same effect
throw new ConversionException(Messages.getString("EnumConverter.TypeNotEnum", paramType)); //$NON-NLS-1$
}
catch (Exception ex)
{
throw new ConversionException(Messages.getString("EnumConverter.ReflectionError", paramType), ex); //$NON-NLS-1$
}
for (int i = 0; i < values.length; i++)
{
Object en = values[i];
if (value.equals(en.toString()))
{
return en;
}
}
throw new ConversionException(Messages.getString("EnumConverter.NoMatch", value, paramType)); //$NON-NLS-1$
}
| public Object convertInbound(Class paramType, InboundVariable iv, InboundContext inctx) throws ConversionException
{
String value = LocalUtil.decode(iv.getValue());
Object[] values = null;
try
{
Method getter = paramType.getMethod("values", new Class[0]); //$NON-NLS-1$
values = (Object[]) getter.invoke(paramType, null);
}
catch (NoSuchMethodException ex)
{
// We would like to have done: if (!paramType.isEnum())
// But this catch block has the same effect
throw new ConversionException(Messages.getString("EnumConverter.TypeNotEnum", paramType)); //$NON-NLS-1$
}
catch (Exception ex)
{
throw new ConversionException(Messages.getString("EnumConverter.ReflectionError", paramType), ex); //$NON-NLS-1$
}
for (int i = 0; i < values.length; i++)
{
Object en = values[i];
if (value.equals(en.toString()))
{
return en;
}
}
throw new ConversionException(Messages.getString("EnumConverter.NoMatch", value, paramType)); //$NON-NLS-1$
}
|
diff --git a/src/uk/me/parabola/imgfmt/app/trergn/LinePreparer.java b/src/uk/me/parabola/imgfmt/app/trergn/LinePreparer.java
index 9356c78c..e24fb13f 100644
--- a/src/uk/me/parabola/imgfmt/app/trergn/LinePreparer.java
+++ b/src/uk/me/parabola/imgfmt/app/trergn/LinePreparer.java
@@ -1,333 +1,333 @@
/**
* Copyright (C) 2006 Steve Ratcliffe
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* Author: steve
* Date: 24-Dec-2006
*/
package uk.me.parabola.imgfmt.app.trergn;
import java.util.List;
import uk.me.parabola.imgfmt.app.BitWriter;
import uk.me.parabola.imgfmt.app.Coord;
import uk.me.parabola.log.Logger;
/**
* This class holds all of the calculations needed to encode a line into
* the garmin format.
*/
class LinePreparer {
private static final Logger log = Logger.getLogger(LinePreparer.class);
// These are our inputs.
private final Polyline polyline;
private boolean extraBit;
private boolean xSameSign;
private boolean xSignNegative; // Set if all negative
private boolean ySameSign;
private boolean ySignNegative; // Set if all negative
// The base number of bits
private int xBase;
private int yBase;
// The delta changes between the points.
private int[] deltas;
private boolean[] nodes;
LinePreparer(Polyline line) {
if (line.isRoad() && line.roadHasInternalNodes())
// it might be safe to write the extra bits regardless,
// but who knows
extraBit = true;
polyline = line;
calcLatLong();
calcDeltas();
}
/**
* Write the bit stream to a BitWriter and return it.
*
* @return A class containing the writen byte stream.
*/
public BitWriter makeBitStream() {
assert xBase >= 0 && yBase >= 0;
int xbits = 2;
if (xBase < 10)
xbits += xBase;
else
xbits += (2 * xBase) - 9;
int ybits = 2;
if (yBase < 10)
ybits += yBase;
else
ybits += (2 * yBase) - 9;
// Note no sign included.
if (log.isDebugEnabled())
log.debug("xbits", xbits, ", y=", ybits);
// Write the bitstream
BitWriter bw = new BitWriter();
// Pre bit stream info
bw.putn(xBase, 4);
bw.putn(yBase, 4);
bw.put1(xSameSign);
if (xSameSign)
bw.put1(xSignNegative);
bw.put1(ySameSign);
if (ySameSign)
bw.put1(ySignNegative);
if (log.isDebugEnabled()) {
log.debug("x same is", xSameSign, "sign is", xSignNegative);
log.debug("y same is", ySameSign, "sign is", ySignNegative);
}
// first extra bit always appears to be false
// refers to the start point?
if (extraBit)
bw.put1(false);
for (int i = 0; i < deltas.length; i+=2) {
int dx = deltas[i];
int dy = deltas[i + 1];
if (dx == 0 && dy == 0)
continue;
if (log.isDebugEnabled())
log.debug("x delta", dx, "~", xbits);
assert dx >> xbits == 0 || dx >> xbits == -1;
if (xSameSign) {
bw.putn(abs(dx), xbits);
} else {
bw.putn(dx, xbits);
bw.put1(dx < 0);
}
if (log.isDebugEnabled())
log.debug("y delta", dy, ybits);
assert dy >> ybits == 0 || dy >> ybits == -1;
if (ySameSign) {
bw.putn(abs(dy), ybits);
} else {
bw.putn(dy, ybits);
bw.put1(dy < 0);
}
if (extraBit)
bw.put1(nodes[i/2]);
}
if (log.isDebugEnabled())
log.debug(bw);
return bw;
}
/**
* Calculate the correct lat and long points. They must be shifted if
* required by the zoom level. The point that is taken to be the
* location is just the first point in the line.
*/
private void calcLatLong() {
Coord co = polyline.getPoints().get(0);
polyline.setLatitude(co.getLatitude());
polyline.setLongitude(co.getLongitude());
}
/**
* Calculate the deltas of one point to the other. While we are doing
* this we must save more information about the maximum sizes, if they
* are all the same sign etc. This must be done separately for both
* the lat and long values.
*/
private void calcDeltas() {
log.info("label offset", polyline.getLabel().getOffset());
int shift = polyline.getSubdiv().getShift();
List<Coord> points = polyline.getPoints();
// Space to hold the deltas
deltas = new int[2 * (points.size() - 1)];
if (extraBit)
nodes = new boolean[points.size()];
boolean first = true;
// OK go through the points
int lastLat = 0;
int lastLong = 0;
boolean xDiffSign = false; // The long values have different sign
boolean yDiffSign = false; // The lat values have different sign
int xSign = 0; // If all the same sign, then this 1 or -1 depending on +ve or -ve
int ySign = 0; // As above for lat.
int xBits = 0; // Number of bits needed for long
int yBits = 0; // Number of bits needed for lat.
// index of first point in a series of identical coords (after shift)
int firstsame = 0;
for (int i = 0; i < points.size(); i++) {
Coord co = points.get(i);
int lat = co.getLatitude() >> shift;
int lon = co.getLongitude() >> shift;
if (log.isDebugEnabled())
log.debug("shifted pos", lat, lon);
if (first) {
lastLat = lat;
lastLong = lon;
first = false;
continue;
}
int dx = lon - lastLong;
int dy = lat - lastLat;
lastLong = lon;
lastLat = lat;
if (dx != 0 || dy != 0)
firstsame = i;
// Current thought is that the node indicator is set when
// the point is a node. There's a separate first extra bit
// that always appears to be false. The last points' extra bit
// is set if the point is a node and this is not the last
// polyline making up the road.
// Todo: special case the last bit
if (extraBit) {
boolean extra;
if (i < nodes.length - 1)
extra = co.getId() != 0;
else
extra = false; // XXX
// only the first among a range of equal points
// is written, so set the bit if any of the points
// is a node
nodes[firstsame] = nodes[firstsame] || extra;
}
// See if they can all be the same sign.
if (!xDiffSign) {
int thisSign = (dx >= 0)? 1: -1;
if (xSign == 0) {
xSign = thisSign;
} else if (thisSign != xSign) {
// The signs are different
xDiffSign = true;
}
}
if (!yDiffSign) {
int thisSign = (dy >= 0)? 1: -1;
if (ySign == 0) {
ySign = thisSign;
} else if (thisSign != ySign) {
// The signs are different
yDiffSign = true;
}
}
// Find the maximum number of bits required to hold the value.
int nbits = bitsNeeded(dx);
if (nbits > xBits)
xBits = nbits;
nbits = bitsNeeded(dy);
if (nbits > yBits)
yBits = nbits;
// Save the deltas
- deltas[2*i] = dx;
- deltas[2*i + 1] = dy;
+ deltas[2*(i-1)] = dx;
+ deltas[2*(i-1) + 1] = dy;
}
// Now we need to know the 'base' number of bits used to represent
// the value. In decoding you start with that number and add various
// adjustments to get the final value. We need to try and work
// backwards from this.
//
// I don't care about getting the smallest possible file size so
// err on the side of caution.
//
// Note that the sign bit is already not included so there is
// no adjustment needed for it.
if (log.isDebugEnabled())
log.debug("initial xBits, yBits", xBits, yBits);
if (xBits < 2)
xBits = 2;
int tmp = xBits - 2;
if (tmp > 10) {
if ((tmp & 0x1) == 0)
tmp++;
tmp = 9 + (tmp - 9) / 2;
}
this.xBase = tmp;
if (yBits < 2)
yBits = 2;
tmp = yBits - 2;
if (tmp > 10) {
if ((tmp & 0x1) == 0)
tmp++;
tmp = 9 + (tmp - 9) / 2;
}
this.yBase = tmp;
if (log.isDebugEnabled())
log.debug("initial xBase, yBase", xBase, yBase);
// Set flags for same sign etc.
this.xSameSign = !xDiffSign;
this.ySameSign = !yDiffSign;
this.xSignNegative = xSign < 0;
this.ySignNegative = ySign < 0;
}
/**
* The bits needed to hold a number without truncating it.
*
* @param val The number for bit couting.
* @return The number of bits required.
*/
private int bitsNeeded(int val) {
int n = abs(val);
int count = val < 0? 1: 0;
while (n != 0) {
n >>>= 1;
count++;
}
return count;
}
private int abs(int val) {
if (val < 0)
return -val;
else
return val;
}
public boolean isExtraBit() {
return extraBit;
}
}
| true | true | private void calcDeltas() {
log.info("label offset", polyline.getLabel().getOffset());
int shift = polyline.getSubdiv().getShift();
List<Coord> points = polyline.getPoints();
// Space to hold the deltas
deltas = new int[2 * (points.size() - 1)];
if (extraBit)
nodes = new boolean[points.size()];
boolean first = true;
// OK go through the points
int lastLat = 0;
int lastLong = 0;
boolean xDiffSign = false; // The long values have different sign
boolean yDiffSign = false; // The lat values have different sign
int xSign = 0; // If all the same sign, then this 1 or -1 depending on +ve or -ve
int ySign = 0; // As above for lat.
int xBits = 0; // Number of bits needed for long
int yBits = 0; // Number of bits needed for lat.
// index of first point in a series of identical coords (after shift)
int firstsame = 0;
for (int i = 0; i < points.size(); i++) {
Coord co = points.get(i);
int lat = co.getLatitude() >> shift;
int lon = co.getLongitude() >> shift;
if (log.isDebugEnabled())
log.debug("shifted pos", lat, lon);
if (first) {
lastLat = lat;
lastLong = lon;
first = false;
continue;
}
int dx = lon - lastLong;
int dy = lat - lastLat;
lastLong = lon;
lastLat = lat;
if (dx != 0 || dy != 0)
firstsame = i;
// Current thought is that the node indicator is set when
// the point is a node. There's a separate first extra bit
// that always appears to be false. The last points' extra bit
// is set if the point is a node and this is not the last
// polyline making up the road.
// Todo: special case the last bit
if (extraBit) {
boolean extra;
if (i < nodes.length - 1)
extra = co.getId() != 0;
else
extra = false; // XXX
// only the first among a range of equal points
// is written, so set the bit if any of the points
// is a node
nodes[firstsame] = nodes[firstsame] || extra;
}
// See if they can all be the same sign.
if (!xDiffSign) {
int thisSign = (dx >= 0)? 1: -1;
if (xSign == 0) {
xSign = thisSign;
} else if (thisSign != xSign) {
// The signs are different
xDiffSign = true;
}
}
if (!yDiffSign) {
int thisSign = (dy >= 0)? 1: -1;
if (ySign == 0) {
ySign = thisSign;
} else if (thisSign != ySign) {
// The signs are different
yDiffSign = true;
}
}
// Find the maximum number of bits required to hold the value.
int nbits = bitsNeeded(dx);
if (nbits > xBits)
xBits = nbits;
nbits = bitsNeeded(dy);
if (nbits > yBits)
yBits = nbits;
// Save the deltas
deltas[2*i] = dx;
deltas[2*i + 1] = dy;
}
// Now we need to know the 'base' number of bits used to represent
// the value. In decoding you start with that number and add various
// adjustments to get the final value. We need to try and work
// backwards from this.
//
// I don't care about getting the smallest possible file size so
// err on the side of caution.
//
// Note that the sign bit is already not included so there is
// no adjustment needed for it.
if (log.isDebugEnabled())
log.debug("initial xBits, yBits", xBits, yBits);
if (xBits < 2)
xBits = 2;
int tmp = xBits - 2;
if (tmp > 10) {
if ((tmp & 0x1) == 0)
tmp++;
tmp = 9 + (tmp - 9) / 2;
}
this.xBase = tmp;
if (yBits < 2)
yBits = 2;
tmp = yBits - 2;
if (tmp > 10) {
if ((tmp & 0x1) == 0)
tmp++;
tmp = 9 + (tmp - 9) / 2;
}
this.yBase = tmp;
if (log.isDebugEnabled())
log.debug("initial xBase, yBase", xBase, yBase);
// Set flags for same sign etc.
this.xSameSign = !xDiffSign;
this.ySameSign = !yDiffSign;
this.xSignNegative = xSign < 0;
this.ySignNegative = ySign < 0;
}
| private void calcDeltas() {
log.info("label offset", polyline.getLabel().getOffset());
int shift = polyline.getSubdiv().getShift();
List<Coord> points = polyline.getPoints();
// Space to hold the deltas
deltas = new int[2 * (points.size() - 1)];
if (extraBit)
nodes = new boolean[points.size()];
boolean first = true;
// OK go through the points
int lastLat = 0;
int lastLong = 0;
boolean xDiffSign = false; // The long values have different sign
boolean yDiffSign = false; // The lat values have different sign
int xSign = 0; // If all the same sign, then this 1 or -1 depending on +ve or -ve
int ySign = 0; // As above for lat.
int xBits = 0; // Number of bits needed for long
int yBits = 0; // Number of bits needed for lat.
// index of first point in a series of identical coords (after shift)
int firstsame = 0;
for (int i = 0; i < points.size(); i++) {
Coord co = points.get(i);
int lat = co.getLatitude() >> shift;
int lon = co.getLongitude() >> shift;
if (log.isDebugEnabled())
log.debug("shifted pos", lat, lon);
if (first) {
lastLat = lat;
lastLong = lon;
first = false;
continue;
}
int dx = lon - lastLong;
int dy = lat - lastLat;
lastLong = lon;
lastLat = lat;
if (dx != 0 || dy != 0)
firstsame = i;
// Current thought is that the node indicator is set when
// the point is a node. There's a separate first extra bit
// that always appears to be false. The last points' extra bit
// is set if the point is a node and this is not the last
// polyline making up the road.
// Todo: special case the last bit
if (extraBit) {
boolean extra;
if (i < nodes.length - 1)
extra = co.getId() != 0;
else
extra = false; // XXX
// only the first among a range of equal points
// is written, so set the bit if any of the points
// is a node
nodes[firstsame] = nodes[firstsame] || extra;
}
// See if they can all be the same sign.
if (!xDiffSign) {
int thisSign = (dx >= 0)? 1: -1;
if (xSign == 0) {
xSign = thisSign;
} else if (thisSign != xSign) {
// The signs are different
xDiffSign = true;
}
}
if (!yDiffSign) {
int thisSign = (dy >= 0)? 1: -1;
if (ySign == 0) {
ySign = thisSign;
} else if (thisSign != ySign) {
// The signs are different
yDiffSign = true;
}
}
// Find the maximum number of bits required to hold the value.
int nbits = bitsNeeded(dx);
if (nbits > xBits)
xBits = nbits;
nbits = bitsNeeded(dy);
if (nbits > yBits)
yBits = nbits;
// Save the deltas
deltas[2*(i-1)] = dx;
deltas[2*(i-1) + 1] = dy;
}
// Now we need to know the 'base' number of bits used to represent
// the value. In decoding you start with that number and add various
// adjustments to get the final value. We need to try and work
// backwards from this.
//
// I don't care about getting the smallest possible file size so
// err on the side of caution.
//
// Note that the sign bit is already not included so there is
// no adjustment needed for it.
if (log.isDebugEnabled())
log.debug("initial xBits, yBits", xBits, yBits);
if (xBits < 2)
xBits = 2;
int tmp = xBits - 2;
if (tmp > 10) {
if ((tmp & 0x1) == 0)
tmp++;
tmp = 9 + (tmp - 9) / 2;
}
this.xBase = tmp;
if (yBits < 2)
yBits = 2;
tmp = yBits - 2;
if (tmp > 10) {
if ((tmp & 0x1) == 0)
tmp++;
tmp = 9 + (tmp - 9) / 2;
}
this.yBase = tmp;
if (log.isDebugEnabled())
log.debug("initial xBase, yBase", xBase, yBase);
// Set flags for same sign etc.
this.xSameSign = !xDiffSign;
this.ySameSign = !yDiffSign;
this.xSignNegative = xSign < 0;
this.ySignNegative = ySign < 0;
}
|
diff --git a/servicemix-components/src/test/java/org/apache/servicemix/components/jca/JmsOverJcaWithFullXATest.java b/servicemix-components/src/test/java/org/apache/servicemix/components/jca/JmsOverJcaWithFullXATest.java
index 8679dbdd4..6b49078c1 100644
--- a/servicemix-components/src/test/java/org/apache/servicemix/components/jca/JmsOverJcaWithFullXATest.java
+++ b/servicemix-components/src/test/java/org/apache/servicemix/components/jca/JmsOverJcaWithFullXATest.java
@@ -1,38 +1,39 @@
/*
* Copyright 2005-2006 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.servicemix.components.jca;
import org.apache.servicemix.tck.TestSupport;
import org.springframework.context.support.AbstractXmlApplicationContext;
import org.xbean.spring.context.ClassPathXmlApplicationContext;
import javax.xml.namespace.QName;
/**
* @version $Revision$
*/
public class JmsOverJcaWithFullXATest extends TestSupport {
public void testSendMessagesToJmsThenOutofJmsToReceiver() throws Exception {
QName service = new QName("http://servicemix.org/cheese/", "myJmsSender");
- assertSendAndReceiveMessages(service);
+ sendMessages(service, messageCount, false);
+ assertMessagesReceived(messageCount);
}
protected AbstractXmlApplicationContext createBeanFactory() {
return new ClassPathXmlApplicationContext("org/apache/servicemix/components/jca/xa-on-jca-flow.xml");
}
}
| true | true | public void testSendMessagesToJmsThenOutofJmsToReceiver() throws Exception {
QName service = new QName("http://servicemix.org/cheese/", "myJmsSender");
assertSendAndReceiveMessages(service);
}
| public void testSendMessagesToJmsThenOutofJmsToReceiver() throws Exception {
QName service = new QName("http://servicemix.org/cheese/", "myJmsSender");
sendMessages(service, messageCount, false);
assertMessagesReceived(messageCount);
}
|
diff --git a/spoon-maven-plugin/src/main/java/com/squareup/spoon/SpoonMojo.java b/spoon-maven-plugin/src/main/java/com/squareup/spoon/SpoonMojo.java
index 7b4c57c..042151a 100644
--- a/spoon-maven-plugin/src/main/java/com/squareup/spoon/SpoonMojo.java
+++ b/spoon-maven-plugin/src/main/java/com/squareup/spoon/SpoonMojo.java
@@ -1,286 +1,290 @@
// Copyright 2012 Square, Inc.
package com.squareup.spoon;
import com.google.common.base.Strings;
import java.io.File;
import java.util.List;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectHelper;
import org.sonatype.aether.RepositorySystem;
import org.sonatype.aether.RepositorySystemSession;
import org.sonatype.aether.collection.CollectRequest;
import org.sonatype.aether.collection.CollectResult;
import org.sonatype.aether.collection.DependencyCollectionException;
import org.sonatype.aether.graph.Dependency;
import org.sonatype.aether.graph.DependencyNode;
import org.sonatype.aether.graph.DependencyVisitor;
import org.sonatype.aether.repository.RemoteRepository;
import org.sonatype.aether.resolution.ArtifactRequest;
import org.sonatype.aether.resolution.ArtifactResolutionException;
import org.sonatype.aether.resolution.ArtifactResult;
import org.sonatype.aether.resolution.DependencyRequest;
import org.sonatype.aether.util.artifact.DefaultArtifact;
import static com.squareup.spoon.SpoonRunner.DEFAULT_OUTPUT_DIRECTORY;
import static org.apache.maven.plugins.annotations.LifecyclePhase.INTEGRATION_TEST;
/**
* Goal which invokes Spoon. By default the output will be placed in a {@code spoon-output/} folder
* in your project's build directory.
*/
@SuppressWarnings("UnusedDeclaration") // Used reflectively by Maven.
@Mojo(name = "run", defaultPhase = INTEGRATION_TEST, threadSafe = false)
public class SpoonMojo extends AbstractMojo {
private static final String SPOON_GROUP_ID = "com.squareup.spoon";
private static final String SPOON_PLUGIN_ARTIFACT_ID = "spoon-maven-plugin";
private static final String SPOON_RUNNER_ARTIFACT_ID = "spoon-runner";
private static final String ARTIFACT_TYPE = "zip";
private static final String ARTIFACT_CLASSIFIER = "spoon-output";
/** {@code -Dmaven.test.skip} is commonly used with Maven to skip tests. We honor it too. */
@Parameter(property = "maven.test.skip", defaultValue = "false", readonly = true)
private boolean mavenTestSkip;
/** {@code -DskipTests} is commonly used with Maven to skip tests. We honor it too. */
@Parameter(property = "skipTests", defaultValue = "false", readonly = true)
private boolean mavenSkipTests;
/** Configuration option to skip execution. */
@Parameter
private boolean skip;
/** Location of the output directory. */
@Parameter(defaultValue = "${project.build.directory}/spoon-output")
private File outputDirectory;
/** A title for the output website. */
@Parameter(defaultValue = "${project.name}")
private String title;
/** The location of the Android SDK. */
@Parameter(defaultValue = "${env.ANDROID_HOME}")
private String androidSdk;
/** Attaches output artifact as zip when {@code true}. */
@Parameter
private boolean attachArtifact;
/** If true then any test failures will cause the plugin to error. */
@Parameter
private boolean failOnFailure;
/** Whether debug logging is enabled. */
@Parameter
private boolean debug;
@Parameter(property = "project.build.directory", required = true, readonly = true)
private File buildDirectory;
@Parameter(property = "project", required = true, readonly = true)
private MavenProject project;
/** Run only a specific test. */
@Parameter(defaultValue = "${spoon.test.class}")
private String className;
/** Run only a specific test method. Must be specified with {@link #className}. */
@Parameter(defaultValue = "${spoon.test.method}")
private String methodName;
@Component
private MavenProjectHelper projectHelper;
@Component
private RepositorySystem repositorySystem;
@Parameter(defaultValue = "${repositorySystemSession}", readonly = true)
private RepositorySystemSession repoSession;
@Parameter(defaultValue = "${project.remoteProjectRepositories}", readonly = true)
private List<RemoteRepository> remoteRepositories;
public void execute() throws MojoExecutionException {
Log log = getLog();
if (mavenTestSkip || mavenSkipTests || skip) {
log.debug("maven.test.skip = " + mavenTestSkip);
log.debug("skipTests = " + mavenSkipTests);
log.debug("skip = " + skip);
log.info("Skipping Spoon execution.");
return;
}
+ if (androidSdk == null) {
+ throw new MojoExecutionException(
+ "Could not find Android SDK. Ensure ANDROID_HOME environment variable is set.");
+ }
File sdkFile = new File(androidSdk);
if (!sdkFile.exists()) {
throw new MojoExecutionException(
- "Could not find Android SDK. Ensure ANDROID_HOME environment variable is set.");
+ String.format("Could not find Android SDK at: %s", androidSdk));
}
log.debug("Android SDK: " + sdkFile.getAbsolutePath());
File instrumentation = getInstrumentationApk();
log.debug("Instrumentation APK: " + instrumentation);
File app = getApplicationApk();
log.debug("Application APK: " + app.getAbsolutePath());
if (!Strings.isNullOrEmpty(className)) {
log.debug("Class name: " + className);
if (!Strings.isNullOrEmpty(methodName)) {
log.debug("Method name: " + methodName);
}
}
String classpath = getSpoonClasspath();
log.debug("Classpath: " + classpath);
log.debug("Output directory: " + outputDirectory.getAbsolutePath());
log.debug("Spoon title: " + title);
log.debug("Debug: " + Boolean.toString(debug));
boolean success = new SpoonRunner.Builder() //
.setTitle(title)
.setApplicationApk(app)
.setInstrumentationApk(instrumentation)
.setOutputDirectory(outputDirectory)
.setAndroidSdk(sdkFile)
.setDebug(debug)
.setClasspath(classpath)
.setClassName(className)
.setMethodName(methodName)
.useAllAttachedDevices()
.build()
.run();
if (!success && failOnFailure) {
throw new MojoExecutionException("Spoon returned non-zero exit code.");
}
if (attachArtifact) {
File outputZip = new File(buildDirectory, DEFAULT_OUTPUT_DIRECTORY + ".zip");
ZipUtil.zip(outputZip, outputDirectory);
projectHelper.attachArtifact(project, ARTIFACT_TYPE, ARTIFACT_CLASSIFIER, outputZip);
}
}
private File getInstrumentationApk() throws MojoExecutionException {
Artifact instrumentationArtifact = project.getArtifact();
if (!"apk".equals(instrumentationArtifact.getType())) {
throw new MojoExecutionException("Spoon can only be invoked on a module with type 'apk'.");
}
return aetherArtifact(instrumentationArtifact).getFile();
}
private File getApplicationApk() throws MojoExecutionException {
for (Artifact dependency : project.getDependencyArtifacts()) {
if ("apk".equals(dependency.getType())) {
return aetherArtifact(dependency).getFile();
}
}
throw new MojoExecutionException(
"Could not find application. Ensure 'apk' dependency on it exists.");
}
private org.sonatype.aether.artifact.Artifact aetherArtifact(Artifact dep)
throws MojoExecutionException {
return resolveArtifact(dep.getGroupId(), dep.getArtifactId(), "apk", dep.getVersion());
}
private String getSpoonClasspath() throws MojoExecutionException {
Log log = getLog();
String spoonVersion = findMyVersion();
log.debug("[getSpoonClasspath] Plugin version: " + spoonVersion);
org.sonatype.aether.artifact.Artifact spoonRunner =
resolveArtifact(SPOON_GROUP_ID, SPOON_RUNNER_ARTIFACT_ID, "jar", spoonVersion);
log.debug("[getSpoonClasspath] Runner artifact: " + spoonRunner);
return createClasspath(spoonRunner);
}
private String findMyVersion() throws MojoExecutionException {
for (Artifact artifact : project.getPluginArtifacts()) {
if (SPOON_GROUP_ID.equals(artifact.getGroupId()) //
&& SPOON_PLUGIN_ARTIFACT_ID.equals(artifact.getArtifactId())) {
return artifact.getVersion();
}
}
throw new MojoExecutionException("Could not find reference to Spoon plugin artifact.");
}
private org.sonatype.aether.artifact.Artifact resolveArtifact(String groupId, String artifactId,
String extension, String version) throws MojoExecutionException {
ArtifactRequest request = new ArtifactRequest();
request.setArtifact(new DefaultArtifact(groupId, artifactId, extension, version));
request.setRepositories(remoteRepositories);
try {
ArtifactResult artifactResult = repositorySystem.resolveArtifact(repoSession, request);
return artifactResult.getArtifact();
} catch (ArtifactResolutionException e) {
throw new MojoExecutionException("Unable to resolve runner from repository.", e);
}
}
private String createClasspath(org.sonatype.aether.artifact.Artifact artifact)
throws MojoExecutionException {
// Request a collection of all dependencies for the artifact.
DependencyRequest dependencyRequest = new DependencyRequest();
CollectRequest collectRequest = new CollectRequest();
collectRequest.setRoot(new Dependency(artifact, ""));
for (RemoteRepository remoteRepository : remoteRepositories) {
collectRequest.addRepository(remoteRepository);
}
CollectResult result;
try {
result = repositorySystem.collectDependencies(repoSession, collectRequest);
} catch (DependencyCollectionException e) {
throw new MojoExecutionException("Unable to resolve runner dependencies.", e);
}
final Log log = getLog();
final StringBuilder builder = new StringBuilder();
// Walk the tree of all dependencies to add to the classpath.
result.getRoot().accept(new DependencyVisitor() {
@Override public boolean visitEnter(DependencyNode node) {
log.debug("Visiting: " + node);
// Resolve the dependency node artifact into a real, local artifact.
org.sonatype.aether.artifact.Artifact resolvedArtifact;
try {
org.sonatype.aether.artifact.Artifact nodeArtifact = node.getDependency().getArtifact();
resolvedArtifact =
resolveArtifact(nodeArtifact.getGroupId(), nodeArtifact.getArtifactId(), "jar",
nodeArtifact.getVersion());
} catch (MojoExecutionException e) {
throw new RuntimeException(e);
}
// Add the artifact's path to our classpath.
if (builder.length() > 0) {
builder.append(File.pathSeparator);
}
builder.append(resolvedArtifact.getFile().getAbsolutePath());
return true;
}
@Override public boolean visitLeave(DependencyNode node) {
return true;
}
});
return builder.toString();
}
}
| false | true | public void execute() throws MojoExecutionException {
Log log = getLog();
if (mavenTestSkip || mavenSkipTests || skip) {
log.debug("maven.test.skip = " + mavenTestSkip);
log.debug("skipTests = " + mavenSkipTests);
log.debug("skip = " + skip);
log.info("Skipping Spoon execution.");
return;
}
File sdkFile = new File(androidSdk);
if (!sdkFile.exists()) {
throw new MojoExecutionException(
"Could not find Android SDK. Ensure ANDROID_HOME environment variable is set.");
}
log.debug("Android SDK: " + sdkFile.getAbsolutePath());
File instrumentation = getInstrumentationApk();
log.debug("Instrumentation APK: " + instrumentation);
File app = getApplicationApk();
log.debug("Application APK: " + app.getAbsolutePath());
if (!Strings.isNullOrEmpty(className)) {
log.debug("Class name: " + className);
if (!Strings.isNullOrEmpty(methodName)) {
log.debug("Method name: " + methodName);
}
}
String classpath = getSpoonClasspath();
log.debug("Classpath: " + classpath);
log.debug("Output directory: " + outputDirectory.getAbsolutePath());
log.debug("Spoon title: " + title);
log.debug("Debug: " + Boolean.toString(debug));
boolean success = new SpoonRunner.Builder() //
.setTitle(title)
.setApplicationApk(app)
.setInstrumentationApk(instrumentation)
.setOutputDirectory(outputDirectory)
.setAndroidSdk(sdkFile)
.setDebug(debug)
.setClasspath(classpath)
.setClassName(className)
.setMethodName(methodName)
.useAllAttachedDevices()
.build()
.run();
if (!success && failOnFailure) {
throw new MojoExecutionException("Spoon returned non-zero exit code.");
}
if (attachArtifact) {
File outputZip = new File(buildDirectory, DEFAULT_OUTPUT_DIRECTORY + ".zip");
ZipUtil.zip(outputZip, outputDirectory);
projectHelper.attachArtifact(project, ARTIFACT_TYPE, ARTIFACT_CLASSIFIER, outputZip);
}
}
| public void execute() throws MojoExecutionException {
Log log = getLog();
if (mavenTestSkip || mavenSkipTests || skip) {
log.debug("maven.test.skip = " + mavenTestSkip);
log.debug("skipTests = " + mavenSkipTests);
log.debug("skip = " + skip);
log.info("Skipping Spoon execution.");
return;
}
if (androidSdk == null) {
throw new MojoExecutionException(
"Could not find Android SDK. Ensure ANDROID_HOME environment variable is set.");
}
File sdkFile = new File(androidSdk);
if (!sdkFile.exists()) {
throw new MojoExecutionException(
String.format("Could not find Android SDK at: %s", androidSdk));
}
log.debug("Android SDK: " + sdkFile.getAbsolutePath());
File instrumentation = getInstrumentationApk();
log.debug("Instrumentation APK: " + instrumentation);
File app = getApplicationApk();
log.debug("Application APK: " + app.getAbsolutePath());
if (!Strings.isNullOrEmpty(className)) {
log.debug("Class name: " + className);
if (!Strings.isNullOrEmpty(methodName)) {
log.debug("Method name: " + methodName);
}
}
String classpath = getSpoonClasspath();
log.debug("Classpath: " + classpath);
log.debug("Output directory: " + outputDirectory.getAbsolutePath());
log.debug("Spoon title: " + title);
log.debug("Debug: " + Boolean.toString(debug));
boolean success = new SpoonRunner.Builder() //
.setTitle(title)
.setApplicationApk(app)
.setInstrumentationApk(instrumentation)
.setOutputDirectory(outputDirectory)
.setAndroidSdk(sdkFile)
.setDebug(debug)
.setClasspath(classpath)
.setClassName(className)
.setMethodName(methodName)
.useAllAttachedDevices()
.build()
.run();
if (!success && failOnFailure) {
throw new MojoExecutionException("Spoon returned non-zero exit code.");
}
if (attachArtifact) {
File outputZip = new File(buildDirectory, DEFAULT_OUTPUT_DIRECTORY + ".zip");
ZipUtil.zip(outputZip, outputDirectory);
projectHelper.attachArtifact(project, ARTIFACT_TYPE, ARTIFACT_CLASSIFIER, outputZip);
}
}
|
diff --git a/ace-webui-vaadin/src/main/java/org/apache/ace/webui/vaadin/VaadinClient.java b/ace-webui-vaadin/src/main/java/org/apache/ace/webui/vaadin/VaadinClient.java
index d409077e..00ee655f 100644
--- a/ace-webui-vaadin/src/main/java/org/apache/ace/webui/vaadin/VaadinClient.java
+++ b/ace-webui-vaadin/src/main/java/org/apache/ace/webui/vaadin/VaadinClient.java
@@ -1,1217 +1,1217 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ace.webui.vaadin;
import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;
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 java.util.Properties;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.ace.client.repository.ObjectRepository;
import org.apache.ace.client.repository.RepositoryAdmin;
import org.apache.ace.client.repository.RepositoryAdminLoginContext;
import org.apache.ace.client.repository.RepositoryObject;
import org.apache.ace.client.repository.SessionFactory;
import org.apache.ace.client.repository.helper.bundle.BundleHelper;
import org.apache.ace.client.repository.object.Artifact2FeatureAssociation;
import org.apache.ace.client.repository.object.ArtifactObject;
import org.apache.ace.client.repository.object.TargetObject;
import org.apache.ace.client.repository.object.Feature2DistributionAssociation;
import org.apache.ace.client.repository.object.FeatureObject;
import org.apache.ace.client.repository.object.Distribution2TargetAssociation;
import org.apache.ace.client.repository.object.DistributionObject;
import org.apache.ace.client.repository.repository.Artifact2FeatureAssociationRepository;
import org.apache.ace.client.repository.repository.ArtifactRepository;
import org.apache.ace.client.repository.repository.Feature2DistributionAssociationRepository;
import org.apache.ace.client.repository.repository.FeatureRepository;
import org.apache.ace.client.repository.repository.Distribution2TargetAssociationRepository;
import org.apache.ace.client.repository.repository.DistributionRepository;
import org.apache.ace.client.repository.stateful.StatefulTargetObject;
import org.apache.ace.client.repository.stateful.StatefulTargetRepository;
import org.apache.ace.test.utils.FileUtils;
import org.apache.ace.webui.NamedObject;
import org.apache.ace.webui.UIExtensionFactory;
import org.apache.ace.webui.domain.OBREntry;
import org.apache.ace.webui.vaadin.component.MainActionToolbar;
import org.apache.felix.dm.Component;
import org.apache.felix.dm.DependencyManager;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.event.EventConstants;
import org.osgi.service.event.EventHandler;
import org.osgi.service.log.LogService;
import org.osgi.service.useradmin.Authorization;
import org.osgi.service.useradmin.User;
import org.osgi.service.useradmin.UserAdmin;
import com.vaadin.data.Item;
import com.vaadin.event.ItemClickEvent;
import com.vaadin.event.ItemClickEvent.ItemClickListener;
import com.vaadin.event.Transferable;
import com.vaadin.event.dd.DragAndDropEvent;
import com.vaadin.event.dd.DropHandler;
import com.vaadin.event.dd.TargetDetails;
import com.vaadin.event.dd.acceptcriteria.AcceptCriterion;
import com.vaadin.event.dd.acceptcriteria.Or;
import com.vaadin.terminal.Sizeable;
import com.vaadin.ui.AbstractSelect.AbstractSelectTargetDetails;
import com.vaadin.ui.AbstractSelect.VerticalLocationIs;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.CheckBox;
import com.vaadin.ui.GridLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.ProgressIndicator;
import com.vaadin.ui.Table;
import com.vaadin.ui.Table.TableTransferable;
import com.vaadin.ui.Window;
/*
TODO:
- Add buttons to remove associations (think about how we can better visualize this)
- Add buttons to remove objects
- Handle ui updates better
- Add functionality for adding an artifact
- Allow live updates of the target column
- Create a special editor for dealing with new artifact types
- Enable drag and drop to create associations (done)
- Add drag and drop to the artifacts column (done)
- Add an editor that appears on double clicking on an item in a table (done)
- Add buttons to create new items in all of the tables (done for those that make sense)
*/
@SuppressWarnings("serial")
public class VaadinClient extends com.vaadin.Application {
public static final String OBJECT_NAME = "name";
public static final String OBJECT_DESCRIPTION = "description";
private static final long serialVersionUID = 1L;
private static long SESSION_ID = 12345;
private static String targetRepo = "target";
private static String shopRepo = "shop";
private static String deployRepo = "deployment";
private static String customerName = "apache";
private static String endpoint = "/repository";
private URL m_aceHost;
private URL m_obrUrl;
private volatile DependencyManager m_manager;
private volatile BundleContext m_context;
private volatile SessionFactory m_sessionFactory;
private volatile UserAdmin m_userAdmin;
private volatile ArtifactRepository m_artifactRepository;
private volatile FeatureRepository m_featureRepository;
private volatile DistributionRepository m_distributionRepository;
private volatile StatefulTargetRepository m_statefulTargetRepository;
private volatile Artifact2FeatureAssociationRepository m_artifact2GroupAssociationRepository;
private volatile Feature2DistributionAssociationRepository m_group2LicenseAssociationRepository;
private volatile Distribution2TargetAssociationRepository m_license2TargetAssociationRepository;
private volatile RepositoryAdmin m_admin;
private volatile LogService m_log;
private String m_sessionID;
private volatile List<DistributionObject> m_distributions;
private ObjectPanel m_artifactsPanel;
private ObjectPanel m_featuresPanel;
private ObjectPanel m_distributionsPanel;
private ObjectPanel m_targetsPanel;
private List<ArtifactObject> m_artifacts;
private List<FeatureObject> m_features;
private List<StatefulTargetObject> m_targets;
private final Associations m_associations = new Associations();
private GridLayout m_grid;
private boolean m_dynamicRelations = true;
private File m_sessionDir; // private folder for session info
private final AtomicBoolean m_dependenciesResolved = new AtomicBoolean(false);
private HorizontalLayout m_artifactToolbar;
private Button m_featureToolbar;
private Button m_distributionToolbar;
private Button m_targetToolbar;
private Window m_mainWindow;
// basic session ID generator
private static long generateSessionID() {
return SESSION_ID++;
}
public VaadinClient(URL aceHost, URL obrUrl) {
m_aceHost = aceHost;
m_obrUrl = obrUrl;
}
public void setupDependencies(Component component) {
m_sessionID = "" + generateSessionID();
File dir = m_context.getDataFile(m_sessionID);
dir.mkdir();
m_sessionDir = dir;
m_sessionFactory.createSession(m_sessionID);
addDependency(component, RepositoryAdmin.class);
addDependency(component, DistributionRepository.class);
addDependency(component, ArtifactRepository.class);
addDependency(component, FeatureRepository.class);
addDependency(component, Artifact2FeatureAssociationRepository.class);
addDependency(component, Feature2DistributionAssociationRepository.class);
addDependency(component, Distribution2TargetAssociationRepository.class);
addDependency(component, StatefulTargetRepository.class);
}
// @formatter:off
private void addDependency(Component component, Class service) {
component.add(m_manager.createServiceDependency()
.setService(service, "(" + SessionFactory.SERVICE_SID + "=" + m_sessionID + ")")
.setRequired(true)
.setInstanceBound(true));
}
// @formatter:on
public void start() {
System.out.println("Starting " + m_sessionID);
m_dependenciesResolved.set(true);
}
public void stop() {
m_dependenciesResolved.set(false);
}
public void destroyDependencies() {
m_sessionFactory.destroySession(m_sessionID);
FileUtils.removeDirectoryWithContent(m_sessionDir);
}
public void init() {
setTheme("ace");
if (!m_dependenciesResolved.get()) {
final Window message = new Window("Apache ACE");
setMainWindow(message);
message.getContent().setSizeFull();
Label richText =
new Label(
"<h1>Apache ACE User Interface</h1>"
+ "<p>Due to missing component dependencies on the server, probably due to misconfiguration, "
+ "the user interface cannot be properly started. Please contact your server administrator. "
+ "You can retry accessing the user interface by <a href=\"?restartApplication\">following this link</a>.</p>");
// TODO we might want to add some more details here as to what's
// missing
// on the other hand, the user probably can't fix that anyway
richText.setContentMode(Label.CONTENT_XHTML);
message.addComponent(richText);
return;
}
m_mainWindow = new Window("Apache ACE");
setMainWindow(m_mainWindow);
m_mainWindow.getContent().setSizeFull();
LoginWindow loginWindow = new LoginWindow(m_log, new LoginWindow.LoginFunction() {
public boolean login(String name, String password) {
return VaadinClient.this.login(name, password);
}
});
m_mainWindow.getWindow().addWindow(loginWindow);
loginWindow.center();
}
private void initGrid(User user) {
Authorization auth = m_userAdmin.getAuthorization(user);
int count = 0;
- for (String role : new String[] { "viewBundle", "viewGroup", "viewLicense", "viewTarget" }) {
+ for (String role : new String[] { "viewArtifact", "viewFeature", "viewDistribution", "viewTarget" }) {
if (auth.hasRole(role)) {
count++;
}
}
m_grid = new GridLayout(count, 4);
m_grid.setSpacing(true);
m_grid.setSizeFull();
m_grid.addComponent(createToolbar(), 0, 0, count - 1, 0);
m_artifactsPanel = createArtifactsPanel(m_mainWindow);
m_artifactToolbar = new HorizontalLayout();
m_artifactToolbar.addComponent(createAddArtifactButton());
CheckBox dynamicCheckBox = new CheckBox("Dynamic Links");
dynamicCheckBox.setImmediate(true);
dynamicCheckBox.setValue(Boolean.TRUE);
dynamicCheckBox.addListener(new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
m_dynamicRelations = event.getButton().booleanValue();
}
});
m_artifactToolbar.addComponent(dynamicCheckBox);
count = 0;
- if (auth.hasRole("viewBundle")) {
+ if (auth.hasRole("viewArtifact")) {
m_grid.addComponent(m_artifactsPanel, count, 2);
m_grid.addComponent(m_artifactToolbar, count, 1);
count++;
}
m_featuresPanel = createFeaturesPanel(m_mainWindow);
m_featureToolbar = createAddFeatureButton(m_mainWindow);
- if (auth.hasRole("viewGroup")) {
+ if (auth.hasRole("viewFeature")) {
m_grid.addComponent(m_featuresPanel, count, 2);
m_grid.addComponent(m_featureToolbar, count, 1);
count++;
}
m_distributionsPanel = createDistributionsPanel(m_mainWindow);
m_distributionToolbar = createAddDistributionButton(m_mainWindow);
- if (auth.hasRole("viewLicense")) {
+ if (auth.hasRole("viewDistribution")) {
m_grid.addComponent(m_distributionsPanel, count, 2);
m_grid.addComponent(m_distributionToolbar, count, 1);
count++;
}
m_targetsPanel = createTargetsPanel(m_mainWindow);
m_targetToolbar = createAddTargetButton(m_mainWindow);
if (auth.hasRole("viewTarget")) {
m_grid.addComponent(m_targetsPanel, count, 2);
m_grid.addComponent(m_targetToolbar, count, 1);
}
m_grid.setRowExpandRatio(2, 1.0f);
ProgressIndicator progress = new ProgressIndicator(0f);
progress.setPollingInterval(500);
m_grid.addComponent(progress, 0, 3);
m_artifactsPanel.addListener(m_associations.createSelectionListener(m_artifactsPanel, m_artifactRepository,
new Class[] {}, new Class[] { FeatureObject.class, DistributionObject.class, TargetObject.class },
new Table[] { m_featuresPanel, m_distributionsPanel, m_targetsPanel }));
m_featuresPanel.addListener(m_associations.createSelectionListener(m_featuresPanel, m_featureRepository,
new Class[] { ArtifactObject.class }, new Class[] { DistributionObject.class, TargetObject.class },
new Table[] { m_artifactsPanel, m_distributionsPanel, m_targetsPanel }));
m_distributionsPanel
.addListener(m_associations.createSelectionListener(m_distributionsPanel, m_distributionRepository,
new Class[] { FeatureObject.class, ArtifactObject.class }, new Class[] { TargetObject.class },
new Table[] { m_artifactsPanel, m_featuresPanel, m_targetsPanel }));
m_targetsPanel.addListener(m_associations.createSelectionListener(m_targetsPanel, m_statefulTargetRepository,
new Class[] { DistributionObject.class, FeatureObject.class, ArtifactObject.class }, new Class[] {},
new Table[] { m_artifactsPanel, m_featuresPanel, m_distributionsPanel }));
m_artifactsPanel.setDropHandler(new AssociationDropHandler((Table) null, m_featuresPanel) {
@Override
protected void associateFromLeft(String left, String right) {
}
@Override
protected void associateFromRight(String left, String right) {
ArtifactObject artifact = getArtifact(left);
// if you drop on a resource processor, and try to get it, you
// will get null
// because you cannot associate anything with a resource
// processor so we check
// for null here
if (artifact != null) {
if (m_dynamicRelations) {
Map<String, String> properties = new HashMap<String, String>();
properties.put(BundleHelper.KEY_ASSOCIATION_VERSIONSTATEMENT, "0.0.0");
m_artifact2GroupAssociationRepository.create(artifact, properties, getFeature(right), null);
}
else {
m_artifact2GroupAssociationRepository.create(artifact, getFeature(right));
}
}
}
});
m_featuresPanel.setDropHandler(new AssociationDropHandler(m_artifactsPanel, m_distributionsPanel) {
@Override
protected void associateFromLeft(String left, String right) {
ArtifactObject artifact = getArtifact(left);
// if you drop on a resource processor, and try to get it, you
// will get null
// because you cannot associate anything with a resource
// processor so we check
// for null here
if (artifact != null) {
if (m_dynamicRelations) {
Map<String, String> properties = new HashMap<String, String>();
properties.put(BundleHelper.KEY_ASSOCIATION_VERSIONSTATEMENT, "0.0.0");
m_artifact2GroupAssociationRepository.create(artifact, properties, getFeature(right), null);
}
else {
m_artifact2GroupAssociationRepository.create(artifact, getFeature(right));
}
}
}
@Override
protected void associateFromRight(String left, String right) {
m_group2LicenseAssociationRepository.create(getFeature(left), getDistribution(right));
}
});
m_distributionsPanel.setDropHandler(new AssociationDropHandler(m_featuresPanel, m_targetsPanel) {
@Override
protected void associateFromLeft(String left, String right) {
m_group2LicenseAssociationRepository.create(getFeature(left), getDistribution(right));
}
@Override
protected void associateFromRight(String left, String right) {
StatefulTargetObject target = getTarget(right);
if (!target.isRegistered()) {
target.register();
target.setAutoApprove(true);
}
m_license2TargetAssociationRepository.create(getDistribution(left), target.getTargetObject());
}
});
m_targetsPanel.setDropHandler(new AssociationDropHandler(m_distributionsPanel, (Table) null) {
@Override
protected void associateFromLeft(String left, String right) {
StatefulTargetObject target = getTarget(right);
if (!target.isRegistered()) {
target.register();
target.setAutoApprove(true);
}
m_license2TargetAssociationRepository.create(getDistribution(left), target.getTargetObject());
}
@Override
protected void associateFromRight(String left, String right) {
}
});
addListener(m_artifactsPanel, ArtifactObject.TOPIC_ALL);
addListener(m_featuresPanel, FeatureObject.TOPIC_ALL);
addListener(m_distributionsPanel, DistributionObject.TOPIC_ALL);
addListener(m_targetsPanel, StatefulTargetObject.TOPIC_ALL);
m_mainWindow.addComponent(m_grid);
}
boolean login(String username, String password) {
try {
User user = m_userAdmin.getUser("username", username);
if (user == null) {
return false;
}
if (!user.hasCredential("password", password)) {
return false;
}
RepositoryAdminLoginContext context = m_admin.createLoginContext(user);
// @formatter:off
context.addShopRepository(new URL(m_aceHost, endpoint), customerName, shopRepo, true)
.setObrBase(m_obrUrl)
.addTargetRepository(new URL(m_aceHost, endpoint), customerName, targetRepo, true)
.addDeploymentRepository(new URL(m_aceHost, endpoint), customerName, deployRepo, true);
// @formatter:on
m_admin.login(context);
initGrid(user);
m_admin.checkout();
return true;
}
catch (IOException e) {
e.printStackTrace();
return false;
}
}
private void addListener(final Object implementation, final String topic) {
m_manager.add(m_manager.createComponent().setInterface(EventHandler.class.getName(), new Properties() {
{
put(EventConstants.EVENT_TOPIC, topic);
put(EventConstants.EVENT_FILTER, "(" + SessionFactory.SERVICE_SID + "=" + m_sessionID + ")");
}
}).setImplementation(implementation));
}
private GridLayout createToolbar() {
MainActionToolbar mainActionToolbar = new MainActionToolbar() {
@Override
protected RepositoryAdmin getRepositoryAdmin() {
return m_admin;
}
@Override
protected void doAfterRevert() throws IOException {
updateTableData();
}
@Override
protected void doAfterRetrieve() throws IOException {
updateTableData();
}
@Override
protected void doAfterCommit() throws IOException {
// Nop
}
private void updateTableData() {
m_artifactsPanel.populate();
m_featuresPanel.populate();
m_distributionsPanel.populate();
m_targetsPanel.populate();
}
};
addListener(mainActionToolbar, RepositoryObject.PUBLIC_TOPIC_ROOT.concat(RepositoryObject.TOPIC_ALL_SUFFIX));
return mainActionToolbar;
}
private ObjectPanel createArtifactsPanel(Window main) {
return new ObjectPanel(m_associations, "Artifact", UIExtensionFactory.EXTENSION_POINT_VALUE_ARTIFACT, main,
true) {
@Override
protected RepositoryObject getFromId(String id) {
return getArtifact(id);
}
public void populate() {
removeAllItems();
for (ArtifactObject artifact : m_artifactRepository.get()) {
add(artifact);
}
}
public void handleEvent(org.osgi.service.event.Event event) {
ArtifactObject artifact = (ArtifactObject) event.getProperty(ArtifactObject.EVENT_ENTITY);
String topic = (String) event.getProperty(EventConstants.EVENT_TOPIC);
if (ArtifactObject.TOPIC_ADDED.equals(topic)) {
add(artifact);
}
if (ArtifactObject.TOPIC_REMOVED.equals(topic)) {
remove(artifact);
}
if (ArtifactObject.TOPIC_CHANGED.equals(topic)) {
change(artifact);
}
}
private void add(ArtifactObject artifact) {
String resourceProcessorPID = artifact.getAttribute(BundleHelper.KEY_RESOURCE_PROCESSOR_PID);
if (resourceProcessorPID != null) {
// if it's a resource processor we don't add it to our list,
// as resource processors don't
// show up there (you can query for them separately)
return;
}
Item item = addItem(artifact.getDefinition());
if (item != null) {
item.getItemProperty(OBJECT_NAME).setValue(artifact.getName());
item.getItemProperty(OBJECT_DESCRIPTION).setValue(artifact.getDescription());
HorizontalLayout buttons = new HorizontalLayout();
Button removeLinkButton = new RemoveLinkButton<ArtifactObject>(artifact, null, m_featuresPanel) {
@Override
protected void removeLinkFromLeft(ArtifactObject object, RepositoryObject other) {
}
@Override
protected void removeLinkFromRight(ArtifactObject object, RepositoryObject other) {
List<Artifact2FeatureAssociation> associations = object
.getAssociationsWith((FeatureObject) other);
for (Artifact2FeatureAssociation association : associations) {
m_artifact2GroupAssociationRepository.remove(association);
}
m_associations.removeAssociatedItem(object);
m_table.requestRepaint();
}
};
buttons.addComponent(removeLinkButton);
buttons.addComponent(new RemoveItemButton<ArtifactObject, ArtifactRepository>(artifact,
m_artifactRepository));
item.getItemProperty(ACTIONS).setValue(buttons);
}
}
private void change(ArtifactObject artifact) {
Item item = getItem(artifact.getDefinition());
if (item != null) {
item.getItemProperty(OBJECT_DESCRIPTION).setValue(artifact.getDescription());
}
}
private void remove(ArtifactObject artifact) {
removeItem(artifact.getDefinition());
}
};
}
private ObjectPanel createFeaturesPanel(Window main) {
return new ObjectPanel(m_associations, "Feature", UIExtensionFactory.EXTENSION_POINT_VALUE_FEATURE, main, true) {
@Override
protected RepositoryObject getFromId(String id) {
return getFeature(id);
}
public void populate() {
removeAllItems();
for (FeatureObject feature : m_featureRepository.get()) {
add(feature);
}
}
public void handleEvent(org.osgi.service.event.Event event) {
FeatureObject feature = (FeatureObject) event.getProperty(FeatureObject.EVENT_ENTITY);
String topic = (String) event.getProperty(EventConstants.EVENT_TOPIC);
if (FeatureObject.TOPIC_ADDED.equals(topic)) {
add(feature);
}
if (FeatureObject.TOPIC_REMOVED.equals(topic)) {
remove(feature);
}
if (FeatureObject.TOPIC_CHANGED.equals(topic)) {
change(feature);
}
}
private void add(FeatureObject feature) {
Item item = addItem(feature.getDefinition());
if (item != null) {
item.getItemProperty(OBJECT_NAME).setValue(feature.getName());
item.getItemProperty(OBJECT_DESCRIPTION).setValue(feature.getDescription());
Button removeLinkButton = new RemoveLinkButton<FeatureObject>(feature, m_artifactsPanel,
m_distributionsPanel) {
@Override
protected void removeLinkFromLeft(FeatureObject object, RepositoryObject other) {
List<Artifact2FeatureAssociation> associations = object
.getAssociationsWith((ArtifactObject) other);
for (Artifact2FeatureAssociation association : associations) {
m_artifact2GroupAssociationRepository.remove(association);
}
m_associations.removeAssociatedItem(object);
m_table.requestRepaint();
}
@Override
protected void removeLinkFromRight(FeatureObject object, RepositoryObject other) {
List<Feature2DistributionAssociation> associations = object
.getAssociationsWith((DistributionObject) other);
for (Feature2DistributionAssociation association : associations) {
m_group2LicenseAssociationRepository.remove(association);
}
m_associations.removeAssociatedItem(object);
m_table.requestRepaint();
}
};
HorizontalLayout buttons = new HorizontalLayout();
buttons.addComponent(removeLinkButton);
buttons.addComponent(new RemoveItemButton<FeatureObject, FeatureRepository>(feature,
m_featureRepository));
item.getItemProperty(ACTIONS).setValue(buttons);
}
}
private void change(FeatureObject go) {
Item item = getItem(go.getDefinition());
if (item != null) {
item.getItemProperty(OBJECT_DESCRIPTION).setValue(go.getDescription());
}
}
private void remove(FeatureObject go) {
removeItem(go.getDefinition());
}
};
}
public abstract class RemoveLinkButton<REPO_OBJECT extends RepositoryObject> extends Button {
// TODO generify?
public RemoveLinkButton(final REPO_OBJECT object, final ObjectPanel toLeft, final ObjectPanel toRight) {
super("-");
setStyleName("small");
addListener(new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
Set<?> selection = m_associations.getActiveSelection();
if (selection != null) {
if (m_associations.isActiveTable(toLeft)) {
for (Object item : selection) {
RepositoryObject selected = m_associations.lookupInActiveSelection(item);
removeLinkFromLeft(object, selected);
}
}
else if (m_associations.isActiveTable(toRight)) {
for (Object item : selection) {
RepositoryObject selected = m_associations.lookupInActiveSelection(item);
removeLinkFromRight(object, selected);
}
}
}
}
});
}
protected abstract void removeLinkFromLeft(REPO_OBJECT object, RepositoryObject other);
protected abstract void removeLinkFromRight(REPO_OBJECT object, RepositoryObject other);
}
public class RemoveItemButton<REPO_OBJECT extends RepositoryObject, REPO extends ObjectRepository> extends Button {
public RemoveItemButton(final REPO_OBJECT object, final REPO repository) {
super("x");
setStyleName("small");
addListener(new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
repository.remove(object);
}
});
}
}
private ObjectPanel createDistributionsPanel(Window main) {
return new ObjectPanel(m_associations, "Distribution", UIExtensionFactory.EXTENSION_POINT_VALUE_DISTRIBUTION,
main, true) {
@Override
protected RepositoryObject getFromId(String id) {
return getDistribution(id);
}
public void populate() {
removeAllItems();
for (DistributionObject distribution : m_distributionRepository.get()) {
add(distribution);
}
}
public void handleEvent(org.osgi.service.event.Event event) {
DistributionObject distribution = (DistributionObject) event.getProperty(DistributionObject.EVENT_ENTITY);
String topic = (String) event.getProperty(EventConstants.EVENT_TOPIC);
if (DistributionObject.TOPIC_ADDED.equals(topic)) {
add(distribution);
}
if (DistributionObject.TOPIC_REMOVED.equals(topic)) {
remove(distribution);
}
if (DistributionObject.TOPIC_CHANGED.equals(topic)) {
change(distribution);
}
}
private void add(DistributionObject distribution) {
Item item = addItem(distribution.getDefinition());
if (item != null) {
item.getItemProperty(OBJECT_NAME).setValue(distribution.getName());
item.getItemProperty(OBJECT_DESCRIPTION).setValue(distribution.getDescription());
Button removeLinkButton = new RemoveLinkButton<DistributionObject>(distribution, m_featuresPanel,
m_targetsPanel) {
@Override
protected void removeLinkFromLeft(DistributionObject object, RepositoryObject other) {
List<Feature2DistributionAssociation> associations = object
.getAssociationsWith((FeatureObject) other);
for (Feature2DistributionAssociation association : associations) {
m_group2LicenseAssociationRepository.remove(association);
}
m_associations.removeAssociatedItem(object);
m_table.requestRepaint();
}
@Override
protected void removeLinkFromRight(DistributionObject object, RepositoryObject other) {
List<Distribution2TargetAssociation> associations = object
.getAssociationsWith((TargetObject) other);
for (Distribution2TargetAssociation association : associations) {
m_license2TargetAssociationRepository.remove(association);
}
m_associations.removeAssociatedItem(object);
m_table.requestRepaint();
}
};
HorizontalLayout buttons = new HorizontalLayout();
buttons.addComponent(removeLinkButton);
buttons.addComponent(new RemoveItemButton<DistributionObject, DistributionRepository>(distribution,
m_distributionRepository));
item.getItemProperty(ACTIONS).setValue(buttons);
}
}
private void change(DistributionObject distribution) {
Item item = getItem(distribution.getDefinition());
if (item != null) {
item.getItemProperty(OBJECT_DESCRIPTION).setValue(distribution.getDescription());
}
}
private void remove(DistributionObject distribution) {
removeItem(distribution.getDefinition());
}
};
}
private ObjectPanel createTargetsPanel(Window main) {
return new ObjectPanel(m_associations, "Target", UIExtensionFactory.EXTENSION_POINT_VALUE_TARGET, main, true) {
@Override
protected RepositoryObject getFromId(String id) {
return getTarget(id);
}
public void populate() {
removeAllItems();
for (StatefulTargetObject statefulTarget : m_statefulTargetRepository.get()) {
add(statefulTarget);
}
}
public void handleEvent(org.osgi.service.event.Event event) {
StatefulTargetObject statefulTarget = (StatefulTargetObject) event
.getProperty(StatefulTargetObject.EVENT_ENTITY);
String topic = (String) event.getProperty(EventConstants.EVENT_TOPIC);
if (StatefulTargetObject.TOPIC_ADDED.equals(topic)) {
add(statefulTarget);
}
if (StatefulTargetObject.TOPIC_REMOVED.equals(topic)) {
remove(statefulTarget);
}
if (StatefulTargetObject.TOPIC_CHANGED.equals(topic)) {
change(statefulTarget);
}
}
private void add(StatefulTargetObject statefulTarget) {
Item item = addItem(statefulTarget.getDefinition());
if (item != null) {
item.getItemProperty(OBJECT_NAME).setValue(statefulTarget.getID());
item.getItemProperty(OBJECT_DESCRIPTION).setValue("");
Button removeLinkButton = new RemoveLinkButton<StatefulTargetObject>(statefulTarget,
m_distributionsPanel, null) {
@Override
protected void removeLinkFromLeft(StatefulTargetObject object, RepositoryObject other) {
List<Distribution2TargetAssociation> associations = object
.getAssociationsWith((DistributionObject) other);
for (Distribution2TargetAssociation association : associations) {
m_license2TargetAssociationRepository.remove(association);
}
m_associations.removeAssociatedItem(object);
m_table.requestRepaint();
}
@Override
protected void removeLinkFromRight(StatefulTargetObject object, RepositoryObject other) {
}
};
HorizontalLayout buttons = new HorizontalLayout();
buttons.addComponent(removeLinkButton);
item.getItemProperty(ACTIONS).setValue(buttons);
}
}
private void change(StatefulTargetObject statefulTarget) {
Item item = getItem(statefulTarget.getDefinition());
if (item != null) {
item.getItemProperty(OBJECT_DESCRIPTION).setValue("");
}
}
private void remove(StatefulTargetObject statefulTarget) {
removeItem(statefulTarget.getDefinition());
}
};
}
private abstract class AssociationDropHandler implements DropHandler {
private final Table m_left;
private final Table m_right;
public AssociationDropHandler(Table left, Table right) {
m_left = left;
m_right = right;
}
public void drop(DragAndDropEvent event) {
Transferable transferable = event.getTransferable();
TargetDetails targetDetails = event.getTargetDetails();
if (transferable instanceof TableTransferable) {
TableTransferable tt = (TableTransferable) transferable;
Object fromItemId = tt.getItemId();
// get the active selection, but only if we drag from the same
// table
Set<?> selection = m_associations.isActiveTable(tt.getSourceComponent()) ? m_associations
.getActiveSelection() : null;
if (targetDetails instanceof AbstractSelectTargetDetails) {
AbstractSelectTargetDetails ttd = (AbstractSelectTargetDetails) targetDetails;
Object toItemId = ttd.getItemIdOver();
if (tt.getSourceComponent().equals(m_left)) {
if (selection != null) {
for (Object item : selection) {
associateFromLeft((String) item, (String) toItemId);
}
}
else {
associateFromLeft((String) fromItemId, (String) toItemId);
}
}
else if (tt.getSourceComponent().equals(m_right)) {
if (selection != null) {
for (Object item : selection) {
associateFromRight((String) toItemId, (String) item);
}
}
else {
associateFromRight((String) toItemId, (String) fromItemId);
}
}
// TODO add to highlighting (it's probably easiest to
// recalculate the whole
// set of related and associated items here, see
// SelectionListener, or to manually
// figure out the changes in all cases
}
}
}
public AcceptCriterion getAcceptCriterion() {
return new Or(VerticalLocationIs.MIDDLE);
}
protected abstract void associateFromLeft(String left, String right);
protected abstract void associateFromRight(String left, String right);
}
/**
* Create a button to show a pop window for adding new features.
*
* @param main Main Window
* @return Button
*/
private Button createAddArtifactButton() {
Button button = new Button("Add artifact...");
button.addListener(new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
showAddArtifactDialog();
}
});
return button;
}
/***
* Create a button to show popup window for adding a new feature. On success
* this calls the createFeature() method.
*
* @param main Main Window
* @return Button
*/
private Button createAddFeatureButton(final Window main) {
Button button = new Button("Add Feature...");
button.addListener(new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
GenericAddWindow addFeatureWindow = new GenericAddWindow(main, "Add Feature");
addFeatureWindow.setOkListeren(new GenericAddWindow.AddFunction() {
public void create(String name, String description) {
createFeature(name, description);
}
});
addFeatureWindow.show();
}
});
return button;
}
/**
* Create a button to show a popup window for adding a new distribution. On
* success this calls the createDistribution() method.
*
* @param main Main Window
* @return Button
*/
private Button createAddDistributionButton(final Window main) {
Button button = new Button("Add Distribution...");
button.addListener(new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
GenericAddWindow addDistributionWindow = new GenericAddWindow(main, "Add Distribution");
addDistributionWindow.setOkListeren(new GenericAddWindow.AddFunction() {
public void create(String name, String description) {
createDistribution(name, description);
}
});
addDistributionWindow.show();
}
});
return button;
}
/**
* Create a button to show a popup window for adding a new target. On
* success this calls the createTarget() method
*
* @param main Main Window
* @return Button
*/
private Button createAddTargetButton(final Window main) {
Button button = new Button("Add target...");
button.addListener(new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
GenericAddWindow addTargetWindow = new GenericAddWindow(main, "Add Target");
addTargetWindow.setOkListeren(new GenericAddWindow.AddFunction() {
public void create(String name, String description) {
createTarget(name, description);
}
});
addTargetWindow.show();
}
});
return button;
}
/**
* Create a new feature (GroupObject) in the feature repository
*
* @param name Name of the new feature
* @param description Description of the new feature
*/
private void createFeature(String name, String description) {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(FeatureObject.KEY_NAME, name);
attributes.put(FeatureObject.KEY_DESCRIPTION, description);
Map<String, String> tags = new HashMap<String, String>();
m_featureRepository.create(attributes, tags);
}
/**
* Create a new Target (StatefulTargetObject) in the statefulTargetRepository
*
* @param name Name of the new Target
* @param description Description of the new Target
*
* TODO description is not persisted. Should we remote it?
*/
private void createTarget(String name, String description) {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(StatefulTargetObject.KEY_ID, name);
attributes.put(TargetObject.KEY_AUTO_APPROVE, "true");
Map<String, String> tags = new HashMap<String, String>();
m_statefulTargetRepository.preregister(attributes, tags);
}
/**
* Create a new Distribution (LicenseObject) in the distributionRepository
*
* @param name Name of the new Distribution (LicenseObject)
* @param description Description of the new Distribution
*/
private void createDistribution(String name, String description) {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(DistributionObject.KEY_NAME, name);
attributes.put(DistributionObject.KEY_DESCRIPTION, description);
Map<String, String> tags = new HashMap<String, String>();
m_distributionRepository.create(attributes, tags);
}
private ArtifactObject getArtifact(String definition) {
return m_artifactRepository.get(definition);
}
private FeatureObject getFeature(String name) {
return m_featureRepository.get(name);
}
private DistributionObject getDistribution(String name) {
return m_distributionRepository.get(name);
}
private StatefulTargetObject getTarget(String name) {
return m_statefulTargetRepository.get(name);
}
private void deleteFeature(String name) {
FeatureObject feature = getFeature(name);
if (feature != null) {
m_featureRepository.remove(feature);
// TODO cleanup links?
}
}
@Override
public void close() {
super.close();
// when the session times out
// TODO: clean up the ace client session?
}
private static class UIExtensionFactoryHolder implements Comparable<UIExtensionFactoryHolder> {
private final ServiceReference m_serviceRef;
private final WeakReference<UIExtensionFactory> m_extensionFactory;
public UIExtensionFactoryHolder(ServiceReference serviceRef, UIExtensionFactory extensionFactory) {
m_serviceRef = serviceRef;
m_extensionFactory = new WeakReference<UIExtensionFactory>(extensionFactory);
}
public int compareTo(UIExtensionFactoryHolder o) {
ServiceReference thatServiceRef = o.m_serviceRef;
ServiceReference thisServiceRef = m_serviceRef;
// Sort in reverse order so that the highest rankings come first...
return thatServiceRef.compareTo(thisServiceRef);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof UIExtensionFactoryHolder)) {
return false;
}
UIExtensionFactoryHolder other = (UIExtensionFactoryHolder) obj;
return m_serviceRef.equals(other.m_serviceRef);
}
/**
* @return the {@link UIExtensionFactory}, can be <code>null</code> if it has been GC'd before this method call.
*/
public UIExtensionFactory getUIExtensionFactory() {
return m_extensionFactory.get();
}
@Override
public int hashCode() {
return m_serviceRef.hashCode() ^ m_extensionFactory.hashCode();
}
}
public abstract class ObjectPanel extends Table implements EventHandler {
public static final String ACTIONS = "actions";
protected Table m_table = this;
protected Associations m_associations;
private List<UIExtensionFactoryHolder> m_extensionFactories = new ArrayList<UIExtensionFactoryHolder>();
private final String m_extensionPoint;
public ObjectPanel(Associations associations, final String name, String extensionPoint, final Window main,
boolean hasEdit) {
super(name + "s");
m_associations = associations;
m_extensionPoint = extensionPoint;
addContainerProperty(OBJECT_NAME, String.class, null);
addContainerProperty(OBJECT_DESCRIPTION, String.class, null);
addContainerProperty(ACTIONS, HorizontalLayout.class, null);
setSizeFull();
setCellStyleGenerator(m_associations.createCellStyleGenerator());
setSelectable(true);
setMultiSelect(true);
setImmediate(true);
setDragMode(TableDragMode.MULTIROW);
if (hasEdit) {
addListener(new ItemClickListener() {
public void itemClick(ItemClickEvent event) {
if (event.isDoubleClick()) {
String itemId = (String) event.getItemId();
RepositoryObject object = getFromId(itemId);
NamedObject namedObject = m_associations.getNamedObject(object);
showEditWindow(namedObject, main);
}
}
});
}
}
private void init(Component component) {
populate();
DependencyManager dm = component.getDependencyManager();
component.add(dm
.createServiceDependency()
.setInstanceBound(true)
.setService(UIExtensionFactory.class,
"(" + UIExtensionFactory.EXTENSION_POINT_KEY + "=" + m_extensionPoint + ")")
.setCallbacks("addExtension", "removeExtension"));
}
public void addExtension(ServiceReference ref, UIExtensionFactory factory) {
synchronized (m_extensionFactories) {
m_extensionFactories.add(new UIExtensionFactoryHolder(ref, factory));
}
populate();
}
public void removeExtension(ServiceReference ref, UIExtensionFactory factory) {
synchronized (m_extensionFactories) {
m_extensionFactories.remove(new UIExtensionFactoryHolder(ref, factory));
}
populate();
}
private void showEditWindow(NamedObject object, Window main) {
List<UIExtensionFactory> extensions = getExtensionFactories();
new EditWindow(object, main, extensions).show();
}
/**
* @return a list of current extension factories, properly ordered, never <code>null</code>.
*/
private List<UIExtensionFactory> getExtensionFactories() {
List<UIExtensionFactory> extensions;
synchronized (m_extensionFactories) {
// Sort the list of extension factories...
Collections.sort(m_extensionFactories);
// Walk through the holders and fetch the extension factories one by one...
extensions = new ArrayList<UIExtensionFactory>(m_extensionFactories.size());
for (UIExtensionFactoryHolder holder : m_extensionFactories) {
UIExtensionFactory extensionFactory = holder.getUIExtensionFactory();
// Make sure only to use non-GCd factories...
if (extensionFactory != null) {
extensions.add(extensionFactory);
}
}
}
return extensions;
}
public abstract void populate();
protected abstract RepositoryObject getFromId(String id);
}
private void showAddArtifactDialog() {
final AddArtifactWindow featureWindow = new AddArtifactWindow(m_sessionDir, m_obrUrl) {
@Override
protected ArtifactRepository getArtifactRepository() {
return m_artifactRepository;
}
@Override
protected LogService getLogger() {
return m_log;
}
};
if (featureWindow.getParent() != null) {
// window is already showing
getMainWindow().showNotification("Window is already open");
}
else {
// Open the subwindow by adding it to the parent
// window
getMainWindow().addWindow(featureWindow);
}
}
}
| false | true | private void initGrid(User user) {
Authorization auth = m_userAdmin.getAuthorization(user);
int count = 0;
for (String role : new String[] { "viewBundle", "viewGroup", "viewLicense", "viewTarget" }) {
if (auth.hasRole(role)) {
count++;
}
}
m_grid = new GridLayout(count, 4);
m_grid.setSpacing(true);
m_grid.setSizeFull();
m_grid.addComponent(createToolbar(), 0, 0, count - 1, 0);
m_artifactsPanel = createArtifactsPanel(m_mainWindow);
m_artifactToolbar = new HorizontalLayout();
m_artifactToolbar.addComponent(createAddArtifactButton());
CheckBox dynamicCheckBox = new CheckBox("Dynamic Links");
dynamicCheckBox.setImmediate(true);
dynamicCheckBox.setValue(Boolean.TRUE);
dynamicCheckBox.addListener(new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
m_dynamicRelations = event.getButton().booleanValue();
}
});
m_artifactToolbar.addComponent(dynamicCheckBox);
count = 0;
if (auth.hasRole("viewBundle")) {
m_grid.addComponent(m_artifactsPanel, count, 2);
m_grid.addComponent(m_artifactToolbar, count, 1);
count++;
}
m_featuresPanel = createFeaturesPanel(m_mainWindow);
m_featureToolbar = createAddFeatureButton(m_mainWindow);
if (auth.hasRole("viewGroup")) {
m_grid.addComponent(m_featuresPanel, count, 2);
m_grid.addComponent(m_featureToolbar, count, 1);
count++;
}
m_distributionsPanel = createDistributionsPanel(m_mainWindow);
m_distributionToolbar = createAddDistributionButton(m_mainWindow);
if (auth.hasRole("viewLicense")) {
m_grid.addComponent(m_distributionsPanel, count, 2);
m_grid.addComponent(m_distributionToolbar, count, 1);
count++;
}
m_targetsPanel = createTargetsPanel(m_mainWindow);
m_targetToolbar = createAddTargetButton(m_mainWindow);
if (auth.hasRole("viewTarget")) {
m_grid.addComponent(m_targetsPanel, count, 2);
m_grid.addComponent(m_targetToolbar, count, 1);
}
m_grid.setRowExpandRatio(2, 1.0f);
ProgressIndicator progress = new ProgressIndicator(0f);
progress.setPollingInterval(500);
m_grid.addComponent(progress, 0, 3);
m_artifactsPanel.addListener(m_associations.createSelectionListener(m_artifactsPanel, m_artifactRepository,
new Class[] {}, new Class[] { FeatureObject.class, DistributionObject.class, TargetObject.class },
new Table[] { m_featuresPanel, m_distributionsPanel, m_targetsPanel }));
m_featuresPanel.addListener(m_associations.createSelectionListener(m_featuresPanel, m_featureRepository,
new Class[] { ArtifactObject.class }, new Class[] { DistributionObject.class, TargetObject.class },
new Table[] { m_artifactsPanel, m_distributionsPanel, m_targetsPanel }));
m_distributionsPanel
.addListener(m_associations.createSelectionListener(m_distributionsPanel, m_distributionRepository,
new Class[] { FeatureObject.class, ArtifactObject.class }, new Class[] { TargetObject.class },
new Table[] { m_artifactsPanel, m_featuresPanel, m_targetsPanel }));
m_targetsPanel.addListener(m_associations.createSelectionListener(m_targetsPanel, m_statefulTargetRepository,
new Class[] { DistributionObject.class, FeatureObject.class, ArtifactObject.class }, new Class[] {},
new Table[] { m_artifactsPanel, m_featuresPanel, m_distributionsPanel }));
m_artifactsPanel.setDropHandler(new AssociationDropHandler((Table) null, m_featuresPanel) {
@Override
protected void associateFromLeft(String left, String right) {
}
@Override
protected void associateFromRight(String left, String right) {
ArtifactObject artifact = getArtifact(left);
// if you drop on a resource processor, and try to get it, you
// will get null
// because you cannot associate anything with a resource
// processor so we check
// for null here
if (artifact != null) {
if (m_dynamicRelations) {
Map<String, String> properties = new HashMap<String, String>();
properties.put(BundleHelper.KEY_ASSOCIATION_VERSIONSTATEMENT, "0.0.0");
m_artifact2GroupAssociationRepository.create(artifact, properties, getFeature(right), null);
}
else {
m_artifact2GroupAssociationRepository.create(artifact, getFeature(right));
}
}
}
});
m_featuresPanel.setDropHandler(new AssociationDropHandler(m_artifactsPanel, m_distributionsPanel) {
@Override
protected void associateFromLeft(String left, String right) {
ArtifactObject artifact = getArtifact(left);
// if you drop on a resource processor, and try to get it, you
// will get null
// because you cannot associate anything with a resource
// processor so we check
// for null here
if (artifact != null) {
if (m_dynamicRelations) {
Map<String, String> properties = new HashMap<String, String>();
properties.put(BundleHelper.KEY_ASSOCIATION_VERSIONSTATEMENT, "0.0.0");
m_artifact2GroupAssociationRepository.create(artifact, properties, getFeature(right), null);
}
else {
m_artifact2GroupAssociationRepository.create(artifact, getFeature(right));
}
}
}
@Override
protected void associateFromRight(String left, String right) {
m_group2LicenseAssociationRepository.create(getFeature(left), getDistribution(right));
}
});
m_distributionsPanel.setDropHandler(new AssociationDropHandler(m_featuresPanel, m_targetsPanel) {
@Override
protected void associateFromLeft(String left, String right) {
m_group2LicenseAssociationRepository.create(getFeature(left), getDistribution(right));
}
@Override
protected void associateFromRight(String left, String right) {
StatefulTargetObject target = getTarget(right);
if (!target.isRegistered()) {
target.register();
target.setAutoApprove(true);
}
m_license2TargetAssociationRepository.create(getDistribution(left), target.getTargetObject());
}
});
m_targetsPanel.setDropHandler(new AssociationDropHandler(m_distributionsPanel, (Table) null) {
@Override
protected void associateFromLeft(String left, String right) {
StatefulTargetObject target = getTarget(right);
if (!target.isRegistered()) {
target.register();
target.setAutoApprove(true);
}
m_license2TargetAssociationRepository.create(getDistribution(left), target.getTargetObject());
}
@Override
protected void associateFromRight(String left, String right) {
}
});
addListener(m_artifactsPanel, ArtifactObject.TOPIC_ALL);
addListener(m_featuresPanel, FeatureObject.TOPIC_ALL);
addListener(m_distributionsPanel, DistributionObject.TOPIC_ALL);
addListener(m_targetsPanel, StatefulTargetObject.TOPIC_ALL);
m_mainWindow.addComponent(m_grid);
}
| private void initGrid(User user) {
Authorization auth = m_userAdmin.getAuthorization(user);
int count = 0;
for (String role : new String[] { "viewArtifact", "viewFeature", "viewDistribution", "viewTarget" }) {
if (auth.hasRole(role)) {
count++;
}
}
m_grid = new GridLayout(count, 4);
m_grid.setSpacing(true);
m_grid.setSizeFull();
m_grid.addComponent(createToolbar(), 0, 0, count - 1, 0);
m_artifactsPanel = createArtifactsPanel(m_mainWindow);
m_artifactToolbar = new HorizontalLayout();
m_artifactToolbar.addComponent(createAddArtifactButton());
CheckBox dynamicCheckBox = new CheckBox("Dynamic Links");
dynamicCheckBox.setImmediate(true);
dynamicCheckBox.setValue(Boolean.TRUE);
dynamicCheckBox.addListener(new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
m_dynamicRelations = event.getButton().booleanValue();
}
});
m_artifactToolbar.addComponent(dynamicCheckBox);
count = 0;
if (auth.hasRole("viewArtifact")) {
m_grid.addComponent(m_artifactsPanel, count, 2);
m_grid.addComponent(m_artifactToolbar, count, 1);
count++;
}
m_featuresPanel = createFeaturesPanel(m_mainWindow);
m_featureToolbar = createAddFeatureButton(m_mainWindow);
if (auth.hasRole("viewFeature")) {
m_grid.addComponent(m_featuresPanel, count, 2);
m_grid.addComponent(m_featureToolbar, count, 1);
count++;
}
m_distributionsPanel = createDistributionsPanel(m_mainWindow);
m_distributionToolbar = createAddDistributionButton(m_mainWindow);
if (auth.hasRole("viewDistribution")) {
m_grid.addComponent(m_distributionsPanel, count, 2);
m_grid.addComponent(m_distributionToolbar, count, 1);
count++;
}
m_targetsPanel = createTargetsPanel(m_mainWindow);
m_targetToolbar = createAddTargetButton(m_mainWindow);
if (auth.hasRole("viewTarget")) {
m_grid.addComponent(m_targetsPanel, count, 2);
m_grid.addComponent(m_targetToolbar, count, 1);
}
m_grid.setRowExpandRatio(2, 1.0f);
ProgressIndicator progress = new ProgressIndicator(0f);
progress.setPollingInterval(500);
m_grid.addComponent(progress, 0, 3);
m_artifactsPanel.addListener(m_associations.createSelectionListener(m_artifactsPanel, m_artifactRepository,
new Class[] {}, new Class[] { FeatureObject.class, DistributionObject.class, TargetObject.class },
new Table[] { m_featuresPanel, m_distributionsPanel, m_targetsPanel }));
m_featuresPanel.addListener(m_associations.createSelectionListener(m_featuresPanel, m_featureRepository,
new Class[] { ArtifactObject.class }, new Class[] { DistributionObject.class, TargetObject.class },
new Table[] { m_artifactsPanel, m_distributionsPanel, m_targetsPanel }));
m_distributionsPanel
.addListener(m_associations.createSelectionListener(m_distributionsPanel, m_distributionRepository,
new Class[] { FeatureObject.class, ArtifactObject.class }, new Class[] { TargetObject.class },
new Table[] { m_artifactsPanel, m_featuresPanel, m_targetsPanel }));
m_targetsPanel.addListener(m_associations.createSelectionListener(m_targetsPanel, m_statefulTargetRepository,
new Class[] { DistributionObject.class, FeatureObject.class, ArtifactObject.class }, new Class[] {},
new Table[] { m_artifactsPanel, m_featuresPanel, m_distributionsPanel }));
m_artifactsPanel.setDropHandler(new AssociationDropHandler((Table) null, m_featuresPanel) {
@Override
protected void associateFromLeft(String left, String right) {
}
@Override
protected void associateFromRight(String left, String right) {
ArtifactObject artifact = getArtifact(left);
// if you drop on a resource processor, and try to get it, you
// will get null
// because you cannot associate anything with a resource
// processor so we check
// for null here
if (artifact != null) {
if (m_dynamicRelations) {
Map<String, String> properties = new HashMap<String, String>();
properties.put(BundleHelper.KEY_ASSOCIATION_VERSIONSTATEMENT, "0.0.0");
m_artifact2GroupAssociationRepository.create(artifact, properties, getFeature(right), null);
}
else {
m_artifact2GroupAssociationRepository.create(artifact, getFeature(right));
}
}
}
});
m_featuresPanel.setDropHandler(new AssociationDropHandler(m_artifactsPanel, m_distributionsPanel) {
@Override
protected void associateFromLeft(String left, String right) {
ArtifactObject artifact = getArtifact(left);
// if you drop on a resource processor, and try to get it, you
// will get null
// because you cannot associate anything with a resource
// processor so we check
// for null here
if (artifact != null) {
if (m_dynamicRelations) {
Map<String, String> properties = new HashMap<String, String>();
properties.put(BundleHelper.KEY_ASSOCIATION_VERSIONSTATEMENT, "0.0.0");
m_artifact2GroupAssociationRepository.create(artifact, properties, getFeature(right), null);
}
else {
m_artifact2GroupAssociationRepository.create(artifact, getFeature(right));
}
}
}
@Override
protected void associateFromRight(String left, String right) {
m_group2LicenseAssociationRepository.create(getFeature(left), getDistribution(right));
}
});
m_distributionsPanel.setDropHandler(new AssociationDropHandler(m_featuresPanel, m_targetsPanel) {
@Override
protected void associateFromLeft(String left, String right) {
m_group2LicenseAssociationRepository.create(getFeature(left), getDistribution(right));
}
@Override
protected void associateFromRight(String left, String right) {
StatefulTargetObject target = getTarget(right);
if (!target.isRegistered()) {
target.register();
target.setAutoApprove(true);
}
m_license2TargetAssociationRepository.create(getDistribution(left), target.getTargetObject());
}
});
m_targetsPanel.setDropHandler(new AssociationDropHandler(m_distributionsPanel, (Table) null) {
@Override
protected void associateFromLeft(String left, String right) {
StatefulTargetObject target = getTarget(right);
if (!target.isRegistered()) {
target.register();
target.setAutoApprove(true);
}
m_license2TargetAssociationRepository.create(getDistribution(left), target.getTargetObject());
}
@Override
protected void associateFromRight(String left, String right) {
}
});
addListener(m_artifactsPanel, ArtifactObject.TOPIC_ALL);
addListener(m_featuresPanel, FeatureObject.TOPIC_ALL);
addListener(m_distributionsPanel, DistributionObject.TOPIC_ALL);
addListener(m_targetsPanel, StatefulTargetObject.TOPIC_ALL);
m_mainWindow.addComponent(m_grid);
}
|
diff --git a/src/main/java/de/deepamehta/plugins/workspaces/WorkspacesPlugin.java b/src/main/java/de/deepamehta/plugins/workspaces/WorkspacesPlugin.java
index 7c078ce..ff608ac 100644
--- a/src/main/java/de/deepamehta/plugins/workspaces/WorkspacesPlugin.java
+++ b/src/main/java/de/deepamehta/plugins/workspaces/WorkspacesPlugin.java
@@ -1,47 +1,47 @@
package de.deepamehta.plugins.workspaces;
import de.deepamehta.core.model.Topic;
import de.deepamehta.core.plugin.DeepaMehtaPlugin;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
public class WorkspacesPlugin extends DeepaMehtaPlugin {
private Logger logger = Logger.getLogger(getClass().getName());
// Note: we must use the postCreateHook to create the relation because at pre_create the document has no ID yet.
@Override
public void postCreateHook(Topic topic, Map<String, String> clientContext) {
// Note 1: we do not relate search results to a workspace. Otherwise the search result would appear
- // as relation when displaying the workspace. That's because an "Auxiliray" relation is not be
+ // as relation when displaying the workspace. That's because a "SEARCH_RESULT" relation is not be
// created if there is another relation already.
// Note 2: we do not relate workspaces to a workspace. This would be contra-intuitive.
- if (!topic.typeId.equals("Serch Result") && !topic.typeId.equals("Workspace")) {
+ if (!topic.typeId.equals("Search Result") && !topic.typeId.equals("Workspace")) {
String workspaceId = clientContext.get("workspace_id");
if (workspaceId != null) {
dms.createRelation("RELATION", topic.id, Long.parseLong(workspaceId), null);
} else {
- logger.warning("Topic " + topic + " can't be related to a workspace (current workspace is unknown)");
+ logger.warning(topic + " can't be related to a workspace (current workspace is unknown)");
}
} else {
- logger.info("### " + topic + " is not assigned to a workspace");
+ logger.info("### " + topic + " is deliberately not assigned to any workspace");
}
}
// ---
@Override
public String getClientPlugin() {
return "dm3_workspaces.js";
}
@Override
public int requiredDBModelVersion() {
return 1;
}
}
| false | true | public void postCreateHook(Topic topic, Map<String, String> clientContext) {
// Note 1: we do not relate search results to a workspace. Otherwise the search result would appear
// as relation when displaying the workspace. That's because an "Auxiliray" relation is not be
// created if there is another relation already.
// Note 2: we do not relate workspaces to a workspace. This would be contra-intuitive.
if (!topic.typeId.equals("Serch Result") && !topic.typeId.equals("Workspace")) {
String workspaceId = clientContext.get("workspace_id");
if (workspaceId != null) {
dms.createRelation("RELATION", topic.id, Long.parseLong(workspaceId), null);
} else {
logger.warning("Topic " + topic + " can't be related to a workspace (current workspace is unknown)");
}
} else {
logger.info("### " + topic + " is not assigned to a workspace");
}
}
| public void postCreateHook(Topic topic, Map<String, String> clientContext) {
// Note 1: we do not relate search results to a workspace. Otherwise the search result would appear
// as relation when displaying the workspace. That's because a "SEARCH_RESULT" relation is not be
// created if there is another relation already.
// Note 2: we do not relate workspaces to a workspace. This would be contra-intuitive.
if (!topic.typeId.equals("Search Result") && !topic.typeId.equals("Workspace")) {
String workspaceId = clientContext.get("workspace_id");
if (workspaceId != null) {
dms.createRelation("RELATION", topic.id, Long.parseLong(workspaceId), null);
} else {
logger.warning(topic + " can't be related to a workspace (current workspace is unknown)");
}
} else {
logger.info("### " + topic + " is deliberately not assigned to any workspace");
}
}
|
diff --git a/src/com/android/browser/NfcHandler.java b/src/com/android/browser/NfcHandler.java
index bdfe25ef..bbac640a 100644
--- a/src/com/android/browser/NfcHandler.java
+++ b/src/com/android/browser/NfcHandler.java
@@ -1,73 +1,72 @@
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.browser;
import android.app.Activity;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
/** This class implements sharing the URL of the currently
* shown browser page over NFC. Sharing is only active
* when the activity is in the foreground and resumed.
* Incognito tabs will not be shared over NFC.
*/
public class NfcHandler implements NfcAdapter.NdefPushCallback {
private NfcAdapter mNfcAdapter;
private Activity mActivity;
private Controller mController;
public NfcHandler(Activity browser, Controller controller) {
mActivity = browser;
mController = controller;
mNfcAdapter = NfcAdapter.getDefaultAdapter(mActivity);
}
void onPause() {
if (mNfcAdapter != null) {
mNfcAdapter.disableForegroundNdefPush(mActivity);
}
}
void onResume() {
if (mNfcAdapter != null) {
mNfcAdapter.enableForegroundNdefPush(mActivity, this);
}
}
@Override
public NdefMessage createMessage() {
Tab currentTab = mController.getCurrentTab();
if (currentTab == null) {
return null;
}
String currentUrl = currentTab.getUrl();
if (currentUrl != null && currentTab.getWebView() != null &&
!currentTab.getWebView().isPrivateBrowsingEnabled()) {
- NdefRecord record = new NdefRecord(NdefRecord.TNF_ABSOLUTE_URI,
- NdefRecord.RTD_URI, new byte[] {}, currentUrl.getBytes());
+ NdefRecord record = NdefRecord.createUri(currentUrl);
NdefMessage msg = new NdefMessage(new NdefRecord[] { record });
return msg;
} else {
return null;
}
}
@Override
public void onMessagePushed() {
}
}
| true | true | public NdefMessage createMessage() {
Tab currentTab = mController.getCurrentTab();
if (currentTab == null) {
return null;
}
String currentUrl = currentTab.getUrl();
if (currentUrl != null && currentTab.getWebView() != null &&
!currentTab.getWebView().isPrivateBrowsingEnabled()) {
NdefRecord record = new NdefRecord(NdefRecord.TNF_ABSOLUTE_URI,
NdefRecord.RTD_URI, new byte[] {}, currentUrl.getBytes());
NdefMessage msg = new NdefMessage(new NdefRecord[] { record });
return msg;
} else {
return null;
}
}
| public NdefMessage createMessage() {
Tab currentTab = mController.getCurrentTab();
if (currentTab == null) {
return null;
}
String currentUrl = currentTab.getUrl();
if (currentUrl != null && currentTab.getWebView() != null &&
!currentTab.getWebView().isPrivateBrowsingEnabled()) {
NdefRecord record = NdefRecord.createUri(currentUrl);
NdefMessage msg = new NdefMessage(new NdefRecord[] { record });
return msg;
} else {
return null;
}
}
|
diff --git a/extensions/gdx-tools/src/com/badlogic/gdx/tools/particleeditor/ScaledNumericPanel.java b/extensions/gdx-tools/src/com/badlogic/gdx/tools/particleeditor/ScaledNumericPanel.java
index 186f4a8b8..b96098021 100644
--- a/extensions/gdx-tools/src/com/badlogic/gdx/tools/particleeditor/ScaledNumericPanel.java
+++ b/extensions/gdx-tools/src/com/badlogic/gdx/tools/particleeditor/ScaledNumericPanel.java
@@ -1,223 +1,223 @@
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.tools.particleeditor;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import com.badlogic.gdx.graphics.g2d.ParticleEmitter.ScaledNumericValue;
class ScaledNumericPanel extends EditorPanel {
final ScaledNumericValue value;
Slider lowMinSlider, lowMaxSlider;
Slider highMinSlider, highMaxSlider;
JCheckBox relativeCheckBox;
Chart chart;
JPanel formPanel;
JButton expandButton;
JButton lowRangeButton;
JButton highRangeButton;
public ScaledNumericPanel (final ScaledNumericValue value, String chartTitle, String name, String description) {
super(value, name, description);
this.value = value;
initializeComponents(chartTitle);
lowMinSlider.setValue(value.getLowMin());
lowMaxSlider.setValue(value.getLowMax());
highMinSlider.setValue(value.getHighMin());
highMaxSlider.setValue(value.getHighMax());
chart.setValues(value.getTimeline(), value.getScaling());
relativeCheckBox.setSelected(value.isRelative());
lowMinSlider.addChangeListener(new ChangeListener() {
public void stateChanged (ChangeEvent event) {
value.setLowMin((Float)lowMinSlider.getValue());
if (!lowMaxSlider.isVisible()) value.setLowMax((Float)lowMinSlider.getValue());
}
});
lowMaxSlider.addChangeListener(new ChangeListener() {
public void stateChanged (ChangeEvent event) {
value.setLowMax((Float)lowMaxSlider.getValue());
}
});
highMinSlider.addChangeListener(new ChangeListener() {
public void stateChanged (ChangeEvent event) {
value.setHighMin((Float)highMinSlider.getValue());
if (!highMaxSlider.isVisible()) value.setHighMax((Float)highMinSlider.getValue());
}
});
highMaxSlider.addChangeListener(new ChangeListener() {
public void stateChanged (ChangeEvent event) {
value.setHighMax((Float)highMaxSlider.getValue());
}
});
relativeCheckBox.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent event) {
value.setRelative(relativeCheckBox.isSelected());
}
});
lowRangeButton.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent event) {
boolean visible = !lowMaxSlider.isVisible();
lowMaxSlider.setVisible(visible);
lowRangeButton.setText(visible ? "<" : ">");
GridBagLayout layout = (GridBagLayout)formPanel.getLayout();
GridBagConstraints constraints = layout.getConstraints(lowRangeButton);
constraints.gridx = visible ? 5 : 4;
layout.setConstraints(lowRangeButton, constraints);
Slider slider = visible ? lowMaxSlider : lowMinSlider;
value.setLowMax((Float)slider.getValue());
}
});
highRangeButton.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent event) {
boolean visible = !highMaxSlider.isVisible();
highMaxSlider.setVisible(visible);
highRangeButton.setText(visible ? "<" : ">");
GridBagLayout layout = (GridBagLayout)formPanel.getLayout();
GridBagConstraints constraints = layout.getConstraints(highRangeButton);
constraints.gridx = visible ? 5 : 4;
layout.setConstraints(highRangeButton, constraints);
Slider slider = visible ? highMaxSlider : highMinSlider;
value.setHighMax((Float)slider.getValue());
}
});
expandButton.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent event) {
chart.setExpanded(!chart.isExpanded());
boolean expanded = chart.isExpanded();
GridBagLayout layout = (GridBagLayout)getContentPanel().getLayout();
GridBagConstraints chartConstraints = layout.getConstraints(chart);
GridBagConstraints expandButtonConstraints = layout.getConstraints(expandButton);
if (expanded) {
chart.setPreferredSize(new Dimension(150, 200));
- expandButton.setText("�");
+ expandButton.setText("-");
chartConstraints.weightx = 1;
expandButtonConstraints.weightx = 0;
} else {
chart.setPreferredSize(new Dimension(150, 30));
expandButton.setText("+");
chartConstraints.weightx = 0;
expandButtonConstraints.weightx = 1;
}
layout.setConstraints(chart, chartConstraints);
layout.setConstraints(expandButton, expandButtonConstraints);
relativeCheckBox.setVisible(!expanded);
formPanel.setVisible(!expanded);
chart.revalidate();
}
});
if (value.getLowMin() == value.getLowMax()) lowRangeButton.doClick(0);
if (value.getHighMin() == value.getHighMax()) highRangeButton.doClick(0);
}
public JPanel getFormPanel () {
return formPanel;
}
private void initializeComponents (String chartTitle) {
JPanel contentPanel = getContentPanel();
{
formPanel = new JPanel(new GridBagLayout());
contentPanel.add(formPanel, new GridBagConstraints(5, 5, 1, 1, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE,
new Insets(0, 0, 0, 6), 0, 0));
{
JLabel label = new JLabel("High:");
formPanel.add(label, new GridBagConstraints(2, 1, 1, 1, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE,
new Insets(0, 0, 0, 6), 0, 0));
}
{
highMinSlider = new Slider(0, -99999, 99999, 1f, -400, 400);
formPanel.add(highMinSlider, new GridBagConstraints(3, 1, 1, 1, 0, 0, GridBagConstraints.WEST,
GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
}
{
highMaxSlider = new Slider(0, -99999, 99999, 1f, -400, 400);
formPanel.add(highMaxSlider, new GridBagConstraints(4, 1, 1, 1, 0, 0, GridBagConstraints.WEST,
GridBagConstraints.NONE, new Insets(0, 6, 0, 0), 0, 0));
}
{
highRangeButton = new JButton("<");
highRangeButton.setBorder(BorderFactory.createEmptyBorder(6, 6, 6, 6));
formPanel.add(highRangeButton, new GridBagConstraints(5, 1, 1, 1, 0.0, 0, GridBagConstraints.WEST,
GridBagConstraints.NONE, new Insets(0, 1, 0, 0), 0, 0));
}
{
JLabel label = new JLabel("Low:");
formPanel.add(label, new GridBagConstraints(2, 2, 1, 1, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE,
new Insets(0, 0, 0, 6), 0, 0));
}
{
lowMinSlider = new Slider(0, -99999, 99999, 1f, -400, 400);
formPanel.add(lowMinSlider, new GridBagConstraints(3, 2, 1, 1, 0, 0, GridBagConstraints.WEST,
GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
}
{
lowMaxSlider = new Slider(0, -99999, 99999, 1f, -400, 400);
formPanel.add(lowMaxSlider, new GridBagConstraints(4, 2, 1, 1, 0, 0, GridBagConstraints.WEST,
GridBagConstraints.NONE, new Insets(0, 6, 0, 0), 0, 0));
}
{
lowRangeButton = new JButton("<");
lowRangeButton.setBorder(BorderFactory.createEmptyBorder(6, 6, 6, 6));
formPanel.add(lowRangeButton, new GridBagConstraints(5, 2, 1, 1, 0.0, 0, GridBagConstraints.WEST,
GridBagConstraints.NONE, new Insets(0, 1, 0, 0), 0, 0));
}
}
{
chart = new Chart(chartTitle) {
public void pointsChanged () {
value.setTimeline(chart.getValuesX());
value.setScaling(chart.getValuesY());
}
};
contentPanel.add(chart, new GridBagConstraints(6, 5, 1, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 0, 0), 0, 0));
chart.setPreferredSize(new Dimension(150, 30));
}
{
expandButton = new JButton("+");
contentPanel.add(expandButton, new GridBagConstraints(7, 5, 1, 1, 1, 0, GridBagConstraints.SOUTHWEST,
GridBagConstraints.NONE, new Insets(0, 5, 0, 0), 0, 0));
expandButton.setBorder(BorderFactory.createEmptyBorder(4, 8, 4, 8));
}
{
relativeCheckBox = new JCheckBox("Relative");
contentPanel.add(relativeCheckBox, new GridBagConstraints(7, 5, 1, 1, 0, 0, GridBagConstraints.NORTHWEST,
GridBagConstraints.NONE, new Insets(0, 6, 0, 0), 0, 0));
}
}
}
| true | true | public ScaledNumericPanel (final ScaledNumericValue value, String chartTitle, String name, String description) {
super(value, name, description);
this.value = value;
initializeComponents(chartTitle);
lowMinSlider.setValue(value.getLowMin());
lowMaxSlider.setValue(value.getLowMax());
highMinSlider.setValue(value.getHighMin());
highMaxSlider.setValue(value.getHighMax());
chart.setValues(value.getTimeline(), value.getScaling());
relativeCheckBox.setSelected(value.isRelative());
lowMinSlider.addChangeListener(new ChangeListener() {
public void stateChanged (ChangeEvent event) {
value.setLowMin((Float)lowMinSlider.getValue());
if (!lowMaxSlider.isVisible()) value.setLowMax((Float)lowMinSlider.getValue());
}
});
lowMaxSlider.addChangeListener(new ChangeListener() {
public void stateChanged (ChangeEvent event) {
value.setLowMax((Float)lowMaxSlider.getValue());
}
});
highMinSlider.addChangeListener(new ChangeListener() {
public void stateChanged (ChangeEvent event) {
value.setHighMin((Float)highMinSlider.getValue());
if (!highMaxSlider.isVisible()) value.setHighMax((Float)highMinSlider.getValue());
}
});
highMaxSlider.addChangeListener(new ChangeListener() {
public void stateChanged (ChangeEvent event) {
value.setHighMax((Float)highMaxSlider.getValue());
}
});
relativeCheckBox.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent event) {
value.setRelative(relativeCheckBox.isSelected());
}
});
lowRangeButton.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent event) {
boolean visible = !lowMaxSlider.isVisible();
lowMaxSlider.setVisible(visible);
lowRangeButton.setText(visible ? "<" : ">");
GridBagLayout layout = (GridBagLayout)formPanel.getLayout();
GridBagConstraints constraints = layout.getConstraints(lowRangeButton);
constraints.gridx = visible ? 5 : 4;
layout.setConstraints(lowRangeButton, constraints);
Slider slider = visible ? lowMaxSlider : lowMinSlider;
value.setLowMax((Float)slider.getValue());
}
});
highRangeButton.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent event) {
boolean visible = !highMaxSlider.isVisible();
highMaxSlider.setVisible(visible);
highRangeButton.setText(visible ? "<" : ">");
GridBagLayout layout = (GridBagLayout)formPanel.getLayout();
GridBagConstraints constraints = layout.getConstraints(highRangeButton);
constraints.gridx = visible ? 5 : 4;
layout.setConstraints(highRangeButton, constraints);
Slider slider = visible ? highMaxSlider : highMinSlider;
value.setHighMax((Float)slider.getValue());
}
});
expandButton.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent event) {
chart.setExpanded(!chart.isExpanded());
boolean expanded = chart.isExpanded();
GridBagLayout layout = (GridBagLayout)getContentPanel().getLayout();
GridBagConstraints chartConstraints = layout.getConstraints(chart);
GridBagConstraints expandButtonConstraints = layout.getConstraints(expandButton);
if (expanded) {
chart.setPreferredSize(new Dimension(150, 200));
expandButton.setText("�");
chartConstraints.weightx = 1;
expandButtonConstraints.weightx = 0;
} else {
chart.setPreferredSize(new Dimension(150, 30));
expandButton.setText("+");
chartConstraints.weightx = 0;
expandButtonConstraints.weightx = 1;
}
layout.setConstraints(chart, chartConstraints);
layout.setConstraints(expandButton, expandButtonConstraints);
relativeCheckBox.setVisible(!expanded);
formPanel.setVisible(!expanded);
chart.revalidate();
}
});
if (value.getLowMin() == value.getLowMax()) lowRangeButton.doClick(0);
if (value.getHighMin() == value.getHighMax()) highRangeButton.doClick(0);
}
| public ScaledNumericPanel (final ScaledNumericValue value, String chartTitle, String name, String description) {
super(value, name, description);
this.value = value;
initializeComponents(chartTitle);
lowMinSlider.setValue(value.getLowMin());
lowMaxSlider.setValue(value.getLowMax());
highMinSlider.setValue(value.getHighMin());
highMaxSlider.setValue(value.getHighMax());
chart.setValues(value.getTimeline(), value.getScaling());
relativeCheckBox.setSelected(value.isRelative());
lowMinSlider.addChangeListener(new ChangeListener() {
public void stateChanged (ChangeEvent event) {
value.setLowMin((Float)lowMinSlider.getValue());
if (!lowMaxSlider.isVisible()) value.setLowMax((Float)lowMinSlider.getValue());
}
});
lowMaxSlider.addChangeListener(new ChangeListener() {
public void stateChanged (ChangeEvent event) {
value.setLowMax((Float)lowMaxSlider.getValue());
}
});
highMinSlider.addChangeListener(new ChangeListener() {
public void stateChanged (ChangeEvent event) {
value.setHighMin((Float)highMinSlider.getValue());
if (!highMaxSlider.isVisible()) value.setHighMax((Float)highMinSlider.getValue());
}
});
highMaxSlider.addChangeListener(new ChangeListener() {
public void stateChanged (ChangeEvent event) {
value.setHighMax((Float)highMaxSlider.getValue());
}
});
relativeCheckBox.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent event) {
value.setRelative(relativeCheckBox.isSelected());
}
});
lowRangeButton.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent event) {
boolean visible = !lowMaxSlider.isVisible();
lowMaxSlider.setVisible(visible);
lowRangeButton.setText(visible ? "<" : ">");
GridBagLayout layout = (GridBagLayout)formPanel.getLayout();
GridBagConstraints constraints = layout.getConstraints(lowRangeButton);
constraints.gridx = visible ? 5 : 4;
layout.setConstraints(lowRangeButton, constraints);
Slider slider = visible ? lowMaxSlider : lowMinSlider;
value.setLowMax((Float)slider.getValue());
}
});
highRangeButton.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent event) {
boolean visible = !highMaxSlider.isVisible();
highMaxSlider.setVisible(visible);
highRangeButton.setText(visible ? "<" : ">");
GridBagLayout layout = (GridBagLayout)formPanel.getLayout();
GridBagConstraints constraints = layout.getConstraints(highRangeButton);
constraints.gridx = visible ? 5 : 4;
layout.setConstraints(highRangeButton, constraints);
Slider slider = visible ? highMaxSlider : highMinSlider;
value.setHighMax((Float)slider.getValue());
}
});
expandButton.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent event) {
chart.setExpanded(!chart.isExpanded());
boolean expanded = chart.isExpanded();
GridBagLayout layout = (GridBagLayout)getContentPanel().getLayout();
GridBagConstraints chartConstraints = layout.getConstraints(chart);
GridBagConstraints expandButtonConstraints = layout.getConstraints(expandButton);
if (expanded) {
chart.setPreferredSize(new Dimension(150, 200));
expandButton.setText("-");
chartConstraints.weightx = 1;
expandButtonConstraints.weightx = 0;
} else {
chart.setPreferredSize(new Dimension(150, 30));
expandButton.setText("+");
chartConstraints.weightx = 0;
expandButtonConstraints.weightx = 1;
}
layout.setConstraints(chart, chartConstraints);
layout.setConstraints(expandButton, expandButtonConstraints);
relativeCheckBox.setVisible(!expanded);
formPanel.setVisible(!expanded);
chart.revalidate();
}
});
if (value.getLowMin() == value.getLowMax()) lowRangeButton.doClick(0);
if (value.getHighMin() == value.getHighMax()) highRangeButton.doClick(0);
}
|
diff --git a/src/test/org/apache/nutch/fetcher/TestFetcher.java b/src/test/org/apache/nutch/fetcher/TestFetcher.java
index e2ca0edb..4c1b2e4e 100644
--- a/src/test/org/apache/nutch/fetcher/TestFetcher.java
+++ b/src/test/org/apache/nutch/fetcher/TestFetcher.java
@@ -1,137 +1,138 @@
/*
* Copyright 2006 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.nutch.fetcher;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.UTF8;
import org.apache.nutch.crawl.CrawlDBTestUtil;
import org.apache.nutch.crawl.Generator;
import org.apache.nutch.crawl.Injector;
import org.apache.nutch.protocol.Content;
import org.mortbay.jetty.Server;
import junit.framework.TestCase;
/**
* Basic fetcher test
* 1. generate seedlist
* 2. inject
* 3. generate
* 3. fetch
* 4. Verify contents
* @author nutch-dev <nutch-dev at lucene.apache.org>
*
*/
public class TestFetcher extends TestCase {
final static Path testdir=new Path("build/test/fetch-test");
Configuration conf;
FileSystem fs;
Path crawldbPath;
Path segmentsPath;
Path urlPath;
Server server;
protected void setUp() throws Exception{
conf=CrawlDBTestUtil.createConfiguration();
fs=FileSystem.get(conf);
fs.delete(testdir);
urlPath=new Path(testdir,"urls");
crawldbPath=new Path(testdir,"crawldb");
segmentsPath=new Path(testdir,"segments");
server=CrawlDBTestUtil.getServer(conf.getInt("content.server.port",50000), "build/test/data/fetch-test-site");
server.start();
}
protected void tearDown() throws InterruptedException, IOException{
server.stop();
fs.delete(testdir);
}
public void testFetch() throws IOException {
//generate seedlist
ArrayList<String> urls=new ArrayList<String>();
addUrl(urls,"index.html");
addUrl(urls,"pagea.html");
addUrl(urls,"pageb.html");
addUrl(urls,"dup_of_pagea.html");
CrawlDBTestUtil.generateSeedList(fs, urlPath, urls);
//inject
Injector injector=new Injector(conf);
injector.inject(crawldbPath, urlPath);
//generate
Generator g=new Generator(conf);
Path generatedSegment=g.generate(crawldbPath, segmentsPath, 1, Long.MAX_VALUE, Long.MAX_VALUE);
long time=System.currentTimeMillis();
//fetch
+ conf.setBoolean("fetcher.parse", true);
Fetcher fetcher=new Fetcher(conf);
- fetcher.fetch(generatedSegment, 1, true);
+ fetcher.fetch(generatedSegment, 1);
time=System.currentTimeMillis()-time;
//verify politeness, time taken should be more than (num_of_pages +1)*delay
int minimumTime=(int) ((urls.size()+1)*1000*conf.getFloat("fetcher.server.delay",5));
assertTrue(time > minimumTime);
//verify results
Path content=new Path(new Path(generatedSegment, Content.DIR_NAME),"part-00000/data");
SequenceFile.Reader reader=new SequenceFile.Reader(fs, content, conf);
ArrayList<String> handledurls=new ArrayList<String>();
READ:
do {
UTF8 key=new UTF8();
Content value=new Content();
if(!reader.next(key, value)) break READ;
String contentString=new String(value.getContent());
if(contentString.indexOf("Nutch fetcher test page")!=-1) {
handledurls.add(key.toString());
}
} while(true);
reader.close();
Collections.sort(urls);
Collections.sort(handledurls);
//verify that enough pages were handled
assertEquals(urls.size(), handledurls.size());
//verify that correct pages were handled
assertTrue(handledurls.containsAll(urls));
assertTrue(urls.containsAll(handledurls));
}
private void addUrl(ArrayList<String> urls, String page) {
urls.add("http://127.0.0.1:" + server.getListeners()[0].getPort() + "/" + page);
}
}
| false | true | public void testFetch() throws IOException {
//generate seedlist
ArrayList<String> urls=new ArrayList<String>();
addUrl(urls,"index.html");
addUrl(urls,"pagea.html");
addUrl(urls,"pageb.html");
addUrl(urls,"dup_of_pagea.html");
CrawlDBTestUtil.generateSeedList(fs, urlPath, urls);
//inject
Injector injector=new Injector(conf);
injector.inject(crawldbPath, urlPath);
//generate
Generator g=new Generator(conf);
Path generatedSegment=g.generate(crawldbPath, segmentsPath, 1, Long.MAX_VALUE, Long.MAX_VALUE);
long time=System.currentTimeMillis();
//fetch
Fetcher fetcher=new Fetcher(conf);
fetcher.fetch(generatedSegment, 1, true);
time=System.currentTimeMillis()-time;
//verify politeness, time taken should be more than (num_of_pages +1)*delay
int minimumTime=(int) ((urls.size()+1)*1000*conf.getFloat("fetcher.server.delay",5));
assertTrue(time > minimumTime);
//verify results
Path content=new Path(new Path(generatedSegment, Content.DIR_NAME),"part-00000/data");
SequenceFile.Reader reader=new SequenceFile.Reader(fs, content, conf);
ArrayList<String> handledurls=new ArrayList<String>();
READ:
do {
UTF8 key=new UTF8();
Content value=new Content();
if(!reader.next(key, value)) break READ;
String contentString=new String(value.getContent());
if(contentString.indexOf("Nutch fetcher test page")!=-1) {
handledurls.add(key.toString());
}
} while(true);
reader.close();
Collections.sort(urls);
Collections.sort(handledurls);
//verify that enough pages were handled
assertEquals(urls.size(), handledurls.size());
//verify that correct pages were handled
assertTrue(handledurls.containsAll(urls));
assertTrue(urls.containsAll(handledurls));
}
| public void testFetch() throws IOException {
//generate seedlist
ArrayList<String> urls=new ArrayList<String>();
addUrl(urls,"index.html");
addUrl(urls,"pagea.html");
addUrl(urls,"pageb.html");
addUrl(urls,"dup_of_pagea.html");
CrawlDBTestUtil.generateSeedList(fs, urlPath, urls);
//inject
Injector injector=new Injector(conf);
injector.inject(crawldbPath, urlPath);
//generate
Generator g=new Generator(conf);
Path generatedSegment=g.generate(crawldbPath, segmentsPath, 1, Long.MAX_VALUE, Long.MAX_VALUE);
long time=System.currentTimeMillis();
//fetch
conf.setBoolean("fetcher.parse", true);
Fetcher fetcher=new Fetcher(conf);
fetcher.fetch(generatedSegment, 1);
time=System.currentTimeMillis()-time;
//verify politeness, time taken should be more than (num_of_pages +1)*delay
int minimumTime=(int) ((urls.size()+1)*1000*conf.getFloat("fetcher.server.delay",5));
assertTrue(time > minimumTime);
//verify results
Path content=new Path(new Path(generatedSegment, Content.DIR_NAME),"part-00000/data");
SequenceFile.Reader reader=new SequenceFile.Reader(fs, content, conf);
ArrayList<String> handledurls=new ArrayList<String>();
READ:
do {
UTF8 key=new UTF8();
Content value=new Content();
if(!reader.next(key, value)) break READ;
String contentString=new String(value.getContent());
if(contentString.indexOf("Nutch fetcher test page")!=-1) {
handledurls.add(key.toString());
}
} while(true);
reader.close();
Collections.sort(urls);
Collections.sort(handledurls);
//verify that enough pages were handled
assertEquals(urls.size(), handledurls.size());
//verify that correct pages were handled
assertTrue(handledurls.containsAll(urls));
assertTrue(urls.containsAll(handledurls));
}
|
diff --git a/src/mist/src/com/trendmicro/mist/cmd/MistSource.java b/src/mist/src/com/trendmicro/mist/cmd/MistSource.java
index d48a13d..dc3cebe 100644
--- a/src/mist/src/com/trendmicro/mist/cmd/MistSource.java
+++ b/src/mist/src/com/trendmicro/mist/cmd/MistSource.java
@@ -1,379 +1,382 @@
package com.trendmicro.mist.cmd;
import java.io.IOException;
import java.io.File;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Date;
import com.trendmicro.mist.Daemon;
import com.trendmicro.mist.MistException;
import com.trendmicro.mist.ThreadInvoker;
import com.trendmicro.mist.util.Exchange;
import com.trendmicro.mist.util.Packet;
import gnu.getopt.Getopt;
import gnu.getopt.LongOpt;
import com.trendmicro.mist.proto.GateTalk;
import com.trendmicro.spn.common.util.Utils;
public class MistSource extends ThreadInvoker {
class Reaper implements Runnable {
private long timeToLive = -1;
private long timeBirth = -1;
////////////////////////////////////////////////////////////////////////////////
public void setLive(long duration) {
timeToLive = duration;
}
public void setBirth(long time) {
timeBirth = time;
}
public void run() {
while(true) {
long now = new Date().getTime();
if(timeBirth != -1 && now - timeBirth > timeToLive)
System.exit(RetVal.TIMEOUT.ordinal());
Utils.justSleep(50);
}
}
}
enum CmdType {
NONE, LIST, MOUNT, UNMOUNT, ATTACH, DETACH,
}
enum RetVal {
OK,
MOUNT_FAILED,
UNMOUNT_FAILED,
ATTACH_FAILED,
DETACH_FAILED,
TIMEOUT,
}
private Exchange exchange = new Exchange();
private int targetSessionId = -1;
private CmdType currCmd = CmdType.NONE;
private Thread threadMain;
private static MistSource myApp;
private boolean daemonDetach = false;
private boolean usePerf = false;
private final int PERF_COUNT = 1000;
private int limitCount = -1;
private int timeout = -1;
private Reaper reaper = new Reaper();
private void addShutdownHook() {
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
myApp.shutdown();
}
});
}
private GateTalk.Request makeDetachRequest() {
GateTalk.Request.Builder req_builder = GateTalk.Request.newBuilder();
req_builder.setType(GateTalk.Request.Type.CLIENT_DETACH);
req_builder.setRole(GateTalk.Request.Role.SOURCE);
req_builder.setArgument(String.valueOf(targetSessionId));
return req_builder.build();
}
private void flushRequest(GateTalk.Request request) {
GateTalk.Command.Builder cmd_builder = GateTalk.Command.newBuilder();
cmd_builder.addRequest(request);
try {
MistSession.sendRequest(cmd_builder.build());
}
catch(MistException e) {
myErr.println(e.getMessage());
}
}
private void shutdown() {
if(new File(Daemon.namePidfile).exists()) {
if(currCmd == CmdType.ATTACH && (exitCode == RetVal.OK.ordinal() && !daemonDetach))
flushRequest(makeDetachRequest());
try {
if(threadMain != null)
threadMain.join(1000);
}
catch(InterruptedException e) {
}
}
}
private void printUsage() {
myOut.printf("Usage:%n");
myOut.printf(" mist-source SESSION_ID [options [arguments...] ]... %n%n");
myOut.printf("Options: %n");
myOut.printf(" --mount=EXCHANGE, -m EXCHANGE %n");
myOut.printf(" --unmount=EXCHANGE, -u EXCHANGE %n");
myOut.printf(" mount/unmount exchange to/from SESSION_ID %n");
myOut.printf(" where EXCHANGE={queue,topic}:EXCHANGENAME %n");
myOut.printf(" --queue, -q %n");
myOut.printf(" use queue (default) %n");
myOut.printf(" --topic, -t %n");
myOut.printf(" use topic %n%n");
myOut.printf(" --attach, -a %n");
myOut.printf(" attach to SESSION_ID and start transmission %n%n");
myOut.printf(" --perf, -p %n");
myOut.printf(" display performance number %n%n");
myOut.printf(" --detach, -d %n");
myOut.printf(" detach from SESSION_ID %n%n");
//myOut.printf(" --limit-count=NUMBER %n");
//myOut.printf(" limit the number of messages to receive %n%n");
//myOut.printf(" --timeout=MILLISECOND %n");
//myOut.printf(" limit the waiting time to receive messages %n%n");
myOut.printf(" --help, -h %n");
myOut.printf(" display help messages %n%n");
}
private void processAttach() {
if(timeout != -1) {
reaper.setLive((long) timeout);
new Thread(reaper).start();
}
GateTalk.Request.Builder req_builder = GateTalk.Request.newBuilder();
req_builder.setType(GateTalk.Request.Type.CLIENT_ATTACH);
req_builder.setArgument(String.valueOf(targetSessionId));
req_builder.setRole(GateTalk.Request.Role.SOURCE);
GateTalk.Command.Builder cmd_builder = GateTalk.Command.newBuilder();
cmd_builder.addRequest(req_builder.build());
int commPort;
try {
GateTalk.Response res = MistSession.sendRequest(cmd_builder.build());
if(!res.getSuccess()) {
myErr.printf("failed: %s %n", res.getException());
exitCode = RetVal.ATTACH_FAILED.ordinal();
return;
}
commPort = Integer.parseInt(res.getContext());
}
catch(MistException e) {
myErr.println(e.getMessage());
exitCode = RetVal.ATTACH_FAILED.ordinal();
return;
}
Socket sock = null;
BufferedInputStream socketIn = null;
BufferedOutputStream socketOut = null;
BufferedOutputStream out = null;
try {
sock = new Socket();
sock.setReuseAddress(true);
sock.setTcpNoDelay(true);
sock.connect(new InetSocketAddress("127.0.0.1", commPort));
socketIn = new BufferedInputStream(sock.getInputStream());
socketOut = new BufferedOutputStream(sock.getOutputStream());
out = new BufferedOutputStream(myOut);
Packet pack = new Packet();
int rdcnt = -1;
int cnt = 0;
long prev_time = System.nanoTime();
do {
reaper.setBirth(new Date().getTime());
if((rdcnt = pack.read(socketIn)) > 0) {
pack.write(out);
+ if(myOut.checkError()) {
+ throw new IOException("MistSource: Pipe is broken!");
+ }
cnt++;
pack.setPayload(GateTalk.Response.newBuilder().setSuccess(true).build().toByteArray());
pack.write(socketOut);
if(usePerf && cnt % PERF_COUNT == 0) {
long curr_time = System.nanoTime();
float duration = (float) (curr_time - prev_time) / (1000000000);
myErr.printf("mist-source: %.2f mps%n", (float) PERF_COUNT / duration);
prev_time = curr_time;
}
if(limitCount != -1 && cnt >= limitCount) {
flushRequest(makeDetachRequest());
break;
}
}
} while(rdcnt != -1);
daemonDetach = true;
}
catch(IOException e) {
myErr.println(e.getMessage());
}
finally {
try {
socketIn.close();
socketOut.close();
out.close();
sock.close();
}
catch(IOException e) {
myErr.println(e.getMessage());
}
}
}
private void processMount() {
GateTalk.Client client = MistSession.makeClientRequest(targetSessionId, exchange, true, true);
GateTalk.Command.Builder cmd_builder = GateTalk.Command.newBuilder();
cmd_builder.addClient(client);
try {
GateTalk.Response res = MistSession.sendRequest(cmd_builder.build());
if(res.getSuccess())
myOut.printf("%s%n", res.getContext());
else {
myErr.printf("failed: %s%n", res.getException());
exitCode = RetVal.MOUNT_FAILED.ordinal();
}
}
catch(MistException e) {
myErr.println(e.getMessage());
}
}
private void processUnmount() {
GateTalk.Client client = MistSession.makeClientRequest(targetSessionId, exchange, true, false);
GateTalk.Command.Builder cmd_builder = GateTalk.Command.newBuilder();
cmd_builder.addClient(client);
try {
GateTalk.Response res = MistSession.sendRequest(cmd_builder.build());
if(res.getSuccess())
myOut.printf("%s%n", res.getContext());
else {
myErr.printf("failed: %s%n", res.getException());
exitCode = RetVal.UNMOUNT_FAILED.ordinal();
}
}
catch(MistException e) {
myErr.println(e.getMessage());
}
}
private void processDetach() {
GateTalk.Command.Builder cmd_builder = GateTalk.Command.newBuilder();
cmd_builder.addRequest(makeDetachRequest());
try {
GateTalk.Response res = MistSession.sendRequest(cmd_builder.build());
if(res.getSuccess())
myOut.printf("%s%n", res.getContext());
else {
myErr.printf("failed: %s%n", res.getException());
exitCode = RetVal.DETACH_FAILED.ordinal();
}
}
catch(MistException e) {
myErr.println(e.getMessage());
}
}
////////////////////////////////////////////////////////////////////////////////
public MistSource() {
super("mist-source");
if(!Daemon.isRunning()) {
System.err.println("Daemon not running");
System.exit(-1);
}
exitCode = RetVal.OK.ordinal();
}
public int run(String argv[]) {
exchange.reset();
LongOpt[] longopts = new LongOpt[] {
new LongOpt("help", LongOpt.NO_ARGUMENT, null, 'h'),
new LongOpt("mount", LongOpt.REQUIRED_ARGUMENT, null, 'm'),
new LongOpt("unmount", LongOpt.REQUIRED_ARGUMENT, null, 'u'),
new LongOpt("attach", LongOpt.NO_ARGUMENT, null, 'a'),
new LongOpt("detach", LongOpt.NO_ARGUMENT, null, 'd'),
new LongOpt("topic", LongOpt.NO_ARGUMENT, null, 't'),
new LongOpt("queue", LongOpt.NO_ARGUMENT, null, 'q'),
new LongOpt("perf", LongOpt.NO_ARGUMENT, null, 'p'),
new LongOpt("limit-count", LongOpt.REQUIRED_ARGUMENT, null, 'c'),
new LongOpt("timeout", LongOpt.REQUIRED_ARGUMENT, null, 'i'),
};
try {
Getopt g = new Getopt("mist-source", argv, "hm:u:adtqp", longopts);
int c;
while((c = g.getopt()) != -1) {
switch(c) {
case 'm':
currCmd = CmdType.MOUNT;
exchange.set(g.getOptarg());
break;
case 'u':
currCmd = CmdType.UNMOUNT;
exchange.set(g.getOptarg());
break;
case 'a':
currCmd = CmdType.ATTACH;
break;
case 'd':
currCmd = CmdType.DETACH;
break;
case 'q':
exchange.setQueue();
break;
case 't':
exchange.setTopic();
break;
case 'p':
usePerf = true;
break;
case 'c':
limitCount = Integer.parseInt(g.getOptarg());
break;
case 'i':
timeout = Integer.parseInt(g.getOptarg());
break;
}
}
if(g.getOptind() < argv.length)
targetSessionId = Integer.parseInt(argv[g.getOptind()]);
else {
myErr.printf("no SESSION_ID specified %n");
currCmd = CmdType.NONE;
}
if(currCmd == CmdType.MOUNT)
processMount();
else if(currCmd == CmdType.UNMOUNT)
processUnmount();
else if(currCmd == CmdType.ATTACH)
processAttach();
else if(currCmd == CmdType.DETACH)
processDetach();
else if(currCmd == CmdType.NONE)
printUsage();
}
catch(NumberFormatException e) {
myErr.printf("%s, invalid number format %n", e.getMessage());
}
catch(Exception e) {
myErr.println(e.getMessage());
}
return exitCode;
}
public static void main(String argv[]) {
myApp = new MistSource();
myApp.threadMain = Thread.currentThread();
myApp.addShutdownHook();
myApp.run(argv);
myApp.threadMain = null;
System.exit(myApp.exitCode);
}
}
| true | true | private void processAttach() {
if(timeout != -1) {
reaper.setLive((long) timeout);
new Thread(reaper).start();
}
GateTalk.Request.Builder req_builder = GateTalk.Request.newBuilder();
req_builder.setType(GateTalk.Request.Type.CLIENT_ATTACH);
req_builder.setArgument(String.valueOf(targetSessionId));
req_builder.setRole(GateTalk.Request.Role.SOURCE);
GateTalk.Command.Builder cmd_builder = GateTalk.Command.newBuilder();
cmd_builder.addRequest(req_builder.build());
int commPort;
try {
GateTalk.Response res = MistSession.sendRequest(cmd_builder.build());
if(!res.getSuccess()) {
myErr.printf("failed: %s %n", res.getException());
exitCode = RetVal.ATTACH_FAILED.ordinal();
return;
}
commPort = Integer.parseInt(res.getContext());
}
catch(MistException e) {
myErr.println(e.getMessage());
exitCode = RetVal.ATTACH_FAILED.ordinal();
return;
}
Socket sock = null;
BufferedInputStream socketIn = null;
BufferedOutputStream socketOut = null;
BufferedOutputStream out = null;
try {
sock = new Socket();
sock.setReuseAddress(true);
sock.setTcpNoDelay(true);
sock.connect(new InetSocketAddress("127.0.0.1", commPort));
socketIn = new BufferedInputStream(sock.getInputStream());
socketOut = new BufferedOutputStream(sock.getOutputStream());
out = new BufferedOutputStream(myOut);
Packet pack = new Packet();
int rdcnt = -1;
int cnt = 0;
long prev_time = System.nanoTime();
do {
reaper.setBirth(new Date().getTime());
if((rdcnt = pack.read(socketIn)) > 0) {
pack.write(out);
cnt++;
pack.setPayload(GateTalk.Response.newBuilder().setSuccess(true).build().toByteArray());
pack.write(socketOut);
if(usePerf && cnt % PERF_COUNT == 0) {
long curr_time = System.nanoTime();
float duration = (float) (curr_time - prev_time) / (1000000000);
myErr.printf("mist-source: %.2f mps%n", (float) PERF_COUNT / duration);
prev_time = curr_time;
}
if(limitCount != -1 && cnt >= limitCount) {
flushRequest(makeDetachRequest());
break;
}
}
} while(rdcnt != -1);
daemonDetach = true;
}
catch(IOException e) {
myErr.println(e.getMessage());
}
finally {
try {
socketIn.close();
socketOut.close();
out.close();
sock.close();
}
catch(IOException e) {
myErr.println(e.getMessage());
}
}
}
| private void processAttach() {
if(timeout != -1) {
reaper.setLive((long) timeout);
new Thread(reaper).start();
}
GateTalk.Request.Builder req_builder = GateTalk.Request.newBuilder();
req_builder.setType(GateTalk.Request.Type.CLIENT_ATTACH);
req_builder.setArgument(String.valueOf(targetSessionId));
req_builder.setRole(GateTalk.Request.Role.SOURCE);
GateTalk.Command.Builder cmd_builder = GateTalk.Command.newBuilder();
cmd_builder.addRequest(req_builder.build());
int commPort;
try {
GateTalk.Response res = MistSession.sendRequest(cmd_builder.build());
if(!res.getSuccess()) {
myErr.printf("failed: %s %n", res.getException());
exitCode = RetVal.ATTACH_FAILED.ordinal();
return;
}
commPort = Integer.parseInt(res.getContext());
}
catch(MistException e) {
myErr.println(e.getMessage());
exitCode = RetVal.ATTACH_FAILED.ordinal();
return;
}
Socket sock = null;
BufferedInputStream socketIn = null;
BufferedOutputStream socketOut = null;
BufferedOutputStream out = null;
try {
sock = new Socket();
sock.setReuseAddress(true);
sock.setTcpNoDelay(true);
sock.connect(new InetSocketAddress("127.0.0.1", commPort));
socketIn = new BufferedInputStream(sock.getInputStream());
socketOut = new BufferedOutputStream(sock.getOutputStream());
out = new BufferedOutputStream(myOut);
Packet pack = new Packet();
int rdcnt = -1;
int cnt = 0;
long prev_time = System.nanoTime();
do {
reaper.setBirth(new Date().getTime());
if((rdcnt = pack.read(socketIn)) > 0) {
pack.write(out);
if(myOut.checkError()) {
throw new IOException("MistSource: Pipe is broken!");
}
cnt++;
pack.setPayload(GateTalk.Response.newBuilder().setSuccess(true).build().toByteArray());
pack.write(socketOut);
if(usePerf && cnt % PERF_COUNT == 0) {
long curr_time = System.nanoTime();
float duration = (float) (curr_time - prev_time) / (1000000000);
myErr.printf("mist-source: %.2f mps%n", (float) PERF_COUNT / duration);
prev_time = curr_time;
}
if(limitCount != -1 && cnt >= limitCount) {
flushRequest(makeDetachRequest());
break;
}
}
} while(rdcnt != -1);
daemonDetach = true;
}
catch(IOException e) {
myErr.println(e.getMessage());
}
finally {
try {
socketIn.close();
socketOut.close();
out.close();
sock.close();
}
catch(IOException e) {
myErr.println(e.getMessage());
}
}
}
|
diff --git a/core/src/main/java/org/apache/mina/filter/codec/demux/DemuxingProtocolCodecFactory.java b/core/src/main/java/org/apache/mina/filter/codec/demux/DemuxingProtocolCodecFactory.java
index 60bd5f4b..e5cf6a24 100644
--- a/core/src/main/java/org/apache/mina/filter/codec/demux/DemuxingProtocolCodecFactory.java
+++ b/core/src/main/java/org/apache/mina/filter/codec/demux/DemuxingProtocolCodecFactory.java
@@ -1,402 +1,404 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.mina.filter.codec.demux;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.apache.mina.common.ByteBuffer;
import org.apache.mina.common.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolCodecFactory;
import org.apache.mina.filter.codec.ProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderException;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.apache.mina.filter.codec.ProtocolEncoder;
import org.apache.mina.filter.codec.ProtocolEncoderException;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;
import org.apache.mina.util.IdentityHashSet;
/**
* A composite {@link ProtocolCodecFactory} that consists of multiple
* {@link MessageEncoder}s and {@link MessageDecoder}s.
* {@link ProtocolEncoder} and {@link ProtocolDecoder} this factory
* returns demultiplex incoming messages and buffers to
* appropriate {@link MessageEncoder}s and {@link MessageDecoder}s.
*
* <h2>Disposing resources acquired by {@link MessageEncoder} and {@link MessageDecoder}</h2>
* <p>
* Make your {@link MessageEncoder} and {@link MessageDecoder} to put all
* resources that need to be released as a session attribute. {@link #disposeCodecResources(IoSession)}
* method will be invoked when a session is closed. Override {@link #disposeCodecResources(IoSession)}
* to release the resources you've put as an attribute.
* <p>
* We didn't provide any <tt>dispose</tt> method for {@link MessageEncoder} and {@link MessageDecoder}
* because they can give you a big performance penalty in case you have a lot of
* message types to handle.
*
* @author The Apache MINA Project ([email protected])
* @version $Rev$, $Date$
*
* @see MessageEncoder
* @see MessageDecoder
*/
public class DemuxingProtocolCodecFactory implements ProtocolCodecFactory {
private MessageDecoderFactory[] decoderFactories = new MessageDecoderFactory[0];
private MessageEncoderFactory<?>[] encoderFactories = new MessageEncoderFactory[0];
private static final Class<?>[] EMPTY_PARAMS = new Class[0];
public DemuxingProtocolCodecFactory() {
}
public void register(Class<?> encoderOrDecoderClass) {
if (encoderOrDecoderClass == null) {
throw new NullPointerException("encoderOrDecoderClass");
}
try {
encoderOrDecoderClass.getConstructor(EMPTY_PARAMS);
} catch (NoSuchMethodException e) {
throw new IllegalArgumentException(
"The specifiec class doesn't have a public default constructor.");
}
boolean registered = false;
if (MessageEncoder.class.isAssignableFrom(encoderOrDecoderClass)) {
register(new DefaultConstructorMessageEncoderFactory(encoderOrDecoderClass));
registered = true;
}
if (MessageDecoder.class.isAssignableFrom(encoderOrDecoderClass)) {
register(new DefaultConstructorMessageDecoderFactory(
encoderOrDecoderClass));
registered = true;
}
if (!registered) {
throw new IllegalArgumentException("Unregisterable type: "
+ encoderOrDecoderClass);
}
}
public <T> void register(MessageEncoder<T> encoder) {
register(new SingletonMessageEncoderFactory<T>(encoder));
}
public void register(MessageEncoderFactory<?> factory) {
if (factory == null) {
throw new NullPointerException("factory");
}
MessageEncoderFactory<?>[] encoderFactories = this.encoderFactories;
MessageEncoderFactory<?>[] newEncoderFactories = new MessageEncoderFactory[encoderFactories.length + 1];
System.arraycopy(encoderFactories, 0, newEncoderFactories, 0,
encoderFactories.length);
newEncoderFactories[encoderFactories.length] = factory;
this.encoderFactories = newEncoderFactories;
}
public void register(MessageDecoder decoder) {
register(new SingletonMessageDecoderFactory(decoder));
}
public void register(MessageDecoderFactory factory) {
if (factory == null) {
throw new NullPointerException("factory");
}
MessageDecoderFactory[] decoderFactories = this.decoderFactories;
MessageDecoderFactory[] newDecoderFactories = new MessageDecoderFactory[decoderFactories.length + 1];
System.arraycopy(decoderFactories, 0, newDecoderFactories, 0,
decoderFactories.length);
newDecoderFactories[decoderFactories.length] = factory;
this.decoderFactories = newDecoderFactories;
}
public ProtocolEncoder getEncoder() throws Exception {
return new ProtocolEncoderImpl();
}
public ProtocolDecoder getDecoder() throws Exception {
return new ProtocolDecoderImpl();
}
/**
* Implement this method to release all resources acquired to perform
* encoding and decoding messages for the specified <tt>session</tt>.
* By default, this method does nothing.
*
* @param session the session that requires resource deallocation now
*/
protected void disposeCodecResources(IoSession session) {
// Do nothing by default; let users implement it as they want.
// This statement is just to avoid compiler warning. Please ignore.
session.getService();
}
private class ProtocolEncoderImpl implements ProtocolEncoder {
private final Map<Class<?>, MessageEncoder> encoders = new IdentityHashMap<Class<?>, MessageEncoder>();
private ProtocolEncoderImpl() throws Exception {
MessageEncoderFactory[] encoderFactories = DemuxingProtocolCodecFactory.this.encoderFactories;
for (int i = encoderFactories.length - 1; i >= 0; i--) {
MessageEncoder encoder = encoderFactories[i].getEncoder();
Set<Class<?>> messageTypes = encoder.getMessageTypes();
if (messageTypes == null) {
throw new IllegalStateException(encoder.getClass()
.getName()
+ "#getMessageTypes() may not return null.");
}
Iterator<Class<?>> it = messageTypes.iterator();
while (it.hasNext()) {
Class<?> type = it.next();
encoders.put(type, encoder);
}
}
}
public void encode(IoSession session, Object message,
ProtocolEncoderOutput out) throws Exception {
Class<?> type = message.getClass();
MessageEncoder encoder = findEncoder(type);
if (encoder == null) {
throw new ProtocolEncoderException("Unexpected message type: "
+ type);
}
encoder.encode(session, message, out);
}
private MessageEncoder findEncoder(Class<?> type) {
MessageEncoder encoder = encoders.get(type);
if (encoder == null) {
encoder = findEncoder(type, new IdentityHashSet<Class<?>>());
}
return encoder;
}
private MessageEncoder findEncoder(Class<?> type,
Set<Class<?>> triedClasses) {
MessageEncoder encoder;
if (triedClasses.contains(type)) {
return null;
}
triedClasses.add(type);
encoder = encoders.get(type);
if (encoder == null) {
encoder = findEncoder(type, triedClasses);
if (encoder != null) {
return encoder;
}
Class<?>[] interfaces = type.getInterfaces();
for (Class<?> element : interfaces) {
encoder = findEncoder(element, triedClasses);
if (encoder != null) {
return encoder;
}
}
return null;
} else {
return encoder;
}
}
public void dispose(IoSession session) throws Exception {
DemuxingProtocolCodecFactory.this.disposeCodecResources(session);
}
}
private class ProtocolDecoderImpl extends CumulativeProtocolDecoder {
private final MessageDecoder[] decoders;
private MessageDecoder currentDecoder;
protected ProtocolDecoderImpl() throws Exception {
MessageDecoderFactory[] decoderFactories = DemuxingProtocolCodecFactory.this.decoderFactories;
decoders = new MessageDecoder[decoderFactories.length];
for (int i = decoderFactories.length - 1; i >= 0; i--) {
decoders[i] = decoderFactories[i].getDecoder();
}
}
@Override
protected boolean doDecode(IoSession session, ByteBuffer in,
ProtocolDecoderOutput out) throws Exception {
if (currentDecoder == null) {
MessageDecoder[] decoders = this.decoders;
int undecodables = 0;
for (int i = decoders.length - 1; i >= 0; i--) {
MessageDecoder decoder = decoders[i];
int limit = in.limit();
int pos = in.position();
MessageDecoderResult result;
try {
result = decoder.decodable(session, in);
} finally {
in.position(pos);
in.limit(limit);
}
if (result == MessageDecoder.OK) {
currentDecoder = decoder;
break;
} else if (result == MessageDecoder.NOT_OK) {
undecodables++;
} else if (result != MessageDecoder.NEED_DATA) {
throw new IllegalStateException(
"Unexpected decode result (see your decodable()): "
+ result);
}
}
if (undecodables == decoders.length) {
// Throw an exception if all decoders cannot decode data.
String dump = in.getHexDump();
in.position(in.limit()); // Skip data
throw new ProtocolDecoderException(
"No appropriate message decoder: " + dump);
}
if (currentDecoder == null) {
// Decoder is not determined yet (i.e. we need more data)
return false;
}
}
MessageDecoderResult result = currentDecoder.decode(session, in,
out);
if (result == MessageDecoder.OK) {
currentDecoder = null;
return true;
} else if (result == MessageDecoder.NEED_DATA) {
return false;
} else if (result == MessageDecoder.NOT_OK) {
+ currentDecoder = null;
throw new ProtocolDecoderException(
"Message decoder returned NOT_OK.");
} else {
+ currentDecoder = null;
throw new IllegalStateException(
"Unexpected decode result (see your decode()): "
+ result);
}
}
@Override
public void finishDecode(IoSession session, ProtocolDecoderOutput out)
throws Exception {
if (currentDecoder == null) {
return;
}
currentDecoder.finishDecode(session, out);
}
@Override
public void dispose(IoSession session) throws Exception {
super.dispose(session);
// ProtocolEncoder.dispose() already called disposeCodec(),
// so there's nothing more we need to do.
}
}
private static class SingletonMessageEncoderFactory<T> implements
MessageEncoderFactory<T> {
private final MessageEncoder<T> encoder;
private SingletonMessageEncoderFactory(MessageEncoder<T> encoder) {
if (encoder == null) {
throw new NullPointerException("encoder");
}
this.encoder = encoder;
}
public MessageEncoder<T> getEncoder() {
return encoder;
}
}
private static class SingletonMessageDecoderFactory implements
MessageDecoderFactory {
private final MessageDecoder decoder;
private SingletonMessageDecoderFactory(MessageDecoder decoder) {
if (decoder == null) {
throw new NullPointerException("decoder");
}
this.decoder = decoder;
}
public MessageDecoder getDecoder() {
return decoder;
}
}
private static class DefaultConstructorMessageEncoderFactory<T> implements
MessageEncoderFactory<T> {
private final Class<MessageEncoder<T>> encoderClass;
private DefaultConstructorMessageEncoderFactory(Class<MessageEncoder<T>> encoderClass) {
if (encoderClass == null) {
throw new NullPointerException("encoderClass");
}
if (!MessageEncoder.class.isAssignableFrom(encoderClass)) {
throw new IllegalArgumentException(
"encoderClass is not assignable to MessageEncoder");
}
this.encoderClass = encoderClass;
}
public MessageEncoder<T> getEncoder() throws Exception {
return encoderClass.newInstance();
}
}
private static class DefaultConstructorMessageDecoderFactory implements
MessageDecoderFactory {
private final Class<?> decoderClass;
private DefaultConstructorMessageDecoderFactory(Class<?> decoderClass) {
if (decoderClass == null) {
throw new NullPointerException("decoderClass");
}
if (!MessageDecoder.class.isAssignableFrom(decoderClass)) {
throw new IllegalArgumentException(
"decoderClass is not assignable to MessageDecoder");
}
this.decoderClass = decoderClass;
}
public MessageDecoder getDecoder() throws Exception {
return (MessageDecoder) decoderClass.newInstance();
}
}
}
| false | true | protected boolean doDecode(IoSession session, ByteBuffer in,
ProtocolDecoderOutput out) throws Exception {
if (currentDecoder == null) {
MessageDecoder[] decoders = this.decoders;
int undecodables = 0;
for (int i = decoders.length - 1; i >= 0; i--) {
MessageDecoder decoder = decoders[i];
int limit = in.limit();
int pos = in.position();
MessageDecoderResult result;
try {
result = decoder.decodable(session, in);
} finally {
in.position(pos);
in.limit(limit);
}
if (result == MessageDecoder.OK) {
currentDecoder = decoder;
break;
} else if (result == MessageDecoder.NOT_OK) {
undecodables++;
} else if (result != MessageDecoder.NEED_DATA) {
throw new IllegalStateException(
"Unexpected decode result (see your decodable()): "
+ result);
}
}
if (undecodables == decoders.length) {
// Throw an exception if all decoders cannot decode data.
String dump = in.getHexDump();
in.position(in.limit()); // Skip data
throw new ProtocolDecoderException(
"No appropriate message decoder: " + dump);
}
if (currentDecoder == null) {
// Decoder is not determined yet (i.e. we need more data)
return false;
}
}
MessageDecoderResult result = currentDecoder.decode(session, in,
out);
if (result == MessageDecoder.OK) {
currentDecoder = null;
return true;
} else if (result == MessageDecoder.NEED_DATA) {
return false;
} else if (result == MessageDecoder.NOT_OK) {
throw new ProtocolDecoderException(
"Message decoder returned NOT_OK.");
} else {
throw new IllegalStateException(
"Unexpected decode result (see your decode()): "
+ result);
}
}
| protected boolean doDecode(IoSession session, ByteBuffer in,
ProtocolDecoderOutput out) throws Exception {
if (currentDecoder == null) {
MessageDecoder[] decoders = this.decoders;
int undecodables = 0;
for (int i = decoders.length - 1; i >= 0; i--) {
MessageDecoder decoder = decoders[i];
int limit = in.limit();
int pos = in.position();
MessageDecoderResult result;
try {
result = decoder.decodable(session, in);
} finally {
in.position(pos);
in.limit(limit);
}
if (result == MessageDecoder.OK) {
currentDecoder = decoder;
break;
} else if (result == MessageDecoder.NOT_OK) {
undecodables++;
} else if (result != MessageDecoder.NEED_DATA) {
throw new IllegalStateException(
"Unexpected decode result (see your decodable()): "
+ result);
}
}
if (undecodables == decoders.length) {
// Throw an exception if all decoders cannot decode data.
String dump = in.getHexDump();
in.position(in.limit()); // Skip data
throw new ProtocolDecoderException(
"No appropriate message decoder: " + dump);
}
if (currentDecoder == null) {
// Decoder is not determined yet (i.e. we need more data)
return false;
}
}
MessageDecoderResult result = currentDecoder.decode(session, in,
out);
if (result == MessageDecoder.OK) {
currentDecoder = null;
return true;
} else if (result == MessageDecoder.NEED_DATA) {
return false;
} else if (result == MessageDecoder.NOT_OK) {
currentDecoder = null;
throw new ProtocolDecoderException(
"Message decoder returned NOT_OK.");
} else {
currentDecoder = null;
throw new IllegalStateException(
"Unexpected decode result (see your decode()): "
+ result);
}
}
|
diff --git a/src/nl/giantit/minecraft/GiantShop/GiantShop.java b/src/nl/giantit/minecraft/GiantShop/GiantShop.java
index 5c1e9af..5a6be2e 100644
--- a/src/nl/giantit/minecraft/GiantShop/GiantShop.java
+++ b/src/nl/giantit/minecraft/GiantShop/GiantShop.java
@@ -1,290 +1,290 @@
package nl.giantit.minecraft.GiantShop;
import nl.giantit.minecraft.giantcore.GiantCore;
import nl.giantit.minecraft.giantcore.Database.Database;
import nl.giantit.minecraft.giantcore.GiantPlugin;
import nl.giantit.minecraft.giantcore.Misc.Messages;
import nl.giantit.minecraft.giantcore.core.Eco.Eco;
import nl.giantit.minecraft.giantcore.perms.PermHandler;
import nl.giantit.minecraft.GiantShop.Locationer.Locationer;
import nl.giantit.minecraft.GiantShop.Misc.Misc;
import nl.giantit.minecraft.GiantShop.core.config;
import nl.giantit.minecraft.GiantShop.core.Commands.ChatExecutor;
import nl.giantit.minecraft.GiantShop.core.Commands.ConsoleExecutor;
import nl.giantit.minecraft.GiantShop.core.Items.Items;
import nl.giantit.minecraft.GiantShop.core.Metrics.MetricsHandler;
import nl.giantit.minecraft.GiantShop.core.Tools.Discount.Discounter;
import nl.giantit.minecraft.GiantShop.core.Tools.dbInit.dbInit;
import nl.giantit.minecraft.GiantShop.core.Updater.Updater;
import org.bukkit.Server;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import nl.giantit.minecraft.GiantShop.API.GiantShopAPI;
/**
*
* @author Giant
*/
public class GiantShop extends GiantPlugin {
public static final Logger log = Logger.getLogger("Minecraft");
private static GiantShop plugin;
private static Server Server;
private GiantCore gc;
private Database db;
private PermHandler permHandler;
private ChatExecutor chat;
private ConsoleExecutor console;
private Items itemHandler;
private Eco econHandler;
private Messages msgHandler;
private Locationer locHandler;
private Updater updater;
private Discounter discounter;
private MetricsHandler metrics;
private String name, dir, pubName;
private String bName = "Cacti Powered";
private boolean useLoc = false;
public List<String> cmds;
private void setPlugin() {
GiantShop.plugin = this;
}
public GiantShop() {
this.setPlugin();
}
@Override
public void onEnable() {
this.gc = GiantCore.getInstance();
if(this.gc == null) {
getLogger().severe("Failed to hook into required GiantCore!");
this.getPluginLoader().disablePlugin(this);
return;
}
- if(this.gc.getProtocolVersion() >= 0.2) {
+ if(this.gc.getProtocolVersion() < 0.3) {
getLogger().severe("The GiantCore version you are using it not made for this plugin!");
this.getPluginLoader().disablePlugin(this);
return;
}
Server = this.getServer();
this.name = getDescription().getName();
this.dir = getDataFolder().toString();
File configFile = new File(getDataFolder(), "conf.yml");
if(!configFile.exists()) {
getDataFolder().mkdir();
getDataFolder().setWritable(true);
getDataFolder().setExecutable(true);
this.extract("conf.yml");
if(!configFile.exists()) {
getLogger().severe("Failed to extract configuration file!");
this.getPluginLoader().disablePlugin(this);
return;
}
}
config conf = config.Obtain(this);
try {
this.updater = new Updater(this); // Dirty fix for NPE
conf.loadConfig(configFile);
if(!conf.isLoaded()) {
getLogger().severe("Failed to load configuration file!");
this.getPluginLoader().disablePlugin(this);
return;
}
HashMap<String, String> db = conf.getMap(this.name + ".db");
db.put("debug", conf.getString(this.name + ".global.debug"));
this.db = this.gc.getDB(this, null, db);
new dbInit(this);
if(conf.getBoolean(this.name + ".permissions.usePermissions")) {
permHandler = this.gc.getPermHandler(PermHandler.findEngine(conf.getString(this.name + ".permissions.Engine")), conf.getBoolean(this.name + ".permissions.opHasPerms"));
}else{
permHandler = this.gc.getPermHandler(PermHandler.findEngine("NOPERM"), true);
}
if(conf.getBoolean(this.name + ".Location.useGiantShopLocation")) {
useLoc = true;
locHandler = new Locationer(this);
cmds = conf.getStringList(this.name + ".Location.protect.Commands");
if(conf.getBoolean(this.name + ".Location.showPlayerEnteredShop"))
getServer().getPluginManager().registerEvents(new nl.giantit.minecraft.GiantShop.Locationer.Listeners.PlayerListener(this), this);
}
if(conf.getBoolean(this.name + ".Updater.checkForUpdates")) {
getServer().getPluginManager().registerEvents(new nl.giantit.minecraft.GiantShop.Listeners.PlayerListener(this), this);
}
this.updater = new Updater(this);
pubName = conf.getString(this.name + ".global.name");
chat = new ChatExecutor(this);
console = new ConsoleExecutor(this);
itemHandler = new Items(this);
econHandler = this.gc.getEcoHandler(Eco.findEngine(conf.getString("GiantShop.Economy.Engine")));
msgHandler = new Messages(this, 1.4);
discounter = new Discounter(this);
if(conf.getBoolean(this.name + ".metrics.useMetrics")) {
this.metrics = new MetricsHandler(this);
}
GiantShopAPI.Obtain();
if(econHandler.isLoaded()) {
log.log(Level.INFO, "[" + this.name + "](" + this.bName + ") Was successfully enabled!");
}else{
log.log(Level.WARNING, "[" + this.name + "] Could not load economy engine yet!");
log.log(Level.WARNING, "[" + this.name + "] Errors might occur if you do not see '[GiantShop]Successfully hooked into (whichever) Engine!' after this message!");
}
}catch(Exception e) {
log.log(Level.SEVERE, "[" + this.name + "](" + this.bName + ") Failed to load!");
if(conf.getBoolean(this.name + ".global.debug")) {
log.log(Level.INFO, e.getMessage(), e);
}
Server.getPluginManager().disablePlugin(this);
}
}
@Override
public void onDisable() {
if(null != this.updater)
this.updater.stop();
GiantShopAPI.Obtain().stop();
if(null != this.db) {
this.db.getEngine().close();
}
log.log(Level.INFO, "[" + this.name + "] Was successfully disabled!");
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
if (Misc.isEitherIgnoreCase(cmd.getName(), "shop", "s")) {
if(!(sender instanceof Player)){
return console.exec(sender, args);
}
return chat.exec(sender, args);
}else if (cmd.getName().equalsIgnoreCase("loc")) {
return locHandler.onCommand(sender, cmd, commandLabel, args);
}
return false;
}
public int scheduleAsyncDelayedTask(final Runnable run) {
return getServer().getScheduler().scheduleAsyncDelayedTask(this, run, 20L);
}
public int scheduleAsyncRepeatingTask(final Runnable run, Long init, Long delay) {
return getServer().getScheduler().scheduleAsyncRepeatingTask(this, run, init, delay);
}
@Override
public GiantCore getGiantCore() {
return this.gc;
}
@Override
public String getPubName() {
return this.pubName;
}
@Override
public String getDir() {
return this.dir;
}
public String getSeparator() {
return File.separator;
}
public Boolean isOutOfDate() {
return this.updater.isOutOfDate();
}
public Boolean useLocation() {
return this.useLoc;
}
public String getVersion() {
return getDescription().getVersion();
}
public String getNewVersion() {
return this.updater.getNewVersion();
}
@Override
public Database getDB() {
return this.db;
}
@Override
public PermHandler getPermHandler() {
return this.permHandler;
}
public Server getSrvr() {
return getServer();
}
public Items getItemHandler() {
return this.itemHandler;
}
@Override
public Eco getEcoHandler() {
return this.econHandler;
}
@Override
public Messages getMsgHandler() {
return this.msgHandler;
}
public Discounter getDiscounter() {
return this.discounter;
}
public Locationer getLocHandler() {
return this.locHandler;
}
public Updater getUpdater() {
return this.updater;
}
public static GiantShop getPlugin() {
return GiantShop.plugin;
}
}
| true | true | public void onEnable() {
this.gc = GiantCore.getInstance();
if(this.gc == null) {
getLogger().severe("Failed to hook into required GiantCore!");
this.getPluginLoader().disablePlugin(this);
return;
}
if(this.gc.getProtocolVersion() >= 0.2) {
getLogger().severe("The GiantCore version you are using it not made for this plugin!");
this.getPluginLoader().disablePlugin(this);
return;
}
Server = this.getServer();
this.name = getDescription().getName();
this.dir = getDataFolder().toString();
File configFile = new File(getDataFolder(), "conf.yml");
if(!configFile.exists()) {
getDataFolder().mkdir();
getDataFolder().setWritable(true);
getDataFolder().setExecutable(true);
this.extract("conf.yml");
if(!configFile.exists()) {
getLogger().severe("Failed to extract configuration file!");
this.getPluginLoader().disablePlugin(this);
return;
}
}
config conf = config.Obtain(this);
try {
this.updater = new Updater(this); // Dirty fix for NPE
conf.loadConfig(configFile);
if(!conf.isLoaded()) {
getLogger().severe("Failed to load configuration file!");
this.getPluginLoader().disablePlugin(this);
return;
}
HashMap<String, String> db = conf.getMap(this.name + ".db");
db.put("debug", conf.getString(this.name + ".global.debug"));
this.db = this.gc.getDB(this, null, db);
new dbInit(this);
if(conf.getBoolean(this.name + ".permissions.usePermissions")) {
permHandler = this.gc.getPermHandler(PermHandler.findEngine(conf.getString(this.name + ".permissions.Engine")), conf.getBoolean(this.name + ".permissions.opHasPerms"));
}else{
permHandler = this.gc.getPermHandler(PermHandler.findEngine("NOPERM"), true);
}
if(conf.getBoolean(this.name + ".Location.useGiantShopLocation")) {
useLoc = true;
locHandler = new Locationer(this);
cmds = conf.getStringList(this.name + ".Location.protect.Commands");
if(conf.getBoolean(this.name + ".Location.showPlayerEnteredShop"))
getServer().getPluginManager().registerEvents(new nl.giantit.minecraft.GiantShop.Locationer.Listeners.PlayerListener(this), this);
}
if(conf.getBoolean(this.name + ".Updater.checkForUpdates")) {
getServer().getPluginManager().registerEvents(new nl.giantit.minecraft.GiantShop.Listeners.PlayerListener(this), this);
}
this.updater = new Updater(this);
pubName = conf.getString(this.name + ".global.name");
chat = new ChatExecutor(this);
console = new ConsoleExecutor(this);
itemHandler = new Items(this);
econHandler = this.gc.getEcoHandler(Eco.findEngine(conf.getString("GiantShop.Economy.Engine")));
msgHandler = new Messages(this, 1.4);
discounter = new Discounter(this);
if(conf.getBoolean(this.name + ".metrics.useMetrics")) {
this.metrics = new MetricsHandler(this);
}
GiantShopAPI.Obtain();
if(econHandler.isLoaded()) {
log.log(Level.INFO, "[" + this.name + "](" + this.bName + ") Was successfully enabled!");
}else{
log.log(Level.WARNING, "[" + this.name + "] Could not load economy engine yet!");
log.log(Level.WARNING, "[" + this.name + "] Errors might occur if you do not see '[GiantShop]Successfully hooked into (whichever) Engine!' after this message!");
}
}catch(Exception e) {
log.log(Level.SEVERE, "[" + this.name + "](" + this.bName + ") Failed to load!");
if(conf.getBoolean(this.name + ".global.debug")) {
log.log(Level.INFO, e.getMessage(), e);
}
Server.getPluginManager().disablePlugin(this);
}
}
| public void onEnable() {
this.gc = GiantCore.getInstance();
if(this.gc == null) {
getLogger().severe("Failed to hook into required GiantCore!");
this.getPluginLoader().disablePlugin(this);
return;
}
if(this.gc.getProtocolVersion() < 0.3) {
getLogger().severe("The GiantCore version you are using it not made for this plugin!");
this.getPluginLoader().disablePlugin(this);
return;
}
Server = this.getServer();
this.name = getDescription().getName();
this.dir = getDataFolder().toString();
File configFile = new File(getDataFolder(), "conf.yml");
if(!configFile.exists()) {
getDataFolder().mkdir();
getDataFolder().setWritable(true);
getDataFolder().setExecutable(true);
this.extract("conf.yml");
if(!configFile.exists()) {
getLogger().severe("Failed to extract configuration file!");
this.getPluginLoader().disablePlugin(this);
return;
}
}
config conf = config.Obtain(this);
try {
this.updater = new Updater(this); // Dirty fix for NPE
conf.loadConfig(configFile);
if(!conf.isLoaded()) {
getLogger().severe("Failed to load configuration file!");
this.getPluginLoader().disablePlugin(this);
return;
}
HashMap<String, String> db = conf.getMap(this.name + ".db");
db.put("debug", conf.getString(this.name + ".global.debug"));
this.db = this.gc.getDB(this, null, db);
new dbInit(this);
if(conf.getBoolean(this.name + ".permissions.usePermissions")) {
permHandler = this.gc.getPermHandler(PermHandler.findEngine(conf.getString(this.name + ".permissions.Engine")), conf.getBoolean(this.name + ".permissions.opHasPerms"));
}else{
permHandler = this.gc.getPermHandler(PermHandler.findEngine("NOPERM"), true);
}
if(conf.getBoolean(this.name + ".Location.useGiantShopLocation")) {
useLoc = true;
locHandler = new Locationer(this);
cmds = conf.getStringList(this.name + ".Location.protect.Commands");
if(conf.getBoolean(this.name + ".Location.showPlayerEnteredShop"))
getServer().getPluginManager().registerEvents(new nl.giantit.minecraft.GiantShop.Locationer.Listeners.PlayerListener(this), this);
}
if(conf.getBoolean(this.name + ".Updater.checkForUpdates")) {
getServer().getPluginManager().registerEvents(new nl.giantit.minecraft.GiantShop.Listeners.PlayerListener(this), this);
}
this.updater = new Updater(this);
pubName = conf.getString(this.name + ".global.name");
chat = new ChatExecutor(this);
console = new ConsoleExecutor(this);
itemHandler = new Items(this);
econHandler = this.gc.getEcoHandler(Eco.findEngine(conf.getString("GiantShop.Economy.Engine")));
msgHandler = new Messages(this, 1.4);
discounter = new Discounter(this);
if(conf.getBoolean(this.name + ".metrics.useMetrics")) {
this.metrics = new MetricsHandler(this);
}
GiantShopAPI.Obtain();
if(econHandler.isLoaded()) {
log.log(Level.INFO, "[" + this.name + "](" + this.bName + ") Was successfully enabled!");
}else{
log.log(Level.WARNING, "[" + this.name + "] Could not load economy engine yet!");
log.log(Level.WARNING, "[" + this.name + "] Errors might occur if you do not see '[GiantShop]Successfully hooked into (whichever) Engine!' after this message!");
}
}catch(Exception e) {
log.log(Level.SEVERE, "[" + this.name + "](" + this.bName + ") Failed to load!");
if(conf.getBoolean(this.name + ".global.debug")) {
log.log(Level.INFO, e.getMessage(), e);
}
Server.getPluginManager().disablePlugin(this);
}
}
|
diff --git a/src/de/geotweeter/Account.java b/src/de/geotweeter/Account.java
index c445e7a..3c1885e 100644
--- a/src/de/geotweeter/Account.java
+++ b/src/de/geotweeter/Account.java
@@ -1,546 +1,546 @@
package de.geotweeter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Stack;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLPeerUnverifiedException;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Token;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Handler;
import android.util.Log;
import de.geotweeter.activities.TimelineActivity;
import de.geotweeter.apiconn.TwitterApiAccess;
import de.geotweeter.timelineelements.DirectMessage;
import de.geotweeter.timelineelements.TimelineElement;
import de.geotweeter.timelineelements.Tweet;
public class Account implements Serializable {
/**
*
*/
private static final long serialVersionUID = -3681363869066996199L;
protected final static Object lock_object = new Object();
protected final String LOG = "Account";
public static ArrayList<Account> all_accounts = new ArrayList<Account>();
private transient int tasksRunning = 0;
protected transient ArrayList<TimelineElement> mainTimeline;
protected transient ArrayList<ArrayList<TimelineElement>> apiResponses;
private Token token;
private transient Handler handler;
private transient StreamRequest stream_request;
private long max_read_tweet_id = 0;
private long max_read_dm_id = 0;
private long max_known_tweet_id = 0;
private long min_known_tweet_id = -1;
private long max_known_dm_id = 0;
private long min_known_dm_id = -1;
private User user;
private transient TimelineElementAdapter elements;
private long max_read_mention_id = 0;
private transient Context appContext;
private transient TwitterApiAccess api;
private transient Stack<TimelineElementAdapter> timeline_stack;
private enum AccessType {
TIMELINE, MENTIONS, DM_RCVD, DM_SENT
}
public Account(TimelineElementAdapter elements, Token token, User user, Context applicationContext, boolean fetchTimeLine) {
mainTimeline = new ArrayList<TimelineElement>();
apiResponses = new ArrayList<ArrayList<TimelineElement>>(4);
api = new TwitterApiAccess(token);
this.token = token;
this.user = user;
handler = new Handler();
this.elements = elements;
this.appContext = applicationContext;
stream_request = new StreamRequest(this);
all_accounts.add(this);
timeline_stack = new Stack<TimelineElementAdapter>();
timeline_stack.push(elements);
if (fetchTimeLine) {
start(true);
}
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
mainTimeline = new ArrayList<TimelineElement>();
apiResponses = new ArrayList<ArrayList<TimelineElement>>(4);
api = new TwitterApiAccess(token);
handler = new Handler();
stream_request = new StreamRequest(this);
}
public void setAppContext(Context appContext) {
this.appContext = appContext;
}
public void start(boolean loadPersistedTweets) {
Log.d(LOG, "In start()");
if (stream_request != null) {
stream_request.stop(true);
}
if (loadPersistedTweets) {
loadPersistedTweets(appContext);
}
if (Debug.ENABLED && Debug.SKIP_FILL_TIMELINE) {
Log.d(LOG, "TimelineRefreshThread skipped. (Debug.SKIP_FILL_TIMELINE)");
} else {
if (Build.VERSION.SDK_INT >= 11) {
refreshTimeline();
} else {
refreshTimelinePreAPI11();
}
}
getMaxReadIDs();
}
public void stopStream() {
stream_request.stop(false);
}
@TargetApi(11)
private void refreshTimeline() {
// if (overallTasksRunning == 0) {
// Utils.showMainSpinner();
// }
tasksRunning = 4;
ThreadPoolExecutor exec = new ThreadPoolExecutor(4, 4, 0, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(4));
new TimelineRefreshTask().executeOnExecutor(exec, AccessType.TIMELINE);
new TimelineRefreshTask().executeOnExecutor(exec, AccessType.MENTIONS);
new TimelineRefreshTask().executeOnExecutor(exec, AccessType.DM_RCVD);
new TimelineRefreshTask().executeOnExecutor(exec, AccessType.DM_SENT);
}
private void refreshTimelinePreAPI11() {
// if (overallTasksRunning == 0) {
// Utils.showMainSpinner();
// }
tasksRunning = 4;
new TimelineRefreshTask().execute(AccessType.TIMELINE);
new TimelineRefreshTask().execute(AccessType.MENTIONS);
new TimelineRefreshTask().execute(AccessType.DM_RCVD);
new TimelineRefreshTask().execute(AccessType.DM_SENT);
}
private class TimelineRefreshTask extends AsyncTask<AccessType, Void, ArrayList<TimelineElement>> {
private AccessType accessType;
private long startTime;
@Override
protected ArrayList<TimelineElement> doInBackground(AccessType... params) {
accessType = params[0];
startTime = System.currentTimeMillis();
switch (accessType) {
case TIMELINE:
Log.d(LOG, "Get home timeline");
return api.getHomeTimeline(0, 0);
case MENTIONS:
Log.d(LOG, "Get mentions");
return api.getMentions(0, 0);
case DM_RCVD:
Log.d(LOG, "Get received dm");
return api.getReceivedDMs(0, 0);
case DM_SENT:
Log.d(LOG, "Get sent dm");
return api.getSentDMs(0, 0);
}
return null;
}
protected void onPostExecute(ArrayList<TimelineElement> result) {
tasksRunning--;
Log.d(LOG, "Get " + accessType.toString() + " finished. Runtime: " + String.valueOf(System.currentTimeMillis() - startTime) + "ms");
if (accessType == AccessType.TIMELINE) {
mainTimeline = result;
} else {
apiResponses.add(result);
}
if (tasksRunning == 0) {
if (mainTimeline == null) {
mainTimeline = new ArrayList<TimelineElement>();
}
if (!mainTimeline.isEmpty()) {
apiResponses.add(0, mainTimeline);
}
parseData(apiResponses, false);
if (Debug.ENABLED && Debug.SKIP_START_STREAM) {
Log.d(LOG, "Not starting stream - Debug.SKIP_START_STREAM is true.");
} else {
stream_request.start();
}
}
// if (overallTasksRunning == 0) {
// Utils.hideMainSpinner();
// }
}
}
protected void parseData(ArrayList<ArrayList<TimelineElement>> responses, boolean do_clip) {
final long old_max_known_dm_id = max_known_dm_id;
Log.d(LOG, "parseData started.");
final ArrayList<TimelineElement> all_elements = new ArrayList<TimelineElement>();
long last_id = 0;
// remove empty arrays
for (int i = responses.size() - 1; i >= 0; i--) {
- if (responses.get(i).size()==0) {
+ if (responses.get(i)==null || responses.get(i).size()==0) {
responses.remove(i);
}
}
while (responses.size() > 0) {
Date newest_date = null;
int newest_index = -1;
for (int i = 0; i < responses.size(); i++) {
TimelineElement element = responses.get(i).get(0);
if (newest_date == null || element.getDate().after(newest_date)) {
newest_date = element.getDate();
newest_index = i;
}
}
TimelineElement element = responses.get(newest_index).remove(0);
if (responses.get(newest_index).size() == 0) {
/* Das primäre Element ist leer. Also brechen wir ab.
* Allerdings muss vorher noch ein bisschen gearbeitet werden... */
responses.remove(newest_index);
if (newest_index == 0) {
if (max_known_tweet_id == 0) {
for (ArrayList<TimelineElement> array : responses) {
TimelineElement first_element = array.get(0);
if (first_element instanceof Tweet && ((Tweet) first_element).id > max_known_tweet_id) {
max_known_tweet_id = ((Tweet)first_element).id;
}
}
}
if (max_known_dm_id==0) {
for (ArrayList<TimelineElement> array : responses) {
TimelineElement first_element = array.get(0);
if (first_element instanceof DirectMessage && first_element.getID() > max_known_dm_id) {
max_known_dm_id = first_element.getID();
}
}
}
Log.d(LOG, "Breaking!");
break;
}
}
long element_id = element.getID();
if (element_id != last_id) {
if (!(element instanceof DirectMessage) || element_id>old_max_known_dm_id) {
all_elements.add(element);
}
}
last_id = element_id;
if (element instanceof Tweet) {
if (element_id > max_known_tweet_id) {
max_known_tweet_id = element_id;
}
if (min_known_tweet_id == -1 || element_id < min_known_tweet_id) {
min_known_tweet_id = element_id;
}
} else if (element instanceof DirectMessage) {
if (element_id > max_known_dm_id) {
max_known_dm_id = element_id;
}
if (min_known_dm_id == -1 || element_id < min_known_dm_id) {
min_known_dm_id = element_id;
}
}
}
Log.d(LOG, "parseData is almost done. " + all_elements.size() + " elements.");
handler.post(new Runnable() {
@Override
public void run() {
elements.addAllAsFirst(all_elements);
}
});
}
public void addTweet(final TimelineElement elm) {
Log.d(LOG, "Adding Tweet.");
if (elm instanceof DirectMessage) {
if (elm.getID() > max_known_dm_id) {
max_known_dm_id = elm.getID();
}
} else if (elm instanceof Tweet) {
if (elm.getID() > max_known_tweet_id) {
max_known_tweet_id = elm.getID();
}
}
//elements.add(tweet);
handler.post(new Runnable() {
public void run() {
elements.addAsFirst(elm);
}
});
}
public void registerForGCMMessages() {
Log.d(LOG, "Registering...");
new Thread(new Runnable() {
public void run() {
HttpClient http_client = new CacertHttpClient(appContext);
HttpPost http_post = new HttpPost(Utils.getProperty("google.gcm.server.url") + "/register");
try {
List<NameValuePair> name_value_pair = new ArrayList<NameValuePair>(5);
name_value_pair.add(new BasicNameValuePair("reg_id", TimelineActivity.reg_id));
name_value_pair.add(new BasicNameValuePair("token", getToken().getToken()));
name_value_pair.add(new BasicNameValuePair("secret", getToken().getSecret()));
name_value_pair.add(new BasicNameValuePair("screen_name", getUser().getScreenName()));
name_value_pair.add(new BasicNameValuePair("protocol_version", "1"));
http_post.setEntity(new UrlEncodedFormEntity(name_value_pair));
http_client.execute(http_post);
} catch(ClientProtocolException e) {
e.printStackTrace();
} catch(SSLPeerUnverifiedException e) {
Log.e(LOG, "Couldn't register account at GCM-server. Maybe you forgot to install CAcert's certificate?");
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
}
}, "register").start();
}
public void getMaxReadIDs() {
new Thread(new Runnable() {
@Override
public void run() {
OAuthRequest oauth_request = api.getVerifiedCredentials();
try {
HttpClient http_client = new DefaultHttpClient();
HttpGet http_get = new HttpGet(Constants.URI_TWEETMARKER_LASTREAD + user.getScreenName() + "&api_key=" + Utils.getProperty("tweetmarker.key"));
http_get.addHeader("X-Auth-Service-Provider", Constants.URI_VERIFY_CREDENTIALS);
http_get.addHeader("X-Verify-Credentials-Authorization", oauth_request.getHeaders().get("Authorization"));
HttpResponse response = http_client.execute(http_get);
if (response.getEntity() == null) {
return;
}
String[] parts = EntityUtils.toString(response.getEntity()).split(",");
try {
max_read_tweet_id = Long.parseLong(parts[0]);
} catch (NumberFormatException ex) {}
try {
max_read_mention_id = Long.parseLong(parts[1]);
} catch (NumberFormatException ex) {}
try {
max_read_dm_id = Long.parseLong(parts[2]);
if (max_known_dm_id == 0) {
max_known_dm_id = max_read_dm_id;
}
} catch (NumberFormatException ex) {}
handler.post(new Runnable() {
@Override
public void run() {
elements.notifyDataSetChanged();
}
});
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}, "GetMaxReadIDs").start();
elements.notifyDataSetChanged();
}
public void setMaxReadIDs(long tweet_id, long mention_id, long dm_id) {
if (tweet_id > this.max_read_tweet_id) {
this.max_read_tweet_id = tweet_id;
}
if (mention_id > this.max_read_mention_id ) {
this.max_read_mention_id = mention_id;
}
if (dm_id > this.max_read_dm_id) {
this.max_read_dm_id = dm_id;
}
new Thread(new Runnable() {
@Override
public void run() {
OAuthRequest oauth_request = api.getVerifiedCredentials();
try {
HttpClient http_client = new DefaultHttpClient();
HttpPost http_post = new HttpPost(Constants.URI_TWEETMARKER_LASTREAD + user.getScreenName() + "&api_key=" + Utils.getProperty("tweetmarker.key"));
http_post.addHeader("X-Auth-Service-Provider", Constants.URI_VERIFY_CREDENTIALS);
http_post.addHeader("X-Verify-Credentials-Authorization", oauth_request.getHeaders().get("Authorization"));
http_post.setEntity(new StringEntity(""+max_read_tweet_id+","+max_read_mention_id+","+max_read_dm_id));
http_client.execute(http_post);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}, "SetMaxReadIDs").start();
elements.notifyDataSetChanged();
}
public long getMaxReadTweetID() {
return max_read_tweet_id;
}
public TimelineElementAdapter getElements() {
return elements;
}
public Token getToken() {
return token;
}
public void setUser(User user) {
this.user = user;
}
public User getUser() {
return user;
}
public void persistTweets(Context context) {
File dir = context.getExternalFilesDir(null);
if (!dir.exists()) {
dir = context.getCacheDir();
}
dir = new File(dir, Constants.PATH_TIMELINE_DATA);
if (!dir.exists()) {
dir.mkdirs();
}
ArrayList<TimelineElement> last_tweets = new ArrayList<TimelineElement>(50);
for (int i=0; i<elements.getCount(); i++) {
if (i >= 100) {
break;
}
last_tweets.add(elements.getItem(i));
}
try {
FileOutputStream fout = new FileOutputStream(dir.getPath() + File.separator + String.valueOf(getUser().id));
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(last_tweets);
oos.close();
} catch(Exception ex) {
ex.printStackTrace();
}
}
public void loadPersistedTweets(Context context) {
String fileToLoad = null;
File dir = context.getExternalFilesDir(null);
if (!dir.exists()) {
dir = context.getCacheDir();
}
dir = new File(dir, Constants.PATH_TIMELINE_DATA);
fileToLoad = dir.getPath() + File.separator + String.valueOf(getUser().id);
if (!(new File(fileToLoad).exists())) {
return;
}
ArrayList<TimelineElement> tweets;
try {
FileInputStream fin = new FileInputStream(fileToLoad);
ObjectInputStream ois = new ObjectInputStream(fin);
tweets = (ArrayList<TimelineElement>) ois.readObject();
ois.close();
} catch (Exception ex) {
ex.printStackTrace();
return;
}
for (TimelineElement elm : tweets) {
if (elm instanceof DirectMessage) {
if (elm.getID() > max_known_dm_id) {
max_known_dm_id = elm.getID();
}
} else if (elm instanceof Tweet) {
if (elm.getID() > max_known_tweet_id) {
max_known_tweet_id = elm.getID();
}
}
}
elements.addAllAsFirst(tweets);
}
public TwitterApiAccess getApi() {
return api;
}
public void pushTimeline(TimelineElementAdapter tea) {
timeline_stack.push(tea);
}
public TimelineElementAdapter getPrevTimeline() {
timeline_stack.pop();
return timeline_stack.peek();
}
public TimelineElementAdapter activeTimeline() {
return timeline_stack.peek();
}
}
| true | true | protected void parseData(ArrayList<ArrayList<TimelineElement>> responses, boolean do_clip) {
final long old_max_known_dm_id = max_known_dm_id;
Log.d(LOG, "parseData started.");
final ArrayList<TimelineElement> all_elements = new ArrayList<TimelineElement>();
long last_id = 0;
// remove empty arrays
for (int i = responses.size() - 1; i >= 0; i--) {
if (responses.get(i).size()==0) {
responses.remove(i);
}
}
while (responses.size() > 0) {
Date newest_date = null;
int newest_index = -1;
for (int i = 0; i < responses.size(); i++) {
TimelineElement element = responses.get(i).get(0);
if (newest_date == null || element.getDate().after(newest_date)) {
newest_date = element.getDate();
newest_index = i;
}
}
TimelineElement element = responses.get(newest_index).remove(0);
if (responses.get(newest_index).size() == 0) {
/* Das primäre Element ist leer. Also brechen wir ab.
* Allerdings muss vorher noch ein bisschen gearbeitet werden... */
responses.remove(newest_index);
if (newest_index == 0) {
if (max_known_tweet_id == 0) {
for (ArrayList<TimelineElement> array : responses) {
TimelineElement first_element = array.get(0);
if (first_element instanceof Tweet && ((Tweet) first_element).id > max_known_tweet_id) {
max_known_tweet_id = ((Tweet)first_element).id;
}
}
}
if (max_known_dm_id==0) {
for (ArrayList<TimelineElement> array : responses) {
TimelineElement first_element = array.get(0);
if (first_element instanceof DirectMessage && first_element.getID() > max_known_dm_id) {
max_known_dm_id = first_element.getID();
}
}
}
Log.d(LOG, "Breaking!");
break;
}
}
long element_id = element.getID();
if (element_id != last_id) {
if (!(element instanceof DirectMessage) || element_id>old_max_known_dm_id) {
all_elements.add(element);
}
}
last_id = element_id;
if (element instanceof Tweet) {
if (element_id > max_known_tweet_id) {
max_known_tweet_id = element_id;
}
if (min_known_tweet_id == -1 || element_id < min_known_tweet_id) {
min_known_tweet_id = element_id;
}
} else if (element instanceof DirectMessage) {
if (element_id > max_known_dm_id) {
max_known_dm_id = element_id;
}
if (min_known_dm_id == -1 || element_id < min_known_dm_id) {
min_known_dm_id = element_id;
}
}
}
Log.d(LOG, "parseData is almost done. " + all_elements.size() + " elements.");
handler.post(new Runnable() {
@Override
public void run() {
elements.addAllAsFirst(all_elements);
}
});
}
| protected void parseData(ArrayList<ArrayList<TimelineElement>> responses, boolean do_clip) {
final long old_max_known_dm_id = max_known_dm_id;
Log.d(LOG, "parseData started.");
final ArrayList<TimelineElement> all_elements = new ArrayList<TimelineElement>();
long last_id = 0;
// remove empty arrays
for (int i = responses.size() - 1; i >= 0; i--) {
if (responses.get(i)==null || responses.get(i).size()==0) {
responses.remove(i);
}
}
while (responses.size() > 0) {
Date newest_date = null;
int newest_index = -1;
for (int i = 0; i < responses.size(); i++) {
TimelineElement element = responses.get(i).get(0);
if (newest_date == null || element.getDate().after(newest_date)) {
newest_date = element.getDate();
newest_index = i;
}
}
TimelineElement element = responses.get(newest_index).remove(0);
if (responses.get(newest_index).size() == 0) {
/* Das primäre Element ist leer. Also brechen wir ab.
* Allerdings muss vorher noch ein bisschen gearbeitet werden... */
responses.remove(newest_index);
if (newest_index == 0) {
if (max_known_tweet_id == 0) {
for (ArrayList<TimelineElement> array : responses) {
TimelineElement first_element = array.get(0);
if (first_element instanceof Tweet && ((Tweet) first_element).id > max_known_tweet_id) {
max_known_tweet_id = ((Tweet)first_element).id;
}
}
}
if (max_known_dm_id==0) {
for (ArrayList<TimelineElement> array : responses) {
TimelineElement first_element = array.get(0);
if (first_element instanceof DirectMessage && first_element.getID() > max_known_dm_id) {
max_known_dm_id = first_element.getID();
}
}
}
Log.d(LOG, "Breaking!");
break;
}
}
long element_id = element.getID();
if (element_id != last_id) {
if (!(element instanceof DirectMessage) || element_id>old_max_known_dm_id) {
all_elements.add(element);
}
}
last_id = element_id;
if (element instanceof Tweet) {
if (element_id > max_known_tweet_id) {
max_known_tweet_id = element_id;
}
if (min_known_tweet_id == -1 || element_id < min_known_tweet_id) {
min_known_tweet_id = element_id;
}
} else if (element instanceof DirectMessage) {
if (element_id > max_known_dm_id) {
max_known_dm_id = element_id;
}
if (min_known_dm_id == -1 || element_id < min_known_dm_id) {
min_known_dm_id = element_id;
}
}
}
Log.d(LOG, "parseData is almost done. " + all_elements.size() + " elements.");
handler.post(new Runnable() {
@Override
public void run() {
elements.addAllAsFirst(all_elements);
}
});
}
|
diff --git a/DefectTracker/src/edu/wpi/cs/wpisuitetng/modules/defecttracker/entitymanagers/DefectManager.java b/DefectTracker/src/edu/wpi/cs/wpisuitetng/modules/defecttracker/entitymanagers/DefectManager.java
index 1d51e008..4b024543 100644
--- a/DefectTracker/src/edu/wpi/cs/wpisuitetng/modules/defecttracker/entitymanagers/DefectManager.java
+++ b/DefectTracker/src/edu/wpi/cs/wpisuitetng/modules/defecttracker/entitymanagers/DefectManager.java
@@ -1,146 +1,147 @@
package edu.wpi.cs.wpisuitetng.modules.defecttracker.entitymanagers;
import java.util.Date;
import java.util.List;
import com.google.gson.Gson;
import edu.wpi.cs.wpisuitetng.Session;
import edu.wpi.cs.wpisuitetng.database.Data;
import edu.wpi.cs.wpisuitetng.exceptions.BadRequestException;
import edu.wpi.cs.wpisuitetng.exceptions.NotFoundException;
import edu.wpi.cs.wpisuitetng.exceptions.WPISuiteException;
import edu.wpi.cs.wpisuitetng.modules.EntityManager;
import edu.wpi.cs.wpisuitetng.modules.core.models.User;
import edu.wpi.cs.wpisuitetng.modules.defecttracker.defect.DefectPanel.Mode;
import edu.wpi.cs.wpisuitetng.modules.defecttracker.models.Defect;
import edu.wpi.cs.wpisuitetng.modules.defecttracker.models.DefectChangeset;
import edu.wpi.cs.wpisuitetng.modules.defecttracker.models.validators.DefectValidator;
import edu.wpi.cs.wpisuitetng.modules.defecttracker.models.validators.ValidationIssue;
/**
* Provides database interaction for Defect models.
*/
public class DefectManager implements EntityManager<Defect> {
Data db;
DefectValidator validator;
ModelMapper updateMapper;
/**
* Create a DefectManager
* @param data The Data instance to use
*/
public DefectManager(Data data) {
db = data;
validator = new DefectValidator(db);
updateMapper = new ModelMapper();
}
@Override
public Defect makeEntity(Session s, String content) throws WPISuiteException {
final Defect newDefect = Defect.fromJSON(content);
// TODO: increment properly, ensure uniqueness using ID generator. This is a gross hack.
newDefect.setId(Count() + 1);
List<ValidationIssue> issues = validator.validate(s, newDefect, Mode.CREATE);
if(issues.size() > 0) {
// TODO: pass errors to client through exception
throw new BadRequestException();
}
if(!db.save(newDefect)) {
throw new WPISuiteException();
}
return newDefect;
}
@Override
public Defect[] getEntity(Session s, String id) throws NotFoundException {
if(id == null || id.equals("")) {
// TODO: getAll should be called from the servlet directly
return getAll(s);
}
final int intId = Integer.parseInt(id);
if(intId < 1) {
throw new NotFoundException();
}
final Defect[] defects = db.retrieve(Defect.class, "id", intId).toArray(new Defect[0]);
if(defects.length < 1 || defects[0] == null) {
throw new NotFoundException();
}
return defects;
}
@Override
public Defect[] getAll(Session s) {
return db.retrieveAll(new Defect()).toArray(new Defect[0]);
}
@Override
public void save(Session s, Defect model) {
// TODO: validate updates
db.save(model);
}
@Override
public boolean deleteEntity(Session s, String id) throws NotFoundException {
// TODO: are nested objects deleted? Dates should be, but Users shouldn't!
return (db.delete(getEntity(s, id)[0]) != null) ? true : false;
}
@Override
public void deleteAll(Session s) {
db.deleteAll(new Defect());
}
@Override
public int Count() {
// TODO: there must be a faster way to do this with db4o
return getAll(null).length;
}
@Override
public Defect update(Session session, String content) throws WPISuiteException {
Defect updatedDefect = Defect.fromJSON(content);
List<ValidationIssue> issues = validator.validate(session, updatedDefect, Mode.EDIT);
if(issues.size() > 0) {
// TODO: pass errors to client through exception
throw new BadRequestException();
}
/*
* Because of the disconnected objects problem in db4o, we can't just save updatedDefect.
* We have to get the original defect from db4o, copy properties from updatedDefect,
* then save the original defect again.
*/
Defect existingDefect = validator.getLastExistingDefect();
Date originalLastModified = existingDefect.getLastModifiedDate();
DefectChangeset changeset = new DefectChangeset();
// core should make sure the session user exists
// if this can't find the user, something's horribly wrong
changeset.setUser((User) db.retrieve(User.class, "username", session.getUsername()).get(0));
ChangesetCallback callback = new ChangesetCallback(changeset);
// copy values to old defect and fill in our changeset appropriately
updateMapper.map(updatedDefect, existingDefect, callback);
if(changeset.getChanges().size() == 0) {
// stupid user didn't even change anything!
// don't bother saving to database, reset last modified date
existingDefect.setLastModifiedDate(originalLastModified);
} else {
// add changeset to Defect events, save to database
existingDefect.getEvents().add(changeset);
- if(!db.save(existingDefect)) {
+ // TODO: events field doesn't persist without explicit save - is this a bug?
+ if(!db.save(existingDefect) || !db.save(existingDefect.getEvents())) {
throw new WPISuiteException();
}
}
return existingDefect;
}
}
| true | true | public Defect update(Session session, String content) throws WPISuiteException {
Defect updatedDefect = Defect.fromJSON(content);
List<ValidationIssue> issues = validator.validate(session, updatedDefect, Mode.EDIT);
if(issues.size() > 0) {
// TODO: pass errors to client through exception
throw new BadRequestException();
}
/*
* Because of the disconnected objects problem in db4o, we can't just save updatedDefect.
* We have to get the original defect from db4o, copy properties from updatedDefect,
* then save the original defect again.
*/
Defect existingDefect = validator.getLastExistingDefect();
Date originalLastModified = existingDefect.getLastModifiedDate();
DefectChangeset changeset = new DefectChangeset();
// core should make sure the session user exists
// if this can't find the user, something's horribly wrong
changeset.setUser((User) db.retrieve(User.class, "username", session.getUsername()).get(0));
ChangesetCallback callback = new ChangesetCallback(changeset);
// copy values to old defect and fill in our changeset appropriately
updateMapper.map(updatedDefect, existingDefect, callback);
if(changeset.getChanges().size() == 0) {
// stupid user didn't even change anything!
// don't bother saving to database, reset last modified date
existingDefect.setLastModifiedDate(originalLastModified);
} else {
// add changeset to Defect events, save to database
existingDefect.getEvents().add(changeset);
if(!db.save(existingDefect)) {
throw new WPISuiteException();
}
}
return existingDefect;
}
| public Defect update(Session session, String content) throws WPISuiteException {
Defect updatedDefect = Defect.fromJSON(content);
List<ValidationIssue> issues = validator.validate(session, updatedDefect, Mode.EDIT);
if(issues.size() > 0) {
// TODO: pass errors to client through exception
throw new BadRequestException();
}
/*
* Because of the disconnected objects problem in db4o, we can't just save updatedDefect.
* We have to get the original defect from db4o, copy properties from updatedDefect,
* then save the original defect again.
*/
Defect existingDefect = validator.getLastExistingDefect();
Date originalLastModified = existingDefect.getLastModifiedDate();
DefectChangeset changeset = new DefectChangeset();
// core should make sure the session user exists
// if this can't find the user, something's horribly wrong
changeset.setUser((User) db.retrieve(User.class, "username", session.getUsername()).get(0));
ChangesetCallback callback = new ChangesetCallback(changeset);
// copy values to old defect and fill in our changeset appropriately
updateMapper.map(updatedDefect, existingDefect, callback);
if(changeset.getChanges().size() == 0) {
// stupid user didn't even change anything!
// don't bother saving to database, reset last modified date
existingDefect.setLastModifiedDate(originalLastModified);
} else {
// add changeset to Defect events, save to database
existingDefect.getEvents().add(changeset);
// TODO: events field doesn't persist without explicit save - is this a bug?
if(!db.save(existingDefect) || !db.save(existingDefect.getEvents())) {
throw new WPISuiteException();
}
}
return existingDefect;
}
|
diff --git a/library/src/com/inqbarna/tablefixheaders/TableFixHeaders.java b/library/src/com/inqbarna/tablefixheaders/TableFixHeaders.java
index 9cfc1fa..5c042ee 100644
--- a/library/src/com/inqbarna/tablefixheaders/TableFixHeaders.java
+++ b/library/src/com/inqbarna/tablefixheaders/TableFixHeaders.java
@@ -1,743 +1,749 @@
package com.inqbarna.tablefixheaders;
import java.util.ArrayList;
import java.util.List;
import com.inqbarna.tablefixheaders.adapters.TableAdapter;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.database.DataSetObserver;
import android.os.Build;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Scroller;
/**
* This view shows a table which can scroll in both directions. Also still
* leaves the headers fixed.
*
* @author Brais Gab�n (InQBarna)
*/
public class TableFixHeaders extends ViewGroup {
private int currentX;
private int currentY;
private TableAdapter adapter;
private int scrollX;
private int scrollY;
private int firstRow;
private int firstColumn;
private int[] widths;
private int[] heights;
@SuppressWarnings("unused")
private View headView;
private List<View> rowViewList;
private List<View> columnViewList;
private List<List<View>> bodyViewTable;
private int rowCount;
private int columnCount;
private int width;
private int height;
private Recycler recycler;
private TableAdapterDataSetObserver tableAdapterDataSetObserver;
private boolean needRelayout;
private final ImageView[] shadows;
private final int shadowSize;
private final int minimumVelocity;
private final int maximumVelocity;
private final Flinger flinger;
private VelocityTracker velocityTracker;
private int touchSlop;
/**
* Simple constructor to use when creating a view from code.
*
* @param context
* The Context the view is running in, through which it can
* access the current theme, resources, etc.
*/
public TableFixHeaders(Context context) {
this(context, null);
}
/**
* Constructor that is called when inflating a view from XML. This is called
* when a view is being constructed from an XML file, supplying attributes
* that were specified in the XML file. This version uses a default style of
* 0, so the only attribute values applied are those in the Context's Theme
* and the given AttributeSet.
*
* The method onFinishInflate() will be called after all children have been
* added.
*
* @param context
* The Context the view is running in, through which it can
* access the current theme, resources, etc.
* @param attrs
* The attributes of the XML tag that is inflating the view.
*/
public TableFixHeaders(Context context, AttributeSet attrs) {
super(context, attrs);
this.headView = null;
this.rowViewList = new ArrayList<View>();
this.columnViewList = new ArrayList<View>();
this.bodyViewTable = new ArrayList<List<View>>();
this.needRelayout = true;
this.shadows = new ImageView[4];
this.shadows[0] = new ImageView(context);
this.shadows[0].setImageResource(R.drawable.shadow_left);
this.shadows[1] = new ImageView(context);
this.shadows[1].setImageResource(R.drawable.shadow_top);
this.shadows[2] = new ImageView(context);
this.shadows[2].setImageResource(R.drawable.shadow_right);
this.shadows[3] = new ImageView(context);
this.shadows[3].setImageResource(R.drawable.shadow_bottom);
this.shadowSize = getResources().getDimensionPixelSize(R.dimen.shadow_size);
this.flinger = new Flinger(context);
final ViewConfiguration configuration = ViewConfiguration.get(context);
this.touchSlop = configuration.getScaledTouchSlop();
this.minimumVelocity = configuration.getScaledMinimumFlingVelocity();
this.maximumVelocity = configuration.getScaledMaximumFlingVelocity();
}
/**
* Returns the adapter currently associated with this widget.
*
* @return The adapter used to provide this view's content.
*/
public TableAdapter getAdapter() {
return adapter;
}
/**
* Sets the data behind this TableFixHeaders.
*
* @param adapter
* The TableAdapter which is responsible for maintaining the data
* backing this list and for producing a view to represent an
* item in that data set.
*/
public void setAdapter(TableAdapter adapter) {
if (this.adapter != null) {
this.adapter.unregisterDataSetObserver(tableAdapterDataSetObserver);
}
this.adapter = adapter;
tableAdapterDataSetObserver = new TableAdapterDataSetObserver();
this.adapter.registerDataSetObserver(tableAdapterDataSetObserver);
this.recycler = new Recycler(adapter.getViewTypeCount());
needRelayout = true;
requestLayout();
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
boolean intercept = false;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
currentX = (int) event.getRawX();
currentY = (int) event.getRawY();
break;
}
case MotionEvent.ACTION_MOVE: {
int x2 = Math.abs(currentX - (int) event.getRawX());
int y2 = Math.abs(currentY - (int) event.getRawY());
if (x2 > touchSlop || y2 > touchSlop) {
intercept = true;
}
break;
}
}
return intercept;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (velocityTracker == null) { // If we do not have velocity tracker
velocityTracker = VelocityTracker.obtain(); // then get one
}
velocityTracker.addMovement(event); // add this movement to it
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
if (!flinger.isFinished()) { // If scrolling, then stop now
flinger.forceFinished();
}
currentX = (int) event.getRawX();
currentY = (int) event.getRawY();
break;
}
case MotionEvent.ACTION_MOVE: {
final int x2 = (int) event.getRawX();
final int y2 = (int) event.getRawY();
final int diffX = currentX - x2;
final int diffY = currentY - y2;
currentX = x2;
currentY = y2;
scrollBy(diffX, diffY);
break;
}
case MotionEvent.ACTION_UP: {
final VelocityTracker velocityTracker = this.velocityTracker;
velocityTracker.computeCurrentVelocity(1000, maximumVelocity);
int velocityX = (int) velocityTracker.getXVelocity();
int velocityY = (int) velocityTracker.getYVelocity();
if (Math.abs(velocityX) > minimumVelocity || Math.abs(velocityY) > minimumVelocity) {
flinger.start(getActualScrollX(), getActualScrollY(), velocityX, velocityY, getMaxScrollX(), getMaxScrollY());
} else {
if (this.velocityTracker != null) { // If the velocity less than threshold
this.velocityTracker.recycle(); // recycle the tracker
this.velocityTracker = null;
}
}
break;
}
}
return true;
}
@Override
public void scrollTo(int x, int y) {
// TODO implement
}
@Override
public void scrollBy(int x, int y) {
+ /**
+ * TODO Improve this function. If the table have an adapter but not
+ * layout I can precalculate the scroll. #10
+ */
+ if (widths != null && heights != null) {
scrollX += x;
scrollY += y;
// scroll bounds
if (scrollX == 0) {
// no op
} else if (scrollX < 0) {
scrollX = Math.max(scrollX, -sumArray(widths, 1, firstColumn));
} else {
scrollX = Math.min(scrollX, sumArray(widths, firstColumn + 1, columnCount - firstColumn) + widths[0] - width);
}
if (scrollY == 0) {
// no op
} else if (scrollY < 0) {
scrollY = Math.max(scrollY, -sumArray(heights, 1, firstRow));
} else {
scrollY = Math.min(scrollY, Math.max(0, sumArray(heights, firstRow + 1, rowCount - firstRow) + heights[0] - height));
}
/*
* TODO Improve the algorithm. Think big diagonal movements. If we are
* in the top left corner and scrollBy to the opposite corner. We will
* have created the views from the top right corner on the X part and we
* will have eliminated to generate the right at the Y.
*/
if (scrollX == 0) {
// no op
} else if (scrollX > 0) {
while (widths[firstColumn + 1] < scrollX) {
if (!rowViewList.isEmpty()) {
removeLeft();
}
scrollX -= widths[firstColumn + 1];
firstColumn++;
}
while (getFilledWidth() < width) {
addRight();
}
} else {
while (!rowViewList.isEmpty() && getFilledWidth() - widths[firstColumn + rowViewList.size() - 1] >= width) {
removeRight();
}
if (rowViewList.isEmpty()) {
while (scrollX < 0) {
firstColumn--;
scrollX += widths[firstColumn + 1];
}
while (getFilledWidth() < width) {
addRight();
}
} else {
while (0 > scrollX) {
addLeft();
firstColumn--;
scrollX += widths[firstColumn + 1];
}
}
}
if (scrollY == 0) {
// no op
} else if (scrollY > 0) {
while (heights[firstRow + 1] < scrollY) {
if (!columnViewList.isEmpty()) {
removeTop();
}
scrollY -= heights[firstRow + 1];
firstRow++;
}
while (getFilledHeight() < height) {
addBottom();
}
} else {
while (!columnViewList.isEmpty() && getFilledHeight() - heights[firstRow + columnViewList.size() - 1] >= height) {
removeBottom();
}
if (columnViewList.isEmpty()) {
while (scrollY < 0) {
firstRow--;
scrollY += heights[firstRow + 1];
}
while (getFilledHeight() < height) {
addBottom();
}
} else {
while (0 > scrollY) {
addTop();
firstRow--;
scrollY += heights[firstRow + 1];
}
}
}
repositionViews();
shadowsVisibility();
+ }
}
public int getActualScrollX() {
return scrollX + sumArray(widths, 1, firstColumn);
}
public int getActualScrollY() {
return scrollY + sumArray(heights, 1, firstRow);
}
private int getMaxScrollX() {
return Math.max(0, sumArray(widths) - width);
}
private int getMaxScrollY() {
return Math.max(0, sumArray(heights) - height);
}
private int getFilledWidth() {
return widths[0] + sumArray(widths, firstColumn + 1, rowViewList.size()) - scrollX;
}
private int getFilledHeight() {
return heights[0] + sumArray(heights, firstRow + 1, columnViewList.size()) - scrollY;
}
private void addLeft() {
addLeftOrRight(firstColumn - 1, 0);
}
private void addTop() {
addTopAndBottom(firstRow - 1, 0);
}
private void addRight() {
final int size = rowViewList.size();
addLeftOrRight(firstColumn + size, size);
}
private void addBottom() {
final int size = columnViewList.size();
addTopAndBottom(firstRow + size, size);
}
private void addLeftOrRight(int column, int index) {
View view = makeView(-1, column, widths[column + 1], heights[0]);
rowViewList.add(index, view);
int i = firstRow;
for (List<View> list : bodyViewTable) {
view = makeView(i, column, widths[column + 1], heights[i + 1]);
list.add(index, view);
i++;
}
}
private void addTopAndBottom(int row, int index) {
View view = makeView(row, -1, widths[0], heights[row + 1]);
columnViewList.add(index, view);
List<View> list = new ArrayList<View>();
final int size = rowViewList.size() + firstColumn;
for (int i = firstColumn; i < size; i++) {
view = makeView(row, i, widths[i + 1], heights[row + 1]);
list.add(view);
}
bodyViewTable.add(index, list);
}
private void removeLeft() {
removeLeftOrRight(0);
}
private void removeTop() {
removeTopOrBottom(0);
}
private void removeRight() {
removeLeftOrRight(rowViewList.size() - 1);
}
private void removeBottom() {
removeTopOrBottom(columnViewList.size() - 1);
}
private void removeLeftOrRight(int position) {
removeView(rowViewList.remove(position));
for (List<View> list : bodyViewTable) {
removeView(list.remove(position));
}
}
private void removeTopOrBottom(int position) {
removeView(columnViewList.remove(position));
List<View> remove = bodyViewTable.remove(position);
for (View view : remove) {
removeView(view);
}
}
@Override
public void removeView(View view) {
super.removeView(view);
final int typeView = (Integer) view.getTag(R.id.tag_type_view);
if (typeView != TableAdapter.IGNORE_ITEM_VIEW_TYPE) {
recycler.addRecycledView(view, typeView);
}
}
private void repositionViews() {
int left, top, right, bottom, i;
left = widths[0] - scrollX;
i = firstColumn;
for (View view : rowViewList) {
right = left + widths[++i];
view.layout(left, 0, right, heights[0]);
left = right;
}
top = heights[0] - scrollY;
i = firstRow;
for (View view : columnViewList) {
bottom = top + heights[++i];
view.layout(0, top, widths[0], bottom);
top = bottom;
}
top = heights[0] - scrollY;
i = firstRow;
for (List<View> list : bodyViewTable) {
bottom = top + heights[++i];
left = widths[0] - scrollX;
int j = firstColumn;
for (View view : list) {
right = left + widths[++j];
view.layout(left, top, right, bottom);
left = right;
}
top = bottom;
}
invalidate();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
final int widthSize = MeasureSpec.getSize(widthMeasureSpec);
final int heightSize = MeasureSpec.getSize(heightMeasureSpec);
final int w;
final int h;
if (adapter != null) {
this.rowCount = adapter.getRowCount();
this.columnCount = adapter.getColumnCount();
widths = new int[columnCount + 1];
for (int i = -1; i < columnCount; i++) {
widths[i + 1] += adapter.getWidth(i);
}
heights = new int[rowCount + 1];
for (int i = -1; i < rowCount; i++) {
heights[i + 1] += adapter.getHeight(i);
}
if (widthMode == MeasureSpec.AT_MOST) {
w = Math.min(widthSize, sumArray(widths));
} else if (widthMode == MeasureSpec.UNSPECIFIED) {
w = sumArray(widths);
} else {
w = widthSize;
int sumArray = sumArray(widths);
if (sumArray < widthSize) {
final float factor = widthSize / (float) sumArray;
for (int i = 1; i < widths.length; i++) {
widths[i] = Math.round(widths[i] * factor);
}
widths[0] = widthSize - sumArray(widths, 1, widths.length - 1);
}
}
if (heightMode == MeasureSpec.AT_MOST) {
h = Math.min(heightSize, sumArray(heights));
} else if (heightMode == MeasureSpec.UNSPECIFIED) {
h = sumArray(heights);
} else {
h = heightSize;
}
} else {
if (heightMode == MeasureSpec.AT_MOST || widthMode == MeasureSpec.UNSPECIFIED) {
w = 0;
h = 0;
} else {
w = widthSize;
h = heightSize;
}
}
setMeasuredDimension(w, h);
}
private int sumArray(int array[]) {
return sumArray(array, 0, array.length);
}
private int sumArray(int array[], int firstIndex, int count) {
int sum = 0;
count += firstIndex;
for (int i = firstIndex; i < count; i++) {
sum += array[i];
}
return sum;
}
@SuppressLint("DrawAllocation")
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
if (needRelayout || changed) {
needRelayout = false;
resetTable();
if (adapter != null) {
width = r - l;
height = b - t;
int left, top, right, bottom;
right = Math.min(width, sumArray(widths));
bottom = Math.min(height, sumArray(heights));
addShadow(shadows[0], widths[0], 0, widths[0] + shadowSize, bottom);
addShadow(shadows[1], 0, heights[0], right, heights[0] + shadowSize);
addShadow(shadows[2], right - shadowSize, 0, right, bottom);
addShadow(shadows[3], 0, bottom - shadowSize, right, bottom);
headView = makeAndSetup(-1, -1, 0, 0, widths[0], heights[0]);
left = widths[0] - scrollX;
for (int i = firstColumn; i < columnCount && left < width; i++) {
right = left + widths[i + 1];
final View view = makeAndSetup(-1, i, left, 0, right, heights[0]);
rowViewList.add(view);
left = right;
}
top = heights[0] - scrollY;
for (int i = firstRow; i < rowCount && top < height; i++) {
bottom = top + heights[i + 1];
final View view = makeAndSetup(i, -1, 0, top, widths[0], bottom);
columnViewList.add(view);
top = bottom;
}
top = heights[0] - scrollY;
for (int i = firstRow; i < rowCount && top < height; i++) {
bottom = top + heights[i + 1];
left = widths[0] - scrollX;
List<View> list = new ArrayList<View>();
for (int j = firstColumn; j < columnCount && left < width; j++) {
right = left + widths[j + 1];
final View view = makeAndSetup(i, j, left, top, right, bottom);
list.add(view);
left = right;
}
bodyViewTable.add(list);
top = bottom;
}
shadowsVisibility();
}
}
}
private void shadowsVisibility() {
final int actualScrollX = getActualScrollX();
final int actualScrollY = getActualScrollY();
final int[] remainPixels = {
actualScrollX,
actualScrollY,
getMaxScrollX() - actualScrollX,
getMaxScrollY() - actualScrollY,
};
for (int i = 0; i < shadows.length; i++) {
setAlpha(shadows[i], Math.min(remainPixels[i] / (float) shadowSize, 1));
}
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@SuppressWarnings("deprecation")
private void setAlpha(ImageView imageView, float alpha) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
imageView.setAlpha(alpha);
} else {
imageView.setAlpha(Math.round(alpha * 255));
}
}
private void addShadow(ImageView imageView, int l, int t, int r, int b) {
imageView.layout(l, t, r, b);
addView(imageView);
}
private void resetTable() {
headView = null;
rowViewList.clear();
columnViewList.clear();
bodyViewTable.clear();
removeAllViews();
this.firstRow = 0;
this.firstColumn = 0;
this.scrollX = 0;
this.scrollY = 0;
}
private View makeAndSetup(int row, int column, int left, int top, int right, int bottom) {
final View view = makeView(row, column, right - left, bottom - top);
view.layout(left, top, right, bottom);
return view;
}
private View makeView(int row, int column, int w, int h) {
final int itemViewType = adapter.getItemViewType(row, column);
final View recycledView;
if (itemViewType == TableAdapter.IGNORE_ITEM_VIEW_TYPE) {
recycledView = null;
} else {
recycledView = recycler.getRecycledView(itemViewType);
}
final View view = adapter.getView(row, column, recycledView, this);
view.setTag(R.id.tag_type_view, itemViewType);
view.measure(MeasureSpec.makeMeasureSpec(w, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(h, MeasureSpec.EXACTLY));
addTableView(view, row, column);
return view;
}
private void addTableView(View view, int row, int column) {
if (row == -1 && column == -1) {
addView(view, getChildCount() - 4);
} else if (row == -1 || column == -1) {
addView(view, getChildCount() - 5);
} else {
addView(view, 0);
}
}
private class TableAdapterDataSetObserver extends DataSetObserver {
@Override
public void onChanged() {
needRelayout = true;
requestLayout();
}
@Override
public void onInvalidated() {
// Do nothing
}
}
// http://stackoverflow.com/a/6219382/842697
private class Flinger implements Runnable {
private final Scroller scroller;
private int lastX = 0;
private int lastY = 0;
Flinger(Context context) {
scroller = new Scroller(context);
}
void start(int initX, int initY, int initialVelocityX, int initialVelocityY, int maxX, int maxY) {
scroller.fling(initX, initY, initialVelocityX, initialVelocityY, 0, maxX, 0, maxY);
lastX = initX;
lastY = initY;
post(this);
}
public void run() {
if (scroller.isFinished()) {
return;
}
boolean more = scroller.computeScrollOffset();
int x = scroller.getCurrX();
int y = scroller.getCurrY();
int diffX = lastX - x;
int diffY = lastY - y;
if (diffX != 0 || diffY != 0) {
scrollBy(diffX, diffY);
lastX = x;
lastY = y;
}
if (more) {
post(this);
}
}
boolean isFinished() {
return scroller.isFinished();
}
void forceFinished() {
if (!scroller.isFinished()) {
scroller.forceFinished(true);
}
}
}
}
| false | true | public void scrollBy(int x, int y) {
scrollX += x;
scrollY += y;
// scroll bounds
if (scrollX == 0) {
// no op
} else if (scrollX < 0) {
scrollX = Math.max(scrollX, -sumArray(widths, 1, firstColumn));
} else {
scrollX = Math.min(scrollX, sumArray(widths, firstColumn + 1, columnCount - firstColumn) + widths[0] - width);
}
if (scrollY == 0) {
// no op
} else if (scrollY < 0) {
scrollY = Math.max(scrollY, -sumArray(heights, 1, firstRow));
} else {
scrollY = Math.min(scrollY, Math.max(0, sumArray(heights, firstRow + 1, rowCount - firstRow) + heights[0] - height));
}
/*
* TODO Improve the algorithm. Think big diagonal movements. If we are
* in the top left corner and scrollBy to the opposite corner. We will
* have created the views from the top right corner on the X part and we
* will have eliminated to generate the right at the Y.
*/
if (scrollX == 0) {
// no op
} else if (scrollX > 0) {
while (widths[firstColumn + 1] < scrollX) {
if (!rowViewList.isEmpty()) {
removeLeft();
}
scrollX -= widths[firstColumn + 1];
firstColumn++;
}
while (getFilledWidth() < width) {
addRight();
}
} else {
while (!rowViewList.isEmpty() && getFilledWidth() - widths[firstColumn + rowViewList.size() - 1] >= width) {
removeRight();
}
if (rowViewList.isEmpty()) {
while (scrollX < 0) {
firstColumn--;
scrollX += widths[firstColumn + 1];
}
while (getFilledWidth() < width) {
addRight();
}
} else {
while (0 > scrollX) {
addLeft();
firstColumn--;
scrollX += widths[firstColumn + 1];
}
}
}
if (scrollY == 0) {
// no op
} else if (scrollY > 0) {
while (heights[firstRow + 1] < scrollY) {
if (!columnViewList.isEmpty()) {
removeTop();
}
scrollY -= heights[firstRow + 1];
firstRow++;
}
while (getFilledHeight() < height) {
addBottom();
}
} else {
while (!columnViewList.isEmpty() && getFilledHeight() - heights[firstRow + columnViewList.size() - 1] >= height) {
removeBottom();
}
if (columnViewList.isEmpty()) {
while (scrollY < 0) {
firstRow--;
scrollY += heights[firstRow + 1];
}
while (getFilledHeight() < height) {
addBottom();
}
} else {
while (0 > scrollY) {
addTop();
firstRow--;
scrollY += heights[firstRow + 1];
}
}
}
repositionViews();
shadowsVisibility();
}
| public void scrollBy(int x, int y) {
/**
* TODO Improve this function. If the table have an adapter but not
* layout I can precalculate the scroll. #10
*/
if (widths != null && heights != null) {
scrollX += x;
scrollY += y;
// scroll bounds
if (scrollX == 0) {
// no op
} else if (scrollX < 0) {
scrollX = Math.max(scrollX, -sumArray(widths, 1, firstColumn));
} else {
scrollX = Math.min(scrollX, sumArray(widths, firstColumn + 1, columnCount - firstColumn) + widths[0] - width);
}
if (scrollY == 0) {
// no op
} else if (scrollY < 0) {
scrollY = Math.max(scrollY, -sumArray(heights, 1, firstRow));
} else {
scrollY = Math.min(scrollY, Math.max(0, sumArray(heights, firstRow + 1, rowCount - firstRow) + heights[0] - height));
}
/*
* TODO Improve the algorithm. Think big diagonal movements. If we are
* in the top left corner and scrollBy to the opposite corner. We will
* have created the views from the top right corner on the X part and we
* will have eliminated to generate the right at the Y.
*/
if (scrollX == 0) {
// no op
} else if (scrollX > 0) {
while (widths[firstColumn + 1] < scrollX) {
if (!rowViewList.isEmpty()) {
removeLeft();
}
scrollX -= widths[firstColumn + 1];
firstColumn++;
}
while (getFilledWidth() < width) {
addRight();
}
} else {
while (!rowViewList.isEmpty() && getFilledWidth() - widths[firstColumn + rowViewList.size() - 1] >= width) {
removeRight();
}
if (rowViewList.isEmpty()) {
while (scrollX < 0) {
firstColumn--;
scrollX += widths[firstColumn + 1];
}
while (getFilledWidth() < width) {
addRight();
}
} else {
while (0 > scrollX) {
addLeft();
firstColumn--;
scrollX += widths[firstColumn + 1];
}
}
}
if (scrollY == 0) {
// no op
} else if (scrollY > 0) {
while (heights[firstRow + 1] < scrollY) {
if (!columnViewList.isEmpty()) {
removeTop();
}
scrollY -= heights[firstRow + 1];
firstRow++;
}
while (getFilledHeight() < height) {
addBottom();
}
} else {
while (!columnViewList.isEmpty() && getFilledHeight() - heights[firstRow + columnViewList.size() - 1] >= height) {
removeBottom();
}
if (columnViewList.isEmpty()) {
while (scrollY < 0) {
firstRow--;
scrollY += heights[firstRow + 1];
}
while (getFilledHeight() < height) {
addBottom();
}
} else {
while (0 > scrollY) {
addTop();
firstRow--;
scrollY += heights[firstRow + 1];
}
}
}
repositionViews();
shadowsVisibility();
}
}
|
diff --git a/messageforums-component-impl/src/java/org/sakaiproject/component/app/messageforums/MembershipManagerImpl.java b/messageforums-component-impl/src/java/org/sakaiproject/component/app/messageforums/MembershipManagerImpl.java
index f8bf26a5..441345dd 100644
--- a/messageforums-component-impl/src/java/org/sakaiproject/component/app/messageforums/MembershipManagerImpl.java
+++ b/messageforums-component-impl/src/java/org/sakaiproject/component/app/messageforums/MembershipManagerImpl.java
@@ -1,402 +1,395 @@
/**********************************************************************************
* $URL: https://source.sakaiproject.org/svn/msgcntr/trunk/messageforums-component-impl/src/java/org/sakaiproject/component/app/messageforums/MembershipManagerImpl.java $
* $Id: MembershipManagerImpl.java 9227 2006-05-15 15:02:42Z [email protected] $
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006 The Sakai Foundation.
*
* Licensed under the Educational Community License, Version 1.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl1.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
package org.sakaiproject.component.app.messageforums;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.api.app.messageforums.MembershipManager;
import org.sakaiproject.api.common.edu.person.SakaiPerson;
import org.sakaiproject.api.common.edu.person.SakaiPersonManager;
import org.sakaiproject.api.privacy.PrivacyManager;
import org.sakaiproject.authz.api.AuthzGroup;
import org.sakaiproject.authz.api.AuthzGroupService;
import org.sakaiproject.authz.api.GroupNotDefinedException;
import org.sakaiproject.authz.api.Member;
import org.sakaiproject.authz.api.Role;
import org.sakaiproject.authz.api.SecurityService;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.site.api.Group;
import org.sakaiproject.site.api.Site;
import org.sakaiproject.site.api.SiteService;
import org.sakaiproject.tool.api.ToolManager;
import org.sakaiproject.user.api.User;
import org.sakaiproject.user.api.UserDirectoryService;
import org.sakaiproject.user.api.UserNotDefinedException;
public class MembershipManagerImpl implements MembershipManager{
private static final Log LOG = LogFactory.getLog(MembershipManagerImpl.class);
private SiteService siteService;
private UserDirectoryService userDirectoryService;
private SakaiPersonManager sakaiPersonManager;
private AuthzGroupService authzGroupService;
private ToolManager toolManager;
private SecurityService securityService;
private PrivacyManager privacyManager;
public void init() {
;
}
/**
*
* @param privacyManager
*/
public void setPrivacyManager(PrivacyManager privacyManager)
{
this.privacyManager = privacyManager;
}
/**
* sets users' privacy status so can be filtered out
*
* @param allCourseUsers - used to get user ids so can call PrivacyManager
* @param courseUserMap - map of all course users
*
* @return Map of all course users with privacy status set
*/
private Map filterByPrivacyManager(List allCourseUsers, Map courseUserMap) {
List userIds = new ArrayList();
Map results = new HashMap();
Collection userCollection = courseUserMap.values();
for (Iterator usersIter = allCourseUsers.iterator(); usersIter.hasNext();) {
MembershipItem memberItem = (MembershipItem) usersIter.next();
if (memberItem.getUser() != null) {
userIds.add(memberItem.getUser().getId());
}
}
// set privacy status
Set memberSet = null;
memberSet = privacyManager.findViewable(
("/site/" + toolManager.getCurrentPlacement().getContext()), new HashSet(userIds));
/** look through the members again to pick out Member objects corresponding
to only those who are visible (as well as current user) */
for (Iterator userIterator = userCollection.iterator(); userIterator.hasNext();) {
MembershipItem memberItem = (MembershipItem) userIterator.next();
if (memberItem.getUser() != null) {
memberItem.setViewable(memberSet.contains(memberItem.getUser().getId()));
}
else {
// want groups to be displayed
memberItem.setViewable(true);
}
results.put(memberItem.getId(), memberItem);
}
return results;
}
/**
* @see org.sakaiproject.api.app.messageforums.MembershipManager#getFilteredCourseMembers(boolean)
*/
public Map getFilteredCourseMembers(boolean filterFerpa){
List allCourseUsers = getAllCourseUsers();
Set membershipRoleSet = new HashSet();
/** generate set of roles which has members */
for (Iterator i = allCourseUsers.iterator(); i.hasNext();){
MembershipItem item = (MembershipItem) i.next();
if (item.getRole() != null){
membershipRoleSet.add(item.getRole());
}
}
/** filter member map */
Map memberMap = getAllCourseMembers(filterFerpa, true, true);
if (filterFerpa) {
memberMap = filterByPrivacyManager(allCourseUsers, memberMap);
}
for (Iterator i = memberMap.entrySet().iterator(); i.hasNext();){
Map.Entry entry = (Map.Entry) i.next();
MembershipItem item = (MembershipItem) entry.getValue();
if (MembershipItem.TYPE_ROLE.equals(item.getType())){
/** if no member belongs to role, filter role */
if (!membershipRoleSet.contains(item.getRole())){
i.remove();
}
}
else if (MembershipItem.TYPE_GROUP.equals(item.getType())){
/** if no member belongs to group, filter group */
if (item.getGroup().getMembers().size() == 0){
i.remove();
}
}
else{
;
}
}
return memberMap;
}
/**
* @see org.sakaiproject.api.app.messageforums.MembershipManager#getAllCourseMembers(boolean, boolean, boolean)
*/
public Map getAllCourseMembers(boolean filterFerpa, boolean includeRoles, boolean includeAllParticipantsMember)
{
Map returnMap = new HashMap();
String realmId = getContextSiteId();
Site currentSite = null;
/** add all participants */
if (includeAllParticipantsMember){
MembershipItem memberAll = MembershipItem.getInstance();
memberAll.setType(MembershipItem.TYPE_ALL_PARTICIPANTS);
memberAll.setName(MembershipItem.ALL_PARTICIPANTS_DESC);
returnMap.put(memberAll.getId(), memberAll);
}
AuthzGroup realm = null;
try{
realm = authzGroupService.getAuthzGroup(realmId);
currentSite = siteService.getSite(toolManager.getCurrentPlacement().getContext());
}
catch (IdUnusedException e){
LOG.debug(e.getMessage(), e);
return returnMap;
} catch (GroupNotDefinedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/** handle groups */
Collection groups = currentSite.getGroups();
for (Iterator groupIterator = groups.iterator(); groupIterator.hasNext();){
Group currentGroup = (Group) groupIterator.next();
MembershipItem member = MembershipItem.getInstance();
member.setType(MembershipItem.TYPE_GROUP);
member.setName(currentGroup.getTitle() + " Group");
member.setGroup(currentGroup);
returnMap.put(member.getId(), member);
}
/** handle roles */
if (includeRoles && realm != null){
Set roles = realm.getRoles();
for (Iterator roleIterator = roles.iterator(); roleIterator.hasNext();){
Role role = (Role) roleIterator.next();
MembershipItem member = MembershipItem.getInstance();
member.setType(MembershipItem.TYPE_ROLE);
String roleId = role.getId();
if (roleId != null && roleId.length() > 0){
roleId = roleId.substring(0,1).toUpperCase() + roleId.substring(1);
}
member.setName(roleId + " Role");
member.setRole(role);
returnMap.put(member.getId(), member);
}
}
/** handle users */
Set users = realm.getMembers();
/** create our HashSet of user ids */
for (Iterator userIterator = users.iterator(); userIterator.hasNext();){
Member member = (Member) userIterator.next();
String userId = member.getUserId();
Role userRole = member.getRole();
User user = null;
try{
if(realm.getMember(userId) != null && realm.getMember(userId).isActive())
{
user = userDirectoryService.getUser(userId);
}
} catch (UserNotDefinedException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
LOG.warn(" User " + userId + " not defined");
}
if(user != null)
{
MembershipItem memberItem = MembershipItem.getInstance();
memberItem.setType(MembershipItem.TYPE_USER);
memberItem.setName(user.getSortName());
memberItem.setUser(user);
memberItem.setRole(userRole);
if(!(userId).equals("admin"))
{
if (filterFerpa){
- List personList = sakaiPersonManager.findSakaiPersonByUid(userId);
boolean ferpa_flag = false;
- for (Iterator iter = personList.iterator(); iter.hasNext();)
- {
- SakaiPerson element = (SakaiPerson) iter.next();
- if (Boolean.TRUE.equals(element.getFerpaEnabled())){
- ferpa_flag = true;
- }
- }
+ ferpa_flag = !privacyManager.isViewable(getContextSiteId(), userId);
if (!ferpa_flag || securityService.unlock(memberItem.getUser(),
SiteService.SECURE_UPDATE_SITE,
getContextSiteId())
|| securityService.unlock(userDirectoryService.getCurrentUser(),
SiteService.SECURE_UPDATE_SITE,
getContextSiteId())
){
returnMap.put(memberItem.getId(), memberItem);
}
}
else{
returnMap.put(memberItem.getId(), memberItem);
}
}
}
}
return returnMap;
}
/**
* @see org.sakaiproject.api.app.messageforums.MembershipManager#getAllCourseUsers()
*/
public List getAllCourseUsers()
{
Map userMap = new HashMap();
String realmId = getContextSiteId();
AuthzGroup realm = null;
try{
realm = authzGroupService.getAuthzGroup(realmId);
} catch (GroupNotDefinedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/** handle users */
Set users = realm.getMembers();
for (Iterator userIterator = users.iterator(); userIterator.hasNext();){
Member member = (Member) userIterator.next();
String userId = member.getUserId();
Role userRole = member.getRole();
User user = null;
try{
if(realm.getMember(userId) != null && realm.getMember(userId).isActive())
{
user = userDirectoryService.getUser(userId);
}
} catch (UserNotDefinedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(user != null)
{
MembershipItem memberItem = MembershipItem.getInstance();
memberItem.setType(MembershipItem.TYPE_USER);
memberItem.setName(user.getSortName());
memberItem.setUser(user);
memberItem.setRole(userRole);
if(!(userId).equals("admin"))
{
userMap.put(memberItem.getId(), memberItem);
}
}
}
return convertMemberMapToList(userMap);
}
/**
* @see org.sakaiproject.api.app.messageforums.MembershipManager#convertMemberMapToList(java.util.Map)
*/
public List convertMemberMapToList(Map memberMap){
MembershipItem[] membershipArray = new MembershipItem[memberMap.size()];
membershipArray = (MembershipItem[]) memberMap.values().toArray(membershipArray);
Arrays.sort(membershipArray);
return Arrays.asList(membershipArray);
}
/**
* get site reference
* @return siteId
*/
public String getContextSiteId()
{
return ("/site/" + toolManager.getCurrentPlacement().getContext());
}
/** setters */
public void setSiteService(SiteService siteService)
{
this.siteService = siteService;
}
public void setSakaiPersonManager(SakaiPersonManager sakaiPersonManager)
{
this.sakaiPersonManager = sakaiPersonManager;
}
public void setUserDirectoryService(UserDirectoryService userDirectoryService)
{
this.userDirectoryService = userDirectoryService;
}
public void setAuthzGroupService(AuthzGroupService authzGroupService)
{
this.authzGroupService = authzGroupService;
}
public void setToolManager(ToolManager toolManager)
{
this.toolManager = toolManager;
}
public void setSecurityService(SecurityService securityService)
{
this.securityService = securityService;
}
}
| false | true | public Map getAllCourseMembers(boolean filterFerpa, boolean includeRoles, boolean includeAllParticipantsMember)
{
Map returnMap = new HashMap();
String realmId = getContextSiteId();
Site currentSite = null;
/** add all participants */
if (includeAllParticipantsMember){
MembershipItem memberAll = MembershipItem.getInstance();
memberAll.setType(MembershipItem.TYPE_ALL_PARTICIPANTS);
memberAll.setName(MembershipItem.ALL_PARTICIPANTS_DESC);
returnMap.put(memberAll.getId(), memberAll);
}
AuthzGroup realm = null;
try{
realm = authzGroupService.getAuthzGroup(realmId);
currentSite = siteService.getSite(toolManager.getCurrentPlacement().getContext());
}
catch (IdUnusedException e){
LOG.debug(e.getMessage(), e);
return returnMap;
} catch (GroupNotDefinedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/** handle groups */
Collection groups = currentSite.getGroups();
for (Iterator groupIterator = groups.iterator(); groupIterator.hasNext();){
Group currentGroup = (Group) groupIterator.next();
MembershipItem member = MembershipItem.getInstance();
member.setType(MembershipItem.TYPE_GROUP);
member.setName(currentGroup.getTitle() + " Group");
member.setGroup(currentGroup);
returnMap.put(member.getId(), member);
}
/** handle roles */
if (includeRoles && realm != null){
Set roles = realm.getRoles();
for (Iterator roleIterator = roles.iterator(); roleIterator.hasNext();){
Role role = (Role) roleIterator.next();
MembershipItem member = MembershipItem.getInstance();
member.setType(MembershipItem.TYPE_ROLE);
String roleId = role.getId();
if (roleId != null && roleId.length() > 0){
roleId = roleId.substring(0,1).toUpperCase() + roleId.substring(1);
}
member.setName(roleId + " Role");
member.setRole(role);
returnMap.put(member.getId(), member);
}
}
/** handle users */
Set users = realm.getMembers();
/** create our HashSet of user ids */
for (Iterator userIterator = users.iterator(); userIterator.hasNext();){
Member member = (Member) userIterator.next();
String userId = member.getUserId();
Role userRole = member.getRole();
User user = null;
try{
if(realm.getMember(userId) != null && realm.getMember(userId).isActive())
{
user = userDirectoryService.getUser(userId);
}
} catch (UserNotDefinedException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
LOG.warn(" User " + userId + " not defined");
}
if(user != null)
{
MembershipItem memberItem = MembershipItem.getInstance();
memberItem.setType(MembershipItem.TYPE_USER);
memberItem.setName(user.getSortName());
memberItem.setUser(user);
memberItem.setRole(userRole);
if(!(userId).equals("admin"))
{
if (filterFerpa){
List personList = sakaiPersonManager.findSakaiPersonByUid(userId);
boolean ferpa_flag = false;
for (Iterator iter = personList.iterator(); iter.hasNext();)
{
SakaiPerson element = (SakaiPerson) iter.next();
if (Boolean.TRUE.equals(element.getFerpaEnabled())){
ferpa_flag = true;
}
}
if (!ferpa_flag || securityService.unlock(memberItem.getUser(),
SiteService.SECURE_UPDATE_SITE,
getContextSiteId())
|| securityService.unlock(userDirectoryService.getCurrentUser(),
SiteService.SECURE_UPDATE_SITE,
getContextSiteId())
){
returnMap.put(memberItem.getId(), memberItem);
}
}
else{
returnMap.put(memberItem.getId(), memberItem);
}
}
}
}
return returnMap;
}
| public Map getAllCourseMembers(boolean filterFerpa, boolean includeRoles, boolean includeAllParticipantsMember)
{
Map returnMap = new HashMap();
String realmId = getContextSiteId();
Site currentSite = null;
/** add all participants */
if (includeAllParticipantsMember){
MembershipItem memberAll = MembershipItem.getInstance();
memberAll.setType(MembershipItem.TYPE_ALL_PARTICIPANTS);
memberAll.setName(MembershipItem.ALL_PARTICIPANTS_DESC);
returnMap.put(memberAll.getId(), memberAll);
}
AuthzGroup realm = null;
try{
realm = authzGroupService.getAuthzGroup(realmId);
currentSite = siteService.getSite(toolManager.getCurrentPlacement().getContext());
}
catch (IdUnusedException e){
LOG.debug(e.getMessage(), e);
return returnMap;
} catch (GroupNotDefinedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/** handle groups */
Collection groups = currentSite.getGroups();
for (Iterator groupIterator = groups.iterator(); groupIterator.hasNext();){
Group currentGroup = (Group) groupIterator.next();
MembershipItem member = MembershipItem.getInstance();
member.setType(MembershipItem.TYPE_GROUP);
member.setName(currentGroup.getTitle() + " Group");
member.setGroup(currentGroup);
returnMap.put(member.getId(), member);
}
/** handle roles */
if (includeRoles && realm != null){
Set roles = realm.getRoles();
for (Iterator roleIterator = roles.iterator(); roleIterator.hasNext();){
Role role = (Role) roleIterator.next();
MembershipItem member = MembershipItem.getInstance();
member.setType(MembershipItem.TYPE_ROLE);
String roleId = role.getId();
if (roleId != null && roleId.length() > 0){
roleId = roleId.substring(0,1).toUpperCase() + roleId.substring(1);
}
member.setName(roleId + " Role");
member.setRole(role);
returnMap.put(member.getId(), member);
}
}
/** handle users */
Set users = realm.getMembers();
/** create our HashSet of user ids */
for (Iterator userIterator = users.iterator(); userIterator.hasNext();){
Member member = (Member) userIterator.next();
String userId = member.getUserId();
Role userRole = member.getRole();
User user = null;
try{
if(realm.getMember(userId) != null && realm.getMember(userId).isActive())
{
user = userDirectoryService.getUser(userId);
}
} catch (UserNotDefinedException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
LOG.warn(" User " + userId + " not defined");
}
if(user != null)
{
MembershipItem memberItem = MembershipItem.getInstance();
memberItem.setType(MembershipItem.TYPE_USER);
memberItem.setName(user.getSortName());
memberItem.setUser(user);
memberItem.setRole(userRole);
if(!(userId).equals("admin"))
{
if (filterFerpa){
boolean ferpa_flag = false;
ferpa_flag = !privacyManager.isViewable(getContextSiteId(), userId);
if (!ferpa_flag || securityService.unlock(memberItem.getUser(),
SiteService.SECURE_UPDATE_SITE,
getContextSiteId())
|| securityService.unlock(userDirectoryService.getCurrentUser(),
SiteService.SECURE_UPDATE_SITE,
getContextSiteId())
){
returnMap.put(memberItem.getId(), memberItem);
}
}
else{
returnMap.put(memberItem.getId(), memberItem);
}
}
}
}
return returnMap;
}
|
diff --git a/src/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java b/src/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java
index 0f505316f..9a524234f 100644
--- a/src/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java
+++ b/src/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java
@@ -1,1859 +1,1865 @@
/**
* Copyright 2007 The Apache Software Foundation
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.regionserver;
import java.io.IOException;
import java.lang.Thread.UncaughtExceptionHandler;
import java.lang.reflect.Constructor;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HMsg;
import org.apache.hadoop.hbase.HRegionInfo;
import org.apache.hadoop.hbase.HRegionLocation;
import org.apache.hadoop.hbase.HServerAddress;
import org.apache.hadoop.hbase.HServerInfo;
import org.apache.hadoop.hbase.HServerLoad;
import org.apache.hadoop.hbase.HStoreKey;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.LeaseListener;
import org.apache.hadoop.hbase.Leases;
import org.apache.hadoop.hbase.LocalHBaseCluster;
import org.apache.hadoop.hbase.NotServingRegionException;
import org.apache.hadoop.hbase.RegionHistorian;
import org.apache.hadoop.hbase.RemoteExceptionHandler;
import org.apache.hadoop.hbase.UnknownScannerException;
import org.apache.hadoop.hbase.UnknownRowLockException;
import org.apache.hadoop.hbase.ValueOverMaxLengthException;
import org.apache.hadoop.hbase.Leases.LeaseStillHeldException;
import org.apache.hadoop.hbase.client.ServerConnection;
import org.apache.hadoop.hbase.client.ServerConnectionManager;
import org.apache.hadoop.hbase.filter.RowFilterInterface;
import org.apache.hadoop.hbase.io.BatchOperation;
import org.apache.hadoop.hbase.io.BatchUpdate;
import org.apache.hadoop.hbase.io.Cell;
import org.apache.hadoop.hbase.io.HbaseMapWritable;
import org.apache.hadoop.hbase.io.RowResult;
import org.apache.hadoop.hbase.ipc.HMasterRegionInterface;
import org.apache.hadoop.hbase.ipc.HRegionInterface;
import org.apache.hadoop.hbase.ipc.HbaseRPC;
import org.apache.hadoop.hbase.regionserver.metrics.RegionServerMetrics;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.FSUtils;
import org.apache.hadoop.hbase.util.InfoServer;
import org.apache.hadoop.hbase.util.Sleeper;
import org.apache.hadoop.hbase.util.Threads;
import org.apache.hadoop.io.MapWritable;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.ipc.Server;
import org.apache.hadoop.util.Progressable;
import org.apache.hadoop.util.StringUtils;
/**
* HRegionServer makes a set of HRegions available to clients. It checks in with
* the HMaster. There are many HRegionServers in a single HBase deployment.
*/
public class HRegionServer implements HConstants, HRegionInterface, Runnable {
static final Log LOG = LogFactory.getLog(HRegionServer.class);
// Set when a report to the master comes back with a message asking us to
// shutdown. Also set by call to stop when debugging or running unit tests
// of HRegionServer in isolation. We use AtomicBoolean rather than
// plain boolean so we can pass a reference to Chore threads. Otherwise,
// Chore threads need to know about the hosting class.
protected final AtomicBoolean stopRequested = new AtomicBoolean(false);
protected final AtomicBoolean quiesced = new AtomicBoolean(false);
// Go down hard. Used if file system becomes unavailable and also in
// debugging and unit tests.
protected volatile boolean abortRequested;
// If false, the file system has become unavailable
protected volatile boolean fsOk;
protected final HServerInfo serverInfo;
protected final HBaseConfiguration conf;
private final ServerConnection connection;
private final AtomicBoolean haveRootRegion = new AtomicBoolean(false);
private FileSystem fs;
private Path rootDir;
private final Random rand = new Random();
// Key is Bytes.hashCode of region name byte array and the value is HRegion
// in both of the maps below. Use Bytes.mapKey(byte []) generating key for
// below maps.
protected final Map<Integer, HRegion> onlineRegions =
new ConcurrentHashMap<Integer, HRegion>();
protected final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
private final List<HMsg> outboundMsgs =
Collections.synchronizedList(new ArrayList<HMsg>());
final int numRetries;
protected final int threadWakeFrequency;
private final int msgInterval;
private final int serverLeaseTimeout;
protected final int numRegionsToReport;
// Remote HMaster
private HMasterRegionInterface hbaseMaster;
// Server to handle client requests. Default access so can be accessed by
// unit tests.
final Server server;
// Leases
private final Leases leases;
// Request counter
private volatile AtomicInteger requestCount = new AtomicInteger();
// Info server. Default access so can be used by unit tests. REGIONSERVER
// is name of the webapp and the attribute name used stuffing this instance
// into web context.
InfoServer infoServer;
/** region server process name */
public static final String REGIONSERVER = "regionserver";
/**
* Space is reserved in HRS constructor and then released when aborting
* to recover from an OOME. See HBASE-706.
*/
private final LinkedList<byte[]> reservedSpace = new LinkedList<byte []>();
private RegionServerMetrics metrics;
/**
* Thread to shutdown the region server in an orderly manner. This thread
* is registered as a shutdown hook in the HRegionServer constructor and is
* only called when the HRegionServer receives a kill signal.
*/
class ShutdownThread extends Thread {
private final HRegionServer instance;
/**
* @param instance
*/
public ShutdownThread(HRegionServer instance) {
this.instance = instance;
}
@Override
public void run() {
LOG.info("Starting shutdown thread.");
// tell the region server to stop and wait for it to complete
instance.stop();
instance.join();
LOG.info("Shutdown thread complete");
}
}
// Compactions
final CompactSplitThread compactSplitThread;
// Cache flushing
final MemcacheFlusher cacheFlusher;
// HLog and HLog roller. log is protected rather than private to avoid
// eclipse warning when accessed by inner classes
protected volatile HLog log;
final LogRoller logRoller;
final LogFlusher logFlusher;
// flag set after we're done setting up server threads (used for testing)
protected volatile boolean isOnline;
/**
* Starts a HRegionServer at the default location
* @param conf
* @throws IOException
*/
public HRegionServer(HBaseConfiguration conf) throws IOException {
this(new HServerAddress(conf.get(REGIONSERVER_ADDRESS,
DEFAULT_REGIONSERVER_ADDRESS)), conf);
}
/**
* Starts a HRegionServer at the specified location
* @param address
* @param conf
* @throws IOException
*/
public HRegionServer(HServerAddress address, HBaseConfiguration conf)
throws IOException {
this.abortRequested = false;
this.fsOk = true;
this.conf = conf;
this.connection = ServerConnectionManager.getConnection(conf);
this.isOnline = false;
// Config'ed params
this.numRetries = conf.getInt("hbase.client.retries.number", 2);
this.threadWakeFrequency = conf.getInt(THREAD_WAKE_FREQUENCY, 10 * 1000);
this.msgInterval = conf.getInt("hbase.regionserver.msginterval", 3 * 1000);
this.serverLeaseTimeout =
conf.getInt("hbase.master.lease.period", 120 * 1000);
// Cache flushing thread.
this.cacheFlusher = new MemcacheFlusher(conf, this);
// Compaction thread
this.compactSplitThread = new CompactSplitThread(this);
// Log rolling thread
this.logRoller = new LogRoller(this);
// Log flushing thread
this.logFlusher =
new LogFlusher(this.threadWakeFrequency, this.stopRequested);
// Task thread to process requests from Master
this.worker = new Worker();
this.workerThread = new Thread(worker);
// Server to handle client requests
this.server = HbaseRPC.getServer(this, address.getBindAddress(),
address.getPort(), conf.getInt("hbase.regionserver.handler.count", 10),
false, conf);
// Address is givin a default IP for the moment. Will be changed after
// calling the master.
this.serverInfo = new HServerInfo(new HServerAddress(
new InetSocketAddress(DEFAULT_HOST,
this.server.getListenerAddress().getPort())), System.currentTimeMillis(),
this.conf.getInt("hbase.regionserver.info.port", 60030));
if (this.serverInfo.getServerAddress() == null) {
throw new NullPointerException("Server address cannot be null; " +
"hbase-958 debugging");
}
this.numRegionsToReport =
conf.getInt("hbase.regionserver.numregionstoreport", 10);
this.leases = new Leases(
conf.getInt("hbase.regionserver.lease.period", 60 * 1000),
this.threadWakeFrequency);
int nbBlocks = conf.getInt("hbase.regionserver.nbreservationblocks", 4);
for(int i = 0; i < nbBlocks; i++) {
reservedSpace.add(new byte[DEFAULT_SIZE_RESERVATION_BLOCK]);
}
// Register shutdown hook for HRegionServer, runs an orderly shutdown
// when a kill signal is recieved
Runtime.getRuntime().addShutdownHook(new ShutdownThread(this));
}
/**
* The HRegionServer sticks in this loop until closed. It repeatedly checks
* in with the HMaster, sending heartbeats & reports, and receiving HRegion
* load/unload instructions.
*/
public void run() {
boolean quiesceRequested = false;
// A sleeper that sleeps for msgInterval.
Sleeper sleeper = new Sleeper(this.msgInterval, this.stopRequested);
try {
init(reportForDuty(sleeper));
long lastMsg = 0;
// Now ask master what it wants us to do and tell it what we have done
for (int tries = 0; !stopRequested.get() && isHealthy();) {
long now = System.currentTimeMillis();
if (lastMsg != 0 && (now - lastMsg) >= serverLeaseTimeout) {
// It has been way too long since we last reported to the master.
LOG.warn("unable to report to master for " + (now - lastMsg) +
" milliseconds - retrying");
}
if ((now - lastMsg) >= msgInterval) {
HMsg outboundArray[] = null;
synchronized(this.outboundMsgs) {
outboundArray =
this.outboundMsgs.toArray(new HMsg[outboundMsgs.size()]);
this.outboundMsgs.clear();
}
try {
doMetrics();
this.serverInfo.setLoad(new HServerLoad(requestCount.get(),
onlineRegions.size(), this.metrics.storefiles.get(),
this.metrics.memcacheSizeMB.get()));
this.requestCount.set(0);
HMsg msgs[] = hbaseMaster.regionServerReport(
serverInfo, outboundArray, getMostLoadedRegions());
lastMsg = System.currentTimeMillis();
if (this.quiesced.get() && onlineRegions.size() == 0) {
// We've just told the master we're exiting because we aren't
// serving any regions. So set the stop bit and exit.
LOG.info("Server quiesced and not serving any regions. " +
"Starting shutdown");
stopRequested.set(true);
this.outboundMsgs.clear();
continue;
}
// Queue up the HMaster's instruction stream for processing
boolean restart = false;
for(int i = 0;
!restart && !stopRequested.get() && i < msgs.length;
i++) {
LOG.info(msgs[i].toString());
switch(msgs[i].getType()) {
case MSG_CALL_SERVER_STARTUP:
// We the MSG_CALL_SERVER_STARTUP on startup but we can also
// get it when the master is panicing because for instance
// the HDFS has been yanked out from under it. Be wary of
// this message.
if (checkFileSystem()) {
closeAllRegions();
try {
log.closeAndDelete();
} catch (Exception e) {
LOG.error("error closing and deleting HLog", e);
}
try {
serverInfo.setStartCode(System.currentTimeMillis());
log = setupHLog();
this.logFlusher.setHLog(log);
} catch (IOException e) {
this.abortRequested = true;
this.stopRequested.set(true);
e = RemoteExceptionHandler.checkIOException(e);
LOG.fatal("error restarting server", e);
break;
}
reportForDuty(sleeper);
restart = true;
} else {
LOG.fatal("file system available check failed. " +
"Shutting down server.");
}
break;
case MSG_REGIONSERVER_STOP:
stopRequested.set(true);
break;
case MSG_REGIONSERVER_QUIESCE:
if (!quiesceRequested) {
try {
toDo.put(new ToDoEntry(msgs[i]));
} catch (InterruptedException e) {
throw new RuntimeException("Putting into msgQueue was " +
"interrupted.", e);
}
quiesceRequested = true;
}
break;
default:
if (fsOk) {
try {
toDo.put(new ToDoEntry(msgs[i]));
} catch (InterruptedException e) {
throw new RuntimeException("Putting into msgQueue was " +
"interrupted.", e);
}
}
}
}
// Reset tries count if we had a successful transaction.
tries = 0;
if (restart || this.stopRequested.get()) {
toDo.clear();
continue;
}
} catch (Exception e) {
if (e instanceof IOException) {
e = RemoteExceptionHandler.checkIOException((IOException) e);
}
if (tries < this.numRetries) {
LOG.warn("Processing message (Retry: " + tries + ")", e);
tries++;
} else {
LOG.error("Exceeded max retries: " + this.numRetries, e);
checkFileSystem();
}
+ if (this.stopRequested.get()) {
+ LOG.info("Stop was requested, clearing the toDo " +
+ "despite of the exception");
+ toDo.clear();
+ continue;
+ }
}
}
// Do some housekeeping before going to sleep
housekeeping();
sleeper.sleep(lastMsg);
} // for
} catch (OutOfMemoryError error) {
abort();
LOG.fatal("Ran out of memory", error);
} catch (Throwable t) {
LOG.fatal("Unhandled exception. Aborting...", t);
abort();
}
RegionHistorian.getInstance().offline();
this.leases.closeAfterLeasesExpire();
this.worker.stop();
this.server.stop();
if (this.infoServer != null) {
LOG.info("Stopping infoServer");
try {
this.infoServer.stop();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
// Send interrupts to wake up threads if sleeping so they notice shutdown.
// TODO: Should we check they are alive? If OOME could have exited already
cacheFlusher.interruptIfNecessary();
logFlusher.interrupt();
compactSplitThread.interruptIfNecessary();
logRoller.interruptIfNecessary();
if (abortRequested) {
if (this.fsOk) {
// Only try to clean up if the file system is available
try {
if (this.log != null) {
this.log.close();
LOG.info("On abort, closed hlog");
}
} catch (IOException e) {
LOG.error("Unable to close log in abort",
RemoteExceptionHandler.checkIOException(e));
}
closeAllRegions(); // Don't leave any open file handles
}
LOG.info("aborting server at: " +
serverInfo.getServerAddress().toString());
} else {
ArrayList<HRegion> closedRegions = closeAllRegions();
try {
log.closeAndDelete();
} catch (IOException e) {
LOG.error("Close and delete failed",
RemoteExceptionHandler.checkIOException(e));
}
try {
HMsg[] exitMsg = new HMsg[closedRegions.size() + 1];
exitMsg[0] = HMsg.REPORT_EXITING;
// Tell the master what regions we are/were serving
int i = 1;
for (HRegion region: closedRegions) {
exitMsg[i++] = new HMsg(HMsg.Type.MSG_REPORT_CLOSE,
region.getRegionInfo());
}
LOG.info("telling master that region server is shutting down at: " +
serverInfo.getServerAddress().toString());
hbaseMaster.regionServerReport(serverInfo, exitMsg, (HRegionInfo[])null);
} catch (IOException e) {
LOG.warn("Failed to send exiting message to master: ",
RemoteExceptionHandler.checkIOException(e));
}
LOG.info("stopping server at: " +
serverInfo.getServerAddress().toString());
}
if (this.hbaseMaster != null) {
HbaseRPC.stopProxy(this.hbaseMaster);
this.hbaseMaster = null;
}
join();
LOG.info(Thread.currentThread().getName() + " exiting");
}
/*
* Run init. Sets up hlog and starts up all server threads.
* @param c Extra configuration.
*/
protected void init(final MapWritable c) throws IOException {
try {
for (Map.Entry<Writable, Writable> e: c.entrySet()) {
String key = e.getKey().toString();
String value = e.getValue().toString();
if (LOG.isDebugEnabled()) {
LOG.debug("Config from master: " + key + "=" + value);
}
this.conf.set(key, value);
}
// Master may have sent us a new address with the other configs.
// Update our address in this case. See HBASE-719
if(conf.get("hbase.regionserver.address") != null)
serverInfo.setServerAddress(new HServerAddress
(conf.get("hbase.regionserver.address"),
serverInfo.getServerAddress().getPort()));
// Master sent us hbase.rootdir to use. Should be fully qualified
// path with file system specification included. Set 'fs.default.name'
// to match the filesystem on hbase.rootdir else underlying hadoop hdfs
// accessors will be going against wrong filesystem (unless all is set
// to defaults).
this.conf.set("fs.default.name", this.conf.get("hbase.rootdir"));
this.fs = FileSystem.get(this.conf);
this.rootDir = new Path(this.conf.get(HConstants.HBASE_DIR));
this.log = setupHLog();
this.logFlusher.setHLog(log);
// Init in here rather than in constructor after thread name has been set
this.metrics = new RegionServerMetrics();
startServiceThreads();
isOnline = true;
} catch (IOException e) {
this.stopRequested.set(true);
isOnline = false;
e = RemoteExceptionHandler.checkIOException(e);
LOG.fatal("Failed init", e);
IOException ex = new IOException("region server startup failed");
ex.initCause(e);
throw ex;
}
}
/**
* Report the status of the server. A server is online once all the startup
* is completed (setting up filesystem, starting service threads, etc.). This
* method is designed mostly to be useful in tests.
* @return true if online, false if not.
*/
public boolean isOnline() {
return isOnline;
}
private HLog setupHLog() throws RegionServerRunningException,
IOException {
Path logdir = new Path(rootDir, "log" + "_" +
serverInfo.getServerAddress().getBindAddress() + "_" +
this.serverInfo.getStartCode() + "_" +
this.serverInfo.getServerAddress().getPort());
if (LOG.isDebugEnabled()) {
LOG.debug("Log dir " + logdir);
}
if (fs.exists(logdir)) {
throw new RegionServerRunningException("region server already " +
"running at " + this.serverInfo.getServerAddress().toString() +
" because logdir " + logdir.toString() + " exists");
}
HLog newlog = new HLog(fs, logdir, conf, logRoller);
return newlog;
}
/*
* @param interval Interval since last time metrics were called.
*/
protected void doMetrics() {
this.metrics.regions.set(this.onlineRegions.size());
this.metrics.incrementRequests(this.requestCount.get());
// Is this too expensive every three seconds getting a lock on onlineRegions
// and then per store carried? Can I make metrics be sloppier and avoid
// the synchronizations?
int storefiles = 0;
long memcacheSize = 0;
synchronized (this.onlineRegions) {
for (Map.Entry<Integer, HRegion> e: this.onlineRegions.entrySet()) {
HRegion r = e.getValue();
memcacheSize += r.memcacheSize.get();
synchronized(r.stores) {
for(Map.Entry<Integer, HStore> ee: r.stores.entrySet()) {
storefiles += ee.getValue().getStorefilesCount();
}
}
}
}
this.metrics.storefiles.set(storefiles);
this.metrics.memcacheSizeMB.set((int)(memcacheSize/(1024*1024)));
}
/**
* @return Region server metrics instance.
*/
public RegionServerMetrics getMetrics() {
return this.metrics;
}
/*
* Start maintanence Threads, Server, Worker and lease checker threads.
* Install an UncaughtExceptionHandler that calls abort of RegionServer if we
* get an unhandled exception. We cannot set the handler on all threads.
* Server's internal Listener thread is off limits. For Server, if an OOME,
* it waits a while then retries. Meantime, a flush or a compaction that
* tries to run should trigger same critical condition and the shutdown will
* run. On its way out, this server will shut down Server. Leases are sort
* of inbetween. It has an internal thread that while it inherits from
* Chore, it keeps its own internal stop mechanism so needs to be stopped
* by this hosting server. Worker logs the exception and exits.
*/
private void startServiceThreads() throws IOException {
String n = Thread.currentThread().getName();
UncaughtExceptionHandler handler = new UncaughtExceptionHandler() {
public void uncaughtException(Thread t, Throwable e) {
abort();
LOG.fatal("Set stop flag in " + t.getName(), e);
}
};
Threads.setDaemonThreadRunning(this.logRoller, n + ".logRoller",
handler);
Threads.setDaemonThreadRunning(this.logFlusher, n + ".logFlusher",
handler);
Threads.setDaemonThreadRunning(this.cacheFlusher, n + ".cacheFlusher",
handler);
Threads.setDaemonThreadRunning(this.compactSplitThread, n + ".compactor",
handler);
Threads.setDaemonThreadRunning(this.workerThread, n + ".worker", handler);
// Leases is not a Thread. Internally it runs a daemon thread. If it gets
// an unhandled exception, it will just exit.
this.leases.setName(n + ".leaseChecker");
this.leases.start();
// Put up info server.
int port = this.conf.getInt("hbase.regionserver.info.port", 60030);
if (port >= 0) {
String a = this.conf.get("hbase.master.info.bindAddress", "0.0.0.0");
this.infoServer = new InfoServer("regionserver", a, port, false);
this.infoServer.setAttribute("regionserver", this);
this.infoServer.start();
}
// Start Server. This service is like leases in that it internally runs
// a thread.
this.server.start();
LOG.info("HRegionServer started at: " +
serverInfo.getServerAddress().toString());
}
/*
* Verify that server is healthy
*/
private boolean isHealthy() {
if (!fsOk) {
// File system problem
return false;
}
// Verify that all threads are alive
if (!(leases.isAlive() && compactSplitThread.isAlive() &&
cacheFlusher.isAlive() && logRoller.isAlive() &&
workerThread.isAlive())) {
// One or more threads are no longer alive - shut down
stop();
return false;
}
return true;
}
/*
* Run some housekeeping tasks before we go into 'hibernation' sleeping at
* the end of the main HRegionServer run loop.
*/
private void housekeeping() {
// Try to get the root region location from the master.
if (!haveRootRegion.get()) {
HServerAddress rootServer = hbaseMaster.getRootRegionLocation();
if (rootServer != null) {
// By setting the root region location, we bypass the wait imposed on
// HTable for all regions being assigned.
this.connection.setRootRegionLocation(
new HRegionLocation(HRegionInfo.ROOT_REGIONINFO, rootServer));
haveRootRegion.set(true);
}
}
// If the todo list has > 0 messages, iterate looking for open region
// messages. Send the master a message that we're working on its
// processing so it doesn't assign the region elsewhere.
if (this.toDo.size() <= 0) {
return;
}
// This iterator is 'safe'. We are guaranteed a view on state of the
// queue at time iterator was taken out. Apparently goes from oldest.
for (ToDoEntry e: this.toDo) {
if (e.msg.isType(HMsg.Type.MSG_REGION_OPEN)) {
addProcessingMessage(e.msg.getRegionInfo());
}
}
}
/** @return the HLog */
HLog getLog() {
return this.log;
}
/**
* Sets a flag that will cause all the HRegionServer threads to shut down
* in an orderly fashion. Used by unit tests.
*/
public void stop() {
this.stopRequested.set(true);
synchronized(this) {
notifyAll(); // Wakes run() if it is sleeping
}
}
/**
* Cause the server to exit without closing the regions it is serving, the
* log it is using and without notifying the master.
* Used unit testing and on catastrophic events such as HDFS is yanked out
* from under hbase or we OOME.
*/
public void abort() {
reservedSpace.clear();
this.abortRequested = true;
stop();
}
/**
* Wait on all threads to finish.
* Presumption is that all closes and stops have already been called.
*/
void join() {
join(this.workerThread);
join(this.cacheFlusher);
join(this.compactSplitThread);
join(this.logRoller);
}
private void join(final Thread t) {
while (t.isAlive()) {
try {
t.join();
} catch (InterruptedException e) {
// continue
}
}
}
/*
* Let the master know we're here
* Run initialization using parameters passed us by the master.
*/
private MapWritable reportForDuty(final Sleeper sleeper) {
if (LOG.isDebugEnabled()) {
LOG.debug("Telling master at " +
conf.get(MASTER_ADDRESS) + " that we are up");
}
HMasterRegionInterface master = null;
while (!stopRequested.get() && master == null) {
try {
// Do initial RPC setup. The final argument indicates that the RPC
// should retry indefinitely.
master = (HMasterRegionInterface)HbaseRPC.waitForProxy(
HMasterRegionInterface.class, HMasterRegionInterface.versionID,
new HServerAddress(conf.get(MASTER_ADDRESS)).getInetSocketAddress(),
this.conf, -1);
} catch (IOException e) {
LOG.warn("Unable to connect to master. Retrying. Error was:", e);
sleeper.sleep();
}
}
this.hbaseMaster = master;
MapWritable result = null;
long lastMsg = 0;
while(!stopRequested.get()) {
try {
this.requestCount.set(0);
this.serverInfo.setLoad(new HServerLoad(0, onlineRegions.size(), 0, 0));
lastMsg = System.currentTimeMillis();
result = this.hbaseMaster.regionServerStartup(serverInfo);
break;
} catch (Leases.LeaseStillHeldException e) {
LOG.info("Lease " + e.getName() + " already held on master. Check " +
"DNS configuration so that all region servers are" +
"reporting their true IPs and not 127.0.0.1. Otherwise, this" +
"problem should resolve itself after the lease period of " +
this.conf.get("hbase.master.lease.period")
+ " seconds expires over on the master");
} catch (IOException e) {
LOG.warn("error telling master we are up", e);
}
sleeper.sleep(lastMsg);
}
return result;
}
/* Add to the outbound message buffer */
private void reportOpen(HRegionInfo region) {
outboundMsgs.add(new HMsg(HMsg.Type.MSG_REPORT_OPEN, region));
}
/* Add to the outbound message buffer */
private void reportClose(HRegionInfo region) {
reportClose(region, null);
}
/* Add to the outbound message buffer */
private void reportClose(final HRegionInfo region, final byte[] message) {
outboundMsgs.add(new HMsg(HMsg.Type.MSG_REPORT_CLOSE, region, message));
}
/**
* Add to the outbound message buffer
*
* When a region splits, we need to tell the master that there are two new
* regions that need to be assigned.
*
* We do not need to inform the master about the old region, because we've
* updated the meta or root regions, and the master will pick that up on its
* next rescan of the root or meta tables.
*/
void reportSplit(HRegionInfo oldRegion, HRegionInfo newRegionA,
HRegionInfo newRegionB) {
outboundMsgs.add(new HMsg(HMsg.Type.MSG_REPORT_SPLIT, oldRegion,
(oldRegion.getRegionNameAsString() + " split; daughters: " +
newRegionA.getRegionNameAsString() + ", " +
newRegionB.getRegionNameAsString()).getBytes()));
outboundMsgs.add(new HMsg(HMsg.Type.MSG_REPORT_OPEN, newRegionA));
outboundMsgs.add(new HMsg(HMsg.Type.MSG_REPORT_OPEN, newRegionB));
}
//////////////////////////////////////////////////////////////////////////////
// HMaster-given operations
//////////////////////////////////////////////////////////////////////////////
/*
* Data structure to hold a HMsg and retries count.
*/
private static class ToDoEntry {
private int tries;
private final HMsg msg;
ToDoEntry(HMsg msg) {
this.tries = 0;
this.msg = msg;
}
}
final BlockingQueue<ToDoEntry> toDo = new LinkedBlockingQueue<ToDoEntry>();
private Worker worker;
private Thread workerThread;
/** Thread that performs long running requests from the master */
class Worker implements Runnable {
void stop() {
synchronized(toDo) {
toDo.notifyAll();
}
}
public void run() {
try {
while(!stopRequested.get()) {
ToDoEntry e = null;
try {
e = toDo.poll(threadWakeFrequency, TimeUnit.MILLISECONDS);
if(e == null || stopRequested.get()) {
continue;
}
LOG.info(e.msg);
switch(e.msg.getType()) {
case MSG_REGIONSERVER_QUIESCE:
closeUserRegions();
break;
case MSG_REGION_OPEN:
// Open a region
openRegion(e.msg.getRegionInfo());
break;
case MSG_REGION_CLOSE:
// Close a region
closeRegion(e.msg.getRegionInfo(), true);
break;
case MSG_REGION_CLOSE_WITHOUT_REPORT:
// Close a region, don't reply
closeRegion(e.msg.getRegionInfo(), false);
break;
case MSG_REGION_SPLIT: {
HRegionInfo info = e.msg.getRegionInfo();
// Force split a region
HRegion region = getRegion(info.getRegionName());
region.regionInfo.shouldSplit(true);
compactSplitThread.compactionRequested(region);
} break;
case MSG_REGION_COMPACT: {
// Compact a region
HRegionInfo info = e.msg.getRegionInfo();
HRegion region = getRegion(info.getRegionName());
compactSplitThread.compactionRequested(region);
} break;
default:
throw new AssertionError(
"Impossible state during msg processing. Instruction: "
+ e.msg.toString());
}
} catch (InterruptedException ex) {
// continue
} catch (Exception ex) {
if (ex instanceof IOException) {
ex = RemoteExceptionHandler.checkIOException((IOException) ex);
}
if(e != null && e.tries < numRetries) {
LOG.warn(ex);
e.tries++;
try {
toDo.put(e);
} catch (InterruptedException ie) {
throw new RuntimeException("Putting into msgQueue was " +
"interrupted.", ex);
}
} else {
LOG.error("unable to process message" +
(e != null ? (": " + e.msg.toString()) : ""), ex);
if (!checkFileSystem()) {
break;
}
}
}
}
} catch(Throwable t) {
LOG.fatal("Unhandled exception", t);
} finally {
LOG.info("worker thread exiting");
}
}
}
void openRegion(final HRegionInfo regionInfo) {
// If historian is not online and this is not a meta region, online it.
if (!regionInfo.isMetaRegion() &&
!RegionHistorian.getInstance().isOnline()) {
RegionHistorian.getInstance().online(this.conf);
}
Integer mapKey = Bytes.mapKey(regionInfo.getRegionName());
HRegion region = this.onlineRegions.get(mapKey);
if (region == null) {
try {
region = instantiateRegion(regionInfo);
// Startup a compaction early if one is needed.
this.compactSplitThread.compactionRequested(region);
} catch (IOException e) {
LOG.error("error opening region " + regionInfo.getRegionNameAsString(), e);
// TODO: add an extra field in HRegionInfo to indicate that there is
// an error. We can't do that now because that would be an incompatible
// change that would require a migration
reportClose(regionInfo, StringUtils.stringifyException(e).getBytes());
return;
}
this.lock.writeLock().lock();
try {
this.log.setSequenceNumber(region.getMinSequenceId());
this.onlineRegions.put(mapKey, region);
} finally {
this.lock.writeLock().unlock();
}
}
reportOpen(regionInfo);
}
protected HRegion instantiateRegion(final HRegionInfo regionInfo)
throws IOException {
HRegion r = new HRegion(HTableDescriptor.getTableDir(rootDir, regionInfo
.getTableDesc().getName()), this.log, this.fs, conf, regionInfo,
this.cacheFlusher);
r.initialize(null, new Progressable() {
public void progress() {
addProcessingMessage(regionInfo);
}
});
return r;
}
/*
* Add a MSG_REPORT_PROCESS_OPEN to the outbound queue.
* This method is called while region is in the queue of regions to process
* and then while the region is being opened, it is called from the Worker
* thread that is running the region open.
* @param hri Region to add the message for
*/
protected void addProcessingMessage(final HRegionInfo hri) {
getOutboundMsgs().add(new HMsg(HMsg.Type.MSG_REPORT_PROCESS_OPEN, hri));
}
void closeRegion(final HRegionInfo hri, final boolean reportWhenCompleted)
throws IOException {
HRegion region = this.removeFromOnlineRegions(hri);
if (region != null) {
region.close();
if(reportWhenCompleted) {
reportClose(hri);
}
}
}
/** Called either when the master tells us to restart or from stop() */
ArrayList<HRegion> closeAllRegions() {
ArrayList<HRegion> regionsToClose = new ArrayList<HRegion>();
this.lock.writeLock().lock();
try {
regionsToClose.addAll(onlineRegions.values());
onlineRegions.clear();
} finally {
this.lock.writeLock().unlock();
}
for(HRegion region: regionsToClose) {
if (LOG.isDebugEnabled()) {
LOG.debug("closing region " + Bytes.toString(region.getRegionName()));
}
try {
region.close(abortRequested);
} catch (IOException e) {
LOG.error("error closing region " +
Bytes.toString(region.getRegionName()),
RemoteExceptionHandler.checkIOException(e));
}
}
return regionsToClose;
}
/** Called as the first stage of cluster shutdown. */
void closeUserRegions() {
ArrayList<HRegion> regionsToClose = new ArrayList<HRegion>();
this.lock.writeLock().lock();
try {
synchronized (onlineRegions) {
for (Iterator<Map.Entry<Integer, HRegion>> i =
onlineRegions.entrySet().iterator(); i.hasNext();) {
Map.Entry<Integer, HRegion> e = i.next();
HRegion r = e.getValue();
if (!r.getRegionInfo().isMetaRegion()) {
regionsToClose.add(r);
i.remove();
}
}
}
} finally {
this.lock.writeLock().unlock();
}
for(HRegion region: regionsToClose) {
if (LOG.isDebugEnabled()) {
LOG.debug("closing region " + Bytes.toString(region.getRegionName()));
}
try {
region.close();
} catch (IOException e) {
LOG.error("error closing region " + region.getRegionName(),
RemoteExceptionHandler.checkIOException(e));
}
}
this.quiesced.set(true);
if (onlineRegions.size() == 0) {
outboundMsgs.add(HMsg.REPORT_EXITING);
} else {
outboundMsgs.add(HMsg.REPORT_QUIESCED);
}
}
//
// HRegionInterface
//
public HRegionInfo getRegionInfo(final byte [] regionName)
throws NotServingRegionException {
requestCount.incrementAndGet();
return getRegion(regionName).getRegionInfo();
}
public Cell[] get(final byte [] regionName, final byte [] row,
final byte [] column, final long timestamp, final int numVersions)
throws IOException {
checkOpen();
requestCount.incrementAndGet();
try {
return getRegion(regionName).get(row, column, timestamp, numVersions);
} catch (IOException e) {
checkFileSystem();
throw e;
}
}
public RowResult getRow(final byte [] regionName, final byte [] row,
final byte [][] columns, final long ts, final long lockId)
throws IOException {
checkOpen();
requestCount.incrementAndGet();
try {
// convert the columns array into a set so it's easy to check later.
Set<byte []> columnSet = null;
if (columns != null) {
columnSet = new TreeSet<byte []>(Bytes.BYTES_COMPARATOR);
columnSet.addAll(Arrays.asList(columns));
}
HRegion region = getRegion(regionName);
Map<byte [], Cell> map = region.getFull(row, columnSet, ts,
getLockFromId(lockId));
HbaseMapWritable<byte [], Cell> result =
new HbaseMapWritable<byte [], Cell>();
result.putAll(map);
return new RowResult(row, result);
} catch (IOException e) {
checkFileSystem();
throw e;
}
}
public RowResult getClosestRowBefore(final byte [] regionName,
final byte [] row)
throws IOException {
checkOpen();
requestCount.incrementAndGet();
try {
// locate the region we're operating on
HRegion region = getRegion(regionName);
// ask the region for all the data
RowResult rr = region.getClosestRowBefore(row);
return rr;
} catch (IOException e) {
checkFileSystem();
throw e;
}
}
public RowResult next(final long scannerId) throws IOException {
RowResult[] rrs = next(scannerId, 1);
return rrs.length == 0 ? null : rrs[0];
}
public RowResult[] next(final long scannerId, int nbRows) throws IOException {
checkOpen();
requestCount.incrementAndGet();
ArrayList<RowResult> resultSets = new ArrayList<RowResult>();
try {
String scannerName = String.valueOf(scannerId);
InternalScanner s = scanners.get(scannerName);
if (s == null) {
throw new UnknownScannerException("Name: " + scannerName);
}
this.leases.renewLease(scannerName);
for(int i = 0; i < nbRows; i++) {
// Collect values to be returned here
HbaseMapWritable<byte [], Cell> values
= new HbaseMapWritable<byte [], Cell>();
HStoreKey key = new HStoreKey();
while (s.next(key, values)) {
if (values.size() > 0) {
// Row has something in it. Return the value.
resultSets.add(new RowResult(key.getRow(), values));
break;
}
}
}
return resultSets.toArray(new RowResult[resultSets.size()]);
} catch (IOException e) {
checkFileSystem();
throw e;
}
}
public void batchUpdate(final byte [] regionName, BatchUpdate b,
@SuppressWarnings("unused") long lockId)
throws IOException {
if (b.getRow() == null)
throw new IllegalArgumentException("update has null row");
checkOpen();
this.requestCount.incrementAndGet();
HRegion region = getRegion(regionName);
validateValuesLength(b, region);
try {
cacheFlusher.reclaimMemcacheMemory();
region.batchUpdate(b, getLockFromId(b.getRowLock()));
} catch (OutOfMemoryError error) {
abort();
LOG.fatal("Ran out of memory", error);
} catch (IOException e) {
checkFileSystem();
throw e;
}
}
public int batchUpdates(final byte[] regionName, final BatchUpdate[] b)
throws IOException {
int i = 0;
checkOpen();
try {
HRegion region = getRegion(regionName);
this.cacheFlusher.reclaimMemcacheMemory();
Integer[] locks = new Integer[b.length];
for (i = 0; i < b.length; i++) {
this.requestCount.incrementAndGet();
validateValuesLength(b[i], region);
locks[i] = getLockFromId(b[i].getRowLock());
region.batchUpdate(b[i], locks[i]);
}
} catch (OutOfMemoryError error) {
abort();
LOG.fatal("Ran out of memory", error);
} catch(WrongRegionException ex) {
return i;
} catch (NotServingRegionException ex) {
return i;
} catch (IOException e) {
checkFileSystem();
throw e;
}
return -1;
}
/**
* Utility method to verify values length
* @param batchUpdate The update to verify
* @throws IOException Thrown if a value is too long
*/
private void validateValuesLength(BatchUpdate batchUpdate,
HRegion region) throws IOException {
HTableDescriptor desc = region.getTableDesc();
for (Iterator<BatchOperation> iter =
batchUpdate.iterator(); iter.hasNext();) {
BatchOperation operation = iter.next();
if (operation.getValue() != null) {
HColumnDescriptor fam =
desc.getFamily(HStoreKey.getFamily(operation.getColumn()));
if (fam != null) {
int maxLength = fam.getMaxValueLength();
if (operation.getValue().length > maxLength) {
throw new ValueOverMaxLengthException("Value in column "
+ Bytes.toString(operation.getColumn()) + " is too long. "
+ operation.getValue().length + " instead of " + maxLength);
}
}
}
}
}
//
// remote scanner interface
//
public long openScanner(byte [] regionName, byte [][] cols, byte [] firstRow,
final long timestamp, final RowFilterInterface filter)
throws IOException {
checkOpen();
NullPointerException npe = null;
if (regionName == null) {
npe = new NullPointerException("regionName is null");
} else if (cols == null) {
npe = new NullPointerException("columns to scan is null");
} else if (firstRow == null) {
npe = new NullPointerException("firstRow for scanner is null");
}
if (npe != null) {
IOException io = new IOException("Invalid arguments to openScanner");
io.initCause(npe);
throw io;
}
requestCount.incrementAndGet();
try {
HRegion r = getRegion(regionName);
InternalScanner s =
r.getScanner(cols, firstRow, timestamp, filter);
long scannerId = addScanner(s);
return scannerId;
} catch (IOException e) {
LOG.error("Error opening scanner (fsOk: " + this.fsOk + ")",
RemoteExceptionHandler.checkIOException(e));
checkFileSystem();
throw e;
}
}
protected long addScanner(InternalScanner s) throws LeaseStillHeldException {
long scannerId = -1L;
scannerId = rand.nextLong();
String scannerName = String.valueOf(scannerId);
synchronized(scanners) {
scanners.put(scannerName, s);
}
this.leases.
createLease(scannerName, new ScannerListener(scannerName));
return scannerId;
}
public void close(final long scannerId) throws IOException {
checkOpen();
requestCount.incrementAndGet();
try {
String scannerName = String.valueOf(scannerId);
InternalScanner s = null;
synchronized(scanners) {
s = scanners.remove(scannerName);
}
if(s == null) {
throw new UnknownScannerException(scannerName);
}
s.close();
this.leases.cancelLease(scannerName);
} catch (IOException e) {
checkFileSystem();
throw e;
}
}
Map<String, InternalScanner> scanners =
new ConcurrentHashMap<String, InternalScanner>();
/**
* Instantiated as a scanner lease.
* If the lease times out, the scanner is closed
*/
private class ScannerListener implements LeaseListener {
private final String scannerName;
ScannerListener(final String n) {
this.scannerName = n;
}
public void leaseExpired() {
LOG.info("Scanner " + this.scannerName + " lease expired");
InternalScanner s = null;
synchronized(scanners) {
s = scanners.remove(this.scannerName);
}
if (s != null) {
try {
s.close();
} catch (IOException e) {
LOG.error("Closing scanner", e);
}
}
}
}
//
// Methods that do the actual work for the remote API
//
public void deleteAll(final byte [] regionName, final byte [] row,
final byte [] column, final long timestamp, final long lockId)
throws IOException {
HRegion region = getRegion(regionName);
region.deleteAll(row, column, timestamp, getLockFromId(lockId));
}
public void deleteAll(final byte [] regionName, final byte [] row,
final long timestamp, final long lockId)
throws IOException {
HRegion region = getRegion(regionName);
region.deleteAll(row, timestamp, getLockFromId(lockId));
}
public void deleteFamily(byte [] regionName, byte [] row, byte [] family,
long timestamp, final long lockId)
throws IOException{
getRegion(regionName).deleteFamily(row, family, timestamp,
getLockFromId(lockId));
}
public long lockRow(byte [] regionName, byte [] row)
throws IOException {
checkOpen();
NullPointerException npe = null;
if(regionName == null) {
npe = new NullPointerException("regionName is null");
} else if(row == null) {
npe = new NullPointerException("row to lock is null");
}
if(npe != null) {
IOException io = new IOException("Invalid arguments to lockRow");
io.initCause(npe);
throw io;
}
requestCount.incrementAndGet();
try {
HRegion region = getRegion(regionName);
Integer r = region.obtainRowLock(row);
long lockId = addRowLock(r,region);
LOG.debug("Row lock " + lockId + " explicitly acquired by client");
return lockId;
} catch (IOException e) {
LOG.error("Error obtaining row lock (fsOk: " + this.fsOk + ")",
RemoteExceptionHandler.checkIOException(e));
checkFileSystem();
throw e;
}
}
protected long addRowLock(Integer r, HRegion region) throws LeaseStillHeldException {
long lockId = -1L;
lockId = rand.nextLong();
String lockName = String.valueOf(lockId);
synchronized(rowlocks) {
rowlocks.put(lockName, r);
}
this.leases.
createLease(lockName, new RowLockListener(lockName, region));
return lockId;
}
/**
* Method to get the Integer lock identifier used internally
* from the long lock identifier used by the client.
* @param lockId long row lock identifier from client
* @return intId Integer row lock used internally in HRegion
* @throws IOException Thrown if this is not a valid client lock id.
*/
private Integer getLockFromId(long lockId)
throws IOException {
if(lockId == -1L) {
return null;
}
String lockName = String.valueOf(lockId);
Integer rl = null;
synchronized(rowlocks) {
rl = rowlocks.get(lockName);
}
if(rl == null) {
throw new IOException("Invalid row lock");
}
this.leases.renewLease(lockName);
return rl;
}
public void unlockRow(byte [] regionName, long lockId)
throws IOException {
checkOpen();
NullPointerException npe = null;
if(regionName == null) {
npe = new NullPointerException("regionName is null");
} else if(lockId == -1L) {
npe = new NullPointerException("lockId is null");
}
if(npe != null) {
IOException io = new IOException("Invalid arguments to unlockRow");
io.initCause(npe);
throw io;
}
requestCount.incrementAndGet();
try {
HRegion region = getRegion(regionName);
String lockName = String.valueOf(lockId);
Integer r = null;
synchronized(rowlocks) {
r = rowlocks.remove(lockName);
}
if(r == null) {
throw new UnknownRowLockException(lockName);
}
region.releaseRowLock(r);
this.leases.cancelLease(lockName);
LOG.debug("Row lock " + lockId + " has been explicitly released by client");
} catch (IOException e) {
checkFileSystem();
throw e;
}
}
Map<String, Integer> rowlocks =
new ConcurrentHashMap<String, Integer>();
/**
* Instantiated as a row lock lease.
* If the lease times out, the row lock is released
*/
private class RowLockListener implements LeaseListener {
private final String lockName;
private final HRegion region;
RowLockListener(final String lockName, final HRegion region) {
this.lockName = lockName;
this.region = region;
}
public void leaseExpired() {
LOG.info("Row Lock " + this.lockName + " lease expired");
Integer r = null;
synchronized(rowlocks) {
r = rowlocks.remove(this.lockName);
}
if(r != null) {
region.releaseRowLock(r);
}
}
}
/**
* @return Info on this server.
*/
public HServerInfo getServerInfo() {
return this.serverInfo;
}
/** @return the info server */
public InfoServer getInfoServer() {
return infoServer;
}
/**
* @return true if a stop has been requested.
*/
public boolean isStopRequested() {
return stopRequested.get();
}
/**
*
* @return the configuration
*/
public HBaseConfiguration getConfiguration() {
return conf;
}
/** @return the write lock for the server */
ReentrantReadWriteLock.WriteLock getWriteLock() {
return lock.writeLock();
}
/**
* @return Immutable list of this servers regions.
*/
public Collection<HRegion> getOnlineRegions() {
return Collections.unmodifiableCollection(onlineRegions.values());
}
/**
* @return The HRegionInfos from online regions sorted
*/
public SortedSet<HRegionInfo> getSortedOnlineRegionInfos() {
SortedSet<HRegionInfo> result = new TreeSet<HRegionInfo>();
synchronized(this.onlineRegions) {
for (HRegion r: this.onlineRegions.values()) {
result.add(r.getRegionInfo());
}
}
return result;
}
/**
* This method removes HRegion corresponding to hri from the Map of onlineRegions.
*
* @param hri the HRegionInfo corresponding to the HRegion to-be-removed.
* @return the removed HRegion, or null if the HRegion was not in onlineRegions.
*/
HRegion removeFromOnlineRegions(HRegionInfo hri) {
this.lock.writeLock().lock();
HRegion toReturn = null;
try {
toReturn = onlineRegions.remove(Bytes.mapKey(hri.getRegionName()));
} finally {
this.lock.writeLock().unlock();
}
return toReturn;
}
/**
* @return A new Map of online regions sorted by region size with the first
* entry being the biggest.
*/
public SortedMap<Long, HRegion> getCopyOfOnlineRegionsSortedBySize() {
// we'll sort the regions in reverse
SortedMap<Long, HRegion> sortedRegions = new TreeMap<Long, HRegion>(
new Comparator<Long>() {
public int compare(Long a, Long b) {
return -1 * a.compareTo(b);
}
});
// Copy over all regions. Regions are sorted by size with biggest first.
synchronized (this.onlineRegions) {
for (HRegion region : this.onlineRegions.values()) {
sortedRegions.put(region.memcacheSize.get(), region);
}
}
return sortedRegions;
}
/**
* @param regionName
* @return HRegion for the passed <code>regionName</code> or null if named
* region is not member of the online regions.
*/
public HRegion getOnlineRegion(final byte [] regionName) {
return onlineRegions.get(Bytes.mapKey(regionName));
}
/** @return the request count */
public AtomicInteger getRequestCount() {
return this.requestCount;
}
/** @return reference to FlushRequester */
public FlushRequester getFlushRequester() {
return this.cacheFlusher;
}
/**
* Protected utility method for safely obtaining an HRegion handle.
* @param regionName Name of online {@link HRegion} to return
* @return {@link HRegion} for <code>regionName</code>
* @throws NotServingRegionException
*/
protected HRegion getRegion(final byte [] regionName)
throws NotServingRegionException {
HRegion region = null;
this.lock.readLock().lock();
try {
Integer key = Integer.valueOf(Bytes.hashCode(regionName));
region = onlineRegions.get(key);
if (region == null) {
throw new NotServingRegionException(regionName);
}
return region;
} finally {
this.lock.readLock().unlock();
}
}
/**
* Get the top N most loaded regions this server is serving so we can
* tell the master which regions it can reallocate if we're overloaded.
* TODO: actually calculate which regions are most loaded. (Right now, we're
* just grabbing the first N regions being served regardless of load.)
*/
protected HRegionInfo[] getMostLoadedRegions() {
ArrayList<HRegionInfo> regions = new ArrayList<HRegionInfo>();
synchronized (onlineRegions) {
for (HRegion r : onlineRegions.values()) {
if (regions.size() < numRegionsToReport) {
regions.add(r.getRegionInfo());
} else {
break;
}
}
}
return regions.toArray(new HRegionInfo[regions.size()]);
}
/**
* Called to verify that this server is up and running.
*
* @throws IOException
*/
protected void checkOpen() throws IOException {
if (this.stopRequested.get() || this.abortRequested) {
throw new IOException("Server not running");
}
if (!fsOk) {
throw new IOException("File system not available");
}
}
/**
* Checks to see if the file system is still accessible.
* If not, sets abortRequested and stopRequested
*
* @return false if file system is not available
*/
protected boolean checkFileSystem() {
if (this.fsOk && fs != null) {
try {
FSUtils.checkFileSystemAvailable(fs);
} catch (IOException e) {
LOG.fatal("Shutting down HRegionServer: file system not available", e);
abort();
fsOk = false;
}
}
return this.fsOk;
}
/**
* @return Returns list of non-closed regions hosted on this server. If no
* regions to check, returns an empty list.
*/
protected Set<HRegion> getRegionsToCheck() {
HashSet<HRegion> regionsToCheck = new HashSet<HRegion>();
//TODO: is this locking necessary?
lock.readLock().lock();
try {
regionsToCheck.addAll(this.onlineRegions.values());
} finally {
lock.readLock().unlock();
}
// Purge closed regions.
for (final Iterator<HRegion> i = regionsToCheck.iterator(); i.hasNext();) {
HRegion r = i.next();
if (r.isClosed()) {
i.remove();
}
}
return regionsToCheck;
}
public long getProtocolVersion(final String protocol,
@SuppressWarnings("unused") final long clientVersion)
throws IOException {
if (protocol.equals(HRegionInterface.class.getName())) {
return HRegionInterface.versionID;
}
throw new IOException("Unknown protocol to name node: " + protocol);
}
/**
* @return Queue to which you can add outbound messages.
*/
protected List<HMsg> getOutboundMsgs() {
return this.outboundMsgs;
}
/**
* Return the total size of all memcaches in every region.
* @return memcache size in bytes
*/
public long getGlobalMemcacheSize() {
long total = 0;
synchronized (onlineRegions) {
for (HRegion region : onlineRegions.values()) {
total += region.memcacheSize.get();
}
}
return total;
}
/**
* @return Return the leases.
*/
protected Leases getLeases() {
return leases;
}
/**
* @return Return the rootDir.
*/
protected Path getRootDir() {
return rootDir;
}
/**
* @return Return the fs.
*/
protected FileSystem getFileSystem() {
return fs;
}
//
// Main program and support routines
//
private static void printUsageAndExit() {
printUsageAndExit(null);
}
private static void printUsageAndExit(final String message) {
if (message != null) {
System.err.println(message);
}
System.err.println("Usage: java " +
"org.apache.hbase.HRegionServer [--bind=hostname:port] start");
System.exit(0);
}
/**
* Do class main.
* @param args
* @param regionServerClass HRegionServer to instantiate.
*/
protected static void doMain(final String [] args,
final Class<? extends HRegionServer> regionServerClass) {
if (args.length < 1) {
printUsageAndExit();
}
Configuration conf = new HBaseConfiguration();
// Process command-line args. TODO: Better cmd-line processing
// (but hopefully something not as painful as cli options).
final String addressArgKey = "--bind=";
for (String cmd: args) {
if (cmd.startsWith(addressArgKey)) {
conf.set(REGIONSERVER_ADDRESS, cmd.substring(addressArgKey.length()));
continue;
}
if (cmd.equals("start")) {
try {
// If 'local', don't start a region server here. Defer to
// LocalHBaseCluster. It manages 'local' clusters.
if (LocalHBaseCluster.isLocal(conf)) {
LOG.warn("Not starting a distinct region server because " +
"hbase.master is set to 'local' mode");
} else {
Constructor<? extends HRegionServer> c =
regionServerClass.getConstructor(HBaseConfiguration.class);
HRegionServer hrs = c.newInstance(conf);
Thread t = new Thread(hrs);
t.setName("regionserver" + hrs.server.getListenerAddress());
t.start();
}
} catch (Throwable t) {
LOG.error( "Can not start region server because "+
StringUtils.stringifyException(t) );
System.exit(-1);
}
break;
}
if (cmd.equals("stop")) {
printUsageAndExit("To shutdown the regionserver run " +
"bin/hbase-daemon.sh stop regionserver or send a kill signal to" +
"the regionserver pid");
}
// Print out usage if we get to here.
printUsageAndExit();
}
}
/**
* @param args
*/
public static void main(String [] args) {
Configuration conf = new HBaseConfiguration();
@SuppressWarnings("unchecked")
Class<? extends HRegionServer> regionServerClass = (Class<? extends HRegionServer>) conf
.getClass(HConstants.REGION_SERVER_IMPL, HRegionServer.class);
doMain(args, regionServerClass);
}
}
| true | true | public void run() {
boolean quiesceRequested = false;
// A sleeper that sleeps for msgInterval.
Sleeper sleeper = new Sleeper(this.msgInterval, this.stopRequested);
try {
init(reportForDuty(sleeper));
long lastMsg = 0;
// Now ask master what it wants us to do and tell it what we have done
for (int tries = 0; !stopRequested.get() && isHealthy();) {
long now = System.currentTimeMillis();
if (lastMsg != 0 && (now - lastMsg) >= serverLeaseTimeout) {
// It has been way too long since we last reported to the master.
LOG.warn("unable to report to master for " + (now - lastMsg) +
" milliseconds - retrying");
}
if ((now - lastMsg) >= msgInterval) {
HMsg outboundArray[] = null;
synchronized(this.outboundMsgs) {
outboundArray =
this.outboundMsgs.toArray(new HMsg[outboundMsgs.size()]);
this.outboundMsgs.clear();
}
try {
doMetrics();
this.serverInfo.setLoad(new HServerLoad(requestCount.get(),
onlineRegions.size(), this.metrics.storefiles.get(),
this.metrics.memcacheSizeMB.get()));
this.requestCount.set(0);
HMsg msgs[] = hbaseMaster.regionServerReport(
serverInfo, outboundArray, getMostLoadedRegions());
lastMsg = System.currentTimeMillis();
if (this.quiesced.get() && onlineRegions.size() == 0) {
// We've just told the master we're exiting because we aren't
// serving any regions. So set the stop bit and exit.
LOG.info("Server quiesced and not serving any regions. " +
"Starting shutdown");
stopRequested.set(true);
this.outboundMsgs.clear();
continue;
}
// Queue up the HMaster's instruction stream for processing
boolean restart = false;
for(int i = 0;
!restart && !stopRequested.get() && i < msgs.length;
i++) {
LOG.info(msgs[i].toString());
switch(msgs[i].getType()) {
case MSG_CALL_SERVER_STARTUP:
// We the MSG_CALL_SERVER_STARTUP on startup but we can also
// get it when the master is panicing because for instance
// the HDFS has been yanked out from under it. Be wary of
// this message.
if (checkFileSystem()) {
closeAllRegions();
try {
log.closeAndDelete();
} catch (Exception e) {
LOG.error("error closing and deleting HLog", e);
}
try {
serverInfo.setStartCode(System.currentTimeMillis());
log = setupHLog();
this.logFlusher.setHLog(log);
} catch (IOException e) {
this.abortRequested = true;
this.stopRequested.set(true);
e = RemoteExceptionHandler.checkIOException(e);
LOG.fatal("error restarting server", e);
break;
}
reportForDuty(sleeper);
restart = true;
} else {
LOG.fatal("file system available check failed. " +
"Shutting down server.");
}
break;
case MSG_REGIONSERVER_STOP:
stopRequested.set(true);
break;
case MSG_REGIONSERVER_QUIESCE:
if (!quiesceRequested) {
try {
toDo.put(new ToDoEntry(msgs[i]));
} catch (InterruptedException e) {
throw new RuntimeException("Putting into msgQueue was " +
"interrupted.", e);
}
quiesceRequested = true;
}
break;
default:
if (fsOk) {
try {
toDo.put(new ToDoEntry(msgs[i]));
} catch (InterruptedException e) {
throw new RuntimeException("Putting into msgQueue was " +
"interrupted.", e);
}
}
}
}
// Reset tries count if we had a successful transaction.
tries = 0;
if (restart || this.stopRequested.get()) {
toDo.clear();
continue;
}
} catch (Exception e) {
if (e instanceof IOException) {
e = RemoteExceptionHandler.checkIOException((IOException) e);
}
if (tries < this.numRetries) {
LOG.warn("Processing message (Retry: " + tries + ")", e);
tries++;
} else {
LOG.error("Exceeded max retries: " + this.numRetries, e);
checkFileSystem();
}
}
}
// Do some housekeeping before going to sleep
housekeeping();
sleeper.sleep(lastMsg);
} // for
} catch (OutOfMemoryError error) {
abort();
LOG.fatal("Ran out of memory", error);
} catch (Throwable t) {
LOG.fatal("Unhandled exception. Aborting...", t);
abort();
}
RegionHistorian.getInstance().offline();
this.leases.closeAfterLeasesExpire();
this.worker.stop();
this.server.stop();
if (this.infoServer != null) {
LOG.info("Stopping infoServer");
try {
this.infoServer.stop();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
// Send interrupts to wake up threads if sleeping so they notice shutdown.
// TODO: Should we check they are alive? If OOME could have exited already
cacheFlusher.interruptIfNecessary();
logFlusher.interrupt();
compactSplitThread.interruptIfNecessary();
logRoller.interruptIfNecessary();
if (abortRequested) {
if (this.fsOk) {
// Only try to clean up if the file system is available
try {
if (this.log != null) {
this.log.close();
LOG.info("On abort, closed hlog");
}
} catch (IOException e) {
LOG.error("Unable to close log in abort",
RemoteExceptionHandler.checkIOException(e));
}
closeAllRegions(); // Don't leave any open file handles
}
LOG.info("aborting server at: " +
serverInfo.getServerAddress().toString());
} else {
ArrayList<HRegion> closedRegions = closeAllRegions();
try {
log.closeAndDelete();
} catch (IOException e) {
LOG.error("Close and delete failed",
RemoteExceptionHandler.checkIOException(e));
}
try {
HMsg[] exitMsg = new HMsg[closedRegions.size() + 1];
exitMsg[0] = HMsg.REPORT_EXITING;
// Tell the master what regions we are/were serving
int i = 1;
for (HRegion region: closedRegions) {
exitMsg[i++] = new HMsg(HMsg.Type.MSG_REPORT_CLOSE,
region.getRegionInfo());
}
LOG.info("telling master that region server is shutting down at: " +
serverInfo.getServerAddress().toString());
hbaseMaster.regionServerReport(serverInfo, exitMsg, (HRegionInfo[])null);
} catch (IOException e) {
LOG.warn("Failed to send exiting message to master: ",
RemoteExceptionHandler.checkIOException(e));
}
LOG.info("stopping server at: " +
serverInfo.getServerAddress().toString());
}
if (this.hbaseMaster != null) {
HbaseRPC.stopProxy(this.hbaseMaster);
this.hbaseMaster = null;
}
join();
LOG.info(Thread.currentThread().getName() + " exiting");
}
| public void run() {
boolean quiesceRequested = false;
// A sleeper that sleeps for msgInterval.
Sleeper sleeper = new Sleeper(this.msgInterval, this.stopRequested);
try {
init(reportForDuty(sleeper));
long lastMsg = 0;
// Now ask master what it wants us to do and tell it what we have done
for (int tries = 0; !stopRequested.get() && isHealthy();) {
long now = System.currentTimeMillis();
if (lastMsg != 0 && (now - lastMsg) >= serverLeaseTimeout) {
// It has been way too long since we last reported to the master.
LOG.warn("unable to report to master for " + (now - lastMsg) +
" milliseconds - retrying");
}
if ((now - lastMsg) >= msgInterval) {
HMsg outboundArray[] = null;
synchronized(this.outboundMsgs) {
outboundArray =
this.outboundMsgs.toArray(new HMsg[outboundMsgs.size()]);
this.outboundMsgs.clear();
}
try {
doMetrics();
this.serverInfo.setLoad(new HServerLoad(requestCount.get(),
onlineRegions.size(), this.metrics.storefiles.get(),
this.metrics.memcacheSizeMB.get()));
this.requestCount.set(0);
HMsg msgs[] = hbaseMaster.regionServerReport(
serverInfo, outboundArray, getMostLoadedRegions());
lastMsg = System.currentTimeMillis();
if (this.quiesced.get() && onlineRegions.size() == 0) {
// We've just told the master we're exiting because we aren't
// serving any regions. So set the stop bit and exit.
LOG.info("Server quiesced and not serving any regions. " +
"Starting shutdown");
stopRequested.set(true);
this.outboundMsgs.clear();
continue;
}
// Queue up the HMaster's instruction stream for processing
boolean restart = false;
for(int i = 0;
!restart && !stopRequested.get() && i < msgs.length;
i++) {
LOG.info(msgs[i].toString());
switch(msgs[i].getType()) {
case MSG_CALL_SERVER_STARTUP:
// We the MSG_CALL_SERVER_STARTUP on startup but we can also
// get it when the master is panicing because for instance
// the HDFS has been yanked out from under it. Be wary of
// this message.
if (checkFileSystem()) {
closeAllRegions();
try {
log.closeAndDelete();
} catch (Exception e) {
LOG.error("error closing and deleting HLog", e);
}
try {
serverInfo.setStartCode(System.currentTimeMillis());
log = setupHLog();
this.logFlusher.setHLog(log);
} catch (IOException e) {
this.abortRequested = true;
this.stopRequested.set(true);
e = RemoteExceptionHandler.checkIOException(e);
LOG.fatal("error restarting server", e);
break;
}
reportForDuty(sleeper);
restart = true;
} else {
LOG.fatal("file system available check failed. " +
"Shutting down server.");
}
break;
case MSG_REGIONSERVER_STOP:
stopRequested.set(true);
break;
case MSG_REGIONSERVER_QUIESCE:
if (!quiesceRequested) {
try {
toDo.put(new ToDoEntry(msgs[i]));
} catch (InterruptedException e) {
throw new RuntimeException("Putting into msgQueue was " +
"interrupted.", e);
}
quiesceRequested = true;
}
break;
default:
if (fsOk) {
try {
toDo.put(new ToDoEntry(msgs[i]));
} catch (InterruptedException e) {
throw new RuntimeException("Putting into msgQueue was " +
"interrupted.", e);
}
}
}
}
// Reset tries count if we had a successful transaction.
tries = 0;
if (restart || this.stopRequested.get()) {
toDo.clear();
continue;
}
} catch (Exception e) {
if (e instanceof IOException) {
e = RemoteExceptionHandler.checkIOException((IOException) e);
}
if (tries < this.numRetries) {
LOG.warn("Processing message (Retry: " + tries + ")", e);
tries++;
} else {
LOG.error("Exceeded max retries: " + this.numRetries, e);
checkFileSystem();
}
if (this.stopRequested.get()) {
LOG.info("Stop was requested, clearing the toDo " +
"despite of the exception");
toDo.clear();
continue;
}
}
}
// Do some housekeeping before going to sleep
housekeeping();
sleeper.sleep(lastMsg);
} // for
} catch (OutOfMemoryError error) {
abort();
LOG.fatal("Ran out of memory", error);
} catch (Throwable t) {
LOG.fatal("Unhandled exception. Aborting...", t);
abort();
}
RegionHistorian.getInstance().offline();
this.leases.closeAfterLeasesExpire();
this.worker.stop();
this.server.stop();
if (this.infoServer != null) {
LOG.info("Stopping infoServer");
try {
this.infoServer.stop();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
// Send interrupts to wake up threads if sleeping so they notice shutdown.
// TODO: Should we check they are alive? If OOME could have exited already
cacheFlusher.interruptIfNecessary();
logFlusher.interrupt();
compactSplitThread.interruptIfNecessary();
logRoller.interruptIfNecessary();
if (abortRequested) {
if (this.fsOk) {
// Only try to clean up if the file system is available
try {
if (this.log != null) {
this.log.close();
LOG.info("On abort, closed hlog");
}
} catch (IOException e) {
LOG.error("Unable to close log in abort",
RemoteExceptionHandler.checkIOException(e));
}
closeAllRegions(); // Don't leave any open file handles
}
LOG.info("aborting server at: " +
serverInfo.getServerAddress().toString());
} else {
ArrayList<HRegion> closedRegions = closeAllRegions();
try {
log.closeAndDelete();
} catch (IOException e) {
LOG.error("Close and delete failed",
RemoteExceptionHandler.checkIOException(e));
}
try {
HMsg[] exitMsg = new HMsg[closedRegions.size() + 1];
exitMsg[0] = HMsg.REPORT_EXITING;
// Tell the master what regions we are/were serving
int i = 1;
for (HRegion region: closedRegions) {
exitMsg[i++] = new HMsg(HMsg.Type.MSG_REPORT_CLOSE,
region.getRegionInfo());
}
LOG.info("telling master that region server is shutting down at: " +
serverInfo.getServerAddress().toString());
hbaseMaster.regionServerReport(serverInfo, exitMsg, (HRegionInfo[])null);
} catch (IOException e) {
LOG.warn("Failed to send exiting message to master: ",
RemoteExceptionHandler.checkIOException(e));
}
LOG.info("stopping server at: " +
serverInfo.getServerAddress().toString());
}
if (this.hbaseMaster != null) {
HbaseRPC.stopProxy(this.hbaseMaster);
this.hbaseMaster = null;
}
join();
LOG.info(Thread.currentThread().getName() + " exiting");
}
|
diff --git a/src/main/java/se/bhg/photos/service/impl/BhgV4ImporterServiceImpl.java b/src/main/java/se/bhg/photos/service/impl/BhgV4ImporterServiceImpl.java
index eed5915..28fbeeb 100644
--- a/src/main/java/se/bhg/photos/service/impl/BhgV4ImporterServiceImpl.java
+++ b/src/main/java/se/bhg/photos/service/impl/BhgV4ImporterServiceImpl.java
@@ -1,105 +1,105 @@
package se.bhg.photos.service.impl;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import com.drew.imaging.ImageProcessingException;
import se.bhg.photos.exception.PhotoAlreadyExistsException;
import se.bhg.photos.model.Photo;
import se.bhg.photos.service.BhgV4ImporterService;
import se.bhg.photos.service.FileService;
import se.bhg.photos.service.PhotoService;
@Service
public class BhgV4ImporterServiceImpl implements BhgV4ImporterService{
private static final Logger LOG = LoggerFactory.getLogger(FileServiceImpl.class);
private final static String BASE_PATH_V4 = "/tmp/oldbhg/";
@Autowired
JdbcTemplate jdbcTemplateImages;
@Autowired
FileService fileService;
@Autowired
PhotoService photoService;
@Override
public void importImagesAndGalleries() throws PhotoAlreadyExistsException {
//importGalleries();
importImages();
}
private void importGalleries() {
List<Map<String, Object>> result = jdbcTemplateImages.queryForList("select * from gallery");
for (Map<String, Object> row: result) {
LOG.info("Found gallery!");
for (Map.Entry<String, Object> entry : row.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
LOG.info(key + " = " + value);
}
}
}
private void importImages() throws PhotoAlreadyExistsException {
long start = System.currentTimeMillis();
List<Map<String, Object>> result = jdbcTemplateImages.queryForList("select * from image");
int n = 0;
for (Map<String, Object> row: result) {
LOG.info("Found images!");
String file = (String) row.get("filename");
int lastSlash = file.lastIndexOf("/");
String fileName = null;
if (lastSlash < file.length() && lastSlash > 0) {
fileName = file.substring(lastSlash + 1);
} else {
LOG.error("Could not find slash in {}", file);
continue;
}
String filePath = BASE_PATH_V4 + file;
byte[] fileData;
try {
fileData = fileService.readFile(BASE_PATH_V4 + file);
} catch (IOException e) {
LOG.error("Could not read file {}: {}", filePath, e.getLocalizedMessage());
e.printStackTrace();
continue;
}
String uuid = UUID.randomUUID().toString();
String username = (String) row.get("owner");
- String gallery = (String) row.get("gallery");
+ String gallery = Integer.toString((int) row.get("gallery"));
try {
Photo photo = photoService.addPhoto(fileName, fileData, username, uuid, gallery);
photo.setViews(Integer.parseInt((String) row.get("views")));
photo.setOldId(Integer.parseInt((String) row.get("id")));
photo.setImported(true);
photoService.save(photo);
} catch (ImageProcessingException | IOException | PhotoAlreadyExistsException e) {
LOG.error("Could not add file {}: {}", filePath, e.getLocalizedMessage());
e.printStackTrace();
}
n++;
/*
for (Map.Entry<String, Object> entry : row.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
LOG.info(key + " = " + value);
}
*/
}
long end = System.currentTimeMillis();
LOG.info("Imported {} images in {}ms", n, end-start);
}
}
| true | true | private void importImages() throws PhotoAlreadyExistsException {
long start = System.currentTimeMillis();
List<Map<String, Object>> result = jdbcTemplateImages.queryForList("select * from image");
int n = 0;
for (Map<String, Object> row: result) {
LOG.info("Found images!");
String file = (String) row.get("filename");
int lastSlash = file.lastIndexOf("/");
String fileName = null;
if (lastSlash < file.length() && lastSlash > 0) {
fileName = file.substring(lastSlash + 1);
} else {
LOG.error("Could not find slash in {}", file);
continue;
}
String filePath = BASE_PATH_V4 + file;
byte[] fileData;
try {
fileData = fileService.readFile(BASE_PATH_V4 + file);
} catch (IOException e) {
LOG.error("Could not read file {}: {}", filePath, e.getLocalizedMessage());
e.printStackTrace();
continue;
}
String uuid = UUID.randomUUID().toString();
String username = (String) row.get("owner");
String gallery = (String) row.get("gallery");
try {
Photo photo = photoService.addPhoto(fileName, fileData, username, uuid, gallery);
photo.setViews(Integer.parseInt((String) row.get("views")));
photo.setOldId(Integer.parseInt((String) row.get("id")));
photo.setImported(true);
photoService.save(photo);
} catch (ImageProcessingException | IOException | PhotoAlreadyExistsException e) {
LOG.error("Could not add file {}: {}", filePath, e.getLocalizedMessage());
e.printStackTrace();
}
n++;
/*
for (Map.Entry<String, Object> entry : row.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
LOG.info(key + " = " + value);
}
*/
}
long end = System.currentTimeMillis();
LOG.info("Imported {} images in {}ms", n, end-start);
}
| private void importImages() throws PhotoAlreadyExistsException {
long start = System.currentTimeMillis();
List<Map<String, Object>> result = jdbcTemplateImages.queryForList("select * from image");
int n = 0;
for (Map<String, Object> row: result) {
LOG.info("Found images!");
String file = (String) row.get("filename");
int lastSlash = file.lastIndexOf("/");
String fileName = null;
if (lastSlash < file.length() && lastSlash > 0) {
fileName = file.substring(lastSlash + 1);
} else {
LOG.error("Could not find slash in {}", file);
continue;
}
String filePath = BASE_PATH_V4 + file;
byte[] fileData;
try {
fileData = fileService.readFile(BASE_PATH_V4 + file);
} catch (IOException e) {
LOG.error("Could not read file {}: {}", filePath, e.getLocalizedMessage());
e.printStackTrace();
continue;
}
String uuid = UUID.randomUUID().toString();
String username = (String) row.get("owner");
String gallery = Integer.toString((int) row.get("gallery"));
try {
Photo photo = photoService.addPhoto(fileName, fileData, username, uuid, gallery);
photo.setViews(Integer.parseInt((String) row.get("views")));
photo.setOldId(Integer.parseInt((String) row.get("id")));
photo.setImported(true);
photoService.save(photo);
} catch (ImageProcessingException | IOException | PhotoAlreadyExistsException e) {
LOG.error("Could not add file {}: {}", filePath, e.getLocalizedMessage());
e.printStackTrace();
}
n++;
/*
for (Map.Entry<String, Object> entry : row.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
LOG.info(key + " = " + value);
}
*/
}
long end = System.currentTimeMillis();
LOG.info("Imported {} images in {}ms", n, end-start);
}
|
diff --git a/src/org/meta_environment/rascal/interpreter/env/JavaFunction.java b/src/org/meta_environment/rascal/interpreter/env/JavaFunction.java
index 5b4189af26..25a2636504 100644
--- a/src/org/meta_environment/rascal/interpreter/env/JavaFunction.java
+++ b/src/org/meta_environment/rascal/interpreter/env/JavaFunction.java
@@ -1,75 +1,75 @@
package org.meta_environment.rascal.interpreter.env;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collections;
import org.eclipse.imp.pdb.facts.IValue;
import org.eclipse.imp.pdb.facts.impl.reference.ValueFactory;
import org.eclipse.imp.pdb.facts.type.Type;
import org.meta_environment.rascal.ast.FunctionDeclaration;
import org.meta_environment.rascal.interpreter.Evaluator;
import org.meta_environment.rascal.interpreter.JavaBridge;
import org.meta_environment.rascal.interpreter.Names;
import org.meta_environment.rascal.interpreter.errors.Error;
import org.meta_environment.rascal.interpreter.errors.ImplementationError;
public class JavaFunction extends Lambda {
private final Method method;
private FunctionDeclaration func;
@SuppressWarnings("unchecked")
public JavaFunction(Evaluator eval, FunctionDeclaration func, boolean varargs, Environment env, JavaBridge javaBridge) {
super(eval, TE.eval(func.getSignature().getType(),env),
Names.name(func.getSignature().getName()),
TE.eval(func.getSignature().getParameters(), env),
varargs,
Collections.EMPTY_LIST, env);
this.method = javaBridge.compileJavaMethod(func);
this.func = func;
}
@Override
public Result call(IValue[] actuals, Type actualTypes, Environment env) {
if (hasVarArgs) {
actuals = computeVarArgsActuals(actuals, formals);
}
IValue result = invoke(actuals);
if (hasVarArgs) {
actualTypes = computeVarArgsActualTypes(actualTypes, formals);
}
bindTypeParameters(actualTypes, formals, env);
Type resultType = returnType.instantiate(env.getTypeBindings());
return new Result(resultType, result);
}
public IValue invoke(IValue[] actuals) {
try {
return (IValue) method.invoke(null, (Object[]) actuals);
} catch (SecurityException e) {
- throw new ImplementationError("Unexpected security exception" + e);
+ throw new ImplementationError("Unexpected security exception", e);
} catch (IllegalArgumentException e) {
- throw new ImplementationError("An illegal argument was generated for a generated method" + e);
+ throw new ImplementationError("An illegal argument was generated for a generated method", e);
} catch (IllegalAccessException e) {
- throw new ImplementationError("Unexpected illegal access exception" + e);
+ throw new ImplementationError("Unexpected illegal access exception", e);
} catch (InvocationTargetException e) {
Throwable targetException = e.getTargetException();
if (targetException instanceof Error) {
throw (Error) targetException;
}
else {
- throw new Error(null, targetException.getMessage());
+ throw new ImplementationError("Unexepected Error", e);
}
}
}
@Override
public String toString() {
return func.toString();
}
}
| false | true | public IValue invoke(IValue[] actuals) {
try {
return (IValue) method.invoke(null, (Object[]) actuals);
} catch (SecurityException e) {
throw new ImplementationError("Unexpected security exception" + e);
} catch (IllegalArgumentException e) {
throw new ImplementationError("An illegal argument was generated for a generated method" + e);
} catch (IllegalAccessException e) {
throw new ImplementationError("Unexpected illegal access exception" + e);
} catch (InvocationTargetException e) {
Throwable targetException = e.getTargetException();
if (targetException instanceof Error) {
throw (Error) targetException;
}
else {
throw new Error(null, targetException.getMessage());
}
}
}
| public IValue invoke(IValue[] actuals) {
try {
return (IValue) method.invoke(null, (Object[]) actuals);
} catch (SecurityException e) {
throw new ImplementationError("Unexpected security exception", e);
} catch (IllegalArgumentException e) {
throw new ImplementationError("An illegal argument was generated for a generated method", e);
} catch (IllegalAccessException e) {
throw new ImplementationError("Unexpected illegal access exception", e);
} catch (InvocationTargetException e) {
Throwable targetException = e.getTargetException();
if (targetException instanceof Error) {
throw (Error) targetException;
}
else {
throw new ImplementationError("Unexepected Error", e);
}
}
}
|
diff --git a/src/main/com/mucommander/ui/tabs/MultipleTabsDisplay.java b/src/main/com/mucommander/ui/tabs/MultipleTabsDisplay.java
index 5ff2725c..2d0474aa 100644
--- a/src/main/com/mucommander/ui/tabs/MultipleTabsDisplay.java
+++ b/src/main/com/mucommander/ui/tabs/MultipleTabsDisplay.java
@@ -1,201 +1,196 @@
/*
* This file is part of muCommander, http://www.mucommander.com
* Copyright (C) 2002-2010 Maxence Bernard
*
* muCommander is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* muCommander is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mucommander.ui.tabs;
import java.awt.Component;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
/**
* Component that present multiple tabs
*
* @author Arik Hadas
*/
public class MultipleTabsDisplay<T extends Tab> extends TabsDisplay<T> implements TabsChangeListener, ChangeListener {
private TabsCollection<T> tabs;
private TabbedPane<T> pane;
public MultipleTabsDisplay(TabsCollection<T> tabs, TabbedPane<T> tabbedpane) {
super(tabbedpane, tabs);
this.tabs = tabs;
this.pane = tabbedpane;
int index = 0;
for (T tab : tabs)
tabbedpane.set(tab, index++);
tabs.addTabsListener(this);
pane.addChangeListener(this);
}
@Override
public int getSelectedTabIndex() {
return pane.getSelectedIndex();
}
public void removeTab(int index) {
pane.remove(index);
}
/*********************
* TabsChangeListener
*********************/
@Override
public void tabUpdated(int index) {
update(tabs.get(index), index);
}
@Override
public void tabAdded(int index) {
add(tabs.get(index), index);
}
@Override
public void tabRemoved(int index) {
removeTab(index);
}
/*****************
* ChangeListener
*****************/
@Override
public void stateChanged(ChangeEvent e) {
int selectedIndex = getSelectedTabIndex();
if (selectedIndex != -1)
show(tabs.get(selectedIndex));
}
/**************
* TabsDisplay
**************/
@Override
public void add(T tab) {
add(tab, tabs.count());
}
@Override
public void add(T tab, int index) {
pane.add(tab, index);
}
@Override
public void update(T tab, int index) {
pane.update(tab, index);
}
@Override
public void show(T t) {
pane.show(t);
}
@Override
public void destroy() {
tabs.removeTabsListener(this);
pane.removeChangeListener(this);
}
@Override
public void setSelectedTabIndex(int index) {
pane.setSelectedIndex(index);
}
@Override
public void requestFocus() {
pane.requestFocusInWindow();
}
@Override
public T removeCurrentTab() {
T tab = tabs.get(getSelectedTabIndex());
tabs.remove(getSelectedTabIndex());
return tab;
}
@Override
public void removeDuplicateTabs() {
// a Set that will contain the tabs we've seen
Set<T> visitedTabs = new HashSet<T>();
// a Set that will contain the tabs which are duplicated
Set<T> duplicatedTabs = new HashSet<T>();
// The index of the selected tab
int selectedTabIndex = getSelectedTabIndex();
// add all duplicated tabs to the duplicatedTab Set
Iterator<T> existingTabsIterator = tabs.iterator();
while (existingTabsIterator.hasNext()) {
T tab = existingTabsIterator.next();
if (!visitedTabs.add(tab))
duplicatedTabs.add(tab);
}
// remove all duplicated tabs which are identical to the selected tab without
// changing the tab selection
T selectedTab = tabs.get(selectedTabIndex);
if (duplicatedTabs.remove(selectedTab)) {
int removedTabsCount = 0;
int tabsCount = tabs.count();
for (int i=0; i<tabsCount; ++i) {
if (i == selectedTabIndex) // do not remove the selected tab
continue;
if (selectedTab.equals(tabs.get(i-removedTabsCount)))
tabs.remove(i-removedTabsCount++);
}
}
// remove all other duplicated tabs
- int removedTabsCount = 0;
- int tabsCount = tabs.count();
- for (int i = 0; i < tabsCount - removedTabsCount; ++i) {
+ for (int i = 0; i < tabs.count(); ++i) {
T currentTab = tabs.get(i);
if (duplicatedTabs.remove(currentTab)) {
- int removedTabsInIterationCount = 0;
- for (int j = i + 1; j < tabsCount; ++j)
- if (currentTab.equals(tabs.get(j - removedTabsInIterationCount))) {
- tabs.remove(j - removedTabsInIterationCount++);
- ++removedTabsCount;
- }
+ for (int j = i + 1; j < tabs.count(); ++j)
+ if (currentTab.equals(tabs.get(j)))
+ tabs.remove(j--);
}
}
}
@Override
public void removeOtherTabs() {
int selectedTabIndex = getSelectedTabIndex();
for (int i=0; i<selectedTabIndex; ++i)
tabs.remove(0);
for(int i=tabs.count()-1; i>0; --i)
tabs.remove(1);
}
@Override
public void removeTab(Component header) {
tabs.remove(pane.indexOfTabComponent(header));
}
}
| false | true | public void removeDuplicateTabs() {
// a Set that will contain the tabs we've seen
Set<T> visitedTabs = new HashSet<T>();
// a Set that will contain the tabs which are duplicated
Set<T> duplicatedTabs = new HashSet<T>();
// The index of the selected tab
int selectedTabIndex = getSelectedTabIndex();
// add all duplicated tabs to the duplicatedTab Set
Iterator<T> existingTabsIterator = tabs.iterator();
while (existingTabsIterator.hasNext()) {
T tab = existingTabsIterator.next();
if (!visitedTabs.add(tab))
duplicatedTabs.add(tab);
}
// remove all duplicated tabs which are identical to the selected tab without
// changing the tab selection
T selectedTab = tabs.get(selectedTabIndex);
if (duplicatedTabs.remove(selectedTab)) {
int removedTabsCount = 0;
int tabsCount = tabs.count();
for (int i=0; i<tabsCount; ++i) {
if (i == selectedTabIndex) // do not remove the selected tab
continue;
if (selectedTab.equals(tabs.get(i-removedTabsCount)))
tabs.remove(i-removedTabsCount++);
}
}
// remove all other duplicated tabs
int removedTabsCount = 0;
int tabsCount = tabs.count();
for (int i = 0; i < tabsCount - removedTabsCount; ++i) {
T currentTab = tabs.get(i);
if (duplicatedTabs.remove(currentTab)) {
int removedTabsInIterationCount = 0;
for (int j = i + 1; j < tabsCount; ++j)
if (currentTab.equals(tabs.get(j - removedTabsInIterationCount))) {
tabs.remove(j - removedTabsInIterationCount++);
++removedTabsCount;
}
}
}
}
| public void removeDuplicateTabs() {
// a Set that will contain the tabs we've seen
Set<T> visitedTabs = new HashSet<T>();
// a Set that will contain the tabs which are duplicated
Set<T> duplicatedTabs = new HashSet<T>();
// The index of the selected tab
int selectedTabIndex = getSelectedTabIndex();
// add all duplicated tabs to the duplicatedTab Set
Iterator<T> existingTabsIterator = tabs.iterator();
while (existingTabsIterator.hasNext()) {
T tab = existingTabsIterator.next();
if (!visitedTabs.add(tab))
duplicatedTabs.add(tab);
}
// remove all duplicated tabs which are identical to the selected tab without
// changing the tab selection
T selectedTab = tabs.get(selectedTabIndex);
if (duplicatedTabs.remove(selectedTab)) {
int removedTabsCount = 0;
int tabsCount = tabs.count();
for (int i=0; i<tabsCount; ++i) {
if (i == selectedTabIndex) // do not remove the selected tab
continue;
if (selectedTab.equals(tabs.get(i-removedTabsCount)))
tabs.remove(i-removedTabsCount++);
}
}
// remove all other duplicated tabs
for (int i = 0; i < tabs.count(); ++i) {
T currentTab = tabs.get(i);
if (duplicatedTabs.remove(currentTab)) {
for (int j = i + 1; j < tabs.count(); ++j)
if (currentTab.equals(tabs.get(j)))
tabs.remove(j--);
}
}
}
|
diff --git a/src/gui/org/deidentifier/arx/gui/view/impl/analyze/ViewStatistics.java b/src/gui/org/deidentifier/arx/gui/view/impl/analyze/ViewStatistics.java
index 9e06de640..033d44f5b 100644
--- a/src/gui/org/deidentifier/arx/gui/view/impl/analyze/ViewStatistics.java
+++ b/src/gui/org/deidentifier/arx/gui/view/impl/analyze/ViewStatistics.java
@@ -1,43 +1,45 @@
package org.deidentifier.arx.gui.view.impl.analyze;
import java.awt.Panel;
import org.deidentifier.arx.DataHandle;
import org.deidentifier.arx.gui.model.Model;
import org.deidentifier.arx.gui.model.ModelEvent.ModelPart;
public abstract class ViewStatistics extends Panel{
private static final long serialVersionUID = 5170104283288654748L;
protected ModelPart target;
protected Model model;
/**
* Returns the data handle
* @return
*/
protected DataHandle getHandle() {
if (model != null){
if (target == ModelPart.INPUT){
DataHandle handle = model.getInputConfig().getInput().getHandle();
if (model.getViewConfig().isSubset() &&
model.getOutputConfig() != null &&
- model.getOutputConfig().getConfig() != null) {
+ model.getOutputConfig().getConfig() != null &&
+ handle != null) {
handle = handle.getView();
}
return handle;
} else {
DataHandle handle = model.getOutput();
if (model.getViewConfig().isSubset() &&
model.getOutputConfig() != null &&
- model.getOutputConfig().getConfig() != null) {
+ model.getOutputConfig().getConfig() != null &&
+ handle != null) {
handle = handle.getView();
}
return handle;
}
} else {
return null;
}
}
}
| false | true | protected DataHandle getHandle() {
if (model != null){
if (target == ModelPart.INPUT){
DataHandle handle = model.getInputConfig().getInput().getHandle();
if (model.getViewConfig().isSubset() &&
model.getOutputConfig() != null &&
model.getOutputConfig().getConfig() != null) {
handle = handle.getView();
}
return handle;
} else {
DataHandle handle = model.getOutput();
if (model.getViewConfig().isSubset() &&
model.getOutputConfig() != null &&
model.getOutputConfig().getConfig() != null) {
handle = handle.getView();
}
return handle;
}
} else {
return null;
}
}
| protected DataHandle getHandle() {
if (model != null){
if (target == ModelPart.INPUT){
DataHandle handle = model.getInputConfig().getInput().getHandle();
if (model.getViewConfig().isSubset() &&
model.getOutputConfig() != null &&
model.getOutputConfig().getConfig() != null &&
handle != null) {
handle = handle.getView();
}
return handle;
} else {
DataHandle handle = model.getOutput();
if (model.getViewConfig().isSubset() &&
model.getOutputConfig() != null &&
model.getOutputConfig().getConfig() != null &&
handle != null) {
handle = handle.getView();
}
return handle;
}
} else {
return null;
}
}
|
diff --git a/src/net/sf/freecol/client/gui/panel/RebelToolTip.java b/src/net/sf/freecol/client/gui/panel/RebelToolTip.java
index 62db50f2b..edd9dd354 100644
--- a/src/net/sf/freecol/client/gui/panel/RebelToolTip.java
+++ b/src/net/sf/freecol/client/gui/panel/RebelToolTip.java
@@ -1,115 +1,115 @@
/**
* Copyright (C) 2002-2011 The FreeCol Team
*
* This file is part of FreeCol.
*
* FreeCol is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* FreeCol is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FreeCol. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.freecol.client.gui.panel;
import java.awt.Dimension;
import javax.swing.JLabel;
import javax.swing.JToolTip;
import net.sf.freecol.client.gui.Canvas;
import net.sf.freecol.client.gui.i18n.Messages;
import net.sf.freecol.common.model.Colony;
import net.sf.freecol.common.model.GoodsType;
import net.sf.freecol.common.model.StringTemplate;
import net.miginfocom.swing.MigLayout;
/**
* This panel provides detailed information about rebels in a colony.
*/
public class RebelToolTip extends JToolTip {
/**
* Creates this RebelToolTip.
*
* @param colony the colony for which to display information
* @param parent a <code>Canvas</code> value
*/
public RebelToolTip(Colony colony, Canvas parent) {
setLayout(new MigLayout("fillx, wrap 3", "[][right][right]", ""));
int members = colony.getMembers();
int rebels = colony.getSoL();
add(new JLabel(Messages.message(StringTemplate.template("colonyPanel.rebelLabel")
.addName("%number%", ""))));
add(new JLabel(Integer.toString(members)));
add(new JLabel(Integer.toString(rebels) + "%"));
add(new JLabel(Messages.message(StringTemplate.template("colonyPanel.royalistLabel")
.addName("%number%", ""))));
add(new JLabel(Integer.toString(colony.getUnitCount() - members)));
add(new JLabel(Integer.toString(colony.getTory()) + "%"));
int libertyProduction = 0;
for (GoodsType goodsType : colony.getSpecification().getLibertyGoodsTypeList()) {
add(new JLabel(Messages.message(goodsType.getNameKey())));
int production = colony.getNetProductionOf(goodsType);
libertyProduction += production;
add(new ProductionLabel(goodsType, production, parent), "span 2");
}
int liberty = colony.getLiberty();
int modulo = liberty % Colony.LIBERTY_PER_REBEL;
FreeColProgressBar progress = new FreeColProgressBar(parent, null, 0, Colony.LIBERTY_PER_REBEL,
modulo, libertyProduction);
progress.setPreferredSize(new Dimension((int) getPreferredSize().getWidth() - 32, 20));
add(progress, "span 3");
float turns100 = 0;
float turns50 = 0;
float turnsNext = 0;
if (libertyProduction > 0) {
int requiredLiberty = Colony.LIBERTY_PER_REBEL * colony.getUnitCount();
if (liberty < requiredLiberty) {
- turns100 = (requiredLiberty - liberty) / libertyProduction;
+ turns100 = (requiredLiberty - liberty) / (float)libertyProduction;
}
requiredLiberty = requiredLiberty / 2;
if (liberty < requiredLiberty) {
- turns50 = (requiredLiberty - liberty) / libertyProduction;
+ turns50 = (requiredLiberty - liberty) / (float)libertyProduction;
}
if (members < colony.getUnitCount()) {
requiredLiberty = Colony.LIBERTY_PER_REBEL * (members + 1);
if (liberty < requiredLiberty) {
- turnsNext = (requiredLiberty - liberty) / libertyProduction;
+ turnsNext = (requiredLiberty - liberty) / (float)libertyProduction;
}
}
}
String na = Messages.message("notApplicable.short");
add(new JLabel(Messages.message("report.nextMember")));
add(new JLabel(turnsNext == 0 ? na : Integer.toString((int) Math.ceil(turnsNext))), "skip");
add(new JLabel(Messages.message("report.50percent")));
add(new JLabel(turns50 == 0 ? na : Integer.toString((int) Math.ceil(turns50))), "skip");
add(new JLabel(Messages.message("report.100percent")));
add(new JLabel(turns100 == 0 ? na : Integer.toString((int) Math.ceil(turns100))), "skip");
}
public Dimension getPreferredSize() {
return new Dimension(350, 250);
}
}
| false | true | public RebelToolTip(Colony colony, Canvas parent) {
setLayout(new MigLayout("fillx, wrap 3", "[][right][right]", ""));
int members = colony.getMembers();
int rebels = colony.getSoL();
add(new JLabel(Messages.message(StringTemplate.template("colonyPanel.rebelLabel")
.addName("%number%", ""))));
add(new JLabel(Integer.toString(members)));
add(new JLabel(Integer.toString(rebels) + "%"));
add(new JLabel(Messages.message(StringTemplate.template("colonyPanel.royalistLabel")
.addName("%number%", ""))));
add(new JLabel(Integer.toString(colony.getUnitCount() - members)));
add(new JLabel(Integer.toString(colony.getTory()) + "%"));
int libertyProduction = 0;
for (GoodsType goodsType : colony.getSpecification().getLibertyGoodsTypeList()) {
add(new JLabel(Messages.message(goodsType.getNameKey())));
int production = colony.getNetProductionOf(goodsType);
libertyProduction += production;
add(new ProductionLabel(goodsType, production, parent), "span 2");
}
int liberty = colony.getLiberty();
int modulo = liberty % Colony.LIBERTY_PER_REBEL;
FreeColProgressBar progress = new FreeColProgressBar(parent, null, 0, Colony.LIBERTY_PER_REBEL,
modulo, libertyProduction);
progress.setPreferredSize(new Dimension((int) getPreferredSize().getWidth() - 32, 20));
add(progress, "span 3");
float turns100 = 0;
float turns50 = 0;
float turnsNext = 0;
if (libertyProduction > 0) {
int requiredLiberty = Colony.LIBERTY_PER_REBEL * colony.getUnitCount();
if (liberty < requiredLiberty) {
turns100 = (requiredLiberty - liberty) / libertyProduction;
}
requiredLiberty = requiredLiberty / 2;
if (liberty < requiredLiberty) {
turns50 = (requiredLiberty - liberty) / libertyProduction;
}
if (members < colony.getUnitCount()) {
requiredLiberty = Colony.LIBERTY_PER_REBEL * (members + 1);
if (liberty < requiredLiberty) {
turnsNext = (requiredLiberty - liberty) / libertyProduction;
}
}
}
String na = Messages.message("notApplicable.short");
add(new JLabel(Messages.message("report.nextMember")));
add(new JLabel(turnsNext == 0 ? na : Integer.toString((int) Math.ceil(turnsNext))), "skip");
add(new JLabel(Messages.message("report.50percent")));
add(new JLabel(turns50 == 0 ? na : Integer.toString((int) Math.ceil(turns50))), "skip");
add(new JLabel(Messages.message("report.100percent")));
add(new JLabel(turns100 == 0 ? na : Integer.toString((int) Math.ceil(turns100))), "skip");
}
| public RebelToolTip(Colony colony, Canvas parent) {
setLayout(new MigLayout("fillx, wrap 3", "[][right][right]", ""));
int members = colony.getMembers();
int rebels = colony.getSoL();
add(new JLabel(Messages.message(StringTemplate.template("colonyPanel.rebelLabel")
.addName("%number%", ""))));
add(new JLabel(Integer.toString(members)));
add(new JLabel(Integer.toString(rebels) + "%"));
add(new JLabel(Messages.message(StringTemplate.template("colonyPanel.royalistLabel")
.addName("%number%", ""))));
add(new JLabel(Integer.toString(colony.getUnitCount() - members)));
add(new JLabel(Integer.toString(colony.getTory()) + "%"));
int libertyProduction = 0;
for (GoodsType goodsType : colony.getSpecification().getLibertyGoodsTypeList()) {
add(new JLabel(Messages.message(goodsType.getNameKey())));
int production = colony.getNetProductionOf(goodsType);
libertyProduction += production;
add(new ProductionLabel(goodsType, production, parent), "span 2");
}
int liberty = colony.getLiberty();
int modulo = liberty % Colony.LIBERTY_PER_REBEL;
FreeColProgressBar progress = new FreeColProgressBar(parent, null, 0, Colony.LIBERTY_PER_REBEL,
modulo, libertyProduction);
progress.setPreferredSize(new Dimension((int) getPreferredSize().getWidth() - 32, 20));
add(progress, "span 3");
float turns100 = 0;
float turns50 = 0;
float turnsNext = 0;
if (libertyProduction > 0) {
int requiredLiberty = Colony.LIBERTY_PER_REBEL * colony.getUnitCount();
if (liberty < requiredLiberty) {
turns100 = (requiredLiberty - liberty) / (float)libertyProduction;
}
requiredLiberty = requiredLiberty / 2;
if (liberty < requiredLiberty) {
turns50 = (requiredLiberty - liberty) / (float)libertyProduction;
}
if (members < colony.getUnitCount()) {
requiredLiberty = Colony.LIBERTY_PER_REBEL * (members + 1);
if (liberty < requiredLiberty) {
turnsNext = (requiredLiberty - liberty) / (float)libertyProduction;
}
}
}
String na = Messages.message("notApplicable.short");
add(new JLabel(Messages.message("report.nextMember")));
add(new JLabel(turnsNext == 0 ? na : Integer.toString((int) Math.ceil(turnsNext))), "skip");
add(new JLabel(Messages.message("report.50percent")));
add(new JLabel(turns50 == 0 ? na : Integer.toString((int) Math.ceil(turns50))), "skip");
add(new JLabel(Messages.message("report.100percent")));
add(new JLabel(turns100 == 0 ? na : Integer.toString((int) Math.ceil(turns100))), "skip");
}
|
diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/source/AnnotationPainter.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/source/AnnotationPainter.java
index 1bb533b00..e9e290956 100644
--- a/org.eclipse.jface.text/src/org/eclipse/jface/text/source/AnnotationPainter.java
+++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/source/AnnotationPainter.java
@@ -1,1012 +1,1012 @@
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jface.text.source;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.eclipse.core.runtime.Platform;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Display;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IPaintPositionManager;
import org.eclipse.jface.text.IPainter;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextInputListener;
import org.eclipse.jface.text.ITextPresentationListener;
import org.eclipse.jface.text.ITextViewerExtension2;
import org.eclipse.jface.text.ITextViewerExtension3;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.TextPresentation;
/**
* Paints annotations provided by an annotation model as squiggly lines and/or
* highlighted onto an associated source viewer.
* Clients usually instantiate and configure objects of this class.
*
* @since 2.1
*/
public class AnnotationPainter implements IPainter, PaintListener, IAnnotationModelListener, IAnnotationModelListenerExtension, ITextPresentationListener {
/**
* Tells whether this class is in debug mode.
* @since 3.0
*/
private static boolean DEBUG= "true".equalsIgnoreCase(Platform.getDebugOption("org.eclipse.jface.text/debug/AnnotationPainter")); //$NON-NLS-1$//$NON-NLS-2$
/**
* The presentation information (decoration) for an annotation. Each such
* object represents one squiggly.
*/
private static class Decoration {
/** The position of this decoration */
private Position fPosition;
/** The color of this decoration */
private Color fColor;
/**
* The annotation's layer
* @since 3.0
*/
private int fLayer;
}
/** Indicates whether this painter is active */
private boolean fIsActive= false;
/** Indicates whether this painter is managing decorations */
private boolean fIsPainting= false;
/** Indicates whether this painter is setting its annotation model */
private boolean fIsSettingModel= false;
/** The associated source viewer */
private ISourceViewer fSourceViewer;
/** The cached widget of the source viewer */
private StyledText fTextWidget;
/** The annotation model providing the annotations to be drawn */
private IAnnotationModel fModel;
/** The annotation access */
private IAnnotationAccess fAnnotationAccess;
/**
* The map with decorations
* @since 3.0
*/
private Map fDecorationsMap= new IdentityHashMap();
/**
* The map with of highlighted decorations.
* @since 3.0
*/
private Map fHighlightedDecorationsMap= new IdentityHashMap();
/** The internal color table */
private Map fColorTable= new HashMap();
/** The list of configured annotation types for being painted by this painter */
private Set fConfiguredAnnotationTypes= new HashSet();
/**
* The list of allowed annotation types for being painted by this painter.
* @since 3.0
*/
private Set fAllowedAnnotationTypes= new HashSet();
/**
* The list of configured annotation typed to be highlighted by this painter.
* @since 3.0
*/
private Set fConfiguredHighlightAnnotationTypes= new HashSet();
/**
* The list of allowed annotation types to be highlighted by this painter.
* @since 3.0
*/
private Set fAllowedHighlightAnnotationTypes= new HashSet();
/**
* The range in which the current highlight annotations can be found.
* @since 3.0
*/
private Position fCurrentHighlightAnnotationRange= null;
/**
* The range in which all add, removed and changed highlight
* annotations can be found since the last world change.
* @since 3.0
*/
private Position fTotalHighlightAnnotationRange= null;
/**
* The text input listener.
* @since 3.0
*/
private ITextInputListener fTextInputListener;
/**
* Flag which tells that a new document input is currently being set.
* @since 3.0
*/
private boolean fInputDocumentAboutToBeChanged;
/**
* Creates a new annotation painter for the given source viewer and with the given
* annotation access. The painter is uninitialized, i.e. no annotation types are configured
* to be painted.
*
* @param sourceViewer the source viewer for this painter
* @param access the annotation access for this painter
*/
public AnnotationPainter(ISourceViewer sourceViewer, IAnnotationAccess access) {
fSourceViewer= sourceViewer;
fAnnotationAccess= access;
fTextWidget= sourceViewer.getTextWidget();
}
/**
* Returns whether this painter has to draw any squiggle.
*
* @return <code>true</code> if there are squiggles to be drawn, <code>false</code> otherwise
*/
private boolean hasDecorations() {
return !fDecorationsMap.isEmpty();
}
/**
* Enables painting. This painter registers a paint listener with the
* source viewer's widget.
*/
private void enablePainting() {
if (!fIsPainting && hasDecorations()) {
fIsPainting= true;
fTextWidget.addPaintListener(this);
handleDrawRequest(null);
}
}
/**
* Disables painting, if is has previously been enabled. Removes
* any paint listeners registered with the source viewer's widget.
*
* @param redraw <code>true</code> if the widget should be redrawn after disabling
*/
private void disablePainting(boolean redraw) {
if (fIsPainting) {
fIsPainting= false;
fTextWidget.removePaintListener(this);
if (redraw && hasDecorations())
handleDrawRequest(null);
}
}
/**
* Sets the annotation model for this painter. Registers this painter
* as listener of the give model, if the model is not <code>null</code>.
*
* @param model the annotation model
*/
private void setModel(IAnnotationModel model) {
if (fModel != model) {
if (fModel != null)
fModel.removeAnnotationModelListener(this);
fModel= model;
if (fModel != null) {
synchronized(this) {
try {
fIsSettingModel= true;
fModel.addAnnotationModelListener(this);
} finally {
fIsSettingModel= false;
}
}
}
}
}
/**
* Updates the set of decorations based on the current state of
* the painter's annotation model.
*/
private synchronized void catchupWithModel(AnnotationModelEvent event) {
if (fDecorationsMap != null) {
int highlightAnnotationRangeStart= Integer.MAX_VALUE;
int highlightAnnotationRangeEnd= -1;
if (fModel != null) {
boolean isWorldChange= false;
Iterator e;
if (event == null || event.isWorldChange()) {
isWorldChange= true;
if (DEBUG && event == null)
System.out.println("AP: INTERNAL CHANGE"); //$NON-NLS-1$
fDecorationsMap.clear();
fHighlightedDecorationsMap.clear();
e= fModel.getAnnotationIterator();
} else {
// Remove annotations
Annotation[] removedAnnotations= event.getRemovedAnnotations();
for (int i=0, length= removedAnnotations.length; i < length; i++) {
Annotation annotation= removedAnnotations[i];
Decoration decoration= (Decoration)fHighlightedDecorationsMap.remove(annotation);
if (decoration != null) {
Position position= decoration.fPosition;
if (position != null && !position.isDeleted()) {
highlightAnnotationRangeStart= Math.min(highlightAnnotationRangeStart, position.offset);
highlightAnnotationRangeEnd= Math.max(highlightAnnotationRangeEnd, position.offset + position.length);
}
}
fDecorationsMap.remove(annotation);
}
// Update existing annotations
Annotation[] changedAnnotations= event.getChangedAnnotations();
for (int i=0, length= changedAnnotations.length; i < length; i++) {
Annotation annotation= changedAnnotations[i];
Object annotationType= annotation.getType();
boolean isHighlighting= shouldBeHighlighted(annotationType);
boolean isDrawingSquiggles= shouldBeDrawn(annotationType);
Decoration decoration= (Decoration)fHighlightedDecorationsMap.get(annotation);
if (decoration != null) {
// The call below updates the decoration - no need to create new decoration
decoration= getDecoration(annotation, decoration, isDrawingSquiggles, isHighlighting);
if (decoration == null)
fHighlightedDecorationsMap.remove(annotation);
} else {
decoration= getDecoration(annotation, decoration, isDrawingSquiggles, isHighlighting);
- if (decoration != null)
+ if (decoration != null && isHighlighting)
fHighlightedDecorationsMap.put(annotation, decoration);
}
Position position= null;
if (decoration == null)
position= fModel.getPosition(annotation);
else
position= decoration.fPosition;
if (position != null && !position.isDeleted()) {
highlightAnnotationRangeStart= Math.min(highlightAnnotationRangeStart, position.offset);
highlightAnnotationRangeEnd= Math.max(highlightAnnotationRangeEnd, position.offset + position.length);
} else {
fHighlightedDecorationsMap.remove(annotation);
}
Decoration oldDecoration= (Decoration)fDecorationsMap.get(annotation);
- if (decoration != null)
+ if (decoration != null && isDrawingSquiggles)
fDecorationsMap.put(annotation, decoration);
else if (oldDecoration != null)
fDecorationsMap.remove(annotation);
}
e= Arrays.asList(event.getAddedAnnotations()).iterator();
}
// Add new annotations
while (e.hasNext()) {
Annotation annotation= (Annotation) e.next();
Object annotationType= annotation.getType();
boolean isHighlighting= shouldBeHighlighted(annotationType);
boolean isDrawingSquiggles= shouldBeDrawn(annotationType);
Decoration pp= getDecoration(annotation, null, isDrawingSquiggles, isHighlighting);
if (pp != null) {
if (isDrawingSquiggles)
fDecorationsMap.put(annotation, pp);
if (isHighlighting) {
fHighlightedDecorationsMap.put(annotation, pp);
highlightAnnotationRangeStart= Math.min(highlightAnnotationRangeStart, pp.fPosition.offset);
highlightAnnotationRangeEnd= Math.max(highlightAnnotationRangeEnd, pp.fPosition.offset + pp.fPosition.length);
}
}
}
updateHighlightRanges(highlightAnnotationRangeStart, highlightAnnotationRangeEnd, isWorldChange);
}
}
}
/**
* Updates the remembered highlight ranges.
*
* @param highlightAnnotationRangeStart the start of the range
* @param highlightAnnotationRangeEnd the end of the range
* @param isWorldChange tells whether the range belongs to a annotation model event reporting a world change
* @since 3.0
*/
private void updateHighlightRanges(int highlightAnnotationRangeStart, int highlightAnnotationRangeEnd, boolean isWorldChange) {
if (highlightAnnotationRangeStart != Integer.MAX_VALUE) {
int maxRangeStart= highlightAnnotationRangeStart;
int maxRangeEnd= highlightAnnotationRangeEnd;
if (fTotalHighlightAnnotationRange != null) {
maxRangeStart= Math.min(maxRangeStart, fTotalHighlightAnnotationRange.offset);
maxRangeEnd= Math.max(maxRangeEnd, fTotalHighlightAnnotationRange.offset + fTotalHighlightAnnotationRange.length);
}
if (fTotalHighlightAnnotationRange == null)
fTotalHighlightAnnotationRange= new Position(0);
if (fCurrentHighlightAnnotationRange == null)
fCurrentHighlightAnnotationRange= new Position(0);
if (isWorldChange) {
fTotalHighlightAnnotationRange.offset= highlightAnnotationRangeStart;
fTotalHighlightAnnotationRange.length= highlightAnnotationRangeEnd - highlightAnnotationRangeStart;
fCurrentHighlightAnnotationRange.offset= maxRangeStart;
fCurrentHighlightAnnotationRange.length= maxRangeEnd - maxRangeStart;
} else {
fTotalHighlightAnnotationRange.offset= maxRangeStart;
fTotalHighlightAnnotationRange.length= maxRangeEnd - maxRangeStart;
fCurrentHighlightAnnotationRange.offset=highlightAnnotationRangeStart;
fCurrentHighlightAnnotationRange.length= highlightAnnotationRangeEnd - highlightAnnotationRangeStart;
}
} else {
if (isWorldChange) {
fCurrentHighlightAnnotationRange= fTotalHighlightAnnotationRange;
fTotalHighlightAnnotationRange= null;
} else {
fCurrentHighlightAnnotationRange= null;
}
}
adaptToDocumentLength(fCurrentHighlightAnnotationRange);
adaptToDocumentLength(fTotalHighlightAnnotationRange);
}
/**
* Adapts the given position to the document length.
*
* @param position the position to adapt
* @since 3.0
*/
private void adaptToDocumentLength(Position position) {
if (position == null)
return;
int length= fSourceViewer.getDocument().getLength();
position.offset= Math.min(position.offset, length);
position.length= Math.min(position.length, length - position.offset);
}
/**
* Returns a decoration for the given annotation if this
* annotation is valid and shown by this painter.
*
* @param annotation the annotation
* @param decoration the decoration to be adapted and returned or <code>null</code> if a new one must be created
* @param isDrawingSquiggles tells if squiggles should be drawn for this annotation
* @param isHighlighting tells if this annotation should be highlighted
* @return the decoration or <code>null</code> if there's no valid one
* @since 3.0
*/
private Decoration getDecoration(Annotation annotation, Decoration decoration, boolean isDrawingSquiggles, boolean isHighlighting) {
if (annotation.isMarkedDeleted())
return null;
Color color= null;
if (isDrawingSquiggles || isHighlighting)
color= findColor(annotation.getType());
if (color == null)
return null;
Position position= fModel.getPosition(annotation);
if (position == null || position.isDeleted())
return null;
if (decoration == null)
decoration= new Decoration();
decoration.fPosition= position;
decoration.fColor= color;
if (fAnnotationAccess instanceof IAnnotationAccessExtension) {
IAnnotationAccessExtension extension= (IAnnotationAccessExtension) fAnnotationAccess;
decoration.fLayer= extension.getLayer(annotation);
} else {
decoration.fLayer= IAnnotationAccessExtension.DEFAULT_LAYER;
}
return decoration;
}
/**
* Returns whether the given annotation type should be drawn.
*
* @param annotationType the annotation type
* @return <code>true</code> if annotation type should be drawn, <code>false</code>
* otherwise
* @since 3.0
*/
private boolean shouldBeDrawn(Object annotationType) {
return contains(annotationType, fAllowedAnnotationTypes, fConfiguredAnnotationTypes);
}
/**
* Returns whether the given annotation type should be highlighted.
*
* @param annotationType the annotation type
* @return <code>true</code> if annotation type should be highlighted, <code>false</code>
* otherwise
* @since 3.0
*/
private boolean shouldBeHighlighted(Object annotationType) {
return contains(annotationType, fAllowedHighlightAnnotationTypes, fConfiguredHighlightAnnotationTypes);
}
/**
* Returns whether the given annotation type is contained in the given <code>allowed</code>
* set. This is the case if the type is either in the set
* or covered by the <code>configured</code> set.
*
* @param annotationType the annotation type
* @return <code>true</code> if annotation is contained, <code>false</code>
* otherwise
* @since 3.0
*/
private boolean contains(Object annotationType, Set allowed, Set configured) {
if (allowed.contains(annotationType))
return true;
boolean covered= isCovered(annotationType, configured);
if (covered)
allowed.add(annotationType);
return covered;
}
/**
* Computes whether the annotations of the given type are covered by the given <code>configured</code>
* set. This is the case if either the type of the annotation or any of its
* super types is contained in the <code>configured</code> set.
*
* @param annotation the annotation
* @param annotationType the annotation type
* @return <code>true</code> if annotation is covered, <code>false</code>
* otherwise
* @since 3.0
*/
private boolean isCovered(Object annotationType, Set configured) {
if (fAnnotationAccess instanceof IAnnotationAccessExtension) {
IAnnotationAccessExtension extension= (IAnnotationAccessExtension) fAnnotationAccess;
Iterator e= configured.iterator();
while (e.hasNext()) {
if (extension.isSubtype(annotationType,e.next()))
return true;
}
return false;
}
return configured.contains(annotationType);
}
/**
* Returns the color for the given annotation type
*
* @param annotationType the annotation type
* @return the color
*/
private Color findColor(Object annotationType) {
Color color= (Color) fColorTable.get(annotationType);
if (color != null)
return color;
if (fAnnotationAccess instanceof IAnnotationAccessExtension) {
IAnnotationAccessExtension extension= (IAnnotationAccessExtension) fAnnotationAccess;
Object[] superTypes= extension.getSupertypes(annotationType);
if (superTypes != null) {
for (int i= superTypes.length -1; i > -1; i--) {
color= (Color) fColorTable.get(superTypes[i]);
if (color != null)
return color;
}
}
}
return null;
}
/**
* Recomputes the squiggles to be drawn and redraws them.
*/
private void updatePainting(AnnotationModelEvent event) {
disablePainting(true);
catchupWithModel(event);
if (!fInputDocumentAboutToBeChanged)
invalidateTextPresentation();
enablePainting();
}
private void invalidateTextPresentation() {
if (fCurrentHighlightAnnotationRange== null)
return;
if (fSourceViewer instanceof ITextViewerExtension2) {
IRegion r= new Region(fCurrentHighlightAnnotationRange.getOffset(), fCurrentHighlightAnnotationRange.getLength());
if (DEBUG)
System.out.println("AP: invalidating offset: " + r.getOffset() + ", length= " + r.getLength()); //$NON-NLS-1$ //$NON-NLS-2$
((ITextViewerExtension2)fSourceViewer).invalidateTextPresentation(r.getOffset(), r.getLength());
} else {
fSourceViewer.invalidateTextPresentation();
}
}
/*
* @see ITextPresentationListener#applyTextPresentation(TextPresentation)
* @since 3.0
*/
public synchronized void applyTextPresentation(TextPresentation tp) {
if (fHighlightedDecorationsMap == null || fHighlightedDecorationsMap.isEmpty())
return;
IRegion region= tp.getExtent();
if (DEBUG)
System.out.println("AP: applying text presentation offset: " + region.getOffset() + ", length= " + region.getLength()); //$NON-NLS-1$ //$NON-NLS-2$
for (int layer= 0, maxLayer= 1; layer < maxLayer; layer++) {
for (Iterator iter= fHighlightedDecorationsMap.values().iterator(); iter.hasNext();) {
Decoration pp = (Decoration)iter.next();
maxLayer= Math.max(maxLayer, pp.fLayer + 1); // dynamically update layer maximum
if (pp.fLayer != layer) // wrong layer: skip annotation
continue;
Position p= pp.fPosition;
if (!fSourceViewer.overlapsWithVisibleRegion(p.offset, p.length))
continue;
if (p.getOffset() + p.getLength() >= region.getOffset() && region.getOffset() + region.getLength() > p.getOffset())
tp.mergeStyleRange(new StyleRange(p.getOffset(), p.getLength(), null, pp.fColor));
}
}
}
/*
* @see IAnnotationModelListener#modelChanged(IAnnotationModel)
*/
public synchronized void modelChanged(final IAnnotationModel model) {
if (DEBUG)
System.err.println("AP: OLD API of AnnotationModelListener called"); //$NON-NLS-1$
modelChanged(new AnnotationModelEvent(model));
}
/*
* @see IAnnotationModelListenerExtension#modelChanged(AnnotationModelEvent)
*/
public synchronized void modelChanged(final AnnotationModelEvent event) {
if (fTextWidget != null && !fTextWidget.isDisposed()) {
if (fIsSettingModel) {
// inside the ui thread -> no need for posting
updatePainting(event);
} else {
Display d= fTextWidget.getDisplay();
if (DEBUG && event != null && event.isWorldChange()) {
System.out.println("AP: WORLD CHANGED, stack trace follows:"); //$NON-NLS-1$
try {
throw new Throwable();
} catch (Throwable t) {
t.printStackTrace(System.out);
}
}
if (d != null) {
d.asyncExec(new Runnable() {
public void run() {
if (fTextWidget != null && !fTextWidget.isDisposed())
updatePainting(event);
}
});
}
}
}
}
/**
* Sets the color in which the squiggly for the given annotation type should be drawn.
*
* @param annotationType the annotation type
* @param color the color
*/
public void setAnnotationTypeColor(Object annotationType, Color color) {
if (color != null)
fColorTable.put(annotationType, color);
else
fColorTable.remove(annotationType);
}
/**
* Adds the given annotation type to the list of annotation types whose
* annotations should be painted by this painter. If the annotation type
* is already in this list, this method is without effect.
*
* @param annotationType the annotation type
*/
public void addAnnotationType(Object annotationType) {
fConfiguredAnnotationTypes.add(annotationType);
}
/**
* Adds the given annotation type to the list of annotation types whose
* annotations should be highlighted this painter. If the annotation type
* is already in this list, this method is without effect.
*
* @param annotationType the annotation type
* @since 3.0
*/
public void addHighlightAnnotationType(Object annotationType) {
fConfiguredHighlightAnnotationTypes.add(annotationType);
if (fTextInputListener == null) {
fTextInputListener= new ITextInputListener() {
/*
* @see org.eclipse.jface.text.ITextInputListener#inputDocumentAboutToBeChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument)
*/
public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) {
fInputDocumentAboutToBeChanged= true;
}
/*
* @see org.eclipse.jface.text.ITextInputListener#inputDocumentChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument)
*/
public void inputDocumentChanged(IDocument oldInput, IDocument newInput) {
fInputDocumentAboutToBeChanged= false;
}
};
fSourceViewer.addTextInputListener(fTextInputListener);
}
}
/**
* Removes the given annotation type from the list of annotation types whose
* annotations are painted by this painter. If the annotation type is not
* in this list, this method is wihtout effect.
*
* @param annotationType the annotation type
*/
public void removeAnnotationType(Object annotationType) {
fConfiguredAnnotationTypes.remove(annotationType);
fAllowedAnnotationTypes.clear();
}
/**
* Removes the given annotation type from the list of annotation types whose
* annotations are highlighted by this painter. If the annotation type is not
* in this list, this method is wihtout effect.
*
* @param annotationType the annotation type
* @since 3.0
*/
public void removeHighlightAnnotationType(Object annotationType) {
fConfiguredHighlightAnnotationTypes.remove(annotationType);
fAllowedHighlightAnnotationTypes.clear();
if (fConfiguredHighlightAnnotationTypes.isEmpty() && fTextInputListener != null) {
fSourceViewer.removeTextInputListener(fTextInputListener);
fTextInputListener= null;
fInputDocumentAboutToBeChanged= false;
}
}
/**
* Clears the list of annotation types whose annotations are
* painted by this painter.
*/
public void removeAllAnnotationTypes() {
fConfiguredAnnotationTypes.clear();
fAllowedAnnotationTypes.clear();
fConfiguredHighlightAnnotationTypes.clear();
fAllowedHighlightAnnotationTypes.clear();
if (fTextInputListener != null) {
fSourceViewer.removeTextInputListener(fTextInputListener);
fTextInputListener= null;
}
}
/**
* Returns whether the list of annotation types whose annotations are painted
* by this painter contains at least on element.
*
* @return <code>true</code> if there is an annotation type whose annotations are painted
*/
public boolean isPaintingAnnotations() {
return !fConfiguredAnnotationTypes.isEmpty() || !fConfiguredHighlightAnnotationTypes.isEmpty();
}
/*
* @see IPainter#dispose()
*/
public void dispose() {
if (fColorTable != null)
fColorTable.clear();
fColorTable= null;
if (fConfiguredAnnotationTypes != null)
fConfiguredAnnotationTypes.clear();
fConfiguredAnnotationTypes= null;
if (fAllowedAnnotationTypes != null)
fAllowedAnnotationTypes.clear();
fAllowedAnnotationTypes= null;
if (fConfiguredHighlightAnnotationTypes != null)
fConfiguredHighlightAnnotationTypes.clear();
fConfiguredHighlightAnnotationTypes= null;
if (fAllowedHighlightAnnotationTypes != null)
fAllowedHighlightAnnotationTypes.clear();
fAllowedHighlightAnnotationTypes= null;
fTextWidget= null;
fSourceViewer= null;
fAnnotationAccess= null;
fModel= null;
fDecorationsMap= null;
fHighlightedDecorationsMap= null;
}
/**
* Returns the document offset of the upper left corner of the source viewer's viewport,
* possibly including partially visible lines.
*
* @return the document offset if the upper left corner of the viewport
*/
private int getInclusiveTopIndexStartOffset() {
if (fTextWidget != null && !fTextWidget.isDisposed()) {
int top= fSourceViewer.getTopIndex();
if ((fTextWidget.getTopPixel() % fTextWidget.getLineHeight()) != 0)
top--;
try {
IDocument document= fSourceViewer.getDocument();
return document.getLineOffset(top);
} catch (BadLocationException ex) {
}
}
return -1;
}
/*
* @see PaintListener#paintControl(PaintEvent)
*/
public void paintControl(PaintEvent event) {
if (fTextWidget != null)
handleDrawRequest(event.gc);
}
/**
* Handles the request to draw the annotations using the given gaphical context.
*
* @param gc the graphical context
*/
private void handleDrawRequest(GC gc) {
if (fTextWidget == null) {
// is already disposed
return;
}
int vOffset= getInclusiveTopIndexStartOffset();
// http://bugs.eclipse.org/bugs/show_bug.cgi?id=17147
int vLength= fSourceViewer.getBottomIndexEndOffset() + 1;
for (int layer= 0, maxLayer= 1; layer < maxLayer; layer++) {
for (Iterator e = fDecorationsMap.values().iterator(); e.hasNext();) {
Decoration pp = (Decoration) e.next();
maxLayer= Math.max(maxLayer, pp.fLayer + 1); // dynamically update layer maximum
if (pp.fLayer != layer) // wrong layer: skip annotation
continue;
Position p= pp.fPosition;
if (p.overlapsWith(vOffset, vLength)) {
IDocument document= fSourceViewer.getDocument();
try {
int startLine= document.getLineOfOffset(p.getOffset());
int lastInclusive= Math.max(p.getOffset(), p.getOffset() + p.getLength() - 1);
int endLine= document.getLineOfOffset(lastInclusive);
for (int i= startLine; i <= endLine; i++) {
IRegion line= document.getLineInformation(i);
int paintStart= Math.max(line.getOffset(), p.getOffset());
int paintEnd= Math.min(line.getOffset() + line.getLength(), p.getOffset() + p.getLength());
if (paintEnd > paintStart) {
// otherwise inside a line delimiter
IRegion widgetRange= getWidgetRange(new Position(paintStart, paintEnd - paintStart));
if (widgetRange != null)
draw(gc, widgetRange.getOffset(), widgetRange.getLength(), pp.fColor);
}
}
} catch (BadLocationException x) {
}
}
}
}
}
/**
* Returns the widget region that corresponds to the given region in the
* viewer's document.
*
* @param p the region in the viewer's document
* @return the corresponding widget region
*/
private IRegion getWidgetRange(Position p) {
if (p == null || p.offset == Integer.MAX_VALUE)
return null;
if (fSourceViewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) fSourceViewer;
return extension.modelRange2WidgetRange(new Region(p.getOffset(), p.getLength()));
} else {
IRegion region= fSourceViewer.getVisibleRegion();
int offset= region.getOffset();
int length= region.getLength();
if (p.overlapsWith(offset , length)) {
int p1= Math.max(offset, p.getOffset());
int p2= Math.min(offset + length, p.getOffset() + p.getLength());
return new Region(p1 - offset, p2 - p1);
}
}
return null;
}
/**
* Computes an array of alternating x and y values which are the corners of the squiggly line of the
* given height between the given end points.
*
* @param left the left end point
* @param right the right end point
* @param height the height of the squiggly line
* @return the array of alternating x and y values which are the corners of the squiggly line
*/
private int[] computePolyline(Point left, Point right, int height) {
final int WIDTH= 4; // must be even
final int HEIGHT= 2; // can be any number
// final int MINPEEKS= 2; // minimal number of peeks
int peeks= (right.x - left.x) / WIDTH;
// if (peeks < MINPEEKS) {
// int missing= (MINPEEKS - peeks) * WIDTH;
// left.x= Math.max(0, left.x - missing/2);
// peeks= MINPEEKS;
// }
int leftX= left.x;
// compute (number of point) * 2
int length= ((2 * peeks) + 1) * 2;
if (length < 0)
return new int[0];
int[] coordinates= new int[length];
// cache peeks' y-coordinates
int bottom= left.y + height - 1;
int top= bottom - HEIGHT;
// populate array with peek coordinates
for (int i= 0; i < peeks; i++) {
int index= 4 * i;
coordinates[index]= leftX + (WIDTH * i);
coordinates[index+1]= bottom;
coordinates[index+2]= coordinates[index] + WIDTH/2;
coordinates[index+3]= top;
}
// the last down flank is missing
coordinates[length-2]= left.x + (WIDTH * peeks);
coordinates[length-1]= bottom;
return coordinates;
}
/**
* Draws a squiggly line of the given length start at the given offset in the
* given color.
*
* @param gc the grahical context
* @param offset the offset of the line
* @param length the length of the line
* @param color the color of the line
*/
private void draw(GC gc, int offset, int length, Color color) {
if (gc != null) {
Point left= fTextWidget.getLocationAtOffset(offset);
Point right= fTextWidget.getLocationAtOffset(offset + length);
gc.setForeground(color);
int[] polyline= computePolyline(left, right, gc.getFontMetrics().getHeight());
gc.drawPolyline(polyline);
} else {
fTextWidget.redrawRange(offset, length, true);
}
}
/*
* @see IPainter#deactivate(boolean)
*/
public void deactivate(boolean redraw) {
if (fIsActive) {
fIsActive= false;
disablePainting(redraw);
setModel(null);
catchupWithModel(null);
}
}
/*
* @see IPainter#paint(int)
*/
public void paint(int reason) {
if (fSourceViewer.getDocument() == null) {
deactivate(false);
return;
}
if (!fIsActive) {
IAnnotationModel model= fSourceViewer.getAnnotationModel();
if (model != null) {
fIsActive= true;
setModel(fSourceViewer.getAnnotationModel());
}
} else if (CONFIGURATION == reason || INTERNAL == reason)
updatePainting(null);
}
/*
* @see org.eclipse.jface.text.IPainter#setPositionManager(org.eclipse.jface.text.IPaintPositionManager)
*/
public void setPositionManager(IPaintPositionManager manager) {
}
}
| false | true | private synchronized void catchupWithModel(AnnotationModelEvent event) {
if (fDecorationsMap != null) {
int highlightAnnotationRangeStart= Integer.MAX_VALUE;
int highlightAnnotationRangeEnd= -1;
if (fModel != null) {
boolean isWorldChange= false;
Iterator e;
if (event == null || event.isWorldChange()) {
isWorldChange= true;
if (DEBUG && event == null)
System.out.println("AP: INTERNAL CHANGE"); //$NON-NLS-1$
fDecorationsMap.clear();
fHighlightedDecorationsMap.clear();
e= fModel.getAnnotationIterator();
} else {
// Remove annotations
Annotation[] removedAnnotations= event.getRemovedAnnotations();
for (int i=0, length= removedAnnotations.length; i < length; i++) {
Annotation annotation= removedAnnotations[i];
Decoration decoration= (Decoration)fHighlightedDecorationsMap.remove(annotation);
if (decoration != null) {
Position position= decoration.fPosition;
if (position != null && !position.isDeleted()) {
highlightAnnotationRangeStart= Math.min(highlightAnnotationRangeStart, position.offset);
highlightAnnotationRangeEnd= Math.max(highlightAnnotationRangeEnd, position.offset + position.length);
}
}
fDecorationsMap.remove(annotation);
}
// Update existing annotations
Annotation[] changedAnnotations= event.getChangedAnnotations();
for (int i=0, length= changedAnnotations.length; i < length; i++) {
Annotation annotation= changedAnnotations[i];
Object annotationType= annotation.getType();
boolean isHighlighting= shouldBeHighlighted(annotationType);
boolean isDrawingSquiggles= shouldBeDrawn(annotationType);
Decoration decoration= (Decoration)fHighlightedDecorationsMap.get(annotation);
if (decoration != null) {
// The call below updates the decoration - no need to create new decoration
decoration= getDecoration(annotation, decoration, isDrawingSquiggles, isHighlighting);
if (decoration == null)
fHighlightedDecorationsMap.remove(annotation);
} else {
decoration= getDecoration(annotation, decoration, isDrawingSquiggles, isHighlighting);
if (decoration != null)
fHighlightedDecorationsMap.put(annotation, decoration);
}
Position position= null;
if (decoration == null)
position= fModel.getPosition(annotation);
else
position= decoration.fPosition;
if (position != null && !position.isDeleted()) {
highlightAnnotationRangeStart= Math.min(highlightAnnotationRangeStart, position.offset);
highlightAnnotationRangeEnd= Math.max(highlightAnnotationRangeEnd, position.offset + position.length);
} else {
fHighlightedDecorationsMap.remove(annotation);
}
Decoration oldDecoration= (Decoration)fDecorationsMap.get(annotation);
if (decoration != null)
fDecorationsMap.put(annotation, decoration);
else if (oldDecoration != null)
fDecorationsMap.remove(annotation);
}
e= Arrays.asList(event.getAddedAnnotations()).iterator();
}
// Add new annotations
while (e.hasNext()) {
Annotation annotation= (Annotation) e.next();
Object annotationType= annotation.getType();
boolean isHighlighting= shouldBeHighlighted(annotationType);
boolean isDrawingSquiggles= shouldBeDrawn(annotationType);
Decoration pp= getDecoration(annotation, null, isDrawingSquiggles, isHighlighting);
if (pp != null) {
if (isDrawingSquiggles)
fDecorationsMap.put(annotation, pp);
if (isHighlighting) {
fHighlightedDecorationsMap.put(annotation, pp);
highlightAnnotationRangeStart= Math.min(highlightAnnotationRangeStart, pp.fPosition.offset);
highlightAnnotationRangeEnd= Math.max(highlightAnnotationRangeEnd, pp.fPosition.offset + pp.fPosition.length);
}
}
}
updateHighlightRanges(highlightAnnotationRangeStart, highlightAnnotationRangeEnd, isWorldChange);
}
}
}
| private synchronized void catchupWithModel(AnnotationModelEvent event) {
if (fDecorationsMap != null) {
int highlightAnnotationRangeStart= Integer.MAX_VALUE;
int highlightAnnotationRangeEnd= -1;
if (fModel != null) {
boolean isWorldChange= false;
Iterator e;
if (event == null || event.isWorldChange()) {
isWorldChange= true;
if (DEBUG && event == null)
System.out.println("AP: INTERNAL CHANGE"); //$NON-NLS-1$
fDecorationsMap.clear();
fHighlightedDecorationsMap.clear();
e= fModel.getAnnotationIterator();
} else {
// Remove annotations
Annotation[] removedAnnotations= event.getRemovedAnnotations();
for (int i=0, length= removedAnnotations.length; i < length; i++) {
Annotation annotation= removedAnnotations[i];
Decoration decoration= (Decoration)fHighlightedDecorationsMap.remove(annotation);
if (decoration != null) {
Position position= decoration.fPosition;
if (position != null && !position.isDeleted()) {
highlightAnnotationRangeStart= Math.min(highlightAnnotationRangeStart, position.offset);
highlightAnnotationRangeEnd= Math.max(highlightAnnotationRangeEnd, position.offset + position.length);
}
}
fDecorationsMap.remove(annotation);
}
// Update existing annotations
Annotation[] changedAnnotations= event.getChangedAnnotations();
for (int i=0, length= changedAnnotations.length; i < length; i++) {
Annotation annotation= changedAnnotations[i];
Object annotationType= annotation.getType();
boolean isHighlighting= shouldBeHighlighted(annotationType);
boolean isDrawingSquiggles= shouldBeDrawn(annotationType);
Decoration decoration= (Decoration)fHighlightedDecorationsMap.get(annotation);
if (decoration != null) {
// The call below updates the decoration - no need to create new decoration
decoration= getDecoration(annotation, decoration, isDrawingSquiggles, isHighlighting);
if (decoration == null)
fHighlightedDecorationsMap.remove(annotation);
} else {
decoration= getDecoration(annotation, decoration, isDrawingSquiggles, isHighlighting);
if (decoration != null && isHighlighting)
fHighlightedDecorationsMap.put(annotation, decoration);
}
Position position= null;
if (decoration == null)
position= fModel.getPosition(annotation);
else
position= decoration.fPosition;
if (position != null && !position.isDeleted()) {
highlightAnnotationRangeStart= Math.min(highlightAnnotationRangeStart, position.offset);
highlightAnnotationRangeEnd= Math.max(highlightAnnotationRangeEnd, position.offset + position.length);
} else {
fHighlightedDecorationsMap.remove(annotation);
}
Decoration oldDecoration= (Decoration)fDecorationsMap.get(annotation);
if (decoration != null && isDrawingSquiggles)
fDecorationsMap.put(annotation, decoration);
else if (oldDecoration != null)
fDecorationsMap.remove(annotation);
}
e= Arrays.asList(event.getAddedAnnotations()).iterator();
}
// Add new annotations
while (e.hasNext()) {
Annotation annotation= (Annotation) e.next();
Object annotationType= annotation.getType();
boolean isHighlighting= shouldBeHighlighted(annotationType);
boolean isDrawingSquiggles= shouldBeDrawn(annotationType);
Decoration pp= getDecoration(annotation, null, isDrawingSquiggles, isHighlighting);
if (pp != null) {
if (isDrawingSquiggles)
fDecorationsMap.put(annotation, pp);
if (isHighlighting) {
fHighlightedDecorationsMap.put(annotation, pp);
highlightAnnotationRangeStart= Math.min(highlightAnnotationRangeStart, pp.fPosition.offset);
highlightAnnotationRangeEnd= Math.max(highlightAnnotationRangeEnd, pp.fPosition.offset + pp.fPosition.length);
}
}
}
updateHighlightRanges(highlightAnnotationRangeStart, highlightAnnotationRangeEnd, isWorldChange);
}
}
}
|
diff --git a/ScreenLayoutTool/src/Data.java b/ScreenLayoutTool/src/Data.java
index 9113a65..0d0d9bd 100644
--- a/ScreenLayoutTool/src/Data.java
+++ b/ScreenLayoutTool/src/Data.java
@@ -1,239 +1,239 @@
import java.awt.Color;
import java.awt.Graphics;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class Data
{
static class Box
{
public String name="noname";
public String desc="nodesc";
public float left,right,top,bottom;
private float x1,y1,x2,y2;
public Box(){}
public boolean isValid()
{
if(left!=right && top!=bottom)
return true;
return false;
}
public void movePixels(int dx, int dy)
{
if(ScreenLayoutTool.sceneView==null || ScreenLayoutTool.sceneView.img==null )
return;
float fx = (float)dx/ScreenLayoutTool.sceneView.img.getWidth();
float fy = (float)dy/ScreenLayoutTool.sceneView.img.getHeight();
move(fx,fy);
}
public void move(float dx, float dy)
{
left += dx;
right += dx;
top += dy;
bottom += dy;
}
public void setFirstPixelPoint(int x, int y)
{
if(ScreenLayoutTool.sceneView==null || ScreenLayoutTool.sceneView.img==null )
return;
float fx = (float)x/ScreenLayoutTool.sceneView.img.getWidth();
float fy = (float)y/ScreenLayoutTool.sceneView.img.getHeight();
setFirstPoint(fx,fy);
sync();
}
public void setSecondPixelPoint(int x, int y)
{
if(ScreenLayoutTool.sceneView==null || ScreenLayoutTool.sceneView.img==null )
return;
float fx = (float)x/ScreenLayoutTool.sceneView.img.getWidth();
float fy = (float)y/ScreenLayoutTool.sceneView.img.getHeight();
setSecondPoint(fx,fy);
sync();
}
public void setFirstPoint(float x, float y)
{
x1 = x;
y1 = y;
x2 = x;
y2 = y;
sync();
}
public void setSecondPoint(float x, float y)
{
x2 = x;
y2 = y;
sync();
}
private void sync()
{
left = Math.min(x1, x2);
right = Math.max(x1, x2);
top = Math.min(y1, y2);
bottom = Math.max(y1, y2);
}
}
public static ArrayList<Box> boxes = new ArrayList<Box>();
public static Box getBoxAtPixel(int x, int y)
{
if(ScreenLayoutTool.sceneView==null || ScreenLayoutTool.sceneView.img==null )
return null;
float fx = (float)x/ScreenLayoutTool.sceneView.img.getWidth();
float fy = (float)y/ScreenLayoutTool.sceneView.img.getHeight();
return getBoxAt(fx,fy);
}
public static Box getBoxAt(float x, float y)
{
for(int i=0; i<boxes.size(); ++i)
{
Box box = boxes.get(i);
if(box.left <= x && x <= box.right
&& box.top <= y && y <= box.bottom)
{
return box;
}
}
return null;
}
public static void removeBox(Box b)
{
boxes.remove(b);
}
public static void addBox(Box b)
{
boxes.add(b);
}
public static void clearAll()
{
boxes.clear();
}
public static void draw(Graphics g)
{
if(ScreenLayoutTool.sceneView.img == null)
return;
g.setColor(boxColor);
for(int i=0; i<boxes.size(); ++i)
{
Box box = boxes.get(i);
int ptop = (int)(box.top * ScreenLayoutTool.sceneView.img.getHeight());
int pbottom = (int)(box.bottom * ScreenLayoutTool.sceneView.img.getHeight());
int pleft = (int)(box.left * ScreenLayoutTool.sceneView.img.getWidth());
int pright = (int)(box.right * ScreenLayoutTool.sceneView.img.getWidth());
g.drawRect(pleft, ptop, pright-pleft, pbottom-ptop);
}
g.setColor(selectedBoxColor);
if(ScreenLayoutTool.sceneView==null || ScreenLayoutTool.sceneView.img==null )
return;
Box box = ScreenLayoutTool.sceneView.selectedBox;
if(box!=null)
{
int ptop = (int)(box.top * ScreenLayoutTool.sceneView.img.getHeight());
int pbottom = (int)(box.bottom * ScreenLayoutTool.sceneView.img.getHeight());
int pleft = (int)(box.left * ScreenLayoutTool.sceneView.img.getWidth());
int pright = (int)(box.right * ScreenLayoutTool.sceneView.img.getWidth());
g.drawRect(pleft, ptop, pright-pleft, pbottom-ptop);
}
}
public static void loadFromFile(String filename)
{
clearAll();
try
{
BufferedReader in = new BufferedReader(new FileReader(filename));
while(true)
{
String line = in.readLine();
if(line==null)break;
StringTokenizer st = new StringTokenizer(line);
Data.Box box = new Data.Box();
box.name = st.nextToken();
box.left = Float.parseFloat(st.nextToken());
box.right = Float.parseFloat(st.nextToken());
box.top = Float.parseFloat(st.nextToken());
box.bottom = Float.parseFloat(st.nextToken());
if(st.hasMoreTokens())
- box.desc = st.nextToken();
+ box.desc = st.nextToken("");
Data.addBox(box);
}
in.close();
}
catch(Exception e)
{
System.out.println("LOAD ERROR!");
System.out.println(e);
}
if(ScreenLayoutTool.sceneView!=null)
ScreenLayoutTool.sceneView.repaint();
}
public static void saveToFile(String filename)
{
try
{
PrintWriter out = new PrintWriter(new FileWriter(filename));
for(int i=0; i<boxes.size(); ++i)
{
Box box = boxes.get(i);
out.println(box.name+" "+box.left+" "+box.right+" "+box.top+" "+box.bottom+" "+box.desc);
}
out.close();
}
catch(Exception e)
{
System.out.println("SAVE ERROR!");
System.out.println(e);
}
}
static Color selectedBoxColor = new Color(0,255,0);
static Color boxColor = new Color(255,0,255);
}
| true | true | public static void loadFromFile(String filename)
{
clearAll();
try
{
BufferedReader in = new BufferedReader(new FileReader(filename));
while(true)
{
String line = in.readLine();
if(line==null)break;
StringTokenizer st = new StringTokenizer(line);
Data.Box box = new Data.Box();
box.name = st.nextToken();
box.left = Float.parseFloat(st.nextToken());
box.right = Float.parseFloat(st.nextToken());
box.top = Float.parseFloat(st.nextToken());
box.bottom = Float.parseFloat(st.nextToken());
if(st.hasMoreTokens())
box.desc = st.nextToken();
Data.addBox(box);
}
in.close();
}
catch(Exception e)
{
System.out.println("LOAD ERROR!");
System.out.println(e);
}
if(ScreenLayoutTool.sceneView!=null)
ScreenLayoutTool.sceneView.repaint();
}
| public static void loadFromFile(String filename)
{
clearAll();
try
{
BufferedReader in = new BufferedReader(new FileReader(filename));
while(true)
{
String line = in.readLine();
if(line==null)break;
StringTokenizer st = new StringTokenizer(line);
Data.Box box = new Data.Box();
box.name = st.nextToken();
box.left = Float.parseFloat(st.nextToken());
box.right = Float.parseFloat(st.nextToken());
box.top = Float.parseFloat(st.nextToken());
box.bottom = Float.parseFloat(st.nextToken());
if(st.hasMoreTokens())
box.desc = st.nextToken("");
Data.addBox(box);
}
in.close();
}
catch(Exception e)
{
System.out.println("LOAD ERROR!");
System.out.println(e);
}
if(ScreenLayoutTool.sceneView!=null)
ScreenLayoutTool.sceneView.repaint();
}
|
diff --git a/src/main/java/br/ufrj/dcc/compgraf/im/ui/options/GreyScaleOptionsDialog.java b/src/main/java/br/ufrj/dcc/compgraf/im/ui/options/GreyScaleOptionsDialog.java
index 32cd9f9..126fdc9 100644
--- a/src/main/java/br/ufrj/dcc/compgraf/im/ui/options/GreyScaleOptionsDialog.java
+++ b/src/main/java/br/ufrj/dcc/compgraf/im/ui/options/GreyScaleOptionsDialog.java
@@ -1,66 +1,66 @@
package br.ufrj.dcc.compgraf.im.ui.options;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import br.ufrj.dcc.compgraf.im.color.GreyScale;
import br.ufrj.dcc.compgraf.im.color.GreyScale.GreyScaleType;
import br.ufrj.dcc.compgraf.im.ui.SwingUtils;
import br.ufrj.dcc.compgraf.im.ui.UIContext;
public class GreyScaleOptionsDialog extends JDialog
{
public GreyScaleOptionsDialog()
{
super(UIContext.instance().getMainWindow(), "Choose the grey scaling type", true);
setSize(240, 100);
SwingUtils.configureDialog(this);
initLayout();
}
private void initLayout()
{
JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
panel.setOpaque(true);
setContentPane(panel);
final JComboBox typesCombo = new JComboBox();
for (GreyScaleType greyScaleType : GreyScaleType.values())
{
typesCombo.addItem(greyScaleType);
}
JButton applyButton = new JButton("Apply");
applyButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
int selected = typesCombo.getSelectedIndex();
GreyScaleType selectedType = GreyScaleType.values()[selected];
BufferedImage newImg = new GreyScale().toGreyScale(UIContext.instance().getCurrentImage(), selectedType);
UIContext.instance().changeCurrentImage(newImg);
dispose();
}
});
- add(new JLabel("Type"));
+ add(new JLabel("Type:"));
add(typesCombo);
add(applyButton);
}
}
| true | true | private void initLayout()
{
JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
panel.setOpaque(true);
setContentPane(panel);
final JComboBox typesCombo = new JComboBox();
for (GreyScaleType greyScaleType : GreyScaleType.values())
{
typesCombo.addItem(greyScaleType);
}
JButton applyButton = new JButton("Apply");
applyButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
int selected = typesCombo.getSelectedIndex();
GreyScaleType selectedType = GreyScaleType.values()[selected];
BufferedImage newImg = new GreyScale().toGreyScale(UIContext.instance().getCurrentImage(), selectedType);
UIContext.instance().changeCurrentImage(newImg);
dispose();
}
});
add(new JLabel("Type"));
add(typesCombo);
add(applyButton);
}
| private void initLayout()
{
JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
panel.setOpaque(true);
setContentPane(panel);
final JComboBox typesCombo = new JComboBox();
for (GreyScaleType greyScaleType : GreyScaleType.values())
{
typesCombo.addItem(greyScaleType);
}
JButton applyButton = new JButton("Apply");
applyButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
int selected = typesCombo.getSelectedIndex();
GreyScaleType selectedType = GreyScaleType.values()[selected];
BufferedImage newImg = new GreyScale().toGreyScale(UIContext.instance().getCurrentImage(), selectedType);
UIContext.instance().changeCurrentImage(newImg);
dispose();
}
});
add(new JLabel("Type:"));
add(typesCombo);
add(applyButton);
}
|
diff --git a/src/main/java/ch/ethz/nlp/headline/visualization/PeerInspector.java b/src/main/java/ch/ethz/nlp/headline/visualization/PeerInspector.java
index 86bd4ba..7ebf083 100644
--- a/src/main/java/ch/ethz/nlp/headline/visualization/PeerInspector.java
+++ b/src/main/java/ch/ethz/nlp/headline/visualization/PeerInspector.java
@@ -1,78 +1,78 @@
package ch.ethz.nlp.headline.visualization;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.ethz.nlp.headline.Model;
import ch.ethz.nlp.headline.Peer;
import ch.ethz.nlp.headline.Task;
import ch.ethz.nlp.headline.cache.AnnotationProvider;
import ch.ethz.nlp.headline.util.RougeN;
import edu.stanford.nlp.pipeline.Annotation;
public class PeerInspector {
private static final Logger LOG = LoggerFactory
.getLogger(PeerInspector.class);
private static final double ROUGE_1_THRESHOLD = 0.20;
private static final double ROUGE_2_THRESHOLD = 0.05;
private static final AnsiColor MODEL_COLOR = AnsiColor.BLUE;
private final AnnotationProvider annotationProvider;
public PeerInspector(AnnotationProvider annotationProvider) {
super();
this.annotationProvider = annotationProvider;
}
public void inspect(Task task, Collection<Peer> peers) throws IOException {
RougeN rouge1 = new RougeN(1);
RougeN rouge2 = new RougeN(2);
NGramHitVisualizer visualizer = NGramHitVisualizer.of(
annotationProvider, task.getModels());
List<Annotation> modelAnnotations = visualizer.getModelAnnotations();
for (Model model : task.getModels()) {
String content = model.getContent();
String logString = String.format("%-16s%s", "MODEL", content);
LOG.info(MODEL_COLOR.makeString(logString));
}
for (Peer peer : peers) {
String generatorId = peer.getGeneratorId();
String headline = peer.load();
Annotation annotation = annotationProvider.getAnnotation(headline);
String visualization = visualizer.visualize(annotation);
- visualization = visualization.replaceAll("\n", "");
+ visualization = visualization.replaceAll("\n", " ");
double rouge1Recall = rouge1.compute(modelAnnotations, annotation);
double rouge2Recall = rouge2.compute(modelAnnotations, annotation);
String rouge1String = String.format("%.2f", rouge1Recall)
.substring(1);
String rouge2String = String.format("%.2f", rouge2Recall)
.substring(1);
if (!generatorId.equals("BASE")) {
if (rouge1Recall < ROUGE_1_THRESHOLD) {
rouge1String = AnsiColor.RED.makeString(rouge1String);
}
if (rouge2Recall < ROUGE_2_THRESHOLD) {
rouge2String = AnsiColor.RED.makeString(rouge2String);
}
}
LOG.info(String.format("%-8s%s %s %s", generatorId, rouge1String,
rouge2String, visualization));
}
}
}
| true | true | public void inspect(Task task, Collection<Peer> peers) throws IOException {
RougeN rouge1 = new RougeN(1);
RougeN rouge2 = new RougeN(2);
NGramHitVisualizer visualizer = NGramHitVisualizer.of(
annotationProvider, task.getModels());
List<Annotation> modelAnnotations = visualizer.getModelAnnotations();
for (Model model : task.getModels()) {
String content = model.getContent();
String logString = String.format("%-16s%s", "MODEL", content);
LOG.info(MODEL_COLOR.makeString(logString));
}
for (Peer peer : peers) {
String generatorId = peer.getGeneratorId();
String headline = peer.load();
Annotation annotation = annotationProvider.getAnnotation(headline);
String visualization = visualizer.visualize(annotation);
visualization = visualization.replaceAll("\n", "");
double rouge1Recall = rouge1.compute(modelAnnotations, annotation);
double rouge2Recall = rouge2.compute(modelAnnotations, annotation);
String rouge1String = String.format("%.2f", rouge1Recall)
.substring(1);
String rouge2String = String.format("%.2f", rouge2Recall)
.substring(1);
if (!generatorId.equals("BASE")) {
if (rouge1Recall < ROUGE_1_THRESHOLD) {
rouge1String = AnsiColor.RED.makeString(rouge1String);
}
if (rouge2Recall < ROUGE_2_THRESHOLD) {
rouge2String = AnsiColor.RED.makeString(rouge2String);
}
}
LOG.info(String.format("%-8s%s %s %s", generatorId, rouge1String,
rouge2String, visualization));
}
}
| public void inspect(Task task, Collection<Peer> peers) throws IOException {
RougeN rouge1 = new RougeN(1);
RougeN rouge2 = new RougeN(2);
NGramHitVisualizer visualizer = NGramHitVisualizer.of(
annotationProvider, task.getModels());
List<Annotation> modelAnnotations = visualizer.getModelAnnotations();
for (Model model : task.getModels()) {
String content = model.getContent();
String logString = String.format("%-16s%s", "MODEL", content);
LOG.info(MODEL_COLOR.makeString(logString));
}
for (Peer peer : peers) {
String generatorId = peer.getGeneratorId();
String headline = peer.load();
Annotation annotation = annotationProvider.getAnnotation(headline);
String visualization = visualizer.visualize(annotation);
visualization = visualization.replaceAll("\n", " ");
double rouge1Recall = rouge1.compute(modelAnnotations, annotation);
double rouge2Recall = rouge2.compute(modelAnnotations, annotation);
String rouge1String = String.format("%.2f", rouge1Recall)
.substring(1);
String rouge2String = String.format("%.2f", rouge2Recall)
.substring(1);
if (!generatorId.equals("BASE")) {
if (rouge1Recall < ROUGE_1_THRESHOLD) {
rouge1String = AnsiColor.RED.makeString(rouge1String);
}
if (rouge2Recall < ROUGE_2_THRESHOLD) {
rouge2String = AnsiColor.RED.makeString(rouge2String);
}
}
LOG.info(String.format("%-8s%s %s %s", generatorId, rouge1String,
rouge2String, visualization));
}
}
|
diff --git a/src/java/fedora/server/storage/lowlevel/PathAlgorithm.java b/src/java/fedora/server/storage/lowlevel/PathAlgorithm.java
index 4eed8f251..17df9dd34 100755
--- a/src/java/fedora/server/storage/lowlevel/PathAlgorithm.java
+++ b/src/java/fedora/server/storage/lowlevel/PathAlgorithm.java
@@ -1,84 +1,84 @@
package fedora.server.storage.lowlevel;
import java.io.File;
import fedora.server.Server;
import fedora.server.errors.LowlevelStorageException;
import fedora.server.errors.MalformedPidException;
/**
*
* <p><b>Title:</b> PathAlgorithm.java</p>
* <p><b>Description:</b> </p>
*
* -----------------------------------------------------------------------------
*
* <p><b>License and Copyright: </b>The contents of this file are subject to the
* Mozilla Public License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License
* at <a href="http://www.mozilla.org/MPL">http://www.mozilla.org/MPL/.</a></p>
*
* <p>Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.</p>
*
* <p>The entire file consists of original code. Copyright © 2002-2005 by The
* Rector and Visitors of the University of Virginia and Cornell University.
* All rights reserved.</p>
*
* -----------------------------------------------------------------------------
*
* @author [email protected]
* @version $Id$
*/
abstract class PathAlgorithm implements IPathAlgorithm {
//protected static final Configuration configuration = Configuration.getInstance();
protected static final String sep = File.separator;
private final String storeBase;
protected final String getStoreBase() {
return storeBase;
}
protected PathAlgorithm (String storeBase) {
this.storeBase = storeBase;
}
private static final String encode(String unencoded) throws LowlevelStorageException {
try {
int i = unencoded.indexOf("+");
if (i != -1) {
- return Server.getPID(unencoded.substring(0, i-1)).toFilename()
+ return Server.getPID(unencoded.substring(0, i)).toFilename()
+ unencoded.substring(i);
} else {
return Server.getPID(unencoded).toFilename();
}
} catch (MalformedPidException e) {
throw new LowlevelStorageException(true, e.getMessage(), e);
}
}
public static final String decode(String encoded) throws LowlevelStorageException {
try {
int i = encoded.indexOf("+");
if (i != -1) {
return Server.pidFromFilename(encoded.substring(0, i-1)).toString()
+ encoded.substring(i);
} else {
return Server.pidFromFilename(encoded).toString();
}
} catch (MalformedPidException e) {
throw new LowlevelStorageException(true, e.getMessage(), e);
}
}
abstract protected String format (String pid) throws LowlevelStorageException;
public final String get (String pid) throws LowlevelStorageException {
return format(encode(pid));
}
}
| true | true | private static final String encode(String unencoded) throws LowlevelStorageException {
try {
int i = unencoded.indexOf("+");
if (i != -1) {
return Server.getPID(unencoded.substring(0, i-1)).toFilename()
+ unencoded.substring(i);
} else {
return Server.getPID(unencoded).toFilename();
}
} catch (MalformedPidException e) {
throw new LowlevelStorageException(true, e.getMessage(), e);
}
}
| private static final String encode(String unencoded) throws LowlevelStorageException {
try {
int i = unencoded.indexOf("+");
if (i != -1) {
return Server.getPID(unencoded.substring(0, i)).toFilename()
+ unencoded.substring(i);
} else {
return Server.getPID(unencoded).toFilename();
}
} catch (MalformedPidException e) {
throw new LowlevelStorageException(true, e.getMessage(), e);
}
}
|
diff --git a/src/gossipLearning/protocols/SlimBanditProtocol.java b/src/gossipLearning/protocols/SlimBanditProtocol.java
index e932b46..cd3dac7 100644
--- a/src/gossipLearning/protocols/SlimBanditProtocol.java
+++ b/src/gossipLearning/protocols/SlimBanditProtocol.java
@@ -1,53 +1,58 @@
package gossipLearning.protocols;
import gossipLearning.interfaces.Model;
import gossipLearning.interfaces.ModelHolder;
import gossipLearning.messages.ModelMessage;
import gossipLearning.modelHolders.BoundedModelHolder;
import gossipLearning.models.bandits.P2GreedyModel;
import gossipLearning.models.bandits.P2GreedySlim;
public class SlimBanditProtocol extends SimpleBanditProtocol2SentModels {
public SlimBanditProtocol(String prefix) {
super(prefix);
}
protected SlimBanditProtocol(SimpleBanditProtocol2SentModels a) {
super(a);
}
public Object clone() {
return new SlimBanditProtocol(this);
}
@Override
public void activeThread() {
// check whether the node has at least one model
if (getModelHolder(0) != null && getModelHolder(0).size() > 0){
// check the model stored in the holder
final Model latestModelG = getModelHolder(0).getModel(getModelHolder(0).size() - 1);
if (! (latestModelG instanceof P2GreedySlim)) {
throw new RuntimeException("This protocol supports only the P2GreedySlim models!!!");
}
// get the latest model from the holder
final P2GreedySlim latestModel = (P2GreedySlim) latestModelG;
// get the stored model of the current peer
final P2GreedySlim storedModel = latestModel.getMyModel();
// get the model with higher expected reward
- final Model M = (latestModel.predict(latestModel.getI()) >= storedModel.predict(storedModel.getI())) ? latestModel : storedModel;
+ Model M = latestModel;
+ if (storedModel != null) {
+ M = (latestModel.predict(latestModel.getI()) >= storedModel.predict(storedModel.getI())) ? latestModel : storedModel;
+ } else {
+ System.err.println("My model is null!!!");
+ }
ModelHolder sendingModelHolder = new BoundedModelHolder(1);
sendingModelHolder.add(M);
// send the latest model to a random neighbor
sendToNeighbor(new ModelMessage(currentNode, sendingModelHolder), 0);
sendToNeighbor(new ModelMessage(currentNode, sendingModelHolder), 1);
}
}
}
| true | true | public void activeThread() {
// check whether the node has at least one model
if (getModelHolder(0) != null && getModelHolder(0).size() > 0){
// check the model stored in the holder
final Model latestModelG = getModelHolder(0).getModel(getModelHolder(0).size() - 1);
if (! (latestModelG instanceof P2GreedySlim)) {
throw new RuntimeException("This protocol supports only the P2GreedySlim models!!!");
}
// get the latest model from the holder
final P2GreedySlim latestModel = (P2GreedySlim) latestModelG;
// get the stored model of the current peer
final P2GreedySlim storedModel = latestModel.getMyModel();
// get the model with higher expected reward
final Model M = (latestModel.predict(latestModel.getI()) >= storedModel.predict(storedModel.getI())) ? latestModel : storedModel;
ModelHolder sendingModelHolder = new BoundedModelHolder(1);
sendingModelHolder.add(M);
// send the latest model to a random neighbor
sendToNeighbor(new ModelMessage(currentNode, sendingModelHolder), 0);
sendToNeighbor(new ModelMessage(currentNode, sendingModelHolder), 1);
}
}
| public void activeThread() {
// check whether the node has at least one model
if (getModelHolder(0) != null && getModelHolder(0).size() > 0){
// check the model stored in the holder
final Model latestModelG = getModelHolder(0).getModel(getModelHolder(0).size() - 1);
if (! (latestModelG instanceof P2GreedySlim)) {
throw new RuntimeException("This protocol supports only the P2GreedySlim models!!!");
}
// get the latest model from the holder
final P2GreedySlim latestModel = (P2GreedySlim) latestModelG;
// get the stored model of the current peer
final P2GreedySlim storedModel = latestModel.getMyModel();
// get the model with higher expected reward
Model M = latestModel;
if (storedModel != null) {
M = (latestModel.predict(latestModel.getI()) >= storedModel.predict(storedModel.getI())) ? latestModel : storedModel;
} else {
System.err.println("My model is null!!!");
}
ModelHolder sendingModelHolder = new BoundedModelHolder(1);
sendingModelHolder.add(M);
// send the latest model to a random neighbor
sendToNeighbor(new ModelMessage(currentNode, sendingModelHolder), 0);
sendToNeighbor(new ModelMessage(currentNode, sendingModelHolder), 1);
}
}
|
diff --git a/org.openbel.framework.core/src/main/java/org/openbel/framework/core/equivalence/StatementEquivalencer.java b/org.openbel.framework.core/src/main/java/org/openbel/framework/core/equivalence/StatementEquivalencer.java
index a82b4de1..4219f74f 100644
--- a/org.openbel.framework.core/src/main/java/org/openbel/framework/core/equivalence/StatementEquivalencer.java
+++ b/org.openbel.framework.core/src/main/java/org/openbel/framework/core/equivalence/StatementEquivalencer.java
@@ -1,129 +1,130 @@
/**
* Copyright (C) 2012 Selventa, Inc.
*
* This file is part of the OpenBEL Framework.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The OpenBEL Framework is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the OpenBEL Framework. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms under LGPL v3:
*
* This license does not authorize you and you are prohibited from using the
* name, trademarks, service marks, logos or similar indicia of Selventa, Inc.,
* or, in the discretion of other licensors or authors of the program, the
* name, trademarks, service marks, logos or similar indicia of such authors or
* licensors, in any marketing or advertising materials relating to your
* distribution of the program or any covered product. This restriction does
* not waive or limit your obligation to keep intact all copyright notices set
* forth in the program as delivered to you.
*
* If you distribute the program in whole or in part, or any modified version
* of the program, and you assume contractual liability to the recipient with
* respect to the program or modified version, then you will indemnify the
* authors and licensors of the program for any liabilities that these
* contractual assumptions directly impose on those licensors and authors.
*/
package org.openbel.framework.core.equivalence;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.openbel.framework.common.protonetwork.model.ProtoEdgeTable;
import org.openbel.framework.common.protonetwork.model.ProtoEdgeTable.TableProtoEdge;
import org.openbel.framework.common.protonetwork.model.ProtoNetwork;
import org.openbel.framework.common.protonetwork.model.ProtoNodeTable;
/**
* StatementEquivalencer equivalences {@link ProtoNetwork} statements by
* comparing statement signatures based on global term ids.
*
* This algorithm has O(n log(n)) complexity.
*
* @author Anthony Bargnesi {@code <[email protected]>}
*/
public class StatementEquivalencer extends Equivalencer {
/**
* Constructs the statement equivalencer with a {@link ProtoNetwork} to
* equivalence.
*
* @param pn {@link ProtoNetwork} the proto network to equivalence
*/
public StatementEquivalencer(ProtoNetwork pn) {
super(pn);
}
/**
* {@inheritDoc}
*/
@Override
public int equivalence() {
ProtoNodeTable pnt = network.getProtoNodeTable();
ProtoEdgeTable pet = network.getProtoEdgeTable();
List<TableProtoEdge> edges = pet.getProtoEdges();
Map<Integer, Set<Integer>> edgeStmts = pet.getEdgeStatements();
Map<Integer, Integer> eqn = pnt.getEquivalences();
Map<Integer, Integer> eqe = pet.getEquivalences();
return equivalenceInternal(edges, edgeStmts, eqn, eqe);
}
protected static int equivalenceInternal(List<TableProtoEdge> edges,
Map<Integer, Set<Integer>> edgeStmts, Map<Integer, Integer> eqn,
Map<Integer, Integer> eqe) {
eqe.clear();
int eqct = 0;
final Map<TableProtoEdge, Integer> edgeCache =
new HashMap<ProtoEdgeTable.TableProtoEdge, Integer>();
final Map<Integer, Integer> revEq = new HashMap<Integer, Integer>();
int eq = 0;
for (int i = 0, n = edges.size(); i < n; i++) {
final TableProtoEdge edge = edges.get(i);
// translate into a proto node equivalent edge
final Integer eqs = eqn.get(edge.getSource());
final Integer eqt = eqn.get(edge.getTarget());
final TableProtoEdge eqEdge =
new TableProtoEdge(eqs, edge.getRel(), eqt);
// we have seen this proto edge so equivalence
Integer cachedEdge = edgeCache.get(eqEdge);
if (cachedEdge != null) {
// reassign equivalence index to previously seen equivalent edge
eqe.put(i, cachedEdge);
// add the current edge's statements to the equivalenced one
final Set<Integer> curEdgeStmts = edgeStmts.get(i);
final Set<Integer> eqEdgeStmts =
edgeStmts.get(revEq.get(cachedEdge));
eqEdgeStmts.addAll(curEdgeStmts);
+ curEdgeStmts.addAll(eqEdgeStmts);
eqct++;
continue;
}
edgeCache.put(eqEdge, eq);
eqe.put(i, eq);
revEq.put(eq, i);
eq++;
}
return eqct;
}
}
| true | true | protected static int equivalenceInternal(List<TableProtoEdge> edges,
Map<Integer, Set<Integer>> edgeStmts, Map<Integer, Integer> eqn,
Map<Integer, Integer> eqe) {
eqe.clear();
int eqct = 0;
final Map<TableProtoEdge, Integer> edgeCache =
new HashMap<ProtoEdgeTable.TableProtoEdge, Integer>();
final Map<Integer, Integer> revEq = new HashMap<Integer, Integer>();
int eq = 0;
for (int i = 0, n = edges.size(); i < n; i++) {
final TableProtoEdge edge = edges.get(i);
// translate into a proto node equivalent edge
final Integer eqs = eqn.get(edge.getSource());
final Integer eqt = eqn.get(edge.getTarget());
final TableProtoEdge eqEdge =
new TableProtoEdge(eqs, edge.getRel(), eqt);
// we have seen this proto edge so equivalence
Integer cachedEdge = edgeCache.get(eqEdge);
if (cachedEdge != null) {
// reassign equivalence index to previously seen equivalent edge
eqe.put(i, cachedEdge);
// add the current edge's statements to the equivalenced one
final Set<Integer> curEdgeStmts = edgeStmts.get(i);
final Set<Integer> eqEdgeStmts =
edgeStmts.get(revEq.get(cachedEdge));
eqEdgeStmts.addAll(curEdgeStmts);
eqct++;
continue;
}
edgeCache.put(eqEdge, eq);
eqe.put(i, eq);
revEq.put(eq, i);
eq++;
}
return eqct;
}
| protected static int equivalenceInternal(List<TableProtoEdge> edges,
Map<Integer, Set<Integer>> edgeStmts, Map<Integer, Integer> eqn,
Map<Integer, Integer> eqe) {
eqe.clear();
int eqct = 0;
final Map<TableProtoEdge, Integer> edgeCache =
new HashMap<ProtoEdgeTable.TableProtoEdge, Integer>();
final Map<Integer, Integer> revEq = new HashMap<Integer, Integer>();
int eq = 0;
for (int i = 0, n = edges.size(); i < n; i++) {
final TableProtoEdge edge = edges.get(i);
// translate into a proto node equivalent edge
final Integer eqs = eqn.get(edge.getSource());
final Integer eqt = eqn.get(edge.getTarget());
final TableProtoEdge eqEdge =
new TableProtoEdge(eqs, edge.getRel(), eqt);
// we have seen this proto edge so equivalence
Integer cachedEdge = edgeCache.get(eqEdge);
if (cachedEdge != null) {
// reassign equivalence index to previously seen equivalent edge
eqe.put(i, cachedEdge);
// add the current edge's statements to the equivalenced one
final Set<Integer> curEdgeStmts = edgeStmts.get(i);
final Set<Integer> eqEdgeStmts =
edgeStmts.get(revEq.get(cachedEdge));
eqEdgeStmts.addAll(curEdgeStmts);
curEdgeStmts.addAll(eqEdgeStmts);
eqct++;
continue;
}
edgeCache.put(eqEdge, eq);
eqe.put(i, eq);
revEq.put(eq, i);
eq++;
}
return eqct;
}
|
diff --git a/SimplyVanish/src/asofold/simplyvanish/SimplyVanish.java b/SimplyVanish/src/asofold/simplyvanish/SimplyVanish.java
index 3d907bb..9626010 100644
--- a/SimplyVanish/src/asofold/simplyvanish/SimplyVanish.java
+++ b/SimplyVanish/src/asofold/simplyvanish/SimplyVanish.java
@@ -1,326 +1,326 @@
package asofold.simplyvanish;
import java.io.File;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.PluginCommand;
import org.bukkit.configuration.Configuration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import asofold.simplyvanish.config.Settings;
/**
* Example plugin for the vanish API as of CB 1914 !
* Vanish + God mode + No Target + No pickup.
* @author mc_dev
*
*/
public class SimplyVanish extends JavaPlugin {
static final SimplyVanishCore core = new SimplyVanishCore();
public static final String msgLabel = ChatColor.GOLD+"[SimplyVanish] ";
public static final String[] baseLabels = new String[]{
"vanish", "reappear", "tvanish", "simplyvanish","vanished",
};
Configuration defaults;
/**
* Map aliases to recognized labels.
*/
Map<String, String> commandAliases = new HashMap<String, String>();
/**
* Constructor: set some defualt configuration values.
*/
public SimplyVanish(){
defaults = Settings.getDefaultConfig();
}
@Override
public void onDisable() {
if (core.settings.saveVanished) core.saveVanished();
core.setEnabled(false);
// TODO: maybe let all players see each other again?
System.out.println("[SimplyVanish] Disabled.");
}
@Override
public void onEnable() {
core.setVanishedFile(new File(getDataFolder(), "vanished.dat"));
// load settings
loadSettings(); // will also load vanished players
// just in case quadratic time checking:
for ( Player player : getServer().getOnlinePlayers()){
core.updateVanishState(player);
}
// register events:
getServer().getPluginManager().registerEvents(core, this);
// finished enabling.
core.setEnabled(true);
System.out.println("[SimplyVanish] Enabled");
}
/**
* Force reloading the config.
*/
public void loadSettings() {
reloadConfig();
Configuration config = getConfig();
Utils.forceDefaults(defaults, config);
Settings settings = new Settings();
settings.applyConfig(config);
core.setSettings(settings);
registerCommandAliases(config);
saveConfig(); // TODO: maybe check for changes, somehow ?
if (settings.saveVanished) core.loadVanished();
}
@Override
public boolean onCommand(CommandSender sender, Command command,
String label, String[] args) {
label = getMappedCommandLabel(label);
int len = args.length;
boolean hasFlags = false;
- for ( int i=args.length-1; i>=0; i++){
+ for ( int i=args.length-1; i>=0; i--){
if (args[i].startsWith("+") || args[i].startsWith("-")){
len --;
hasFlags = true;
}
}
if (label.equals("nosee") && len==0){
// TODO: EXPERIMENTAL ADDITION
// toggle for oneself.
if ( !Utils.checkPlayer(sender)) return true;
if ( !Utils.checkPerm(sender, "simplyvanish.see-all")) return true;
core.onToggleNosee((Player) sender);
return true;
}
else if ( label.equals("vanish") && len==0 ){
if ( !Utils.checkPlayer(sender)) return true;
if ( !Utils.checkPerm(sender, "simplyvanish.vanish.self")) return true;
// Make sure the player is vanished...
if (hasFlags){
if (Utils.hasPermission(sender, "simplyvanish.flags.set.self")) core.setFlags(((Player) sender).getName(), args, 0);
else sender.sendMessage(SimplyVanish.msgLabel+ChatColor.RED+"You do not have permission to set flags.");
}
core.onVanish((Player) sender);
return true;
}
else if ( label.equals("vanish") && len==1 ){
if ( !Utils.checkPerm(sender, "simplyvanish.vanish.other")) return true;
// Make sure the other player is vanished...
String name = args[0].trim();
if (hasFlags){
if (Utils.hasPermission(sender, "simplyvanish.flags.set.self")) core.setFlags(name, args, 1);
else sender.sendMessage(SimplyVanish.msgLabel+ChatColor.RED+"You do not have permission to set flags for others.");
}
setVanished(name, true);
Utils.send(sender, msgLabel + "Vanish player: "+name);
return true;
}
else if (label.equals("reappear") && len==0 ){
if ( !Utils.checkPlayer(sender)) return true;
if ( !Utils.checkPerm(sender, "simplyvanish.vanish.self")) return true;
// Let the player be seen...
if (hasFlags){
if (Utils.hasPermission(sender, "simplyvanish.flags.set.self")) core.setFlags(((Player) sender).getName(), args, 0);
else sender.sendMessage(SimplyVanish.msgLabel+ChatColor.RED+"You do not have permission to set flags.");
}
core.onReappear((Player) sender);
return true;
}
else if ( label.equals("reappear") && len==1 ){
if ( !Utils.checkPerm(sender, "simplyvanish.vanish.other")) return true;
// Make sure the other player is shown...
String name = args[0].trim();
if (hasFlags){
if (Utils.hasPermission(sender, "simplyvanish.flags.set.other")) core.setFlags(name, args, 1);
else sender.sendMessage(SimplyVanish.msgLabel+ChatColor.RED+"You do not have permission to set flags.");
}
setVanished(name, false);
Utils.send(sender, msgLabel + "Show player: "+name);
return true;
}
else if ( label.equals("tvanish") && len==0 ){
if ( !Utils.checkPlayer(sender)) return true;
Player player = (Player) sender;
if ( !Utils.checkPerm(sender, "simplyvanish.vanish.self")) return true;
if (hasFlags){
if (Utils.hasPermission(sender, "simplyvanish.flags.set.self")) core.setFlags(player.getName(), args, 0);
else sender.sendMessage(SimplyVanish.msgLabel+ChatColor.RED+"You do not have permission to set flags.");
}
setVanished(player, !isVanished(player));
return true;
}
else if (label.equals("vanished")){
if ( !Utils.checkPerm(sender, "simplyvanish.vanished")) return true;
Utils.send(sender, core.getVanishedMessage());
return true;
}
else if ( label.equals("simplyvanish")){
if (len==1 && args[0].equalsIgnoreCase("reload")){
if ( !Utils.checkPerm(sender, "simplyvanish.reload")) return true;
loadSettings();
Utils.send(sender, msgLabel + "Settings reloaded.");
return true;
}
else if (len==1 && args[0].equalsIgnoreCase("drop")){
if ( !Utils.checkPerm(sender, "simplyvanish.cmd.drop")) return true;
if (!Utils.checkPlayer(sender)) return true;
Utils.dropItemInHand((Player) sender);
return true;
}
else if (hasFlags && len == 0){
if (!Utils.checkPlayer(sender)) return true;
if (Utils.hasPermission(sender, "simplyvanish.flags.set.self")) core.setFlags(((Player)sender).getName(), args, 0);
else sender.sendMessage(SimplyVanish.msgLabel+ChatColor.RED+"You do not have permission to set flags.");
return true;
}
else if (len == 0){
if (!Utils.checkPlayer(sender)) return true;
if (Utils.hasPermission(sender, "simplyvanish.flags.display.self")) core.onShowFlags((Player) sender, null);
else sender.sendMessage(SimplyVanish.msgLabel+ChatColor.RED+"You do not have permission to display flags.");
return true;
}
else if (len==1){
if (!Utils.checkPlayer(sender)) return true;
if (Utils.hasPermission(sender, "simplyvanish.flags.display.other")) core.onShowFlags((Player) sender, args[0]);
else sender.sendMessage(SimplyVanish.msgLabel+ChatColor.RED+"You do not have permission to display flags of others.");
return true;
}
}
Utils.send(sender, msgLabel + ChatColor.DARK_RED+"Unrecognized command or number of arguments.");
return false;
}
/**
* @deprecated Use setVanished(player, true)
* @param player
*/
public void vanish(Player player){
setVanished(player, true);
}
/**
* @deprecated Use setVanished(player, false)
* @param player
*/
public void reappear(Player player){
setVanished(player, false);
}
/**
* API
* @param player
* @param vanished true=vanish, false=reappear
*/
public static void setVanished(Player player, boolean vanished){
if (!core.isEnabled()) return;
core.setVanished(player.getName(), vanished);
}
/**
* API
* @param playerName
* @param vanished
*/
public static void setVanished(String playerName, boolean vanished){
if (!core.isEnabled()) return;
core.setVanished(playerName, vanished);
}
/**
* API
* @param playerName Exact player name.
* @return
*/
public static boolean isVanished(String playerName){
if (!core.isEnabled()) return false;
else return core.isVanished(playerName);
}
/**
* API
* @param player
* @return
*/
public static boolean isVanished(Player player){
if (!core.isEnabled()) return false;
else return core.isVanished(player.getName());
}
/**
* API
* Get a new Set containing the lower case names of Players to be vanished.<br>
* These are not necessarily online.<br>
* @deprecated The method signature will most likely change to Collection or List.
* @return
*/
public static Set<String> getVanishedPlayers(){
if (!core.isEnabled()) return new HashSet<String>();
else return core.getVanishedPlayers();
}
void registerCommandAliases(Configuration config) {
// OLD ATTEMPT TO REGISTER DYNAMICALLY COMMENTED OUT:
//for ( String cmd : SimplyVanish.baseLabels){
// List<String> mapped = config.getStringList("commands."+cmd+".aliases");
// if ( mapped == null || mapped.isEmpty()) continue;
// for ( String alias: mapped){
// commandAliases.put(alias.trim().toLowerCase(), cmd);
// }
// ArrayList<String> aliases = new ArrayList<String>(mapped.size());
// aliases.addAll(mapped); // TEST
// PluginCommand command = plugin.getCommand(cmd);
// try{
// command.unregister(cmap);
// command.setAliases(aliases);
// command.register(cmap);
// for (String alias : aliases){
// PluginCommand aliasCommand = plugin.getCommand(alias);
// if ( aliasCommand == null ) plugin.getServer().getLogger().warning("[SimplyVanish] Failed to set up command alias for '"+cmd+"': "+alias);
// else aliasCommand.setExecutor(plugin);
// }
// } catch (Throwable t){
// plugin.getServer().getLogger().severe("[SimplyVanish] Failed to register command aliases for '"+cmd+"': "+t.getMessage());
// t.printStackTrace();
// }
// command.setExecutor(plugin);
//}
// JUST TO REGISTER ALIASES FOR onCommand:
for ( String label : SimplyVanish.baseLabels){
PluginCommand command = getCommand(label);
List<String> aliases = command.getAliases();
if ( aliases == null) continue;
for ( String alias: aliases){
commandAliases.put(alias.trim().toLowerCase(), label.toLowerCase());
}
}
}
/**
* Get standardized lower-case label, possibly mapped from an alias.
* @param label
* @return
*/
String getMappedCommandLabel(String label){
label = label.toLowerCase();
String mapped = commandAliases.get(label);
if (mapped == null) return label;
else return mapped;
}
}
| true | true | public boolean onCommand(CommandSender sender, Command command,
String label, String[] args) {
label = getMappedCommandLabel(label);
int len = args.length;
boolean hasFlags = false;
for ( int i=args.length-1; i>=0; i++){
if (args[i].startsWith("+") || args[i].startsWith("-")){
len --;
hasFlags = true;
}
}
if (label.equals("nosee") && len==0){
// TODO: EXPERIMENTAL ADDITION
// toggle for oneself.
if ( !Utils.checkPlayer(sender)) return true;
if ( !Utils.checkPerm(sender, "simplyvanish.see-all")) return true;
core.onToggleNosee((Player) sender);
return true;
}
else if ( label.equals("vanish") && len==0 ){
if ( !Utils.checkPlayer(sender)) return true;
if ( !Utils.checkPerm(sender, "simplyvanish.vanish.self")) return true;
// Make sure the player is vanished...
if (hasFlags){
if (Utils.hasPermission(sender, "simplyvanish.flags.set.self")) core.setFlags(((Player) sender).getName(), args, 0);
else sender.sendMessage(SimplyVanish.msgLabel+ChatColor.RED+"You do not have permission to set flags.");
}
core.onVanish((Player) sender);
return true;
}
else if ( label.equals("vanish") && len==1 ){
if ( !Utils.checkPerm(sender, "simplyvanish.vanish.other")) return true;
// Make sure the other player is vanished...
String name = args[0].trim();
if (hasFlags){
if (Utils.hasPermission(sender, "simplyvanish.flags.set.self")) core.setFlags(name, args, 1);
else sender.sendMessage(SimplyVanish.msgLabel+ChatColor.RED+"You do not have permission to set flags for others.");
}
setVanished(name, true);
Utils.send(sender, msgLabel + "Vanish player: "+name);
return true;
}
else if (label.equals("reappear") && len==0 ){
if ( !Utils.checkPlayer(sender)) return true;
if ( !Utils.checkPerm(sender, "simplyvanish.vanish.self")) return true;
// Let the player be seen...
if (hasFlags){
if (Utils.hasPermission(sender, "simplyvanish.flags.set.self")) core.setFlags(((Player) sender).getName(), args, 0);
else sender.sendMessage(SimplyVanish.msgLabel+ChatColor.RED+"You do not have permission to set flags.");
}
core.onReappear((Player) sender);
return true;
}
else if ( label.equals("reappear") && len==1 ){
if ( !Utils.checkPerm(sender, "simplyvanish.vanish.other")) return true;
// Make sure the other player is shown...
String name = args[0].trim();
if (hasFlags){
if (Utils.hasPermission(sender, "simplyvanish.flags.set.other")) core.setFlags(name, args, 1);
else sender.sendMessage(SimplyVanish.msgLabel+ChatColor.RED+"You do not have permission to set flags.");
}
setVanished(name, false);
Utils.send(sender, msgLabel + "Show player: "+name);
return true;
}
else if ( label.equals("tvanish") && len==0 ){
if ( !Utils.checkPlayer(sender)) return true;
Player player = (Player) sender;
if ( !Utils.checkPerm(sender, "simplyvanish.vanish.self")) return true;
if (hasFlags){
if (Utils.hasPermission(sender, "simplyvanish.flags.set.self")) core.setFlags(player.getName(), args, 0);
else sender.sendMessage(SimplyVanish.msgLabel+ChatColor.RED+"You do not have permission to set flags.");
}
setVanished(player, !isVanished(player));
return true;
}
else if (label.equals("vanished")){
if ( !Utils.checkPerm(sender, "simplyvanish.vanished")) return true;
Utils.send(sender, core.getVanishedMessage());
return true;
}
else if ( label.equals("simplyvanish")){
if (len==1 && args[0].equalsIgnoreCase("reload")){
if ( !Utils.checkPerm(sender, "simplyvanish.reload")) return true;
loadSettings();
Utils.send(sender, msgLabel + "Settings reloaded.");
return true;
}
else if (len==1 && args[0].equalsIgnoreCase("drop")){
if ( !Utils.checkPerm(sender, "simplyvanish.cmd.drop")) return true;
if (!Utils.checkPlayer(sender)) return true;
Utils.dropItemInHand((Player) sender);
return true;
}
else if (hasFlags && len == 0){
if (!Utils.checkPlayer(sender)) return true;
if (Utils.hasPermission(sender, "simplyvanish.flags.set.self")) core.setFlags(((Player)sender).getName(), args, 0);
else sender.sendMessage(SimplyVanish.msgLabel+ChatColor.RED+"You do not have permission to set flags.");
return true;
}
else if (len == 0){
if (!Utils.checkPlayer(sender)) return true;
if (Utils.hasPermission(sender, "simplyvanish.flags.display.self")) core.onShowFlags((Player) sender, null);
else sender.sendMessage(SimplyVanish.msgLabel+ChatColor.RED+"You do not have permission to display flags.");
return true;
}
else if (len==1){
if (!Utils.checkPlayer(sender)) return true;
if (Utils.hasPermission(sender, "simplyvanish.flags.display.other")) core.onShowFlags((Player) sender, args[0]);
else sender.sendMessage(SimplyVanish.msgLabel+ChatColor.RED+"You do not have permission to display flags of others.");
return true;
}
}
Utils.send(sender, msgLabel + ChatColor.DARK_RED+"Unrecognized command or number of arguments.");
return false;
}
| public boolean onCommand(CommandSender sender, Command command,
String label, String[] args) {
label = getMappedCommandLabel(label);
int len = args.length;
boolean hasFlags = false;
for ( int i=args.length-1; i>=0; i--){
if (args[i].startsWith("+") || args[i].startsWith("-")){
len --;
hasFlags = true;
}
}
if (label.equals("nosee") && len==0){
// TODO: EXPERIMENTAL ADDITION
// toggle for oneself.
if ( !Utils.checkPlayer(sender)) return true;
if ( !Utils.checkPerm(sender, "simplyvanish.see-all")) return true;
core.onToggleNosee((Player) sender);
return true;
}
else if ( label.equals("vanish") && len==0 ){
if ( !Utils.checkPlayer(sender)) return true;
if ( !Utils.checkPerm(sender, "simplyvanish.vanish.self")) return true;
// Make sure the player is vanished...
if (hasFlags){
if (Utils.hasPermission(sender, "simplyvanish.flags.set.self")) core.setFlags(((Player) sender).getName(), args, 0);
else sender.sendMessage(SimplyVanish.msgLabel+ChatColor.RED+"You do not have permission to set flags.");
}
core.onVanish((Player) sender);
return true;
}
else if ( label.equals("vanish") && len==1 ){
if ( !Utils.checkPerm(sender, "simplyvanish.vanish.other")) return true;
// Make sure the other player is vanished...
String name = args[0].trim();
if (hasFlags){
if (Utils.hasPermission(sender, "simplyvanish.flags.set.self")) core.setFlags(name, args, 1);
else sender.sendMessage(SimplyVanish.msgLabel+ChatColor.RED+"You do not have permission to set flags for others.");
}
setVanished(name, true);
Utils.send(sender, msgLabel + "Vanish player: "+name);
return true;
}
else if (label.equals("reappear") && len==0 ){
if ( !Utils.checkPlayer(sender)) return true;
if ( !Utils.checkPerm(sender, "simplyvanish.vanish.self")) return true;
// Let the player be seen...
if (hasFlags){
if (Utils.hasPermission(sender, "simplyvanish.flags.set.self")) core.setFlags(((Player) sender).getName(), args, 0);
else sender.sendMessage(SimplyVanish.msgLabel+ChatColor.RED+"You do not have permission to set flags.");
}
core.onReappear((Player) sender);
return true;
}
else if ( label.equals("reappear") && len==1 ){
if ( !Utils.checkPerm(sender, "simplyvanish.vanish.other")) return true;
// Make sure the other player is shown...
String name = args[0].trim();
if (hasFlags){
if (Utils.hasPermission(sender, "simplyvanish.flags.set.other")) core.setFlags(name, args, 1);
else sender.sendMessage(SimplyVanish.msgLabel+ChatColor.RED+"You do not have permission to set flags.");
}
setVanished(name, false);
Utils.send(sender, msgLabel + "Show player: "+name);
return true;
}
else if ( label.equals("tvanish") && len==0 ){
if ( !Utils.checkPlayer(sender)) return true;
Player player = (Player) sender;
if ( !Utils.checkPerm(sender, "simplyvanish.vanish.self")) return true;
if (hasFlags){
if (Utils.hasPermission(sender, "simplyvanish.flags.set.self")) core.setFlags(player.getName(), args, 0);
else sender.sendMessage(SimplyVanish.msgLabel+ChatColor.RED+"You do not have permission to set flags.");
}
setVanished(player, !isVanished(player));
return true;
}
else if (label.equals("vanished")){
if ( !Utils.checkPerm(sender, "simplyvanish.vanished")) return true;
Utils.send(sender, core.getVanishedMessage());
return true;
}
else if ( label.equals("simplyvanish")){
if (len==1 && args[0].equalsIgnoreCase("reload")){
if ( !Utils.checkPerm(sender, "simplyvanish.reload")) return true;
loadSettings();
Utils.send(sender, msgLabel + "Settings reloaded.");
return true;
}
else if (len==1 && args[0].equalsIgnoreCase("drop")){
if ( !Utils.checkPerm(sender, "simplyvanish.cmd.drop")) return true;
if (!Utils.checkPlayer(sender)) return true;
Utils.dropItemInHand((Player) sender);
return true;
}
else if (hasFlags && len == 0){
if (!Utils.checkPlayer(sender)) return true;
if (Utils.hasPermission(sender, "simplyvanish.flags.set.self")) core.setFlags(((Player)sender).getName(), args, 0);
else sender.sendMessage(SimplyVanish.msgLabel+ChatColor.RED+"You do not have permission to set flags.");
return true;
}
else if (len == 0){
if (!Utils.checkPlayer(sender)) return true;
if (Utils.hasPermission(sender, "simplyvanish.flags.display.self")) core.onShowFlags((Player) sender, null);
else sender.sendMessage(SimplyVanish.msgLabel+ChatColor.RED+"You do not have permission to display flags.");
return true;
}
else if (len==1){
if (!Utils.checkPlayer(sender)) return true;
if (Utils.hasPermission(sender, "simplyvanish.flags.display.other")) core.onShowFlags((Player) sender, args[0]);
else sender.sendMessage(SimplyVanish.msgLabel+ChatColor.RED+"You do not have permission to display flags of others.");
return true;
}
}
Utils.send(sender, msgLabel + ChatColor.DARK_RED+"Unrecognized command or number of arguments.");
return false;
}
|
diff --git a/src/org/concord/geniverse/server/OrganismServiceImpl.java b/src/org/concord/geniverse/server/OrganismServiceImpl.java
index 4e8503d..f24f71f 100644
--- a/src/org/concord/geniverse/server/OrganismServiceImpl.java
+++ b/src/org/concord/geniverse/server/OrganismServiceImpl.java
@@ -1,282 +1,282 @@
package org.concord.geniverse.server;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import org.concord.biologica.engine.Characteristic;
import org.concord.biologica.engine.Organism;
import org.concord.biologica.engine.Species;
import org.concord.biologica.engine.SpeciesImage;
import org.concord.biologica.engine.Trait;
import org.concord.biologica.engine.World;
import org.concord.geniverse.client.GOrganism;
import org.concord.geniverse.client.OrganismService;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
public class OrganismServiceImpl extends RemoteServiceServlet implements OrganismService {
private static final Logger logger = Logger.getLogger(OrganismServiceImpl.class.getName());
private static final long serialVersionUID = 1L;
private World world = new World("org/concord/biologica/worlds/new-dragons.xml");
private Species species = world.getCurrentSpecies();
private static int currentDragonNumber = 0;
private void cleanupWorld(Organism org) {
world.deleteOrganism(org);
}
private GOrganism createGOrg(Organism org) {
GOrganism gOrg = new GOrganism();
gOrg.setName(org.getName());
gOrg.setSex(org.getSex());
gOrg.setAlleles(org.getAlleleString());
gOrg.setImageURL(getOrganismImageURL(org, SpeciesImage.XLARGE_IMAGE_SIZE));
HashMap<String, String> characteristicMap = getOrganismPhenotypes(org);
ArrayList<String> phenotypes = new ArrayList<String>();
phenotypes.addAll(characteristicMap.values());
gOrg.setCharacteristics(phenotypes);
gOrg.setCharacteristicMap(characteristicMap);
return gOrg;
}
private Organism createOrg(GOrganism gOrg) {
Organism org = new Organism(world, gOrg.getName(), species, gOrg.getSex(), gOrg.getAlleles());
return org;
}
public GOrganism getOrganism(int sex) {
System.out.println("getOrganism(int sex) called:");
Organism dragon = new Organism(world, sex, "Organism " + (++currentDragonNumber), world.getCurrentSpecies());
GOrganism gOrg = createGOrg(dragon);
cleanupWorld(dragon);
return gOrg;
}
public GOrganism getOrganism(int sex, String alleles) {
Organism dragon = new Organism(world, "Organism " + (++currentDragonNumber), world.getCurrentSpecies(), sex, alleles) ;
GOrganism gOrg = createGOrg(dragon);
cleanupWorld(dragon);
return gOrg;
}
public GOrganism getOrganism() {
System.out.println("getOrganism(int sex) called:");
Organism dragon = new Organism(world, Organism.RANDOM_SEX, "Organism " + (++currentDragonNumber), world.getCurrentSpecies());
GOrganism gOrg = createGOrg(dragon);
cleanupWorld(dragon);
return gOrg;
}
public ArrayList<String> getOrganismPhenotypes(GOrganism gOrg) {
Organism org = createOrg(gOrg);
ArrayList<String> phenotypes = new ArrayList<String>();
phenotypes.addAll(getOrganismPhenotypes(org).values());
cleanupWorld(org);
return phenotypes;
}
private HashMap<String, String> getOrganismPhenotypes(Organism org) {
HashMap<String, String> phenotypes = new HashMap<String, String>();
Enumeration<Characteristic> chars = org.getCharacteristics();
while (chars.hasMoreElements()) {
Characteristic c = chars.nextElement();
Trait t = c.getTrait();
phenotypes.put(t.getName().toLowerCase(), c.getName());
}
return phenotypes;
}
public String getOrganismImageURL() {
// FIXME cleanup
try {
return getOrganismImageURL(getOrganism(), SpeciesImage.XLARGE_IMAGE_SIZE);
} catch(Exception e) {
return e.toString();
}
}
public String getOrganismImageURL(GOrganism organism, int imageSize) {
Organism dragon = createOrg(organism);
String imageUrl = getOrganismImageURL(dragon, imageSize);
cleanupWorld(dragon);
return imageUrl;
}
private String getOrganismImageURL(Organism dragon, int imageSize) {
String filename = generateFilename(dragon, imageSize);
String host = getThreadLocalRequest().getServerName();
int port = getThreadLocalRequest().getServerPort();
String scheme = getThreadLocalRequest().getScheme();
String prefix = scheme + "://" + host;
if (port != 80) {
prefix += ":" + Integer.toString(port);
}
return prefix + "/resources/drakes/images/" + filename;
}
private String generateFilename(Organism org, int imageSize) {
if (getCharacteristic(org, "Liveliness").equalsIgnoreCase("Dead")){
return "dead-drake.png";
}
// [color]_[sex]_[wing]_[limbs]_[armor]_[tail]_[horn]_[rostralHorn]_[health].png
String filename = "";
// color
filename += getCharacteristic(org, "Color").toLowerCase().substring(0,
2)
+ "_";
// sex
filename += org.getSex() == 0 ? "m_" : "f_";
// wings
filename += getCharacteristic(org, "Wings").equalsIgnoreCase("Wings") ? "wing_"
: "noWing_";
// limbs
String limbs = "";
boolean forelimbs = getCharacteristic(org, "Forelimbs")
.equalsIgnoreCase("Forelimbs");
boolean hindlimbs = getCharacteristic(org, "Hindlimbs")
.equalsIgnoreCase("Hindlimbs");
if (forelimbs) {
if (hindlimbs) {
limbs = "allLimb";
} else {
limbs = "fore";
}
} else if (hindlimbs) {
limbs = "hind";
} else {
limbs = "noLimb";
}
filename += limbs + "_";
// armor
String armor = getCharacteristic(org, "Armor");
String armorStr = "";
if (armor.equalsIgnoreCase("Five armor")) {
armorStr = "a5";
} else if (armor.equalsIgnoreCase("Three armor")) {
armorStr = "a3";
} else if (armor.equalsIgnoreCase("One armor")) {
armorStr = "a1";
} else {
armorStr = "a0";
}
filename += armorStr + "_";
// tail
String tail = getCharacteristic(org, "Tail");
String tailStr = "";
if (tail.equalsIgnoreCase("Long tail")) {
tailStr = "flair";
} else if (tail.equalsIgnoreCase("Kinked tail")) {
- tailStr = "kinked";
+ tailStr = "kink";
} else {
tailStr = "short";
}
filename += tailStr + "_";
// horns
filename += getCharacteristic(org, "Horns").equalsIgnoreCase("Horns") ? "horn_"
: "noHorn_";
// rostral horn
filename += getCharacteristic(org, "Rostral horn").equalsIgnoreCase("Rostral horn") ? "rostral_"
: "noRostral_";
// health
filename += "healthy";
filename += ".png";
return filename;
}
private String getCharacteristic(Organism org, String trait) {
// rm "Characteristic: "
Characteristic c = org.getCharacteristicOfTrait(trait);
if (c == null) {
// FIXME probably we should do something smarter... throw a custom exception?
return "unknown";
}
return c.toString().split(": ")[1];
}
public GOrganism breedOrganism(GOrganism gorg1, GOrganism gorg2) {
System.out.println("breedOrganism(GOrganism gorg1, GOrganism gorg2) called:");
Organism org1 = createOrg(gorg1);
Organism org2 = createOrg(gorg2);
try {
Organism child = new Organism(org1, org2, "child");
GOrganism gOrg = createGOrg(child);
cleanupWorld(child);
cleanupWorld(org1);
cleanupWorld(org2);
return gOrg;
} catch (IllegalArgumentException e){
logger.log(Level.SEVERE, "Could not breed these organisms!", e);
cleanupWorld(org1);
cleanupWorld(org2);
return null;
}
}
public ArrayList<GOrganism> breedOrganisms(int number, GOrganism gorg1, GOrganism gorg2) {
logger.warning("Actually breeding " + number + " dragons");
ArrayList<GOrganism> orgs = new ArrayList<GOrganism>(number);
Organism org1 = createOrg(gorg1);
Organism org2 = createOrg(gorg2);
for (int i = 0; i < number; i++) {
Organism child = new Organism(org1, org2, "child " + i);
logger.warning("Bred " + child.getSexAsString() + " child: " + child.getAlleleString(false));
GOrganism gChild = createGOrg(child);
orgs.add(gChild);
cleanupWorld(child);
}
cleanupWorld(org1);
cleanupWorld(org2);
return orgs;
}
public ArrayList<GOrganism> breedOrganismsWithCrossover(int number, GOrganism gorg1, GOrganism gorg2, boolean crossingOver) {
logger.warning("Actually breeding " + number + " dragons");
ArrayList<GOrganism> orgs = new ArrayList<GOrganism>(number);
Organism org1 = createOrg(gorg1);
Organism org2 = createOrg(gorg2);
for (int i = 0; i < number; i++) {
Organism child = new Organism(org1, org2, "child " + i, crossingOver);
logger.warning("Bred " + child.getSexAsString() + " child: " + child.getAlleleString(false));
GOrganism gChild = createGOrg(child);
orgs.add(gChild);
cleanupWorld(child);
}
cleanupWorld(org1);
cleanupWorld(org2);
return orgs;
}
}
| true | true | private String generateFilename(Organism org, int imageSize) {
if (getCharacteristic(org, "Liveliness").equalsIgnoreCase("Dead")){
return "dead-drake.png";
}
// [color]_[sex]_[wing]_[limbs]_[armor]_[tail]_[horn]_[rostralHorn]_[health].png
String filename = "";
// color
filename += getCharacteristic(org, "Color").toLowerCase().substring(0,
2)
+ "_";
// sex
filename += org.getSex() == 0 ? "m_" : "f_";
// wings
filename += getCharacteristic(org, "Wings").equalsIgnoreCase("Wings") ? "wing_"
: "noWing_";
// limbs
String limbs = "";
boolean forelimbs = getCharacteristic(org, "Forelimbs")
.equalsIgnoreCase("Forelimbs");
boolean hindlimbs = getCharacteristic(org, "Hindlimbs")
.equalsIgnoreCase("Hindlimbs");
if (forelimbs) {
if (hindlimbs) {
limbs = "allLimb";
} else {
limbs = "fore";
}
} else if (hindlimbs) {
limbs = "hind";
} else {
limbs = "noLimb";
}
filename += limbs + "_";
// armor
String armor = getCharacteristic(org, "Armor");
String armorStr = "";
if (armor.equalsIgnoreCase("Five armor")) {
armorStr = "a5";
} else if (armor.equalsIgnoreCase("Three armor")) {
armorStr = "a3";
} else if (armor.equalsIgnoreCase("One armor")) {
armorStr = "a1";
} else {
armorStr = "a0";
}
filename += armorStr + "_";
// tail
String tail = getCharacteristic(org, "Tail");
String tailStr = "";
if (tail.equalsIgnoreCase("Long tail")) {
tailStr = "flair";
} else if (tail.equalsIgnoreCase("Kinked tail")) {
tailStr = "kinked";
} else {
tailStr = "short";
}
filename += tailStr + "_";
// horns
filename += getCharacteristic(org, "Horns").equalsIgnoreCase("Horns") ? "horn_"
: "noHorn_";
// rostral horn
filename += getCharacteristic(org, "Rostral horn").equalsIgnoreCase("Rostral horn") ? "rostral_"
: "noRostral_";
// health
filename += "healthy";
filename += ".png";
return filename;
}
| private String generateFilename(Organism org, int imageSize) {
if (getCharacteristic(org, "Liveliness").equalsIgnoreCase("Dead")){
return "dead-drake.png";
}
// [color]_[sex]_[wing]_[limbs]_[armor]_[tail]_[horn]_[rostralHorn]_[health].png
String filename = "";
// color
filename += getCharacteristic(org, "Color").toLowerCase().substring(0,
2)
+ "_";
// sex
filename += org.getSex() == 0 ? "m_" : "f_";
// wings
filename += getCharacteristic(org, "Wings").equalsIgnoreCase("Wings") ? "wing_"
: "noWing_";
// limbs
String limbs = "";
boolean forelimbs = getCharacteristic(org, "Forelimbs")
.equalsIgnoreCase("Forelimbs");
boolean hindlimbs = getCharacteristic(org, "Hindlimbs")
.equalsIgnoreCase("Hindlimbs");
if (forelimbs) {
if (hindlimbs) {
limbs = "allLimb";
} else {
limbs = "fore";
}
} else if (hindlimbs) {
limbs = "hind";
} else {
limbs = "noLimb";
}
filename += limbs + "_";
// armor
String armor = getCharacteristic(org, "Armor");
String armorStr = "";
if (armor.equalsIgnoreCase("Five armor")) {
armorStr = "a5";
} else if (armor.equalsIgnoreCase("Three armor")) {
armorStr = "a3";
} else if (armor.equalsIgnoreCase("One armor")) {
armorStr = "a1";
} else {
armorStr = "a0";
}
filename += armorStr + "_";
// tail
String tail = getCharacteristic(org, "Tail");
String tailStr = "";
if (tail.equalsIgnoreCase("Long tail")) {
tailStr = "flair";
} else if (tail.equalsIgnoreCase("Kinked tail")) {
tailStr = "kink";
} else {
tailStr = "short";
}
filename += tailStr + "_";
// horns
filename += getCharacteristic(org, "Horns").equalsIgnoreCase("Horns") ? "horn_"
: "noHorn_";
// rostral horn
filename += getCharacteristic(org, "Rostral horn").equalsIgnoreCase("Rostral horn") ? "rostral_"
: "noRostral_";
// health
filename += "healthy";
filename += ".png";
return filename;
}
|
diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/EngineTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/EngineTest.java
index abe56f7af..d96fe7a4f 100644
--- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/EngineTest.java
+++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/EngineTest.java
@@ -1,802 +1,804 @@
/*******************************************************************************
* Copyright (c) 2007, 2010 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.equinox.p2.tests.engine;
import java.io.File;
import java.util.*;
import org.eclipse.core.runtime.*;
import org.eclipse.equinox.internal.p2.engine.*;
import org.eclipse.equinox.internal.p2.engine.phases.*;
import org.eclipse.equinox.p2.core.IProvisioningAgent;
import org.eclipse.equinox.p2.engine.*;
import org.eclipse.equinox.p2.engine.spi.ProvisioningAction;
import org.eclipse.equinox.p2.metadata.*;
import org.eclipse.equinox.p2.metadata.MetadataFactory.InstallableUnitDescription;
import org.eclipse.equinox.p2.metadata.MetadataFactory.InstallableUnitFragmentDescription;
import org.eclipse.equinox.p2.query.*;
import org.eclipse.equinox.p2.tests.AbstractProvisioningTest;
/**
* Simple test of the engine API.
*
* Note:
* Currently you MUST have previously generated metadata from a 3.3.1 install.
* There are ordering dependencies for the tests temporarily
*/
public class EngineTest extends AbstractProvisioningTest {
private static class CountPhase extends Phase {
int operandCount = 0;
int phaseCount = 0;
protected CountPhase(String name, boolean forced) {
super(name, 1, forced);
}
protected CountPhase(String name) {
this(name, false);
}
protected IStatus completeOperand(IProfile profile, Operand operand, Map parameters, IProgressMonitor monitor) {
operandCount--;
return super.completeOperand(profile, operand, parameters, monitor);
}
protected IStatus completePhase(IProgressMonitor monitor, IProfile profile, Map parameters) {
phaseCount--;
return super.completePhase(monitor, profile, parameters);
}
protected IStatus initializeOperand(IProfile profile, Operand operand, Map parameters, IProgressMonitor monitor) {
operandCount++;
return super.initializeOperand(profile, operand, parameters, monitor);
}
protected IStatus initializePhase(IProgressMonitor monitor, IProfile profile, Map parameters) {
phaseCount++;
return super.initializePhase(monitor, profile, parameters);
}
protected List<ProvisioningAction> getActions(Operand operand) {
return null;
}
public boolean isConsistent() {
return operandCount == 0 && phaseCount == 0;
}
}
private static class NPEPhase extends CountPhase {
protected NPEPhase() {
super("NPE");
}
protected IStatus completePhase(IProgressMonitor monitor, IProfile profile, Map parameters) {
super.completePhase(monitor, profile, parameters);
throw new NullPointerException();
}
protected List<ProvisioningAction> getActions(Operand operand) {
return null;
}
}
private static class ActionNPEPhase extends CountPhase {
protected ActionNPEPhase(boolean forced) {
super("ActionNPEPhase", forced);
}
protected ActionNPEPhase() {
this(false);
}
protected List<ProvisioningAction> getActions(Operand operand) {
ProvisioningAction action = new ProvisioningAction() {
public IStatus undo(Map parameters) {
throw new NullPointerException();
}
public IStatus execute(Map parameters) {
throw new NullPointerException();
}
};
return Collections.singletonList(action);
}
}
private static class TestPhaseSet extends PhaseSet {
public TestPhaseSet(Phase phase) {
super(new Phase[] {new Collect(100), new Unconfigure(10), new Uninstall(50), new Property(1), new CheckTrust(10), new Install(50), new Configure(10), phase});
}
public TestPhaseSet(boolean forced) {
super(new Phase[] {new Collect(100), new Unconfigure(10, forced), new Uninstall(50, forced), new Property(1), new CheckTrust(10), new Install(50), new Configure(10)});
}
}
private IEngine engine;
private File testProvisioning;
public EngineTest(String name) {
super(name);
}
public EngineTest() {
this("");
}
private static boolean deleteDirectory(File directory) {
if (directory.exists() && directory.isDirectory()) {
File[] files = directory.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
deleteDirectory(files[i]);
} else {
files[i].delete();
}
}
}
return directory.delete();
}
protected void setUp() throws Exception {
engine = getEngine();
testProvisioning = new File(System.getProperty("java.io.tmpdir"), "testProvisioning");
deleteDirectory(testProvisioning);
testProvisioning.mkdir();
}
protected void tearDown() throws Exception {
engine = null;
deleteDirectory(testProvisioning);
}
public void testNullProfile() {
IProfile profile = null;
try {
engine.perform(engine.createPlan(profile, null), new NullProgressMonitor());
} catch (AssertionFailedException expected) {
return;
}
fail();
}
public void testNullPhaseSet() {
IProfile profile = createProfile("test");
PhaseSet phaseSet = null;
try {
engine.perform(engine.createPlan(profile, null), phaseSet, new NullProgressMonitor());
} catch (IllegalArgumentException expected) {
return;
}
fail();
}
public void testNullPlan() {
try {
engine.perform(null, new NullProgressMonitor());
fail();
} catch (RuntimeException expected) {
//expected
}
}
/*
* Tests for {@link IEngine#createPhaseSetExcluding}.
*/
public void testCreatePhaseSetExcluding() {
//null argument
IPhaseSet set = PhaseSetFactory.createDefaultPhaseSetExcluding(null);
assertEquals("1.0", 7, set.getPhaseIds().length);
//empty argument
set = PhaseSetFactory.createDefaultPhaseSetExcluding(new String[0]);
assertEquals("2.0", 7, set.getPhaseIds().length);
//bogus argument
set = PhaseSetFactory.createDefaultPhaseSetExcluding(new String[] {"blort"});
assertEquals("3.0", 7, set.getPhaseIds().length);
//valid argument
set = PhaseSetFactory.createDefaultPhaseSetExcluding(new String[] {PhaseSetFactory.PHASE_CHECK_TRUST});
final String[] phases = set.getPhaseIds();
assertEquals("4.0", 6, phases.length);
for (int i = 0; i < phases.length; i++)
if (phases[i].equals(PhaseSetFactory.PHASE_CHECK_TRUST))
fail("4.1." + i);
}
/*
* Tests for {@link IEngine#createPhaseSetIncluding}.
*/
public void testCreatePhaseSetIncluding() {
//null argument
IPhaseSet set = PhaseSetFactory.createPhaseSetIncluding(null);
assertNotNull("1.0", set);
assertEquals("1.1", 0, set.getPhaseIds().length);
//expected
//empty argument
set = PhaseSetFactory.createPhaseSetIncluding(new String[0]);
assertNotNull("2.0", set);
assertEquals("2.1", 0, set.getPhaseIds().length);
//unknown argument
set = PhaseSetFactory.createPhaseSetIncluding(new String[] {"blort", "not a phase", "bad input"});
assertNotNull("3.0", set);
assertEquals("3.1", 0, set.getPhaseIds().length);
//one valid phase
set = PhaseSetFactory.createPhaseSetIncluding(new String[] {PhaseSetFactory.PHASE_COLLECT});
assertNotNull("4.0", set);
assertEquals("4.1", 1, set.getPhaseIds().length);
assertEquals("4.2", PhaseSetFactory.PHASE_COLLECT, set.getPhaseIds()[0]);
//one valid phase and one bogus
set = PhaseSetFactory.createPhaseSetIncluding(new String[] {PhaseSetFactory.PHASE_COLLECT, "bogus"});
assertNotNull("4.0", set);
assertEquals("4.1", 1, set.getPhaseIds().length);
assertEquals("4.2", PhaseSetFactory.PHASE_COLLECT, set.getPhaseIds()[0]);
}
public void testEmptyOperands() {
IProfile profile = createProfile("test");
IStatus result = engine.perform(engine.createPlan(profile, null), new NullProgressMonitor());
assertTrue(result.isOK());
}
public void testEmptyPhaseSet() {
IProfile profile = createProfile("testEmptyPhaseSet");
PhaseSet phaseSet = new PhaseSet(new Phase[] {}) {
// empty PhaseSet
};
IProvisioningPlan plan = engine.createPlan(profile, null);
plan.removeInstallableUnit(createResolvedIU(createIU("name")));
IStatus result = engine.perform(plan, phaseSet, new NullProgressMonitor());
assertTrue(result.isOK());
}
public void testPerformAddSingleNullIU() {
try {
IProfile profile = createProfile("testPerformAddSingleNullIU");
IProvisioningPlan plan = engine.createPlan(profile, null);
plan.addInstallableUnit(null);
fail("Should not allow null iu");
} catch (RuntimeException e) {
//expected
}
}
public void testPerformPropertyInstallUninstall() {
IProfile profile = createProfile("testPerformPropertyInstallUninstall");
IProvisioningPlan plan = engine.createPlan(profile, null);
plan.setProfileProperty("test", "test");
IInstallableUnit testIU = createResolvedIU(createIU("test"));
plan.addInstallableUnit(testIU);
plan.setInstallableUnitProfileProperty(testIU, "test", "test");
IStatus result = engine.perform(plan, new NullProgressMonitor());
assertTrue(result.isOK());
assertEquals("test", profile.getProperty("test"));
assertEquals("test", profile.getInstallableUnitProperty(testIU, "test"));
plan = engine.createPlan(profile, null);
plan.setProfileProperty("test", null);
plan.removeInstallableUnit(testIU);
plan.setInstallableUnitProfileProperty(testIU, "test", null);
result = engine.perform(plan, new NullProgressMonitor());
assertTrue(result.isOK());
assertNull("test", profile.getProperty("test"));
assertNull("test", profile.getInstallableUnitProperty(testIU, "test"));
}
// This tests currently does not download anything. We need another sizing test to ensure sizes are retrieved
public void testPerformSizingOSGiFrameworkNoArtifacts() {
Map properties = new HashMap();
properties.put(IProfile.PROP_INSTALL_FOLDER, testProvisioning.getAbsolutePath());
IProfile profile = createProfile("testPerformSizing", properties);
for (Iterator it = getInstallableUnits(profile); it.hasNext();) {
IProvisioningPlan plan = engine.createPlan(profile, null);
IInstallableUnit doomed = (IInstallableUnit) it.next();
plan.removeInstallableUnit(doomed);
engine.perform(plan, new NullProgressMonitor());
}
final Sizing sizingPhase = new Sizing(100);
PhaseSet phaseSet = new PhaseSet(new Phase[] {sizingPhase});
IProvisioningPlan plan = engine.createPlan(profile, null);
plan.addInstallableUnit(createOSGiIU());
IStatus result = engine.perform(plan, phaseSet, new NullProgressMonitor());
assertTrue(result.isOK());
assertTrue(sizingPhase.getDiskSize() == 0);
assertTrue(sizingPhase.getDownloadSize() == 0);
}
// removing validate from engine api
// public void testValidateInstallOSGiFramework() {
// Map properties = new HashMap();
// properties.put(IProfile.PROP_INSTALL_FOLDER, testProvisioning.getAbsolutePath());
//
// IProfile profile = createProfile("testPerformInstallOSGiFramework", properties);
// for (Iterator it = getInstallableUnits(profile); it.hasNext();) {
// IInstallableUnit doomed = (IInstallableUnit) it.next();
// InstallableUnitOperand[] operands = new InstallableUnitOperand[] {new InstallableUnitOperand(createResolvedIU(doomed), null)};
// engine.perform(engine.createPlan(profile, null), new NullProgressMonitor());
// }
// PhaseSet phaseSet = new PhaseSetFactory();
// InstallableUnitOperand[] operands = new InstallableUnitOperand[] {new InstallableUnitOperand(null, createOSGiIU())};
// IStatus result = ((Engine) engine).validate(profile, phaseSet, operands, null, new NullProgressMonitor());
// assertTrue(result.isOK());
// }
public void testPerformInstallOSGiFramework() {
Map properties = new HashMap();
properties.put(IProfile.PROP_INSTALL_FOLDER, testProvisioning.getAbsolutePath());
IProfile profile = createProfile("testPerformInstallOSGiFramework", properties);
for (Iterator it = getInstallableUnits(profile); it.hasNext();) {
IProvisioningPlan plan = engine.createPlan(profile, null);
IInstallableUnit doomed = (IInstallableUnit) it.next();
plan.removeInstallableUnit(doomed);
engine.perform(plan, new NullProgressMonitor());
}
IProvisioningPlan plan = engine.createPlan(profile, null);
plan.addInstallableUnit(createOSGiIU());
IStatus result = engine.perform(plan, new NullProgressMonitor());
assertTrue(result.isOK());
Iterator ius = getInstallableUnits(profile);
assertTrue(ius.hasNext());
}
public void testPerformUpdateOSGiFramework() {
Map properties = new HashMap();
properties.put(IProfile.PROP_INSTALL_FOLDER, testProvisioning.getAbsolutePath());
IProfile profile = createProfile("testPerformUpdateOSGiFramework", properties);
IInstallableUnit iu33 = createOSGiIU("3.3");
IInstallableUnit iu34 = createOSGiIU("3.4");
IProvisioningPlan plan = engine.createPlan(profile, null);
plan.addInstallableUnit(iu33);
IStatus result = engine.perform(plan, new NullProgressMonitor());
assertTrue(result.isOK());
Iterator ius = profile.query(QueryUtil.createIUQuery(iu33), null).iterator();
assertTrue(ius.hasNext());
plan = engine.createPlan(profile, null);
plan.updateInstallableUnit(iu33, iu34);
result = engine.perform(plan, new NullProgressMonitor());
assertTrue(result.isOK());
ius = profile.query(QueryUtil.createIUQuery(iu34), null).iterator();
assertTrue(ius.hasNext());
}
public void testPerformUninstallOSGiFramework() {
Map properties = new HashMap();
properties.put(IProfile.PROP_INSTALL_FOLDER, testProvisioning.getAbsolutePath());
IProfile profile = createProfile("testPerformUninstallOSGiFramework", properties);
IProvisioningPlan plan = engine.createPlan(profile, null);
plan.removeInstallableUnit(createOSGiIU());
IStatus result = engine.perform(plan, new NullProgressMonitor());
assertTrue(result.isOK());
assertEmptyProfile(profile);
}
public void testPerformRollback() {
Map properties = new HashMap();
properties.put(IProfile.PROP_INSTALL_FOLDER, testProvisioning.getAbsolutePath());
IProfile profile = createProfile("testPerformRollback", properties);
Iterator ius = getInstallableUnits(profile);
assertFalse(ius.hasNext());
IProvisioningPlan plan = engine.createPlan(profile, null);
plan.addInstallableUnit(createOSGiIU());
plan.addInstallableUnit(createBadIU());
IStatus result = engine.perform(plan, new NullProgressMonitor());
assertFalse(result.isOK());
ius = getInstallableUnits(profile);
assertFalse(ius.hasNext());
}
// removing validate from engine api
// public void testValidateMissingAction() {
//
// Map properties = new HashMap();
// properties.put(IProfile.PROP_INSTALL_FOLDER, testProvisioning.getAbsolutePath());
// IProfile profile = createProfile("testPerformRollback", properties);
// PhaseSet phaseSet = new PhaseSetFactory();
//
// Iterator ius = getInstallableUnits(profile);
// assertFalse(ius.hasNext());
//
// InstallableUnitOperand[] operands = new InstallableUnitOperand[] {new InstallableUnitOperand(null, createOSGiIU()), new InstallableUnitOperand(null, createMissingActionIU())};
// IStatus result = ((Engine) engine).validate(profile, phaseSet, operands, null, new NullProgressMonitor());
// assertFalse(result.isOK());
//
// Throwable t = result.getException();
// assertTrue(t instanceof MissingActionsException);
// MissingActionsException e = (MissingActionsException) t;
// assertEquals("org.eclipse.equinox.p2.touchpoint.eclipse.thisactionismissing", e.getMissingActions()[0].getActionId());
// }
public void testPerformMissingAction() {
Map properties = new HashMap();
properties.put(IProfile.PROP_INSTALL_FOLDER, testProvisioning.getAbsolutePath());
IProfile profile = createProfile("testPerformMissingAction", properties);
Iterator ius = getInstallableUnits(profile);
assertFalse(ius.hasNext());
IProvisioningPlan plan = engine.createPlan(profile, null);
plan.addInstallableUnit(createOSGiIU());
plan.addInstallableUnit(createMissingActionIU());
IStatus result = engine.perform(plan, new NullProgressMonitor());
assertFalse(result.isOK());
ius = getInstallableUnits(profile);
assertFalse(ius.hasNext());
}
public void testPerformRollbackOnPhaseError() {
Map properties = new HashMap();
properties.put(IProfile.PROP_INSTALL_FOLDER, testProvisioning.getAbsolutePath());
IProfile profile = createProfile("testPerformRollbackOnError", properties);
NPEPhase phase = new NPEPhase();
PhaseSet phaseSet = new TestPhaseSet(phase);
Iterator ius = getInstallableUnits(profile);
assertFalse(ius.hasNext());
IProvisioningPlan plan = engine.createPlan(profile, null);
plan.addInstallableUnit(createOSGiIU());
IStatus result = engine.perform(plan, phaseSet, new NullProgressMonitor());
assertTrue(result.toString().contains("java.lang.NullPointerException"));
assertFalse(result.isOK());
ius = getInstallableUnits(profile);
assertFalse(ius.hasNext());
assertTrue(phase.isConsistent());
}
public void testPerformRollbackOnActionError() {
Map properties = new HashMap();
properties.put(IProfile.PROP_INSTALL_FOLDER, testProvisioning.getAbsolutePath());
IProfile profile = createProfile("testPerformRollbackOnError", properties);
ActionNPEPhase phase = new ActionNPEPhase();
PhaseSet phaseSet = new TestPhaseSet(phase);
Iterator ius = getInstallableUnits(profile);
assertFalse(ius.hasNext());
IProvisioningPlan plan = engine.createPlan(profile, null);
plan.addInstallableUnit(createOSGiIU());
IStatus result = engine.perform(plan, phaseSet, new NullProgressMonitor());
assertFalse(result.isOK());
ius = getInstallableUnits(profile);
assertFalse(ius.hasNext());
assertTrue(phase.isConsistent());
}
public void testPerformForcedPhaseWithActionError() {
Map properties = new HashMap();
properties.put(IProfile.PROP_INSTALL_FOLDER, testProvisioning.getAbsolutePath());
IProfile profile = createProfile("testPerformForceWithActionError", properties);
ActionNPEPhase phase = new ActionNPEPhase(true);
PhaseSet phaseSet = new TestPhaseSet(phase);
Iterator ius = getInstallableUnits(profile);
assertFalse(ius.hasNext());
IProvisioningPlan plan = engine.createPlan(profile, null);
plan.addInstallableUnit(createOSGiIU());
IStatus result = engine.perform(plan, phaseSet, new NullProgressMonitor());
// assertTrue(result.toString().contains("An error occurred during the org.eclipse.equinox.p2.tests.engine.EngineTest$ActionNPEPhase phase"));
assertTrue(result.isOK());
ius = getInstallableUnits(profile);
assertTrue(ius.hasNext());
assertTrue(phase.isConsistent());
}
public void testPerformForcedUninstallWithBadUninstallIUActionThrowsException() {
Map properties = new HashMap();
properties.put(IProfile.PROP_INSTALL_FOLDER, testProvisioning.getAbsolutePath());
IProfile profile = createProfile("testPerformForcedUninstallWithBadUninstallIUActionThrowsException", properties);
// forcedUninstall is false by default
IPhaseSet phaseSet = PhaseSetFactory.createDefaultPhaseSet();
Iterator ius = getInstallableUnits(profile);
assertFalse(ius.hasNext());
IProvisioningPlan plan = engine.createPlan(profile, null);
IInstallableUnit badUninstallIU = createBadUninstallIUThrowsException();
plan.addInstallableUnit(badUninstallIU);
IStatus result = engine.perform(plan, phaseSet, new NullProgressMonitor());
assertTrue(result.isOK());
ius = getInstallableUnits(profile);
assertTrue(ius.hasNext());
plan = engine.createPlan(profile, null);
plan.removeInstallableUnit(badUninstallIU);
result = engine.perform(plan, phaseSet, new NullProgressMonitor());
assertFalse(result.isOK());
ius = getInstallableUnits(profile);
assertTrue(ius.hasNext());
// this simulates a PhaseSetFactory with forcedUninstall set
phaseSet = new TestPhaseSet(true);
plan = engine.createPlan(profile, null);
plan.removeInstallableUnit(badUninstallIU);
result = engine.perform(plan, phaseSet, new NullProgressMonitor());
// assertTrue(result.toString().contains("An error occurred while uninstalling"));
assertTrue(result.isOK());
ius = getInstallableUnits(profile);
assertFalse(ius.hasNext());
}
public void testPerformForcedUninstallWithBadUninstallIUActionReturnsError() {
Map properties = new HashMap();
properties.put(IProfile.PROP_INSTALL_FOLDER, testProvisioning.getAbsolutePath());
IProfile profile = createProfile("testPerformForcedUninstallWithBadUninstallIUActionReturnsError", properties);
// forcedUninstall is false by default
Iterator ius = getInstallableUnits(profile);
assertFalse(ius.hasNext());
IProvisioningPlan plan = engine.createPlan(profile, null);
IInstallableUnit badUninstallIU = createBadUninstallIUReturnsError();
plan.addInstallableUnit(badUninstallIU);
IStatus result = engine.perform(plan, new NullProgressMonitor());
assertTrue(result.isOK());
ius = getInstallableUnits(profile);
assertTrue(ius.hasNext());
plan = engine.createPlan(profile, null);
plan.removeInstallableUnit(badUninstallIU);
result = engine.perform(plan, new NullProgressMonitor());
assertFalse(result.isOK());
ius = getInstallableUnits(profile);
assertTrue(ius.hasNext());
// this simulates a PhaseSetFactory with forcedUninstall set
IPhaseSet phaseSet = new TestPhaseSet(true);
plan = engine.createPlan(profile, null);
plan.removeInstallableUnit(badUninstallIU);
result = engine.perform(plan, phaseSet, new NullProgressMonitor());
assertTrue(result.isOK());
ius = getInstallableUnits(profile);
assertFalse(ius.hasNext());
}
public void testOrphanedIUProperty() {
IProfile profile = createProfile("testOrphanedIUProperty");
IInstallableUnit iu = createIU("someIU");
IProvisioningPlan plan = engine.createPlan(profile, null);
plan.setInstallableUnitProfileProperty(iu, "key", "value");
IStatus result = engine.perform(plan, new NullProgressMonitor());
assertTrue(result.isOK());
assertFalse(profile.getInstallableUnitProperties(iu).containsKey("key"));
plan = engine.createPlan(profile, null);
plan.addInstallableUnit(iu);
plan.setInstallableUnitProfileProperty(iu, "adifferentkey", "value");
result = engine.perform(plan, new NullProgressMonitor());
assertTrue(result.isOK());
assertTrue(profile.getInstallableUnitProperties(iu).containsKey("adifferentkey"));
assertFalse(profile.getInstallableUnitProperties(iu).containsKey("key"));
}
private IInstallableUnit createOSGiIU() {
return createOSGiIU("3.3.1.R33x_v20070828");
}
private IInstallableUnit createOSGiIU(String version) {
MetadataFactory.InstallableUnitDescription description = new MetadataFactory.InstallableUnitDescription();
description.setId("org.eclipse.osgi");
description.setVersion(Version.create(version));
description.setTouchpointType(AbstractProvisioningTest.TOUCHPOINT_OSGI);
Map touchpointData = new HashMap();
String manifest = "Manifest-Version: 1.0\r\n" + "Bundle-Activator: org.eclipse.osgi.framework.internal.core.SystemBundl\r\n" + " eActivator\r\n" + "Bundle-RequiredExecutionEnvironment: J2SE-1.4,OSGi/Minimum-1.0\r\n" + "Export-Package: org.eclipse.osgi.event;version=\"1.0\",org.eclipse.osgi.\r\n" + " framework.console;version=\"1.0\",org.eclipse.osgi.framework.eventmgr;v\r\n" + " ersion=\"1.0\",org.eclipse.osgi.framework.log;version=\"1.0\",org.eclipse\r\n" + " .osgi.service.datalocation;version=\"1.0\",org.eclipse.osgi.service.deb\r\n" + " ug;version=\"1.0\",org.eclipse.osgi.service.environment;version=\"1.0\",o\r\n" + " rg.eclipse.osgi.service.localization;version=\"1.0\",org.eclipse.osgi.s\r\n" + " ervice.pluginconversion;version=\"1.0\",org.eclipse.osgi.service.resolv\r\n"
+ " er;version=\"1.1\",org.eclipse.osgi.service.runnable;version=\"1.0\",org.\r\n" + " eclipse.osgi.service.urlconversion;version=\"1.0\",org.eclipse.osgi.sto\r\n" + " ragemanager;version=\"1.0\",org.eclipse.osgi.util;version=\"1.0\",org.osg\r\n" + " i.framework;version=\"1.3\",org.osgi.service.condpermadmin;version=\"1.0\r\n" + " \",org.osgi.service.packageadmin;version=\"1.2\",org.osgi.service.permis\r\n" + " sionadmin;version=\"1.2\",org.osgi.service.startlevel;version=\"1.0\",org\r\n" + " .osgi.service.url;version=\"1.0\",org.osgi.util.tracker;version=\"1.3.2\"\r\n" + " ,org.eclipse.core.runtime.adaptor;x-friends:=\"org.eclipse.core.runtim\r\n" + " e\",org.eclipse.core.runtime.internal.adaptor;x-internal:=true,org.ecl\r\n"
+ " ipse.core.runtime.internal.stats;x-friends:=\"org.eclipse.core.runtime\r\n" + " \",org.eclipse.osgi.baseadaptor;x-internal:=true,org.eclipse.osgi.base\r\n" + " adaptor.bundlefile;x-internal:=true,org.eclipse.osgi.baseadaptor.hook\r\n" + " s;x-internal:=true,org.eclipse.osgi.baseadaptor.loader;x-internal:=tr\r\n" + " ue,org.eclipse.osgi.framework.adaptor;x-internal:=true,org.eclipse.os\r\n" + " gi.framework.debug;x-internal:=true,org.eclipse.osgi.framework.intern\r\n" + " al.core;x-internal:=true,org.eclipse.osgi.framework.internal.protocol\r\n" + " ;x-internal:=true,org.eclipse.osgi.framework.internal.protocol.bundle\r\n" + " entry;x-internal:=true,org.eclipse.osgi.framework.internal.protocol.b\r\n"
+ " undleresource;x-internal:=true,org.eclipse.osgi.framework.internal.pr\r\n" + " otocol.reference;x-internal:=true,org.eclipse.osgi.framework.internal\r\n" + " .reliablefile;x-internal:=true,org.eclipse.osgi.framework.launcher;x-\r\n" + " internal:=true,org.eclipse.osgi.framework.util;x-internal:=true,org.e\r\n" + " clipse.osgi.internal.baseadaptor;x-internal:=true,org.eclipse.osgi.in\r\n" + " ternal.module;x-internal:=true,org.eclipse.osgi.internal.profile;x-in\r\n" + " ternal:=true,org.eclipse.osgi.internal.resolver;x-internal:=true,org.\r\n" + " eclipse.osgi.internal.verifier;x-internal:=true,org.eclipse.osgi.inte\r\n" + " rnal.provisional.verifier;x-friends:=\"org.eclipse.update.core,org.ecl\r\n" + " ipse.ui.workbench\"\r\n" + "Bundle-Version: 3.3.0.v20060925\r\n"
+ "Eclipse-SystemBundle: true\r\n" + "Bundle-Copyright: %copyright\r\n" + "Bundle-Name: %systemBundle\r\n" + "Bundle-Description: %systemBundle\r\n" + "Bundle-DocUrl: http://www.eclipse.org\r\n" + "Bundle-ManifestVersion: 2\r\n" + "Export-Service: org.osgi.service.packageadmin.PackageAdmin,org.osgi.se\r\n" + " rvice.permissionadmin.PermissionAdmin,org.osgi.service.startlevel.Sta\r\n" + " rtLevel,org.eclipse.osgi.service.debug.DebugOptions\r\n" + "Bundle-Vendor: %eclipse.org\r\n" + "Main-Class: org.eclipse.core.runtime.adaptor.EclipseStarter\r\n" + "Bundle-SymbolicName: org.eclipse.osgi; singleton:=true\r\n" + "Bundle-Localization: systembundle\r\n" + "Eclipse-ExtensibleAPI: true\r\n" + "\r\n" + "";
touchpointData.put("manifest", manifest);
//touchpointData.put("install", "installBundle(bundle:${artifact});");
//touchpointData.put("uninstall", "uninstallBundle(bundle:${artifact});");
IInstallableUnitFragment[] cus = new IInstallableUnitFragment[1];
InstallableUnitFragmentDescription desc = new InstallableUnitFragmentDescription();
desc.addTouchpointData(MetadataFactory.createTouchpointData(touchpointData));
IInstallableUnitFragment fragment = MetadataFactory.createInstallableUnitFragment(desc);
cus[0] = fragment;
//IArtifactKey key = new ArtifactKey("eclipse", "plugin", "org.eclipse.osgi", Version.create("3.3.1.R33x_v20070828"));
//iu.setArtifacts(new IArtifactKey[] {key});
IInstallableUnit iu = MetadataFactory.createInstallableUnit(description);
return MetadataFactory.createResolvedInstallableUnit(iu, cus);
}
private IInstallableUnit createBadIU() {
InstallableUnitDescription description = new MetadataFactory.InstallableUnitDescription();
description.setId("org.eclipse.osgi.bad");
description.setVersion(Version.create("3.3.1.R33x_v20070828"));
description.setTouchpointType(AbstractProvisioningTest.TOUCHPOINT_OSGI);
Map touchpointData = new HashMap();
String manifest = "Manifest-Version: 1.0\r\n" + "Bundle-Activator: org.eclipse.osgi.framework.internal.core.SystemBundl\r\n" + " eActivator\r\n" + "Bundle-RequiredExecutionEnvironment: J2SE-1.4,OSGi/Minimum-1.0\r\n" + "Export-Package: org.eclipse.osgi.event;version=\"1.0\",org.eclipse.osgi.\r\n" + " framework.console;version=\"1.0\",org.eclipse.osgi.framework.eventmgr;v\r\n" + " ersion=\"1.0\",org.eclipse.osgi.framework.log;version=\"1.0\",org.eclipse\r\n" + " .osgi.service.datalocation;version=\"1.0\",org.eclipse.osgi.service.deb\r\n" + " ug;version=\"1.0\",org.eclipse.osgi.service.environment;version=\"1.0\",o\r\n" + " rg.eclipse.osgi.service.localization;version=\"1.0\",org.eclipse.osgi.s\r\n" + " ervice.pluginconversion;version=\"1.0\",org.eclipse.osgi.service.resolv\r\n"
+ " er;version=\"1.1\",org.eclipse.osgi.service.runnable;version=\"1.0\",org.\r\n" + " eclipse.osgi.service.urlconversion;version=\"1.0\",org.eclipse.osgi.sto\r\n" + " ragemanager;version=\"1.0\",org.eclipse.osgi.util;version=\"1.0\",org.osg\r\n" + " i.framework;version=\"1.3\",org.osgi.service.condpermadmin;version=\"1.0\r\n" + " \",org.osgi.service.packageadmin;version=\"1.2\",org.osgi.service.permis\r\n" + " sionadmin;version=\"1.2\",org.osgi.service.startlevel;version=\"1.0\",org\r\n" + " .osgi.service.url;version=\"1.0\",org.osgi.util.tracker;version=\"1.3.2\"\r\n" + " ,org.eclipse.core.runtime.adaptor;x-friends:=\"org.eclipse.core.runtim\r\n" + " e\",org.eclipse.core.runtime.internal.adaptor;x-internal:=true,org.ecl\r\n"
+ " ipse.core.runtime.internal.stats;x-friends:=\"org.eclipse.core.runtime\r\n" + " \",org.eclipse.osgi.baseadaptor;x-internal:=true,org.eclipse.osgi.base\r\n" + " adaptor.bundlefile;x-internal:=true,org.eclipse.osgi.baseadaptor.hook\r\n" + " s;x-internal:=true,org.eclipse.osgi.baseadaptor.loader;x-internal:=tr\r\n" + " ue,org.eclipse.osgi.framework.adaptor;x-internal:=true,org.eclipse.os\r\n" + " gi.framework.debug;x-internal:=true,org.eclipse.osgi.framework.intern\r\n" + " al.core;x-internal:=true,org.eclipse.osgi.framework.internal.protocol\r\n" + " ;x-internal:=true,org.eclipse.osgi.framework.internal.protocol.bundle\r\n" + " entry;x-internal:=true,org.eclipse.osgi.framework.internal.protocol.b\r\n"
+ " undleresource;x-internal:=true,org.eclipse.osgi.framework.internal.pr\r\n" + " otocol.reference;x-internal:=true,org.eclipse.osgi.framework.internal\r\n" + " .reliablefile;x-internal:=true,org.eclipse.osgi.framework.launcher;x-\r\n" + " internal:=true,org.eclipse.osgi.framework.util;x-internal:=true,org.e\r\n" + " clipse.osgi.internal.baseadaptor;x-internal:=true,org.eclipse.osgi.in\r\n" + " ternal.module;x-internal:=true,org.eclipse.osgi.internal.profile;x-in\r\n" + " ternal:=true,org.eclipse.osgi.internal.resolver;x-internal:=true,org.\r\n" + " eclipse.osgi.internal.verifier;x-internal:=true,org.eclipse.osgi.inte\r\n" + " rnal.provisional.verifier;x-friends:=\"org.eclipse.update.core,org.ecl\r\n" + " ipse.ui.workbench\"\r\n" + "Bundle-Version: 3.3.0.v20060925\r\n"
+ "Eclipse-SystemBundle: true\r\n" + "Bundle-Copyright: %copyright\r\n" + "Bundle-Name: %systemBundle\r\n" + "Bundle-Description: %systemBundle\r\n" + "Bundle-DocUrl: http://www.eclipse.org\r\n" + "Bundle-ManifestVersion: 2\r\n" + "Export-Service: org.osgi.service.packageadmin.PackageAdmin,org.osgi.se\r\n" + " rvice.permissionadmin.PermissionAdmin,org.osgi.service.startlevel.Sta\r\n" + " rtLevel,org.eclipse.osgi.service.debug.DebugOptions\r\n" + "Bundle-Vendor: %eclipse.org\r\n" + "Main-Class: org.eclipse.core.runtime.adaptor.EclipseStarter\r\n" + "Bundle-SymbolicName: org.eclipse.osgi; singleton:=true\r\n" + "Bundle-Localization: systembundle\r\n" + "Eclipse-ExtensibleAPI: true\r\n" + "\r\n" + "";
touchpointData.put("manifest", manifest);
touchpointData.put("install", "BAD");
IInstallableUnitFragment[] cus = new IInstallableUnitFragment[1];
InstallableUnitFragmentDescription desc = new InstallableUnitFragmentDescription();
desc.addTouchpointData(MetadataFactory.createTouchpointData(touchpointData));
cus[0] = MetadataFactory.createInstallableUnitFragment(desc);
//IArtifactKey key = new ArtifactKey("eclipse", "plugin", "org.eclipse.osgi", Version.create("3.3.1.R33x_v20070828"));
//iu.setArtifacts(new IArtifactKey[] {key});
IInstallableUnit iu = MetadataFactory.createInstallableUnit(description);
return MetadataFactory.createResolvedInstallableUnit(iu, cus);
}
private IInstallableUnit createBadUninstallIUReturnsError() {
InstallableUnitDescription description = new MetadataFactory.InstallableUnitDescription();
description.setId("org.eclipse.osgi.bad");
description.setVersion(Version.create("3.3.1.R33x_v20070828"));
description.setTouchpointType(AbstractProvisioningTest.TOUCHPOINT_OSGI);
Map touchpointData = new HashMap();
String manifest = "Manifest-Version: 1.0\r\n" + "Bundle-Activator: org.eclipse.osgi.framework.internal.core.SystemBundl\r\n" + " eActivator\r\n" + "Bundle-RequiredExecutionEnvironment: J2SE-1.4,OSGi/Minimum-1.0\r\n" + "Export-Package: org.eclipse.osgi.event;version=\"1.0\",org.eclipse.osgi.\r\n" + " framework.console;version=\"1.0\",org.eclipse.osgi.framework.eventmgr;v\r\n" + " ersion=\"1.0\",org.eclipse.osgi.framework.log;version=\"1.0\",org.eclipse\r\n" + " .osgi.service.datalocation;version=\"1.0\",org.eclipse.osgi.service.deb\r\n" + " ug;version=\"1.0\",org.eclipse.osgi.service.environment;version=\"1.0\",o\r\n" + " rg.eclipse.osgi.service.localization;version=\"1.0\",org.eclipse.osgi.s\r\n" + " ervice.pluginconversion;version=\"1.0\",org.eclipse.osgi.service.resolv\r\n"
+ " er;version=\"1.1\",org.eclipse.osgi.service.runnable;version=\"1.0\",org.\r\n" + " eclipse.osgi.service.urlconversion;version=\"1.0\",org.eclipse.osgi.sto\r\n" + " ragemanager;version=\"1.0\",org.eclipse.osgi.util;version=\"1.0\",org.osg\r\n" + " i.framework;version=\"1.3\",org.osgi.service.condpermadmin;version=\"1.0\r\n" + " \",org.osgi.service.packageadmin;version=\"1.2\",org.osgi.service.permis\r\n" + " sionadmin;version=\"1.2\",org.osgi.service.startlevel;version=\"1.0\",org\r\n" + " .osgi.service.url;version=\"1.0\",org.osgi.util.tracker;version=\"1.3.2\"\r\n" + " ,org.eclipse.core.runtime.adaptor;x-friends:=\"org.eclipse.core.runtim\r\n" + " e\",org.eclipse.core.runtime.internal.adaptor;x-internal:=true,org.ecl\r\n"
+ " ipse.core.runtime.internal.stats;x-friends:=\"org.eclipse.core.runtime\r\n" + " \",org.eclipse.osgi.baseadaptor;x-internal:=true,org.eclipse.osgi.base\r\n" + " adaptor.bundlefile;x-internal:=true,org.eclipse.osgi.baseadaptor.hook\r\n" + " s;x-internal:=true,org.eclipse.osgi.baseadaptor.loader;x-internal:=tr\r\n" + " ue,org.eclipse.osgi.framework.adaptor;x-internal:=true,org.eclipse.os\r\n" + " gi.framework.debug;x-internal:=true,org.eclipse.osgi.framework.intern\r\n" + " al.core;x-internal:=true,org.eclipse.osgi.framework.internal.protocol\r\n" + " ;x-internal:=true,org.eclipse.osgi.framework.internal.protocol.bundle\r\n" + " entry;x-internal:=true,org.eclipse.osgi.framework.internal.protocol.b\r\n"
+ " undleresource;x-internal:=true,org.eclipse.osgi.framework.internal.pr\r\n" + " otocol.reference;x-internal:=true,org.eclipse.osgi.framework.internal\r\n" + " .reliablefile;x-internal:=true,org.eclipse.osgi.framework.launcher;x-\r\n" + " internal:=true,org.eclipse.osgi.framework.util;x-internal:=true,org.e\r\n" + " clipse.osgi.internal.baseadaptor;x-internal:=true,org.eclipse.osgi.in\r\n" + " ternal.module;x-internal:=true,org.eclipse.osgi.internal.profile;x-in\r\n" + " ternal:=true,org.eclipse.osgi.internal.resolver;x-internal:=true,org.\r\n" + " eclipse.osgi.internal.verifier;x-internal:=true,org.eclipse.osgi.inte\r\n" + " rnal.provisional.verifier;x-friends:=\"org.eclipse.update.core,org.ecl\r\n" + " ipse.ui.workbench\"\r\n" + "Bundle-Version: 3.3.0.v20060925\r\n"
+ "Eclipse-SystemBundle: true\r\n" + "Bundle-Copyright: %copyright\r\n" + "Bundle-Name: %systemBundle\r\n" + "Bundle-Description: %systemBundle\r\n" + "Bundle-DocUrl: http://www.eclipse.org\r\n" + "Bundle-ManifestVersion: 2\r\n" + "Export-Service: org.osgi.service.packageadmin.PackageAdmin,org.osgi.se\r\n" + " rvice.permissionadmin.PermissionAdmin,org.osgi.service.startlevel.Sta\r\n" + " rtLevel,org.eclipse.osgi.service.debug.DebugOptions\r\n" + "Bundle-Vendor: %eclipse.org\r\n" + "Main-Class: org.eclipse.core.runtime.adaptor.EclipseStarter\r\n" + "Bundle-SymbolicName: org.eclipse.osgi; singleton:=true\r\n" + "Bundle-Localization: systembundle\r\n" + "Eclipse-ExtensibleAPI: true\r\n" + "\r\n" + "";
touchpointData.put("manifest", manifest);
touchpointData.put("uninstall", "setProgramProperty(missing_mandatory_parameters:xyz)");
IInstallableUnitFragment[] cus = new IInstallableUnitFragment[1];
InstallableUnitFragmentDescription desc = new InstallableUnitFragmentDescription();
desc.addTouchpointData(MetadataFactory.createTouchpointData(touchpointData));
cus[0] = MetadataFactory.createInstallableUnitFragment(desc);
//IArtifactKey key = new ArtifactKey("eclipse", "plugin", "org.eclipse.osgi", Version.create("3.3.1.R33x_v20070828"));
//iu.setArtifacts(new IArtifactKey[] {key});
IInstallableUnit iu = MetadataFactory.createInstallableUnit(description);
return MetadataFactory.createResolvedInstallableUnit(iu, cus);
}
private IInstallableUnit createBadUninstallIUThrowsException() {
InstallableUnitDescription description = new MetadataFactory.InstallableUnitDescription();
description.setId("org.eclipse.osgi.bad");
description.setVersion(Version.create("3.3.1.R33x_v20070828"));
description.setTouchpointType(AbstractProvisioningTest.TOUCHPOINT_OSGI);
Map touchpointData = new HashMap();
String manifest = "Manifest-Version: 1.0\r\n" + "Bundle-Activator: org.eclipse.osgi.framework.internal.core.SystemBundl\r\n" + " eActivator\r\n" + "Bundle-RequiredExecutionEnvironment: J2SE-1.4,OSGi/Minimum-1.0\r\n" + "Export-Package: org.eclipse.osgi.event;version=\"1.0\",org.eclipse.osgi.\r\n" + " framework.console;version=\"1.0\",org.eclipse.osgi.framework.eventmgr;v\r\n" + " ersion=\"1.0\",org.eclipse.osgi.framework.log;version=\"1.0\",org.eclipse\r\n" + " .osgi.service.datalocation;version=\"1.0\",org.eclipse.osgi.service.deb\r\n" + " ug;version=\"1.0\",org.eclipse.osgi.service.environment;version=\"1.0\",o\r\n" + " rg.eclipse.osgi.service.localization;version=\"1.0\",org.eclipse.osgi.s\r\n" + " ervice.pluginconversion;version=\"1.0\",org.eclipse.osgi.service.resolv\r\n"
+ " er;version=\"1.1\",org.eclipse.osgi.service.runnable;version=\"1.0\",org.\r\n" + " eclipse.osgi.service.urlconversion;version=\"1.0\",org.eclipse.osgi.sto\r\n" + " ragemanager;version=\"1.0\",org.eclipse.osgi.util;version=\"1.0\",org.osg\r\n" + " i.framework;version=\"1.3\",org.osgi.service.condpermadmin;version=\"1.0\r\n" + " \",org.osgi.service.packageadmin;version=\"1.2\",org.osgi.service.permis\r\n" + " sionadmin;version=\"1.2\",org.osgi.service.startlevel;version=\"1.0\",org\r\n" + " .osgi.service.url;version=\"1.0\",org.osgi.util.tracker;version=\"1.3.2\"\r\n" + " ,org.eclipse.core.runtime.adaptor;x-friends:=\"org.eclipse.core.runtim\r\n" + " e\",org.eclipse.core.runtime.internal.adaptor;x-internal:=true,org.ecl\r\n"
+ " ipse.core.runtime.internal.stats;x-friends:=\"org.eclipse.core.runtime\r\n" + " \",org.eclipse.osgi.baseadaptor;x-internal:=true,org.eclipse.osgi.base\r\n" + " adaptor.bundlefile;x-internal:=true,org.eclipse.osgi.baseadaptor.hook\r\n" + " s;x-internal:=true,org.eclipse.osgi.baseadaptor.loader;x-internal:=tr\r\n" + " ue,org.eclipse.osgi.framework.adaptor;x-internal:=true,org.eclipse.os\r\n" + " gi.framework.debug;x-internal:=true,org.eclipse.osgi.framework.intern\r\n" + " al.core;x-internal:=true,org.eclipse.osgi.framework.internal.protocol\r\n" + " ;x-internal:=true,org.eclipse.osgi.framework.internal.protocol.bundle\r\n" + " entry;x-internal:=true,org.eclipse.osgi.framework.internal.protocol.b\r\n"
+ " undleresource;x-internal:=true,org.eclipse.osgi.framework.internal.pr\r\n" + " otocol.reference;x-internal:=true,org.eclipse.osgi.framework.internal\r\n" + " .reliablefile;x-internal:=true,org.eclipse.osgi.framework.launcher;x-\r\n" + " internal:=true,org.eclipse.osgi.framework.util;x-internal:=true,org.e\r\n" + " clipse.osgi.internal.baseadaptor;x-internal:=true,org.eclipse.osgi.in\r\n" + " ternal.module;x-internal:=true,org.eclipse.osgi.internal.profile;x-in\r\n" + " ternal:=true,org.eclipse.osgi.internal.resolver;x-internal:=true,org.\r\n" + " eclipse.osgi.internal.verifier;x-internal:=true,org.eclipse.osgi.inte\r\n" + " rnal.provisional.verifier;x-friends:=\"org.eclipse.update.core,org.ecl\r\n" + " ipse.ui.workbench\"\r\n" + "Bundle-Version: 3.3.0.v20060925\r\n"
+ "Eclipse-SystemBundle: true\r\n" + "Bundle-Copyright: %copyright\r\n" + "Bundle-Name: %systemBundle\r\n" + "Bundle-Description: %systemBundle\r\n" + "Bundle-DocUrl: http://www.eclipse.org\r\n" + "Bundle-ManifestVersion: 2\r\n" + "Export-Service: org.osgi.service.packageadmin.PackageAdmin,org.osgi.se\r\n" + " rvice.permissionadmin.PermissionAdmin,org.osgi.service.startlevel.Sta\r\n" + " rtLevel,org.eclipse.osgi.service.debug.DebugOptions\r\n" + "Bundle-Vendor: %eclipse.org\r\n" + "Main-Class: org.eclipse.core.runtime.adaptor.EclipseStarter\r\n" + "Bundle-SymbolicName: org.eclipse.osgi; singleton:=true\r\n" + "Bundle-Localization: systembundle\r\n" + "Eclipse-ExtensibleAPI: true\r\n" + "\r\n" + "";
touchpointData.put("manifest", manifest);
touchpointData.put("uninstall", "thisactionismissing()");
IInstallableUnitFragment[] cus = new IInstallableUnitFragment[1];
InstallableUnitFragmentDescription desc = new InstallableUnitFragmentDescription();
desc.addTouchpointData(MetadataFactory.createTouchpointData(touchpointData));
cus[0] = MetadataFactory.createInstallableUnitFragment(desc);
//IArtifactKey key = new ArtifactKey("eclipse", "plugin", "org.eclipse.osgi", Version.create("3.3.1.R33x_v20070828"));
//iu.setArtifacts(new IArtifactKey[] {key});
IInstallableUnit iu = MetadataFactory.createInstallableUnit(description);
return MetadataFactory.createResolvedInstallableUnit(iu, cus);
}
private IInstallableUnit createMissingActionIU() {
InstallableUnitDescription description = new MetadataFactory.InstallableUnitDescription();
description.setId("org.eclipse.osgi.bad");
description.setVersion(Version.create("3.3.1.R33x_v20070828"));
description.setTouchpointType(AbstractProvisioningTest.TOUCHPOINT_OSGI);
Map touchpointData = new HashMap();
String manifest = "Manifest-Version: 1.0\r\n" + "Bundle-Activator: org.eclipse.osgi.framework.internal.core.SystemBundl\r\n" + " eActivator\r\n" + "Bundle-RequiredExecutionEnvironment: J2SE-1.4,OSGi/Minimum-1.0\r\n" + "Export-Package: org.eclipse.osgi.event;version=\"1.0\",org.eclipse.osgi.\r\n" + " framework.console;version=\"1.0\",org.eclipse.osgi.framework.eventmgr;v\r\n" + " ersion=\"1.0\",org.eclipse.osgi.framework.log;version=\"1.0\",org.eclipse\r\n" + " .osgi.service.datalocation;version=\"1.0\",org.eclipse.osgi.service.deb\r\n" + " ug;version=\"1.0\",org.eclipse.osgi.service.environment;version=\"1.0\",o\r\n" + " rg.eclipse.osgi.service.localization;version=\"1.0\",org.eclipse.osgi.s\r\n" + " ervice.pluginconversion;version=\"1.0\",org.eclipse.osgi.service.resolv\r\n"
+ " er;version=\"1.1\",org.eclipse.osgi.service.runnable;version=\"1.0\",org.\r\n" + " eclipse.osgi.service.urlconversion;version=\"1.0\",org.eclipse.osgi.sto\r\n" + " ragemanager;version=\"1.0\",org.eclipse.osgi.util;version=\"1.0\",org.osg\r\n" + " i.framework;version=\"1.3\",org.osgi.service.condpermadmin;version=\"1.0\r\n" + " \",org.osgi.service.packageadmin;version=\"1.2\",org.osgi.service.permis\r\n" + " sionadmin;version=\"1.2\",org.osgi.service.startlevel;version=\"1.0\",org\r\n" + " .osgi.service.url;version=\"1.0\",org.osgi.util.tracker;version=\"1.3.2\"\r\n" + " ,org.eclipse.core.runtime.adaptor;x-friends:=\"org.eclipse.core.runtim\r\n" + " e\",org.eclipse.core.runtime.internal.adaptor;x-internal:=true,org.ecl\r\n"
+ " ipse.core.runtime.internal.stats;x-friends:=\"org.eclipse.core.runtime\r\n" + " \",org.eclipse.osgi.baseadaptor;x-internal:=true,org.eclipse.osgi.base\r\n" + " adaptor.bundlefile;x-internal:=true,org.eclipse.osgi.baseadaptor.hook\r\n" + " s;x-internal:=true,org.eclipse.osgi.baseadaptor.loader;x-internal:=tr\r\n" + " ue,org.eclipse.osgi.framework.adaptor;x-internal:=true,org.eclipse.os\r\n" + " gi.framework.debug;x-internal:=true,org.eclipse.osgi.framework.intern\r\n" + " al.core;x-internal:=true,org.eclipse.osgi.framework.internal.protocol\r\n" + " ;x-internal:=true,org.eclipse.osgi.framework.internal.protocol.bundle\r\n" + " entry;x-internal:=true,org.eclipse.osgi.framework.internal.protocol.b\r\n"
+ " undleresource;x-internal:=true,org.eclipse.osgi.framework.internal.pr\r\n" + " otocol.reference;x-internal:=true,org.eclipse.osgi.framework.internal\r\n" + " .reliablefile;x-internal:=true,org.eclipse.osgi.framework.launcher;x-\r\n" + " internal:=true,org.eclipse.osgi.framework.util;x-internal:=true,org.e\r\n" + " clipse.osgi.internal.baseadaptor;x-internal:=true,org.eclipse.osgi.in\r\n" + " ternal.module;x-internal:=true,org.eclipse.osgi.internal.profile;x-in\r\n" + " ternal:=true,org.eclipse.osgi.internal.resolver;x-internal:=true,org.\r\n" + " eclipse.osgi.internal.verifier;x-internal:=true,org.eclipse.osgi.inte\r\n" + " rnal.provisional.verifier;x-friends:=\"org.eclipse.update.core,org.ecl\r\n" + " ipse.ui.workbench\"\r\n" + "Bundle-Version: 3.3.0.v20060925\r\n"
+ "Eclipse-SystemBundle: true\r\n" + "Bundle-Copyright: %copyright\r\n" + "Bundle-Name: %systemBundle\r\n" + "Bundle-Description: %systemBundle\r\n" + "Bundle-DocUrl: http://www.eclipse.org\r\n" + "Bundle-ManifestVersion: 2\r\n" + "Export-Service: org.osgi.service.packageadmin.PackageAdmin,org.osgi.se\r\n" + " rvice.permissionadmin.PermissionAdmin,org.osgi.service.startlevel.Sta\r\n" + " rtLevel,org.eclipse.osgi.service.debug.DebugOptions\r\n" + "Bundle-Vendor: %eclipse.org\r\n" + "Main-Class: org.eclipse.core.runtime.adaptor.EclipseStarter\r\n" + "Bundle-SymbolicName: org.eclipse.osgi; singleton:=true\r\n" + "Bundle-Localization: systembundle\r\n" + "Eclipse-ExtensibleAPI: true\r\n" + "\r\n" + "";
touchpointData.put("manifest", manifest);
touchpointData.put("install", "thisactionismissing()");
IInstallableUnitFragment[] cus = new IInstallableUnitFragment[1];
InstallableUnitFragmentDescription desc = new InstallableUnitFragmentDescription();
desc.addTouchpointData(MetadataFactory.createTouchpointData(touchpointData));
cus[0] = MetadataFactory.createInstallableUnitFragment(desc);
//IArtifactKey key = new ArtifactKey("eclipse", "plugin", "org.eclipse.osgi", Version.create("3.3.1.R33x_v20070828"));
//iu.setArtifacts(new IArtifactKey[] {key});
IInstallableUnit iu = MetadataFactory.createInstallableUnit(description);
return MetadataFactory.createResolvedInstallableUnit(iu, cus);
}
public void testIncompatibleProfile() {
IProfile profile = new IProfile() {
public IQueryResult<IInstallableUnit> available(IQuery<IInstallableUnit> query, IProgressMonitor monitor) {
return new Collector<IInstallableUnit>();
}
public Map getInstallableUnitProperties(IInstallableUnit iu) {
return null;
}
public String getInstallableUnitProperty(IInstallableUnit iu, String key) {
return null;
}
public String getProfileId() {
return null;
}
public Map getProperties() {
return null;
}
public String getProperty(String key) {
return null;
}
public IProvisioningAgent getProvisioningAgent() {
return getAgent();
}
public long getTimestamp() {
return 0;
}
public IQueryResult<IInstallableUnit> query(IQuery<IInstallableUnit> query, IProgressMonitor monitor) {
return new Collector<IInstallableUnit>();
}
};
try {
- engine.perform(engine.createPlan(profile, null), new NullProgressMonitor());
+ IProvisioningPlan plan = engine.createPlan(profile, null);
+ plan.addInstallableUnit(createOSGiIU());
+ engine.perform(plan, new NullProgressMonitor());
} catch (IllegalArgumentException expected) {
return;
}
fail();
}
}
| true | true | public void testIncompatibleProfile() {
IProfile profile = new IProfile() {
public IQueryResult<IInstallableUnit> available(IQuery<IInstallableUnit> query, IProgressMonitor monitor) {
return new Collector<IInstallableUnit>();
}
public Map getInstallableUnitProperties(IInstallableUnit iu) {
return null;
}
public String getInstallableUnitProperty(IInstallableUnit iu, String key) {
return null;
}
public String getProfileId() {
return null;
}
public Map getProperties() {
return null;
}
public String getProperty(String key) {
return null;
}
public IProvisioningAgent getProvisioningAgent() {
return getAgent();
}
public long getTimestamp() {
return 0;
}
public IQueryResult<IInstallableUnit> query(IQuery<IInstallableUnit> query, IProgressMonitor monitor) {
return new Collector<IInstallableUnit>();
}
};
try {
engine.perform(engine.createPlan(profile, null), new NullProgressMonitor());
} catch (IllegalArgumentException expected) {
return;
}
fail();
}
| public void testIncompatibleProfile() {
IProfile profile = new IProfile() {
public IQueryResult<IInstallableUnit> available(IQuery<IInstallableUnit> query, IProgressMonitor monitor) {
return new Collector<IInstallableUnit>();
}
public Map getInstallableUnitProperties(IInstallableUnit iu) {
return null;
}
public String getInstallableUnitProperty(IInstallableUnit iu, String key) {
return null;
}
public String getProfileId() {
return null;
}
public Map getProperties() {
return null;
}
public String getProperty(String key) {
return null;
}
public IProvisioningAgent getProvisioningAgent() {
return getAgent();
}
public long getTimestamp() {
return 0;
}
public IQueryResult<IInstallableUnit> query(IQuery<IInstallableUnit> query, IProgressMonitor monitor) {
return new Collector<IInstallableUnit>();
}
};
try {
IProvisioningPlan plan = engine.createPlan(profile, null);
plan.addInstallableUnit(createOSGiIU());
engine.perform(plan, new NullProgressMonitor());
} catch (IllegalArgumentException expected) {
return;
}
fail();
}
|
diff --git a/src/de/fuberlin/projecta/src/main/java/analysis/SemanticAnalyzer.java b/src/de/fuberlin/projecta/src/main/java/analysis/SemanticAnalyzer.java
index 0884e4e8..8e2693a2 100644
--- a/src/de/fuberlin/projecta/src/main/java/analysis/SemanticAnalyzer.java
+++ b/src/de/fuberlin/projecta/src/main/java/analysis/SemanticAnalyzer.java
@@ -1,444 +1,439 @@
package analysis;
import lexer.TokenType;
import lombok.Getter;
import parser.ISyntaxTree;
import parser.ITree.DefaultAttribute;
import parser.NonTerminal;
import parser.Symbol.Reserved;
import analysis.ast.nodes.Args;
import analysis.ast.nodes.Array;
import analysis.ast.nodes.ArrayCall;
import analysis.ast.nodes.BasicType;
import analysis.ast.nodes.BinaryOp;
import analysis.ast.nodes.Block;
import analysis.ast.nodes.BoolLiteral;
import analysis.ast.nodes.Break;
import analysis.ast.nodes.Declaration;
import analysis.ast.nodes.Do;
import analysis.ast.nodes.FuncCall;
import analysis.ast.nodes.FuncDef;
import analysis.ast.nodes.Id;
import analysis.ast.nodes.If;
import analysis.ast.nodes.IfElse;
import analysis.ast.nodes.IntLiteral;
import analysis.ast.nodes.Params;
import analysis.ast.nodes.Print;
import analysis.ast.nodes.Program;
import analysis.ast.nodes.RealLiteral;
import analysis.ast.nodes.Record;
import analysis.ast.nodes.RecordVarCall;
import analysis.ast.nodes.Return;
import analysis.ast.nodes.Statement;
import analysis.ast.nodes.StringLiteral;
import analysis.ast.nodes.Type;
import analysis.ast.nodes.UnaryOp;
import analysis.ast.nodes.While;
public class SemanticAnalyzer {
private static final String lattribute = "lattribute";
private ISyntaxTree parseTree;
private SymbolTableStack tables;
@Getter
private ISyntaxTree AST;
public SemanticAnalyzer(ISyntaxTree tree) {
this.parseTree = tree;
tables = new SymbolTableStack();
}
public void analyze() throws SemanticException {
toAST(parseTree);
parseTreeForRemoval();
parseTreeForBuildingSymbolTable();
AST.printTree();
checkForValidity(AST);
}
public void toAST(ISyntaxTree tree) {
toAST(tree, null);
}
/**
* Traverses through the parseTree in depth-first-search and adds new nodes
* to the given insertNode. Only l-attributed nodes must be passed through
* node-attributes!
*
* The idea is that one node knows where it should get added to.
*
* @param tree
* current parseTree-node (with symbol)
* @param insertNode
* syntaxTree-Node, in which new nodes get added
*/
public void toAST(ISyntaxTree tree, ISyntaxTree insertNode) {
if (tree.getSymbol().isNonTerminal()) {
NonTerminal nonT = tree.getSymbol().asNonTerminal();
switch (nonT) {
case program:
AST = new Program();
toAST(tree.getChild(0), AST);
return;
case funcs:
for (int i = 0; i < tree.getChildrenCount(); i++) {
toAST(tree.getChild(i), insertNode);
}
return;
case func:
FuncDef func = new FuncDef();
for (int i = 0; i < tree.getChildrenCount(); i++) {
toAST(tree.getChild(i), func);
}
insertNode.addChild(func);
return;
case type:
if (tree.getChild(0).getSymbol().isNonTerminal()) {
if (tree.getChild(0).getSymbol().asNonTerminal() == NonTerminal.basic) {
if (tree.getChild(1).getChildrenCount() != 0) { // this
// is
// type_
// and
// it
// must
// exist!
Type array = new Array();
// the basic node gets added to this temporary node
// and is passed to the new array
ISyntaxTree tmp = new Program(); // it doesn't
// matter
// which node to
// take as long
// as
// it is a
// treenode.
toAST(tree.getChild(0), tmp);
array.addAttribute(lattribute);
boolean success = array.setAttribute(lattribute,
tmp.getChild(0)); // this is already the
// BasicType node
assert (success);
insertNode.addChild(array);
toAST(tree.getChild(1), array);
} else
// type_ is empty, hook the basic node in the parent
toAST(tree.getChild(0), insertNode);
}
} else { // we have a record! *CONGRATS*
Record record = new Record();
// test if we have an array of this record
if (tree.getChild(4).getChildrenCount() != 0) {
Type array = new Array();
toAST(tree.getChild(2), record); // <-- decls!!!
array.addAttribute(lattribute);
array.setAttribute(lattribute, record);
toAST(tree.getChild(4), array);
insertNode.addChild(array);
} else // this is simply one record
{
toAST(tree.getChild(2), record); // <-- decls!!!
insertNode.addChild(record);
}
}
return;
case type_:
// TODO: Width of array!!!
toAST(tree.getChild(1), insertNode);
if (tree.getChild(3).getChildrenCount() != 0) {
Array array = new Array();
array.addAttribute(lattribute);
array.setAttribute(lattribute,
insertNode.getAttribute(lattribute));
toAST(tree.getChild(3), array);
insertNode.addChild(array);
} else // array declaration stopped here...
{
insertNode.addChild((ISyntaxTree) insertNode
.getAttribute(lattribute));
}
return;
case optparams:
Params params = new Params();
for (int i = 0; i < tree.getChildrenCount(); i++) {
toAST(tree.getChild(i), params);
}
insertNode.addChild(params);
return;
case block:
Block block = new Block();
for (int i = 0; i < tree.getChildrenCount(); i++) {
toAST(tree.getChild(i), block);
}
if (block.getChildrenCount() != 0) {
insertNode.addChild(block);
} // else func_ -> ;
return;
case decl:
Declaration decl = new Declaration();
for (int i = 0; i < tree.getChildrenCount(); i++) {
toAST(tree.getChild(i), decl);
}
insertNode.addChild(decl);
return;
case stmt:
Statement stmt = null;
ISyntaxTree firstChild = tree.getChild(0);
if (firstChild.getSymbol().isTerminal()) {
if (firstChild.getSymbol().asTerminal() == TokenType.IF) {
ISyntaxTree stmt_ = tree.getChild(5); //
if (stmt_.getChildrenCount() == 0)
stmt = new If();
else
stmt = new IfElse();
} else if (firstChild.getSymbol().asTerminal() == TokenType.WHILE) {
stmt = new While();
} else if (firstChild.getSymbol().asTerminal() == TokenType.DO) {
stmt = new Do();
} else if (firstChild.getSymbol().asTerminal() == TokenType.BREAK) {
stmt = new Break();
} else if (firstChild.getSymbol().asTerminal() == TokenType.RETURN) {
stmt = new Return();
} else if (firstChild.getSymbol().asTerminal() == TokenType.PRINT) {
stmt = new Print();
}
} else if (firstChild.getSymbol().isNonTerminal()) {
- if (firstChild.getSymbol().asNonTerminal() == NonTerminal.block) {
- stmt = new Block();
- } else if (firstChild.getSymbol().asNonTerminal() == NonTerminal.assign) {
- // use the default case
- toAST(firstChild, insertNode);
- }
+ toAST(firstChild, insertNode);
}
if (stmt != null) {
for (int i = 0; i < tree.getChildrenCount(); i++) {
toAST(tree.getChild(i), stmt);
}
insertNode.addChild(stmt);
} else {
// throw new SemanticException(
// "stmt could'nt be set to any node in semantic analyzer");
}
return;
case assign:
case bool:
case join:
case equality:
case rel:
case expr:
case term:
if (tree.getChild(1).getChildrenCount() == 0) {
toAST(tree.getChild(0), insertNode);
} else {
BinaryOp bOp = new BinaryOp(tree.getChild(1).getChild(0)
.getSymbol().asTerminal());
if (bOp != null) {
// simply hang in both children trees
toAST(tree.getChild(0), bOp); // rel
toAST(tree.getChild(1), bOp); // equality'
insertNode.addChild(bOp);
}
}
return;
case unary:
if (tree.getChild(0).getSymbol().isNonTerminal()) {
toAST(tree.getChild(0), insertNode);
} else {
UnaryOp uOp = new UnaryOp(tree.getChild(0).getSymbol()
.asTerminal());
if (uOp != null) {
// simply hang in both children trees
toAST(tree.getChild(1), uOp); // unary
insertNode.addChild(uOp);
}
}
return;
case factor:
if (tree.getChild(0).getSymbol().isNonTerminal()) {
if (tree.getChild(1).getChildrenCount() == 0) {
toAST(tree.getChild(0), insertNode);
} else {
FuncCall call = new FuncCall();
for (ISyntaxTree tmp : tree.getChildren()) {
toAST(tmp, call);
}
insertNode.addChild(call);
}
} else {
for (ISyntaxTree tmp : tree.getChildren()) {
toAST(tmp, insertNode);
}
}
return;
case factor_:
if (tree.getChild(1).getChildrenCount() != 0) {
Args args = new Args();
toAST(tree.getChild(1), args);
insertNode.addChild(args);
}
return;
case loc:
if (tree.getChild(1).getChildrenCount() == 0) {
toAST(tree.getChild(0), insertNode);
} else {
ISyntaxTree tmp = new Program();
toAST(tree.getChild(0), tmp);
tree.getChild(1).addAttribute(lattribute);
// there is only one child (the id itself)!
tree.getChild(1).setAttribute(lattribute, tmp.getChild(0));
toAST(tree.getChild(1), insertNode);
}
return;
case loc__:
tree.getChild(0).addAttribute(lattribute);
tree.getChild(0).setAttribute(lattribute,
tree.getAttribute(lattribute));
if (tree.getChild(1).getChildrenCount() == 0) {
toAST(tree.getChild(0), insertNode);
} else {
ISyntaxTree tmp = new Program();
toAST(tree.getChild(0), tmp);
if (tmp.getChildrenCount() == 1) {
tree.getChild(1).addAttribute(lattribute);
tree.getChild(1).setAttribute(lattribute,
tmp.getChild(0));
toAST(tree.getChild(1), insertNode);
}
}
return;
case loc_:
// TODO: not everything is well thought atm...
if (tree.getChild(0).getSymbol().asTerminal() == TokenType.OP_DOT) {
RecordVarCall varCall = new RecordVarCall();
varCall.addChild((ISyntaxTree) tree
.getAttribute(lattribute));
toAST(tree.getChild(1), varCall);
insertNode.addChild(varCall);
} else {
ArrayCall array = new ArrayCall();
toAST(tree.getChild(1), array);
array.addChild((ISyntaxTree) tree.getAttribute(lattribute));
insertNode.addChild(array);
}
return;
// list of nodes which use the default case:
// assign_, basic, bool_, decls, equality_, expr_, factor_,
// func_, join_,
// params, params_, rel_, stmt_, stmt__, stmts,
default:
// nothing to do here just pass it through
for (ISyntaxTree tmp : tree.getChildren()) {
toAST(tmp, insertNode);
}
return;
}
} else if (tree.getSymbol().isTerminal()) {
TokenType t = tree.getSymbol().asTerminal();
switch (t) {
case BOOL_TYPE:
insertNode.addChild(new BasicType(TokenType.BOOL_TYPE));
return;
case INT_TYPE:
insertNode.addChild(new BasicType(TokenType.INT_TYPE));
return;
case REAL_TYPE:
insertNode.addChild(new BasicType(TokenType.REAL_TYPE));
return;
case STRING_TYPE:
insertNode.addChild(new BasicType(TokenType.STRING_TYPE));
return;
case INT_LITERAL:
insertNode.addChild(new IntLiteral((Integer) tree
.getAttribute(DefaultAttribute.TokenValue.name())));
return;
case STRING_LITERAL:
insertNode.addChild(new StringLiteral((String) tree
.getAttribute(DefaultAttribute.TokenValue.name())));
return;
case REAL_LITERAL:
insertNode.addChild(new RealLiteral((Double) tree
.getAttribute(DefaultAttribute.TokenValue.name())));
return;
case BOOL_LITERAL:
insertNode.addChild(new BoolLiteral((Boolean) tree
.getAttribute(DefaultAttribute.TokenValue.name())));
return;
case ID:
insertNode.addChild(new Id((String) tree
.getAttribute(DefaultAttribute.TokenValue.name())));
return;
default:// everything, which has no class member in its node uses
// the default.
return;
}
} else if (tree.getSymbol().isReservedTerminal()) {
Reserved res = tree.getSymbol().asReservedTerminal();
switch (res) {
case EPSILON:
if (tree.getChildrenCount() == 1) {
toAST(tree.getChild(0));
} else {
// this should never occur
throw new SemanticException(
"Epsilon in other position than head?");
}
case SP:
// this should never occur
// throw new SemanticException("Stack pointer in parsetree?");
}
}
}
/**
* Should find productions which are semantically nonsense. Like double
* assignment, funcCalls which aren't declared in this scope, assessing
* record members which aren't existing or where the record does not exist,
* ...
*
* @param tree
* @return
*/
private boolean checkForValidity(ISyntaxTree tree) {
return true;
}
/**
* Runs every nodes run method in depth-first-left-to-right order.
*
* @param tree
*/
private void parseTreeForBuildingSymbolTable() {
AST.buildSymbolTable(tables);
}
/**
* Checks whether the tree contains disallowed semantic.
*/
private void parseTreeForRemoval() {
// TODO: think about how to smartly encode disallowed trees
}
}
| true | true | public void toAST(ISyntaxTree tree, ISyntaxTree insertNode) {
if (tree.getSymbol().isNonTerminal()) {
NonTerminal nonT = tree.getSymbol().asNonTerminal();
switch (nonT) {
case program:
AST = new Program();
toAST(tree.getChild(0), AST);
return;
case funcs:
for (int i = 0; i < tree.getChildrenCount(); i++) {
toAST(tree.getChild(i), insertNode);
}
return;
case func:
FuncDef func = new FuncDef();
for (int i = 0; i < tree.getChildrenCount(); i++) {
toAST(tree.getChild(i), func);
}
insertNode.addChild(func);
return;
case type:
if (tree.getChild(0).getSymbol().isNonTerminal()) {
if (tree.getChild(0).getSymbol().asNonTerminal() == NonTerminal.basic) {
if (tree.getChild(1).getChildrenCount() != 0) { // this
// is
// type_
// and
// it
// must
// exist!
Type array = new Array();
// the basic node gets added to this temporary node
// and is passed to the new array
ISyntaxTree tmp = new Program(); // it doesn't
// matter
// which node to
// take as long
// as
// it is a
// treenode.
toAST(tree.getChild(0), tmp);
array.addAttribute(lattribute);
boolean success = array.setAttribute(lattribute,
tmp.getChild(0)); // this is already the
// BasicType node
assert (success);
insertNode.addChild(array);
toAST(tree.getChild(1), array);
} else
// type_ is empty, hook the basic node in the parent
toAST(tree.getChild(0), insertNode);
}
} else { // we have a record! *CONGRATS*
Record record = new Record();
// test if we have an array of this record
if (tree.getChild(4).getChildrenCount() != 0) {
Type array = new Array();
toAST(tree.getChild(2), record); // <-- decls!!!
array.addAttribute(lattribute);
array.setAttribute(lattribute, record);
toAST(tree.getChild(4), array);
insertNode.addChild(array);
} else // this is simply one record
{
toAST(tree.getChild(2), record); // <-- decls!!!
insertNode.addChild(record);
}
}
return;
case type_:
// TODO: Width of array!!!
toAST(tree.getChild(1), insertNode);
if (tree.getChild(3).getChildrenCount() != 0) {
Array array = new Array();
array.addAttribute(lattribute);
array.setAttribute(lattribute,
insertNode.getAttribute(lattribute));
toAST(tree.getChild(3), array);
insertNode.addChild(array);
} else // array declaration stopped here...
{
insertNode.addChild((ISyntaxTree) insertNode
.getAttribute(lattribute));
}
return;
case optparams:
Params params = new Params();
for (int i = 0; i < tree.getChildrenCount(); i++) {
toAST(tree.getChild(i), params);
}
insertNode.addChild(params);
return;
case block:
Block block = new Block();
for (int i = 0; i < tree.getChildrenCount(); i++) {
toAST(tree.getChild(i), block);
}
if (block.getChildrenCount() != 0) {
insertNode.addChild(block);
} // else func_ -> ;
return;
case decl:
Declaration decl = new Declaration();
for (int i = 0; i < tree.getChildrenCount(); i++) {
toAST(tree.getChild(i), decl);
}
insertNode.addChild(decl);
return;
case stmt:
Statement stmt = null;
ISyntaxTree firstChild = tree.getChild(0);
if (firstChild.getSymbol().isTerminal()) {
if (firstChild.getSymbol().asTerminal() == TokenType.IF) {
ISyntaxTree stmt_ = tree.getChild(5); //
if (stmt_.getChildrenCount() == 0)
stmt = new If();
else
stmt = new IfElse();
} else if (firstChild.getSymbol().asTerminal() == TokenType.WHILE) {
stmt = new While();
} else if (firstChild.getSymbol().asTerminal() == TokenType.DO) {
stmt = new Do();
} else if (firstChild.getSymbol().asTerminal() == TokenType.BREAK) {
stmt = new Break();
} else if (firstChild.getSymbol().asTerminal() == TokenType.RETURN) {
stmt = new Return();
} else if (firstChild.getSymbol().asTerminal() == TokenType.PRINT) {
stmt = new Print();
}
} else if (firstChild.getSymbol().isNonTerminal()) {
if (firstChild.getSymbol().asNonTerminal() == NonTerminal.block) {
stmt = new Block();
} else if (firstChild.getSymbol().asNonTerminal() == NonTerminal.assign) {
// use the default case
toAST(firstChild, insertNode);
}
}
if (stmt != null) {
for (int i = 0; i < tree.getChildrenCount(); i++) {
toAST(tree.getChild(i), stmt);
}
insertNode.addChild(stmt);
} else {
// throw new SemanticException(
// "stmt could'nt be set to any node in semantic analyzer");
}
return;
case assign:
case bool:
case join:
case equality:
case rel:
case expr:
case term:
if (tree.getChild(1).getChildrenCount() == 0) {
toAST(tree.getChild(0), insertNode);
} else {
BinaryOp bOp = new BinaryOp(tree.getChild(1).getChild(0)
.getSymbol().asTerminal());
if (bOp != null) {
// simply hang in both children trees
toAST(tree.getChild(0), bOp); // rel
toAST(tree.getChild(1), bOp); // equality'
insertNode.addChild(bOp);
}
}
return;
case unary:
if (tree.getChild(0).getSymbol().isNonTerminal()) {
toAST(tree.getChild(0), insertNode);
} else {
UnaryOp uOp = new UnaryOp(tree.getChild(0).getSymbol()
.asTerminal());
if (uOp != null) {
// simply hang in both children trees
toAST(tree.getChild(1), uOp); // unary
insertNode.addChild(uOp);
}
}
return;
case factor:
if (tree.getChild(0).getSymbol().isNonTerminal()) {
if (tree.getChild(1).getChildrenCount() == 0) {
toAST(tree.getChild(0), insertNode);
} else {
FuncCall call = new FuncCall();
for (ISyntaxTree tmp : tree.getChildren()) {
toAST(tmp, call);
}
insertNode.addChild(call);
}
} else {
for (ISyntaxTree tmp : tree.getChildren()) {
toAST(tmp, insertNode);
}
}
return;
case factor_:
if (tree.getChild(1).getChildrenCount() != 0) {
Args args = new Args();
toAST(tree.getChild(1), args);
insertNode.addChild(args);
}
return;
case loc:
if (tree.getChild(1).getChildrenCount() == 0) {
toAST(tree.getChild(0), insertNode);
} else {
ISyntaxTree tmp = new Program();
toAST(tree.getChild(0), tmp);
tree.getChild(1).addAttribute(lattribute);
// there is only one child (the id itself)!
tree.getChild(1).setAttribute(lattribute, tmp.getChild(0));
toAST(tree.getChild(1), insertNode);
}
return;
case loc__:
tree.getChild(0).addAttribute(lattribute);
tree.getChild(0).setAttribute(lattribute,
tree.getAttribute(lattribute));
if (tree.getChild(1).getChildrenCount() == 0) {
toAST(tree.getChild(0), insertNode);
} else {
ISyntaxTree tmp = new Program();
toAST(tree.getChild(0), tmp);
if (tmp.getChildrenCount() == 1) {
tree.getChild(1).addAttribute(lattribute);
tree.getChild(1).setAttribute(lattribute,
tmp.getChild(0));
toAST(tree.getChild(1), insertNode);
}
}
return;
case loc_:
// TODO: not everything is well thought atm...
if (tree.getChild(0).getSymbol().asTerminal() == TokenType.OP_DOT) {
RecordVarCall varCall = new RecordVarCall();
varCall.addChild((ISyntaxTree) tree
.getAttribute(lattribute));
toAST(tree.getChild(1), varCall);
insertNode.addChild(varCall);
} else {
ArrayCall array = new ArrayCall();
toAST(tree.getChild(1), array);
array.addChild((ISyntaxTree) tree.getAttribute(lattribute));
insertNode.addChild(array);
}
return;
// list of nodes which use the default case:
// assign_, basic, bool_, decls, equality_, expr_, factor_,
// func_, join_,
// params, params_, rel_, stmt_, stmt__, stmts,
default:
// nothing to do here just pass it through
for (ISyntaxTree tmp : tree.getChildren()) {
toAST(tmp, insertNode);
}
return;
}
} else if (tree.getSymbol().isTerminal()) {
TokenType t = tree.getSymbol().asTerminal();
switch (t) {
case BOOL_TYPE:
insertNode.addChild(new BasicType(TokenType.BOOL_TYPE));
return;
case INT_TYPE:
insertNode.addChild(new BasicType(TokenType.INT_TYPE));
return;
case REAL_TYPE:
insertNode.addChild(new BasicType(TokenType.REAL_TYPE));
return;
case STRING_TYPE:
insertNode.addChild(new BasicType(TokenType.STRING_TYPE));
return;
case INT_LITERAL:
insertNode.addChild(new IntLiteral((Integer) tree
.getAttribute(DefaultAttribute.TokenValue.name())));
return;
case STRING_LITERAL:
insertNode.addChild(new StringLiteral((String) tree
.getAttribute(DefaultAttribute.TokenValue.name())));
return;
case REAL_LITERAL:
insertNode.addChild(new RealLiteral((Double) tree
.getAttribute(DefaultAttribute.TokenValue.name())));
return;
case BOOL_LITERAL:
insertNode.addChild(new BoolLiteral((Boolean) tree
.getAttribute(DefaultAttribute.TokenValue.name())));
return;
case ID:
insertNode.addChild(new Id((String) tree
.getAttribute(DefaultAttribute.TokenValue.name())));
return;
default:// everything, which has no class member in its node uses
// the default.
return;
}
} else if (tree.getSymbol().isReservedTerminal()) {
Reserved res = tree.getSymbol().asReservedTerminal();
switch (res) {
case EPSILON:
if (tree.getChildrenCount() == 1) {
toAST(tree.getChild(0));
} else {
// this should never occur
throw new SemanticException(
"Epsilon in other position than head?");
}
case SP:
// this should never occur
// throw new SemanticException("Stack pointer in parsetree?");
}
}
}
| public void toAST(ISyntaxTree tree, ISyntaxTree insertNode) {
if (tree.getSymbol().isNonTerminal()) {
NonTerminal nonT = tree.getSymbol().asNonTerminal();
switch (nonT) {
case program:
AST = new Program();
toAST(tree.getChild(0), AST);
return;
case funcs:
for (int i = 0; i < tree.getChildrenCount(); i++) {
toAST(tree.getChild(i), insertNode);
}
return;
case func:
FuncDef func = new FuncDef();
for (int i = 0; i < tree.getChildrenCount(); i++) {
toAST(tree.getChild(i), func);
}
insertNode.addChild(func);
return;
case type:
if (tree.getChild(0).getSymbol().isNonTerminal()) {
if (tree.getChild(0).getSymbol().asNonTerminal() == NonTerminal.basic) {
if (tree.getChild(1).getChildrenCount() != 0) { // this
// is
// type_
// and
// it
// must
// exist!
Type array = new Array();
// the basic node gets added to this temporary node
// and is passed to the new array
ISyntaxTree tmp = new Program(); // it doesn't
// matter
// which node to
// take as long
// as
// it is a
// treenode.
toAST(tree.getChild(0), tmp);
array.addAttribute(lattribute);
boolean success = array.setAttribute(lattribute,
tmp.getChild(0)); // this is already the
// BasicType node
assert (success);
insertNode.addChild(array);
toAST(tree.getChild(1), array);
} else
// type_ is empty, hook the basic node in the parent
toAST(tree.getChild(0), insertNode);
}
} else { // we have a record! *CONGRATS*
Record record = new Record();
// test if we have an array of this record
if (tree.getChild(4).getChildrenCount() != 0) {
Type array = new Array();
toAST(tree.getChild(2), record); // <-- decls!!!
array.addAttribute(lattribute);
array.setAttribute(lattribute, record);
toAST(tree.getChild(4), array);
insertNode.addChild(array);
} else // this is simply one record
{
toAST(tree.getChild(2), record); // <-- decls!!!
insertNode.addChild(record);
}
}
return;
case type_:
// TODO: Width of array!!!
toAST(tree.getChild(1), insertNode);
if (tree.getChild(3).getChildrenCount() != 0) {
Array array = new Array();
array.addAttribute(lattribute);
array.setAttribute(lattribute,
insertNode.getAttribute(lattribute));
toAST(tree.getChild(3), array);
insertNode.addChild(array);
} else // array declaration stopped here...
{
insertNode.addChild((ISyntaxTree) insertNode
.getAttribute(lattribute));
}
return;
case optparams:
Params params = new Params();
for (int i = 0; i < tree.getChildrenCount(); i++) {
toAST(tree.getChild(i), params);
}
insertNode.addChild(params);
return;
case block:
Block block = new Block();
for (int i = 0; i < tree.getChildrenCount(); i++) {
toAST(tree.getChild(i), block);
}
if (block.getChildrenCount() != 0) {
insertNode.addChild(block);
} // else func_ -> ;
return;
case decl:
Declaration decl = new Declaration();
for (int i = 0; i < tree.getChildrenCount(); i++) {
toAST(tree.getChild(i), decl);
}
insertNode.addChild(decl);
return;
case stmt:
Statement stmt = null;
ISyntaxTree firstChild = tree.getChild(0);
if (firstChild.getSymbol().isTerminal()) {
if (firstChild.getSymbol().asTerminal() == TokenType.IF) {
ISyntaxTree stmt_ = tree.getChild(5); //
if (stmt_.getChildrenCount() == 0)
stmt = new If();
else
stmt = new IfElse();
} else if (firstChild.getSymbol().asTerminal() == TokenType.WHILE) {
stmt = new While();
} else if (firstChild.getSymbol().asTerminal() == TokenType.DO) {
stmt = new Do();
} else if (firstChild.getSymbol().asTerminal() == TokenType.BREAK) {
stmt = new Break();
} else if (firstChild.getSymbol().asTerminal() == TokenType.RETURN) {
stmt = new Return();
} else if (firstChild.getSymbol().asTerminal() == TokenType.PRINT) {
stmt = new Print();
}
} else if (firstChild.getSymbol().isNonTerminal()) {
toAST(firstChild, insertNode);
}
if (stmt != null) {
for (int i = 0; i < tree.getChildrenCount(); i++) {
toAST(tree.getChild(i), stmt);
}
insertNode.addChild(stmt);
} else {
// throw new SemanticException(
// "stmt could'nt be set to any node in semantic analyzer");
}
return;
case assign:
case bool:
case join:
case equality:
case rel:
case expr:
case term:
if (tree.getChild(1).getChildrenCount() == 0) {
toAST(tree.getChild(0), insertNode);
} else {
BinaryOp bOp = new BinaryOp(tree.getChild(1).getChild(0)
.getSymbol().asTerminal());
if (bOp != null) {
// simply hang in both children trees
toAST(tree.getChild(0), bOp); // rel
toAST(tree.getChild(1), bOp); // equality'
insertNode.addChild(bOp);
}
}
return;
case unary:
if (tree.getChild(0).getSymbol().isNonTerminal()) {
toAST(tree.getChild(0), insertNode);
} else {
UnaryOp uOp = new UnaryOp(tree.getChild(0).getSymbol()
.asTerminal());
if (uOp != null) {
// simply hang in both children trees
toAST(tree.getChild(1), uOp); // unary
insertNode.addChild(uOp);
}
}
return;
case factor:
if (tree.getChild(0).getSymbol().isNonTerminal()) {
if (tree.getChild(1).getChildrenCount() == 0) {
toAST(tree.getChild(0), insertNode);
} else {
FuncCall call = new FuncCall();
for (ISyntaxTree tmp : tree.getChildren()) {
toAST(tmp, call);
}
insertNode.addChild(call);
}
} else {
for (ISyntaxTree tmp : tree.getChildren()) {
toAST(tmp, insertNode);
}
}
return;
case factor_:
if (tree.getChild(1).getChildrenCount() != 0) {
Args args = new Args();
toAST(tree.getChild(1), args);
insertNode.addChild(args);
}
return;
case loc:
if (tree.getChild(1).getChildrenCount() == 0) {
toAST(tree.getChild(0), insertNode);
} else {
ISyntaxTree tmp = new Program();
toAST(tree.getChild(0), tmp);
tree.getChild(1).addAttribute(lattribute);
// there is only one child (the id itself)!
tree.getChild(1).setAttribute(lattribute, tmp.getChild(0));
toAST(tree.getChild(1), insertNode);
}
return;
case loc__:
tree.getChild(0).addAttribute(lattribute);
tree.getChild(0).setAttribute(lattribute,
tree.getAttribute(lattribute));
if (tree.getChild(1).getChildrenCount() == 0) {
toAST(tree.getChild(0), insertNode);
} else {
ISyntaxTree tmp = new Program();
toAST(tree.getChild(0), tmp);
if (tmp.getChildrenCount() == 1) {
tree.getChild(1).addAttribute(lattribute);
tree.getChild(1).setAttribute(lattribute,
tmp.getChild(0));
toAST(tree.getChild(1), insertNode);
}
}
return;
case loc_:
// TODO: not everything is well thought atm...
if (tree.getChild(0).getSymbol().asTerminal() == TokenType.OP_DOT) {
RecordVarCall varCall = new RecordVarCall();
varCall.addChild((ISyntaxTree) tree
.getAttribute(lattribute));
toAST(tree.getChild(1), varCall);
insertNode.addChild(varCall);
} else {
ArrayCall array = new ArrayCall();
toAST(tree.getChild(1), array);
array.addChild((ISyntaxTree) tree.getAttribute(lattribute));
insertNode.addChild(array);
}
return;
// list of nodes which use the default case:
// assign_, basic, bool_, decls, equality_, expr_, factor_,
// func_, join_,
// params, params_, rel_, stmt_, stmt__, stmts,
default:
// nothing to do here just pass it through
for (ISyntaxTree tmp : tree.getChildren()) {
toAST(tmp, insertNode);
}
return;
}
} else if (tree.getSymbol().isTerminal()) {
TokenType t = tree.getSymbol().asTerminal();
switch (t) {
case BOOL_TYPE:
insertNode.addChild(new BasicType(TokenType.BOOL_TYPE));
return;
case INT_TYPE:
insertNode.addChild(new BasicType(TokenType.INT_TYPE));
return;
case REAL_TYPE:
insertNode.addChild(new BasicType(TokenType.REAL_TYPE));
return;
case STRING_TYPE:
insertNode.addChild(new BasicType(TokenType.STRING_TYPE));
return;
case INT_LITERAL:
insertNode.addChild(new IntLiteral((Integer) tree
.getAttribute(DefaultAttribute.TokenValue.name())));
return;
case STRING_LITERAL:
insertNode.addChild(new StringLiteral((String) tree
.getAttribute(DefaultAttribute.TokenValue.name())));
return;
case REAL_LITERAL:
insertNode.addChild(new RealLiteral((Double) tree
.getAttribute(DefaultAttribute.TokenValue.name())));
return;
case BOOL_LITERAL:
insertNode.addChild(new BoolLiteral((Boolean) tree
.getAttribute(DefaultAttribute.TokenValue.name())));
return;
case ID:
insertNode.addChild(new Id((String) tree
.getAttribute(DefaultAttribute.TokenValue.name())));
return;
default:// everything, which has no class member in its node uses
// the default.
return;
}
} else if (tree.getSymbol().isReservedTerminal()) {
Reserved res = tree.getSymbol().asReservedTerminal();
switch (res) {
case EPSILON:
if (tree.getChildrenCount() == 1) {
toAST(tree.getChild(0));
} else {
// this should never occur
throw new SemanticException(
"Epsilon in other position than head?");
}
case SP:
// this should never occur
// throw new SemanticException("Stack pointer in parsetree?");
}
}
}
|
diff --git a/src/org/pentaho/di/ui/job/entries/hadoopjobexecutor/JobEntryHadoopJobExecutorDialog.java b/src/org/pentaho/di/ui/job/entries/hadoopjobexecutor/JobEntryHadoopJobExecutorDialog.java
index f9c961a9..9bfc491d 100644
--- a/src/org/pentaho/di/ui/job/entries/hadoopjobexecutor/JobEntryHadoopJobExecutorDialog.java
+++ b/src/org/pentaho/di/ui/job/entries/hadoopjobexecutor/JobEntryHadoopJobExecutorDialog.java
@@ -1,159 +1,164 @@
/*
* Copyright (c) 2011 Pentaho Corporation. All rights reserved.
* This software was developed by Pentaho Corporation and is provided under the terms
* of the GNU Lesser General Public License, Version 2.1. You may not use
* this file except in compliance with the license. If you need a copy of the license,
* please go to http://www.gnu.org/licenses/lgpl-2.1.txt. The Original Code is Pentaho
* Data Integration. The Initial Developer is Pentaho Corporation.
*
* Software distributed under the GNU Lesser Public License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to
* the license for the specific language governing your rights and limitations.
*/
package org.pentaho.di.ui.job.entries.hadoopjobexecutor;
import java.util.Enumeration;
import java.util.ResourceBundle;
import org.dom4j.DocumentException;
import org.eclipse.swt.widgets.Shell;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.job.JobMeta;
import org.pentaho.di.job.entries.hadoopjobexecutor.JobEntryHadoopJobExecutor;
import org.pentaho.di.job.entry.JobEntryDialogInterface;
import org.pentaho.di.job.entry.JobEntryInterface;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.ui.job.entries.hadoopjobexecutor.JobEntryHadoopJobExecutorController.AdvancedConfiguration;
import org.pentaho.di.ui.job.entries.hadoopjobexecutor.JobEntryHadoopJobExecutorController.SimpleConfiguration;
import org.pentaho.di.ui.job.entry.JobEntryDialog;
import org.pentaho.ui.xul.XulDomContainer;
import org.pentaho.ui.xul.XulException;
import org.pentaho.ui.xul.XulRunner;
import org.pentaho.ui.xul.binding.BindingConvertor;
import org.pentaho.ui.xul.binding.BindingFactory;
import org.pentaho.ui.xul.binding.DefaultBindingFactory;
import org.pentaho.ui.xul.binding.Binding.Type;
import org.pentaho.ui.xul.components.XulRadio;
import org.pentaho.ui.xul.components.XulTextbox;
import org.pentaho.ui.xul.containers.XulDialog;
import org.pentaho.ui.xul.containers.XulTree;
import org.pentaho.ui.xul.containers.XulVbox;
import org.pentaho.ui.xul.swt.SwtXulLoader;
import org.pentaho.ui.xul.swt.SwtXulRunner;
public class JobEntryHadoopJobExecutorDialog extends JobEntryDialog implements JobEntryDialogInterface {
private static final Class<?> CLZ = JobEntryHadoopJobExecutor.class;
private JobEntryHadoopJobExecutor jobEntry;
private JobEntryHadoopJobExecutorController controller = new JobEntryHadoopJobExecutorController();
private XulDomContainer container;
private BindingFactory bf;
private ResourceBundle bundle = new ResourceBundle() {
@Override
public Enumeration<String> getKeys() {
return null;
}
@Override
protected Object handleGetObject(String key) {
return BaseMessages.getString(CLZ, key);
}
};
public JobEntryHadoopJobExecutorDialog(Shell parent, JobEntryInterface jobEntry, Repository rep, JobMeta jobMeta) throws XulException, DocumentException {
super(parent, jobEntry, rep, jobMeta);
this.jobEntry = (JobEntryHadoopJobExecutor) jobEntry;
SwtXulLoader swtXulLoader = new SwtXulLoader();
swtXulLoader.registerClassLoader(getClass().getClassLoader());
swtXulLoader.setOuterContext(shell);
container = swtXulLoader.loadXul("org/pentaho/di/ui/job/entries/hadoopjobexecutor/JobEntryHadoopJobExecutorDialog.xul", bundle); //$NON-NLS-1$
final XulRunner runner = new SwtXulRunner();
runner.addContainer(container);
container.addEventHandler(controller);
bf = new DefaultBindingFactory();
bf.setDocument(container.getDocumentRoot());
bf.setBindingType(Type.BI_DIRECTIONAL);
bf.createBinding("jobentry-name", "value", controller, JobEntryHadoopJobExecutorController.JOB_ENTRY_NAME); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
bf.createBinding("hadoop-distribution", "selectedItem", controller.getAdvancedConfiguration(), JobEntryHadoopJobExecutorController.AdvancedConfiguration.HADOOP_DISTRIBUTION); //$NON-NLS-1$ //$NON-NLS-2$
bf.createBinding("jobentry-hadoopjob-name", "value", controller, JobEntryHadoopJobExecutorController.HADOOP_JOB_NAME); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
bf.createBinding("jar-url", "value", controller, JobEntryHadoopJobExecutorController.JAR_URL); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
bf.createBinding("command-line-arguments", "value", controller.getSimpleConfiguration(), SimpleConfiguration.CMD_LINE_ARGS); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
bf.createBinding("classes-output-key-class", "value", controller.getAdvancedConfiguration(), AdvancedConfiguration.OUTPUT_KEY_CLASS); //$NON-NLS-1$ //$NON-NLS-2$
bf.createBinding("classes-output-value-class", "value", controller.getAdvancedConfiguration(), AdvancedConfiguration.OUTPUT_VALUE_CLASS); //$NON-NLS-1$ //$NON-NLS-2$
bf.createBinding("classes-mapper-class", "value", controller.getAdvancedConfiguration(), AdvancedConfiguration.MAPPER_CLASS); //$NON-NLS-1$ //$NON-NLS-2$
bf.createBinding("classes-combiner-class", "value", controller.getAdvancedConfiguration(), AdvancedConfiguration.COMBINER_CLASS); //$NON-NLS-1$ //$NON-NLS-2$
bf.createBinding("classes-reducer-class", "value", controller.getAdvancedConfiguration(), AdvancedConfiguration.REDUCER_CLASS); //$NON-NLS-1$ //$NON-NLS-2$
bf.createBinding("classes-input-format", "value", controller.getAdvancedConfiguration(), AdvancedConfiguration.INPUT_FORMAT_CLASS); //$NON-NLS-1$ //$NON-NLS-2$
bf.createBinding("classes-output-format", "value", controller.getAdvancedConfiguration(), AdvancedConfiguration.OUTPUT_FORMAT_CLASS); //$NON-NLS-1$ //$NON-NLS-2$
final BindingConvertor<String, Integer> bindingConverter = new BindingConvertor<String, Integer>() {
public Integer sourceToTarget(String value) {
return Integer.parseInt(value);
}
public String targetToSource(Integer value) {
return value.toString();
}
};
bf.createBinding("num-map-tasks", "value", controller.getAdvancedConfiguration(), AdvancedConfiguration.NUM_MAP_TASKS, bindingConverter); //$NON-NLS-1$ //$NON-NLS-2$
bf.createBinding("num-reduce-tasks", "value", controller.getAdvancedConfiguration(), AdvancedConfiguration.NUM_REDUCE_TASKS, bindingConverter); //$NON-NLS-1$ //$NON-NLS-2$
bf.createBinding("blocking", "selected", controller.getAdvancedConfiguration(), AdvancedConfiguration.BLOCKING); //$NON-NLS-1$ //$NON-NLS-2$
bf.createBinding("logging-interval", "value", controller.getAdvancedConfiguration(), AdvancedConfiguration.LOGGING_INTERVAL, bindingConverter); //$NON-NLS-1$ //$NON-NLS-2$
bf.createBinding("input-path", "value", controller.getAdvancedConfiguration(), AdvancedConfiguration.INPUT_PATH); //$NON-NLS-1$ //$NON-NLS-2$
bf.createBinding("output-path", "value", controller.getAdvancedConfiguration(), AdvancedConfiguration.OUTPUT_PATH); //$NON-NLS-1$ //$NON-NLS-2$
bf.createBinding("hdfs-hostname", "value", controller.getAdvancedConfiguration(), AdvancedConfiguration.HDFS_HOSTNAME); //$NON-NLS-1$ //$NON-NLS-2$
bf.createBinding("hdfs-port", "value", controller.getAdvancedConfiguration(), AdvancedConfiguration.HDFS_PORT); //$NON-NLS-1$ //$NON-NLS-2$
bf.createBinding("job-tracker-hostname", "value", controller.getAdvancedConfiguration(), AdvancedConfiguration.JOB_TRACKER_HOSTNAME); //$NON-NLS-1$ //$NON-NLS-2$
bf.createBinding("job-tracker-port", "value", controller.getAdvancedConfiguration(), AdvancedConfiguration.JOB_TRACKER_PORT); //$NON-NLS-1$ //$NON-NLS-2$
bf.createBinding("working-dir", "value", controller.getAdvancedConfiguration(), AdvancedConfiguration.WORKING_DIRECTORY); //$NON-NLS-1$ //$NON-NLS-2$
((XulRadio) container.getDocumentRoot().getElementById("simpleRadioButton")).setSelected(this.jobEntry.isSimple()); //$NON-NLS-1$
((XulRadio) container.getDocumentRoot().getElementById("advancedRadioButton")).setSelected(!this.jobEntry.isSimple()); //$NON-NLS-1$
((XulVbox) container.getDocumentRoot().getElementById("advanced-configuration")).setVisible(!this.jobEntry.isSimple()); //$NON-NLS-1$
XulTextbox loggingInterval = (XulTextbox) container.getDocumentRoot().getElementById("logging-interval");
loggingInterval.setValue("" + controller.getAdvancedConfiguration().getLoggingInterval());
XulTextbox mapTasks = (XulTextbox) container.getDocumentRoot().getElementById("num-map-tasks");
mapTasks.setValue("" + controller.getAdvancedConfiguration().getNumMapTasks());
XulTextbox reduceTasks = (XulTextbox) container.getDocumentRoot().getElementById("num-reduce-tasks");
reduceTasks.setValue("" + controller.getAdvancedConfiguration().getNumReduceTasks());
XulTree variablesTree = (XulTree) container.getDocumentRoot().getElementById("fields-table"); //$NON-NLS-1$
bf.setBindingType(Type.ONE_WAY);
bf.createBinding(controller.getUserDefined(), "children", variablesTree, "elements"); //$NON-NLS-1$//$NON-NLS-2$
bf.setBindingType(Type.BI_DIRECTIONAL);
controller.setJobEntry((JobEntryHadoopJobExecutor) jobEntry);
- controller.init();
+ try {
+ // TODO Controller should not throw Throwable. Looks like we need to change HadoopConfigurerFactory to throw a more specific exception.
+ controller.init();
+ } catch (Throwable t) {
+ throw new XulException("Unable to initialize", t);
+ }
}
public JobEntryInterface open() {
XulDialog dialog = (XulDialog) container.getDocumentRoot().getElementById("job-entry-dialog"); //$NON-NLS-1$
dialog.show();
return jobEntry;
}
}
| true | true | public JobEntryHadoopJobExecutorDialog(Shell parent, JobEntryInterface jobEntry, Repository rep, JobMeta jobMeta) throws XulException, DocumentException {
super(parent, jobEntry, rep, jobMeta);
this.jobEntry = (JobEntryHadoopJobExecutor) jobEntry;
SwtXulLoader swtXulLoader = new SwtXulLoader();
swtXulLoader.registerClassLoader(getClass().getClassLoader());
swtXulLoader.setOuterContext(shell);
container = swtXulLoader.loadXul("org/pentaho/di/ui/job/entries/hadoopjobexecutor/JobEntryHadoopJobExecutorDialog.xul", bundle); //$NON-NLS-1$
final XulRunner runner = new SwtXulRunner();
runner.addContainer(container);
container.addEventHandler(controller);
bf = new DefaultBindingFactory();
bf.setDocument(container.getDocumentRoot());
bf.setBindingType(Type.BI_DIRECTIONAL);
bf.createBinding("jobentry-name", "value", controller, JobEntryHadoopJobExecutorController.JOB_ENTRY_NAME); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
bf.createBinding("hadoop-distribution", "selectedItem", controller.getAdvancedConfiguration(), JobEntryHadoopJobExecutorController.AdvancedConfiguration.HADOOP_DISTRIBUTION); //$NON-NLS-1$ //$NON-NLS-2$
bf.createBinding("jobentry-hadoopjob-name", "value", controller, JobEntryHadoopJobExecutorController.HADOOP_JOB_NAME); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
bf.createBinding("jar-url", "value", controller, JobEntryHadoopJobExecutorController.JAR_URL); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
bf.createBinding("command-line-arguments", "value", controller.getSimpleConfiguration(), SimpleConfiguration.CMD_LINE_ARGS); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
bf.createBinding("classes-output-key-class", "value", controller.getAdvancedConfiguration(), AdvancedConfiguration.OUTPUT_KEY_CLASS); //$NON-NLS-1$ //$NON-NLS-2$
bf.createBinding("classes-output-value-class", "value", controller.getAdvancedConfiguration(), AdvancedConfiguration.OUTPUT_VALUE_CLASS); //$NON-NLS-1$ //$NON-NLS-2$
bf.createBinding("classes-mapper-class", "value", controller.getAdvancedConfiguration(), AdvancedConfiguration.MAPPER_CLASS); //$NON-NLS-1$ //$NON-NLS-2$
bf.createBinding("classes-combiner-class", "value", controller.getAdvancedConfiguration(), AdvancedConfiguration.COMBINER_CLASS); //$NON-NLS-1$ //$NON-NLS-2$
bf.createBinding("classes-reducer-class", "value", controller.getAdvancedConfiguration(), AdvancedConfiguration.REDUCER_CLASS); //$NON-NLS-1$ //$NON-NLS-2$
bf.createBinding("classes-input-format", "value", controller.getAdvancedConfiguration(), AdvancedConfiguration.INPUT_FORMAT_CLASS); //$NON-NLS-1$ //$NON-NLS-2$
bf.createBinding("classes-output-format", "value", controller.getAdvancedConfiguration(), AdvancedConfiguration.OUTPUT_FORMAT_CLASS); //$NON-NLS-1$ //$NON-NLS-2$
final BindingConvertor<String, Integer> bindingConverter = new BindingConvertor<String, Integer>() {
public Integer sourceToTarget(String value) {
return Integer.parseInt(value);
}
public String targetToSource(Integer value) {
return value.toString();
}
};
bf.createBinding("num-map-tasks", "value", controller.getAdvancedConfiguration(), AdvancedConfiguration.NUM_MAP_TASKS, bindingConverter); //$NON-NLS-1$ //$NON-NLS-2$
bf.createBinding("num-reduce-tasks", "value", controller.getAdvancedConfiguration(), AdvancedConfiguration.NUM_REDUCE_TASKS, bindingConverter); //$NON-NLS-1$ //$NON-NLS-2$
bf.createBinding("blocking", "selected", controller.getAdvancedConfiguration(), AdvancedConfiguration.BLOCKING); //$NON-NLS-1$ //$NON-NLS-2$
bf.createBinding("logging-interval", "value", controller.getAdvancedConfiguration(), AdvancedConfiguration.LOGGING_INTERVAL, bindingConverter); //$NON-NLS-1$ //$NON-NLS-2$
bf.createBinding("input-path", "value", controller.getAdvancedConfiguration(), AdvancedConfiguration.INPUT_PATH); //$NON-NLS-1$ //$NON-NLS-2$
bf.createBinding("output-path", "value", controller.getAdvancedConfiguration(), AdvancedConfiguration.OUTPUT_PATH); //$NON-NLS-1$ //$NON-NLS-2$
bf.createBinding("hdfs-hostname", "value", controller.getAdvancedConfiguration(), AdvancedConfiguration.HDFS_HOSTNAME); //$NON-NLS-1$ //$NON-NLS-2$
bf.createBinding("hdfs-port", "value", controller.getAdvancedConfiguration(), AdvancedConfiguration.HDFS_PORT); //$NON-NLS-1$ //$NON-NLS-2$
bf.createBinding("job-tracker-hostname", "value", controller.getAdvancedConfiguration(), AdvancedConfiguration.JOB_TRACKER_HOSTNAME); //$NON-NLS-1$ //$NON-NLS-2$
bf.createBinding("job-tracker-port", "value", controller.getAdvancedConfiguration(), AdvancedConfiguration.JOB_TRACKER_PORT); //$NON-NLS-1$ //$NON-NLS-2$
bf.createBinding("working-dir", "value", controller.getAdvancedConfiguration(), AdvancedConfiguration.WORKING_DIRECTORY); //$NON-NLS-1$ //$NON-NLS-2$
((XulRadio) container.getDocumentRoot().getElementById("simpleRadioButton")).setSelected(this.jobEntry.isSimple()); //$NON-NLS-1$
((XulRadio) container.getDocumentRoot().getElementById("advancedRadioButton")).setSelected(!this.jobEntry.isSimple()); //$NON-NLS-1$
((XulVbox) container.getDocumentRoot().getElementById("advanced-configuration")).setVisible(!this.jobEntry.isSimple()); //$NON-NLS-1$
XulTextbox loggingInterval = (XulTextbox) container.getDocumentRoot().getElementById("logging-interval");
loggingInterval.setValue("" + controller.getAdvancedConfiguration().getLoggingInterval());
XulTextbox mapTasks = (XulTextbox) container.getDocumentRoot().getElementById("num-map-tasks");
mapTasks.setValue("" + controller.getAdvancedConfiguration().getNumMapTasks());
XulTextbox reduceTasks = (XulTextbox) container.getDocumentRoot().getElementById("num-reduce-tasks");
reduceTasks.setValue("" + controller.getAdvancedConfiguration().getNumReduceTasks());
XulTree variablesTree = (XulTree) container.getDocumentRoot().getElementById("fields-table"); //$NON-NLS-1$
bf.setBindingType(Type.ONE_WAY);
bf.createBinding(controller.getUserDefined(), "children", variablesTree, "elements"); //$NON-NLS-1$//$NON-NLS-2$
bf.setBindingType(Type.BI_DIRECTIONAL);
controller.setJobEntry((JobEntryHadoopJobExecutor) jobEntry);
controller.init();
}
| public JobEntryHadoopJobExecutorDialog(Shell parent, JobEntryInterface jobEntry, Repository rep, JobMeta jobMeta) throws XulException, DocumentException {
super(parent, jobEntry, rep, jobMeta);
this.jobEntry = (JobEntryHadoopJobExecutor) jobEntry;
SwtXulLoader swtXulLoader = new SwtXulLoader();
swtXulLoader.registerClassLoader(getClass().getClassLoader());
swtXulLoader.setOuterContext(shell);
container = swtXulLoader.loadXul("org/pentaho/di/ui/job/entries/hadoopjobexecutor/JobEntryHadoopJobExecutorDialog.xul", bundle); //$NON-NLS-1$
final XulRunner runner = new SwtXulRunner();
runner.addContainer(container);
container.addEventHandler(controller);
bf = new DefaultBindingFactory();
bf.setDocument(container.getDocumentRoot());
bf.setBindingType(Type.BI_DIRECTIONAL);
bf.createBinding("jobentry-name", "value", controller, JobEntryHadoopJobExecutorController.JOB_ENTRY_NAME); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
bf.createBinding("hadoop-distribution", "selectedItem", controller.getAdvancedConfiguration(), JobEntryHadoopJobExecutorController.AdvancedConfiguration.HADOOP_DISTRIBUTION); //$NON-NLS-1$ //$NON-NLS-2$
bf.createBinding("jobentry-hadoopjob-name", "value", controller, JobEntryHadoopJobExecutorController.HADOOP_JOB_NAME); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
bf.createBinding("jar-url", "value", controller, JobEntryHadoopJobExecutorController.JAR_URL); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
bf.createBinding("command-line-arguments", "value", controller.getSimpleConfiguration(), SimpleConfiguration.CMD_LINE_ARGS); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
bf.createBinding("classes-output-key-class", "value", controller.getAdvancedConfiguration(), AdvancedConfiguration.OUTPUT_KEY_CLASS); //$NON-NLS-1$ //$NON-NLS-2$
bf.createBinding("classes-output-value-class", "value", controller.getAdvancedConfiguration(), AdvancedConfiguration.OUTPUT_VALUE_CLASS); //$NON-NLS-1$ //$NON-NLS-2$
bf.createBinding("classes-mapper-class", "value", controller.getAdvancedConfiguration(), AdvancedConfiguration.MAPPER_CLASS); //$NON-NLS-1$ //$NON-NLS-2$
bf.createBinding("classes-combiner-class", "value", controller.getAdvancedConfiguration(), AdvancedConfiguration.COMBINER_CLASS); //$NON-NLS-1$ //$NON-NLS-2$
bf.createBinding("classes-reducer-class", "value", controller.getAdvancedConfiguration(), AdvancedConfiguration.REDUCER_CLASS); //$NON-NLS-1$ //$NON-NLS-2$
bf.createBinding("classes-input-format", "value", controller.getAdvancedConfiguration(), AdvancedConfiguration.INPUT_FORMAT_CLASS); //$NON-NLS-1$ //$NON-NLS-2$
bf.createBinding("classes-output-format", "value", controller.getAdvancedConfiguration(), AdvancedConfiguration.OUTPUT_FORMAT_CLASS); //$NON-NLS-1$ //$NON-NLS-2$
final BindingConvertor<String, Integer> bindingConverter = new BindingConvertor<String, Integer>() {
public Integer sourceToTarget(String value) {
return Integer.parseInt(value);
}
public String targetToSource(Integer value) {
return value.toString();
}
};
bf.createBinding("num-map-tasks", "value", controller.getAdvancedConfiguration(), AdvancedConfiguration.NUM_MAP_TASKS, bindingConverter); //$NON-NLS-1$ //$NON-NLS-2$
bf.createBinding("num-reduce-tasks", "value", controller.getAdvancedConfiguration(), AdvancedConfiguration.NUM_REDUCE_TASKS, bindingConverter); //$NON-NLS-1$ //$NON-NLS-2$
bf.createBinding("blocking", "selected", controller.getAdvancedConfiguration(), AdvancedConfiguration.BLOCKING); //$NON-NLS-1$ //$NON-NLS-2$
bf.createBinding("logging-interval", "value", controller.getAdvancedConfiguration(), AdvancedConfiguration.LOGGING_INTERVAL, bindingConverter); //$NON-NLS-1$ //$NON-NLS-2$
bf.createBinding("input-path", "value", controller.getAdvancedConfiguration(), AdvancedConfiguration.INPUT_PATH); //$NON-NLS-1$ //$NON-NLS-2$
bf.createBinding("output-path", "value", controller.getAdvancedConfiguration(), AdvancedConfiguration.OUTPUT_PATH); //$NON-NLS-1$ //$NON-NLS-2$
bf.createBinding("hdfs-hostname", "value", controller.getAdvancedConfiguration(), AdvancedConfiguration.HDFS_HOSTNAME); //$NON-NLS-1$ //$NON-NLS-2$
bf.createBinding("hdfs-port", "value", controller.getAdvancedConfiguration(), AdvancedConfiguration.HDFS_PORT); //$NON-NLS-1$ //$NON-NLS-2$
bf.createBinding("job-tracker-hostname", "value", controller.getAdvancedConfiguration(), AdvancedConfiguration.JOB_TRACKER_HOSTNAME); //$NON-NLS-1$ //$NON-NLS-2$
bf.createBinding("job-tracker-port", "value", controller.getAdvancedConfiguration(), AdvancedConfiguration.JOB_TRACKER_PORT); //$NON-NLS-1$ //$NON-NLS-2$
bf.createBinding("working-dir", "value", controller.getAdvancedConfiguration(), AdvancedConfiguration.WORKING_DIRECTORY); //$NON-NLS-1$ //$NON-NLS-2$
((XulRadio) container.getDocumentRoot().getElementById("simpleRadioButton")).setSelected(this.jobEntry.isSimple()); //$NON-NLS-1$
((XulRadio) container.getDocumentRoot().getElementById("advancedRadioButton")).setSelected(!this.jobEntry.isSimple()); //$NON-NLS-1$
((XulVbox) container.getDocumentRoot().getElementById("advanced-configuration")).setVisible(!this.jobEntry.isSimple()); //$NON-NLS-1$
XulTextbox loggingInterval = (XulTextbox) container.getDocumentRoot().getElementById("logging-interval");
loggingInterval.setValue("" + controller.getAdvancedConfiguration().getLoggingInterval());
XulTextbox mapTasks = (XulTextbox) container.getDocumentRoot().getElementById("num-map-tasks");
mapTasks.setValue("" + controller.getAdvancedConfiguration().getNumMapTasks());
XulTextbox reduceTasks = (XulTextbox) container.getDocumentRoot().getElementById("num-reduce-tasks");
reduceTasks.setValue("" + controller.getAdvancedConfiguration().getNumReduceTasks());
XulTree variablesTree = (XulTree) container.getDocumentRoot().getElementById("fields-table"); //$NON-NLS-1$
bf.setBindingType(Type.ONE_WAY);
bf.createBinding(controller.getUserDefined(), "children", variablesTree, "elements"); //$NON-NLS-1$//$NON-NLS-2$
bf.setBindingType(Type.BI_DIRECTIONAL);
controller.setJobEntry((JobEntryHadoopJobExecutor) jobEntry);
try {
// TODO Controller should not throw Throwable. Looks like we need to change HadoopConfigurerFactory to throw a more specific exception.
controller.init();
} catch (Throwable t) {
throw new XulException("Unable to initialize", t);
}
}
|
diff --git a/beam-visat-rcp/src/test/java/org/esa/beam/visat/toolviews/layermanager/LayerTreeModelTest.java b/beam-visat-rcp/src/test/java/org/esa/beam/visat/toolviews/layermanager/LayerTreeModelTest.java
index 013d687c9..c77c099dd 100644
--- a/beam-visat-rcp/src/test/java/org/esa/beam/visat/toolviews/layermanager/LayerTreeModelTest.java
+++ b/beam-visat-rcp/src/test/java/org/esa/beam/visat/toolviews/layermanager/LayerTreeModelTest.java
@@ -1,111 +1,111 @@
/*
* Copyright (C) 2002-2008 by Brockmann Consult
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation. This program is distributed in the hope it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package org.esa.beam.visat.toolviews.layermanager;
import com.bc.ceres.glayer.Layer;
import junit.framework.TestCase;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import java.util.List;
public class LayerTreeModelTest extends TestCase {
public void testIt() {
Layer layer0 = new Layer();
Layer layer1 = new Layer();
Layer layer2 = new Layer();
Layer layer3 = new Layer();
layer0.getChildren().add(layer1);
layer0.getChildren().add(layer2);
layer0.getChildren().add(layer3);
Layer layer4 = new Layer();
Layer layer5 = new Layer();
layer3.getChildren().add(layer4);
layer3.getChildren().add(layer5);
LayerTreeModel treeModel = new LayerTreeModel(layer0);
assertSame(layer0, treeModel.getRoot());
Layer[] path = LayerTreeModel.getLayerPath(layer0, layer0);
assertNotNull(path);
assertEquals(1, path.length);
assertSame(layer0, path[0]);
path = LayerTreeModel.getLayerPath(layer3, layer4);
assertNotNull(path);
assertEquals(2, path.length);
assertSame(layer3, path[0]);
assertSame(layer4, path[1]);
path = LayerTreeModel.getLayerPath(layer0, layer4);
assertNotNull(path);
assertEquals(3, path.length);
assertSame(layer0, path[0]);
assertSame(layer3, path[1]);
assertSame(layer4, path[2]);
path = LayerTreeModel.getLayerPath(layer4, layer3);
assertNotNull(path);
assertEquals(0, path.length);
assertEquals(3, treeModel.getChildCount(layer0));
assertSame(layer1, treeModel.getChild(layer0, 0));
assertSame(layer2, treeModel.getChild(layer0, 1));
assertSame(layer3, treeModel.getChild(layer0, 2));
assertEquals(0, treeModel.getChildCount(layer1));
assertEquals(0, treeModel.getChildCount(layer2));
assertEquals(2, treeModel.getChildCount(layer3));
assertSame(layer4, treeModel.getChild(layer3, 0));
assertSame(layer5, treeModel.getChild(layer3, 1));
final MyTreeModelListener listener = new MyTreeModelListener();
treeModel.addTreeModelListener(listener);
final List<Layer> children = layer3.getChildren();
children.remove(layer4);
- assertEquals("treeNodesRemoved;", listener.trace);
+ assertEquals("treeStructureChanged;", listener.trace);
}
private static class MyTreeModelListener implements TreeModelListener {
String trace = "";
TreeModelEvent e;
public void treeNodesChanged(TreeModelEvent e) {
trace+="treeNodesChanged;";
this.e = e;
}
public void treeNodesInserted(TreeModelEvent e) {
trace+="treeNodesInserted;";
this.e = e;
}
public void treeNodesRemoved(TreeModelEvent e) {
trace+="treeNodesRemoved;";
this.e = e;
}
public void treeStructureChanged(TreeModelEvent e) {
trace+="treeStructureChanged;";
this.e = e;
}
}
}
| true | true | public void testIt() {
Layer layer0 = new Layer();
Layer layer1 = new Layer();
Layer layer2 = new Layer();
Layer layer3 = new Layer();
layer0.getChildren().add(layer1);
layer0.getChildren().add(layer2);
layer0.getChildren().add(layer3);
Layer layer4 = new Layer();
Layer layer5 = new Layer();
layer3.getChildren().add(layer4);
layer3.getChildren().add(layer5);
LayerTreeModel treeModel = new LayerTreeModel(layer0);
assertSame(layer0, treeModel.getRoot());
Layer[] path = LayerTreeModel.getLayerPath(layer0, layer0);
assertNotNull(path);
assertEquals(1, path.length);
assertSame(layer0, path[0]);
path = LayerTreeModel.getLayerPath(layer3, layer4);
assertNotNull(path);
assertEquals(2, path.length);
assertSame(layer3, path[0]);
assertSame(layer4, path[1]);
path = LayerTreeModel.getLayerPath(layer0, layer4);
assertNotNull(path);
assertEquals(3, path.length);
assertSame(layer0, path[0]);
assertSame(layer3, path[1]);
assertSame(layer4, path[2]);
path = LayerTreeModel.getLayerPath(layer4, layer3);
assertNotNull(path);
assertEquals(0, path.length);
assertEquals(3, treeModel.getChildCount(layer0));
assertSame(layer1, treeModel.getChild(layer0, 0));
assertSame(layer2, treeModel.getChild(layer0, 1));
assertSame(layer3, treeModel.getChild(layer0, 2));
assertEquals(0, treeModel.getChildCount(layer1));
assertEquals(0, treeModel.getChildCount(layer2));
assertEquals(2, treeModel.getChildCount(layer3));
assertSame(layer4, treeModel.getChild(layer3, 0));
assertSame(layer5, treeModel.getChild(layer3, 1));
final MyTreeModelListener listener = new MyTreeModelListener();
treeModel.addTreeModelListener(listener);
final List<Layer> children = layer3.getChildren();
children.remove(layer4);
assertEquals("treeNodesRemoved;", listener.trace);
}
| public void testIt() {
Layer layer0 = new Layer();
Layer layer1 = new Layer();
Layer layer2 = new Layer();
Layer layer3 = new Layer();
layer0.getChildren().add(layer1);
layer0.getChildren().add(layer2);
layer0.getChildren().add(layer3);
Layer layer4 = new Layer();
Layer layer5 = new Layer();
layer3.getChildren().add(layer4);
layer3.getChildren().add(layer5);
LayerTreeModel treeModel = new LayerTreeModel(layer0);
assertSame(layer0, treeModel.getRoot());
Layer[] path = LayerTreeModel.getLayerPath(layer0, layer0);
assertNotNull(path);
assertEquals(1, path.length);
assertSame(layer0, path[0]);
path = LayerTreeModel.getLayerPath(layer3, layer4);
assertNotNull(path);
assertEquals(2, path.length);
assertSame(layer3, path[0]);
assertSame(layer4, path[1]);
path = LayerTreeModel.getLayerPath(layer0, layer4);
assertNotNull(path);
assertEquals(3, path.length);
assertSame(layer0, path[0]);
assertSame(layer3, path[1]);
assertSame(layer4, path[2]);
path = LayerTreeModel.getLayerPath(layer4, layer3);
assertNotNull(path);
assertEquals(0, path.length);
assertEquals(3, treeModel.getChildCount(layer0));
assertSame(layer1, treeModel.getChild(layer0, 0));
assertSame(layer2, treeModel.getChild(layer0, 1));
assertSame(layer3, treeModel.getChild(layer0, 2));
assertEquals(0, treeModel.getChildCount(layer1));
assertEquals(0, treeModel.getChildCount(layer2));
assertEquals(2, treeModel.getChildCount(layer3));
assertSame(layer4, treeModel.getChild(layer3, 0));
assertSame(layer5, treeModel.getChild(layer3, 1));
final MyTreeModelListener listener = new MyTreeModelListener();
treeModel.addTreeModelListener(listener);
final List<Layer> children = layer3.getChildren();
children.remove(layer4);
assertEquals("treeStructureChanged;", listener.trace);
}
|
diff --git a/src/java/gov/health/bean/DbfController.java b/src/java/gov/health/bean/DbfController.java
index fb88fa0..192b0d1 100644
--- a/src/java/gov/health/bean/DbfController.java
+++ b/src/java/gov/health/bean/DbfController.java
@@ -1,1006 +1,1011 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package gov.health.bean;
import gov.health.entity.Institution;
import gov.health.entity.DbfFile;
import gov.health.entity.PersonInstitution;
import gov.health.entity.Person;
import gov.health.entity.Category;
import com.linuxense.javadbf.DBFField;
import com.linuxense.javadbf.DBFReader;
import gov.health.data.DesignationSummeryRecord;
import gov.health.entity.Designation;
import gov.health.entity.InstitutionSet;
import gov.health.facade.CategoryFacade;
import gov.health.facade.DbfFileFacade;
import gov.health.facade.DesignationFacade;
import gov.health.facade.InstitutionFacade;
import gov.health.facade.InstitutionSetFacade;
import gov.health.facade.PersonFacade;
import gov.health.facade.PersonInstitutionFacade;
import gov.health.entity.TransferHistory;
import gov.health.facade.TransferHistoryFacade;
import java.io.ByteArrayInputStream;
import javax.faces.bean.ManagedBean;
import org.primefaces.model.UploadedFile;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.apache.commons.io.IOUtils;
/**
*
* @author buddhika
*/
@ManagedBean
@SessionScoped
public class DbfController implements Serializable {
StreamedContent scImage;
StreamedContent scImageById;
private UploadedFile file;
@EJB
TransferHistoryFacade thFacade;
@EJB
DbfFileFacade dbfFileFacade;
@EJB
InstitutionFacade insFacade;
@EJB
PersonFacade perFacade;
@EJB
CategoryFacade catFacade;
@EJB
PersonInstitutionFacade piFacade;
@EJB
DesignationFacade desFacade;
@EJB
InstitutionSetFacade insetFacade;
//
//
Institution institution;
Person person;
Category category;
//
DbfFile defFile;
List<DbfFile> dbfFiles;
List<PersonInstitution> existingPersonInstitutions;
List<PersonInstitution> previousPersonInstitutions;
List<PersonInstitution> newPersonInstitutions;
@ManagedProperty(value = "#{sessionController}")
SessionController sessionController;
Integer payYear = 0;
Integer payMonth = 0;
List<Integer> payYears;
List<Integer> payMonths;
List<InstitutionSet> insSets;
InstitutionSet insSet;
List<DesignationSummeryRecord> designationSummery;
//
int activeTab = 0;
Long withoutNicCount;
Long withoutDesignationCount;
Long withoutMappedDesignationCount;
Long withoutInstitutionCount;
Long withoutMappedInstitutionCount;
Long activeCount;
Long temporaryCount;
//
Boolean toGetRecordsagain = Boolean.TRUE;
int[] monthColR = new int[12];
int[] monthColG = new int[12];
int[] monthColB = new int[12];
int[] completedSet = new int[12];
int setCount;
public int getSetCount() {
if (getInstitution() == null) {
return 0;
}
String sql;
sql = "select iset from InstitutionSet iset where iset.retired = false and iset.institution.id = " + getInstitution().getId() + " ";
try {
setCount =getPiFacade().findBySQL(sql).size();
return setCount;
} catch (Exception e) {
System.out.println("Error in getting set count is " + e.getMessage());
return 0;
}
}
public void setSetCount(int setCount) {
this.setCount = setCount;
}
public int[] getMonthColR() {
return monthColR;
}
public void setMonthColR(int[] monthColR) {
this.monthColR = monthColR;
}
public int[] getMonthColG() {
return monthColG;
}
public void setMonthColG(int[] monthColG) {
this.monthColG = monthColG;
}
public int[] getMonthColB() {
return monthColB;
}
public void setMonthColB(int[] monthColB) {
this.monthColB = monthColB;
}
public void prepareSetSeubmitColours() {
getSetCount();
completedSetCount(getPayYear());
System.out.println("Set Count " + setCount);
for (int i = 0; i < 12; i++) {
System.out.println("Completed Sets " + completedSet[i]);
if (setCount == 0) {
monthColR[i] = 0;
monthColG[i] = 255;
monthColB[i]=0;
} else if (setCount == completedSet[i]) {
monthColR[i] = 0;
monthColG[i] = 255;
monthColB[i]=0;
} else if (completedSet[i] >= (setCount / 2)) {
monthColR[i] = 255;
monthColG[i] = 255;
monthColB[i]=0;
} else {
monthColR[i] = 245;
monthColG[i] = 245;
monthColB[i]=245;
}
System.out.println("i " + i);
System.out.println("R " + monthColR[i]);
System.out.println("G " + monthColG[i]);
}
}
public int[] getCompletedSet() {
return completedSet;
}
public void setCompletedSet(int[] completedSet) {
this.completedSet = completedSet;
}
public static int intValue(long value) {
int valueInt = (int) value;
if (valueInt != value) {
throw new IllegalArgumentException(
"The long value " + value + " is not within range of the int type");
}
return valueInt;
}
public void completedSetCount(Integer temPayYear) {
int temPayMonth = 0;
if (getInstitution() == null || getPayYear() == 0) {
System.out.println("Completed Set Count ok");
System.out.println(getInstitution().toString());
System.out.println("Pay Month " + temPayMonth);
System.out.println("Pay Year " + temPayYear);
return;
}
for (int i = 0; i < 12; i++) {
temPayMonth = i + 1;
String sql;
sql = "select distinct pi.paySet from PersonInstitution pi where pi.retired = false and pi.payYear = " + temPayYear + " and pi.payMonth = " + temPayMonth + " and pi.payCentre.id = " + getInstitution().getId() + " ";
System.out.println(sql);
try {
completedSet[i] = getPiFacade().findBySQL(sql).size();
System.out.println(completedSet[i]);
} catch (Exception e) {
System.out.println(e.getMessage());
completedSet[i] = 0;
}
}
}
public Boolean getToGetRecordsagain() {
return toGetRecordsagain;
}
public void setToGetRecordsagain(Boolean toGetRecordsagain) {
this.toGetRecordsagain = toGetRecordsagain;
}
public List<PersonInstitution> getPreviousPersonInstitutions() {
return previousPersonInstitutions;
}
public void setPreviousPersonInstitutions(List<PersonInstitution> previousPersonInstitutions) {
this.previousPersonInstitutions = previousPersonInstitutions;
}
public void getSummeryCounts(List<PersonInstitution> pis) {
withoutNicCount = 0L;
withoutDesignationCount = 0L;
withoutMappedDesignationCount = 0L;
withoutInstitutionCount = 0L;
withoutMappedInstitutionCount = 0L;
activeCount = 0L;
temporaryCount = 0L;
for (PersonInstitution pi : pis) {
if (pi.getNic().trim().equals("")) {
withoutNicCount++;
}
if (pi.getDesignation() == null) {
withoutDesignationCount++;
} else {
if (pi.getDesignation().getOfficial() == Boolean.FALSE && pi.getDesignation().getMappedToDesignation() == null) {
withoutMappedInstitutionCount++;
}
}
if (pi.getInstitution() == null) {
withoutInstitutionCount++;
} else {
if (pi.getInstitution().getOfficial() == Boolean.FALSE && pi.getInstitution().getMappedToInstitution() == null) {
withoutMappedInstitutionCount++;
}
}
if (pi.getActiveState() == Boolean.TRUE) {
activeCount++;
}
if (pi.getPermanent() == Boolean.FALSE) {
temporaryCount++;
}
}
}
public Long getWithoutNicCount() {
getExistingPersonInstitutions();
return withoutNicCount;
}
public void setWithoutNicCount(Long withoutNicCount) {
this.withoutNicCount = withoutNicCount;
}
public Long getWithoutDesignationCount() {
getExistingPersonInstitutions();
return withoutDesignationCount;
}
public void setWithoutDesignationCount(Long withoutDesignationCount) {
this.withoutDesignationCount = withoutDesignationCount;
}
public Long getWithoutMappedDesignationCount() {
getExistingPersonInstitutions();
return withoutMappedDesignationCount;
}
public void setWithoutMappedDesignationCount(Long withoutMappedDesignationCount) {
this.withoutMappedDesignationCount = withoutMappedDesignationCount;
}
public Long getWithoutInstitutionCount() {
getExistingPersonInstitutions();
return withoutInstitutionCount;
}
public void setWithoutInstitutionCount(Long withoutInstitutionCount) {
this.withoutInstitutionCount = withoutInstitutionCount;
}
public Long getWithoutMappedInstitutionCount() {
getExistingPersonInstitutions();
return withoutMappedInstitutionCount;
}
public void setWithoutMappedInstitutionCount(Long withoutMappedInstitutionCount) {
this.withoutMappedInstitutionCount = withoutMappedInstitutionCount;
}
public Long getActiveCount() {
getExistingPersonInstitutions();
return activeCount;
}
public void setActiveCount(Long activeCount) {
this.activeCount = activeCount;
}
public Long getTemporaryCount() {
getExistingPersonInstitutions();
return temporaryCount;
}
public void setTemporaryCount(Long temporaryCount) {
this.temporaryCount = temporaryCount;
}
public int getActiveTab() {
if (getNewPersonInstitutions().size() > 0) {
activeTab = 1;
} else {
activeTab = 0;
}
return activeTab;
}
public void setActiveTab(int activeTab) {
this.activeTab = activeTab;
}
public List<DesignationSummeryRecord> getDesignationSummery() {
if (getInstitution() == null || getPayMonth() == null || getPayYear() == null) {
return new ArrayList<DesignationSummeryRecord>();
}
String sql = "select pi.designation.name, count(pi) from PersonInstitution pi where pi.retired = false and pi.payYear = " + getPayYear() + " and pi.payMonth = " + getPayMonth() + " and pi.payCentre.id = " + getInstitution().getId() + " group by pi.designation.name";
List lst = getPiFacade().findGroupingBySql(sql);
List<DesignationSummeryRecord> sums = new ArrayList<DesignationSummeryRecord>();
Iterator<Object[]> itr = lst.iterator();
while (itr.hasNext()) {
Object[] o = itr.next();
DesignationSummeryRecord s = new DesignationSummeryRecord();
s.setDesignationName(o[0].toString());
s.setCount(Long.valueOf(o[1].toString()));
sums.add(s);
}
getSetCount();
prepareSetSeubmitColours();
return sums;
}
public TransferHistoryFacade getThFacade() {
return thFacade;
}
public void setThFacade(TransferHistoryFacade thFacade) {
this.thFacade = thFacade;
}
public void setDesignationSummery(List<DesignationSummeryRecord> designationSummery) {
this.designationSummery = designationSummery;
}
public InstitutionSetFacade getInsetFacade() {
return insetFacade;
}
public void setInsetFacade(InstitutionSetFacade insetFacade) {
this.insetFacade = insetFacade;
}
public InstitutionSet getInsSet() {
return insSet;
}
public void setInsSet(InstitutionSet insSet) {
if (this.insSet != insSet) {
setToGetRecordsagain(Boolean.TRUE);
}
this.insSet = insSet;
}
public List<InstitutionSet> getInsSets() {
if (getSessionController().getLoggedUser().getRestrictedInstitution() != null) {
setInstitution(getSessionController().getLoggedUser().getRestrictedInstitution());
}
if (getInstitution() == null || getInstitution().getId() == null || getInstitution().getId() == 0) {
return null;
}
String sql;
sql = "select s from InstitutionSet s where s.retired = false and s.institution.id = " + getInstitution().getId();
insSets = getInsetFacade().findBySQL(sql);
return insSets;
}
public void setInsSets(List<InstitutionSet> insSets) {
this.insSets = insSets;
}
public List<Integer> getPayMonths() {
if (payMonths == null) {
payMonths = new ArrayList<Integer>();
payMonths.add(1);
payMonths.add(2);
payMonths.add(3);
payMonths.add(4);
payMonths.add(5);
payMonths.add(6);
payMonths.add(7);
payMonths.add(8);
payMonths.add(9);
payMonths.add(10);
payMonths.add(11);
payMonths.add(12);
}
return payMonths;
}
public void setPayMonths(List<Integer> payMonths) {
this.payMonths = payMonths;
}
public List<Integer> getPayYears() {
if (payYears == null) {
payYears = new ArrayList<Integer>();
payYears.add(2011);
payYears.add(2012);
payYears.add(2013);
}
return payYears;
}
public void setPayYears(List<Integer> payYears) {
this.payYears = payYears;
}
public Integer getPayMonth() {
if (payMonth == null || payMonth == 0) {
return Calendar.getInstance().get(Calendar.MONTH);
}
return payMonth;
}
public void setPayMonth(Integer payMonth) {
if (this.payMonth != payMonth) {
setToGetRecordsagain(Boolean.TRUE);
}
this.payMonth = payMonth;
}
public Integer getPayYear() {
if (payYear == null || payYear == 0) {
return Calendar.getInstance().get(Calendar.YEAR);
}
return payYear;
}
public void setPayYear(Integer payYear) {
if (this.payYear != payYear) {
setToGetRecordsagain(Boolean.TRUE);
}
this.payYear = payYear;
}
public DesignationFacade getDesFacade() {
return desFacade;
}
public void setDesFacade(DesignationFacade desFacade) {
this.desFacade = desFacade;
}
public SessionController getSessionController() {
return sessionController;
}
public void setSessionController(SessionController sessionController) {
this.sessionController = sessionController;
}
public List<DbfFile> getDbfFiles() {
return dbfFiles;
}
public void setDbfFiles(List<DbfFile> dbfFiles) {
this.dbfFiles = dbfFiles;
}
public List<PersonInstitution> getExistingPersonInstitutions() {
if (getInstitution() == null || getInsSet() == null || getPayMonth() == null || getPayYear() == null) {
return new ArrayList<PersonInstitution>();
}
if (getToGetRecordsagain()) {
existingPersonInstitutions = getPiFacade().findBySQL("select pi from PersonInstitution pi where pi.retired = false and pi.payYear = " + getPayYear() + " and pi.payMonth = " + getPayMonth() + " and pi.paySet.id = " + getInsSet().getId() + " and pi.payCentre.id = " + getInstitution().getId());
getSummeryCounts(existingPersonInstitutions);
setToGetRecordsagain(Boolean.FALSE);
} else {
}
return existingPersonInstitutions;
}
public List<PersonInstitution> getPersonInstitutionsWithoutNic() {
if (getInstitution() == null || getInsSet() == null || getPayMonth() == null || getPayYear() == null) {
return new ArrayList<PersonInstitution>();
}
existingPersonInstitutions = getPiFacade().findBySQL("select pi from PersonInstitution pi where pi.retired = false and pi.payYear = " + getPayYear() + " and pi.payMonth = " + getPayMonth() + " and pi.paySet.id = " + getInsSet().getId() + " and pi.payCentre.id = " + getInstitution().getId() + " and pi.person is null order by pi.name");
return existingPersonInstitutions;
}
public List<PersonInstitution> getPersonInstitutionsWithoutDesignations() {
if (getInstitution() == null || getInsSet() == null || getPayMonth() == null || getPayYear() == null) {
return new ArrayList<PersonInstitution>();
}
existingPersonInstitutions = getPiFacade().findBySQL("select pi from PersonInstitution pi where pi.retired = false and pi.payYear = " + getPayYear() + " and pi.payMonth = " + getPayMonth() + " and pi.paySet.id = " + getInsSet().getId() + " and pi.payCentre.id = " + getInstitution().getId() + " and pi.designation is null order by pi.name");
return existingPersonInstitutions;
}
public void setExistingPersonInstitutions(List<PersonInstitution> existingPersonInstitutions) {
this.existingPersonInstitutions = existingPersonInstitutions;
}
public List<PersonInstitution> getNewPersonInstitutions() {
if (newPersonInstitutions == null) {
newPersonInstitutions = new ArrayList<PersonInstitution>();
}
return newPersonInstitutions;
}
public void setNewPersonInstitutions(List<PersonInstitution> newPersonInstitutions) {
this.newPersonInstitutions = newPersonInstitutions;
}
public PersonInstitutionFacade getPiFacade() {
return piFacade;
}
public void setPiFacade(PersonInstitutionFacade piFacade) {
this.piFacade = piFacade;
}
public StreamedContent getScImageById() {
FacesContext context = FacesContext.getCurrentInstance();
if (context.getRenderResponse()) {
// So, we're rendering the view. Return a stub StreamedContent so that it will generate right URL.
return new DefaultStreamedContent();
} else {
// So, browser is requesting the image. Get ID value from actual request param.
String id = context.getExternalContext().getRequestParameterMap().get("id");
DbfFile temImg = getDbfFileFacade().find(Long.valueOf(id));
return new DefaultStreamedContent(new ByteArrayInputStream(temImg.getBaImage()), temImg.getFileType());
}
}
public void setScImageById(StreamedContent scImageById) {
this.scImageById = scImageById;
}
public StreamedContent getScImage() {
return scImage;
}
public List<DbfFile> getAppImages() {
if (dbfFiles == null) {
dbfFiles = new ArrayList<DbfFile>();
}
System.out.println("Getting app images - count is" + dbfFiles.size());
return dbfFiles;
}
public void setAppImages(List<DbfFile> appImages) {
this.dbfFiles = appImages;
}
public void setScImage(StreamedContent scImage) {
this.scImage = scImage;
}
public DbfFile getDefFile() {
return defFile;
}
public void setDefFile(DbfFile defFile) {
this.defFile = defFile;
}
public DbfFileFacade getDbfFileFacade() {
return dbfFileFacade;
}
public void setDbfFileFacade(DbfFileFacade dbfFileFacade) {
this.dbfFileFacade = dbfFileFacade;
}
/**
* Creates a new instance of ImageController
*/
public DbfController() {
}
public UploadedFile getFile() {
return file;
}
public void setFile(UploadedFile file) {
this.file = file;
setToGetRecordsagain(Boolean.TRUE);
}
private void prepareImages(String sql) {
dbfFiles = getDbfFileFacade().findBySQL(sql);
}
public CategoryFacade getCatFacade() {
return catFacade;
}
public void setCatFacade(CategoryFacade catFacade) {
this.catFacade = catFacade;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
if (category == null && category.getId() != null) {
prepareImages("Select ai from AppImage ai Where ai.category.id = " + category.getId());
} else {
dbfFiles = null;
}
}
public InstitutionFacade getInsFacade() {
return insFacade;
}
public void setInsFacade(InstitutionFacade insFacade) {
this.insFacade = insFacade;
}
public Institution getInstitution() {
if (getSessionController().getLoggedUser().getRestrictedInstitution() == null) {
return institution;
} else {
return getSessionController().getLoggedUser().getRestrictedInstitution();
}
}
public void setInstitution(Institution institution) {
this.institution = institution;
if (this.institution != institution) {
setToGetRecordsagain(Boolean.TRUE);
}
if (institution == null && institution.getId() != null) {
prepareImages("Select ai from AppImage ai Where ai.institution.id = " + institution.getId());
} else {
dbfFiles = null;
}
}
public PersonFacade getPerFacade() {
return perFacade;
}
public void setPerFacade(PersonFacade perFacade) {
this.perFacade = perFacade;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
if (person == null && person.getId() != null) {
prepareImages("Select ai from AppImage ai Where ai.person.id = " + person.getId());
} else {
dbfFiles = null;
}
}
public void savePersonImage() {
if (person == null) {
JsfUtil.addErrorMessage("Please select a Person");
return;
}
defFile = new DbfFile();
defFile.setPerson(person);
saveImage();
setPerson(person);
}
public void saveImage() {
InputStream in;
if (file == null) {
JsfUtil.addErrorMessage("Please upload an image");
return;
}
JsfUtil.addSuccessMessage(file.getFileName());
try {
defFile.setFileName(file.getFileName());
defFile.setFileType(file.getContentType());
in = file.getInputstream();
defFile.setBaImage(IOUtils.toByteArray(in));
dbfFileFacade.create(defFile);
JsfUtil.addSuccessMessage(file.getFileName() + " saved successfully");
} catch (Exception e) {
System.out.println("Error " + e.getMessage());
}
}
private Boolean isCorrectDbfFile(DBFReader reader) {
Boolean correct = true;
try {
if (!reader.getField(0).getName().equalsIgnoreCase("F1_EMPNO")) {
correct = false;
}
if (!reader.getField(2).getName().equalsIgnoreCase("F1_SURNAME")) {
correct = false;
}
if (!reader.getField(7).getName().equalsIgnoreCase("F1_DOB")) {
correct = false;
}
if (!reader.getField(48).getName().equalsIgnoreCase("F1_NICNO")) {
correct = false;
}
} catch (Exception e) {
}
return correct;
}
public void replaceData() {
if (institution == null) {
JsfUtil.addErrorMessage("Please select an institute");
return;
}
if (newPersonInstitutions == null) {
JsfUtil.addErrorMessage("Please upload a dbf file before saving data");
return;
}
for (PersonInstitution pi : existingPersonInstitutions) {
pi.setRetired(true);
pi.setRetiredAt(Calendar.getInstance().getTime());
pi.setRetirer(sessionController.loggedUser);
getPiFacade().edit(pi);
}
for (PersonInstitution pi : newPersonInstitutions) {
// getPerFacade().create(pi.getPerson());
getPiFacade().create(pi);
}
getExistingPersonInstitutions();
existingPersonInstitutions = newPersonInstitutions;
newPersonInstitutions = new ArrayList<PersonInstitution>();
JsfUtil.addSuccessMessage("Data Replaced Successfully");
}
public void markTransfer(Person p, Institution fromIns, Institution toIns, PersonInstitution pi) {
TransferHistory hx = new TransferHistory();
// hx.setPersonInstitution(pi);
hx.setFromInstitution(fromIns);
hx.setToInstitution(toIns);
hx.setPerson(person);
thFacade.create(hx);
}
public String extractData() {
InputStream in;
String temNic;
Boolean newEntries = false;
if (sessionController.getLoggedUser().getRestrictedInstitution() != null) {
setInstitution(sessionController.getLoggedUser().getRestrictedInstitution());
+ }else{
+ if(getInstitution()==null){
+ JsfUtil.addErrorMessage("Please select an institution");
+ return "";
+ }
}
if (getInstitution() == null) {
JsfUtil.addErrorMessage("Please select an institute");
return "";
}
if (file == null) {
JsfUtil.addErrorMessage("Please select the dbf file to upload");
return "";
}
if (payYear == null || payYear == 0) {
JsfUtil.addErrorMessage("Please select a year");
return "";
}
if (payMonth == null || payMonth == 0) {
JsfUtil.addErrorMessage("Please select a Month");
return "";
}
if (insSet == null) {
JsfUtil.addErrorMessage("Please select a Set");
return "";
}
if (getExistingPersonInstitutions().size() > 0) {
newEntries = false;
} else {
newEntries = true;
}
try {
in = file.getInputstream();
DBFReader reader = new DBFReader(in);
if (!isCorrectDbfFile(reader)) {
JsfUtil.addErrorMessage("But the file you selected is not the correct file. Please make sure you selected the correct file named PYREMPMA.DBF. If you are sure that you selected the correct file, you may be using an old version.");
return "";
}
int numberOfFields = reader.getFieldCount();
System.out.println("Number of fields is " + numberOfFields);
for (int i = 0; i < numberOfFields; i++) {
DBFField field = reader.getField(i);
System.out.println("Data Field " + i + " is " + field.getName());
}
Object[] rowObjects;
newPersonInstitutions = new ArrayList<PersonInstitution>();
while ((rowObjects = reader.nextRecord()) != null) {
Person p = null;
PersonInstitution pi = new PersonInstitution();
Institution attachedIns;
String insName;
insName = rowObjects[21].toString() + " " + rowObjects[22].toString() + " " + rowObjects[23].toString();
if (insName.trim().equals("")) {
attachedIns = getInstitution();
} else {
attachedIns = findInstitution(insName);
}
temNic = rowObjects[48].toString();
if ("".equals(temNic.trim())) {
pi.setPerson(null);
} else {
p = getPerFacade().findFirstBySQL("select p from Person p where p.retired = false and p.nic = '" + temNic + "'");
if (p == null) {
p = new Person();
p.setCreatedAt(Calendar.getInstance().getTime());
p.setCreater(sessionController.getLoggedUser());
p.setInstitution(attachedIns);
p.setTitle(rowObjects[1].toString());
p.setInitials(rowObjects[3].toString());
p.setSurname(rowObjects[2].toString());
SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
try {
p.setDob(dateFormat.parse(rowObjects[7].toString()));
} catch (Exception e) {
p.setDob(null);
}
p.setNic(rowObjects[48].toString());
p.setName(p.getTitle() + " " + p.getInitials() + " " + p.getSurname());
getPerFacade().create(p);
} else {
if (p.getInstitution() != getInstitution()) {
markTransfer(p, p.getInstitution(), institution, pi);
}
}
}
pi.setPerson(p);
pi.setInstitution(attachedIns);
pi.setPayCentre(getInstitution());
pi.setNic(rowObjects[48].toString());
pi.setEmpNo(rowObjects[0].toString());
pi.setAddress1(rowObjects[18].toString());
pi.setAddress2(rowObjects[19].toString());
pi.setAddress3(rowObjects[20].toString());
pi.setOffAddress1(rowObjects[21].toString());
pi.setOffAddress2(rowObjects[22].toString());
pi.setOffAddress3(rowObjects[23].toString());
pi.setDesignation(findDesignation(rowObjects[8].toString()));
pi.setName(rowObjects[1].toString() + " " + rowObjects[2].toString() + " " + rowObjects[3].toString());
pi.setPayMonth(payMonth);
pi.setPayYear(payYear);
pi.setPaySet(insSet);
if (rowObjects[4].toString().equals("") || rowObjects[50].toString().equals("")) {
pi.setPermanent(Boolean.FALSE);
} else {
pi.setPermanent(Boolean.TRUE);
}
try {
if (Integer.valueOf(rowObjects[4].toString()) == 0) {
pi.setNopay(Boolean.TRUE);
} else {
}
} catch (Exception e) {
}
try {
pi.setActiveState((Boolean) rowObjects[40]);
} catch (Exception e) {
pi.setActiveState(true);
}
try {
pi.setNopay((Boolean) rowObjects[31]);
} catch (Exception e) {
pi.setNopay(false);
}
if (newEntries) {
getPiFacade().create(pi);
}
newPersonInstitutions.add(pi);
}
if (newEntries) {
JsfUtil.addSuccessMessage("Date in the file " + file.getFileName() + " recorded successfully. ");
newPersonInstitutions = new ArrayList<PersonInstitution>();
getSummeryCounts(newPersonInstitutions);
toGetRecordsagain = Boolean.TRUE;
} else {
JsfUtil.addSuccessMessage("Date in the file " + file.getFileName() + " is listed successfully. If you are satisfied, please click the Save button to permanantly save the new set of data Replacing the old ones under " + institution.getName() + ".");
toGetRecordsagain = Boolean.TRUE;
}
} catch (Exception e) {
System.out.println("Error " + e.getMessage());
}
return "";
}
private Designation findDesignation(String designationName) {
designationName = designationName.trim();
if (designationName.equals("")) {
return null;
}
Designation des = getDesFacade().findFirstBySQL("select d from Designation d where lower(d.name) = '" + designationName.toLowerCase() + "'");
if (des == null) {
des = new Designation();
des.setName(designationName);
des.setCreatedAt(Calendar.getInstance().getTime());
des.setCreater(sessionController.loggedUser);
des.setOfficial(Boolean.FALSE);
getDesFacade().create(des);
} else {
if (des.getOfficial().equals(Boolean.FALSE)) {
if (des.getMappedToDesignation() != null) {
return des.getMappedToDesignation();
}
}
}
return des;
}
private Institution findInstitution(String insName) {
insName = insName.trim();
if (insName.equals("")) {
return null;
}
Institution ins = getInsFacade().findFirstBySQL("select d from Institution d where d.retired = false and lower(d.name) = '" + insName.toLowerCase() + "'");
if (ins == null) {
ins = new Institution();
ins.setName(insName);
ins.setCreatedAt(Calendar.getInstance().getTime());
ins.setCreater(sessionController.loggedUser);
ins.setOfficial(Boolean.FALSE);
getInsFacade().create(ins);
} else {
if (ins.getOfficial().equals(Boolean.FALSE)) {
if (ins.getMappedToInstitution() != null) {
return ins.getMappedToInstitution();
}
}
}
return ins;
}
}
| true | true | public String extractData() {
InputStream in;
String temNic;
Boolean newEntries = false;
if (sessionController.getLoggedUser().getRestrictedInstitution() != null) {
setInstitution(sessionController.getLoggedUser().getRestrictedInstitution());
}
if (getInstitution() == null) {
JsfUtil.addErrorMessage("Please select an institute");
return "";
}
if (file == null) {
JsfUtil.addErrorMessage("Please select the dbf file to upload");
return "";
}
if (payYear == null || payYear == 0) {
JsfUtil.addErrorMessage("Please select a year");
return "";
}
if (payMonth == null || payMonth == 0) {
JsfUtil.addErrorMessage("Please select a Month");
return "";
}
if (insSet == null) {
JsfUtil.addErrorMessage("Please select a Set");
return "";
}
if (getExistingPersonInstitutions().size() > 0) {
newEntries = false;
} else {
newEntries = true;
}
try {
in = file.getInputstream();
DBFReader reader = new DBFReader(in);
if (!isCorrectDbfFile(reader)) {
JsfUtil.addErrorMessage("But the file you selected is not the correct file. Please make sure you selected the correct file named PYREMPMA.DBF. If you are sure that you selected the correct file, you may be using an old version.");
return "";
}
int numberOfFields = reader.getFieldCount();
System.out.println("Number of fields is " + numberOfFields);
for (int i = 0; i < numberOfFields; i++) {
DBFField field = reader.getField(i);
System.out.println("Data Field " + i + " is " + field.getName());
}
Object[] rowObjects;
newPersonInstitutions = new ArrayList<PersonInstitution>();
while ((rowObjects = reader.nextRecord()) != null) {
Person p = null;
PersonInstitution pi = new PersonInstitution();
Institution attachedIns;
String insName;
insName = rowObjects[21].toString() + " " + rowObjects[22].toString() + " " + rowObjects[23].toString();
if (insName.trim().equals("")) {
attachedIns = getInstitution();
} else {
attachedIns = findInstitution(insName);
}
temNic = rowObjects[48].toString();
if ("".equals(temNic.trim())) {
pi.setPerson(null);
} else {
p = getPerFacade().findFirstBySQL("select p from Person p where p.retired = false and p.nic = '" + temNic + "'");
if (p == null) {
p = new Person();
p.setCreatedAt(Calendar.getInstance().getTime());
p.setCreater(sessionController.getLoggedUser());
p.setInstitution(attachedIns);
p.setTitle(rowObjects[1].toString());
p.setInitials(rowObjects[3].toString());
p.setSurname(rowObjects[2].toString());
SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
try {
p.setDob(dateFormat.parse(rowObjects[7].toString()));
} catch (Exception e) {
p.setDob(null);
}
p.setNic(rowObjects[48].toString());
p.setName(p.getTitle() + " " + p.getInitials() + " " + p.getSurname());
getPerFacade().create(p);
} else {
if (p.getInstitution() != getInstitution()) {
markTransfer(p, p.getInstitution(), institution, pi);
}
}
}
pi.setPerson(p);
pi.setInstitution(attachedIns);
pi.setPayCentre(getInstitution());
pi.setNic(rowObjects[48].toString());
pi.setEmpNo(rowObjects[0].toString());
pi.setAddress1(rowObjects[18].toString());
pi.setAddress2(rowObjects[19].toString());
pi.setAddress3(rowObjects[20].toString());
pi.setOffAddress1(rowObjects[21].toString());
pi.setOffAddress2(rowObjects[22].toString());
pi.setOffAddress3(rowObjects[23].toString());
pi.setDesignation(findDesignation(rowObjects[8].toString()));
pi.setName(rowObjects[1].toString() + " " + rowObjects[2].toString() + " " + rowObjects[3].toString());
pi.setPayMonth(payMonth);
pi.setPayYear(payYear);
pi.setPaySet(insSet);
if (rowObjects[4].toString().equals("") || rowObjects[50].toString().equals("")) {
pi.setPermanent(Boolean.FALSE);
} else {
pi.setPermanent(Boolean.TRUE);
}
try {
if (Integer.valueOf(rowObjects[4].toString()) == 0) {
pi.setNopay(Boolean.TRUE);
} else {
}
} catch (Exception e) {
}
try {
pi.setActiveState((Boolean) rowObjects[40]);
} catch (Exception e) {
pi.setActiveState(true);
}
try {
pi.setNopay((Boolean) rowObjects[31]);
} catch (Exception e) {
pi.setNopay(false);
}
if (newEntries) {
getPiFacade().create(pi);
}
newPersonInstitutions.add(pi);
}
if (newEntries) {
JsfUtil.addSuccessMessage("Date in the file " + file.getFileName() + " recorded successfully. ");
newPersonInstitutions = new ArrayList<PersonInstitution>();
getSummeryCounts(newPersonInstitutions);
toGetRecordsagain = Boolean.TRUE;
} else {
JsfUtil.addSuccessMessage("Date in the file " + file.getFileName() + " is listed successfully. If you are satisfied, please click the Save button to permanantly save the new set of data Replacing the old ones under " + institution.getName() + ".");
toGetRecordsagain = Boolean.TRUE;
}
} catch (Exception e) {
System.out.println("Error " + e.getMessage());
}
return "";
}
| public String extractData() {
InputStream in;
String temNic;
Boolean newEntries = false;
if (sessionController.getLoggedUser().getRestrictedInstitution() != null) {
setInstitution(sessionController.getLoggedUser().getRestrictedInstitution());
}else{
if(getInstitution()==null){
JsfUtil.addErrorMessage("Please select an institution");
return "";
}
}
if (getInstitution() == null) {
JsfUtil.addErrorMessage("Please select an institute");
return "";
}
if (file == null) {
JsfUtil.addErrorMessage("Please select the dbf file to upload");
return "";
}
if (payYear == null || payYear == 0) {
JsfUtil.addErrorMessage("Please select a year");
return "";
}
if (payMonth == null || payMonth == 0) {
JsfUtil.addErrorMessage("Please select a Month");
return "";
}
if (insSet == null) {
JsfUtil.addErrorMessage("Please select a Set");
return "";
}
if (getExistingPersonInstitutions().size() > 0) {
newEntries = false;
} else {
newEntries = true;
}
try {
in = file.getInputstream();
DBFReader reader = new DBFReader(in);
if (!isCorrectDbfFile(reader)) {
JsfUtil.addErrorMessage("But the file you selected is not the correct file. Please make sure you selected the correct file named PYREMPMA.DBF. If you are sure that you selected the correct file, you may be using an old version.");
return "";
}
int numberOfFields = reader.getFieldCount();
System.out.println("Number of fields is " + numberOfFields);
for (int i = 0; i < numberOfFields; i++) {
DBFField field = reader.getField(i);
System.out.println("Data Field " + i + " is " + field.getName());
}
Object[] rowObjects;
newPersonInstitutions = new ArrayList<PersonInstitution>();
while ((rowObjects = reader.nextRecord()) != null) {
Person p = null;
PersonInstitution pi = new PersonInstitution();
Institution attachedIns;
String insName;
insName = rowObjects[21].toString() + " " + rowObjects[22].toString() + " " + rowObjects[23].toString();
if (insName.trim().equals("")) {
attachedIns = getInstitution();
} else {
attachedIns = findInstitution(insName);
}
temNic = rowObjects[48].toString();
if ("".equals(temNic.trim())) {
pi.setPerson(null);
} else {
p = getPerFacade().findFirstBySQL("select p from Person p where p.retired = false and p.nic = '" + temNic + "'");
if (p == null) {
p = new Person();
p.setCreatedAt(Calendar.getInstance().getTime());
p.setCreater(sessionController.getLoggedUser());
p.setInstitution(attachedIns);
p.setTitle(rowObjects[1].toString());
p.setInitials(rowObjects[3].toString());
p.setSurname(rowObjects[2].toString());
SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
try {
p.setDob(dateFormat.parse(rowObjects[7].toString()));
} catch (Exception e) {
p.setDob(null);
}
p.setNic(rowObjects[48].toString());
p.setName(p.getTitle() + " " + p.getInitials() + " " + p.getSurname());
getPerFacade().create(p);
} else {
if (p.getInstitution() != getInstitution()) {
markTransfer(p, p.getInstitution(), institution, pi);
}
}
}
pi.setPerson(p);
pi.setInstitution(attachedIns);
pi.setPayCentre(getInstitution());
pi.setNic(rowObjects[48].toString());
pi.setEmpNo(rowObjects[0].toString());
pi.setAddress1(rowObjects[18].toString());
pi.setAddress2(rowObjects[19].toString());
pi.setAddress3(rowObjects[20].toString());
pi.setOffAddress1(rowObjects[21].toString());
pi.setOffAddress2(rowObjects[22].toString());
pi.setOffAddress3(rowObjects[23].toString());
pi.setDesignation(findDesignation(rowObjects[8].toString()));
pi.setName(rowObjects[1].toString() + " " + rowObjects[2].toString() + " " + rowObjects[3].toString());
pi.setPayMonth(payMonth);
pi.setPayYear(payYear);
pi.setPaySet(insSet);
if (rowObjects[4].toString().equals("") || rowObjects[50].toString().equals("")) {
pi.setPermanent(Boolean.FALSE);
} else {
pi.setPermanent(Boolean.TRUE);
}
try {
if (Integer.valueOf(rowObjects[4].toString()) == 0) {
pi.setNopay(Boolean.TRUE);
} else {
}
} catch (Exception e) {
}
try {
pi.setActiveState((Boolean) rowObjects[40]);
} catch (Exception e) {
pi.setActiveState(true);
}
try {
pi.setNopay((Boolean) rowObjects[31]);
} catch (Exception e) {
pi.setNopay(false);
}
if (newEntries) {
getPiFacade().create(pi);
}
newPersonInstitutions.add(pi);
}
if (newEntries) {
JsfUtil.addSuccessMessage("Date in the file " + file.getFileName() + " recorded successfully. ");
newPersonInstitutions = new ArrayList<PersonInstitution>();
getSummeryCounts(newPersonInstitutions);
toGetRecordsagain = Boolean.TRUE;
} else {
JsfUtil.addSuccessMessage("Date in the file " + file.getFileName() + " is listed successfully. If you are satisfied, please click the Save button to permanantly save the new set of data Replacing the old ones under " + institution.getName() + ".");
toGetRecordsagain = Boolean.TRUE;
}
} catch (Exception e) {
System.out.println("Error " + e.getMessage());
}
return "";
}
|
diff --git a/waterken/remote/src/org/waterken/remote/http/Warning.java b/waterken/remote/src/org/waterken/remote/http/Warning.java
index 712a9b18..1b1b2697 100644
--- a/waterken/remote/src/org/waterken/remote/http/Warning.java
+++ b/waterken/remote/src/org/waterken/remote/http/Warning.java
@@ -1,22 +1,22 @@
// Copyright 2010 Waterken Inc. under the terms of the MIT X license
// found at http://www.opensource.org/licenses/mit-license.html
package org.waterken.remote.http;
import org.ref_send.deserializer;
import org.ref_send.promise.Failure;
/**
* Indicates an HTTP response contained a <code>Warning</code> header.
*/
public class
Warning extends Failure {
static private final long serialVersionUID = 1L;
/**
* Constructs an instance.
*/
public @deserializer
Warning() {
- super("400", "state response");
+ super("400", "stale response");
}
}
| true | true | Warning() {
super("400", "state response");
}
| Warning() {
super("400", "stale response");
}
|
diff --git a/cagwas/src/gov/nih/nci/cagwas/web/action/LoginAction.java b/cagwas/src/gov/nih/nci/cagwas/web/action/LoginAction.java
index 5840f84..6f3b5a9 100644
--- a/cagwas/src/gov/nih/nci/cagwas/web/action/LoginAction.java
+++ b/cagwas/src/gov/nih/nci/cagwas/web/action/LoginAction.java
@@ -1,144 +1,144 @@
package gov.nih.nci.cagwas.web.action;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.security.sasl.AuthenticationException;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.ActionMessage;
import org.apache.log4j.Logger;
import gov.nih.nci.cagwas.web.form.LoginForm;
import gov.nih.nci.caintegrator.security.SecurityManager;
import gov.nih.nci.caintegrator.security.UserCredentials;
import gov.nih.nci.security.authorization.domainobjects.ProtectionElement;
/**
* The LoginAction class is called when the login form posts. It is
* responsible for authenticating the user and getting its roles.
* <P>
* @author mholck
* @see org.apache.struts.action.Action
*/
public class LoginAction extends Action
{
private static Logger logger = Logger.getLogger(LoginAction.class);
private final String APPLICATION_CONTEXT = "cagwas";
/**
* execute is called when this action is posted to
* <P>
* @param mapping The ActionMapping for this action as configured in struts
* @param form The ActionForm that posted to this action if any
* @param request The HttpServletRequest for the current post
* @param response The HttpServletResponse for the current post
*/
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception
{
ActionMessages errors = new ActionMessages();
ActionForward forward = null;
// Figure out the state of the form
LoginForm lForm = (LoginForm)form;
String username = lForm.getUsername();
String password = lForm.getPassword();
logger.debug("Username is " + username);
SecurityManager securityManager = SecurityManager.getInstance(APPLICATION_CONTEXT);
UserCredentials credentials = null;
if (securityManager == null)
{
logger.error("Unable to get security manager for authentication");
errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.authentication"));
}
else
{
try
{
if(securityManager.authenticate(username, password))
{
credentials = securityManager.authorization(username);
}
}
catch (AuthenticationException e)
{
logger.debug(e);
}
if (credentials != null && credentials.authenticated())
{
// Now put the logged attribute in the session to signify they are logged in
request.getSession().setAttribute("logged", "yes");
request.getSession().setAttribute("name", username);
request.getSession().setAttribute("email", credentials.getEmailAddress());
Collection<ProtectionElement> protectionElements = credentials.getprotectionElements();
if(protectionElements != null && !protectionElements.isEmpty()){
List<String> studyIDList = new ArrayList<String>();
for(ProtectionElement pe:protectionElements){
- if(pe.getProtectionElementName().contains("caGWAS")){
+ if(pe.getProtectionElementId()!= null){
studyIDList.add(pe.getObjectId());
}
}
request.getSession().setAttribute("studyIDList", studyIDList);
}
}
else
{
errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.authentication"));
//request.getSession().invalidate();
}
}
// If there were errors then return to the input page else go on
if (!errors.isEmpty())
{
addErrors(request, errors);
forward = new ActionForward(mapping.getInput());
}
else
{
if(request.getSession().getAttribute("ref") != null)
{
String go = (String)request.getSession().getAttribute("ref");
request.getSession().removeAttribute("ref");
List studyIDs = (List)request.getSession().getAttribute("studyIDList");
Long studyId = (Long)request.getSession().getAttribute("studyId");
// must do this preprocessing before forwarding to make sure beans are in place
String logged = (String)request.getSession().getAttribute("logged");
if (logged != null && (logged.equals("yes") &&
studyId != null &&
studyIDs != null && studyIDs.contains(studyId.toString())))
{
BrowseAction brac = new BrowseAction();
// Setting up genotypes will get everything for subjects too
brac.setupGenotype(request);
// make a new forward with the orig referer as the new path
forward = new ActionForward(go, false);
}
else{
forward = mapping.findForward("accessWarning");
}
}
else
{
forward = mapping.findForward("success");
}
}
return forward;
}
}
| true | true | public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception
{
ActionMessages errors = new ActionMessages();
ActionForward forward = null;
// Figure out the state of the form
LoginForm lForm = (LoginForm)form;
String username = lForm.getUsername();
String password = lForm.getPassword();
logger.debug("Username is " + username);
SecurityManager securityManager = SecurityManager.getInstance(APPLICATION_CONTEXT);
UserCredentials credentials = null;
if (securityManager == null)
{
logger.error("Unable to get security manager for authentication");
errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.authentication"));
}
else
{
try
{
if(securityManager.authenticate(username, password))
{
credentials = securityManager.authorization(username);
}
}
catch (AuthenticationException e)
{
logger.debug(e);
}
if (credentials != null && credentials.authenticated())
{
// Now put the logged attribute in the session to signify they are logged in
request.getSession().setAttribute("logged", "yes");
request.getSession().setAttribute("name", username);
request.getSession().setAttribute("email", credentials.getEmailAddress());
Collection<ProtectionElement> protectionElements = credentials.getprotectionElements();
if(protectionElements != null && !protectionElements.isEmpty()){
List<String> studyIDList = new ArrayList<String>();
for(ProtectionElement pe:protectionElements){
if(pe.getProtectionElementName().contains("caGWAS")){
studyIDList.add(pe.getObjectId());
}
}
request.getSession().setAttribute("studyIDList", studyIDList);
}
}
else
{
errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.authentication"));
//request.getSession().invalidate();
}
}
// If there were errors then return to the input page else go on
if (!errors.isEmpty())
{
addErrors(request, errors);
forward = new ActionForward(mapping.getInput());
}
else
{
if(request.getSession().getAttribute("ref") != null)
{
String go = (String)request.getSession().getAttribute("ref");
request.getSession().removeAttribute("ref");
List studyIDs = (List)request.getSession().getAttribute("studyIDList");
Long studyId = (Long)request.getSession().getAttribute("studyId");
// must do this preprocessing before forwarding to make sure beans are in place
String logged = (String)request.getSession().getAttribute("logged");
if (logged != null && (logged.equals("yes") &&
studyId != null &&
studyIDs != null && studyIDs.contains(studyId.toString())))
{
BrowseAction brac = new BrowseAction();
// Setting up genotypes will get everything for subjects too
brac.setupGenotype(request);
// make a new forward with the orig referer as the new path
forward = new ActionForward(go, false);
}
else{
forward = mapping.findForward("accessWarning");
}
}
else
{
forward = mapping.findForward("success");
}
}
return forward;
}
| public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception
{
ActionMessages errors = new ActionMessages();
ActionForward forward = null;
// Figure out the state of the form
LoginForm lForm = (LoginForm)form;
String username = lForm.getUsername();
String password = lForm.getPassword();
logger.debug("Username is " + username);
SecurityManager securityManager = SecurityManager.getInstance(APPLICATION_CONTEXT);
UserCredentials credentials = null;
if (securityManager == null)
{
logger.error("Unable to get security manager for authentication");
errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.authentication"));
}
else
{
try
{
if(securityManager.authenticate(username, password))
{
credentials = securityManager.authorization(username);
}
}
catch (AuthenticationException e)
{
logger.debug(e);
}
if (credentials != null && credentials.authenticated())
{
// Now put the logged attribute in the session to signify they are logged in
request.getSession().setAttribute("logged", "yes");
request.getSession().setAttribute("name", username);
request.getSession().setAttribute("email", credentials.getEmailAddress());
Collection<ProtectionElement> protectionElements = credentials.getprotectionElements();
if(protectionElements != null && !protectionElements.isEmpty()){
List<String> studyIDList = new ArrayList<String>();
for(ProtectionElement pe:protectionElements){
if(pe.getProtectionElementId()!= null){
studyIDList.add(pe.getObjectId());
}
}
request.getSession().setAttribute("studyIDList", studyIDList);
}
}
else
{
errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.authentication"));
//request.getSession().invalidate();
}
}
// If there were errors then return to the input page else go on
if (!errors.isEmpty())
{
addErrors(request, errors);
forward = new ActionForward(mapping.getInput());
}
else
{
if(request.getSession().getAttribute("ref") != null)
{
String go = (String)request.getSession().getAttribute("ref");
request.getSession().removeAttribute("ref");
List studyIDs = (List)request.getSession().getAttribute("studyIDList");
Long studyId = (Long)request.getSession().getAttribute("studyId");
// must do this preprocessing before forwarding to make sure beans are in place
String logged = (String)request.getSession().getAttribute("logged");
if (logged != null && (logged.equals("yes") &&
studyId != null &&
studyIDs != null && studyIDs.contains(studyId.toString())))
{
BrowseAction brac = new BrowseAction();
// Setting up genotypes will get everything for subjects too
brac.setupGenotype(request);
// make a new forward with the orig referer as the new path
forward = new ActionForward(go, false);
}
else{
forward = mapping.findForward("accessWarning");
}
}
else
{
forward = mapping.findForward("success");
}
}
return forward;
}
|
diff --git a/disambiguation-author/src/main/java/pl/edu/icm/coansys/disambiguation/author/benchmark/TimerSyso.java b/disambiguation-author/src/main/java/pl/edu/icm/coansys/disambiguation/author/benchmark/TimerSyso.java
index 3300783e..7d3b5829 100644
--- a/disambiguation-author/src/main/java/pl/edu/icm/coansys/disambiguation/author/benchmark/TimerSyso.java
+++ b/disambiguation-author/src/main/java/pl/edu/icm/coansys/disambiguation/author/benchmark/TimerSyso.java
@@ -1,79 +1,79 @@
/*
* This file is part of CoAnSys project.
* Copyright (c) 20012-2013 ICM-UW
*
* CoAnSys is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* CoAnSys is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CoAnSys. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.coansys.disambiguation.author.benchmark;
import org.slf4j.LoggerFactory;
public class TimerSyso implements Runnable {
private long start;
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(Timer.class);
public TimerSyso() {
logger.info( "Writing statistics into standard output." );
}
private long currentTime() {
return System.nanoTime();
}
@Override
public void run() {
}
public void play() {
start = currentTime(); //nano time
}
public void stop( Object...monits ) {
addCheckpoint( monits );
start = -1;
}
public void addMonit( Object...monits ) {
StringBuffer monit = new StringBuffer();
for ( Object o : monits ) {
monit.append( o.toString() );
monit.append("\t");
}
System.out.println( monit.toString() );
}
public void addCheckpoint( Object...monits ) {
long t = currentTime() - start;
Object[] nm = new Object[ monits.length + 1 ];
boolean isTimeAdded = false;
for ( int i = 0; i < monits.length; i++ ) {
if ( monits[i].equals("#time") ) {
nm[i] = t;
isTimeAdded = true;
} else {
nm[i] = monits[i];
}
}
if( !isTimeAdded ) {
- nm[ monits.length ] = (t / 60.0);
+ nm[ monits.length ] = (t / 1000000000.0); //in sec
}
addMonit( nm );
}
}
| true | true | public void addCheckpoint( Object...monits ) {
long t = currentTime() - start;
Object[] nm = new Object[ monits.length + 1 ];
boolean isTimeAdded = false;
for ( int i = 0; i < monits.length; i++ ) {
if ( monits[i].equals("#time") ) {
nm[i] = t;
isTimeAdded = true;
} else {
nm[i] = monits[i];
}
}
if( !isTimeAdded ) {
nm[ monits.length ] = (t / 60.0);
}
addMonit( nm );
}
| public void addCheckpoint( Object...monits ) {
long t = currentTime() - start;
Object[] nm = new Object[ monits.length + 1 ];
boolean isTimeAdded = false;
for ( int i = 0; i < monits.length; i++ ) {
if ( monits[i].equals("#time") ) {
nm[i] = t;
isTimeAdded = true;
} else {
nm[i] = monits[i];
}
}
if( !isTimeAdded ) {
nm[ monits.length ] = (t / 1000000000.0); //in sec
}
addMonit( nm );
}
|
diff --git a/courses/app/controllers/Students.java b/courses/app/controllers/Students.java
index fada721..d728a6b 100644
--- a/courses/app/controllers/Students.java
+++ b/courses/app/controllers/Students.java
@@ -1,174 +1,174 @@
package controllers;
import play.*;
import play.mvc.*;
import java.util.*;
import models.*;
import views.html.*;
import play.data.Form;
@Security.Authenticated(Secured.class)
public class Students extends Controller {
static Form<Course> courseForm = form(Course.class);
public static Result index() {
return redirect(routes.Students.studyplan());
}
public static Result addToStudyPlan(Long idCourse, Long idStudent) {
UserCredentials uc = UserCredentials.find.where().eq("userName",request().username()).findUnique();
if (Secured.isStudent(uc))
{
Student s = uc.getStudent();
s.addToStudyPlan(idCourse);
return redirect(
routes.Students.index());
}
else if (Secured.isAdmin(uc))
{
Student s = Student.find.byId(idStudent);
s.addToStudyPlan(idCourse);
return redirect(
routes.Admins.studentDetails(idStudent));
}
else
return unauthorized(forbidden.render());
}
public static Result rmFromStudyPlan(Long idCourse, Long idStudent) {
UserCredentials uc = UserCredentials.find.where().eq("userName",request().username()).findUnique();
if (Secured.isStudent(uc))
{
Student s = uc.getStudent();
s.rmFromStudyPlan(idCourse);
return redirect(
routes.Students.index());
}
else if (Secured.isAdmin(uc))
{
Student s = Student.find.byId(idStudent);
s.rmFromStudyPlan(idCourse);
return redirect(
routes.Admins.studentDetails(idStudent));
}
else
return unauthorized(forbidden.render());
}
public static Result studyplan() {
return Students.studyplan(courseForm,false,"");
}
public static Result studyplan(Form<Course> form, boolean badRequest, String appreqMsg) {
String username = request().username();
UserCredentials uc = UserCredentials.find.where().eq("userName",request().username()).findUnique();
if (Secured.isStudent(uc))
{
Student student = uc.getStudent();
List<Course> studyPlan = student.getStudyPlan();
List<Course> coursesNotInSp = new ArrayList();
for (Course c: Course.currentCourses())
if (!studyPlan.contains(c))
coursesNotInSp.add(c);
if (badRequest)
return badRequest(students_studyplans.render(uc,student,studyPlan, coursesNotInSp, form, appreqMsg));
else
return ok(students_studyplans.render(uc,student,studyPlan, coursesNotInSp, form, appreqMsg));
}
else
{
return unauthorized(forbidden.render());
}
}
public static Result career() {
String username = request().username();
UserCredentials uc = UserCredentials.find.where().eq("userName",request().username()).findUnique();
if (Secured.isStudent(uc))
{
Student student = uc.getStudent();
List<CourseEnrollment> career = student.getEnrollmentsCareer();
return ok(students_careers.render(uc, career));
}
else
{
return unauthorized(forbidden.render());
}
}
public static Result appreq() {
String username = request().username();
UserCredentials uc = UserCredentials.find.where().eq("userName",request().username()).findUnique();
if (Secured.isStudent(uc))
{
Student student = uc.getStudent();
if (student.isStudyPlanOk())
{
student.approvalRequest();
//send email
- String body = "";
+ String body = "I've defined my study plan. Please check it!\n\n";
String subject = "Request for study plan APPROVAL";
String msg = SecuredApplication.emailMeNow(student.currentAdvisor.email,body,subject,student.email);
return Students.studyplan(courseForm,false,msg);
}
else
{
String msg = student.checkStudyPlan();
return Students.studyplan(courseForm,false,msg);
}
}
else
{
return unauthorized(forbidden.render());
}
}
public static Result newExternCourse() {
Form<Course> filledForm = courseForm.bindFromRequest();
UserCredentials uc = UserCredentials.find.where().eq("userName",request().username()).findUnique();
if (Secured.isStudent(uc))
{
if (filledForm.hasErrors())
{
return Students.studyplan(filledForm,true,"");
}
else
{
Course newcourse = filledForm.get();
newcourse.academicYear = Course.AcademicYear();
newcourse.credits = 3;
newcourse.isInManifesto = false;
newcourse.notes = "external course";
newcourse.isbyUNITN = false;
newcourse.deleted = false;
Course.create(newcourse);
Students.addToStudyPlan(newcourse.courseID.longValue(),uc.getStudent().userID.longValue());
return redirect(routes.Students.studyplan());
}
}
else
{
return unauthorized(forbidden.render());
}
}
public static Result modifyStudyplan() {
UserCredentials uc = UserCredentials.find.where().eq("userName",request().username()).findUnique();
if (Secured.isStudent(uc))
{
uc.getStudent().rejectSP();
return studyplan() ;
}
else
{
return unauthorized(forbidden.render());
}
}
}
| true | true | public static Result appreq() {
String username = request().username();
UserCredentials uc = UserCredentials.find.where().eq("userName",request().username()).findUnique();
if (Secured.isStudent(uc))
{
Student student = uc.getStudent();
if (student.isStudyPlanOk())
{
student.approvalRequest();
//send email
String body = "";
String subject = "Request for study plan APPROVAL";
String msg = SecuredApplication.emailMeNow(student.currentAdvisor.email,body,subject,student.email);
return Students.studyplan(courseForm,false,msg);
}
else
{
String msg = student.checkStudyPlan();
return Students.studyplan(courseForm,false,msg);
}
}
else
{
return unauthorized(forbidden.render());
}
}
| public static Result appreq() {
String username = request().username();
UserCredentials uc = UserCredentials.find.where().eq("userName",request().username()).findUnique();
if (Secured.isStudent(uc))
{
Student student = uc.getStudent();
if (student.isStudyPlanOk())
{
student.approvalRequest();
//send email
String body = "I've defined my study plan. Please check it!\n\n";
String subject = "Request for study plan APPROVAL";
String msg = SecuredApplication.emailMeNow(student.currentAdvisor.email,body,subject,student.email);
return Students.studyplan(courseForm,false,msg);
}
else
{
String msg = student.checkStudyPlan();
return Students.studyplan(courseForm,false,msg);
}
}
else
{
return unauthorized(forbidden.render());
}
}
|
diff --git a/VCC/exportGrammar/src/de/hszg/atocc/vcc/export/grammar/internal/ExportGrammar.java b/VCC/exportGrammar/src/de/hszg/atocc/vcc/export/grammar/internal/ExportGrammar.java
index 01ead9f..8ef4c9a 100644
--- a/VCC/exportGrammar/src/de/hszg/atocc/vcc/export/grammar/internal/ExportGrammar.java
+++ b/VCC/exportGrammar/src/de/hszg/atocc/vcc/export/grammar/internal/ExportGrammar.java
@@ -1,80 +1,80 @@
package de.hszg.atocc.vcc.export.grammar.internal;
import javax.xml.xpath.XPathExpressionException;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import de.hszg.atocc.core.util.AbstractXmlTransformationService;
import de.hszg.atocc.core.util.GrammarService;
import de.hszg.atocc.core.util.SerializationException;
import de.hszg.atocc.core.util.XmlTransformationException;
import de.hszg.atocc.core.util.XmlUtilService;
import de.hszg.atocc.core.util.XmlValidationException;
import de.hszg.atocc.core.util.grammar.Grammar;
public class ExportGrammar extends AbstractXmlTransformationService {
private XmlUtilService xmlUtils;
private GrammarService grammarUtils;
private Grammar grammar = new Grammar();
@Override
protected void transform() throws XmlTransformationException {
tryToGetRequiredServices();
try {
validateInput("COMPILER");
final NodeList lhsElements = xmlUtils.extractNodes(getInput(), "//RULES/RULE");
for (int i = 0; i < lhsElements.getLength(); ++i) {
final Element lhsElement = (Element) lhsElements.item(i);
final String lhs = lhsElement.getAttribute("name");
- final NodeList rhsElements = xmlUtils.extractNodes(lhsElement, "//RIGHTSIDE");
+ final NodeList rhsElements = xmlUtils.extractNodes(lhsElement, "RIGHTSIDE");
for(int j = 0; j < rhsElements.getLength(); ++j) {
final Element rhsElement = (Element) rhsElements.item(j);
String rhs = "";
final NodeList childNodes = rhsElement.getChildNodes();
for(int k = 0; k < childNodes.getLength(); ++k) {
final Node child = childNodes.item(k);
if(child.getNodeType() == Node.ELEMENT_NODE) {
final Element partElement = (Element) child;
rhs += partElement.getAttribute("name") + " ";
}
}
grammar.appendRule(lhs, rhs.trim());
}
}
} catch (XmlValidationException e) {
throw new XmlTransformationException("ExportGrammar|INVALID_INPUT", e);
} catch (XPathExpressionException e) {
throw new XmlTransformationException("ExportGrammar|XPATH_ERROR", e);
}
try {
setOutput(grammarUtils.grammarToXml(grammar));
validateOutput("GRAMMAR");
} catch (XmlValidationException e) {
throw new XmlTransformationException("ExportGrammar|INVALID_OUTPUT", e);
} catch (SerializationException e) {
throw new XmlTransformationException("ExportGrammar|SERIALIZATION_FAILED", e);
}
}
private void tryToGetRequiredServices() {
xmlUtils = getService(XmlUtilService.class);
grammarUtils = getService(GrammarService.class);
}
}
| true | true | protected void transform() throws XmlTransformationException {
tryToGetRequiredServices();
try {
validateInput("COMPILER");
final NodeList lhsElements = xmlUtils.extractNodes(getInput(), "//RULES/RULE");
for (int i = 0; i < lhsElements.getLength(); ++i) {
final Element lhsElement = (Element) lhsElements.item(i);
final String lhs = lhsElement.getAttribute("name");
final NodeList rhsElements = xmlUtils.extractNodes(lhsElement, "//RIGHTSIDE");
for(int j = 0; j < rhsElements.getLength(); ++j) {
final Element rhsElement = (Element) rhsElements.item(j);
String rhs = "";
final NodeList childNodes = rhsElement.getChildNodes();
for(int k = 0; k < childNodes.getLength(); ++k) {
final Node child = childNodes.item(k);
if(child.getNodeType() == Node.ELEMENT_NODE) {
final Element partElement = (Element) child;
rhs += partElement.getAttribute("name") + " ";
}
}
grammar.appendRule(lhs, rhs.trim());
}
}
} catch (XmlValidationException e) {
throw new XmlTransformationException("ExportGrammar|INVALID_INPUT", e);
} catch (XPathExpressionException e) {
throw new XmlTransformationException("ExportGrammar|XPATH_ERROR", e);
}
try {
setOutput(grammarUtils.grammarToXml(grammar));
validateOutput("GRAMMAR");
} catch (XmlValidationException e) {
throw new XmlTransformationException("ExportGrammar|INVALID_OUTPUT", e);
} catch (SerializationException e) {
throw new XmlTransformationException("ExportGrammar|SERIALIZATION_FAILED", e);
}
}
| protected void transform() throws XmlTransformationException {
tryToGetRequiredServices();
try {
validateInput("COMPILER");
final NodeList lhsElements = xmlUtils.extractNodes(getInput(), "//RULES/RULE");
for (int i = 0; i < lhsElements.getLength(); ++i) {
final Element lhsElement = (Element) lhsElements.item(i);
final String lhs = lhsElement.getAttribute("name");
final NodeList rhsElements = xmlUtils.extractNodes(lhsElement, "RIGHTSIDE");
for(int j = 0; j < rhsElements.getLength(); ++j) {
final Element rhsElement = (Element) rhsElements.item(j);
String rhs = "";
final NodeList childNodes = rhsElement.getChildNodes();
for(int k = 0; k < childNodes.getLength(); ++k) {
final Node child = childNodes.item(k);
if(child.getNodeType() == Node.ELEMENT_NODE) {
final Element partElement = (Element) child;
rhs += partElement.getAttribute("name") + " ";
}
}
grammar.appendRule(lhs, rhs.trim());
}
}
} catch (XmlValidationException e) {
throw new XmlTransformationException("ExportGrammar|INVALID_INPUT", e);
} catch (XPathExpressionException e) {
throw new XmlTransformationException("ExportGrammar|XPATH_ERROR", e);
}
try {
setOutput(grammarUtils.grammarToXml(grammar));
validateOutput("GRAMMAR");
} catch (XmlValidationException e) {
throw new XmlTransformationException("ExportGrammar|INVALID_OUTPUT", e);
} catch (SerializationException e) {
throw new XmlTransformationException("ExportGrammar|SERIALIZATION_FAILED", e);
}
}
|
diff --git a/src/main/java/edu/illinois/ncsa/versus/store/DiskFileProcessor.java b/src/main/java/edu/illinois/ncsa/versus/store/DiskFileProcessor.java
index ad4c98b..90d4b3f 100644
--- a/src/main/java/edu/illinois/ncsa/versus/store/DiskFileProcessor.java
+++ b/src/main/java/edu/illinois/ncsa/versus/store/DiskFileProcessor.java
@@ -1,92 +1,92 @@
/**
*
*/
package edu.illinois.ncsa.versus.store;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import java.util.UUID;
import edu.illinois.ncsa.versus.restlet.PropertiesUtil;
/**
* Disk based file storage.
*
* @author Luigi Marini <[email protected]>
*
*/
public class DiskFileProcessor implements FileProcessor {
private String directory;
public DiskFileProcessor() {
Properties properties;
try {
properties = PropertiesUtil.load();
String location = properties.getProperty("file.directory");
if (location != null) {
directory = location;
} else {
directory = System.getProperty("java.io.tmpdir");
}
//System.out.println("Storing file in " + directory);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public String addFile(InputStream inputStream, String filename) {
try {
File file;
File ff = new File(directory);
if (filename == null) {
file = File.createTempFile("versus", ".tmp", ff);
} else {
int idx = filename.lastIndexOf(".");
if (idx != -1) {
file = File.createTempFile(filename.substring(0, idx), filename.substring(idx), ff);
} else {
file = File.createTempFile(filename, ".tmp", ff);
}
}
OutputStream out = new FileOutputStream(file);
byte buf[] = new byte[1024];
int len;
while ((len = inputStream.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.close();
inputStream.close();
return file.getName();
} catch (FileNotFoundException e) {
- // TODO Auto-generated catch block
+ System.err.println("Upload directory not found: " + directory);
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}
@Override
public InputStream getFile(String id) {
File file = new File(directory, id);
System.out.println("Reading file " + file);
try {
return new FileInputStream(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
| true | true | public String addFile(InputStream inputStream, String filename) {
try {
File file;
File ff = new File(directory);
if (filename == null) {
file = File.createTempFile("versus", ".tmp", ff);
} else {
int idx = filename.lastIndexOf(".");
if (idx != -1) {
file = File.createTempFile(filename.substring(0, idx), filename.substring(idx), ff);
} else {
file = File.createTempFile(filename, ".tmp", ff);
}
}
OutputStream out = new FileOutputStream(file);
byte buf[] = new byte[1024];
int len;
while ((len = inputStream.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.close();
inputStream.close();
return file.getName();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}
| public String addFile(InputStream inputStream, String filename) {
try {
File file;
File ff = new File(directory);
if (filename == null) {
file = File.createTempFile("versus", ".tmp", ff);
} else {
int idx = filename.lastIndexOf(".");
if (idx != -1) {
file = File.createTempFile(filename.substring(0, idx), filename.substring(idx), ff);
} else {
file = File.createTempFile(filename, ".tmp", ff);
}
}
OutputStream out = new FileOutputStream(file);
byte buf[] = new byte[1024];
int len;
while ((len = inputStream.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.close();
inputStream.close();
return file.getName();
} catch (FileNotFoundException e) {
System.err.println("Upload directory not found: " + directory);
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}
|
diff --git a/user/src/com/google/gwt/user/cellview/client/AbstractHasData.java b/user/src/com/google/gwt/user/cellview/client/AbstractHasData.java
index 08482a3bf..0ea1b6d84 100644
--- a/user/src/com/google/gwt/user/cellview/client/AbstractHasData.java
+++ b/user/src/com/google/gwt/user/cellview/client/AbstractHasData.java
@@ -1,1255 +1,1255 @@
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.gwt.user.cellview.client;
import com.google.gwt.cell.client.Cell;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.dom.client.BrowserEvents;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.EventTarget;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.dom.client.Style.Display;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.EventHandler;
import com.google.gwt.event.shared.GwtEvent.Type;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.user.cellview.client.LoadingStateChangeEvent.LoadingState;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Focusable;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.impl.FocusImpl;
import com.google.gwt.view.client.CellPreviewEvent;
import com.google.gwt.view.client.DefaultSelectionEventManager;
import com.google.gwt.view.client.HasData;
import com.google.gwt.view.client.HasKeyProvider;
import com.google.gwt.view.client.ProvidesKey;
import com.google.gwt.view.client.Range;
import com.google.gwt.view.client.RangeChangeEvent;
import com.google.gwt.view.client.RowCountChangeEvent;
import com.google.gwt.view.client.SelectionModel;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* An abstract {@link Widget} that implements {@link HasData}.
*
* @param <T> the data type of each row
*/
public abstract class AbstractHasData<T> extends Composite implements HasData<T>,
HasKeyProvider<T>, Focusable, HasKeyboardPagingPolicy {
/**
* Default implementation of a keyboard navigation handler.
*
* @param <T> the data type of each row
*/
public static class DefaultKeyboardSelectionHandler<T> implements CellPreviewEvent.Handler<T> {
/**
* The number of rows to jump when PAGE_UP or PAGE_DOWN is pressed and the
* {@link HasKeyboardPagingPolicy.KeyboardPagingPolicy} is
* {@link HasKeyboardPagingPolicy.KeyboardPagingPolicy#INCREASE_RANGE}.
*/
private static final int PAGE_INCREMENT = 30;
private final AbstractHasData<T> display;
/**
* Construct a new keyboard selection handler for the specified view.
*
* @param display the display being handled
*/
public DefaultKeyboardSelectionHandler(AbstractHasData<T> display) {
this.display = display;
}
public AbstractHasData<T> getDisplay() {
return display;
}
@Override
public void onCellPreview(CellPreviewEvent<T> event) {
NativeEvent nativeEvent = event.getNativeEvent();
String eventType = event.getNativeEvent().getType();
if (BrowserEvents.KEYDOWN.equals(eventType) && !event.isCellEditing()) {
/*
* Handle keyboard navigation, unless the cell is being edited. If the
* cell is being edited, we do not want to change rows.
*
* Prevent default on navigation events to prevent default scrollbar
* behavior.
*/
switch (nativeEvent.getKeyCode()) {
case KeyCodes.KEY_DOWN:
nextRow();
handledEvent(event);
return;
case KeyCodes.KEY_UP:
prevRow();
handledEvent(event);
return;
case KeyCodes.KEY_PAGEDOWN:
nextPage();
handledEvent(event);
return;
case KeyCodes.KEY_PAGEUP:
prevPage();
handledEvent(event);
return;
case KeyCodes.KEY_HOME:
home();
handledEvent(event);
return;
case KeyCodes.KEY_END:
end();
handledEvent(event);
return;
case 32:
// Prevent the list box from scrolling.
handledEvent(event);
return;
}
} else if (BrowserEvents.CLICK.equals(eventType)) {
/*
* Move keyboard focus to the clicked row, even if the Cell is being
* edited. Unlike key events, we aren't moving the currently selected
* row, just updating it based on where the user clicked.
*/
int relRow = event.getIndex() - display.getPageStart();
// If a natively focusable element was just clicked, then do not steal
// focus.
boolean isFocusable = false;
Element target = Element.as(event.getNativeEvent().getEventTarget());
isFocusable = CellBasedWidgetImpl.get().isFocusable(target);
display.setKeyboardSelectedRow(relRow, !isFocusable);
// Do not cancel the event as the click may have occurred on a Cell.
} else if (BrowserEvents.FOCUS.equals(eventType)) {
// Move keyboard focus to match the currently focused element.
int relRow = event.getIndex() - display.getPageStart();
if (display.getKeyboardSelectedRow() != relRow) {
// Do not steal focus as this was a focus event.
- display.setKeyboardSelectedRow(event.getIndex(), false);
+ display.setKeyboardSelectedRow(relRow, false);
// Do not cancel the event as the click may have occurred on a Cell.
return;
}
}
}
// Visible for testing.
void end() {
setKeyboardSelectedRow(display.getRowCount() - 1);
}
void handledEvent(CellPreviewEvent<?> event) {
event.setCanceled(true);
event.getNativeEvent().preventDefault();
}
// Visible for testing.
void home() {
setKeyboardSelectedRow(-display.getPageStart());
}
// Visible for testing.
void nextPage() {
KeyboardPagingPolicy keyboardPagingPolicy = display.getKeyboardPagingPolicy();
if (KeyboardPagingPolicy.CHANGE_PAGE == keyboardPagingPolicy) {
// 0th index of next page.
setKeyboardSelectedRow(display.getPageSize());
} else if (KeyboardPagingPolicy.INCREASE_RANGE == keyboardPagingPolicy) {
setKeyboardSelectedRow(display.getKeyboardSelectedRow() + PAGE_INCREMENT);
}
}
// Visible for testing.
void nextRow() {
setKeyboardSelectedRow(display.getKeyboardSelectedRow() + 1);
}
// Visible for testing.
void prevPage() {
KeyboardPagingPolicy keyboardPagingPolicy = display.getKeyboardPagingPolicy();
if (KeyboardPagingPolicy.CHANGE_PAGE == keyboardPagingPolicy) {
// 0th index of previous page.
setKeyboardSelectedRow(-display.getPageSize());
} else if (KeyboardPagingPolicy.INCREASE_RANGE == keyboardPagingPolicy) {
setKeyboardSelectedRow(display.getKeyboardSelectedRow() - PAGE_INCREMENT);
}
}
// Visible for testing.
void prevRow() {
setKeyboardSelectedRow(display.getKeyboardSelectedRow() - 1);
}
// Visible for testing.
void setKeyboardSelectedRow(int row) {
display.setKeyboardSelectedRow(row, true);
}
}
/**
* Implementation of {@link HasDataPresenter.View} used by this widget.
*
* @param <T> the data type of the view
*/
private static class View<T> implements HasDataPresenter.View<T> {
private final AbstractHasData<T> hasData;
private boolean wasFocused;
public View(AbstractHasData<T> hasData) {
this.hasData = hasData;
}
@Override
public <H extends EventHandler> HandlerRegistration addHandler(H handler, Type<H> type) {
return hasData.addHandler(handler, type);
}
@Override
public void replaceAllChildren(List<T> values, SelectionModel<? super T> selectionModel,
boolean stealFocus) {
SafeHtml html = renderRowValues(values, hasData.getPageStart(), selectionModel);
// Removing elements can fire a blur event, which we ignore.
hasData.isFocused = hasData.isFocused || stealFocus;
wasFocused = hasData.isFocused;
hasData.isRefreshing = true;
hasData.replaceAllChildren(values, html);
hasData.isRefreshing = false;
// Ensure that the keyboard selected element is focusable.
Element elem = hasData.getKeyboardSelectedElement();
if (elem != null) {
hasData.setFocusable(elem, true);
if (hasData.isFocused) {
hasData.onFocus();
}
}
fireValueChangeEvent();
}
@Override
public void replaceChildren(List<T> values, int start,
SelectionModel<? super T> selectionModel, boolean stealFocus) {
SafeHtml html = renderRowValues(values, hasData.getPageStart() + start, selectionModel);
// Removing elements can fire a blur event, which we ignore.
hasData.isFocused = hasData.isFocused || stealFocus;
wasFocused = hasData.isFocused;
hasData.isRefreshing = true;
hasData.replaceChildren(values, start, html);
hasData.isRefreshing = false;
// Ensure that the keyboard selected element is focusable.
Element elem = hasData.getKeyboardSelectedElement();
if (elem != null) {
hasData.setFocusable(elem, true);
if (hasData.isFocused) {
hasData.onFocus();
}
}
fireValueChangeEvent();
}
@Override
public void resetFocus() {
if (wasFocused) {
CellBasedWidgetImpl.get().resetFocus(new Scheduler.ScheduledCommand() {
@Override
public void execute() {
if (!hasData.resetFocusOnCell()) {
Element elem = hasData.getKeyboardSelectedElement();
if (elem != null) {
elem.focus();
}
}
}
});
}
}
@Override
public void setKeyboardSelected(int index, boolean seleted, boolean stealFocus) {
hasData.isFocused = hasData.isFocused || stealFocus;
hasData.setKeyboardSelected(index, seleted, stealFocus);
}
@Override
public void setLoadingState(LoadingState state) {
hasData.isRefreshing = true;
hasData.onLoadingStateChanged(state);
hasData.isRefreshing = false;
}
/**
* Fire a value change event.
*/
private void fireValueChangeEvent() {
// Use an anonymous class to override ValueChangeEvents's protected
// constructor. We can't call ValueChangeEvent.fire() because this class
// doesn't implement HasValueChangeHandlers.
hasData.fireEvent(new ValueChangeEvent<List<T>>(hasData.getVisibleItems()) {
});
}
/**
* Render a list of row values.
*
* @param values the row values
* @param start the absolute start index of the values
* @param selectionModel the {@link SelectionModel}
* @return null, unless the implementation renders using SafeHtml
*/
private SafeHtml renderRowValues(List<T> values, int start,
SelectionModel<? super T> selectionModel) {
try {
SafeHtmlBuilder sb = new SafeHtmlBuilder();
hasData.renderRowValues(sb, values, start, selectionModel);
return sb.toSafeHtml();
} catch (UnsupportedOperationException e) {
// If renderRowValues throws, the implementation will render directly in
// the replaceChildren method.
return null;
}
}
}
/**
* The temporary element use to convert HTML to DOM.
*/
private static com.google.gwt.user.client.Element tmpElem;
/**
* Convenience method to convert the specified HTML into DOM elements and
* return the parent of the DOM elements.
*
* @param html the HTML to convert
* @param tmpElem a temporary element
* @return the parent element
*/
static Element convertToElements(Widget widget, com.google.gwt.user.client.Element tmpElem,
SafeHtml html) {
// Attach an event listener so we can catch synchronous load events from
// cached images.
DOM.setEventListener(tmpElem, widget);
tmpElem.setInnerSafeHtml(html);
// Detach the event listener.
DOM.setEventListener(tmpElem, null);
return tmpElem;
}
/**
* Convenience method to replace all children of a Widget.
*
* @param widget the widget who's contents will be replaced
* @param childContainer the container that holds the contents
* @param html the html to set
*/
static void replaceAllChildren(Widget widget, Element childContainer, SafeHtml html) {
// If the widget is not attached, attach an event listener so we can catch
// synchronous load events from cached images.
if (!widget.isAttached()) {
DOM.setEventListener(widget.getElement(), widget);
}
// Render the HTML.
childContainer.setInnerSafeHtml(CellBasedWidgetImpl.get().processHtml(html));
// Detach the event listener.
if (!widget.isAttached()) {
DOM.setEventListener(widget.getElement(), null);
}
}
/**
* Convenience method to convert the specified HTML into DOM elements and
* replace the existing elements starting at the specified index. If the
* number of children specified exceeds the existing number of children, the
* remaining children should be appended.
*
* @param widget the widget who's contents will be replaced
* @param childContainer the container that holds the contents
* @param newChildren an element containing the new children
* @param start the start index to replace
* @param html the HTML to convert
*/
static void replaceChildren(Widget widget, Element childContainer, Element newChildren,
int start, SafeHtml html) {
// Get the first element to be replaced.
int childCount = childContainer.getChildCount();
Element toReplace = null;
if (start < childCount) {
toReplace = childContainer.getChild(start).cast();
}
// Replace the elements.
int count = newChildren.getChildCount();
for (int i = 0; i < count; i++) {
if (toReplace == null) {
// The child will be removed from tmpElem, so always use index 0.
childContainer.appendChild(newChildren.getChild(0));
} else {
Element nextSibling = toReplace.getNextSiblingElement();
childContainer.replaceChild(newChildren.getChild(0), toReplace);
toReplace = nextSibling;
}
}
}
/**
* Return the temporary element used to create elements.
*/
private static com.google.gwt.user.client.Element getTmpElem() {
if (tmpElem == null) {
tmpElem = Document.get().createDivElement().cast();
}
return tmpElem;
}
/**
* A boolean indicating that the widget has focus.
*/
boolean isFocused;
private char accessKey = 0;
/**
* A boolean indicating that the widget is refreshing, so all events should be
* ignored.
*/
private boolean isRefreshing;
private final HasDataPresenter<T> presenter;
private HandlerRegistration keyboardSelectionReg;
private HandlerRegistration selectionManagerReg;
private int tabIndex;
/**
* Constructs an {@link AbstractHasData} with the given page size.
*
* @param elem the parent {@link Element}
* @param pageSize the page size
* @param keyProvider the key provider, or null
*/
public AbstractHasData(final Element elem, final int pageSize, final ProvidesKey<T> keyProvider) {
this(new Widget() {
{
setElement(elem);
}
}, pageSize, keyProvider);
}
/**
* Constructs an {@link AbstractHasData} with the given page size.
*
* @param widget the parent {@link Widget}
* @param pageSize the page size
* @param keyProvider the key provider, or null
*/
public AbstractHasData(Widget widget, final int pageSize, final ProvidesKey<T> keyProvider) {
initWidget(widget);
this.presenter = new HasDataPresenter<T>(this, new View<T>(this), pageSize, keyProvider);
// Sink events.
Set<String> eventTypes = new HashSet<String>();
eventTypes.add(BrowserEvents.FOCUS);
eventTypes.add(BrowserEvents.BLUR);
eventTypes.add(BrowserEvents.KEYDOWN); // Used for keyboard navigation.
eventTypes.add(BrowserEvents.KEYUP); // Used by subclasses for selection.
eventTypes.add(BrowserEvents.CLICK); // Used by subclasses for selection.
eventTypes.add(BrowserEvents.MOUSEDOWN); // No longer used, but here for legacy support.
CellBasedWidgetImpl.get().sinkEvents(this, eventTypes);
// Add a default selection event manager.
selectionManagerReg =
addCellPreviewHandler(DefaultSelectionEventManager.<T> createDefaultManager());
// Add a default keyboard selection handler.
setKeyboardSelectionHandler(new DefaultKeyboardSelectionHandler<T>(this));
}
@Override
public HandlerRegistration addCellPreviewHandler(CellPreviewEvent.Handler<T> handler) {
return presenter.addCellPreviewHandler(handler);
}
/**
* Add a {@link LoadingStateChangeEvent.Handler} to be notified of changes in
* the loading state.
*
* @param handler the handle
* @return the registration for the handler
*/
public HandlerRegistration addLoadingStateChangeHandler(LoadingStateChangeEvent.Handler handler) {
return presenter.addLoadingStateChangeHandler(handler);
}
@Override
public HandlerRegistration addRangeChangeHandler(RangeChangeEvent.Handler handler) {
return presenter.addRangeChangeHandler(handler);
}
@Override
public HandlerRegistration addRowCountChangeHandler(RowCountChangeEvent.Handler handler) {
return presenter.addRowCountChangeHandler(handler);
}
/**
* Get the access key.
*
* @return the access key, or -1 if not set
* @see #setAccessKey(char)
*/
public char getAccessKey() {
return accessKey;
}
/**
* Get the row value at the specified visible index. Index 0 corresponds to
* the first item on the page.
*
* @param indexOnPage the index on the page
* @return the row value
* @deprecated use {@link #getVisibleItem(int)} instead
*/
@Deprecated
public T getDisplayedItem(int indexOnPage) {
return getVisibleItem(indexOnPage);
}
/**
* Return the row values that the widget is currently displaying as an
* immutable list.
*
* @return a List of displayed items
* @deprecated use {@link #getVisibleItems()} instead
*/
@Deprecated
public List<T> getDisplayedItems() {
return getVisibleItems();
}
@Override
public KeyboardPagingPolicy getKeyboardPagingPolicy() {
return presenter.getKeyboardPagingPolicy();
}
/**
* Get the index of the row that is currently selected via the keyboard,
* relative to the page start index.
*
* <p>
* This is not same as the selected row in the {@link SelectionModel}. The
* keyboard selected row refers to the row that the user navigated to via the
* keyboard or mouse.
* </p>
*
* @return the currently selected row, or -1 if none selected
*/
public int getKeyboardSelectedRow() {
return presenter.getKeyboardSelectedRow();
}
@Override
public KeyboardSelectionPolicy getKeyboardSelectionPolicy() {
return presenter.getKeyboardSelectionPolicy();
}
@Override
public ProvidesKey<T> getKeyProvider() {
return presenter.getKeyProvider();
}
/**
* Return the range size.
*
* @return the size of the range as an int
*
* @see #getVisibleRange()
* @see #setPageSize(int)
*/
public final int getPageSize() {
return getVisibleRange().getLength();
}
/**
* Return the range start.
*
* @return the start of the range as an int
*
* @see #getVisibleRange()
* @see #setPageStart(int)
*/
public final int getPageStart() {
return getVisibleRange().getStart();
}
/**
* Return the outer element that contains all of the rendered row values. This
* method delegates to {@link #getChildContainer()};
*
* @return the {@link Element} that contains the rendered row values
*/
public Element getRowContainer() {
presenter.flush();
return getChildContainer();
}
@Override
public int getRowCount() {
return presenter.getRowCount();
}
@Override
public SelectionModel<? super T> getSelectionModel() {
return presenter.getSelectionModel();
}
@Override
public int getTabIndex() {
return tabIndex;
}
/**
* Get the key for the specified value. If a keyProvider is not specified or the value is null,
* the value is returned. If the key provider is specified, it is used to get the key from
* the value.
*
* @param value the value
* @return the key
*/
public Object getValueKey(T value) {
ProvidesKey<T> keyProvider = getKeyProvider();
return (keyProvider == null || value == null) ? value : keyProvider.getKey(value);
}
@Override
public T getVisibleItem(int indexOnPage) {
checkRowBounds(indexOnPage);
return presenter.getVisibleItem(indexOnPage);
}
@Override
public int getVisibleItemCount() {
return presenter.getVisibleItemCount();
}
/**
* Return the row values that the widget is currently displaying as an
* immutable list.
*
* @return a List of displayed items
*/
@Override
public List<T> getVisibleItems() {
return presenter.getVisibleItems();
}
@Override
public Range getVisibleRange() {
return presenter.getVisibleRange();
}
@Override
public boolean isRowCountExact() {
return presenter.isRowCountExact();
}
/**
* Handle browser events. Subclasses should override
* {@link #onBrowserEvent2(Event)} if they want to extend browser event
* handling.
*
* @see #onBrowserEvent2(Event)
*/
@Override
public final void onBrowserEvent(Event event) {
CellBasedWidgetImpl.get().onBrowserEvent(this, event);
// Ignore spurious events (such as onblur) while we refresh the table.
if (isRefreshing) {
return;
}
// Verify that the target is still a child of this widget. IE fires focus
// events even after the element has been removed from the DOM.
EventTarget eventTarget = event.getEventTarget();
if (!Element.is(eventTarget)) {
return;
}
Element target = Element.as(eventTarget);
if (!getElement().isOrHasChild(Element.as(eventTarget))) {
return;
}
super.onBrowserEvent(event);
String eventType = event.getType();
if (BrowserEvents.FOCUS.equals(eventType)) {
// Remember the focus state.
isFocused = true;
onFocus();
} else if (BrowserEvents.BLUR.equals(eventType)) {
// Remember the blur state.
isFocused = false;
onBlur();
} else if (BrowserEvents.KEYDOWN.equals(eventType)) {
// A key event indicates that we already have focus.
isFocused = true;
} else if (BrowserEvents.MOUSEDOWN.equals(eventType)
&& CellBasedWidgetImpl.get().isFocusable(Element.as(target))) {
// If a natively focusable element was just clicked, then we must have
// focus.
isFocused = true;
}
// Let subclasses handle the event now.
onBrowserEvent2(event);
}
/**
* Redraw the widget using the existing data.
*/
public void redraw() {
presenter.redraw();
}
/**
* Redraw a single row using the existing data.
*
* @param absRowIndex the absolute row index to redraw
*/
public void redrawRow(int absRowIndex) {
int relRowIndex = absRowIndex - getPageStart();
checkRowBounds(relRowIndex);
setRowData(absRowIndex, Collections.singletonList(getVisibleItem(relRowIndex)));
}
/**
* {@inheritDoc}
*
* @see #getAccessKey()
*/
@Override
public void setAccessKey(char key) {
this.accessKey = key;
setKeyboardSelected(getKeyboardSelectedRow(), true, false);
}
@Override
public void setFocus(boolean focused) {
Element elem = getKeyboardSelectedElement();
if (elem != null) {
if (focused) {
elem.focus();
} else {
elem.blur();
}
}
}
@Override
public void setKeyboardPagingPolicy(KeyboardPagingPolicy policy) {
presenter.setKeyboardPagingPolicy(policy);
}
/**
* Set the keyboard selected row. The row index is the index relative to the
* current page start index.
*
* <p>
* If keyboard selection is disabled, this method does nothing.
* </p>
*
* <p>
* If the keyboard selected row is outside of the range of the current page
* (that is, less than 0 or greater than or equal to the page size), the page
* or range will be adjusted depending on the keyboard paging policy. If the
* keyboard paging policy is limited to the current range, the row index will
* be clipped to the current page.
* </p>
*
* @param row the row index relative to the page start
*/
public final void setKeyboardSelectedRow(int row) {
setKeyboardSelectedRow(row, true);
}
/**
* Set the keyboard selected row and optionally focus on the new row.
*
* @param row the row index relative to the page start
* @param stealFocus true to focus on the new row
* @see #setKeyboardSelectedRow(int)
*/
public void setKeyboardSelectedRow(int row, boolean stealFocus) {
presenter.setKeyboardSelectedRow(row, stealFocus, true);
}
/**
* Set the handler that handles keyboard selection/navigation.
*/
public void setKeyboardSelectionHandler(CellPreviewEvent.Handler<T> keyboardSelectionReg) {
// Remove the old manager.
if (this.keyboardSelectionReg != null) {
this.keyboardSelectionReg.removeHandler();
this.keyboardSelectionReg = null;
}
// Add the new manager.
if (keyboardSelectionReg != null) {
this.keyboardSelectionReg = addCellPreviewHandler(keyboardSelectionReg);
}
}
@Override
public void setKeyboardSelectionPolicy(KeyboardSelectionPolicy policy) {
presenter.setKeyboardSelectionPolicy(policy);
}
/**
* Set the number of rows per page and refresh the view.
*
* @param pageSize the page size
* @see #setVisibleRange(Range)
* @see #getPageSize()
*/
public final void setPageSize(int pageSize) {
setVisibleRange(getPageStart(), pageSize);
}
/**
* Set the starting index of the current visible page. The actual page start
* will be clamped in the range [0, getSize() - 1].
*
* @param pageStart the index of the row that should appear at the start of
* the page
* @see #setVisibleRange(Range)
* @see #getPageStart()
*/
public final void setPageStart(int pageStart) {
setVisibleRange(pageStart, getPageSize());
}
@Override
public final void setRowCount(int count) {
setRowCount(count, true);
}
@Override
public void setRowCount(int size, boolean isExact) {
presenter.setRowCount(size, isExact);
}
/**
* <p>
* Set the complete list of values to display on one page.
* </p>
* <p>
* Equivalent to calling {@link #setRowCount(int)} with the length of the list
* of values, {@link #setVisibleRange(Range)} from 0 to the size of the list
* of values, and {@link #setRowData(int, List)} with a start of 0 and the
* specified list of values.
* </p>
*
* @param values
*/
public final void setRowData(List<? extends T> values) {
setRowCount(values.size());
setVisibleRange(0, values.size());
setRowData(0, values);
}
@Override
public void setRowData(int start, List<? extends T> values) {
presenter.setRowData(start, values);
}
/**
* Set the {@link SelectionModel} used by this {@link HasData}.
*
* <p>
* By default, selection occurs when the user clicks on a Cell or presses the
* spacebar. If you need finer control over selection, you can specify a
* {@link DefaultSelectionEventManager} using
* {@link #setSelectionModel(SelectionModel, com.google.gwt.view.client.CellPreviewEvent.Handler)}. {@link DefaultSelectionEventManager} provides some default
* implementations to handle checkbox based selection, as well as a blacklist
* or whitelist of columns to prevent or allow selection.
* </p>
*
* @param selectionModel the {@link SelectionModel}
* @see #setSelectionModel(SelectionModel,
* com.google.gwt.view.client.CellPreviewEvent.Handler)
* @see #getSelectionModel()
*/
@Override
public void setSelectionModel(SelectionModel<? super T> selectionModel) {
presenter.setSelectionModel(selectionModel);
}
/**
* Set the {@link SelectionModel} that defines which items are selected and
* the {@link com.google.gwt.view.client.CellPreviewEvent.Handler} that
* controls how user selection is handled.
*
* @param selectionModel the {@link SelectionModel} that defines selection
* @param selectionEventManager the handler that controls user selection
*/
public void setSelectionModel(SelectionModel<? super T> selectionModel,
CellPreviewEvent.Handler<T> selectionEventManager) {
// Remove the old manager.
if (this.selectionManagerReg != null) {
this.selectionManagerReg.removeHandler();
this.selectionManagerReg = null;
}
// Add the new manager.
if (selectionEventManager != null) {
this.selectionManagerReg = addCellPreviewHandler(selectionEventManager);
}
// Set the selection model.
setSelectionModel(selectionModel);
}
@Override
public void setTabIndex(int index) {
this.tabIndex = index;
setKeyboardSelected(getKeyboardSelectedRow(), true, false);
}
@Override
public final void setVisibleRange(int start, int length) {
setVisibleRange(new Range(start, length));
}
@Override
public void setVisibleRange(Range range) {
presenter.setVisibleRange(range);
}
@Override
public void setVisibleRangeAndClearData(Range range, boolean forceRangeChangeEvent) {
presenter.setVisibleRangeAndClearData(range, forceRangeChangeEvent);
}
/**
* Check if a cell consumes the specified event type.
*
* @param cell the cell
* @param eventType the event type to check
* @return true if consumed, false if not
*/
protected boolean cellConsumesEventType(Cell<?> cell, String eventType) {
Set<String> consumedEvents = cell.getConsumedEvents();
return consumedEvents != null && consumedEvents.contains(eventType);
}
/**
* Check that the row is within the correct bounds.
*
* @param row row index to check
* @throws IndexOutOfBoundsException
*/
protected void checkRowBounds(int row) {
if (!isRowWithinBounds(row)) {
throw new IndexOutOfBoundsException("Row index: " + row + ", Row size: " + getRowCount());
}
}
/**
* Convert the specified HTML into DOM elements and return the parent of the
* DOM elements.
*
* @param html the HTML to convert
* @return the parent element
*/
protected Element convertToElements(SafeHtml html) {
return convertToElements(this, getTmpElem(), html);
}
/**
* Check whether or not the cells in the view depend on the selection state.
*
* @return true if cells depend on selection, false if not
*/
protected abstract boolean dependsOnSelection();
/**
* Return the element that holds the rendered cells.
*
* @return the container {@link Element}
*/
protected abstract Element getChildContainer();
/**
* Get the element that represents the specified index.
*
* @param index the index of the row value
* @return the child element, or null if it does not exist
*/
protected Element getChildElement(int index) {
Element childContainer = getChildContainer();
int childCount = childContainer.getChildCount();
return (index < childCount) ? childContainer.getChild(index).<Element> cast() : null;
}
/**
* Get the element that has keyboard selection.
*
* @return the keyboard selected element
*/
protected abstract Element getKeyboardSelectedElement();
/**
* Check if keyboard navigation is being suppressed, such as when the user is
* editing a cell.
*
* @return true if suppressed, false if not
*/
protected abstract boolean isKeyboardNavigationSuppressed();
/**
* Checks that the row is within bounds of the view.
*
* @param row row index to check
* @return true if within bounds, false if not
*/
protected boolean isRowWithinBounds(int row) {
return row >= 0 && row < presenter.getVisibleItemCount();
}
/**
* Called when the widget is blurred.
*/
protected void onBlur() {
}
/**
* Called after {@link #onBrowserEvent(Event)} completes.
*
* @param event the event that was fired
*/
protected void onBrowserEvent2(Event event) {
}
/**
* Called when the widget is focused.
*/
protected void onFocus() {
}
/**
* Called when the loading state changes. By default, this implementation
* fires a {@link LoadingStateChangeEvent}.
*
* @param state the new loading state
*/
protected void onLoadingStateChanged(LoadingState state) {
fireEvent(new LoadingStateChangeEvent(state));
}
@Override
protected void onUnload() {
isFocused = false;
super.onUnload();
}
/**
* Render all row values into the specified {@link SafeHtmlBuilder}.
*
* <p>
* Subclasses can optionally throw an {@link UnsupportedOperationException} if
* they prefer to render the rows in
* {@link #replaceAllChildren(List, SafeHtml)} and
* {@link #replaceChildren(List, int, SafeHtml)}. In this case, the
* {@link SafeHtml} argument will be null. Though a bit hacky, this is
* designed to supported legacy widgets that use {@link SafeHtmlBuilder}, and
* newer widgets that use other builders, such as the ElementBuilder API.
* </p>
*
* @param sb the {@link SafeHtmlBuilder} to render into
* @param values the row values
* @param start the absolute start index of the values
* @param selectionModel the {@link SelectionModel}
* @throws UnsupportedOperationException if the values will be rendered in
* {@link #replaceAllChildren(List, SafeHtml)} and
* {@link #replaceChildren(List, int, SafeHtml)}
*/
protected abstract void renderRowValues(SafeHtmlBuilder sb, List<T> values, int start,
SelectionModel<? super T> selectionModel) throws UnsupportedOperationException;
/**
* Replace all children with the specified html.
*
* @param values the values of the new children
* @param html the html to render, or null if
* {@link #renderRowValues(SafeHtmlBuilder, List, int, SelectionModel)}
* throws an {@link UnsupportedOperationException}
*/
protected void replaceAllChildren(List<T> values, SafeHtml html) {
replaceAllChildren(this, getChildContainer(), html);
}
/**
* Convert the specified HTML into DOM elements and replace the existing
* elements starting at the specified index. If the number of children
* specified exceeds the existing number of children, the remaining children
* should be appended.
*
* @param values the values of the new children
* @param start the start index to be replaced, relative to the page start
* @param html the html to render, or null if
* {@link #renderRowValues(SafeHtmlBuilder, List, int, SelectionModel)}
* throws an {@link UnsupportedOperationException}
*/
protected void replaceChildren(List<T> values, int start, SafeHtml html) {
Element newChildren = convertToElements(html);
replaceChildren(this, getChildContainer(), newChildren, start, html);
}
/**
* Reset focus on the currently focused cell.
*
* @return true if focus is taken, false if not
*/
protected abstract boolean resetFocusOnCell();
/**
* Make an element focusable or not.
*
* @param elem the element
* @param focusable true to make focusable, false to make unfocusable
*/
protected void setFocusable(Element elem, boolean focusable) {
if (focusable) {
FocusImpl focusImpl = FocusImpl.getFocusImplForWidget();
com.google.gwt.user.client.Element rowElem = elem.cast();
focusImpl.setTabIndex(rowElem, getTabIndex());
if (accessKey != 0) {
focusImpl.setAccessKey(rowElem, accessKey);
}
} else {
// Chrome: Elements remain focusable after removing the tabIndex, so set
// it to -1 first.
elem.setTabIndex(-1);
elem.removeAttribute("tabIndex");
elem.removeAttribute("accessKey");
}
}
/**
* Update an element to reflect its keyboard selected state.
*
* @param index the index of the element
* @param selected true if selected, false if not
* @param stealFocus true if the row should steal focus, false if not
*/
protected abstract void setKeyboardSelected(int index, boolean selected, boolean stealFocus);
/**
* Update an element to reflect its selected state.
*
* @param elem the element to update
* @param selected true if selected, false if not
* @deprecated this method is never called by AbstractHasData, render the
* selected styles in
* {@link #renderRowValues(SafeHtmlBuilder, List, int, SelectionModel)}
*/
@Deprecated
protected void setSelected(Element elem, boolean selected) {
// Never called.
}
/**
* Add a {@link ValueChangeHandler} that is called when the display values
* change. Used by {@link CellBrowser} to detect when the displayed data
* changes.
*
* @param handler the handler
* @return a {@link HandlerRegistration} to remove the handler
*/
final HandlerRegistration addValueChangeHandler(ValueChangeHandler<List<T>> handler) {
return addHandler(handler, ValueChangeEvent.getType());
}
/**
* Adopt the specified widget.
*
* @param child the child to adopt
*/
native void adopt(Widget child) /*-{
[email protected]::setParent(Lcom/google/gwt/user/client/ui/Widget;)(this);
}-*/;
/**
* Attach a child.
*
* @param child the child to attach
*/
native void doAttach(Widget child) /*-{
[email protected]::onAttach()();
}-*/;
/**
* Detach a child.
*
* @param child the child to detach
*/
native void doDetach(Widget child) /*-{
[email protected]::onDetach()();
}-*/;
HasDataPresenter<T> getPresenter() {
return presenter;
}
/**
* Show or hide an element.
*
* @param element the element
* @param show true to show, false to hide
*/
void showOrHide(Element element, boolean show) {
if (element == null) {
return;
}
if (show) {
element.getStyle().clearDisplay();
} else {
element.getStyle().setDisplay(Display.NONE);
}
}
}
| true | true | public void onCellPreview(CellPreviewEvent<T> event) {
NativeEvent nativeEvent = event.getNativeEvent();
String eventType = event.getNativeEvent().getType();
if (BrowserEvents.KEYDOWN.equals(eventType) && !event.isCellEditing()) {
/*
* Handle keyboard navigation, unless the cell is being edited. If the
* cell is being edited, we do not want to change rows.
*
* Prevent default on navigation events to prevent default scrollbar
* behavior.
*/
switch (nativeEvent.getKeyCode()) {
case KeyCodes.KEY_DOWN:
nextRow();
handledEvent(event);
return;
case KeyCodes.KEY_UP:
prevRow();
handledEvent(event);
return;
case KeyCodes.KEY_PAGEDOWN:
nextPage();
handledEvent(event);
return;
case KeyCodes.KEY_PAGEUP:
prevPage();
handledEvent(event);
return;
case KeyCodes.KEY_HOME:
home();
handledEvent(event);
return;
case KeyCodes.KEY_END:
end();
handledEvent(event);
return;
case 32:
// Prevent the list box from scrolling.
handledEvent(event);
return;
}
} else if (BrowserEvents.CLICK.equals(eventType)) {
/*
* Move keyboard focus to the clicked row, even if the Cell is being
* edited. Unlike key events, we aren't moving the currently selected
* row, just updating it based on where the user clicked.
*/
int relRow = event.getIndex() - display.getPageStart();
// If a natively focusable element was just clicked, then do not steal
// focus.
boolean isFocusable = false;
Element target = Element.as(event.getNativeEvent().getEventTarget());
isFocusable = CellBasedWidgetImpl.get().isFocusable(target);
display.setKeyboardSelectedRow(relRow, !isFocusable);
// Do not cancel the event as the click may have occurred on a Cell.
} else if (BrowserEvents.FOCUS.equals(eventType)) {
// Move keyboard focus to match the currently focused element.
int relRow = event.getIndex() - display.getPageStart();
if (display.getKeyboardSelectedRow() != relRow) {
// Do not steal focus as this was a focus event.
display.setKeyboardSelectedRow(event.getIndex(), false);
// Do not cancel the event as the click may have occurred on a Cell.
return;
}
}
}
| public void onCellPreview(CellPreviewEvent<T> event) {
NativeEvent nativeEvent = event.getNativeEvent();
String eventType = event.getNativeEvent().getType();
if (BrowserEvents.KEYDOWN.equals(eventType) && !event.isCellEditing()) {
/*
* Handle keyboard navigation, unless the cell is being edited. If the
* cell is being edited, we do not want to change rows.
*
* Prevent default on navigation events to prevent default scrollbar
* behavior.
*/
switch (nativeEvent.getKeyCode()) {
case KeyCodes.KEY_DOWN:
nextRow();
handledEvent(event);
return;
case KeyCodes.KEY_UP:
prevRow();
handledEvent(event);
return;
case KeyCodes.KEY_PAGEDOWN:
nextPage();
handledEvent(event);
return;
case KeyCodes.KEY_PAGEUP:
prevPage();
handledEvent(event);
return;
case KeyCodes.KEY_HOME:
home();
handledEvent(event);
return;
case KeyCodes.KEY_END:
end();
handledEvent(event);
return;
case 32:
// Prevent the list box from scrolling.
handledEvent(event);
return;
}
} else if (BrowserEvents.CLICK.equals(eventType)) {
/*
* Move keyboard focus to the clicked row, even if the Cell is being
* edited. Unlike key events, we aren't moving the currently selected
* row, just updating it based on where the user clicked.
*/
int relRow = event.getIndex() - display.getPageStart();
// If a natively focusable element was just clicked, then do not steal
// focus.
boolean isFocusable = false;
Element target = Element.as(event.getNativeEvent().getEventTarget());
isFocusable = CellBasedWidgetImpl.get().isFocusable(target);
display.setKeyboardSelectedRow(relRow, !isFocusable);
// Do not cancel the event as the click may have occurred on a Cell.
} else if (BrowserEvents.FOCUS.equals(eventType)) {
// Move keyboard focus to match the currently focused element.
int relRow = event.getIndex() - display.getPageStart();
if (display.getKeyboardSelectedRow() != relRow) {
// Do not steal focus as this was a focus event.
display.setKeyboardSelectedRow(relRow, false);
// Do not cancel the event as the click may have occurred on a Cell.
return;
}
}
}
|
diff --git a/src/phm1/NewJ/DiagramPanel.java b/src/phm1/NewJ/DiagramPanel.java
index 3ecf17a..4fd3a17 100755
--- a/src/phm1/NewJ/DiagramPanel.java
+++ b/src/phm1/NewJ/DiagramPanel.java
@@ -1,62 +1,62 @@
package phm1.NewJ;
import javax.swing.*;
import java.awt.*;
public class DiagramPanel extends JPanel{
private GUI gui;
private NJClass selected;
private boolean inheriting;
public boolean getInheriting(){
return inheriting;
}
public void setInheriting(boolean inheriting){
this.inheriting = (selected != null) && inheriting;
if(this.inheriting){
selected.setInherits(new NJInheritance());
}
}
public NJClass getSelected() {
return selected;
}
public void setSelected(NJClass selected) {
if(inheriting){
- if(selected == null){
+ if(selected == null && this.selected != null){
this.selected.setInherits(null);
} else if(selected != null && this.selected.getInherits() != null){
this.selected.getInherits().setTo(selected);
}
}
this.selected = selected;
}
public DiagramPanel(GUI g){
this.gui = g;
this.inheriting = false;
this.setLayout(new BorderLayout());
this.setBackground(Color.WHITE);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
gui.drawAll(g);
}
public NJClass findNearestClass(int x, int y) {
NJClass c;
//calls a method in vector of boxes to find which box the mouse is inside, then returns that box
c = gui.clickedInBox(x, y);
repaint();
return c;
}
public void unselectAll() {
setSelected(null);
}
}
| true | true | public void setSelected(NJClass selected) {
if(inheriting){
if(selected == null){
this.selected.setInherits(null);
} else if(selected != null && this.selected.getInherits() != null){
this.selected.getInherits().setTo(selected);
}
}
this.selected = selected;
}
| public void setSelected(NJClass selected) {
if(inheriting){
if(selected == null && this.selected != null){
this.selected.setInherits(null);
} else if(selected != null && this.selected.getInherits() != null){
this.selected.getInherits().setTo(selected);
}
}
this.selected = selected;
}
|
diff --git a/src/main/java/com/hawkfalcon/deathswap/Stop.java b/src/main/java/com/hawkfalcon/deathswap/Stop.java
index 48138f5..8904235 100644
--- a/src/main/java/com/hawkfalcon/deathswap/Stop.java
+++ b/src/main/java/com/hawkfalcon/deathswap/Stop.java
@@ -1,53 +1,53 @@
package com.hawkfalcon.deathswap;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import com.hawkfalcon.deathswap.API.DeathSwapWinEvent;
import com.hawkfalcon.deathswap.API.DeathSwapWinGameEvent;
public class Stop {
public DeathSwap plugin;
public Stop(DeathSwap ds) {
this.plugin = ds;
}
public void dealWithLeftoverGames(Player loser, boolean died) {
if (plugin.match.containsKey(loser.getName())) {
Player winner = plugin.getServer().getPlayerExact(plugin.match.get(loser.getName()));
cleanUp(loser, winner, died);
} else if (plugin.match.containsValue(loser.getName())) {
Player winner = null;
for (String key : plugin.match.keySet()) {
if (plugin.match.get(key).equals(loser.getName())) {
winner = plugin.getServer().getPlayerExact(key);
}
}
cleanUp(loser, winner, died);
}
}
public void cleanUp(Player loser, Player winner, boolean died) {
DeathSwapWinEvent dswe = new DeathSwapWinEvent(winner.getName(), loser.getName());
Bukkit.getServer().getPluginManager().callEvent(dswe);
DeathSwapWinGameEvent dswge = new DeathSwapWinGameEvent(winner, loser);
Bukkit.getServer().getPluginManager().callEvent(dswge);
//JOPHESTUS IS AWESOME
plugin.utility.broadcast(ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("gameend").replace("%WINNER%", winner.getName()).replace("%LOSER%", loser.getName())));
if (died) {
- plugin.utility.message(loser + " died, you win!", winner);
+ plugin.utility.message(loser.getName() + " died, you win!", winner);
} else {
- plugin.utility.message(loser + " has left the game, you win!", winner);
+ plugin.utility.message(loser.getName() + " has left the game, you win!", winner);
}
- plugin.game.remove(winner);
+ plugin.game.remove(winner.getName());
plugin.utility.playerReset(winner);
plugin.utility.teleport(winner, 1);
- plugin.match.remove(loser);
- plugin.startgame.remove(loser);
- plugin.match.remove(winner);
- plugin.startgame.remove(winner);
+ plugin.match.remove(loser.getName());
+ plugin.startgame.remove(loser.getName());
+ plugin.match.remove(winner.getName());
+ plugin.startgame.remove(winner.getName());
}
}
| false | true | public void cleanUp(Player loser, Player winner, boolean died) {
DeathSwapWinEvent dswe = new DeathSwapWinEvent(winner.getName(), loser.getName());
Bukkit.getServer().getPluginManager().callEvent(dswe);
DeathSwapWinGameEvent dswge = new DeathSwapWinGameEvent(winner, loser);
Bukkit.getServer().getPluginManager().callEvent(dswge);
//JOPHESTUS IS AWESOME
plugin.utility.broadcast(ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("gameend").replace("%WINNER%", winner.getName()).replace("%LOSER%", loser.getName())));
if (died) {
plugin.utility.message(loser + " died, you win!", winner);
} else {
plugin.utility.message(loser + " has left the game, you win!", winner);
}
plugin.game.remove(winner);
plugin.utility.playerReset(winner);
plugin.utility.teleport(winner, 1);
plugin.match.remove(loser);
plugin.startgame.remove(loser);
plugin.match.remove(winner);
plugin.startgame.remove(winner);
}
| public void cleanUp(Player loser, Player winner, boolean died) {
DeathSwapWinEvent dswe = new DeathSwapWinEvent(winner.getName(), loser.getName());
Bukkit.getServer().getPluginManager().callEvent(dswe);
DeathSwapWinGameEvent dswge = new DeathSwapWinGameEvent(winner, loser);
Bukkit.getServer().getPluginManager().callEvent(dswge);
//JOPHESTUS IS AWESOME
plugin.utility.broadcast(ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("gameend").replace("%WINNER%", winner.getName()).replace("%LOSER%", loser.getName())));
if (died) {
plugin.utility.message(loser.getName() + " died, you win!", winner);
} else {
plugin.utility.message(loser.getName() + " has left the game, you win!", winner);
}
plugin.game.remove(winner.getName());
plugin.utility.playerReset(winner);
plugin.utility.teleport(winner, 1);
plugin.match.remove(loser.getName());
plugin.startgame.remove(loser.getName());
plugin.match.remove(winner.getName());
plugin.startgame.remove(winner.getName());
}
|
diff --git a/tool/src/java/uk/ac/ox/oucs/oxam/pages/SakaiPage.java b/tool/src/java/uk/ac/ox/oucs/oxam/pages/SakaiPage.java
index be50531..7412c51 100644
--- a/tool/src/java/uk/ac/ox/oucs/oxam/pages/SakaiPage.java
+++ b/tool/src/java/uk/ac/ox/oucs/oxam/pages/SakaiPage.java
@@ -1,166 +1,166 @@
package uk.ac.ox.oucs.oxam.pages;
import org.apache.log4j.Logger;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.Component;
import org.apache.wicket.Page;
import org.apache.wicket.ResourceReference;
import org.apache.wicket.behavior.AttributeAppender;
import org.apache.wicket.behavior.SimpleAttributeModifier;
import org.apache.wicket.feedback.FeedbackMessage;
import org.apache.wicket.feedback.IFeedbackMessageFilter;
import org.apache.wicket.markup.html.IHeaderContributor;
import org.apache.wicket.markup.html.IHeaderResponse;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.link.PageLink;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.repeater.RepeatingView;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import uk.ac.ox.oucs.oxam.logic.SakaiProxy;
/**
* This is our base page for our Sakai app. It sets up the containing markup and
* top navigation. All top level pages should extend from this page so as to
* keep the same navigation. The content for those pages will be rendered in the
* main area below the top nav.
*
* <p>
* It also allows us to setup the API injection and any other common methods,
* which are then made available in the other pages.
*
* @author Steve Swinsburg ([email protected])
*
*/
public class SakaiPage extends WebPage implements IHeaderContributor {
private static final Logger log = Logger.getLogger(SakaiPage.class);
@SpringBean(name = "sakaiProxy")
protected SakaiProxy sakaiProxy;
FeedbackPanel feedbackPanel;
// Any links to be added to the page.
private RepeatingView links;
public SakaiPage() {
- log.debug("BasePage()");
+ log.debug("SakaiPage()");
links = new RepeatingView("link");
add(links);
// Add a FeedbackPanel for displaying our messages
feedbackPanel = new FeedbackPanel("feedback") {
private static final long serialVersionUID = 1L;
@Override
protected Component newMessageDisplayComponent(final String id,
final FeedbackMessage message) {
final Component newMessageDisplayComponent = super
.newMessageDisplayComponent(id, message);
if (message.getLevel() == FeedbackMessage.ERROR
|| message.getLevel() == FeedbackMessage.DEBUG
|| message.getLevel() == FeedbackMessage.FATAL
|| message.getLevel() == FeedbackMessage.WARNING) {
add(new SimpleAttributeModifier("class", "alertMessage"));
} else if (message.getLevel() == FeedbackMessage.INFO) {
add(new SimpleAttributeModifier("class", "success"));
}
return newMessageDisplayComponent;
}
// If we don't link up visibility to having messages, then when changing the filter after displaying
// the message, the message disappears but they surrounding box remains.
public boolean isVisible() {
return anyMessage();
}
};
feedbackPanel.setFilter(new IFeedbackMessageFilter() {
private static final long serialVersionUID = 1L;
public boolean accept(FeedbackMessage message) {
return !message.isRendered();
}
});
add(feedbackPanel);
}
/**
* Helper to clear the feedbackpanel display.
*
* @param f
* FeedBackPanel
*/
public void clearFeedback(FeedbackPanel f) {
if (!f.hasFeedbackMessage()) {
f.add(new SimpleAttributeModifier("class", ""));
}
}
/**
* This block adds the required wrapper markup to style it like a Sakai
* tool. Add to this any additional CSS or JS references that you need.
*
*/
public void renderHead(IHeaderResponse response) {
// get Sakai skin
String skinRepo = sakaiProxy.getSkinRepoProperty();
String toolCSS = sakaiProxy.getToolSkinCSS(skinRepo);
String toolBaseCSS = skinRepo + "/tool_base.css";
// Sakai additions
response.renderJavascriptReference("/library/js/headscripts.js");
response.renderCSSReference(toolBaseCSS);
response.renderCSSReference(toolCSS);
response.renderOnLoadJavascript("\nif (typeof setMainFrameHeight !== 'undefined'){\nsetMainFrameHeight( window.name );\n}");
// Tool additions (at end so we can override if required)
response.renderString("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n");
response.renderCSSReference(new ResourceReference(getClass(),"style.css"));
// Need a resource reference so that we don't have to worry about path components.
response.renderJavascriptReference(new ResourceReference(getClass(), "jquery-1.7.1.min.js"));
response.renderJavascriptReference(new ResourceReference(getClass(), "script.js"));
}
/**
* Helper to disable a link. Add the Sakai class 'current'.
*/
protected void disableLink(Link<Void> l) {
l.add(new AttributeAppender("class", new Model<String>("current"), " "));
l.setRenderBodyOnly(true);
l.setEnabled(false);
}
protected void addLink(Class<? extends Page> clazz, String title,
String tooltip) {
Link<Page> link = new BookmarkablePageLink<Page>("anchor", clazz);
link.setEnabled(!getClass().equals(clazz));
addLink(link, title, tooltip);
}
protected void addLink(final Link<Page> link, String title,
String tooltip) {
WebMarkupContainer parent = new WebMarkupContainer(links.newChildId());
links.add(parent);
link.add(new Label("label", new ResourceModel(title))
.setRenderBodyOnly(true));
if (tooltip != null) {
link.add(new AttributeModifier("title", true, new ResourceModel(
tooltip)));
};
parent.add(link);
}
}
| true | true | public SakaiPage() {
log.debug("BasePage()");
links = new RepeatingView("link");
add(links);
// Add a FeedbackPanel for displaying our messages
feedbackPanel = new FeedbackPanel("feedback") {
private static final long serialVersionUID = 1L;
@Override
protected Component newMessageDisplayComponent(final String id,
final FeedbackMessage message) {
final Component newMessageDisplayComponent = super
.newMessageDisplayComponent(id, message);
if (message.getLevel() == FeedbackMessage.ERROR
|| message.getLevel() == FeedbackMessage.DEBUG
|| message.getLevel() == FeedbackMessage.FATAL
|| message.getLevel() == FeedbackMessage.WARNING) {
add(new SimpleAttributeModifier("class", "alertMessage"));
} else if (message.getLevel() == FeedbackMessage.INFO) {
add(new SimpleAttributeModifier("class", "success"));
}
return newMessageDisplayComponent;
}
// If we don't link up visibility to having messages, then when changing the filter after displaying
// the message, the message disappears but they surrounding box remains.
public boolean isVisible() {
return anyMessage();
}
};
feedbackPanel.setFilter(new IFeedbackMessageFilter() {
private static final long serialVersionUID = 1L;
public boolean accept(FeedbackMessage message) {
return !message.isRendered();
}
});
add(feedbackPanel);
}
| public SakaiPage() {
log.debug("SakaiPage()");
links = new RepeatingView("link");
add(links);
// Add a FeedbackPanel for displaying our messages
feedbackPanel = new FeedbackPanel("feedback") {
private static final long serialVersionUID = 1L;
@Override
protected Component newMessageDisplayComponent(final String id,
final FeedbackMessage message) {
final Component newMessageDisplayComponent = super
.newMessageDisplayComponent(id, message);
if (message.getLevel() == FeedbackMessage.ERROR
|| message.getLevel() == FeedbackMessage.DEBUG
|| message.getLevel() == FeedbackMessage.FATAL
|| message.getLevel() == FeedbackMessage.WARNING) {
add(new SimpleAttributeModifier("class", "alertMessage"));
} else if (message.getLevel() == FeedbackMessage.INFO) {
add(new SimpleAttributeModifier("class", "success"));
}
return newMessageDisplayComponent;
}
// If we don't link up visibility to having messages, then when changing the filter after displaying
// the message, the message disappears but they surrounding box remains.
public boolean isVisible() {
return anyMessage();
}
};
feedbackPanel.setFilter(new IFeedbackMessageFilter() {
private static final long serialVersionUID = 1L;
public boolean accept(FeedbackMessage message) {
return !message.isRendered();
}
});
add(feedbackPanel);
}
|
diff --git a/ScoreBoardMouseListener.java b/ScoreBoardMouseListener.java
index 266a00e..f07c95c 100644
--- a/ScoreBoardMouseListener.java
+++ b/ScoreBoardMouseListener.java
@@ -1,83 +1,83 @@
import javax.swing.event.MouseInputAdapter;
import java.awt.event.MouseEvent;
import java.util.List;
class ScoreBoardMouseListener extends MouseInputAdapter {
private List<HotZone> hotZones;
private ScoreBoard scoreBoard;
private Game game;
private Thread controlsHider;
public ScoreBoardMouseListener(ScoreBoard sb, Game g, List<HotZone> hz) {
this.hotZones = hz;
this.scoreBoard = sb;
this.game = g;
this.controlsHider = new Thread() {
public void run() {
while (true) {
try {
Thread.sleep(5000);
scoreBoard.setShowMouseControls(false);
}
catch (Exception ex) {
}
}
}
};
}
public void mouseClicked(MouseEvent me) {
+ resetHideCounter();
synchronized(hotZones) {
- resetHideCounter();
for (HotZone hz : hotZones) {
if (hz.zone.contains(me.getPoint())) {
if (hz.operation == HotZone.ops.INC) {
hz.player.updateVP(+1);
}
else if (hz.operation == HotZone.ops.DEC) {
hz.player.updateVP(-1);
}
else if (hz.operation == HotZone.ops.LA) {
if (hz.player != null) {
game.setAchievement(hz.player.getPlayerColor(), Achievement.LargestArmy);
}
else {
game.removeAchievement(Achievement.LargestArmy);
}
}
else if (hz.operation == HotZone.ops.LR) {
if (hz.player != null) {
game.setAchievement(hz.player.getPlayerColor(), Achievement.LongestRoad);
}
else {
game.removeAchievement(Achievement.LongestRoad);
}
}
return;
}
}
}
}
private void resetHideCounter() {
synchronized(controlsHider) {
scoreBoard.setShowMouseControls(true);
if (controlsHider.getState() != Thread.State.NEW) {
try {
controlsHider.interrupt();
}
catch (IllegalThreadStateException ex) {
// so the thread wasn't running, fair enough.
}
}
else {
controlsHider.start();
}
}
}
public void mouseMoved(MouseEvent me) {
resetHideCounter();
}
}
| false | true | public void mouseClicked(MouseEvent me) {
synchronized(hotZones) {
resetHideCounter();
for (HotZone hz : hotZones) {
if (hz.zone.contains(me.getPoint())) {
if (hz.operation == HotZone.ops.INC) {
hz.player.updateVP(+1);
}
else if (hz.operation == HotZone.ops.DEC) {
hz.player.updateVP(-1);
}
else if (hz.operation == HotZone.ops.LA) {
if (hz.player != null) {
game.setAchievement(hz.player.getPlayerColor(), Achievement.LargestArmy);
}
else {
game.removeAchievement(Achievement.LargestArmy);
}
}
else if (hz.operation == HotZone.ops.LR) {
if (hz.player != null) {
game.setAchievement(hz.player.getPlayerColor(), Achievement.LongestRoad);
}
else {
game.removeAchievement(Achievement.LongestRoad);
}
}
return;
}
}
}
}
| public void mouseClicked(MouseEvent me) {
resetHideCounter();
synchronized(hotZones) {
for (HotZone hz : hotZones) {
if (hz.zone.contains(me.getPoint())) {
if (hz.operation == HotZone.ops.INC) {
hz.player.updateVP(+1);
}
else if (hz.operation == HotZone.ops.DEC) {
hz.player.updateVP(-1);
}
else if (hz.operation == HotZone.ops.LA) {
if (hz.player != null) {
game.setAchievement(hz.player.getPlayerColor(), Achievement.LargestArmy);
}
else {
game.removeAchievement(Achievement.LargestArmy);
}
}
else if (hz.operation == HotZone.ops.LR) {
if (hz.player != null) {
game.setAchievement(hz.player.getPlayerColor(), Achievement.LongestRoad);
}
else {
game.removeAchievement(Achievement.LongestRoad);
}
}
return;
}
}
}
}
|
diff --git a/FinancialRecorderServer/src/main/java/com/financial/tools/recorderserver/util/NotificationHelper.java b/FinancialRecorderServer/src/main/java/com/financial/tools/recorderserver/util/NotificationHelper.java
index a0df94f..22ad557 100644
--- a/FinancialRecorderServer/src/main/java/com/financial/tools/recorderserver/util/NotificationHelper.java
+++ b/FinancialRecorderServer/src/main/java/com/financial/tools/recorderserver/util/NotificationHelper.java
@@ -1,64 +1,64 @@
package com.financial.tools.recorderserver.util;
import java.io.IOException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.android.gcm.server.Message;
import com.google.android.gcm.server.Message.Builder;
import com.google.android.gcm.server.Result;
import com.google.android.gcm.server.Sender;
/**
* Helper class used to push notification to device via GCM(Google Cloud
* Message) service. Only available for Android.
*
* @author eortwyz
*
*/
public class NotificationHelper {
private static final String ERROR_CODE_NOT_REGISTERED = "NotRegistered";
private static final String GCM_MESSAGE_TITLE_KEY = "title";
private static final String GCM_MESSAGE_BODY_KEY = "message";
private static final String GCM_KEY = "AIzaSyDm5fOxjtm38z6oSxdzlwttQo0clbrKFC4";
private static final int RETRY_TIMES = 3;
private static Logger logger = LoggerFactory.getLogger(NotificationHelper.class);
public static boolean sendNotification(String deviceRegId, NotificationType notificationType,
String notificationMessage, int timeToLive) {
if (StringUtils.isEmpty(deviceRegId)) {
logger.warn("deviceRegId:{} doesn't exist.", deviceRegId);
return false;
}
logger.debug("send notification message: {} to deviceRegId: {}.", notificationMessage, deviceRegId);
Builder messageBuilder = new Message.Builder();
if (timeToLive > 0) {
messageBuilder.timeToLive(timeToLive);
}
- Message message = messageBuilder.delayWhileIdle(true)
+ Message message = messageBuilder.delayWhileIdle(false)
.addData(GCM_MESSAGE_TITLE_KEY, notificationType.getTitle())
.addData(GCM_MESSAGE_BODY_KEY, notificationMessage).build();
Sender sender = new Sender(GCM_KEY);
try {
Result result = sender.send(message, deviceRegId, RETRY_TIMES);
logger.debug("notification send to deviceRegId: {}, result: {}.", deviceRegId, result);
if (result.getErrorCodeName() != null && result.getErrorCodeName().equals(ERROR_CODE_NOT_REGISTERED)) {
return false;
}
} catch (IOException e) {
logger.error("Can't send notification to deviceRegId: {}", deviceRegId);
return false;
}
return true;
}
}
| true | true | public static boolean sendNotification(String deviceRegId, NotificationType notificationType,
String notificationMessage, int timeToLive) {
if (StringUtils.isEmpty(deviceRegId)) {
logger.warn("deviceRegId:{} doesn't exist.", deviceRegId);
return false;
}
logger.debug("send notification message: {} to deviceRegId: {}.", notificationMessage, deviceRegId);
Builder messageBuilder = new Message.Builder();
if (timeToLive > 0) {
messageBuilder.timeToLive(timeToLive);
}
Message message = messageBuilder.delayWhileIdle(true)
.addData(GCM_MESSAGE_TITLE_KEY, notificationType.getTitle())
.addData(GCM_MESSAGE_BODY_KEY, notificationMessage).build();
Sender sender = new Sender(GCM_KEY);
try {
Result result = sender.send(message, deviceRegId, RETRY_TIMES);
logger.debug("notification send to deviceRegId: {}, result: {}.", deviceRegId, result);
if (result.getErrorCodeName() != null && result.getErrorCodeName().equals(ERROR_CODE_NOT_REGISTERED)) {
return false;
}
} catch (IOException e) {
logger.error("Can't send notification to deviceRegId: {}", deviceRegId);
return false;
}
return true;
}
| public static boolean sendNotification(String deviceRegId, NotificationType notificationType,
String notificationMessage, int timeToLive) {
if (StringUtils.isEmpty(deviceRegId)) {
logger.warn("deviceRegId:{} doesn't exist.", deviceRegId);
return false;
}
logger.debug("send notification message: {} to deviceRegId: {}.", notificationMessage, deviceRegId);
Builder messageBuilder = new Message.Builder();
if (timeToLive > 0) {
messageBuilder.timeToLive(timeToLive);
}
Message message = messageBuilder.delayWhileIdle(false)
.addData(GCM_MESSAGE_TITLE_KEY, notificationType.getTitle())
.addData(GCM_MESSAGE_BODY_KEY, notificationMessage).build();
Sender sender = new Sender(GCM_KEY);
try {
Result result = sender.send(message, deviceRegId, RETRY_TIMES);
logger.debug("notification send to deviceRegId: {}, result: {}.", deviceRegId, result);
if (result.getErrorCodeName() != null && result.getErrorCodeName().equals(ERROR_CODE_NOT_REGISTERED)) {
return false;
}
} catch (IOException e) {
logger.error("Can't send notification to deviceRegId: {}", deviceRegId);
return false;
}
return true;
}
|
diff --git a/src/main/java/org/atlasapi/media/entity/simple/Location.java b/src/main/java/org/atlasapi/media/entity/simple/Location.java
index 159bf824..b7b2858e 100644
--- a/src/main/java/org/atlasapi/media/entity/simple/Location.java
+++ b/src/main/java/org/atlasapi/media/entity/simple/Location.java
@@ -1,505 +1,507 @@
package org.atlasapi.media.entity.simple;
/* Copyright 2010 Meta Broadcast Ltd
Licensed under the Apache License, Version 2.0 (the "License"); you
may not use this file except in compliance with the License. You may
obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License. */
import java.util.Date;
import java.util.Set;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import org.atlasapi.media.TransportType;
import org.atlasapi.media.vocabulary.PLAY_SIMPLE_XML;
import org.joda.time.DateTime;
import com.google.common.base.Function;
import com.google.common.base.Objects;
import com.google.common.base.Predicate;
import com.google.common.base.Strings;
import com.google.common.collect.Ordering;
import com.google.common.collect.Sets;
import com.metabroadcast.common.time.DateTimeZones;
@XmlRootElement(namespace = PLAY_SIMPLE_XML.NS)
@XmlType(name = "location", namespace = PLAY_SIMPLE_XML.NS)
public class Location extends Version {
private Integer advertisingDuration;
private Integer audioBitRate;
private Integer audioChannels;
private String audioCoding;
private Integer bitRate;
private Boolean containsAdvertising;
private String dataContainerFormat;
private Long dataSize;
private String distributor;
private Boolean hasDOG;
private String source;
private String videoAspectRatio;
private Integer videoBitRate;
private String videoCoding;
private Float videoFrameRate;
private Integer videoHorizontalSize;
private Boolean videoProgressiveScan;
private Integer videoVerticalSize;
private Date actualAvailabilityStart;
private Date availabilityStart;
private Date availabilityEnd;
private Date drmPlayableFrom;
private Set<String> availableCountries = Sets.newHashSet();
private String currency;
private Integer price;
private String revenueContract;
private String restrictedBy;
private Boolean transportIsLive;
private String transportSubType;
private String transportType;
private String uri;
private String embedCode;
private String embedId;
private String platform;
private String network;
private Boolean available;
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public String getDataContainerFormat() {
return dataContainerFormat;
}
public void setDataContainerFormat(String dataContainerFormat) {
this.dataContainerFormat = dataContainerFormat;
}
@XmlElementWrapper(namespace = PLAY_SIMPLE_XML.NS, name = "availableCountries")
@XmlElement(name = "code")
public Set<String> getAvailableCountries() {
return availableCountries;
}
public void setAvailableCountries(Iterable<String> availableCountries) {
this.availableCountries = Sets.newHashSet(availableCountries);
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
public String getRevenueContract() {
return revenueContract;
}
public void setRevenueContract(String revenueContract) {
this.revenueContract = revenueContract;
}
public Integer getAdvertisingDuration() {
return advertisingDuration;
}
public void setAdvertisingDuration(Integer advertisingDuration) {
this.advertisingDuration = advertisingDuration;
}
public Integer getAudioBitRate() {
return audioBitRate;
}
public void setAudioBitRate(Integer audioBitRate) {
this.audioBitRate = audioBitRate;
}
public Integer getAudioChannels() {
return audioChannels;
}
public void setAudioChannels(Integer audioChannels) {
this.audioChannels = audioChannels;
}
public String getAudioCoding() {
return audioCoding;
}
public void setAudioCoding(String audioCoding) {
this.audioCoding = audioCoding;
}
public Integer getBitRate() {
return bitRate;
}
public void setBitRate(Integer bitRate) {
this.bitRate = bitRate;
}
public Boolean getContainsAdvertising() {
return containsAdvertising;
}
public void setContainsAdvertising(Boolean containsAdvertising) {
this.containsAdvertising = containsAdvertising;
}
public Long getDataSize() {
return dataSize;
}
public void setDataSize(Long dataSize) {
this.dataSize = dataSize;
}
public String getDistributor() {
return distributor;
}
public void setDistributor(String distributor) {
this.distributor = distributor;
}
public Boolean getHasDOG() {
return hasDOG;
}
public void setHasDOG(Boolean hasDOG) {
this.hasDOG = hasDOG;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getVideoAspectRatio() {
return videoAspectRatio;
}
public void setVideoAspectRatio(String videoAspectRatio) {
this.videoAspectRatio = videoAspectRatio;
}
public Integer getVideoBitRate() {
return videoBitRate;
}
public void setVideoBitRate(Integer videoBitRate) {
this.videoBitRate = videoBitRate;
}
public String getVideoCoding() {
return videoCoding;
}
public void setVideoCoding(String videoCoding) {
this.videoCoding = videoCoding;
}
public Float getVideoFrameRate() {
return videoFrameRate;
}
public void setVideoFrameRate(Float videoFrameRate) {
this.videoFrameRate = videoFrameRate;
}
public Integer getVideoHorizontalSize() {
return videoHorizontalSize;
}
public void setVideoHorizontalSize(Integer videoHorizontalSize) {
this.videoHorizontalSize = videoHorizontalSize;
}
public Boolean getVideoProgressiveScan() {
return videoProgressiveScan;
}
public void setVideoProgressiveScan(Boolean videoProgressiveScan) {
this.videoProgressiveScan = videoProgressiveScan;
}
public Integer getVideoVerticalSize() {
return videoVerticalSize;
}
public void setVideoVerticalSize(Integer videoVerticalSize) {
this.videoVerticalSize = videoVerticalSize;
}
public Date getActualAvailabilityStart() {
return actualAvailabilityStart;
}
public void setActualAvailabilityStart(Date actualAvailabilityStart) {
this.actualAvailabilityStart = actualAvailabilityStart;
}
public Date getAvailabilityStart() {
return availabilityStart;
}
public void setAvailabilityStart(Date availabilityStart) {
this.availabilityStart = availabilityStart;
}
public Date getDrmPlayableFrom() {
return drmPlayableFrom;
}
public void setDrmPlayableFrom(Date drmPlayableFrom) {
this.drmPlayableFrom = drmPlayableFrom;
}
public String getRestrictedBy() {
return restrictedBy;
}
public void setRestrictedBy(String restrictedBy) {
this.restrictedBy = restrictedBy;
}
public Boolean getTransportIsLive() {
return transportIsLive;
}
public void setTransportIsLive(Boolean transportIsLive) {
this.transportIsLive = transportIsLive;
}
public String getTransportSubType() {
return transportSubType;
}
public void setTransportSubType(String transportSubType) {
this.transportSubType = transportSubType;
}
public String getTransportType() {
return transportType;
}
public void setTransportType(String transportType) {
this.transportType = transportType;
}
public String getEmbedCode() {
return embedCode;
}
public void setEmbedCode(String embedCode) {
this.embedCode = embedCode;
}
public String getEmbedId() {
return embedId;
}
public void setEmbedId(String embedId) {
this.embedId = embedId;
}
@XmlElement
public boolean isAvailable() {
return IS_AVAILABLE.apply(this);
}
public void setAvailable(boolean available) {
this.available = available;
}
public void setAvailabilityEnd(Date availabilityEnd) {
this.availabilityEnd = availabilityEnd;
}
public Date getAvailabilityEnd() {
return availabilityEnd;
}
public void setPlatform(String platform) {
this.platform = platform;
}
public String getPlatform() {
return platform;
}
public void setNetwork(String network) {
this.network = network;
}
public String getNetwork() {
return network;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Location) {
Location target = (Location) obj;
if (isEmbed()) {
return transportType.equals(target.transportType) && Objects.equal(embedCode, target.embedCode) && Objects.equal(embedId, target.embedId);
} else if (!Strings.isNullOrEmpty(uri)) {
return transportType.equals(target.transportType)
&& Objects.equal(uri, target.uri)
&& Objects.equal(actualAvailabilityStart, target.actualAvailabilityStart)
&& Objects.equal(availabilityStart, target.availabilityStart)
&& Objects.equal(platform, target.platform)
&& Objects.equal(network, target.network)
&& Objects.equal(availableCountries, target.availableCountries);
} else {
return super.equals(obj);
}
}
return false;
}
@Override
public int hashCode() {
if (TransportType.EMBED.toString().equals(transportType) && !Strings.isNullOrEmpty(embedCode)) {
return embedCode.hashCode();
} else if (TransportType.EMBED.toString().equals(transportType) && !Strings.isNullOrEmpty(embedId)) {
return embedId.hashCode();
} else if (!Strings.isNullOrEmpty(uri)) {
return Objects.hashCode(uri, transportType, actualAvailabilityStart, availabilityStart, platform, network, availableCountries);
} else {
return super.hashCode();
}
}
@Override
public String toString() {
if (isEmbed()) {
return "embed location: " + embedCode + " and id: "+ embedId;
} else {
return transportType + " location: " + uri;
}
}
private boolean isEmbed() {
return TransportType.EMBED.toString().equals(transportType) && (!Strings.isNullOrEmpty(embedCode) || !Strings.isNullOrEmpty(embedId));
}
public Location copy() {
Location copy = new Location();
copyTo(copy);
copy.setAdvertisingDuration(getAdvertisingDuration());
copy.setAudioBitRate(getAudioBitRate());
copy.setAudioChannels(getAudioChannels());
copy.setAudioCoding(getAudioCoding());
copy.setBitRate(getBitRate());
copy.setContainsAdvertising(getContainsAdvertising());
copy.setDataContainerFormat(getDataContainerFormat());
copy.setDataSize(getDataSize());
copy.setDistributor(getDistributor());
copy.setHasDOG(getHasDOG());
copy.setSource(getSource());
copy.setVideoAspectRatio(getVideoAspectRatio());
copy.setVideoBitRate(getVideoBitRate());
copy.setVideoCoding(getVideoCoding());
copy.setVideoFrameRate(getVideoFrameRate());
copy.setVideoHorizontalSize(getVideoHorizontalSize());
copy.setVideoProgressiveScan(getVideoProgressiveScan());
copy.setVideoVerticalSize(getVideoVerticalSize());
if (getActualAvailabilityStart() != null) {
copy.setActualAvailabilityStart((Date) getActualAvailabilityStart().clone());
}
if (getAvailabilityStart() != null) {
copy.setAvailabilityStart((Date) getAvailabilityStart().clone());
}
if (getAvailabilityEnd() != null) {
copy.setAvailabilityEnd((Date) getAvailabilityEnd().clone());
}
if (getDrmPlayableFrom() != null) {
copy.setDrmPlayableFrom((Date) getDrmPlayableFrom().clone());
}
copy.setAvailableCountries(getAvailableCountries());
copy.setCurrency(getCurrency());
copy.setPrice(getPrice());
copy.setRevenueContract(getRevenueContract());
copy.setRestrictedBy(getRestrictedBy());
copy.setTransportType(getTransportType());
copy.setTransportIsLive(getTransportIsLive());
copy.setTransportSubType(getTransportSubType());
copy.setUri(getUri());
copy.setEmbedCode(getEmbedCode());
copy.setEmbedId(getEmbedId());
copy.setPlatform(getPlatform());
copy.setNetwork(getNetwork());
- copy.setAvailable(available);
+ if (available != null) {
+ copy.setAvailable(available);
+ }
return copy;
}
public static final Predicate<Location> IS_AVAILABLE = new Predicate<Location>() {
@Override
public boolean apply(Location input) {
Date start = input.getActualAvailabilityStart();
start = start == null ? input.getAvailabilityStart() : start;
return (input.available == null || input.available)
&& (start == null || ! (new DateTime(start).isAfterNow()))
&& (input.getAvailabilityEnd() == null || new DateTime(input.getAvailabilityEnd()).isAfterNow());
}
};
public static final Predicate<Location> IS_UPCOMING = new Predicate<Location>() {
@Override
public boolean apply(Location input) {
return input.getAvailabilityStart() != null && new DateTime(input.getAvailabilityStart(), DateTimeZones.UTC).isAfterNow();
}
};
public static final Ordering<Location> BY_AVAILABILITY_START = new Ordering<Location>() {
@Override
public int compare(Location left, Location right) {
return left.getAvailabilityStart().compareTo(right.getAvailabilityStart());
}
};
public static final Function<Location, Location> TO_COPY = new Function<Location, Location>() {
@Override
public Location apply(Location input) {
return input.copy();
}
};
}
| true | true | public Location copy() {
Location copy = new Location();
copyTo(copy);
copy.setAdvertisingDuration(getAdvertisingDuration());
copy.setAudioBitRate(getAudioBitRate());
copy.setAudioChannels(getAudioChannels());
copy.setAudioCoding(getAudioCoding());
copy.setBitRate(getBitRate());
copy.setContainsAdvertising(getContainsAdvertising());
copy.setDataContainerFormat(getDataContainerFormat());
copy.setDataSize(getDataSize());
copy.setDistributor(getDistributor());
copy.setHasDOG(getHasDOG());
copy.setSource(getSource());
copy.setVideoAspectRatio(getVideoAspectRatio());
copy.setVideoBitRate(getVideoBitRate());
copy.setVideoCoding(getVideoCoding());
copy.setVideoFrameRate(getVideoFrameRate());
copy.setVideoHorizontalSize(getVideoHorizontalSize());
copy.setVideoProgressiveScan(getVideoProgressiveScan());
copy.setVideoVerticalSize(getVideoVerticalSize());
if (getActualAvailabilityStart() != null) {
copy.setActualAvailabilityStart((Date) getActualAvailabilityStart().clone());
}
if (getAvailabilityStart() != null) {
copy.setAvailabilityStart((Date) getAvailabilityStart().clone());
}
if (getAvailabilityEnd() != null) {
copy.setAvailabilityEnd((Date) getAvailabilityEnd().clone());
}
if (getDrmPlayableFrom() != null) {
copy.setDrmPlayableFrom((Date) getDrmPlayableFrom().clone());
}
copy.setAvailableCountries(getAvailableCountries());
copy.setCurrency(getCurrency());
copy.setPrice(getPrice());
copy.setRevenueContract(getRevenueContract());
copy.setRestrictedBy(getRestrictedBy());
copy.setTransportType(getTransportType());
copy.setTransportIsLive(getTransportIsLive());
copy.setTransportSubType(getTransportSubType());
copy.setUri(getUri());
copy.setEmbedCode(getEmbedCode());
copy.setEmbedId(getEmbedId());
copy.setPlatform(getPlatform());
copy.setNetwork(getNetwork());
copy.setAvailable(available);
return copy;
}
| public Location copy() {
Location copy = new Location();
copyTo(copy);
copy.setAdvertisingDuration(getAdvertisingDuration());
copy.setAudioBitRate(getAudioBitRate());
copy.setAudioChannels(getAudioChannels());
copy.setAudioCoding(getAudioCoding());
copy.setBitRate(getBitRate());
copy.setContainsAdvertising(getContainsAdvertising());
copy.setDataContainerFormat(getDataContainerFormat());
copy.setDataSize(getDataSize());
copy.setDistributor(getDistributor());
copy.setHasDOG(getHasDOG());
copy.setSource(getSource());
copy.setVideoAspectRatio(getVideoAspectRatio());
copy.setVideoBitRate(getVideoBitRate());
copy.setVideoCoding(getVideoCoding());
copy.setVideoFrameRate(getVideoFrameRate());
copy.setVideoHorizontalSize(getVideoHorizontalSize());
copy.setVideoProgressiveScan(getVideoProgressiveScan());
copy.setVideoVerticalSize(getVideoVerticalSize());
if (getActualAvailabilityStart() != null) {
copy.setActualAvailabilityStart((Date) getActualAvailabilityStart().clone());
}
if (getAvailabilityStart() != null) {
copy.setAvailabilityStart((Date) getAvailabilityStart().clone());
}
if (getAvailabilityEnd() != null) {
copy.setAvailabilityEnd((Date) getAvailabilityEnd().clone());
}
if (getDrmPlayableFrom() != null) {
copy.setDrmPlayableFrom((Date) getDrmPlayableFrom().clone());
}
copy.setAvailableCountries(getAvailableCountries());
copy.setCurrency(getCurrency());
copy.setPrice(getPrice());
copy.setRevenueContract(getRevenueContract());
copy.setRestrictedBy(getRestrictedBy());
copy.setTransportType(getTransportType());
copy.setTransportIsLive(getTransportIsLive());
copy.setTransportSubType(getTransportSubType());
copy.setUri(getUri());
copy.setEmbedCode(getEmbedCode());
copy.setEmbedId(getEmbedId());
copy.setPlatform(getPlatform());
copy.setNetwork(getNetwork());
if (available != null) {
copy.setAvailable(available);
}
return copy;
}
|
diff --git a/src/main/java/jline/ConsoleReader.java b/src/main/java/jline/ConsoleReader.java
index 129dfc1..e51e9e0 100644
--- a/src/main/java/jline/ConsoleReader.java
+++ b/src/main/java/jline/ConsoleReader.java
@@ -1,1626 +1,1627 @@
/*
* Copyright (c) 2002-2007, Marc Prud'hommeaux. All rights reserved.
*
* This software is distributable under the BSD license. See the terms of the
* BSD license in the documentation provided with this software.
*/
package jline;
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.*;
import java.util.List;
/**
* A reader for console applications. It supports custom tab-completion,
* saveable command history, and command line editing. On some platforms,
* platform-specific commands will need to be issued before the reader will
* function properly. See {@link Terminal#initializeTerminal} for convenience
* methods for issuing platform-specific setup commands.
*
* @author <a href="mailto:[email protected]">Marc Prud'hommeaux</a>
*/
public class ConsoleReader implements ConsoleOperations {
final static int TAB_WIDTH = 4;
String prompt;
private boolean useHistory = true;
private boolean usePagination = false;
public static final String CR = System.getProperty("line.separator");
private static ResourceBundle loc = ResourceBundle
.getBundle(CandidateListCompletionHandler.class.getName());
/**
* Map that contains the operation name to keymay operation mapping.
*/
public static SortedMap KEYMAP_NAMES;
static {
Map names = new TreeMap();
names.put("MOVE_TO_BEG", new Short(MOVE_TO_BEG));
names.put("MOVE_TO_END", new Short(MOVE_TO_END));
names.put("PREV_CHAR", new Short(PREV_CHAR));
names.put("NEWLINE", new Short(NEWLINE));
names.put("KILL_LINE", new Short(KILL_LINE));
names.put("PASTE", new Short(PASTE));
names.put("CLEAR_SCREEN", new Short(CLEAR_SCREEN));
names.put("NEXT_HISTORY", new Short(NEXT_HISTORY));
names.put("PREV_HISTORY", new Short(PREV_HISTORY));
names.put("START_OF_HISTORY", new Short(START_OF_HISTORY));
names.put("END_OF_HISTORY", new Short(END_OF_HISTORY));
names.put("REDISPLAY", new Short(REDISPLAY));
names.put("KILL_LINE_PREV", new Short(KILL_LINE_PREV));
names.put("DELETE_PREV_WORD", new Short(DELETE_PREV_WORD));
names.put("NEXT_CHAR", new Short(NEXT_CHAR));
names.put("REPEAT_PREV_CHAR", new Short(REPEAT_PREV_CHAR));
names.put("SEARCH_PREV", new Short(SEARCH_PREV));
names.put("REPEAT_NEXT_CHAR", new Short(REPEAT_NEXT_CHAR));
names.put("SEARCH_NEXT", new Short(SEARCH_NEXT));
names.put("PREV_SPACE_WORD", new Short(PREV_SPACE_WORD));
names.put("TO_END_WORD", new Short(TO_END_WORD));
names.put("REPEAT_SEARCH_PREV", new Short(REPEAT_SEARCH_PREV));
names.put("PASTE_PREV", new Short(PASTE_PREV));
names.put("REPLACE_MODE", new Short(REPLACE_MODE));
names.put("SUBSTITUTE_LINE", new Short(SUBSTITUTE_LINE));
names.put("TO_PREV_CHAR", new Short(TO_PREV_CHAR));
names.put("NEXT_SPACE_WORD", new Short(NEXT_SPACE_WORD));
names.put("DELETE_PREV_CHAR", new Short(DELETE_PREV_CHAR));
names.put("ADD", new Short(ADD));
names.put("PREV_WORD", new Short(PREV_WORD));
names.put("CHANGE_META", new Short(CHANGE_META));
names.put("DELETE_META", new Short(DELETE_META));
names.put("END_WORD", new Short(END_WORD));
names.put("NEXT_CHAR", new Short(NEXT_CHAR));
names.put("INSERT", new Short(INSERT));
names.put("REPEAT_SEARCH_NEXT", new Short(REPEAT_SEARCH_NEXT));
names.put("PASTE_NEXT", new Short(PASTE_NEXT));
names.put("REPLACE_CHAR", new Short(REPLACE_CHAR));
names.put("SUBSTITUTE_CHAR", new Short(SUBSTITUTE_CHAR));
names.put("TO_NEXT_CHAR", new Short(TO_NEXT_CHAR));
names.put("UNDO", new Short(UNDO));
names.put("NEXT_WORD", new Short(NEXT_WORD));
names.put("DELETE_NEXT_CHAR", new Short(DELETE_NEXT_CHAR));
names.put("CHANGE_CASE", new Short(CHANGE_CASE));
names.put("COMPLETE", new Short(COMPLETE));
names.put("EXIT", new Short(EXIT));
names.put("CLEAR_LINE", new Short(CLEAR_LINE));
KEYMAP_NAMES = new TreeMap(Collections.unmodifiableMap(names));
}
/**
* The map for logical operations.
*/
private final short[] keybindings;
/**
* If true, issue an audible keyboard bell when appropriate.
*/
private boolean bellEnabled = true;
/**
* The current character mask.
*/
private Character mask = null;
/**
* The null mask.
*/
private static final Character NULL_MASK = new Character((char) 0);
/**
* The number of tab-completion candidates above which a warning will be
* prompted before showing all the candidates.
*/
private int autoprintThreshhold = Integer.getInteger(
"jline.completion.threshold", 100).intValue(); // same default as
// bash
/**
* The Terminal to use.
*/
private final Terminal terminal;
private CompletionHandler completionHandler = new CandidateListCompletionHandler();
InputStream in;
final Writer out;
final CursorBuffer buf = new CursorBuffer();
static PrintWriter debugger;
History history = new History();
final List completors = new LinkedList();
private Character echoCharacter = null;
private Map triggeredActions = new HashMap();
/**
* Adding a triggered Action allows to give another curse of action
* if a character passed the preprocessing.
*
* Say you want to close the application if the user enter q.
* addTriggerAction('q', new ActionListener(){ System.exit(0); });
* would do the trick.
*
* @param c
* @param listener
*/
public void addTriggeredAction(char c, ActionListener listener){
triggeredActions.put(new Character(c), listener);
}
/**
* Create a new reader using {@link FileDescriptor#in} for input and
* {@link System#out} for output. {@link FileDescriptor#in} is used because
* it has a better chance of being unbuffered.
*/
public ConsoleReader() throws IOException {
this(new FileInputStream(FileDescriptor.in),
new PrintWriter(
new OutputStreamWriter(System.out,
System.getProperty("jline.WindowsTerminal.output.encoding",System.getProperty("file.encoding")))));
}
/**
* Create a new reader using the specified {@link InputStream} for input and
* the specific writer for output, using the default keybindings resource.
*/
public ConsoleReader(final InputStream in, final Writer out)
throws IOException {
this(in, out, null);
}
public ConsoleReader(final InputStream in, final Writer out,
final InputStream bindings) throws IOException {
this(in, out, bindings, Terminal.getTerminal());
}
/**
* Create a new reader.
*
* @param in
* the input
* @param out
* the output
* @param bindings
* the key bindings to use
* @param term
* the terminal to use
*/
public ConsoleReader(InputStream in, Writer out, InputStream bindings,
Terminal term) throws IOException {
this.terminal = term;
setInput(in);
this.out = out;
if (bindings == null) {
try {
String bindingFile = System.getProperty("jline.keybindings",
new File(System.getProperty("user.home",
".jlinebindings.properties")).getAbsolutePath());
if (new File(bindingFile).isFile()) {
bindings = new FileInputStream(new File(bindingFile));
}
} catch (Exception e) {
// swallow exceptions with option debugging
if (debugger != null) {
e.printStackTrace(debugger);
}
}
}
if (bindings == null) {
bindings = terminal.getDefaultBindings();
}
this.keybindings = new short[Character.MAX_VALUE * 2];
Arrays.fill(this.keybindings, UNKNOWN);
/**
* Loads the key bindings. Bindings file is in the format:
*
* keycode: operation name
*/
if (bindings != null) {
Properties p = new Properties();
p.load(bindings);
bindings.close();
for (Iterator i = p.keySet().iterator(); i.hasNext();) {
String val = (String) i.next();
try {
Short code = new Short(val);
String op = (String) p.getProperty(val);
Short opval = (Short) KEYMAP_NAMES.get(op);
if (opval != null) {
keybindings[code.shortValue()] = opval.shortValue();
}
} catch (NumberFormatException nfe) {
consumeException(nfe);
}
}
// hardwired arrow key bindings
// keybindings[VK_UP] = PREV_HISTORY;
// keybindings[VK_DOWN] = NEXT_HISTORY;
// keybindings[VK_LEFT] = PREV_CHAR;
// keybindings[VK_RIGHT] = NEXT_CHAR;
}
}
public Terminal getTerminal() {
return this.terminal;
}
/**
* Set the stream for debugging. Development use only.
*/
public void setDebug(final PrintWriter debugger) {
ConsoleReader.debugger = debugger;
}
/**
* Set the stream to be used for console input.
*/
public void setInput(final InputStream in) {
this.in = in;
}
/**
* Returns the stream used for console input.
*/
public InputStream getInput() {
return this.in;
}
/**
* Read the next line and return the contents of the buffer.
*/
public String readLine() throws IOException {
return readLine((String) null);
}
/**
* Read the next line with the specified character mask. If null, then
* characters will be echoed. If 0, then no characters will be echoed.
*/
public String readLine(final Character mask) throws IOException {
return readLine(null, mask);
}
/**
* @param bellEnabled
* if true, enable audible keyboard bells if an alert is
* required.
*/
public void setBellEnabled(final boolean bellEnabled) {
this.bellEnabled = bellEnabled;
}
/**
* @return true is audible keyboard bell is enabled.
*/
public boolean getBellEnabled() {
return this.bellEnabled;
}
/**
* Query the terminal to find the current width;
*
* @see Terminal#getTerminalWidth
* @return the width of the current terminal.
*/
public int getTermwidth() {
return Terminal.setupTerminal().getTerminalWidth();
}
/**
* Query the terminal to find the current width;
*
* @see Terminal#getTerminalHeight
*
* @return the height of the current terminal.
*/
public int getTermheight() {
return Terminal.setupTerminal().getTerminalHeight();
}
/**
* @param autoprintThreshhold
* the number of candidates to print without issuing a warning.
*/
public void setAutoprintThreshhold(final int autoprintThreshhold) {
this.autoprintThreshhold = autoprintThreshhold;
}
/**
* @return the number of candidates to print without issing a warning.
*/
public int getAutoprintThreshhold() {
return this.autoprintThreshhold;
}
int getKeyForAction(short logicalAction) {
for (int i = 0; i < keybindings.length; i++) {
if (keybindings[i] == logicalAction) {
return i;
}
}
return -1;
}
/**
* Clear the echoed characters for the specified character code.
*/
int clearEcho(int c) throws IOException {
// if the terminal is not echoing, then just return...
if (!terminal.getEcho()) {
return 0;
}
// otherwise, clear
int num = countEchoCharacters((char) c);
back(num);
drawBuffer(num);
return num;
}
int countEchoCharacters(char c) {
// tabs as special: we need to determine the number of spaces
// to cancel based on what out current cursor position is
if (c == 9) {
int tabstop = 8; // will this ever be different?
int position = getCursorPosition();
return tabstop - (position % tabstop);
}
return getPrintableCharacters(c).length();
}
/**
* Return the number of characters that will be printed when the specified
* character is echoed to the screen. Adapted from cat by Torbjorn Granlund,
* as repeated in stty by David MacKenzie.
*/
StringBuffer getPrintableCharacters(char ch) {
StringBuffer sbuff = new StringBuffer();
if (ch >= 32) {
if (ch < 127) {
sbuff.append(ch);
} else if (ch == 127) {
sbuff.append('^');
sbuff.append('?');
} else {
sbuff.append('M');
sbuff.append('-');
if (ch >= (128 + 32)) {
if (ch < (128 + 127)) {
sbuff.append((char) (ch - 128));
} else {
sbuff.append('^');
sbuff.append('?');
}
} else {
sbuff.append('^');
sbuff.append((char) (ch - 128 + 64));
}
}
} else {
sbuff.append('^');
sbuff.append((char) (ch + 64));
}
return sbuff;
}
int getCursorPosition() {
// FIXME: does not handle anything but a line with a prompt
// absolute position
return ((prompt == null) ? 0 : prompt.length()) + buf.cursor;
}
public String readLine(final String prompt) throws IOException {
return readLine(prompt, null);
}
/**
* The default prompt that will be issued.
*/
public void setDefaultPrompt(String prompt) {
this.prompt = prompt;
}
/**
* The default prompt that will be issued.
*/
public String getDefaultPrompt() {
return prompt;
}
/**
* Read a line from the <i>in</i> {@link InputStream}, and return the line
* (without any trailing newlines).
*
* @param prompt
* the prompt to issue to the console, may be null.
* @return a line that is read from the terminal, or null if there was null
* input (e.g., <i>CTRL-D</i> was pressed).
*/
public String readLine(final String prompt, final Character mask)
throws IOException {
this.mask = mask;
if (prompt != null)
this.prompt = prompt;
try {
terminal.beforeReadLine(this, this.prompt, mask);
if ((this.prompt != null) && (this.prompt.length() > 0)) {
out.write(this.prompt);
out.flush();
}
// if the terminal is unsupported, just use plain-java reading
if (!terminal.isSupported()) {
return readLine(in);
}
while (true) {
int[] next = readBinding();
if (next == null) {
return null;
}
int c = next[0];
int code = next[1];
if (c == -1) {
return null;
}
boolean success = true;
switch (code) {
case EXIT: // ctrl-d
if (buf.buffer.length() == 0) {
return null;
}
+ break;
case COMPLETE: // tab
success = complete();
break;
case MOVE_TO_BEG:
success = setCursorPosition(0);
break;
case KILL_LINE: // CTRL-K
success = killLine();
break;
case CLEAR_SCREEN: // CTRL-L
success = clearScreen();
break;
case KILL_LINE_PREV: // CTRL-U
success = resetLine();
break;
case NEWLINE: // enter
moveToEnd();
printNewline(); // output newline
return finishBuffer();
case DELETE_PREV_CHAR: // backspace
success = backspace();
break;
case DELETE_NEXT_CHAR: // delete
success = deleteCurrentCharacter();
break;
case MOVE_TO_END:
success = moveToEnd();
break;
case PREV_CHAR:
success = moveCursor(-1) != 0;
break;
case NEXT_CHAR:
success = moveCursor(1) != 0;
break;
case NEXT_HISTORY:
success = moveHistory(true);
break;
case PREV_HISTORY:
success = moveHistory(false);
break;
case REDISPLAY:
break;
case PASTE:
success = paste();
break;
case DELETE_PREV_WORD:
success = deletePreviousWord();
break;
case PREV_WORD:
success = previousWord();
break;
case NEXT_WORD:
success = nextWord();
break;
case START_OF_HISTORY:
success = history.moveToFirstEntry();
if (success)
setBuffer(history.current());
break;
case END_OF_HISTORY:
success = history.moveToLastEntry();
if (success)
setBuffer(history.current());
break;
case CLEAR_LINE:
moveInternal(-(buf.buffer.length()));
killLine();
break;
case INSERT:
buf.setOvertyping(!buf.isOvertyping());
break;
case UNKNOWN:
default:
if (c != 0) { // ignore null chars
ActionListener action = (ActionListener) triggeredActions.get(new Character((char)c));
if (action != null)
action.actionPerformed(null);
else
putChar(c, true);
} else
success = false;
}
if (!(success)) {
beep();
}
flushConsole();
}
} finally {
terminal.afterReadLine(this, this.prompt, mask);
}
}
private String readLine(InputStream in) throws IOException {
StringBuffer buf = new StringBuffer();
while (true) {
int i = in.read();
if ((i == -1) || (i == '\n') || (i == '\r')) {
return buf.toString();
}
buf.append((char) i);
}
// return new BufferedReader (new InputStreamReader (in)).readLine ();
}
/**
* Reads the console input and returns an array of the form [raw, key
* binding].
*/
private int[] readBinding() throws IOException {
int c = readVirtualKey();
if (c == -1) {
return null;
}
// extract the appropriate key binding
short code = keybindings[c];
if (debugger != null) {
debug(" translated: " + (int) c + ": " + code);
}
return new int[] { c, code };
}
/**
* Move up or down the history tree.
*
* @param direction
* less than 0 to move up the tree, down otherwise
*/
private final boolean moveHistory(final boolean next) throws IOException {
if (next && !history.next()) {
return false;
} else if (!next && !history.previous()) {
return false;
}
setBuffer(history.current());
return true;
}
/**
* Paste the contents of the clipboard into the console buffer
*
* @return true if clipboard contents pasted
*/
public boolean paste() throws IOException {
Clipboard clipboard;
try { // May throw ugly exception on system without X
clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
} catch (Exception e) {
return false;
}
if (clipboard == null) {
return false;
}
Transferable transferable = clipboard.getContents(null);
if (transferable == null) {
return false;
}
try {
Object content = transferable
.getTransferData(DataFlavor.plainTextFlavor);
/*
* This fix was suggested in bug #1060649 at
* http://sourceforge.net/tracker/index.php?func=detail&aid=1060649&group_id=64033&atid=506056
* to get around the deprecated DataFlavor.plainTextFlavor, but it
* raises a UnsupportedFlavorException on Mac OS X
*/
if (content == null) {
try {
content = new DataFlavor().getReaderForText(transferable);
} catch (Exception e) {
}
}
if (content == null) {
return false;
}
String value;
if (content instanceof Reader) {
// TODO: we might want instead connect to the input stream
// so we can interpret individual lines
value = "";
String line = null;
for (BufferedReader read = new BufferedReader((Reader) content); (line = read
.readLine()) != null;) {
if (value.length() > 0) {
value += "\n";
}
value += line;
}
} else {
value = content.toString();
}
if (value == null) {
return true;
}
putString(value);
return true;
} catch (UnsupportedFlavorException ufe) {
if (debugger != null)
debug(ufe + "");
return false;
}
}
/**
* Kill the buffer ahead of the current cursor position.
*
* @return true if successful
*/
public boolean killLine() throws IOException {
int cp = buf.cursor;
int len = buf.buffer.length();
if (cp >= len) {
return false;
}
int num = buf.buffer.length() - cp;
clearAhead(num);
for (int i = 0; i < num; i++) {
buf.buffer.deleteCharAt(len - i - 1);
}
return true;
}
/**
* Clear the screen by issuing the ANSI "clear screen" code.
*/
public boolean clearScreen() throws IOException {
if (!terminal.isANSISupported()) {
return false;
}
// send the ANSI code to clear the screen
printString(((char) 27) + "[2J");
flushConsole();
// then send the ANSI code to go to position 1,1
printString(((char) 27) + "[1;1H");
flushConsole();
redrawLine();
return true;
}
/**
* Use the completors to modify the buffer with the appropriate completions.
*
* @return true if successful
*/
private final boolean complete() throws IOException {
// debug ("tab for (" + buf + ")");
if (completors.size() == 0) {
return false;
}
List candidates = new LinkedList();
String bufstr = buf.buffer.toString();
int cursor = buf.cursor;
int position = -1;
for (Iterator i = completors.iterator(); i.hasNext();) {
Completor comp = (Completor) i.next();
if ((position = comp.complete(bufstr, cursor, candidates)) != -1) {
break;
}
}
// no candidates? Fail.
if (candidates.size() == 0) {
return false;
}
return completionHandler.complete(this, candidates, position);
}
public CursorBuffer getCursorBuffer() {
return buf;
}
/**
* Output the specified {@link Collection} in proper columns.
*
* @param stuff
* the stuff to print
*/
public void printColumns(final Collection stuff) throws IOException {
if ((stuff == null) || (stuff.size() == 0)) {
return;
}
int width = getTermwidth();
int maxwidth = 0;
for (Iterator i = stuff.iterator(); i.hasNext(); maxwidth = Math.max(
maxwidth, i.next().toString().length())) {
;
}
StringBuffer line = new StringBuffer();
int showLines;
if (usePagination)
showLines = getTermheight() - 1; // page limit
else
showLines = Integer.MAX_VALUE;
for (Iterator i = stuff.iterator(); i.hasNext();) {
String cur = (String) i.next();
if ((line.length() + maxwidth) > width) {
printString(line.toString().trim());
printNewline();
line.setLength(0);
if (--showLines == 0) { // Overflow
printString(loc.getString("display-more"));
flushConsole();
int c = readVirtualKey();
if (c == '\r' || c == '\n')
showLines = 1; // one step forward
else if (c != 'q')
showLines = getTermheight() - 1; // page forward
back(loc.getString("display-more").length());
if (c == 'q')
break; // cancel
}
}
pad(cur, maxwidth + 3, line);
}
if (line.length() > 0) {
printString(line.toString().trim());
printNewline();
line.setLength(0);
}
}
/**
* Append <i>toPad</i> to the specified <i>appendTo</i>, as well as (<i>toPad.length () -
* len</i>) spaces.
*
* @param toPad
* the {@link String} to pad
* @param len
* the target length
* @param appendTo
* the {@link StringBuffer} to which to append the padded
* {@link String}.
*/
private final void pad(final String toPad, final int len,
final StringBuffer appendTo) {
appendTo.append(toPad);
for (int i = 0; i < (len - toPad.length()); i++, appendTo.append(' ')) {
;
}
}
/**
* Add the specified {@link Completor} to the list of handlers for
* tab-completion.
*
* @param completor
* the {@link Completor} to add
* @return true if it was successfully added
*/
public boolean addCompletor(final Completor completor) {
return completors.add(completor);
}
/**
* Remove the specified {@link Completor} from the list of handlers for
* tab-completion.
*
* @param completor
* the {@link Completor} to remove
* @return true if it was successfully removed
*/
public boolean removeCompletor(final Completor completor) {
return completors.remove(completor);
}
/**
* Returns an unmodifiable list of all the completors.
*/
public Collection getCompletors() {
return Collections.unmodifiableList(completors);
}
/**
* Erase the current line.
*
* @return false if we failed (e.g., the buffer was empty)
*/
final boolean resetLine() throws IOException {
if (buf.cursor == 0) {
return false;
}
backspaceAll();
return true;
}
/**
* Move the cursor position to the specified absolute index.
*/
public final boolean setCursorPosition(final int position)
throws IOException {
return moveCursor(position - buf.cursor) != 0;
}
/**
* Set the current buffer's content to the specified {@link String}. The
* visual console will be modified to show the current buffer.
*
* @param buffer
* the new contents of the buffer.
*/
private final void setBuffer(final String buffer) throws IOException {
// don't bother modifying it if it is unchanged
if (buffer.equals(buf.buffer.toString())) {
return;
}
// obtain the difference between the current buffer and the new one
int sameIndex = 0;
for (int i = 0, l1 = buffer.length(), l2 = buf.buffer.length(); (i < l1)
&& (i < l2); i++) {
if (buffer.charAt(i) == buf.buffer.charAt(i)) {
sameIndex++;
} else {
break;
}
}
int diff = buf.buffer.length() - sameIndex;
backspace(diff); // go back for the differences
killLine(); // clear to the end of the line
buf.buffer.setLength(sameIndex); // the new length
putString(buffer.substring(sameIndex)); // append the differences
}
/**
* Clear the line and redraw it.
*/
public final void redrawLine() throws IOException {
printCharacter(RESET_LINE);
flushConsole();
drawLine();
}
/**
* Output put the prompt + the current buffer
*/
public final void drawLine() throws IOException {
if (prompt != null) {
printString(prompt);
}
printString(buf.buffer.toString());
if (buf.length() != buf.cursor) // not at end of line
back(buf.length() - buf.cursor); // sync
}
/**
* Output a platform-dependant newline.
*/
public final void printNewline() throws IOException {
printString(CR);
flushConsole();
}
/**
* Clear the buffer and add its contents to the history.
*
* @return the former contents of the buffer.
*/
final String finishBuffer() {
String str = buf.buffer.toString();
// we only add it to the history if the buffer is not empty
// and if mask is null, since having a mask typically means
// the string was a password. We clear the mask after this call
if (str.length() > 0) {
if (mask == null && useHistory) {
history.addToHistory(str);
} else {
mask = null;
}
}
history.moveToEnd();
buf.buffer.setLength(0);
buf.cursor = 0;
return str;
}
/**
* Write out the specified string to the buffer and the output stream.
*/
public final void putString(final String str) throws IOException {
buf.write(str);
printString(str);
drawBuffer();
}
/**
* Output the specified string to the output stream (but not the buffer).
*/
public final void printString(final String str) throws IOException {
printCharacters(str.toCharArray());
}
/**
* Output the specified character, both to the buffer and the output stream.
*/
private final void putChar(final int c, final boolean print)
throws IOException {
buf.write((char) c);
if (print) {
// no masking...
if (mask == null) {
printCharacter(c);
}
// null mask: don't print anything...
else if (mask.charValue() == 0) {
;
}
// otherwise print the mask...
else {
printCharacter(mask.charValue());
}
drawBuffer();
}
}
/**
* Redraw the rest of the buffer from the cursor onwards. This is necessary
* for inserting text into the buffer.
*
* @param clear
* the number of characters to clear after the end of the buffer
*/
private final void drawBuffer(final int clear) throws IOException {
// debug ("drawBuffer: " + clear);
char[] chars = buf.buffer.substring(buf.cursor).toCharArray();
if (mask != null)
Arrays.fill(chars, mask.charValue());
printCharacters(chars);
clearAhead(clear);
back(chars.length);
flushConsole();
}
/**
* Redraw the rest of the buffer from the cursor onwards. This is necessary
* for inserting text into the buffer.
*/
private final void drawBuffer() throws IOException {
drawBuffer(0);
}
/**
* Clear ahead the specified number of characters without moving the cursor.
*/
private final void clearAhead(final int num) throws IOException {
if (num == 0) {
return;
}
// debug ("clearAhead: " + num);
// print blank extra characters
printCharacters(' ', num);
// we need to flush here so a "clever" console
// doesn't just ignore the redundancy of a space followed by
// a backspace.
flushConsole();
// reset the visual cursor
back(num);
flushConsole();
}
/**
* Move the visual cursor backwards without modifying the buffer cursor.
*/
private final void back(final int num) throws IOException {
printCharacters(BACKSPACE, num);
flushConsole();
}
/**
* Issue an audible keyboard bell, if {@link #getBellEnabled} return true.
*/
public final void beep() throws IOException {
if (!(getBellEnabled())) {
return;
}
printCharacter(KEYBOARD_BELL);
// need to flush so the console actually beeps
flushConsole();
}
/**
* Output the specified character to the output stream without manipulating
* the current buffer.
*/
private final void printCharacter(final int c) throws IOException {
if (c == '\t') {
char cbuf[] = new char[TAB_WIDTH];
Arrays.fill(cbuf, ' ');
out.write(cbuf);
return;
}
out.write(c);
}
/**
* Output the specified characters to the output stream without manipulating
* the current buffer.
*/
private final void printCharacters(final char[] c) throws IOException {
int len = 0;
for (int i = 0; i < c.length; i++)
if (c[i] == '\t')
len += TAB_WIDTH;
else
len++;
char cbuf[];
if (len == c.length)
cbuf = c;
else {
cbuf = new char[len];
int pos = 0;
for (int i = 0; i < c.length; i++){
if (c[i] == '\t') {
Arrays.fill(cbuf, pos, pos + TAB_WIDTH, ' ');
pos += TAB_WIDTH;
} else {
cbuf[pos] = c[i];
pos++;
}
}
}
out.write(cbuf);
}
private final void printCharacters(final char c, final int num)
throws IOException {
if (num == 1) {
printCharacter(c);
} else {
char[] chars = new char[num];
Arrays.fill(chars, c);
printCharacters(chars);
}
}
/**
* Flush the console output stream. This is important for printout out
* single characters (like a backspace or keyboard) that we want the console
* to handle immedately.
*/
public final void flushConsole() throws IOException {
out.flush();
}
private final int backspaceAll() throws IOException {
return backspace(Integer.MAX_VALUE);
}
/**
* Issue <em>num</em> backspaces.
*
* @return the number of characters backed up
*/
private final int backspace(final int num) throws IOException {
if (buf.cursor == 0) {
return 0;
}
int count = 0;
count = moveCursor(-1 * num) * -1;
// debug ("Deleting from " + buf.cursor + " for " + count);
buf.buffer.delete(buf.cursor, buf.cursor + count);
drawBuffer(count);
return count;
}
/**
* Issue a backspace.
*
* @return true if successful
*/
public final boolean backspace() throws IOException {
return backspace(1) == 1;
}
private final boolean moveToEnd() throws IOException {
if (moveCursor(1) == 0) {
return false;
}
while (moveCursor(1) != 0) {
;
}
return true;
}
/**
* Delete the character at the current position and redraw the remainder of
* the buffer.
*/
private final boolean deleteCurrentCharacter() throws IOException {
boolean success = buf.buffer.length() > 0;
if (!success) {
return false;
}
if (buf.cursor == buf.buffer.length()) {
return false;
}
buf.buffer.deleteCharAt(buf.cursor);
drawBuffer(1);
return true;
}
private final boolean previousWord() throws IOException {
while (isDelimiter(buf.current()) && (moveCursor(-1) != 0)) {
;
}
while (!isDelimiter(buf.current()) && (moveCursor(-1) != 0)) {
;
}
return true;
}
private final boolean nextWord() throws IOException {
while (isDelimiter(buf.current()) && (moveCursor(1) != 0)) {
;
}
while (!isDelimiter(buf.current()) && (moveCursor(1) != 0)) {
;
}
return true;
}
private final boolean deletePreviousWord() throws IOException {
while (isDelimiter(buf.current()) && backspace()) {
;
}
while (!isDelimiter(buf.current()) && backspace()) {
;
}
return true;
}
/**
* Move the cursor <i>where</i> characters.
*
* @param where
* if less than 0, move abs(<i>where</i>) to the left,
* otherwise move <i>where</i> to the right.
*
* @return the number of spaces we moved
*/
public final int moveCursor(final int num) throws IOException {
int where = num;
if ((buf.cursor == 0) && (where < 0)) {
return 0;
}
if ((buf.cursor == buf.buffer.length()) && (where > 0)) {
return 0;
}
if ((buf.cursor + where) < 0) {
where = -buf.cursor;
} else if ((buf.cursor + where) > buf.buffer.length()) {
where = buf.buffer.length() - buf.cursor;
}
moveInternal(where);
return where;
}
/**
* debug.
*
* @param str
* the message to issue.
*/
public static void debug(final String str) {
if (debugger != null) {
debugger.println(str);
debugger.flush();
}
}
/**
* Move the cursor <i>where</i> characters, withough checking the current
* buffer.
*
* @see #where
*
* @param where
* the number of characters to move to the right or left.
*/
private final void moveInternal(final int where) throws IOException {
// debug ("move cursor " + where + " ("
// + buf.cursor + " => " + (buf.cursor + where) + ")");
buf.cursor += where;
char c;
if (where < 0) {
int len = 0;
for (int i = buf.cursor; i < buf.cursor - where; i++){
if (buf.getBuffer().charAt(i) == '\t')
len += TAB_WIDTH;
else
len++;
}
char cbuf[] = new char[len];
Arrays.fill(cbuf, BACKSPACE);
out.write(cbuf);
return;
} else if (buf.cursor == 0) {
return;
} else if (mask != null) {
c = mask.charValue();
} else {
printCharacters(buf.buffer.substring(buf.cursor - where, buf.cursor).toCharArray());
return;
}
// null character mask: don't output anything
if (NULL_MASK.equals(mask)) {
return;
}
printCharacters(c, Math.abs(where));
}
/**
* Read a character from the console.
*
* @return the character, or -1 if an EOF is received.
*/
public final int readVirtualKey() throws IOException {
int c = terminal.readVirtualKey(in);
if (debugger != null) {
debug("keystroke: " + c + "");
}
// clear any echo characters
clearEcho(c);
return c;
}
public final int readCharacter(final char[] allowed) throws IOException {
// if we restrict to a limited set and the current character
// is not in the set, then try again.
char c;
Arrays.sort(allowed); // always need to sort before binarySearch
while (Arrays.binarySearch(allowed, c = (char) readVirtualKey()) < 0)
;
return c;
}
/**
* Issue <em>num</em> deletes.
*
* @return the number of characters backed up
*/
private final int delete (final int num)
throws IOException
{
/* Commented out beacuse of DWA-2949:
if (buf.cursor == 0)
return 0;*/
buf.buffer.delete (buf.cursor, buf.cursor + 1);
drawBuffer (1);
return 1;
}
public final boolean replace(int num, String replacement) {
buf.buffer.replace(buf.cursor - num, buf.cursor, replacement);
try {
moveCursor(-num);
drawBuffer(Math.max(0, num - replacement.length()));
moveCursor(replacement.length());
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* Issue a delete.
*
* @return true if successful
*/
public final boolean delete ()
throws IOException
{
return delete (1) == 1;
}
public void setHistory(final History history) {
this.history = history;
}
public History getHistory() {
return this.history;
}
public void setCompletionHandler(final CompletionHandler completionHandler) {
this.completionHandler = completionHandler;
}
public CompletionHandler getCompletionHandler() {
return this.completionHandler;
}
/**
* <p>
* Set the echo character. For example, to have "*" entered when a password
* is typed:
* </p>
*
* <pre>
* myConsoleReader.setEchoCharacter(new Character('*'));
* </pre>
*
* <p>
* Setting the character to
*
* <pre>
* null
* </pre>
*
* will restore normal character echoing. Setting the character to
*
* <pre>
* new Character(0)
* </pre>
*
* will cause nothing to be echoed.
* </p>
*
* @param echoCharacter
* the character to echo to the console in place of the typed
* character.
*/
public void setEchoCharacter(final Character echoCharacter) {
this.echoCharacter = echoCharacter;
}
/**
* Returns the echo character.
*/
public Character getEchoCharacter() {
return this.echoCharacter;
}
/**
* No-op for exceptions we want to silently consume.
*/
private void consumeException(final Throwable e) {
}
/**
* Checks to see if the specified character is a delimiter. We consider a
* character a delimiter if it is anything but a letter or digit.
*
* @param c
* the character to test
* @return true if it is a delimiter
*/
private boolean isDelimiter(char c) {
return !Character.isLetterOrDigit(c);
}
/**
* Whether or not to add new commands to the history buffer.
*/
public void setUseHistory(boolean useHistory) {
this.useHistory = useHistory;
}
/**
* Whether or not to add new commands to the history buffer.
*/
public boolean getUseHistory() {
return useHistory;
}
/**
* Whether to use pagination when the number of rows of candidates exceeds
* the height of the temrinal.
*/
public void setUsePagination(boolean usePagination) {
this.usePagination = usePagination;
}
/**
* Whether to use pagination when the number of rows of candidates exceeds
* the height of the temrinal.
*/
public boolean getUsePagination() {
return this.usePagination;
}
}
| true | true | public String readLine(final String prompt, final Character mask)
throws IOException {
this.mask = mask;
if (prompt != null)
this.prompt = prompt;
try {
terminal.beforeReadLine(this, this.prompt, mask);
if ((this.prompt != null) && (this.prompt.length() > 0)) {
out.write(this.prompt);
out.flush();
}
// if the terminal is unsupported, just use plain-java reading
if (!terminal.isSupported()) {
return readLine(in);
}
while (true) {
int[] next = readBinding();
if (next == null) {
return null;
}
int c = next[0];
int code = next[1];
if (c == -1) {
return null;
}
boolean success = true;
switch (code) {
case EXIT: // ctrl-d
if (buf.buffer.length() == 0) {
return null;
}
case COMPLETE: // tab
success = complete();
break;
case MOVE_TO_BEG:
success = setCursorPosition(0);
break;
case KILL_LINE: // CTRL-K
success = killLine();
break;
case CLEAR_SCREEN: // CTRL-L
success = clearScreen();
break;
case KILL_LINE_PREV: // CTRL-U
success = resetLine();
break;
case NEWLINE: // enter
moveToEnd();
printNewline(); // output newline
return finishBuffer();
case DELETE_PREV_CHAR: // backspace
success = backspace();
break;
case DELETE_NEXT_CHAR: // delete
success = deleteCurrentCharacter();
break;
case MOVE_TO_END:
success = moveToEnd();
break;
case PREV_CHAR:
success = moveCursor(-1) != 0;
break;
case NEXT_CHAR:
success = moveCursor(1) != 0;
break;
case NEXT_HISTORY:
success = moveHistory(true);
break;
case PREV_HISTORY:
success = moveHistory(false);
break;
case REDISPLAY:
break;
case PASTE:
success = paste();
break;
case DELETE_PREV_WORD:
success = deletePreviousWord();
break;
case PREV_WORD:
success = previousWord();
break;
case NEXT_WORD:
success = nextWord();
break;
case START_OF_HISTORY:
success = history.moveToFirstEntry();
if (success)
setBuffer(history.current());
break;
case END_OF_HISTORY:
success = history.moveToLastEntry();
if (success)
setBuffer(history.current());
break;
case CLEAR_LINE:
moveInternal(-(buf.buffer.length()));
killLine();
break;
case INSERT:
buf.setOvertyping(!buf.isOvertyping());
break;
case UNKNOWN:
default:
if (c != 0) { // ignore null chars
ActionListener action = (ActionListener) triggeredActions.get(new Character((char)c));
if (action != null)
action.actionPerformed(null);
else
putChar(c, true);
} else
success = false;
}
if (!(success)) {
beep();
}
flushConsole();
}
} finally {
terminal.afterReadLine(this, this.prompt, mask);
}
}
| public String readLine(final String prompt, final Character mask)
throws IOException {
this.mask = mask;
if (prompt != null)
this.prompt = prompt;
try {
terminal.beforeReadLine(this, this.prompt, mask);
if ((this.prompt != null) && (this.prompt.length() > 0)) {
out.write(this.prompt);
out.flush();
}
// if the terminal is unsupported, just use plain-java reading
if (!terminal.isSupported()) {
return readLine(in);
}
while (true) {
int[] next = readBinding();
if (next == null) {
return null;
}
int c = next[0];
int code = next[1];
if (c == -1) {
return null;
}
boolean success = true;
switch (code) {
case EXIT: // ctrl-d
if (buf.buffer.length() == 0) {
return null;
}
break;
case COMPLETE: // tab
success = complete();
break;
case MOVE_TO_BEG:
success = setCursorPosition(0);
break;
case KILL_LINE: // CTRL-K
success = killLine();
break;
case CLEAR_SCREEN: // CTRL-L
success = clearScreen();
break;
case KILL_LINE_PREV: // CTRL-U
success = resetLine();
break;
case NEWLINE: // enter
moveToEnd();
printNewline(); // output newline
return finishBuffer();
case DELETE_PREV_CHAR: // backspace
success = backspace();
break;
case DELETE_NEXT_CHAR: // delete
success = deleteCurrentCharacter();
break;
case MOVE_TO_END:
success = moveToEnd();
break;
case PREV_CHAR:
success = moveCursor(-1) != 0;
break;
case NEXT_CHAR:
success = moveCursor(1) != 0;
break;
case NEXT_HISTORY:
success = moveHistory(true);
break;
case PREV_HISTORY:
success = moveHistory(false);
break;
case REDISPLAY:
break;
case PASTE:
success = paste();
break;
case DELETE_PREV_WORD:
success = deletePreviousWord();
break;
case PREV_WORD:
success = previousWord();
break;
case NEXT_WORD:
success = nextWord();
break;
case START_OF_HISTORY:
success = history.moveToFirstEntry();
if (success)
setBuffer(history.current());
break;
case END_OF_HISTORY:
success = history.moveToLastEntry();
if (success)
setBuffer(history.current());
break;
case CLEAR_LINE:
moveInternal(-(buf.buffer.length()));
killLine();
break;
case INSERT:
buf.setOvertyping(!buf.isOvertyping());
break;
case UNKNOWN:
default:
if (c != 0) { // ignore null chars
ActionListener action = (ActionListener) triggeredActions.get(new Character((char)c));
if (action != null)
action.actionPerformed(null);
else
putChar(c, true);
} else
success = false;
}
if (!(success)) {
beep();
}
flushConsole();
}
} finally {
terminal.afterReadLine(this, this.prompt, mask);
}
}
|
diff --git a/vaadin-touchkit-agpl/src/main/java/com/vaadin/addon/touchkit/gwt/client/VerticalComponentGroupWidget.java b/vaadin-touchkit-agpl/src/main/java/com/vaadin/addon/touchkit/gwt/client/VerticalComponentGroupWidget.java
index d012fb5..e1d3698 100644
--- a/vaadin-touchkit-agpl/src/main/java/com/vaadin/addon/touchkit/gwt/client/VerticalComponentGroupWidget.java
+++ b/vaadin-touchkit-agpl/src/main/java/com/vaadin/addon/touchkit/gwt/client/VerticalComponentGroupWidget.java
@@ -1,80 +1,83 @@
package com.vaadin.addon.touchkit.gwt.client;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Widget;
import com.vaadin.addon.touchkit.gwt.client.navigation.VNavigationButton;
import com.vaadin.shared.ui.VMarginInfo;
import com.vaadin.terminal.gwt.client.StyleConstants;
import com.vaadin.terminal.gwt.client.ui.button.VButton;
public class VerticalComponentGroupWidget extends FlowPanel {
public static final String TAGNAME = "verticalcomponentgroup";
private static final String CLASSNAME = "v-touchkit-" + TAGNAME;
public static final String CAPTION_CLASSNAME = "v-caption";
private boolean firstElement = true;
private HTML captionWidget;
private FlowPanel content = new FlowPanel();
public VerticalComponentGroupWidget() {
content.addStyleName(CLASSNAME);
captionWidget = new HTML("");
captionWidget.addStyleName("v-touchkit-verticalcomponentgroup-caption");
}
public void setCaption(String caption) {
captionWidget.setHTML(caption);
}
/**
* Adds Widget with icon url and caption text
*
* @param widget
* @param icon
* @param caption
*/
public void add(final Widget widget, final String iconUrl,
final String captionText) {
if (firstElement) {
firstElement = false;
add(captionWidget);
add(content);
}
if (iconUrl != null
&& !iconUrl.isEmpty()
&& !(widget instanceof VButton || widget instanceof VNavigationButton)) {
IconWidget newIcon = new IconWidget(iconUrl);
getElement().insertFirst(newIcon.getElement());
}
if (captionText != null
&& !captionText.isEmpty()
&& !(widget instanceof VButton || widget instanceof VNavigationButton)) {
HTML caption = new HTML(captionText);
caption.setStyleName(CAPTION_CLASSNAME);
widget.addStyleName("v-touchkit-has-caption");
content.add(caption);
}
- widget.setWidth("90%");
+ if (!(widget instanceof HorizontalComponentGroupWidget
+ || widget instanceof VButton || widget instanceof VNavigationButton)) {
+ widget.addStyleName("v-touchkit-fitwidth");
+ }
content.add(widget);
}
/**
* Sets CSS classes for margin based on the given parameters.
*
* @param margins
* A {@link VMarginInfo} object that provides info on
* top/left/bottom/right margins
*/
public void setMarginStyles(VMarginInfo margins) {
content.setStyleName(getElement(), TAGNAME + "-"
+ StyleConstants.MARGIN_TOP, margins.hasTop());
content.setStyleName(getElement(), TAGNAME + "-"
+ StyleConstants.MARGIN_RIGHT, margins.hasRight());
content.setStyleName(getElement(), TAGNAME + "-"
+ StyleConstants.MARGIN_BOTTOM, margins.hasBottom());
content.setStyleName(getElement(), TAGNAME + "-"
+ StyleConstants.MARGIN_LEFT, margins.hasLeft());
}
}
| true | true | public void add(final Widget widget, final String iconUrl,
final String captionText) {
if (firstElement) {
firstElement = false;
add(captionWidget);
add(content);
}
if (iconUrl != null
&& !iconUrl.isEmpty()
&& !(widget instanceof VButton || widget instanceof VNavigationButton)) {
IconWidget newIcon = new IconWidget(iconUrl);
getElement().insertFirst(newIcon.getElement());
}
if (captionText != null
&& !captionText.isEmpty()
&& !(widget instanceof VButton || widget instanceof VNavigationButton)) {
HTML caption = new HTML(captionText);
caption.setStyleName(CAPTION_CLASSNAME);
widget.addStyleName("v-touchkit-has-caption");
content.add(caption);
}
widget.setWidth("90%");
content.add(widget);
}
| public void add(final Widget widget, final String iconUrl,
final String captionText) {
if (firstElement) {
firstElement = false;
add(captionWidget);
add(content);
}
if (iconUrl != null
&& !iconUrl.isEmpty()
&& !(widget instanceof VButton || widget instanceof VNavigationButton)) {
IconWidget newIcon = new IconWidget(iconUrl);
getElement().insertFirst(newIcon.getElement());
}
if (captionText != null
&& !captionText.isEmpty()
&& !(widget instanceof VButton || widget instanceof VNavigationButton)) {
HTML caption = new HTML(captionText);
caption.setStyleName(CAPTION_CLASSNAME);
widget.addStyleName("v-touchkit-has-caption");
content.add(caption);
}
if (!(widget instanceof HorizontalComponentGroupWidget
|| widget instanceof VButton || widget instanceof VNavigationButton)) {
widget.addStyleName("v-touchkit-fitwidth");
}
content.add(widget);
}
|
diff --git a/core/src/main/java/com/google/bitcoin/utils/EventListenerInvoker.java b/core/src/main/java/com/google/bitcoin/utils/EventListenerInvoker.java
index e2abfc2..f0dd964 100644
--- a/core/src/main/java/com/google/bitcoin/utils/EventListenerInvoker.java
+++ b/core/src/main/java/com/google/bitcoin/utils/EventListenerInvoker.java
@@ -1,55 +1,57 @@
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.bitcoin.utils;
import java.util.List;
/**
* A utility class that makes it easier to run lists of event listeners that are allowed to
* delete themselves during their execution. Event listeners are locked during execution. <p>
*
* Use like this:<p>
*
* <tt><pre>
* final Foo myself = this;
* final Bar change = ...;
* EventListenerInvoker.invoke(myEventListeners, new EventListenerInvoker<FooEventListener, Void>() {
* public void invoke(FooEventListener listener) {
* listener.onSomethingChanged(myself, change);
* }
* });
* </pre></tt>
*/
public abstract class EventListenerInvoker<E> {
public abstract void invoke(E listener);
public static <E> void invoke(List<E> listeners,
EventListenerInvoker<E> invoker) {
if (listeners == null) return;
synchronized (listeners) {
for (int i = 0; i < listeners.size(); i++) {
E l = listeners.get(i);
synchronized (l) {
invoker.invoke(l);
}
- if (listeners.get(i) != l) {
- i--; // Listener removed itself.
+ if (i == listeners.size()) {
+ break; // Listener removed itself and it was the last one.
+ } else if (listeners.get(i) != l) {
+ i--; // Listener removed itself and it was not the last one.
}
}
}
}
}
| true | true | public static <E> void invoke(List<E> listeners,
EventListenerInvoker<E> invoker) {
if (listeners == null) return;
synchronized (listeners) {
for (int i = 0; i < listeners.size(); i++) {
E l = listeners.get(i);
synchronized (l) {
invoker.invoke(l);
}
if (listeners.get(i) != l) {
i--; // Listener removed itself.
}
}
}
}
| public static <E> void invoke(List<E> listeners,
EventListenerInvoker<E> invoker) {
if (listeners == null) return;
synchronized (listeners) {
for (int i = 0; i < listeners.size(); i++) {
E l = listeners.get(i);
synchronized (l) {
invoker.invoke(l);
}
if (i == listeners.size()) {
break; // Listener removed itself and it was the last one.
} else if (listeners.get(i) != l) {
i--; // Listener removed itself and it was not the last one.
}
}
}
}
|
diff --git a/src/uk/org/ponder/rsf/renderer/html/BasicHTMLRenderSystem.java b/src/uk/org/ponder/rsf/renderer/html/BasicHTMLRenderSystem.java
index 01d8403..1c388b1 100644
--- a/src/uk/org/ponder/rsf/renderer/html/BasicHTMLRenderSystem.java
+++ b/src/uk/org/ponder/rsf/renderer/html/BasicHTMLRenderSystem.java
@@ -1,436 +1,439 @@
/*
* Created on Jul 27, 2005
*/
package uk.org.ponder.rsf.renderer.html;
import java.io.InputStream;
import java.io.Reader;
import java.util.HashMap;
import java.util.Map;
import uk.org.ponder.rsf.components.UIAnchor;
import uk.org.ponder.rsf.components.UIBound;
import uk.org.ponder.rsf.components.UIBoundBoolean;
import uk.org.ponder.rsf.components.UIBoundList;
import uk.org.ponder.rsf.components.UICommand;
import uk.org.ponder.rsf.components.UIComponent;
import uk.org.ponder.rsf.components.UIForm;
import uk.org.ponder.rsf.components.UIInput;
import uk.org.ponder.rsf.components.UILink;
import uk.org.ponder.rsf.components.UIOutput;
import uk.org.ponder.rsf.components.UIOutputMultiline;
import uk.org.ponder.rsf.components.UIParameter;
import uk.org.ponder.rsf.components.UISelect;
import uk.org.ponder.rsf.components.UISelectChoice;
import uk.org.ponder.rsf.components.UISelectLabel;
import uk.org.ponder.rsf.components.UIVerbatim;
import uk.org.ponder.rsf.renderer.ComponentRenderer;
import uk.org.ponder.rsf.renderer.DecoratorManager;
import uk.org.ponder.rsf.renderer.RenderSystem;
import uk.org.ponder.rsf.renderer.RenderUtil;
import uk.org.ponder.rsf.renderer.StaticComponentRenderer;
import uk.org.ponder.rsf.renderer.StaticRendererCollection;
import uk.org.ponder.rsf.renderer.TagRenderContext;
import uk.org.ponder.rsf.request.FossilizedConverter;
import uk.org.ponder.rsf.request.SubmittedValueEntry;
import uk.org.ponder.rsf.template.XMLLump;
import uk.org.ponder.rsf.template.XMLLumpList;
import uk.org.ponder.rsf.uitype.UITypes;
import uk.org.ponder.rsf.view.View;
import uk.org.ponder.streamutil.StreamCopyUtil;
import uk.org.ponder.streamutil.write.PrintOutputStream;
import uk.org.ponder.stringutil.StringList;
import uk.org.ponder.stringutil.URLUtil;
import uk.org.ponder.util.Logger;
import uk.org.ponder.xml.XMLUtil;
import uk.org.ponder.xml.XMLWriter;
/**
* The implementation of the standard XHTML rendering System. This class is due
* for basic refactoring since it contains logic that belongs in a) a "base
* System-independent" lookup bean, and b) in a number of individual
* ComponentRenderer objects.
*
* @author Antranig Basman ([email protected])
*
*/
public class BasicHTMLRenderSystem implements RenderSystem {
private StaticRendererCollection scrc;
private DecoratorManager decoratormanager;
public void setStaticRenderers(StaticRendererCollection scrc) {
this.scrc = scrc;
}
public void setDecoratorManager(DecoratorManager decoratormanager) {
this.decoratormanager = decoratormanager;
}
// two methods for the RenderSystemDecoder interface
public void normalizeRequestMap(Map requestparams) {
String key = RenderUtil.findCommandParams(requestparams);
if (key != null) {
String params = key.substring(FossilizedConverter.COMMAND_LINK_PARAMETERS
.length());
RenderUtil.unpackCommandLink(params, requestparams);
requestparams.remove(key);
}
}
public void fixupUIType(SubmittedValueEntry sve) {
if (sve.oldvalue instanceof Boolean) {
if (sve.newvalue == null)
sve.newvalue = Boolean.FALSE;
}
else if (sve.oldvalue instanceof String[]) {
if (sve.newvalue == null)
sve.newvalue = new String[] {};
}
}
private void closeTag(PrintOutputStream pos, XMLLump uselump) {
pos.print("</");
pos.write(uselump.buffer, uselump.start + 1, uselump.length - 2);
pos.print(">");
}
private void dumpBoundFields(UIBound torender, XMLWriter xmlw) {
if (torender != null) {
if (torender.fossilizedbinding != null) {
RenderUtil.dumpHiddenField(torender.fossilizedbinding.name,
torender.fossilizedbinding.value, xmlw);
}
if (torender.fossilizedshaper != null) {
RenderUtil.dumpHiddenField(torender.fossilizedshaper.name,
torender.fossilizedshaper.value, xmlw);
}
}
}
// No, this method will not stay like this forever! We plan on an architecture
// with renderer-per-component "class" as before, plus interceptors.
// Although a lot of the parameterisation now lies in the allowable tag
// set at target.
public int renderComponent(UIComponent torendero, View view, XMLLump[] lumps,
int lumpindex, PrintOutputStream pos) {
XMLWriter xmlw = new XMLWriter(pos);
XMLLump lump = lumps[lumpindex];
int nextpos = -1;
XMLLump outerendopen = lump.open_end;
XMLLump outerclose = lump.close_tag;
nextpos = outerclose.lumpindex + 1;
XMLLumpList payloadlist = lump.downmap == null ? null
: lump.downmap.hasID(XMLLump.PAYLOAD_COMPONENT) ? lump.downmap
.headsForID(XMLLump.PAYLOAD_COMPONENT)
: null;
XMLLump payload = payloadlist == null ? null
: payloadlist.lumpAt(0);
// if there is no peer component, it might still be a static resource holder
// that needs URLs rewriting.
// we assume there is no payload component here, since there is no producer
// ID that might govern selection. So we use "outer" indices.
if (torendero == null) {
if (lump.rsfID.startsWith(XMLLump.SCR_PREFIX)) {
String scrname = lump.rsfID.substring(XMLLump.SCR_PREFIX.length());
StaticComponentRenderer scr = scrc.getSCR(scrname);
if (scr != null) {
int tagtype = scr.render(lumps, lumpindex, xmlw);
nextpos = tagtype == ComponentRenderer.LEAF_TAG ? outerclose.lumpindex + 1
: outerendopen.lumpindex + 1;
}
}
if (lump.textEquals("<form ")) {
Logger.log.warn("Warning: skipping form tag with rsf:id " + lump.rsfID
+ " and all children at " + lump.toDebugString()
+ " since no peer component");
}
}
else {
// else there IS a component and we are going to render it. First make
// sure we render any preamble.
XMLLump endopen = outerendopen;
XMLLump close = outerclose;
XMLLump uselump = lump;
if (payload != null) {
endopen = payload.open_end;
close = payload.close_tag;
uselump = payload;
RenderUtil.dumpTillLump(lumps, lumpindex, payload.lumpindex, pos);
lumpindex = payload.lumpindex;
}
String fullID = torendero.getFullID();
HashMap attrcopy = new HashMap();
attrcopy.putAll(uselump.attributemap);
attrcopy.put("id", fullID);
attrcopy.remove(XMLLump.ID_ATTRIBUTE);
decoratormanager.decorate(torendero.decorators, uselump.getTag(), attrcopy);
TagRenderContext rendercontext = new TagRenderContext(attrcopy, lumps,
uselump, endopen, close, pos, xmlw);
// ALWAYS dump the tag name, this can never be rewritten. (probably?!)
pos.write(uselump.buffer, uselump.start, uselump.length);
// TODO: Note that these are actually BOUND now. Create some kind of
// defaultBoundRenderer.
if (torendero instanceof UIBound) {
UIBound torender = (UIBound) torendero;
if (!torender.willinput) {
if (torendero.getClass() == UIOutput.class) {
String value = ((UIOutput) torendero).getValue();
rewriteLeaf(value, rendercontext);
}
else if (torendero.getClass() == UIOutputMultiline.class) {
StringList value = ((UIOutputMultiline) torendero).getValue();
if (value == null) {
RenderUtil.dumpTillLump(lumps, lumpindex + 1,
close.lumpindex + 1, pos);
}
else {
XMLUtil.dumpAttributes(attrcopy, xmlw);
pos.print(">");
for (int i = 0; i < value.size(); ++i) {
if (i != 0) {
pos.print("<br/>");
}
xmlw.write(value.stringAt(i));
}
closeTag(pos, uselump);
}
}
else if (torender.getClass() == UIAnchor.class) {
String value = ((UIAnchor) torendero).getValue();
if (UITypes.isPlaceholder(value)) {
renderUnchanged(rendercontext);
}
else {
attrcopy.put("name", value);
replaceAttributes(rendercontext);
}
}
}
// factor out component-invariant processing of UIBound.
else { // Bound with willinput = true
attrcopy.put("name", fullID);
// attrcopy.put("id", fullID);
String value = "";
String body = null;
if (torendero instanceof UIInput) {
value = ((UIInput) torender).getValue();
if (uselump.textEquals("<textarea ")) {
body = value;
}
else {
attrcopy.put("value", value);
}
}
else if (torendero instanceof UIBoundBoolean) {
if (((UIBoundBoolean) torender).getValue()) {
attrcopy.put("checked", "yes");
}
else {
attrcopy.remove("checked");
}
attrcopy.put("value", "true");
}
rewriteLeaf(body, rendercontext);
// unify hidden field processing? ANY parameter children found must
// be dumped as hidden fields.
}
// dump any fossilized binding for this component.
dumpBoundFields(torender, xmlw);
} // end if UIBound
else if (torendero instanceof UISelect) {
UISelect select = (UISelect) torendero;
// The HTML submitted value from a <select> actually corresponds
// with the selection member, not the top-level component.
attrcopy.put("name", select.selection.submittingname);
attrcopy.put("id", select.selection.getFullID());
boolean ishtmlselect = uselump.textEquals("<select ");
if (select.selection instanceof UIBoundList && ishtmlselect) {
attrcopy.put("multiple", "true");
}
XMLUtil.dumpAttributes(attrcopy, xmlw);
if (ishtmlselect) {
pos.print(">");
String[] values = select.optionlist.getValue();
String[] names = select.optionnames == null ? values
: select.optionnames.getValue();
for (int i = 0; i < names.length; ++i) {
pos.print("<option value=\"");
xmlw.write(values[i]);
if (select.selected.contains(values[i])) {
pos.print("\" selected=\"true");
}
pos.print("\">");
xmlw.write(names[i]);
pos.print("</option>\n");
}
closeTag(pos, uselump);
}
else {
dumpTemplateBody(rendercontext);
}
dumpBoundFields(select.selection, xmlw);
dumpBoundFields(select.optionlist, xmlw);
dumpBoundFields(select.optionnames, xmlw);
}
else if (torendero instanceof UISelectChoice) {
UISelectChoice torender = (UISelectChoice) torendero;
UISelect parent = (UISelect) view.getComponent(torender.parentFullID);
String value = parent.optionlist.getValue()[torender.choiceindex];
// currently only peers with "input type="radio"".
attrcopy.put("name", torender.parentFullID +"-selection");
attrcopy.put("value", value);
attrcopy.remove("checked");
if (parent.selected.contains(value)) {
attrcopy.put("checked", "true");
}
replaceAttributes(rendercontext);
}
else if (torendero instanceof UISelectLabel) {
UISelectLabel torender = (UISelectLabel) torendero;
UISelect parent = (UISelect) view.getComponent(torender.parentFullID);
String value = parent.optionnames.getValue()[torender.choiceindex];
replaceBody(value, rendercontext);
}
else if (torendero instanceof UILink) {
UILink torender = (UILink) torendero;
String attrname = URLRewriteSCR.getLinkAttribute(uselump);
if (attrname != null) {
String target = torender.target.getValue();
+ if (target == null || target.length() == 0) {
+ throw new IllegalArgumentException("Empty URL in UILink at " + uselump.toDebugString());
+ }
URLRewriteSCR urlrewriter = (URLRewriteSCR) scrc.getSCR(URLRewriteSCR.NAME);
if (!URLUtil.isAbsolute(target)) {
String rewritten = urlrewriter.resolveURL(target);
if (rewritten != null) target = rewritten;
}
attrcopy.put(attrname, target);
}
String value = torender.linktext == null ? null
: torender.linktext.getValue();
rewriteLeaf(value, rendercontext);
}
else if (torendero instanceof UICommand) {
UICommand torender = (UICommand) torendero;
String value = RenderUtil.makeURLAttributes(torender.parameters);
// any desired "attributes" decoded for JUST THIS ACTION must be
// secretly
// bundled as this special attribute.
attrcopy.put("name", FossilizedConverter.COMMAND_LINK_PARAMETERS
+ value);
String text = torender.commandtext;
boolean isbutton = lump.textEquals("<button ");
if (text != null && !isbutton) {
attrcopy.put("value", torender.commandtext);
text = null;
}
rewriteLeaf(text, rendercontext);
// RenderUtil.dumpHiddenField(SubmittedValueEntry.ACTION_METHOD,
// torender.actionhandler, pos);
}
// Forms behave slightly oddly in the hierarchy - by the time they reach
// the renderer, they have been "shunted out" of line with their children,
// i.e. any "submitting" controls, if indeed they ever were there.
else if (torendero instanceof UIForm) {
UIForm torender = (UIForm) torendero;
if (attrcopy.get("method") == null) { // forms DEFAULT to be post
attrcopy.put("method", "post");
}
// form fixer guarantees that this URL is attribute free.
attrcopy.put("action", torender.targetURL);
XMLUtil.dumpAttributes(attrcopy, xmlw);
pos.println(">");
for (int i = 0; i < torender.parameters.size(); ++i) {
UIParameter param = torender.parameters.parameterAt(i);
RenderUtil.dumpHiddenField(param.name, param.value, xmlw);
}
// override "nextpos" - form is expected to contain numerous nested
// Components.
// this is the only ANOMALY!! Forms together with payload cannot work.
// the fact we are at the wrong recursion level will "come out in the
// wash"
// since we must return to the base recursion level before we exit this
// domain.
// Assuming there are no paths *IN* through forms that do not also lead
// *OUT* there will be no problem. Check what this *MEANS* tomorrow.
nextpos = endopen.lumpindex + 1;
}
else if (torendero instanceof UIVerbatim) {
UIVerbatim torender = (UIVerbatim) torendero;
String rendered = null;
// inefficient implementation for now, upgrade when we write bulk POS
// utils.
if (torender.markup instanceof InputStream) {
rendered = StreamCopyUtil
.streamToString((InputStream) torender.markup);
}
else if (torender.markup instanceof Reader) {
rendered = StreamCopyUtil.readerToString((Reader) torender.markup);
}
else if (torender.markup != null) {
rendered = torender.markup.toString();
}
if (rendered == null) {
renderUnchanged(rendercontext);
}
else {
XMLUtil.dumpAttributes(attrcopy, xmlw);
pos.print(">");
pos.print(rendered);
closeTag(pos, uselump);
}
}
// if there is a payload, dump the postamble.
if (payload != null) {
RenderUtil.dumpTillLump(lumps, close.lumpindex + 1,
outerclose.lumpindex + 1, pos);
}
}
return nextpos;
}
private void renderUnchanged(TagRenderContext c) {
RenderUtil.dumpTillLump(c.lumps, c.uselump.lumpindex + 1,
c.close.lumpindex + 1, c.pos);
}
private void rewriteLeaf(String value, TagRenderContext c) {
if (value != null && !UITypes.isPlaceholder(value)) replaceBody(value, c);
else replaceAttributes(c);
}
private void replaceBody(String value, TagRenderContext c) {
XMLUtil.dumpAttributes(c.attrcopy, c.xmlw);
c.pos.print(">");
c.xmlw.write(value);
closeTag(c.pos, c.uselump);
}
private void replaceAttributes(TagRenderContext c) {
XMLUtil.dumpAttributes(c.attrcopy, c.xmlw);
dumpTemplateBody(c);
}
private void dumpTemplateBody(TagRenderContext c) {
if (c.endopen.lumpindex == c.close.lumpindex) {
c.pos.print("/>");
}
else {
c.pos.print(">");
RenderUtil.dumpTillLump(c.lumps, c.endopen.lumpindex + 1,
c.close.lumpindex + 1, c.pos);
}
}
}
| true | true | public int renderComponent(UIComponent torendero, View view, XMLLump[] lumps,
int lumpindex, PrintOutputStream pos) {
XMLWriter xmlw = new XMLWriter(pos);
XMLLump lump = lumps[lumpindex];
int nextpos = -1;
XMLLump outerendopen = lump.open_end;
XMLLump outerclose = lump.close_tag;
nextpos = outerclose.lumpindex + 1;
XMLLumpList payloadlist = lump.downmap == null ? null
: lump.downmap.hasID(XMLLump.PAYLOAD_COMPONENT) ? lump.downmap
.headsForID(XMLLump.PAYLOAD_COMPONENT)
: null;
XMLLump payload = payloadlist == null ? null
: payloadlist.lumpAt(0);
// if there is no peer component, it might still be a static resource holder
// that needs URLs rewriting.
// we assume there is no payload component here, since there is no producer
// ID that might govern selection. So we use "outer" indices.
if (torendero == null) {
if (lump.rsfID.startsWith(XMLLump.SCR_PREFIX)) {
String scrname = lump.rsfID.substring(XMLLump.SCR_PREFIX.length());
StaticComponentRenderer scr = scrc.getSCR(scrname);
if (scr != null) {
int tagtype = scr.render(lumps, lumpindex, xmlw);
nextpos = tagtype == ComponentRenderer.LEAF_TAG ? outerclose.lumpindex + 1
: outerendopen.lumpindex + 1;
}
}
if (lump.textEquals("<form ")) {
Logger.log.warn("Warning: skipping form tag with rsf:id " + lump.rsfID
+ " and all children at " + lump.toDebugString()
+ " since no peer component");
}
}
else {
// else there IS a component and we are going to render it. First make
// sure we render any preamble.
XMLLump endopen = outerendopen;
XMLLump close = outerclose;
XMLLump uselump = lump;
if (payload != null) {
endopen = payload.open_end;
close = payload.close_tag;
uselump = payload;
RenderUtil.dumpTillLump(lumps, lumpindex, payload.lumpindex, pos);
lumpindex = payload.lumpindex;
}
String fullID = torendero.getFullID();
HashMap attrcopy = new HashMap();
attrcopy.putAll(uselump.attributemap);
attrcopy.put("id", fullID);
attrcopy.remove(XMLLump.ID_ATTRIBUTE);
decoratormanager.decorate(torendero.decorators, uselump.getTag(), attrcopy);
TagRenderContext rendercontext = new TagRenderContext(attrcopy, lumps,
uselump, endopen, close, pos, xmlw);
// ALWAYS dump the tag name, this can never be rewritten. (probably?!)
pos.write(uselump.buffer, uselump.start, uselump.length);
// TODO: Note that these are actually BOUND now. Create some kind of
// defaultBoundRenderer.
if (torendero instanceof UIBound) {
UIBound torender = (UIBound) torendero;
if (!torender.willinput) {
if (torendero.getClass() == UIOutput.class) {
String value = ((UIOutput) torendero).getValue();
rewriteLeaf(value, rendercontext);
}
else if (torendero.getClass() == UIOutputMultiline.class) {
StringList value = ((UIOutputMultiline) torendero).getValue();
if (value == null) {
RenderUtil.dumpTillLump(lumps, lumpindex + 1,
close.lumpindex + 1, pos);
}
else {
XMLUtil.dumpAttributes(attrcopy, xmlw);
pos.print(">");
for (int i = 0; i < value.size(); ++i) {
if (i != 0) {
pos.print("<br/>");
}
xmlw.write(value.stringAt(i));
}
closeTag(pos, uselump);
}
}
else if (torender.getClass() == UIAnchor.class) {
String value = ((UIAnchor) torendero).getValue();
if (UITypes.isPlaceholder(value)) {
renderUnchanged(rendercontext);
}
else {
attrcopy.put("name", value);
replaceAttributes(rendercontext);
}
}
}
// factor out component-invariant processing of UIBound.
else { // Bound with willinput = true
attrcopy.put("name", fullID);
// attrcopy.put("id", fullID);
String value = "";
String body = null;
if (torendero instanceof UIInput) {
value = ((UIInput) torender).getValue();
if (uselump.textEquals("<textarea ")) {
body = value;
}
else {
attrcopy.put("value", value);
}
}
else if (torendero instanceof UIBoundBoolean) {
if (((UIBoundBoolean) torender).getValue()) {
attrcopy.put("checked", "yes");
}
else {
attrcopy.remove("checked");
}
attrcopy.put("value", "true");
}
rewriteLeaf(body, rendercontext);
// unify hidden field processing? ANY parameter children found must
// be dumped as hidden fields.
}
// dump any fossilized binding for this component.
dumpBoundFields(torender, xmlw);
} // end if UIBound
else if (torendero instanceof UISelect) {
UISelect select = (UISelect) torendero;
// The HTML submitted value from a <select> actually corresponds
// with the selection member, not the top-level component.
attrcopy.put("name", select.selection.submittingname);
attrcopy.put("id", select.selection.getFullID());
boolean ishtmlselect = uselump.textEquals("<select ");
if (select.selection instanceof UIBoundList && ishtmlselect) {
attrcopy.put("multiple", "true");
}
XMLUtil.dumpAttributes(attrcopy, xmlw);
if (ishtmlselect) {
pos.print(">");
String[] values = select.optionlist.getValue();
String[] names = select.optionnames == null ? values
: select.optionnames.getValue();
for (int i = 0; i < names.length; ++i) {
pos.print("<option value=\"");
xmlw.write(values[i]);
if (select.selected.contains(values[i])) {
pos.print("\" selected=\"true");
}
pos.print("\">");
xmlw.write(names[i]);
pos.print("</option>\n");
}
closeTag(pos, uselump);
}
else {
dumpTemplateBody(rendercontext);
}
dumpBoundFields(select.selection, xmlw);
dumpBoundFields(select.optionlist, xmlw);
dumpBoundFields(select.optionnames, xmlw);
}
else if (torendero instanceof UISelectChoice) {
UISelectChoice torender = (UISelectChoice) torendero;
UISelect parent = (UISelect) view.getComponent(torender.parentFullID);
String value = parent.optionlist.getValue()[torender.choiceindex];
// currently only peers with "input type="radio"".
attrcopy.put("name", torender.parentFullID +"-selection");
attrcopy.put("value", value);
attrcopy.remove("checked");
if (parent.selected.contains(value)) {
attrcopy.put("checked", "true");
}
replaceAttributes(rendercontext);
}
else if (torendero instanceof UISelectLabel) {
UISelectLabel torender = (UISelectLabel) torendero;
UISelect parent = (UISelect) view.getComponent(torender.parentFullID);
String value = parent.optionnames.getValue()[torender.choiceindex];
replaceBody(value, rendercontext);
}
else if (torendero instanceof UILink) {
UILink torender = (UILink) torendero;
String attrname = URLRewriteSCR.getLinkAttribute(uselump);
if (attrname != null) {
String target = torender.target.getValue();
URLRewriteSCR urlrewriter = (URLRewriteSCR) scrc.getSCR(URLRewriteSCR.NAME);
if (!URLUtil.isAbsolute(target)) {
String rewritten = urlrewriter.resolveURL(target);
if (rewritten != null) target = rewritten;
}
attrcopy.put(attrname, target);
}
String value = torender.linktext == null ? null
: torender.linktext.getValue();
rewriteLeaf(value, rendercontext);
}
else if (torendero instanceof UICommand) {
UICommand torender = (UICommand) torendero;
String value = RenderUtil.makeURLAttributes(torender.parameters);
// any desired "attributes" decoded for JUST THIS ACTION must be
// secretly
// bundled as this special attribute.
attrcopy.put("name", FossilizedConverter.COMMAND_LINK_PARAMETERS
+ value);
String text = torender.commandtext;
boolean isbutton = lump.textEquals("<button ");
if (text != null && !isbutton) {
attrcopy.put("value", torender.commandtext);
text = null;
}
rewriteLeaf(text, rendercontext);
// RenderUtil.dumpHiddenField(SubmittedValueEntry.ACTION_METHOD,
// torender.actionhandler, pos);
}
// Forms behave slightly oddly in the hierarchy - by the time they reach
// the renderer, they have been "shunted out" of line with their children,
// i.e. any "submitting" controls, if indeed they ever were there.
else if (torendero instanceof UIForm) {
UIForm torender = (UIForm) torendero;
if (attrcopy.get("method") == null) { // forms DEFAULT to be post
attrcopy.put("method", "post");
}
// form fixer guarantees that this URL is attribute free.
attrcopy.put("action", torender.targetURL);
XMLUtil.dumpAttributes(attrcopy, xmlw);
pos.println(">");
for (int i = 0; i < torender.parameters.size(); ++i) {
UIParameter param = torender.parameters.parameterAt(i);
RenderUtil.dumpHiddenField(param.name, param.value, xmlw);
}
// override "nextpos" - form is expected to contain numerous nested
// Components.
// this is the only ANOMALY!! Forms together with payload cannot work.
// the fact we are at the wrong recursion level will "come out in the
// wash"
// since we must return to the base recursion level before we exit this
// domain.
// Assuming there are no paths *IN* through forms that do not also lead
// *OUT* there will be no problem. Check what this *MEANS* tomorrow.
nextpos = endopen.lumpindex + 1;
}
else if (torendero instanceof UIVerbatim) {
UIVerbatim torender = (UIVerbatim) torendero;
String rendered = null;
// inefficient implementation for now, upgrade when we write bulk POS
// utils.
if (torender.markup instanceof InputStream) {
rendered = StreamCopyUtil
.streamToString((InputStream) torender.markup);
}
else if (torender.markup instanceof Reader) {
rendered = StreamCopyUtil.readerToString((Reader) torender.markup);
}
else if (torender.markup != null) {
rendered = torender.markup.toString();
}
if (rendered == null) {
renderUnchanged(rendercontext);
}
else {
XMLUtil.dumpAttributes(attrcopy, xmlw);
pos.print(">");
pos.print(rendered);
closeTag(pos, uselump);
}
}
// if there is a payload, dump the postamble.
if (payload != null) {
RenderUtil.dumpTillLump(lumps, close.lumpindex + 1,
outerclose.lumpindex + 1, pos);
}
}
return nextpos;
}
| public int renderComponent(UIComponent torendero, View view, XMLLump[] lumps,
int lumpindex, PrintOutputStream pos) {
XMLWriter xmlw = new XMLWriter(pos);
XMLLump lump = lumps[lumpindex];
int nextpos = -1;
XMLLump outerendopen = lump.open_end;
XMLLump outerclose = lump.close_tag;
nextpos = outerclose.lumpindex + 1;
XMLLumpList payloadlist = lump.downmap == null ? null
: lump.downmap.hasID(XMLLump.PAYLOAD_COMPONENT) ? lump.downmap
.headsForID(XMLLump.PAYLOAD_COMPONENT)
: null;
XMLLump payload = payloadlist == null ? null
: payloadlist.lumpAt(0);
// if there is no peer component, it might still be a static resource holder
// that needs URLs rewriting.
// we assume there is no payload component here, since there is no producer
// ID that might govern selection. So we use "outer" indices.
if (torendero == null) {
if (lump.rsfID.startsWith(XMLLump.SCR_PREFIX)) {
String scrname = lump.rsfID.substring(XMLLump.SCR_PREFIX.length());
StaticComponentRenderer scr = scrc.getSCR(scrname);
if (scr != null) {
int tagtype = scr.render(lumps, lumpindex, xmlw);
nextpos = tagtype == ComponentRenderer.LEAF_TAG ? outerclose.lumpindex + 1
: outerendopen.lumpindex + 1;
}
}
if (lump.textEquals("<form ")) {
Logger.log.warn("Warning: skipping form tag with rsf:id " + lump.rsfID
+ " and all children at " + lump.toDebugString()
+ " since no peer component");
}
}
else {
// else there IS a component and we are going to render it. First make
// sure we render any preamble.
XMLLump endopen = outerendopen;
XMLLump close = outerclose;
XMLLump uselump = lump;
if (payload != null) {
endopen = payload.open_end;
close = payload.close_tag;
uselump = payload;
RenderUtil.dumpTillLump(lumps, lumpindex, payload.lumpindex, pos);
lumpindex = payload.lumpindex;
}
String fullID = torendero.getFullID();
HashMap attrcopy = new HashMap();
attrcopy.putAll(uselump.attributemap);
attrcopy.put("id", fullID);
attrcopy.remove(XMLLump.ID_ATTRIBUTE);
decoratormanager.decorate(torendero.decorators, uselump.getTag(), attrcopy);
TagRenderContext rendercontext = new TagRenderContext(attrcopy, lumps,
uselump, endopen, close, pos, xmlw);
// ALWAYS dump the tag name, this can never be rewritten. (probably?!)
pos.write(uselump.buffer, uselump.start, uselump.length);
// TODO: Note that these are actually BOUND now. Create some kind of
// defaultBoundRenderer.
if (torendero instanceof UIBound) {
UIBound torender = (UIBound) torendero;
if (!torender.willinput) {
if (torendero.getClass() == UIOutput.class) {
String value = ((UIOutput) torendero).getValue();
rewriteLeaf(value, rendercontext);
}
else if (torendero.getClass() == UIOutputMultiline.class) {
StringList value = ((UIOutputMultiline) torendero).getValue();
if (value == null) {
RenderUtil.dumpTillLump(lumps, lumpindex + 1,
close.lumpindex + 1, pos);
}
else {
XMLUtil.dumpAttributes(attrcopy, xmlw);
pos.print(">");
for (int i = 0; i < value.size(); ++i) {
if (i != 0) {
pos.print("<br/>");
}
xmlw.write(value.stringAt(i));
}
closeTag(pos, uselump);
}
}
else if (torender.getClass() == UIAnchor.class) {
String value = ((UIAnchor) torendero).getValue();
if (UITypes.isPlaceholder(value)) {
renderUnchanged(rendercontext);
}
else {
attrcopy.put("name", value);
replaceAttributes(rendercontext);
}
}
}
// factor out component-invariant processing of UIBound.
else { // Bound with willinput = true
attrcopy.put("name", fullID);
// attrcopy.put("id", fullID);
String value = "";
String body = null;
if (torendero instanceof UIInput) {
value = ((UIInput) torender).getValue();
if (uselump.textEquals("<textarea ")) {
body = value;
}
else {
attrcopy.put("value", value);
}
}
else if (torendero instanceof UIBoundBoolean) {
if (((UIBoundBoolean) torender).getValue()) {
attrcopy.put("checked", "yes");
}
else {
attrcopy.remove("checked");
}
attrcopy.put("value", "true");
}
rewriteLeaf(body, rendercontext);
// unify hidden field processing? ANY parameter children found must
// be dumped as hidden fields.
}
// dump any fossilized binding for this component.
dumpBoundFields(torender, xmlw);
} // end if UIBound
else if (torendero instanceof UISelect) {
UISelect select = (UISelect) torendero;
// The HTML submitted value from a <select> actually corresponds
// with the selection member, not the top-level component.
attrcopy.put("name", select.selection.submittingname);
attrcopy.put("id", select.selection.getFullID());
boolean ishtmlselect = uselump.textEquals("<select ");
if (select.selection instanceof UIBoundList && ishtmlselect) {
attrcopy.put("multiple", "true");
}
XMLUtil.dumpAttributes(attrcopy, xmlw);
if (ishtmlselect) {
pos.print(">");
String[] values = select.optionlist.getValue();
String[] names = select.optionnames == null ? values
: select.optionnames.getValue();
for (int i = 0; i < names.length; ++i) {
pos.print("<option value=\"");
xmlw.write(values[i]);
if (select.selected.contains(values[i])) {
pos.print("\" selected=\"true");
}
pos.print("\">");
xmlw.write(names[i]);
pos.print("</option>\n");
}
closeTag(pos, uselump);
}
else {
dumpTemplateBody(rendercontext);
}
dumpBoundFields(select.selection, xmlw);
dumpBoundFields(select.optionlist, xmlw);
dumpBoundFields(select.optionnames, xmlw);
}
else if (torendero instanceof UISelectChoice) {
UISelectChoice torender = (UISelectChoice) torendero;
UISelect parent = (UISelect) view.getComponent(torender.parentFullID);
String value = parent.optionlist.getValue()[torender.choiceindex];
// currently only peers with "input type="radio"".
attrcopy.put("name", torender.parentFullID +"-selection");
attrcopy.put("value", value);
attrcopy.remove("checked");
if (parent.selected.contains(value)) {
attrcopy.put("checked", "true");
}
replaceAttributes(rendercontext);
}
else if (torendero instanceof UISelectLabel) {
UISelectLabel torender = (UISelectLabel) torendero;
UISelect parent = (UISelect) view.getComponent(torender.parentFullID);
String value = parent.optionnames.getValue()[torender.choiceindex];
replaceBody(value, rendercontext);
}
else if (torendero instanceof UILink) {
UILink torender = (UILink) torendero;
String attrname = URLRewriteSCR.getLinkAttribute(uselump);
if (attrname != null) {
String target = torender.target.getValue();
if (target == null || target.length() == 0) {
throw new IllegalArgumentException("Empty URL in UILink at " + uselump.toDebugString());
}
URLRewriteSCR urlrewriter = (URLRewriteSCR) scrc.getSCR(URLRewriteSCR.NAME);
if (!URLUtil.isAbsolute(target)) {
String rewritten = urlrewriter.resolveURL(target);
if (rewritten != null) target = rewritten;
}
attrcopy.put(attrname, target);
}
String value = torender.linktext == null ? null
: torender.linktext.getValue();
rewriteLeaf(value, rendercontext);
}
else if (torendero instanceof UICommand) {
UICommand torender = (UICommand) torendero;
String value = RenderUtil.makeURLAttributes(torender.parameters);
// any desired "attributes" decoded for JUST THIS ACTION must be
// secretly
// bundled as this special attribute.
attrcopy.put("name", FossilizedConverter.COMMAND_LINK_PARAMETERS
+ value);
String text = torender.commandtext;
boolean isbutton = lump.textEquals("<button ");
if (text != null && !isbutton) {
attrcopy.put("value", torender.commandtext);
text = null;
}
rewriteLeaf(text, rendercontext);
// RenderUtil.dumpHiddenField(SubmittedValueEntry.ACTION_METHOD,
// torender.actionhandler, pos);
}
// Forms behave slightly oddly in the hierarchy - by the time they reach
// the renderer, they have been "shunted out" of line with their children,
// i.e. any "submitting" controls, if indeed they ever were there.
else if (torendero instanceof UIForm) {
UIForm torender = (UIForm) torendero;
if (attrcopy.get("method") == null) { // forms DEFAULT to be post
attrcopy.put("method", "post");
}
// form fixer guarantees that this URL is attribute free.
attrcopy.put("action", torender.targetURL);
XMLUtil.dumpAttributes(attrcopy, xmlw);
pos.println(">");
for (int i = 0; i < torender.parameters.size(); ++i) {
UIParameter param = torender.parameters.parameterAt(i);
RenderUtil.dumpHiddenField(param.name, param.value, xmlw);
}
// override "nextpos" - form is expected to contain numerous nested
// Components.
// this is the only ANOMALY!! Forms together with payload cannot work.
// the fact we are at the wrong recursion level will "come out in the
// wash"
// since we must return to the base recursion level before we exit this
// domain.
// Assuming there are no paths *IN* through forms that do not also lead
// *OUT* there will be no problem. Check what this *MEANS* tomorrow.
nextpos = endopen.lumpindex + 1;
}
else if (torendero instanceof UIVerbatim) {
UIVerbatim torender = (UIVerbatim) torendero;
String rendered = null;
// inefficient implementation for now, upgrade when we write bulk POS
// utils.
if (torender.markup instanceof InputStream) {
rendered = StreamCopyUtil
.streamToString((InputStream) torender.markup);
}
else if (torender.markup instanceof Reader) {
rendered = StreamCopyUtil.readerToString((Reader) torender.markup);
}
else if (torender.markup != null) {
rendered = torender.markup.toString();
}
if (rendered == null) {
renderUnchanged(rendercontext);
}
else {
XMLUtil.dumpAttributes(attrcopy, xmlw);
pos.print(">");
pos.print(rendered);
closeTag(pos, uselump);
}
}
// if there is a payload, dump the postamble.
if (payload != null) {
RenderUtil.dumpTillLump(lumps, close.lumpindex + 1,
outerclose.lumpindex + 1, pos);
}
}
return nextpos;
}
|
diff --git a/src/mccity/plugins/pvprealm/object/PvpPlayer.java b/src/mccity/plugins/pvprealm/object/PvpPlayer.java
index 567e972..6a452a6 100644
--- a/src/mccity/plugins/pvprealm/object/PvpPlayer.java
+++ b/src/mccity/plugins/pvprealm/object/PvpPlayer.java
@@ -1,190 +1,190 @@
package mccity.plugins.pvprealm.object;
import com.herocraftonline.heroes.characters.Hero;
import com.herocraftonline.heroes.characters.classes.HeroClass;
import mccity.plugins.pvprealm.Config;
import mccity.plugins.pvprealm.PvpRealm;
import mccity.plugins.pvprealm.PvpRealmEventHandler;
import me.galaran.bukkitutils.pvprealm.GUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import java.util.*;
import java.util.logging.Level;
public class PvpPlayer implements ConfigurationSerializable {
private final PvpRealm plugin;
private final String name;
private Player player;
private Location returnLoc;
public PvpPlayer(PvpRealm plugin, Player player) {
this.plugin = plugin;
this.player = player;
name = player.getName();
returnLoc = null;
}
public void updateEntity(Player player) {
this.player = player;
}
public Player getPlayer() {
return player;
}
public void giveKit(ItemsKit kit, boolean dropIfFull) {
Inventory inv = player.getInventory();
HashMap<Integer,ItemStack> ungiven = inv.addItem(kit.getStacks());
if (ungiven != null && !ungiven.isEmpty()) {
GUtils.sendMessage(player, "You have not enought slots in the inventory");
if (dropIfFull) {
World world = player.getWorld();
for (ItemStack ungivenStack : ungiven.values()) {
world.dropItem(player.getLocation().add(0, 2, 0), ungivenStack);
}
}
}
player.updateInventory();
GUtils.sendMessage(player, "You have obtain kit " + ChatColor.GOLD + kit.getName());
}
public void enterPvpRealm() {
Location curLoc = player.getLocation();
if (curLoc.getWorld().equals(Config.pvpWorld)) { // no action required
GUtils.log("Player " + player.getName() + " entering to pvp world " + Config.pvpWorld.getName() +
" but it already in", Level.WARNING);
return;
}
if (teleportUnchecked(Config.entryLoc)) {
returnLoc = curLoc;
} else {
GUtils.log("Failed to teleport player " + player.getName() + " into pvp world ", Level.WARNING);
}
}
public void leavePvpRealm() {
Location curLoc = player.getLocation();
String playerName = player.getName();
if (!curLoc.getWorld().equals(Config.pvpWorld)) { // no action required
GUtils.log("Player " + playerName + " leaving pvp world " + Config.pvpWorld.getName() +
" but already out of it at loc " + GUtils.locToStringWorldXYZ(curLoc), Level.WARNING);
return;
}
Location returnLoc = this.returnLoc;
if (returnLoc == null) {
GUtils.log("Return loc not found for player " + playerName, Level.WARNING);
returnLoc = Config.defaultReturnLoc;
}
if (teleportUnchecked(returnLoc)) {
this.returnLoc = null;
} else {
GUtils.log("Failed to teleport player " + playerName + " out of the pvp world ", Level.WARNING);
}
}
public boolean tpToBattlePoint(String prefix) {
if (Config.pvpWorld.equals(player.getLocation().getWorld())) {
BattlePoint[] points = ObjectManager.instance.getBattlePoints();
List<BattlePoint> matchedPoints = new ArrayList<BattlePoint>();
for (BattlePoint curPoint : points) {
if (curPoint.getName().startsWith(prefix)) {
matchedPoints.add(curPoint);
}
}
if (matchedPoints.isEmpty()) {
return false;
}
BattlePoint targetPoint = matchedPoints.get(GUtils.random.nextInt(matchedPoints.size()));
if (!teleportUnchecked(targetPoint.getLoc())) {
GUtils.log("Failed to teleport player " + player.getName() + " to tp point " + targetPoint.getName(), Level.WARNING);
}
} else {
GUtils.log("Failed teleport player " + player.getName() + " to battle point: player is not in the pvp world", Level.WARNING);
}
return true;
}
private boolean teleportUnchecked(Location loc) {
PvpRealmEventHandler.setCheckTeleport(false);
try {
return player.teleport(loc);
} finally {
PvpRealmEventHandler.setCheckTeleport(true);
}
}
public void onSideTeleportOut() {
returnLoc = null;
GUtils.sendMessage(player, "You has been side-teleported out of Pvp Realm");
}
public void onSideTeleportIn(Location from) {
returnLoc = from;
GUtils.sendMessage(player, "You has been side-teleported to Pvp Realm");
}
public String getName() {
return name;
}
public void load(ConfigurationSection section) {
ConfigurationSection returnSection = section.getConfigurationSection("return-loc");
if (returnSection != null) {
returnLoc = GUtils.deserializeLocation(returnSection.getValues(false));
} else {
returnLoc = null;
}
}
@Override
public Map<String, Object> serialize() {
Map<String, Object> result = new LinkedHashMap<String, Object>();
if (returnLoc != null) {
result.put("return-loc", GUtils.serializeLocation(returnLoc));
}
return result;
}
public void onPvpLogout(Set<Player> combatPlayers) {
if (player.isOp() && !Config.pvpLoggerOp) return;
StringBuilder playerList = new StringBuilder();
Iterator<Player> itr = combatPlayers.iterator();
while (itr.hasNext()) {
Player player = itr.next();
playerList.append(player.getName());
if (itr.hasNext()) {
playerList.append(", ");
}
}
String message = Config.pvpLoggerMessageText.replace("$leaver", name).replace("$playerlist", playerList);
if (Config.pvpLoggerMessage) {
Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "say " + message);
}
- GUtils.log(message);
+ GUtils.log(ChatColor.stripColor(message));
Hero hero = plugin.getHero(this);
if (Config.pvpLoggerExpPenalty > 0) {
hero.gainExp(-Config.pvpLoggerExpPenalty, HeroClass.ExperienceType.EXTERNAL, player.getLocation());
}
if (Config.pvpLoggerKill) {
hero.setHealth(0);
hero.syncHealth();
}
}
}
| true | true | public void onPvpLogout(Set<Player> combatPlayers) {
if (player.isOp() && !Config.pvpLoggerOp) return;
StringBuilder playerList = new StringBuilder();
Iterator<Player> itr = combatPlayers.iterator();
while (itr.hasNext()) {
Player player = itr.next();
playerList.append(player.getName());
if (itr.hasNext()) {
playerList.append(", ");
}
}
String message = Config.pvpLoggerMessageText.replace("$leaver", name).replace("$playerlist", playerList);
if (Config.pvpLoggerMessage) {
Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "say " + message);
}
GUtils.log(message);
Hero hero = plugin.getHero(this);
if (Config.pvpLoggerExpPenalty > 0) {
hero.gainExp(-Config.pvpLoggerExpPenalty, HeroClass.ExperienceType.EXTERNAL, player.getLocation());
}
if (Config.pvpLoggerKill) {
hero.setHealth(0);
hero.syncHealth();
}
}
| public void onPvpLogout(Set<Player> combatPlayers) {
if (player.isOp() && !Config.pvpLoggerOp) return;
StringBuilder playerList = new StringBuilder();
Iterator<Player> itr = combatPlayers.iterator();
while (itr.hasNext()) {
Player player = itr.next();
playerList.append(player.getName());
if (itr.hasNext()) {
playerList.append(", ");
}
}
String message = Config.pvpLoggerMessageText.replace("$leaver", name).replace("$playerlist", playerList);
if (Config.pvpLoggerMessage) {
Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "say " + message);
}
GUtils.log(ChatColor.stripColor(message));
Hero hero = plugin.getHero(this);
if (Config.pvpLoggerExpPenalty > 0) {
hero.gainExp(-Config.pvpLoggerExpPenalty, HeroClass.ExperienceType.EXTERNAL, player.getLocation());
}
if (Config.pvpLoggerKill) {
hero.setHealth(0);
hero.syncHealth();
}
}
|
diff --git a/easysoa-registry-v1/easysoa-registry-rest-server/src/main/java/org/easysoa/registry/integration/EndpointStateServiceImpl.java b/easysoa-registry-v1/easysoa-registry-rest-server/src/main/java/org/easysoa/registry/integration/EndpointStateServiceImpl.java
index d8d66702..64f69d93 100644
--- a/easysoa-registry-v1/easysoa-registry-rest-server/src/main/java/org/easysoa/registry/integration/EndpointStateServiceImpl.java
+++ b/easysoa-registry-v1/easysoa-registry-rest-server/src/main/java/org/easysoa/registry/integration/EndpointStateServiceImpl.java
@@ -1,336 +1,336 @@
/**
*
*/
package org.easysoa.registry.integration;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import org.easysoa.registry.rest.integration.EndpointStateService;
import org.easysoa.registry.rest.integration.ServiceLevelHealth;
import org.easysoa.registry.rest.integration.SlaOrOlaIndicator;
import org.easysoa.registry.rest.integration.SlaOrOlaIndicators;
import org.easysoa.registry.types.Endpoint;
import org.nuxeo.ecm.core.api.ClientException;
import org.nuxeo.ecm.core.api.CoreSession;
import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.ecm.core.api.DocumentModelList;
import org.nuxeo.ecm.directory.DirectoryException;
import org.nuxeo.ecm.directory.Session;
import org.nuxeo.ecm.directory.api.DirectoryService;
import org.nuxeo.ecm.directory.sql.filter.SQLBetweenFilter;
import org.nuxeo.ecm.platform.query.nxql.NXQLQueryBuilder;
import org.nuxeo.ecm.webengine.jaxrs.session.SessionFactory;
import org.nuxeo.runtime.api.Framework;
/**
* Endpoint state service implementation
*
* @author jguillemotte
*
*/
@Path("easysoa/endpointStateService")
public class EndpointStateServiceImpl implements EndpointStateService {
// Servlet context
@Context
HttpServletRequest request;
/**
* @see org.easysoa.registry.rest.integration.EndpointStateService#updateSlaOlaIndicators(SlaOrOlaIndicator[])
*/
@Override
public void createSlaOlaIndicators(SlaOrOlaIndicators slaOrOlaIndicators) throws Exception {
DirectoryService directoryService = Framework.getService(DirectoryService.class);
if(slaOrOlaIndicators != null){
// Open a session on slaOrOlaIndicator directory
Session session = directoryService.open("slaOrOlaIndicator");
if(session == null){
throw new Exception("Unable to open a new session on directory 'slaOrOlaIndicator'");
}
try{
// Update each indicator
for(SlaOrOlaIndicator indicator : slaOrOlaIndicators.getSlaOrOlaIndicatorList()){
// Create new indicator
createIndicator(session, indicator);
}
}
catch(Exception ex){
// Return the exception and cancel the transaction
throw new Exception("Failed to update SLA or OLA indicators ", ex);
} finally {
if (session != null) {
// NB. container manages transaction, so no need to commit or rollback
// (see doc of deprecated session.commit())
session.close();
}
}
}
}
private void createIndicator(Session session, SlaOrOlaIndicator indicator)
throws DirectoryException, ClientException, Exception {
checkNotNull(indicator.getEndpointId(), "SlaOrOlaIndicator.endpointId");
checkNotNull(indicator.getSlaOrOlaName(), "SlaOrOlaIndicator.slaOrOlaName");
// TODO LATER check that both exist
Map<String, Object> properties = new HashMap<String, Object>();
properties.put("endpointId", indicator.getEndpointId());
properties.put("slaOrOlaName", indicator.getSlaOrOlaName());
properties.put("serviceLeveHealth", indicator.getServiceLevelHealth().toString());
properties.put("serviceLevelViolation", indicator.isServiceLevelViolation());
if(indicator.getTimestamp() != null){
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(indicator.getTimestamp());
properties.put("timestamp", calendar);
}
session.createEntry(properties);
}
private void checkNotNull(String value, String displayName) throws Exception {
if (value == null || value.trim().isEmpty()) {
throw new Exception(displayName + " must not be empty !");
}
}
/**
* @see org.easysoa.registry.rest.integration.EndpointStateService#updateSlaOlaIndicators(SlaOrOlaIndicator[])
*/
@Override
public void updateSlaOlaIndicators(SlaOrOlaIndicators slaOrOlaIndicators) throws Exception {
DirectoryService directoryService = Framework.getService(DirectoryService.class);
if(slaOrOlaIndicators != null){
// Open a session on slaOrOlaIndicator directory
Session session = directoryService.open("slaOrOlaIndicator");
if(session == null){
throw new Exception("Unable to open a new session on directory 'slaOrOlaIndicator'");
}
try{
// Update each indicator
for(SlaOrOlaIndicator indicator : slaOrOlaIndicators.getSlaOrOlaIndicatorList()){
// get the indicator if exists
Map<String, Serializable> parameters = new HashMap<String, Serializable>();
parameters.put("slaOrOlaName", indicator.getSlaOrOlaName());
parameters.put("endpointId", indicator.getEndpointId());
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(indicator.getTimestamp());
parameters.put("timestamp", calendar);
DocumentModelList documentModelList = session.query(parameters);
DocumentModel indicatorModel;
if(documentModelList != null && documentModelList.size() > 0){
// Update existing indicator
indicatorModel = documentModelList.get(0);
indicatorModel.setPropertyValue("serviceLeveHealth", indicator.getServiceLevelHealth().toString());
indicatorModel.setPropertyValue("serviceLevelViolation", String.valueOf(indicator.isServiceLevelViolation()));
session.updateEntry(indicatorModel);
} else {
// Create new indicator
createIndicator(session, indicator);
}
}
}
catch(Exception ex){
// Return the exception and cancel the transaction
throw new Exception("Failed to update SLA or OLA indicators ", ex);
} finally {
if (session != null) {
// NB. container manages transaction, so no need to commit or rollback
// (see doc of deprecated session.commit())
session.close();
}
}
}
}
/**
* @see org.easysoa.registry.rest.integration.EndpointStateService#getSlaOrOlaIndicatorsByEnv(String, String, Date,
* Date, int, int)
*/
@Override
public SlaOrOlaIndicators getSlaOrOlaIndicatorsByEnv(String environment, String projectId,
String periodStart, String periodEnd, int pageSize, int pageStart) throws Exception {
// TODO NXQL query returning all endpoints where environment & projectId
// TODO put them in call to getSlaOrOlaIndicators(String endpointIds...) and return it
CoreSession documentManager = SessionFactory.getSession(request);
if(environment != null && !"".equals(environment) && projectId != null && !"".equals(projectId)){
throw new IllegalArgumentException("Environment or projectid parameter must not be null or empty");
}
// Fetch SoaNode list
ArrayList<String> parameters = new ArrayList<String>();
StringBuilder query = new StringBuilder();
query.append("SELECT * FROM Endpoint WHERE ");
// Search parameters
if(environment != null && !"".equals(environment)){
query.append(Endpoint.XPATH_ENDP_ENVIRONMENT + " like '?' ");
parameters.add(environment);
}
if(projectId != null && !"".equals(projectId)){
if(environment != null && !"".equals(environment)){
query.append(" AND ");
}
query.append("endp:projectid" + " like '?' ");
parameters.add(projectId);
}
// Execute query
String nxqlQuery = NXQLQueryBuilder.getQuery(query.toString(), parameters.toArray(), false, true);
DocumentModelList soaNodeModelList = documentManager.query(nxqlQuery);
// Get endpoints list
List<String> endpointsList = new ArrayList<String>();
for(DocumentModel documentModel : soaNodeModelList){
endpointsList.add((String)documentModel.getPropertyValue(Endpoint.XPATH_UUID));
}
// Get endpoints indicators
return this.getSlaOrOlaIndicators(endpointsList, periodStart, periodEnd, pageSize, pageStart);
}
/**
*
* not REST, used by above
* TODO LATER ask Nuxeo to support OR in SQL Directory queries
*
* @param endpointIds
* @param periodStart
* @param periodEnd
* @param pageSize
* @param pageStart
* @return
* @throws Exception
*/
protected SlaOrOlaIndicators getSlaOrOlaIndicators(List<String> endpointIds,
String periodStart, String periodEnd, int pageSize, int pageStart) throws Exception {
// For each endpoint, get the corresponding indicators and returns the indicator list
SlaOrOlaIndicators slaOrOlaIndicators = new SlaOrOlaIndicators();
for(String endpointId : endpointIds){
slaOrOlaIndicators.getSlaOrOlaIndicatorList().addAll(getSlaOrOlaIndicators(endpointId, "", periodStart, periodEnd, pageSize, pageStart).getSlaOrOlaIndicatorList());
}
return slaOrOlaIndicators;
}
/**
* @see org.easysoa.registry.rest.integration.EndpointStateService#getSlaOrOlaIndicators(String, String, Date,
* Date, int, int)
*/
@Override
public SlaOrOlaIndicators getSlaOrOlaIndicators(String endpointId,
String slaOrOlaName, String periodStart, String periodEnd, int pageSize, int pageStart) throws Exception {
DirectoryService directoryService = Framework.getService(DirectoryService.class);
Session session = directoryService.open(org.easysoa.registry.types.SlaOrOlaIndicator.DOCTYPE);
/*
* Returns level indicators, in the given period (default : daily)
* OPT paginated navigation
* @param periodStart : if null day start, if both null returns all in the current day
* @param periodEnd : if null now, if both null returns all in the current day
* @param pageSize OPT pagination : number of indicators per page, if not specified, all results are returned
* @param pageStart OPT pagination : index of the first indicator to return (starts with 0)
* @return SlaOrOlaIndicators array of SlaOrOlaIndicator
*/
if(session == null){
throw new Exception("Unable to open a new session on directory '" + org.easysoa.registry.types.SlaOrOlaIndicator.DOCTYPE + "'");
}
Map<String, Serializable> parameters = new HashMap<String, Serializable>();
if(endpointId != null && !"".equals(endpointId)){
parameters.put("endpointId", endpointId);
}
if(slaOrOlaName != null && !"".equals(slaOrOlaName)){
parameters.put("slaOrOlaName", slaOrOlaName);
}
SlaOrOlaIndicators slaOrOlaIndicators = new SlaOrOlaIndicators();
// Execute query
try {
// Use this method to have request on date range and pagination
Map<String, String> orderByParams = new HashMap<String, String>();
Set<String> fullTextSearchParams = new HashSet<String>();
SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Calendar calendarFrom = new GregorianCalendar();
Calendar calendarTo = new GregorianCalendar();
Calendar currentDate = new GregorianCalendar();
// Add date Range param
// If periodEnd is null and period start is null, set to current day end
if(periodEnd == null && periodStart == null){
calendarTo.clear();
calendarTo.set(currentDate.get(Calendar.YEAR) , currentDate.get(Calendar.MONTH), currentDate.get(Calendar.DAY_OF_MONTH), 23, 59, 59);
}
// If period End is null and periodStart not null, set to now
else if(periodEnd == null && periodStart != null) {
calendarTo.setTime(currentDate.getTime());
}
// else set with the periodEnd param
else {
calendarTo.setTime(dateFormater.parse(periodEnd));
}
// Set period start
if(periodStart != null){
calendarFrom.setTime(dateFormater.parse(periodStart));
}
// If periodStart is null, set to current day start
else {
calendarFrom.clear();
// TODO : previous setting was to fix the from date to the current day
// But cause some problems to test the UI when the model is not reloaded daily
// Remove the "-1" when finished
- calendarFrom.set(currentDate.get(Calendar.YEAR) - 1, currentDate.get(Calendar.MONTH), currentDate.get(Calendar.DAY_OF_MONTH));
+ calendarFrom.set(currentDate.get(Calendar.YEAR)/* - 1*/, currentDate.get(Calendar.MONTH), currentDate.get(Calendar.DAY_OF_MONTH));
}
SQLBetweenFilter dateRangeFilter = new SQLBetweenFilter(calendarFrom, calendarTo);
parameters.put("timestamp", dateRangeFilter);
// Execute the query
DocumentModelList soaNodeModelList = session.query(parameters, fullTextSearchParams, orderByParams, false, pageSize, pageStart * pageSize);
SlaOrOlaIndicator indicator;
for(DocumentModel model : soaNodeModelList){
indicator = new SlaOrOlaIndicator();
indicator.setEndpointId((String)model.getPropertyValue(org.easysoa.registry.types.SlaOrOlaIndicator.XPATH_ENDPOINT_ID));
indicator.setType(model.getType());
indicator.setServiceLevelHealth(ServiceLevelHealth.valueOf((String)model.getPropertyValue(org.easysoa.registry.types.SlaOrOlaIndicator.XPATH_SERVICE_LEVEL_HEALTH)));
indicator.setServiceLevelViolation((Boolean)model.getPropertyValue(org.easysoa.registry.types.SlaOrOlaIndicator.XPATH_SERVICE_LEVEL_VIOLATION));
indicator.setSlaOrOlaName((String)model.getPropertyValue(org.easysoa.registry.types.SlaOrOlaIndicator.XPATH_SLA_OR_OLA_NAME));
GregorianCalendar calendar = (GregorianCalendar)model.getPropertyValue(org.easysoa.registry.types.SlaOrOlaIndicator.XPATH_TIMESTAMP);
indicator.setTimestamp(calendar.getTime());
slaOrOlaIndicators.getSlaOrOlaIndicatorList().add(indicator);
}
} catch (ClientException ex) {
ex.printStackTrace();
throw ex;
}
return slaOrOlaIndicators;
}
}
| true | true | public SlaOrOlaIndicators getSlaOrOlaIndicators(String endpointId,
String slaOrOlaName, String periodStart, String periodEnd, int pageSize, int pageStart) throws Exception {
DirectoryService directoryService = Framework.getService(DirectoryService.class);
Session session = directoryService.open(org.easysoa.registry.types.SlaOrOlaIndicator.DOCTYPE);
/*
* Returns level indicators, in the given period (default : daily)
* OPT paginated navigation
* @param periodStart : if null day start, if both null returns all in the current day
* @param periodEnd : if null now, if both null returns all in the current day
* @param pageSize OPT pagination : number of indicators per page, if not specified, all results are returned
* @param pageStart OPT pagination : index of the first indicator to return (starts with 0)
* @return SlaOrOlaIndicators array of SlaOrOlaIndicator
*/
if(session == null){
throw new Exception("Unable to open a new session on directory '" + org.easysoa.registry.types.SlaOrOlaIndicator.DOCTYPE + "'");
}
Map<String, Serializable> parameters = new HashMap<String, Serializable>();
if(endpointId != null && !"".equals(endpointId)){
parameters.put("endpointId", endpointId);
}
if(slaOrOlaName != null && !"".equals(slaOrOlaName)){
parameters.put("slaOrOlaName", slaOrOlaName);
}
SlaOrOlaIndicators slaOrOlaIndicators = new SlaOrOlaIndicators();
// Execute query
try {
// Use this method to have request on date range and pagination
Map<String, String> orderByParams = new HashMap<String, String>();
Set<String> fullTextSearchParams = new HashSet<String>();
SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Calendar calendarFrom = new GregorianCalendar();
Calendar calendarTo = new GregorianCalendar();
Calendar currentDate = new GregorianCalendar();
// Add date Range param
// If periodEnd is null and period start is null, set to current day end
if(periodEnd == null && periodStart == null){
calendarTo.clear();
calendarTo.set(currentDate.get(Calendar.YEAR) , currentDate.get(Calendar.MONTH), currentDate.get(Calendar.DAY_OF_MONTH), 23, 59, 59);
}
// If period End is null and periodStart not null, set to now
else if(periodEnd == null && periodStart != null) {
calendarTo.setTime(currentDate.getTime());
}
// else set with the periodEnd param
else {
calendarTo.setTime(dateFormater.parse(periodEnd));
}
// Set period start
if(periodStart != null){
calendarFrom.setTime(dateFormater.parse(periodStart));
}
// If periodStart is null, set to current day start
else {
calendarFrom.clear();
// TODO : previous setting was to fix the from date to the current day
// But cause some problems to test the UI when the model is not reloaded daily
// Remove the "-1" when finished
calendarFrom.set(currentDate.get(Calendar.YEAR) - 1, currentDate.get(Calendar.MONTH), currentDate.get(Calendar.DAY_OF_MONTH));
}
SQLBetweenFilter dateRangeFilter = new SQLBetweenFilter(calendarFrom, calendarTo);
parameters.put("timestamp", dateRangeFilter);
// Execute the query
DocumentModelList soaNodeModelList = session.query(parameters, fullTextSearchParams, orderByParams, false, pageSize, pageStart * pageSize);
SlaOrOlaIndicator indicator;
for(DocumentModel model : soaNodeModelList){
indicator = new SlaOrOlaIndicator();
indicator.setEndpointId((String)model.getPropertyValue(org.easysoa.registry.types.SlaOrOlaIndicator.XPATH_ENDPOINT_ID));
indicator.setType(model.getType());
indicator.setServiceLevelHealth(ServiceLevelHealth.valueOf((String)model.getPropertyValue(org.easysoa.registry.types.SlaOrOlaIndicator.XPATH_SERVICE_LEVEL_HEALTH)));
indicator.setServiceLevelViolation((Boolean)model.getPropertyValue(org.easysoa.registry.types.SlaOrOlaIndicator.XPATH_SERVICE_LEVEL_VIOLATION));
indicator.setSlaOrOlaName((String)model.getPropertyValue(org.easysoa.registry.types.SlaOrOlaIndicator.XPATH_SLA_OR_OLA_NAME));
GregorianCalendar calendar = (GregorianCalendar)model.getPropertyValue(org.easysoa.registry.types.SlaOrOlaIndicator.XPATH_TIMESTAMP);
indicator.setTimestamp(calendar.getTime());
slaOrOlaIndicators.getSlaOrOlaIndicatorList().add(indicator);
}
} catch (ClientException ex) {
ex.printStackTrace();
throw ex;
}
return slaOrOlaIndicators;
}
| public SlaOrOlaIndicators getSlaOrOlaIndicators(String endpointId,
String slaOrOlaName, String periodStart, String periodEnd, int pageSize, int pageStart) throws Exception {
DirectoryService directoryService = Framework.getService(DirectoryService.class);
Session session = directoryService.open(org.easysoa.registry.types.SlaOrOlaIndicator.DOCTYPE);
/*
* Returns level indicators, in the given period (default : daily)
* OPT paginated navigation
* @param periodStart : if null day start, if both null returns all in the current day
* @param periodEnd : if null now, if both null returns all in the current day
* @param pageSize OPT pagination : number of indicators per page, if not specified, all results are returned
* @param pageStart OPT pagination : index of the first indicator to return (starts with 0)
* @return SlaOrOlaIndicators array of SlaOrOlaIndicator
*/
if(session == null){
throw new Exception("Unable to open a new session on directory '" + org.easysoa.registry.types.SlaOrOlaIndicator.DOCTYPE + "'");
}
Map<String, Serializable> parameters = new HashMap<String, Serializable>();
if(endpointId != null && !"".equals(endpointId)){
parameters.put("endpointId", endpointId);
}
if(slaOrOlaName != null && !"".equals(slaOrOlaName)){
parameters.put("slaOrOlaName", slaOrOlaName);
}
SlaOrOlaIndicators slaOrOlaIndicators = new SlaOrOlaIndicators();
// Execute query
try {
// Use this method to have request on date range and pagination
Map<String, String> orderByParams = new HashMap<String, String>();
Set<String> fullTextSearchParams = new HashSet<String>();
SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Calendar calendarFrom = new GregorianCalendar();
Calendar calendarTo = new GregorianCalendar();
Calendar currentDate = new GregorianCalendar();
// Add date Range param
// If periodEnd is null and period start is null, set to current day end
if(periodEnd == null && periodStart == null){
calendarTo.clear();
calendarTo.set(currentDate.get(Calendar.YEAR) , currentDate.get(Calendar.MONTH), currentDate.get(Calendar.DAY_OF_MONTH), 23, 59, 59);
}
// If period End is null and periodStart not null, set to now
else if(periodEnd == null && periodStart != null) {
calendarTo.setTime(currentDate.getTime());
}
// else set with the periodEnd param
else {
calendarTo.setTime(dateFormater.parse(periodEnd));
}
// Set period start
if(periodStart != null){
calendarFrom.setTime(dateFormater.parse(periodStart));
}
// If periodStart is null, set to current day start
else {
calendarFrom.clear();
// TODO : previous setting was to fix the from date to the current day
// But cause some problems to test the UI when the model is not reloaded daily
// Remove the "-1" when finished
calendarFrom.set(currentDate.get(Calendar.YEAR)/* - 1*/, currentDate.get(Calendar.MONTH), currentDate.get(Calendar.DAY_OF_MONTH));
}
SQLBetweenFilter dateRangeFilter = new SQLBetweenFilter(calendarFrom, calendarTo);
parameters.put("timestamp", dateRangeFilter);
// Execute the query
DocumentModelList soaNodeModelList = session.query(parameters, fullTextSearchParams, orderByParams, false, pageSize, pageStart * pageSize);
SlaOrOlaIndicator indicator;
for(DocumentModel model : soaNodeModelList){
indicator = new SlaOrOlaIndicator();
indicator.setEndpointId((String)model.getPropertyValue(org.easysoa.registry.types.SlaOrOlaIndicator.XPATH_ENDPOINT_ID));
indicator.setType(model.getType());
indicator.setServiceLevelHealth(ServiceLevelHealth.valueOf((String)model.getPropertyValue(org.easysoa.registry.types.SlaOrOlaIndicator.XPATH_SERVICE_LEVEL_HEALTH)));
indicator.setServiceLevelViolation((Boolean)model.getPropertyValue(org.easysoa.registry.types.SlaOrOlaIndicator.XPATH_SERVICE_LEVEL_VIOLATION));
indicator.setSlaOrOlaName((String)model.getPropertyValue(org.easysoa.registry.types.SlaOrOlaIndicator.XPATH_SLA_OR_OLA_NAME));
GregorianCalendar calendar = (GregorianCalendar)model.getPropertyValue(org.easysoa.registry.types.SlaOrOlaIndicator.XPATH_TIMESTAMP);
indicator.setTimestamp(calendar.getTime());
slaOrOlaIndicators.getSlaOrOlaIndicatorList().add(indicator);
}
} catch (ClientException ex) {
ex.printStackTrace();
throw ex;
}
return slaOrOlaIndicators;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.